repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
dmikey/syr | android/syrnative/src/main/java/syr/js/org/syrnative/SyrAnimatedText.java | 566 | package syr.js.org.syrnative;
import android.content.Context;
import android.view.View;
import org.json.JSONObject;
/**
* Created by dereanderson on 1/16/18.
*/
public class SyrAnimatedText extends SyrText {
@Override
public View render(JSONObject component, Context context, View instance) {
View animatedText = super.render(component, context, instance);
animatedText.setLayerType(View.LAYER_TYPE_HARDWARE, null);
return animatedText;
}
@Override
public String getName() {
return "AnimatedText";
}
}
| mit |
teeebor/reboot_mingw | src/engine/engine.cpp | 808 | #include <engine/engine.h>
#include <engine/entity/gameObject.h>
#include <engine/component/renderer.h>
namespace reboot
{
Scene *Engine::m_Scene;
Engine::Engine(BYTE contextType, BYTE canvasType)
{
m_Contex = new reboot_driver::Context(contextType, canvasType);
m_Contex->m_Canvas->create();
input=new reboot_driver::Input();
}
Engine::~Engine()
{
delete m_Contex;
delete m_Scene;
}
void Engine::setScene(Scene *scene) {
m_Scene = scene;
}
void Engine::start()
{
while (!m_Contex->m_Canvas->closed()) {
m_Contex->m_Canvas->update();
if(m_Scene)
m_Scene->update(m_RenderMode);
}
}
void Engine::setResolution(unsigned width, unsigned height) {
m_Contex->m_Canvas->resize(width,height);
}
} | mit |
mzubairahmed/externalapi | src/main/java/com/asi/ext/api/radar/model/MediaCriteriaMatches.java | 798 | package com.asi.ext.api.radar.model;
import com.fasterxml.jackson.annotation.JsonProperty;
public class MediaCriteriaMatches {
@JsonProperty("CriteriaSetValueId")
private String criteriaSetValueId;
@JsonProperty("MediaId")
private String mediaId;
/**
* @return the criteriaSetValueId
*/
public String getCriteriaSetValueId() {
return criteriaSetValueId;
}
/**
* @param criteriaSetValueId
* the criteriaSetValueId to set
*/
public void setCriteriaSetValueId(String criteriaSetValueId) {
this.criteriaSetValueId = criteriaSetValueId;
}
/**
* @return the mediaId
*/
public String getMediaId() {
return mediaId;
}
/**
* @param mediaId
* the mediaId to set
*/
public void setMediaId(String mediaId) {
this.mediaId = mediaId;
}
}
| mit |
ddemarco5/SensorMovementClassification | jsat/src/main/java/jsat/regression/NadarayaWatson.java | 2926 |
package jsat.regression;
import java.util.*;
import java.util.concurrent.ExecutorService;
import jsat.classifiers.DataPoint;
import jsat.distributions.multivariate.MultivariateKDE;
import jsat.linear.Vec;
import jsat.linear.VecPaired;
import jsat.parameters.Parameter;
import jsat.parameters.Parameterized;
/**
* The Nadaraya-Watson regressor uses the {@link jsat.distributions.multivariate.MultivariateKDE Kernel Density Estimator } to perform regression on a data set. <br>
* Nadaraya-Watson can also be expressed as a classifier, and equivalent results can be obtained by combining a KDE with {@link jsat.classifiers.bayesian.BestClassDistribution}.
*
* @author Edward Raff
*/
public class NadarayaWatson implements Regressor, Parameterized
{
@Parameter.ParameterHolder
private MultivariateKDE kde;
public NadarayaWatson(MultivariateKDE kde)
{
this.kde = kde;
}
public double regress(DataPoint data)
{
List<? extends VecPaired<VecPaired<Vec, Integer>, Double>> nearBy = kde.getNearby(data.getNumericalValues());
if(nearBy.isEmpty())
return 0;///hmmm... what should be retruned in this case?
double weightSum = 0;
double sum = 0;
for(VecPaired<VecPaired<Vec, Integer>, Double> v : nearBy)
{
double weight = v.getPair();
double regressionValue = ( (VecPaired<Vec, Double>) v.getVector().getVector()).getPair();
weightSum += weight;
sum += weight*regressionValue;
}
return sum / weightSum;
}
@Override
public void train(RegressionDataSet dataSet, ExecutorService threadPool)
{
List<VecPaired<Vec, Double>> vectors = collectVectors(dataSet);
kde.setUsingData(vectors, threadPool);
}
private List<VecPaired<Vec, Double>> collectVectors(RegressionDataSet dataSet)
{
List<VecPaired<Vec, Double>> vectors = new ArrayList<VecPaired<Vec, Double>>(dataSet.getSampleSize());
for(int i = 0; i < dataSet.getSampleSize(); i++)
vectors.add(new VecPaired<Vec, Double>(dataSet.getDataPoint(i).getNumericalValues(), dataSet.getTargetValue(i)));
return vectors;
}
@Override
public void train(RegressionDataSet dataSet)
{
List<VecPaired<Vec, Double>> vectors = collectVectors(dataSet);;
kde.setUsingData(vectors);
}
@Override
public boolean supportsWeightedData()
{
return true;
}
@Override
public NadarayaWatson clone()
{
return new NadarayaWatson((MultivariateKDE)kde.clone());
}
@Override
public List<Parameter> getParameters()
{
return Parameter.getParamsFromMethods(this);
}
@Override
public Parameter getParameter(String paramName)
{
return Parameter.toParameterMap(getParameters()).get(paramName);
}
}
| mit |
Kore-Core/kore | src/script/script.cpp | 10627 | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The KoreCore developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "script.h"
#include "tinyformat.h"
#include "utilstrencodings.h"
namespace {
inline std::string ValueString(const std::vector<unsigned char>& vch)
{
if (vch.size() <= 4)
return strprintf("%d", CScriptNum(vch, false).getint());
else
return HexStr(vch);
}
} // anon namespace
using namespace std;
const char* GetOpName(opcodetype opcode)
{
switch (opcode)
{
// push value
case OP_0 : return "0";
case OP_PUSHDATA1 : return "OP_PUSHDATA1";
case OP_PUSHDATA2 : return "OP_PUSHDATA2";
case OP_PUSHDATA4 : return "OP_PUSHDATA4";
case OP_1NEGATE : return "-1";
case OP_RESERVED : return "OP_RESERVED";
case OP_1 : return "1";
case OP_2 : return "2";
case OP_3 : return "3";
case OP_4 : return "4";
case OP_5 : return "5";
case OP_6 : return "6";
case OP_7 : return "7";
case OP_8 : return "8";
case OP_9 : return "9";
case OP_10 : return "10";
case OP_11 : return "11";
case OP_12 : return "12";
case OP_13 : return "13";
case OP_14 : return "14";
case OP_15 : return "15";
case OP_16 : return "16";
// control
case OP_NOP : return "OP_NOP";
case OP_VER : return "OP_VER";
case OP_IF : return "OP_IF";
case OP_NOTIF : return "OP_NOTIF";
case OP_VERIF : return "OP_VERIF";
case OP_VERNOTIF : return "OP_VERNOTIF";
case OP_ELSE : return "OP_ELSE";
case OP_ENDIF : return "OP_ENDIF";
case OP_VERIFY : return "OP_VERIFY";
case OP_RETURN : return "OP_RETURN";
// stack ops
case OP_TOALTSTACK : return "OP_TOALTSTACK";
case OP_FROMALTSTACK : return "OP_FROMALTSTACK";
case OP_2DROP : return "OP_2DROP";
case OP_2DUP : return "OP_2DUP";
case OP_3DUP : return "OP_3DUP";
case OP_2OVER : return "OP_2OVER";
case OP_2ROT : return "OP_2ROT";
case OP_2SWAP : return "OP_2SWAP";
case OP_IFDUP : return "OP_IFDUP";
case OP_DEPTH : return "OP_DEPTH";
case OP_DROP : return "OP_DROP";
case OP_DUP : return "OP_DUP";
case OP_NIP : return "OP_NIP";
case OP_OVER : return "OP_OVER";
case OP_PICK : return "OP_PICK";
case OP_ROLL : return "OP_ROLL";
case OP_ROT : return "OP_ROT";
case OP_SWAP : return "OP_SWAP";
case OP_TUCK : return "OP_TUCK";
// splice ops
case OP_CAT : return "OP_CAT";
case OP_SUBSTR : return "OP_SUBSTR";
case OP_LEFT : return "OP_LEFT";
case OP_RIGHT : return "OP_RIGHT";
case OP_SIZE : return "OP_SIZE";
// bit logic
case OP_INVERT : return "OP_INVERT";
case OP_AND : return "OP_AND";
case OP_OR : return "OP_OR";
case OP_XOR : return "OP_XOR";
case OP_EQUAL : return "OP_EQUAL";
case OP_EQUALVERIFY : return "OP_EQUALVERIFY";
case OP_RESERVED1 : return "OP_RESERVED1";
case OP_RESERVED2 : return "OP_RESERVED2";
// numeric
case OP_1ADD : return "OP_1ADD";
case OP_1SUB : return "OP_1SUB";
case OP_2MUL : return "OP_2MUL";
case OP_2DIV : return "OP_2DIV";
case OP_NEGATE : return "OP_NEGATE";
case OP_ABS : return "OP_ABS";
case OP_NOT : return "OP_NOT";
case OP_0NOTEQUAL : return "OP_0NOTEQUAL";
case OP_ADD : return "OP_ADD";
case OP_SUB : return "OP_SUB";
case OP_MUL : return "OP_MUL";
case OP_DIV : return "OP_DIV";
case OP_MOD : return "OP_MOD";
case OP_LSHIFT : return "OP_LSHIFT";
case OP_RSHIFT : return "OP_RSHIFT";
case OP_BOOLAND : return "OP_BOOLAND";
case OP_BOOLOR : return "OP_BOOLOR";
case OP_NUMEQUAL : return "OP_NUMEQUAL";
case OP_NUMEQUALVERIFY : return "OP_NUMEQUALVERIFY";
case OP_NUMNOTEQUAL : return "OP_NUMNOTEQUAL";
case OP_LESSTHAN : return "OP_LESSTHAN";
case OP_GREATERTHAN : return "OP_GREATERTHAN";
case OP_LESSTHANOREQUAL : return "OP_LESSTHANOREQUAL";
case OP_GREATERTHANOREQUAL : return "OP_GREATERTHANOREQUAL";
case OP_MIN : return "OP_MIN";
case OP_MAX : return "OP_MAX";
case OP_WITHIN : return "OP_WITHIN";
// crypto
case OP_RIPEMD160 : return "OP_RIPEMD160";
case OP_SHA1 : return "OP_SHA1";
case OP_SHA256 : return "OP_SHA256";
case OP_HASH160 : return "OP_HASH160";
case OP_HASH256 : return "OP_HASH256";
case OP_CODESEPARATOR : return "OP_CODESEPARATOR";
case OP_CHECKSIG : return "OP_CHECKSIG";
case OP_CHECKSIGVERIFY : return "OP_CHECKSIGVERIFY";
case OP_CHECKMULTISIG : return "OP_CHECKMULTISIG";
case OP_CHECKMULTISIGVERIFY : return "OP_CHECKMULTISIGVERIFY";
// expanson
case OP_NOP1 : return "OP_NOP1";
case OP_CHECKLOCKTIMEVERIFY : return "OP_CHECKLOCKTIMEVERIFY";
case OP_CHECKSEQUENCEVERIFY : return "OP_CHECKSEQUENCEVERIFY";
case OP_NOP4 : return "OP_NOP4";
case OP_NOP5 : return "OP_NOP5";
case OP_NOP6 : return "OP_NOP6";
case OP_NOP7 : return "OP_NOP7";
case OP_NOP8 : return "OP_NOP8";
case OP_NOP9 : return "OP_NOP9";
case OP_NOP10 : return "OP_NOP10";
case OP_INVALIDOPCODE : return "OP_INVALIDOPCODE";
// Note:
// The template matching params OP_SMALLINTEGER/etc are defined in opcodetype enum
// as kind of implementation hack, they are *NOT* real opcodes. If found in real
// Script, just let the default: case deal with them.
default:
return "OP_UNKNOWN";
}
}
unsigned int CScript::GetSigOpCount(bool fAccurate) const
{
unsigned int n = 0;
const_iterator pc = begin();
opcodetype lastOpcode = OP_INVALIDOPCODE;
while (pc < end())
{
opcodetype opcode;
if (!GetOp(pc, opcode))
break;
if (opcode == OP_CHECKSIG || opcode == OP_CHECKSIGVERIFY)
n++;
else if (opcode == OP_CHECKMULTISIG || opcode == OP_CHECKMULTISIGVERIFY)
{
if (fAccurate && lastOpcode >= OP_1 && lastOpcode <= OP_16)
n += DecodeOP_N(lastOpcode);
else
n += MAX_PUBKEYS_PER_MULTISIG;
}
lastOpcode = opcode;
}
return n;
}
unsigned int CScript::GetSigOpCount(const CScript& scriptSig) const
{
if (!IsPayToScriptHash())
return GetSigOpCount(true);
// This is a pay-to-script-hash scriptPubKey;
// get the last item that the scriptSig
// pushes onto the stack:
const_iterator pc = scriptSig.begin();
vector<unsigned char> data;
while (pc < scriptSig.end())
{
opcodetype opcode;
if (!scriptSig.GetOp(pc, opcode, data))
return 0;
if (opcode > OP_16)
return 0;
}
/// ... and return its opcount:
CScript subscript(data.begin(), data.end());
return subscript.GetSigOpCount(true);
}
bool CScript::IsNormalPaymentScript() const
{
if(this->size() != 25) return false;
std::string str;
opcodetype opcode;
const_iterator pc = begin();
int i = 0;
while (pc < end())
{
GetOp(pc, opcode);
if( i == 0 && opcode != OP_DUP) return false;
else if(i == 1 && opcode != OP_HASH160) return false;
else if(i == 3 && opcode != OP_EQUALVERIFY) return false;
else if(i == 4 && opcode != OP_CHECKSIG) return false;
else if(i == 5) return false;
i++;
}
return true;
}
bool CScript::IsPayToScriptHash() const
{
// Extra-fast test for pay-to-script-hash CScripts:
return (this->size() == 23 &&
(*this)[0] == OP_HASH160 &&
(*this)[1] == 0x14 &&
(*this)[22] == OP_EQUAL);
}
bool CScript::IsPushOnly(const_iterator pc) const
{
while (pc < end())
{
opcodetype opcode;
if (!GetOp(pc, opcode))
return false;
// Note that IsPushOnly() *does* consider OP_RESERVED to be a
// push-type opcode, however execution of OP_RESERVED fails, so
// it's not relevant to P2SH/BIP62 as the scriptSig would fail prior to
// the P2SH special validation code being executed.
if (opcode > OP_16)
return false;
}
return true;
}
bool CScript::IsPushOnly() const
{
return this->IsPushOnly(begin());
}
std::string CScript::ToString() const
{
std::string str;
opcodetype opcode;
std::vector<unsigned char> vch;
const_iterator pc = begin();
while (pc < end())
{
if (!str.empty())
str += " ";
if (!GetOp(pc, opcode, vch))
{
str += "[error]";
return str;
}
if (0 <= opcode && opcode <= OP_PUSHDATA4)
str += ValueString(vch);
else
str += GetOpName(opcode);
}
return str;
} | mit |
billybones79/spree_lookbook | app/assets/javascripts/spree/backend/setup_taxon_select.js | 1816 | var set_taxon_select_from_parent = function(selector, maximumSelectionSize){
if ($(selector).length > 0) {
$(selector).select2({
placeholder: Spree.translations.taxon_placeholder,
multiple: true,
maximumSelectionSize: maximumSelectionSize,
initSelection: function (element, callback) {
var url = Spree.url(Spree.routes.taxons_search, {
ids: element.val().split(','),
token: Spree.api_key
});
return $.getJSON(url, null, function (data) {
return callback(data['taxons']);
});
},
ajax: {
url: Spree.routes.taxons_search,
datatype: 'json',
data: function (term, page) {
return {
per_page: 50,
page: page,
without_children: true,
q: {
name_cont: term
},
token: Spree.api_key
};
},
results: function (data, page) {
var more = page < data.pages;
return {
results: data['taxons'],
more: more
};
}
},
formatResult: function (taxon) {
return taxon.pretty_name;
},
formatSelection: function (taxon) {
return taxon.pretty_name;
}
});
}
}
$(document).ready(function () {
set_taxon_select_from_parent('#lookbook_spree_taxon_id', 1);
set_taxon_select_from_parent('#kit_taxon_ids', false);
});
| mit |
ld-test/prosody | util/sasl/scram.lua | 10492 | -- sasl.lua v0.4
-- Copyright (C) 2008-2010 Tobias Markmann
--
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
--
-- * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
-- * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
-- * Neither the name of Tobias Markmann nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
local s_match = string.match;
local type = type
local base64 = require "util.encodings".base64;
local hmac_sha1 = require "util.hashes".hmac_sha1;
local sha1 = require "util.hashes".sha1;
local Hi = require "util.hashes".scram_Hi_sha1;
local generate_uuid = require "util.uuid".generate;
local saslprep = require "util.encodings".stringprep.saslprep;
local nodeprep = require "util.encodings".stringprep.nodeprep;
local log = require "util.logger".init("sasl");
local t_concat = table.concat;
local char = string.char;
local byte = string.byte;
local _ENV = nil;
--=========================
--SASL SCRAM-SHA-1 according to RFC 5802
--[[
Supported Authentication Backends
scram_{MECH}:
-- MECH being a standard hash name (like those at IANA's hash registry) with '-' replaced with '_'
function(username, realm)
return stored_key, server_key, iteration_count, salt, state;
end
Supported Channel Binding Backends
'tls-unique' according to RFC 5929
]]
local default_i = 4096
local xor_map = {0;1;2;3;4;5;6;7;8;9;10;11;12;13;14;15;1;0;3;2;5;4;7;6;9;8;11;10;13;12;15;14;2;3;0;1;6;7;4;5;10;11;8;9;14;15;12;13;3;2;1;0;7;6;5;4;11;10;9;8;15;14;13;12;4;5;6;7;0;1;2;3;12;13;14;15;8;9;10;11;5;4;7;6;1;0;3;2;13;12;15;14;9;8;11;10;6;7;4;5;2;3;0;1;14;15;12;13;10;11;8;9;7;6;5;4;3;2;1;0;15;14;13;12;11;10;9;8;8;9;10;11;12;13;14;15;0;1;2;3;4;5;6;7;9;8;11;10;13;12;15;14;1;0;3;2;5;4;7;6;10;11;8;9;14;15;12;13;2;3;0;1;6;7;4;5;11;10;9;8;15;14;13;12;3;2;1;0;7;6;5;4;12;13;14;15;8;9;10;11;4;5;6;7;0;1;2;3;13;12;15;14;9;8;11;10;5;4;7;6;1;0;3;2;14;15;12;13;10;11;8;9;6;7;4;5;2;3;0;1;15;14;13;12;11;10;9;8;7;6;5;4;3;2;1;0;};
local result = {};
local function binaryXOR( a, b )
for i=1, #a do
local x, y = byte(a, i), byte(b, i);
local lowx, lowy = x % 16, y % 16;
local hix, hiy = (x - lowx) / 16, (y - lowy) / 16;
local lowr, hir = xor_map[lowx * 16 + lowy + 1], xor_map[hix * 16 + hiy + 1];
local r = hir * 16 + lowr;
result[i] = char(r)
end
return t_concat(result);
end
local function validate_username(username, _nodeprep)
-- check for forbidden char sequences
for eq in username:gmatch("=(.?.?)") do
if eq ~= "2C" and eq ~= "3D" then
return false
end
end
-- replace =2C with , and =3D with =
username = username:gsub("=2C", ",");
username = username:gsub("=3D", "=");
-- apply SASLprep
username = saslprep(username);
if username and _nodeprep ~= false then
username = (_nodeprep or nodeprep)(username);
end
return username and #username>0 and username;
end
local function hashprep(hashname)
return hashname:lower():gsub("-", "_");
end
local function getAuthenticationDatabaseSHA1(password, salt, iteration_count)
if type(password) ~= "string" or type(salt) ~= "string" or type(iteration_count) ~= "number" then
return false, "inappropriate argument types"
end
if iteration_count < 4096 then
log("warn", "Iteration count < 4096 which is the suggested minimum according to RFC 5802.")
end
local salted_password = Hi(password, salt, iteration_count);
local stored_key = sha1(hmac_sha1(salted_password, "Client Key"))
local server_key = hmac_sha1(salted_password, "Server Key");
return true, stored_key, server_key
end
local function scram_gen(hash_name, H_f, HMAC_f)
local profile_name = "scram_" .. hashprep(hash_name);
local function scram_hash(self, message)
local support_channel_binding = false;
if self.profile.cb then support_channel_binding = true; end
if type(message) ~= "string" or #message == 0 then return "failure", "malformed-request" end
local state = self.state;
if not state then
-- we are processing client_first_message
local client_first_message = message;
-- TODO: fail if authzid is provided, since we don't support them yet
local gs2_header, gs2_cbind_flag, gs2_cbind_name, authzid, client_first_message_bare, username, clientnonce
= s_match(client_first_message, "^(([pny])=?([^,]*),([^,]*),)(m?=?[^,]*,?n=([^,]*),r=([^,]*),?.*)$");
if not gs2_cbind_flag then
return "failure", "malformed-request";
end
if support_channel_binding and gs2_cbind_flag == "y" then
-- "y" -> client does support channel binding
-- but thinks the server does not.
return "failure", "malformed-request";
end
if gs2_cbind_flag == "n" then
-- "n" -> client doesn't support channel binding.
support_channel_binding = false;
end
if support_channel_binding and gs2_cbind_flag == "p" then
-- check whether we support the proposed channel binding type
if not self.profile.cb[gs2_cbind_name] then
return "failure", "malformed-request", "Proposed channel binding type isn't supported.";
end
else
-- no channel binding,
gs2_cbind_name = nil;
end
username = validate_username(username, self.profile.nodeprep);
if not username then
log("debug", "Username violates either SASLprep or contains forbidden character sequences.")
return "failure", "malformed-request", "Invalid username.";
end
-- retreive credentials
local stored_key, server_key, salt, iteration_count;
if self.profile.plain then
local password, state = self.profile.plain(self, username, self.realm)
if state == nil then return "failure", "not-authorized"
elseif state == false then return "failure", "account-disabled" end
password = saslprep(password);
if not password then
log("debug", "Password violates SASLprep.");
return "failure", "not-authorized", "Invalid password."
end
salt = generate_uuid();
iteration_count = default_i;
local succ = false;
succ, stored_key, server_key = getAuthenticationDatabaseSHA1(password, salt, iteration_count);
if not succ then
log("error", "Generating authentication database failed. Reason: %s", stored_key);
return "failure", "temporary-auth-failure";
end
elseif self.profile[profile_name] then
local state;
stored_key, server_key, iteration_count, salt, state = self.profile[profile_name](self, username, self.realm);
if state == nil then return "failure", "not-authorized"
elseif state == false then return "failure", "account-disabled" end
end
local nonce = clientnonce .. generate_uuid();
local server_first_message = "r="..nonce..",s="..base64.encode(salt)..",i="..iteration_count;
self.state = {
gs2_header = gs2_header;
gs2_cbind_name = gs2_cbind_name;
username = username;
nonce = nonce;
server_key = server_key;
stored_key = stored_key;
client_first_message_bare = client_first_message_bare;
server_first_message = server_first_message;
}
return "challenge", server_first_message
else
-- we are processing client_final_message
local client_final_message = message;
local client_final_message_without_proof, channelbinding, nonce, proof
= s_match(client_final_message, "(c=([^,]*),r=([^,]*),?.-),p=(.*)$");
if not proof or not nonce or not channelbinding then
return "failure", "malformed-request", "Missing an attribute(p, r or c) in SASL message.";
end
local client_gs2_header = base64.decode(channelbinding)
local our_client_gs2_header = state["gs2_header"]
if state.gs2_cbind_name then
-- we support channelbinding, so check if the value is valid
our_client_gs2_header = our_client_gs2_header .. self.profile.cb[state.gs2_cbind_name](self);
end
if client_gs2_header ~= our_client_gs2_header then
return "failure", "malformed-request", "Invalid channel binding value.";
end
if nonce ~= state.nonce then
return "failure", "malformed-request", "Wrong nonce in client-final-message.";
end
local ServerKey = state.server_key;
local StoredKey = state.stored_key;
local AuthMessage = state.client_first_message_bare .. "," .. state.server_first_message .. "," .. client_final_message_without_proof
local ClientSignature = HMAC_f(StoredKey, AuthMessage)
local ClientKey = binaryXOR(ClientSignature, base64.decode(proof))
local ServerSignature = HMAC_f(ServerKey, AuthMessage)
if StoredKey == H_f(ClientKey) then
local server_final_message = "v="..base64.encode(ServerSignature);
self["username"] = state.username;
return "success", server_final_message;
else
return "failure", "not-authorized", "The response provided by the client doesn't match the one we calculated.";
end
end
end
return scram_hash;
end
local function init(registerMechanism)
local function registerSCRAMMechanism(hash_name, hash, hmac_hash)
registerMechanism("SCRAM-"..hash_name, {"plain", "scram_"..(hashprep(hash_name))}, scram_gen(hash_name:lower(), hash, hmac_hash));
-- register channel binding equivalent
registerMechanism("SCRAM-"..hash_name.."-PLUS", {"plain", "scram_"..(hashprep(hash_name))}, scram_gen(hash_name:lower(), hash, hmac_hash), {"tls-unique"});
end
registerSCRAMMechanism("SHA-1", sha1, hmac_sha1);
end
return {
getAuthenticationDatabaseSHA1 = getAuthenticationDatabaseSHA1;
init = init;
}
| mit |
pexip/os-ruby-passenger | build/rake_extensions.rb | 4707 | # Phusion Passenger - https://www.phusionpassenger.com/
# Copyright (c) 2010 Phusion
#
# "Phusion Passenger" is a trademark of Hongli Lai & Ninh Bui.
#
# 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.
require 'pathname'
# Provides useful extensions for Rake.
module RakeExtensions
# Allows one to define Rake rules in the context of the given
# subdirectory. For example,
#
# subdir 'foo' do
# file 'libfoo.so' => ['foo.c'] do
# sh 'gcc foo.c -shared -fPIC -o libfoo.so'
# end
# end
#
# subdir 'bar' do
# file 'bar' => ['bar.c', '../foo/libfoo.so'] do
# sh 'gcc bar.c -o bar -L../foo -lfoo'
# end
# end
#
# is equivalent to:
#
# file 'foo/libfoo.so' => ['foo/foo.c'] do
# Dir.chdir('foo') do
# sh 'gcc foo.c -shared -fPIC -o libfoo.so'
# end
# end
#
# file 'bar/bar' => ['bar/bar.c', 'foo/libfoo.so'] do
# Dir.chdir('bar') do
# sh 'gcc bar.c -o bar -L../foo -lfoo'
# end
# end
#
# === String dependencies are assumed to be filenames
#
# But be careful with string dependencies. They are assumed to be filenames,
# and will be automatically converted. For example:
#
# subdir 'foo' do
# task 'super_app' => ['super_app:compile', 'super_app:unit_test']
#
# task 'super_app:compile' do
# ...
# end
#
# task 'super_app:unit_test' do
# ...
# end
# end
#
# will be treated like:
#
# subdir 'foo' do
# # !!!!!!!
# task 'super_app' => ['foo/super_app:compile', 'foo/super_app:unit_test']
#
# task 'super_app:compile' do
# ...
# end
#
# task 'super_app:unit_test' do
# ...
# end
# end
#
# To solve this, declare your dependencies as symbols:
#
# task 'super_app' => [:'super_app:compile', :'super_app:unit_test']
#
# (note the leading ':' character)
#
# === Supported Rake commands
#
# Only the <tt>file</tt> and <tt>target</tt> Rake commands are supported.
def subdir(dir, &block)
subdir = Subdir.new(dir)
Dir.chdir(dir) do
subdir.instance_eval(&block)
end
end
class Subdir # :nodoc:
# Rake 0.9 compatibility since methods like <tt>task<tt> and <tt>desc</tt>
# aren't available in Object anymore.
# See: https://github.com/jimweirich/rake/issues/33#issuecomment-1213705
include Rake::DSL if defined?(Rake::DSL)
def initialize(dir)
@dir = dir
@toplevel_dir = Pathname.getwd
end
def file(args, &block)
case args
when String
args = mangle_path(args)
when Hash
target = mangle_path(args.keys[0])
sources = mangle_path_or_path_array(args.values[0])
args = { target => sources }
end
Rake::FileTask.define_task(args) do
puts "### In #{@dir}:"
Dir.chdir(@dir) do
Object.class_eval(&block)
end
puts ""
end
end
def task(*args, &block)
if !args.empty? && args[0].is_a?(Hash)
target = args[0].keys[0]
sources = mangle_path_or_path_array(args[0].values[0])
args[0] = { target => sources }
end
if block_given?
Rake::Task.define_task(*args) do
puts "### In #{@dir}:"
Dir.chdir(@dir) do
Object.class_eval(&block)
end
puts ""
end
else
Rake::Task.define_task(*args)
end
end
private
def mangle_path(path)
path = File.expand_path(path)
return Pathname.new(path).relative_path_from(@toplevel_dir).to_s
end
def mangle_path_array(array)
array = array.dup
array.each_with_index do |item, i|
if item.is_a?(String)
array[i] = mangle_path(item)
end
end
return array
end
def mangle_path_or_path_array(item)
case item
when String
return mangle_path(item)
when Array
return mangle_path_array(item)
else
return item
end
end
end
end # module RakeExtensions
Object.class_eval do
include RakeExtensions
end
| mit |
demigor/nreact | NReact/Differs/NListDiffer.cs | 4980 | using System;
namespace NReact
{
struct NListDiffer
{
public static NPatch Diff(NElement[] source, NElement[] target)
{
var oldSet = source != null;
var newSet = target != null;
if (oldSet == newSet)
{
if (!oldSet)
return null;
return new NListDiffer(source, target).Diff();
}
return NPatch.AssignNewValue;
}
readonly NElement[] _source, _target;
NListDiffer(NElement[] source, NElement[] target)
{
_source = source;
_target = target;
_head = null;
_tail = null;
}
NListPatchEntry _head, _tail;
NPatch Diff()
{
var cOld = _source.Length;
var cNew = _target.Length;
if (cOld == 0 || cNew == 0)
return NPatch.AssignNewValue;
var iOld = 0;
var iNew = 0;
var iFix = 0;
for (;;)
{
var oldH = iOld < cOld;
var oldE = oldH ? _source[iOld] : null;
var newH = iNew < cNew;
var newE = newH ? _target[iNew] : null;
if (oldH)
{
if (newH && NPatch.ElementEquals(oldE, newE))
{
Update(iOld + iFix, newE, oldE);
iNew++;
}
else
{
Remove(iOld + iFix, oldE);
iFix--;
}
iOld++;
}
else
{
if (newH)
{
Insert(iOld + iFix, newE);
iOld++;
iNew++;
}
else
break;
}
}
Optimize();
TransferClasses();
return _head != null ? new NListPatch(_head) : null;
}
void Optimize()
{
for (var i = _head; i != null; i = i.Next)
switch (i.Op)
{
case NListPatchOp.Insert: OptimizeInsert(i); break;
case NListPatchOp.Remove: OptimizeRemove(i); break;
}
}
void OptimizeInsert(NListPatchEntry e)
{
var delta = 0;
var newE = e.Finalizer;
var last = e;
for (var i = e.Next; i != null; i = i.Next)
{
switch (i.Op)
{
case NListPatchOp.Remove:
{
var oldE = i.Value;
if (NPatch.ElementEquals(newE, oldE))
{
e.Op = NListPatchOp.Move; // transform to move operation
e.Finalizer = null; // remove finalizer
e.iRemove = i.iRemove + delta; // correct removal index at the time of move
e.Value = oldE; // preserve moved value
e.Patch = NPropDiffer.Diff(oldE, ref newE); // make patch
last.Next = i.Next; // delete removal
return;
}
delta++;
}
break;
case NListPatchOp.Insert:
delta--;
break;
}
last = i;
}
}
void OptimizeRemove(NListPatchEntry e)
{
var delta = 0;
var oldE = e.Finalizer;
var last = e;
for (var i = e.Next; i != null; i = i.Next)
{
switch (i.Op)
{
case NListPatchOp.Insert:
{
var newE = i.Value;
if (NPatch.ElementEquals(newE, oldE))
{
e.Op = NListPatchOp.Move; // transform to move
e.Finalizer = null; // remove finalizer
e.iInsert = i.iInsert + delta; // correct insert index at the time of move
e.iFinal = i.iFinal; // preserve final index
e.Patch = NPropDiffer.Diff(oldE, ref newE); // make patch
e.Value = oldE; // preserve moved value
last.Next = i.Next; // delete insertion
return;
}
delta--;
}
break;
case NListPatchOp.Remove:
delta++;
break;
}
last = i;
}
}
void TransferClasses()
{
for (var i = _head; i != null; i = i.Next)
if (i.Op == NListPatchOp.Move && i.Value is NClass)
_target[i.iFinal] = i.Value;
}
void Add(NListPatchEntry entry)
{
if (_tail != null)
_tail.Next = entry;
else
_head = entry;
_tail = entry;
}
void Insert(int idx, NElement newE)
{
Add(new NListPatchEntry { Op = NListPatchOp.Insert, Value = newE, iInsert = idx, iFinal = idx });
}
void Remove(int idx, NElement oldE)
{
Add(new NListPatchEntry { Op = NListPatchOp.Remove, iRemove = idx, Finalizer = oldE });
}
void Update(int idx, NElement newE, NElement oldE)
{
if (oldE is NClass)
_target[idx] = oldE; // transfer updated classes
var p = NPropDiffer.Diff(oldE, ref newE);
if (p != null)
Add(new NListPatchEntry { Op = NListPatchOp.Patch, Value = oldE, iFinal = idx, Patch = p });
}
}
}
| mit |
mrazicz/redis-model-extension | lib/redis-model-extension/get_find.rb | 5146 | # -*- encoding : utf-8 -*-
module RedisModelExtension
# == Get & Find
# * Model.all => Array of all instances
# * Model.find(1) => Array of one instance with id 1
# * Model.get(1) => Array of one instance with id 1
# * Model.find( id: 1 ) => Array of one instance with id 1
# * Model.find( field: "test" ) => Array of all instances with field == test [field must be in redis key]
module ClassGetFind
######################################
# FIND METHODS
######################################
#Find method for searching in redis
# * args (Integer) - search by id
# * args (Hash) - search by arguments in redis_key
def find(args = {})
# when argument is integer - search by id
args = { id: args } if args.is_a?(Integer)
#normalize input hash of arguments
args = HashWithIndifferentAccess.new(args)
out = []
klass = self.name.constantize
search_key = klass.generate_key(args)
#is key specified directly? -> no needs of looking for other keys! -> faster
unless search_key =~ /\*/
out << klass.new_by_key(search_key) if klass.exists?(args)
else
RedisModelExtension::Database.redis {|r| r.keys(search_key) }.each do |key|
out << klass.new_by_key(key)
end
end
out
end
alias :all :find
#Find method for searching in redis
def find_by_alias(alias_name, args = {})
#check if asked dynamic alias exists
raise ArgumentError, "Unknown dynamic alias: '#{alias_name}', use: #{redis_alias_config.keys.join(", ")} " unless redis_alias_config.has_key?(alias_name.to_sym)
#normalize input hash of arguments
args = HashWithIndifferentAccess.new(args)
out = []
klass = self.name.constantize
search_key = klass.generate_alias_key(alias_name, args)
#is key specified directly? -> no needs of looking for other keys! -> faster
unless search_key =~ /\*/
out = klass.get_by_alias(alias_name, args) if klass.alias_exists?(alias_name, args)
else
RedisModelExtension::Database.redis {|r| r.keys(search_key) }.each do |key|
out << klass.get_by_alias_key(key)
end
end
out.flatten
end
######################################
# GET BY ARGUMENTS
######################################
#fastest method to get object from redis by getting it by arguments
# * args (Integer) - search by id
# * args (Hash) - search by arguments in redis_key
def get(args = {})
# when argument is integer - search by id
args = { id: args } if args.is_a?(Integer)
#normalize input hash of arguments
args = HashWithIndifferentAccess.new(args)
klass = self.name.constantize
if klass.valid_key?(args) && klass.exists?(args)
klass.new_by_key(klass.generate_key(args))
else
nil
end
end
######################################
# GET BY REDIS KEYS
######################################
#fastest method to get object from redis by getting it by dynamic alias and arguments
def get_by_alias(alias_name, args = {})
#check if asked dynamic alias exists
raise ArgumentError, "Unknown dynamic alias: '#{alias_name}', use: #{redis_alias_config.keys.join(", ")} " unless redis_alias_config.has_key?(alias_name.to_sym)
#normalize input hash of arguments
args = HashWithIndifferentAccess.new(args)
klass = self.name.constantize
if klass.valid_alias_key?(alias_name, args) && klass.alias_exists?(alias_name, args)
out = []
RedisModelExtension::Database.redis {|r| r.smembers(klass.generate_alias_key(alias_name, args)) }.each do |key|
item = klass.new_by_key(key)
out << item if item
end
return out
end
nil
end
######################################
# GET BY REDIS KEYS
######################################
#if you know redis key and would like to get object
def get_by_redis_key(redis_key)
if redis_key.is_a?(String)
klass = self.name.constantize
klass.new_by_key(redis_key)
else
nil
end
end
#fastest method to get object from redis by getting it by alias and arguments
def get_by_alias_key(alias_key)
klass = self.name.constantize
if RedisModelExtension::Database.redis {|r| r.exists(alias_key) }
out = []
RedisModelExtension::Database.redis {|r| r.smembers(alias_key) }.each do |key|
item = klass.new_by_key(key)
out << item if item
end
return out
end
nil
end
######################################
# CREATE NEW OBJECT BY HASH VALUES
######################################
# read all data from redis and create new instance (used for Find & Get method)
def new_by_key(key)
args = RedisModelExtension::Database.redis {|r| r.hgetall(key) }
return nil unless args && args.any?
args.symbolize_keys!
new_instance = new(args)
new_instance.store_keys
return new_instance
end
end
end
| mit |
MonoKu2014/iso | application/views/causas_incidencias/agregar.php | 2307 | <div class="container-fluid">
<ol class="breadcrumb">
<li><a href="<?= base_url();?>panel">Dashboard</a></li>
<li>Parámetros</li>
<li><a href="<?= base_url();?>causas_incidencias">Causas Incidencias</a></li>
<li class="active">Agregar</li>
</ol>
<div class="row">
<div class="col-lg-12">
<h2 class="page-header">
Agregar Causa Incidencia
<a href="<?= base_url(); ?>causas_incidencias" class="btn btn-default pull-right">
<i class="fa fa-chevron-left"></i> Volver
</a>
</h2>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<form method="post" action="<?= base_url(); ?>causas_incidencias/guardar" class="form">
<div class="row">
<div class="col-xs-12 col-lg-10 col-lg-offset-1">
<p><em>Todos los campos marcados con (*) son de caracter obligatorio</em></p>
<p id="message"></p>
<div class="col-xs-12 col-sm-6 col-md-3 bg-info information">
Código Causa (*)
</div>
<div class="col-xs-12 col-sm-6 col-md-9">
<div class="form-group">
<input type="text" name="causa_incidencia_codigo" data-validate="string" class="form-control required" placeholder="Código Causa" required>
</div>
</div>
<div class="col-xs-12 col-sm-6 col-md-3 bg-info information">
Causa (*)
</div>
<div class="col-xs-12 col-sm-6 col-md-9">
<div class="form-group">
<input type="text" name="causa_incidencia" data-validate="string" class="form-control required" placeholder="Causa" required>
</div>
</div>
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-12">
<button type="submit" class="btn btn-success save">Guardar</button>
<a href="<?= base_url(); ?>causas_incidencias" class="btn btn-default">Cancelar</a>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div> | mit |
DavidVeksler/SmallTalk | Apps/SmallTalk.Web/App_Start/IdentityConfig.cs | 1790 | using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using SmallTalk.Web.Models;
namespace SmallTalk.Web
{
// Configure the application user manager used in this application. UserManager is defined in ASP.NET Identity and is used by the application.
public class ApplicationUserManager : UserManager<ApplicationUser>
{
public ApplicationUserManager(IUserStore<ApplicationUser> store)
: base(store)
{
}
public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
{
var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
// Configure validation logic for usernames
manager.UserValidator = new UserValidator<ApplicationUser>(manager)
{
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = true
};
// Configure validation logic for passwords
manager.PasswordValidator = new PasswordValidator
{
RequiredLength = 6,
RequireNonLetterOrDigit = true,
RequireDigit = true,
RequireLowercase = true,
RequireUppercase = true,
};
var dataProtectionProvider = options.DataProtectionProvider;
if (dataProtectionProvider != null)
{
manager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
}
return manager;
}
}
}
| mit |
jonhenning/CodeEndeavors-ResourceManager | CodeEndeavors.ResourceManager.ServiceHost/ServiceHostRepository.cs | 13671 | using CodeEndeavors.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RepositoryDomainObjects = CodeEndeavors.Services.ResourceManager.Shared.DomainObjects;
using DomainObjects = CodeEndeavors.ResourceManager.DomainObjects;
using System.Collections.Concurrent;
using CodeEndeavors.ResourceManager;
using CodeEndeavors.Services.ResourceManager.Client;
using CodeEndeavors.ServiceHost.Common.Services;
namespace CodeEndeavors.ResourceManager.ServiceHost
{
public class ServiceHostRepository : IRepository, IDisposable
{
private Dictionary<string, object> _connection = null;
private Dictionary<string, object> _cacheConnection = null;
//private string _cacheName;
private string _namespace;
//private bool _useFileMonitor;
private int _auditHistorySize;
private bool _enableAudit;
private ConcurrentDictionary<string, List<RepositoryDomainObjects.Resource>> _pendingResourceUpdates = new ConcurrentDictionary<string, List<RepositoryDomainObjects.Resource>>();
private ConcurrentDictionary<string, List<RepositoryDomainObjects.ResourceAudit>> _pendingAuditUpdates = new ConcurrentDictionary<string, List<RepositoryDomainObjects.ResourceAudit>>();
//repository instance lifespan is a single request (for videre) - not ideal as we really don't want to dictate how resourcemanager is used in relation to its lifespan
private ConcurrentDictionary<string, object> _pendingDict = new ConcurrentDictionary<string, object>();
public ServiceHostRepository()
{
}
public void Initialize(Dictionary<string, object> connection, Dictionary<string, object> cacheConnection)
{
_connection = connection;
_cacheConnection = cacheConnection;
var cacheName = _cacheConnection.GetSetting("cacheName", "");
_namespace = _connection.GetSetting("namespace", "");
//_useFileMonitor = _connection.GetSetting("useFileMonitor", false);
_auditHistorySize = _connection.GetSetting("auditHistorySize", 10); //todo: how is this getting passed up the chain?
_enableAudit = _auditHistorySize > 0;
var url = _connection.GetSetting("url", "");
var requestTimeout = _connection.GetSetting("requestTimeout", 600000);
var httpUser = _connection.GetSetting("httpUser", "");
var httpPassword = _connection.GetSetting("httpPassword", "");
var authenticationType = _connection.GetSetting("authenticationType", "None");
var logLevel = _connection.GetSetting("logLevel", "Info");
if (string.IsNullOrEmpty(url))
throw new Exception("url key not found in connection");
if (authenticationType != "None")
ServiceLocator.Register<RepositoryService>(url, requestTimeout, httpUser, httpPassword, authenticationType.ToType<AuthenticationType>());
else
ServiceLocator.Register<RepositoryService>(url, requestTimeout);
//todo: setaquireuserid?!?!?!
ServiceLocator.Resolve<RepositoryService>().SetAquireUserIdDelegate(() => { return "5"; }); //FIX;
ServiceLocator.Resolve<RepositoryService>().ConfigureLogging("ResourceManager", logLevel, (string level, string message) =>
{
Logging.Log(Logging.LoggingLevel.Minimal, message); //todo: map log levels
});
ServiceLocator.Resolve<RepositoryService>().ConfigureCache(cacheName, _cacheConnection.ToJson());
//Logging.Log(Logging.LoggingLevel.Minimal, "ServiceHost Repository Initialized");
}
public DomainObjects.Resource<T> GetResource<T>(string id)
{
var dict = AllDict<T>();
if (!string.IsNullOrEmpty(id) && dict.ContainsKey(id))
return dict[id];
return null;
}
public List<T> Find<T>(Func<T, bool> predicate)
{
return All<T>().Where(predicate).ToList();
}
public List<DomainObjects.Resource<T>> FindResources<T>(Func<DomainObjects.Resource<T>, bool> predicate)
{
return AllResources<T>().Where(predicate).ToList();
}
public List<DomainObjects.Resource<T>> AllResources<T>()
{
return AllDict<T>().Values.ToList(); //todo: perf problem????
}
public List<T> All<T>()
{
return AllDict<T>().Values.Select(v => v.Data).ToList();
}
public ConcurrentDictionary<string, DomainObjects.Resource<T>> AllDict<T>()
{
var resourceType = getResourceType<T>();
if (_pendingDict.ContainsKey(resourceType))
{
Logging.Log(Logging.LoggingLevel.Verbose, "Pulled {0} from _pendingDict", resourceType);
return _pendingDict[resourceType] as ConcurrentDictionary<string, DomainObjects.Resource<T>>;
}
Func<ConcurrentDictionary<string, DomainObjects.Resource<T>>> getDelegate = delegate()
{
var resource = new List<DomainObjects.Resource<T>>();
var sr = RepositoryService.Resolve().GetResources(resourceType, _enableAudit, _namespace);
if (sr.Success)
{
foreach (var resourceRow in sr.Data)
{
resource.Add(toResource<T>(resourceRow));
}
//todo: handle Audit
return new ConcurrentDictionary<string, DomainObjects.Resource<T>>(resource.ToDictionary(r => r.Id));
}
else
throw new Exception(sr.ToString());
};
//var dict = CodeEndeavors.Distributed.Cache.Client.Service.GetCacheEntry(_cacheName, resourceType, getDelegate, null); //getMonitorOptions(fileName));
var dict = getDelegate();
_pendingDict[resourceType] = dict;
return dict;
}
public void Store<T>(DomainObjects.Resource<T> item)
{
var resourceType = getResourceType<T>();
var rowState = RepositoryDomainObjects.RowStateEnum.Modified;
if (string.IsNullOrEmpty(item.Id))
{
item.Id = Guid.NewGuid().ToString(); //todo: use another resource for this...
try
{
((dynamic)item.Data).Id = item.Id; //todo: require Id on object?
}
catch { }
rowState = RepositoryDomainObjects.RowStateEnum.Added;
}
var dict = AllDict<T>();
dict[item.Id] = item; //item is inserted into "local" cache here, we need to add it to Redis if we have it!
//_cacheName, "Table", TimeSpan.FromHours(1), new List<string> { resourceType }, resourceType, resourceType
//Storing updated dictionary directly before update!!!!!
//we cache the DomainObjects.Resource, not the direct object
//RepositoryService.Resolve().SetCacheEntry(resourceType, null, resourceType, dict.Values.Select(d => toRepositoryResource(d, Services.ResourceManager.Shared.DomainObjects.RowStateEnum.Unchanged)).ToList());
RepositoryService.Resolve().SetResource(resourceType, null, toRepositoryResource(item, Services.ResourceManager.Shared.DomainObjects.RowStateEnum.Unchanged), _namespace);
if (!_pendingResourceUpdates.ContainsKey(resourceType))
_pendingResourceUpdates[resourceType] = new List<RepositoryDomainObjects.Resource>();
if (!_pendingAuditUpdates.ContainsKey(resourceType))
_pendingAuditUpdates[resourceType] = new List<RepositoryDomainObjects.ResourceAudit>();
_pendingResourceUpdates[resourceType].Add(toRepositoryResource(item, rowState));
if (item.Audit.Count > 0)
_pendingAuditUpdates[resourceType].Add(toRepositoryAudit(item.Id, item.Audit.FirstOrDefault()));
}
public void Save()
{
foreach (var resourceType in _pendingResourceUpdates.Keys)
{
if (_pendingResourceUpdates[resourceType].Count > 0)
{
if (_pendingAuditUpdates.ContainsKey(resourceType))
_pendingResourceUpdates[resourceType].ForEach(r => r.ResourceAudits = _pendingAuditUpdates[resourceType].Where(a => a.ResourceId == r.Id).ToList());
var sr = RepositoryService.Resolve().SaveResources(_pendingResourceUpdates[resourceType], _namespace);
if (!sr.Success)
throw new Exception(sr.ToString());
//expireCacheEntry(resourceType);
}
}
_pendingResourceUpdates = new ConcurrentDictionary<string, List<RepositoryDomainObjects.Resource>>();
_pendingAuditUpdates = new ConcurrentDictionary<string, List<RepositoryDomainObjects.ResourceAudit>>();
}
public void Delete<T>(DomainObjects.Resource<T> item)
{
var resourceType = getResourceType<T>();
if (!_pendingResourceUpdates.ContainsKey(resourceType))
_pendingResourceUpdates[resourceType] = new List<RepositoryDomainObjects.Resource>();
_pendingResourceUpdates[resourceType].Add(toRepositoryResource(item, RepositoryDomainObjects.RowStateEnum.Deleted));
}
public void DeleteAll<T>()
{
var resourceType = getResourceType<T>();
var sr = RepositoryService.Resolve().DeleteAll(resourceType, "", _namespace);
if (sr.Success)
{
//expireCacheEntry(resourceType);
List<RepositoryDomainObjects.Resource> res;
List<RepositoryDomainObjects.ResourceAudit> resAudit;
_pendingResourceUpdates.TryRemove(resourceType, out res);
_pendingAuditUpdates.TryRemove(resourceType, out resAudit);
}
else
throw new Exception(sr.ToString());
}
public string ObtainLock(string source, string ns)
{
var sr = RepositoryService.Resolve().ObtainLock(source, ns);
if (sr.Success)
return sr.Data;
else
throw new Exception(sr.ToString());
}
public bool RemoveLock(string source, string ns)
{
var sr = RepositoryService.Resolve().RemoveLock(source, ns);
if (sr.Success)
return sr.Data;
else
throw new Exception(sr.ToString());
}
private string getResourceType<T>()
{
return typeof(T).ToString();
}
//private void expireCacheEntry(string key)
//{
// CodeEndeavors.Distributed.Cache.Client.Service.ExpireCacheEntry(_cacheName, key);
//}
private object getMonitorOptions(string fileName)
{
//if (_useFileMonitor)
// return new { monitorType = "CodeEndeavors.Distributed.Cache.Client.File.FileMonitor", fileName = fileName, uniqueProperty = "fileName" };
return null;
}
private DomainObjects.Resource<T> toResource<T>(RepositoryDomainObjects.Resource resource)
{
var ret = new DomainObjects.Resource<T>();
ret.Id = resource.Id;
ret.Key = resource.Key;
ret.Type = resource.Type;
ret.EffectiveDate = resource.EffectiveDate;
ret.ExpirationDate = resource.ExpirationDate;
var json = resource.Data;
if (!string.IsNullOrEmpty(json))
ret.Data = json.ToObject<T>();
json = resource.Scope;
if (!string.IsNullOrEmpty(json))
ret.Scope = json.ToObject<dynamic>();
foreach (var audit in resource.ResourceAudits)
{
ret.Audit.Add(new DomainObjects.Audit()
{
Action = audit.Action,
UserId = audit.UserId,
Date = audit.AuditDate
});
}
return ret;
}
private RepositoryDomainObjects.Resource toRepositoryResource<T>(DomainObjects.Resource<T> resource, RepositoryDomainObjects.RowStateEnum rowState)
{
return new RepositoryDomainObjects.Resource()
{
Id = resource.Id,
ResourceType = getResourceType<T>(),
Key = resource.Key,
Type = resource.Type,
Sequence = resource.Sequence,
EffectiveDate = resource.EffectiveDate,
ExpirationDate = resource.ExpirationDate,
Data = resource.Data != null ? resource.Data.ToJson(false, "db") : null,
Scope = resource.Scope != null ? ((object)resource.Scope).ToJson() : null,
RowState = rowState
};
}
private RepositoryDomainObjects.ResourceAudit toRepositoryAudit(string resourceId, DomainObjects.Audit audit)
{
return new RepositoryDomainObjects.ResourceAudit()
{
ResourceId = resourceId,
UserId = audit.UserId,
Action = audit.Action
};
}
public void Dispose()
{
}
}
}
| mit |
x335/JSIL | Tests/CompilerUtil.cs | 11087 | using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Web.Script.Serialization;
using FSharp.Compiler.CodeDom;
using Microsoft.CSharp;
using Microsoft.VisualBasic;
namespace JSIL.Tests {
using System.Runtime.Serialization;
public static class CompilerUtil {
public static string TempPath;
// Attempt to clean up stray assembly files from previous test runs
// since the assemblies would have remained locked and undeletable
// due to being loaded
static CompilerUtil () {
TempPath = Path.Combine(Path.GetTempPath(), "JSIL Tests");
if (!Directory.Exists(TempPath))
Directory.CreateDirectory(TempPath);
foreach (var filename in Directory.GetFiles(TempPath))
try {
File.Delete(filename);
} catch {
}
}
public static CompileResult Compile (
IEnumerable<string> filenames, string assemblyName, string compilerOptions = ""
) {
var extension = Path.GetExtension(filenames.First()).ToLower();
Func<CodeDomProvider> provider = null;
switch (extension) {
case ".cs":
provider = () => new CSharpCodeProvider(new Dictionary<string, string>() {
{ "CompilerVersion", "v4.0" }
});
break;
case ".vb":
provider = () => new VBCodeProvider(new Dictionary<string, string>() {
{ "CompilerVersion", "v4.0" }
});
break;
case ".fs":
provider = () => {
var result = new FSharpCodeProvider();
return result;
};
break;
case ".il":
provider = () =>
{
var result = new CILCodeProvider();
return result;
};
break;
case ".cpp":
provider = () =>
{
var result = new CPPCodeProvider();
return result;
};
break;
default:
throw new NotImplementedException("Extension '" + extension + "' cannot be compiled for test cases");
}
return Compile(
provider, filenames, assemblyName, compilerOptions
);
}
private static DateTime GetJSILMetaTimestamp () {
return File.GetLastWriteTimeUtc(typeof(JSIL.Meta.JSChangeName).Assembly.Location);
}
private static bool CheckCompileManifest (IEnumerable<string> inputs, string outputDirectory) {
var manifestPath = Path.Combine(outputDirectory, "compileManifest.json");
if (!File.Exists(manifestPath))
return false;
var jss = new JavaScriptSerializer();
var manifest = jss.Deserialize<Dictionary<string, string>>(File.ReadAllText(manifestPath));
var expectedMetaTimestamp = GetJSILMetaTimestamp().ToString();
string metaTimestamp;
if (!manifest.TryGetValue("metaTimestamp", out metaTimestamp)) {
return false;
}
if (metaTimestamp != expectedMetaTimestamp) {
return false;
}
foreach (var input in inputs) {
var fi = new FileInfo(input);
var key = Path.GetFileName(input);
if (!manifest.ContainsKey(key))
return false;
var previousTimestamp = DateTime.Parse(manifest[key]);
var delta = fi.LastWriteTime - previousTimestamp;
if (Math.Abs(delta.TotalSeconds) >= 1) {
return false;
}
}
return true;
}
private static void WriteCompileManifest (IEnumerable<string> inputs, string outputDirectory) {
var manifest = new Dictionary<string, string>();
manifest["metaTimestamp"] = GetJSILMetaTimestamp().ToString();
foreach (var input in inputs) {
var fi = new FileInfo(input);
var key = Path.GetFileName(input);
manifest[key] = fi.LastWriteTime.ToString("O");
}
var manifestPath = Path.Combine(outputDirectory, "compileManifest.json");
var jss = new JavaScriptSerializer();
File.WriteAllText(manifestPath, jss.Serialize(manifest));
}
private static CompileResult Compile (
Func<CodeDomProvider> getProvider, IEnumerable<string> _filenames, string assemblyName, string compilerOptions
) {
var filenames = _filenames.ToArray();
var tempPath = Path.Combine(TempPath, assemblyName);
Directory.CreateDirectory(tempPath);
var warningTextPath = Path.Combine(
tempPath, "warnings.txt"
);
var references = new List<string> {
"System.dll",
"System.Core.dll", "System.Xml.dll",
"Microsoft.CSharp.dll",
typeof(JSIL.Meta.JSIgnore).Assembly.Location
};
bool generateExecutable = false;
var metacomments = new List<Metacomment>();
foreach (var sourceFile in filenames) {
var sourceText = File.ReadAllText(sourceFile);
var localMetacomments = Metacomment.FromText(sourceText);
foreach (var metacomment in localMetacomments) {
switch (metacomment.Command.ToLower()) {
case "reference":
references.Add(metacomment.Arguments);
break;
case "compileroption":
compilerOptions += " " + metacomment.Arguments;
break;
case "generateexecutable":
generateExecutable = true;
break;
}
}
metacomments.AddRange(localMetacomments);
}
var outputAssembly = Path.Combine(
tempPath,
Path.GetFileNameWithoutExtension(assemblyName) +
(generateExecutable ? ".exe" : ".dll")
);
if (
File.Exists(outputAssembly) &&
CheckCompileManifest(filenames, tempPath)
) {
if (File.Exists(warningTextPath))
Console.Error.WriteLine(File.ReadAllText(warningTextPath));
return new CompileResult(
generateExecutable ? Assembly.ReflectionOnlyLoadFrom(outputAssembly) : Assembly.LoadFile(outputAssembly),
metacomments.ToArray()
);
}
var files = Directory.GetFiles(tempPath);
foreach (var file in files) {
try {
File.Delete(file);
} catch {
}
}
var parameters = new CompilerParameters(references.ToArray()) {
CompilerOptions = compilerOptions,
GenerateExecutable = generateExecutable,
GenerateInMemory = false,
IncludeDebugInformation = true,
TempFiles = new TempFileCollection(tempPath, true),
OutputAssembly = outputAssembly,
WarningLevel = 4,
TreatWarningsAsErrors = false
};
CompilerResults results;
using (var provider = getProvider()) {
results = provider.CompileAssemblyFromFile(
parameters,
filenames.ToArray()
);
}
var compileErrorsAndWarnings = results.Errors.Cast<CompilerError>().ToArray();
var compileWarnings = (from ce in compileErrorsAndWarnings where ce.IsWarning select ce).ToArray();
var compileErrors = (from ce in compileErrorsAndWarnings where !ce.IsWarning select ce).ToArray();
// Mono incorrectly trats some warnings as errors;
if (Type.GetType("Mono.Runtime") != null)
{
if (compileErrors.Length > 0 && File.Exists(outputAssembly))
{
try
{
results.CompiledAssembly = Assembly.LoadFrom(outputAssembly);
compileErrors = new CompilerError[0];
compileWarnings = compileErrorsAndWarnings;
}
catch (Exception)
{
}
}
}
if (compileWarnings.Length > 0) {
var warningText = String.Format(
"// C# Compiler warning(s) follow //\r\n{0}\r\n// End of C# compiler warning(s) //",
String.Join(Environment.NewLine, compileWarnings.Select(Convert.ToString).ToArray())
);
Console.Error.WriteLine(
warningText
);
File.WriteAllText(
warningTextPath, warningText
);
} else {
if (File.Exists(warningTextPath))
File.Delete(warningTextPath);
}
if (compileErrors.Length > 0) {
throw new Exception(
String.Join(Environment.NewLine, compileErrors.Select(Convert.ToString).ToArray())
);
}
WriteCompileManifest(filenames, tempPath);
return new CompileResult(
results.CompiledAssembly,
metacomments.ToArray()
);
}
}
public class CompileResult {
public readonly Assembly Assembly;
public readonly Metacomment[] Metacomments;
public CompileResult (Assembly assembly, Metacomment[] metacomments) {
Assembly = assembly;
Metacomments = metacomments;
}
}
[Serializable]
public class CompilerNotFoundException : Exception
{
public CompilerNotFoundException()
{
}
public CompilerNotFoundException(string message) : base(message)
{
}
public CompilerNotFoundException(string message, Exception innerException) : base(message, innerException)
{
}
protected CompilerNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}
}
| mit |
spike01/planner | app/presenters/member_presenter.rb | 382 | class MemberPresenter < BasePresenter
def organiser?
has_role? :organiser, :any
end
def event_organiser?(event)
has_role?(:organiser, event) || has_role?(:organiser, event.chapter) || has_role?(:admin)
end
def newbie?
!workshop_invitations.attended.exists?
end
def attending?(event)
event.invitations.accepted.where(member: model).exists?
end
end
| mit |
LegionXI/pydarkstar | pydarkstar/logutils.py | 3579 | import contextlib
import warnings
import logging
import logging.handlers
lfmt = '[%(asctime)s][%(process)5d][%(levelname)-5s]: %(message)s'
dfmt = "%Y-%m-%d %H:%M:%S"
logging.basicConfig(level=logging.ERROR, format=lfmt, datefmt=dfmt)
logging.addLevelName(logging.CRITICAL, 'FATAL')
logging.addLevelName(logging.WARNING , 'WARN' )
def setLevel(level):
logging.getLogger().setLevel(level)
def setDebug():
setLevel(logging.DEBUG)
def setError():
setLevel(logging.ERROR)
def setInfo():
setLevel(logging.INFO)
def custom_warning_format(message, category, filename, lineno, *args, **kwargs):
return '%s:%s\n%s: %s' % (filename, lineno, category.__name__, message)
@contextlib.contextmanager
def capture(capture_warnings=True, fail=False):
"""
Log exceptions and warnings.
"""
try:
if capture_warnings:
default_warning_format = warnings.formatwarning
warnings.formatwarning = custom_warning_format
logging.captureWarnings(True)
try:
yield
except Exception as e:
logging.exception('caught unhandled excetion')
if fail:
if not isinstance(e, Warning):
raise RuntimeError('application failure')
finally:
if capture_warnings:
warnings.formatwarning = default_warning_format
logging.captureWarnings(False)
class LoggingObject(object):
"""
Inherit from this to get a bunch of logging functions as class methods.
"""
def __init__(self):
self._init_notify()
def _init_notify(self):
self.debug('init')
def debug(self, msg, *args, **kwargs):
logging.debug(self._preprocess(msg), *args, **kwargs)
def error(self, msg, *args, **kwargs):
logging.error(self._preprocess(msg), *args, **kwargs)
def fatal(self, msg, *args, **kwargs):
logging.fatal(self._preprocess(msg), *args, **kwargs)
exit(-1)
def info(self, msg, *args, **kwargs):
logging.info(self._preprocess(msg), *args, **kwargs)
def exception(self, msg, *args, **kwargs):
logging.exception(self._preprocess(msg), *args, **kwargs)
def log(self, level, msg, *args, **kwargs):
logging.log(level, self._preprocess(msg), *args, **kwargs)
def _preprocess(self, msg):
return '{}: {}'.format(repr(self), msg)
@contextlib.contextmanager
def capture(self, **kwargs):
try:
with capture(**kwargs):
yield
finally:
pass
def addRotatingFileHandler(level=logging.DEBUG, fname='app.log',
logger=None, fmt=lfmt, **kwargs):
"""
Create rotating file handler and add it to logging.
:param level: logging level
:param fname: name of file
:param name: logger instance
:param fmt: format
"""
_kwargs = dict(maxBytes=(1048576*5), backupCount=5)
_kwargs.update(**kwargs)
handler = logging.handlers.RotatingFileHandler(fname, **kwargs)
handler.setLevel(level)
formatter = logging.Formatter(fmt)
handler.setFormatter(formatter)
if isinstance(logger, str):
logger = logging.getLogger(logger)
elif logger is None:
logger = logging.getLogger()
logger.addHandler(handler)
return logger
def basicConfig(verbose=False, silent=False, fname=None):
"""
Setup logging.
"""
setInfo()
if verbose:
setDebug()
if silent:
setError()
if fname:
addRotatingFileHandler(fname=fname)
if __name__ == '__main__':
pass
| mit |
madepeople/magento | app/code/community/Adyen/Payment/Model/Adyen/Oneclick.php | 4517 | <?php
/**
* Adyen Payment Module
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @category Adyen
* @package Adyen_Payment
* @copyright Copyright (c) 2011 Adyen (http://www.adyen.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
/**
* @category Payment Gateway
* @package Adyen_Payment
* @author Adyen
* @property Adyen B.V
* @copyright Copyright (c) 2014 Adyen BV (http://www.adyen.com)
*/
class Adyen_Payment_Model_Adyen_Oneclick extends Adyen_Payment_Model_Adyen_Cc {
protected $_code = 'adyen_oneclick';
protected $_formBlockType = 'adyen/form_oneclick';
protected $_infoBlockType = 'adyen/info_oneclick';
protected $_paymentMethod = 'oneclick';
protected $_canUseInternal = true; // not possible through backoffice interface
/**
* Ability to set the code, for dynamic payment methods.
* @param $code
* @return $this
*/
public function setCode($code)
{
$this->_code = $code;
return $this;
}
public function assignData($data) {
if (!($data instanceof Varien_Object)) {
$data = new Varien_Object($data);
}
$info = $this->getInfoInstance();
// get storeId
if(Mage::app()->getStore()->isAdmin()) {
$store = Mage::getSingleton('adminhtml/session_quote')->getStore();
} else {
$store = Mage::app()->getStore();
}
$storeId = $store->getId();
// Get recurringDetailReference from config
$recurringDetailReference = Mage::getStoreConfig("payment/".$this->getCode() . "/recurringDetailReference", $storeId);
$info->setAdditionalInformation('recurring_detail_reference', $recurringDetailReference);
$ccType = Mage::getStoreConfig("payment/".$this->getCode() . "/variant", $storeId);
$info->setCcType($ccType);
if ($this->isCseEnabled()) {
$info->setAdditionalInformation('encrypted_data', $data->getEncryptedData());
} else {
// check if expiry month and year is changed
$expiryMonth = $data->getOneclickExpMonth();
$expiryYear = $data->getOneclickExpYear();
$cvcCode = $data->getOneclickCid();
$cardHolderName = Mage::getStoreConfig("payment/".$this->getCode() . "/card_holderName", $storeId);
$last4Digits = Mage::getStoreConfig("payment/".$this->getCode() . "/card_number", $storeId);
$cardHolderName = Mage::getStoreConfig("payment/".$this->getCode() . "/card_holderName", $storeId);
// just set default data for info block only
$info->setCcType($ccType)
->setCcOwner($cardHolderName)
->setCcLast4($last4Digits)
->setCcExpMonth($expiryMonth)
->setCcExpYear($expiryYear)
->setCcCid($cvcCode);
}
if(Mage::helper('adyen/installments')->isInstallmentsEnabled()) {
$info->setAdditionalInformation('number_of_installments', $data->getInstallment());
} else {
$info->setAdditionalInformation('number_of_installments', "");
}
// recalculate the totals so that extra fee is defined
$quote = (Mage::getModel('checkout/type_onepage') !== false)? Mage::getModel('checkout/type_onepage')->getQuote(): Mage::getModel('checkout/session')->getQuote();
$quote->setTotalsCollectedFlag(false);
$quote->collectTotals();
return $this;
}
public function getlistRecurringDetails()
{
$quote = (Mage::getModel('checkout/type_onepage') !== false)? Mage::getModel('checkout/type_onepage')->getQuote(): Mage::getModel('checkout/session')->getQuote();
$customerId = $quote->getCustomerId();
return $this->_processRecurringRequest($customerId);
}
public function isNotRecurring() {
$recurring_type = $this->_getConfigData('recurringtypes', 'adyen_abstract');
if($recurring_type == "RECURRING")
return false;
return true;
}
} | mit |
scotthue/unicycling-registration | app/controllers/compete/age_group_entries_controller.rb | 340 | class Compete::AgeGroupEntriesController < ApplicationController
before_action :authenticate_user!
include SortableObject
before_action :authenticate_ability
private
def authenticate_ability
authorize @config, :setup_competition?
end
def sortable_object
@sortable_object = AgeGroupEntry.find(params[:id])
end
end
| mit |
syniosis76/canoepoloscoreboard | Utilities/OnUserMessageDelegate.cs | 293 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
namespace Utilities
{
public delegate MessageBoxResult OnUserMessageDelegate(MessageBoxImage image, string message, MessageBoxButton buttons, MessageBoxResult defaultResult);
}
| mit |
tamag901/LeapCoin | src/qt/optionsdialog.cpp | 9334 | // Copyright (c) 2011-2013 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 "optionsdialog.h"
#include "ui_optionsdialog.h"
#include "bitcoinunits.h"
#include "monitoreddatamapper.h"
#include "netbase.h"
#include "optionsmodel.h"
#include <QDir>
#include <QIntValidator>
#include <QLocale>
#include <QMessageBox>
OptionsDialog::OptionsDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::OptionsDialog),
model(0),
mapper(0),
fRestartWarningDisplayed_Proxy(false),
fRestartWarningDisplayed_Lang(false),
fProxyIpValid(true)
{
ui->setupUi(this);
/* Network elements init */
#ifndef USE_UPNP
ui->mapPortUpnp->setEnabled(false);
#endif
ui->proxyIp->setEnabled(false);
ui->proxyPort->setEnabled(false);
ui->proxyPort->setValidator(new QIntValidator(1, 65535, this));
ui->socksVersion->setEnabled(false);
ui->socksVersion->addItem("5", 5);
ui->socksVersion->addItem("4", 4);
ui->socksVersion->setCurrentIndex(0);
connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyIp, SLOT(setEnabled(bool)));
connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyPort, SLOT(setEnabled(bool)));
connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->socksVersion, SLOT(setEnabled(bool)));
connect(ui->connectSocks, SIGNAL(clicked(bool)), this, SLOT(showRestartWarning_Proxy()));
ui->proxyIp->installEventFilter(this);
/* Window elements init */
#ifdef Q_OS_MAC
/* remove Window tab on Mac */
ui->tabWidget->removeTab(ui->tabWidget->indexOf(ui->tabWindow));
#endif
/* Display elements init */
QDir translations(":translations");
ui->lang->addItem(QString("(") + tr("default") + QString(")"), QVariant(""));
foreach(const QString &langStr, translations.entryList())
{
QLocale locale(langStr);
/** check if the locale name consists of 2 parts (language_country) */
if(langStr.contains("_"))
{
#if QT_VERSION >= 0x040800
/** display language strings as "native language - native country (locale name)", e.g. "Deutsch - Deutschland (de)" */
ui->lang->addItem(locale.nativeLanguageName() + QString(" - ") + locale.nativeCountryName() + QString(" (") + langStr + QString(")"), QVariant(langStr));
#else
/** display language strings as "language - country (locale name)", e.g. "German - Germany (de)" */
ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" - ") + QLocale::countryToString(locale.country()) + QString(" (") + langStr + QString(")"), QVariant(langStr));
#endif
}
else
{
#if QT_VERSION >= 0x040800
/** display language strings as "native language (locale name)", e.g. "Deutsch (de)" */
ui->lang->addItem(locale.nativeLanguageName() + QString(" (") + langStr + QString(")"), QVariant(langStr));
#else
/** display language strings as "language (locale name)", e.g. "German (de)" */
ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" (") + langStr + QString(")"), QVariant(langStr));
#endif
}
}
ui->unit->setModel(new BitcoinUnits(this));
/* Widget-to-option mapper */
mapper = new MonitoredDataMapper(this);
mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit);
mapper->setOrientation(Qt::Vertical);
/* enable apply button when data modified */
connect(mapper, SIGNAL(viewModified()), this, SLOT(enableApplyButton()));
/* disable apply button when new data loaded */
connect(mapper, SIGNAL(currentIndexChanged(int)), this, SLOT(disableApplyButton()));
/* setup/change UI elements when proxy IP is invalid/valid */
connect(this, SIGNAL(proxyIpValid(QValidatedLineEdit *, bool)), this, SLOT(handleProxyIpValid(QValidatedLineEdit *, bool)));
}
OptionsDialog::~OptionsDialog()
{
delete ui;
}
void OptionsDialog::setModel(OptionsModel *model)
{
this->model = model;
if(model)
{
connect(model, SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
mapper->setModel(model);
setMapper();
mapper->toFirst();
}
/* update the display unit, to not use the default ("BTC") */
updateDisplayUnit();
/* warn only when language selection changes by user action (placed here so init via mapper doesn't trigger this) */
connect(ui->lang, SIGNAL(valueChanged()), this, SLOT(showRestartWarning_Lang()));
/* disable apply button after settings are loaded as there is nothing to save */
disableApplyButton();
}
void OptionsDialog::setMapper()
{
/* Main */
mapper->addMapping(ui->bitcoinAtStartup, OptionsModel::StartAtStartup);
/* Wallet */
mapper->addMapping(ui->transactionFee, OptionsModel::Fee);
mapper->addMapping(ui->spendZeroConfChange, OptionsModel::SpendZeroConfChange);
/* Network */
mapper->addMapping(ui->mapPortUpnp, OptionsModel::MapPortUPnP);
mapper->addMapping(ui->connectSocks, OptionsModel::ProxyUse);
mapper->addMapping(ui->proxyIp, OptionsModel::ProxyIP);
mapper->addMapping(ui->proxyPort, OptionsModel::ProxyPort);
mapper->addMapping(ui->socksVersion, OptionsModel::ProxySocksVersion);
/* Window */
#ifndef Q_OS_MAC
mapper->addMapping(ui->minimizeToTray, OptionsModel::MinimizeToTray);
mapper->addMapping(ui->minimizeOnClose, OptionsModel::MinimizeOnClose);
#endif
/* Display */
mapper->addMapping(ui->lang, OptionsModel::Language);
mapper->addMapping(ui->unit, OptionsModel::DisplayUnit);
mapper->addMapping(ui->displayAddresses, OptionsModel::DisplayAddresses);
mapper->addMapping(ui->coinControlFeatures, OptionsModel::CoinControlFeatures);
}
void OptionsDialog::enableApplyButton()
{
ui->applyButton->setEnabled(true);
}
void OptionsDialog::disableApplyButton()
{
ui->applyButton->setEnabled(false);
}
void OptionsDialog::enableSaveButtons()
{
/* prevent enabling of the save buttons when data modified, if there is an invalid proxy address present */
if(fProxyIpValid)
setSaveButtonState(true);
}
void OptionsDialog::disableSaveButtons()
{
setSaveButtonState(false);
}
void OptionsDialog::setSaveButtonState(bool fState)
{
ui->applyButton->setEnabled(fState);
ui->okButton->setEnabled(fState);
}
void OptionsDialog::on_resetButton_clicked()
{
if(model)
{
// confirmation dialog
QMessageBox::StandardButton btnRetVal = QMessageBox::question(this, tr("Confirm options reset"),
tr("Some settings may require a client restart to take effect.") + "<br><br>" + tr("Do you want to proceed?"),
QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel);
if(btnRetVal == QMessageBox::Cancel)
return;
disableApplyButton();
/* disable restart warning messages display */
fRestartWarningDisplayed_Lang = fRestartWarningDisplayed_Proxy = true;
/* reset all options and save the default values (QSettings) */
model->Reset();
mapper->toFirst();
mapper->submit();
/* re-enable restart warning messages display */
fRestartWarningDisplayed_Lang = fRestartWarningDisplayed_Proxy = false;
}
}
void OptionsDialog::on_okButton_clicked()
{
mapper->submit();
accept();
}
void OptionsDialog::on_cancelButton_clicked()
{
reject();
}
void OptionsDialog::on_applyButton_clicked()
{
mapper->submit();
disableApplyButton();
}
void OptionsDialog::showRestartWarning_Proxy()
{
if(!fRestartWarningDisplayed_Proxy)
{
QMessageBox::warning(this, tr("Warning"), tr("This setting will take effect after restarting Leapcoin."), QMessageBox::Ok);
fRestartWarningDisplayed_Proxy = true;
}
}
void OptionsDialog::showRestartWarning_Lang()
{
if(!fRestartWarningDisplayed_Lang)
{
QMessageBox::warning(this, tr("Warning"), tr("This setting will take effect after restarting Leapcoin."), QMessageBox::Ok);
fRestartWarningDisplayed_Lang = true;
}
}
void OptionsDialog::updateDisplayUnit()
{
if(model)
{
/* Update transactionFee with the current unit */
ui->transactionFee->setDisplayUnit(model->getDisplayUnit());
}
}
void OptionsDialog::handleProxyIpValid(QValidatedLineEdit *object, bool fState)
{
// this is used in a check before re-enabling the save buttons
fProxyIpValid = fState;
if(fProxyIpValid)
{
enableSaveButtons();
ui->statusLabel->clear();
}
else
{
disableSaveButtons();
object->setValid(fProxyIpValid);
ui->statusLabel->setStyleSheet("QLabel { color: red; }");
ui->statusLabel->setText(tr("The supplied proxy address is invalid."));
}
}
bool OptionsDialog::eventFilter(QObject *object, QEvent *event)
{
if(event->type() == QEvent::FocusOut)
{
if(object == ui->proxyIp)
{
CService addr;
/* Check proxyIp for a valid IPv4/IPv6 address and emit the proxyIpValid signal */
emit proxyIpValid(ui->proxyIp, LookupNumeric(ui->proxyIp->text().toStdString().c_str(), addr));
}
}
return QDialog::eventFilter(object, event);
}
| mit |
icqparty/linebuild | module/Application/src/Application/Service/ProjectService.php | 148 | <?php
/**
* Created by PhpStorm.
* User: icqparty
* Date: 12.10.14
* Time: 9:15
*/
namespace Application\Service;
class ProjectService {
} | mit |
bpander/motherboard-legacy | src/config.js | 136 | require.config({
baseUrl: 'src',
paths: {
EventEmitter: '../bower_components/EventEmitter/dist/EventEmitter'
}
});
| mit |
simo-tuomisto/portfolio | Computational Nanoscience 2013 - Final project/Code/plot_data.py | 7122 | import numpy as np
import matplotlib.pyplot as mpl
from matplotlib.ticker import NullFormatter
import sys
from glob import glob
import re
import os
if __name__=="__main__":
# Plot these ranges
plotranges = {
5.0 : [0.009 , 0.011],
10.0: [0.007 , 0.011],
15.0: [0.005 , 0.010],
20.0: [0.005 , 0.010],
25.0: [0.005 , 0.010],
30.0: [0.005 , 0.010]
}
colormap_f={
0.005 : 'b',
0.006 : 'c',
0.007 : 'g',
0.008 : 'y',
0.009 : 'r',
0.010 : 'm'
}
colormap_r={
5 : 'b',
10 : 'c',
15 : 'g',
20 : 'y',
25 : 'r',
30 : 'm'
}
strainreg = re.compile('.*-r_(?P<r>.+)-f_(?P<f>.+)-t_(?P<t>.+)_strain.npy')
strainfiles = glob('*_strain.npy')
avglen = 3
rdict = dict()
for strainfile in strainfiles:
match = strainreg.match(strainfile)
if match != None:
stressfile = strainfile[:-10] + 'stress.npy'
if os.path.exists(stressfile):
groups = match.groupdict()
r = float(groups['r'])
if r not in rdict:
rdict[r] = []
f = float(groups['f'])
t = int(groups['t'])
straindata = np.load(strainfile)
stressdata = np.load(stressfile)
rdict[r].append([f,t,straindata,stressdata])
measured_data = []
for r,dataarrays in rdict.items():
if r not in plotranges:
continue
lowlimit = plotranges[r][0]
highlimit = plotranges[r][1]
fig1 = mpl.figure(facecolor='white',figsize=(12,9))
fig2 = mpl.figure(facecolor='white',figsize=(12,9))
fig3 = mpl.figure(facecolor='white',figsize=(12,9))
for dataarray in dataarrays:
f,t,straindata,stressdata = dataarray
stressdata = stressdata/(np.pi*np.power(r,2))
if ((f<lowlimit) or (f>highlimit)):
continue
avgstress = np.zeros_like(stressdata)
for i in np.arange(avglen,len(stressdata)-avglen-1):
avgstress[i] = np.average(stressdata[i-avglen:i+avglen+1])
#mpl.loglog(straindata, stressdata)
stressmax = np.amax(stressdata)
strain = (straindata - straindata[0])/straindata[0]
strainmax = np.amax(strain)
strainrate = strainmax/len(strain)
measured_data.append([r,f,stressmax,strainmax,strainrate])
mpl.figure(fig1.number)
mpl.plot(strain[avglen:-avglen-1], avgstress[avglen:-avglen-1], label='f=%f' % f, color=colormap_f.get(f,'k'))
mpl.figure(fig2.number)
mpl.plot(0.5*np.arange(0, len(strain)),strain, label='f=%f' % f, color=colormap_f.get(f,'k'))
if (f == 0.008):
mpl.figure(fig3.number)
t = 0.5*np.arange(avglen, len(avgstress)+avglen)
mpl.plot(t[avgstress>0],avgstress[avgstress>0],label='f=%f' % f, color=colormap_f.get(f,'k'))
mpl.figure(fig1.number)
mpl.title('r=%d' % int(r))
mpl.xlabel('strain')
mpl.ylabel('stress')
mpl.gca().yaxis.set_major_formatter(NullFormatter())
mpl.legend(loc=1)
mpl.savefig('strain_vs_stress-r_%d.pdf' % int(r))
mpl.figure(fig2.number)
mpl.title('r=%d' % int(r))
mpl.xlabel('time')
mpl.ylabel('strain')
#mpl.gca().yaxis.set_major_formatter(NullFormatter())
mpl.legend(loc=3)
mpl.savefig('time_vs_strain-r_%d.pdf' % int(r))
mpl.figure(fig3.number)
mpl.title('r=%d' % int(r))
mpl.xlabel('time')
mpl.ylabel('strain')
mpl.gca().yaxis.set_major_formatter(NullFormatter())
#mpl.legend(loc=3)
mpl.savefig('time_vs_stress-r_%d.pdf' % int(r))
#break
measured_data = np.asfarray(measured_data)
mpl.figure(facecolor='white',figsize=(12,9))
for f in np.unique(measured_data[:,1]):
r = measured_data[measured_data[:,1] == f,0]
stressmax = measured_data[measured_data[:,1] == f,2]
if (f==0.009):
fit = np.polyfit(np.log(r), np.log(stressmax), deg=1)
fitr = r
mpl.plot(r,stressmax,'^', color=colormap_f.get(f,'k'),label='f=%f' % f)
mpl.plot(r,stressmax,linestyle='--', color=colormap_f.get(f,'k'))
mpl.plot(fitr,np.exp(np.polyval(fit,np.log(fitr))), label='Fit with exponent %f' % fit[0])
mpl.xlabel('r')
mpl.ylabel('Maximum stress')
mpl.legend(loc=1)
#mpl.gca().yaxis.set_major_formatter(NullFormatter())
mpl.savefig('r_vs_stressmax.pdf')
mpl.figure(facecolor='white',figsize=(12,9))
for f in np.unique(measured_data[:,1]):
r = measured_data[measured_data[:,1] == f,0]
stressmax = measured_data[measured_data[:,1] == f,2]
mpl.loglog(r,stressmax,'^', color=colormap_f.get(f,'k'),label='f=%f' % f)
mpl.loglog(r,stressmax,linestyle='--', color=colormap_f.get(f,'k'))
mpl.xlabel('r')
mpl.ylabel('Maximum stress')
mpl.legend(loc=4)
mpl.gca().yaxis.set_major_formatter(NullFormatter())
mpl.savefig('r_vs_stressmax_loglog.pdf')
mpl.figure(facecolor='white',figsize=(12,9))
for r in np.unique(measured_data[:,0]):
f = measured_data[measured_data[:,0] == r,1]
stressmax = measured_data[measured_data[:,0] == r,2]
mpl.plot(f,stressmax,'^', color=colormap_r.get(r,'k'),label='r=%d' % r)
mpl.plot(f,stressmax,linestyle='--', color=colormap_r.get(r,'k'))
mpl.xlabel('f')
mpl.ylabel('Maximum stress')
mpl.gca().yaxis.set_major_formatter(NullFormatter())
mpl.legend(loc=4)
mpl.savefig('f_vs_stressmax.pdf')
mpl.figure(facecolor='white',figsize=(12,9))
for f in np.unique(measured_data[:,1]):
r = measured_data[measured_data[:,1] == f,0]
strainmax = measured_data[measured_data[:,1] == f,3]
mpl.plot(r,strainmax,'^', color=colormap_f.get(f,'k'),label='f=%f' % f)
mpl.plot(r,strainmax,linestyle='--', color=colormap_f.get(f,'k'))
mpl.xlabel('r')
mpl.ylabel('Strain at the time of failure')
mpl.legend(loc=0)
#mpl.gca().yaxis.set_major_formatter(NullFormatter())
mpl.savefig('r_vs_strainmax.pdf')
mpl.figure(facecolor='white',figsize=(12,9))
for r in np.unique(measured_data[:,0]):
f = measured_data[measured_data[:,0] == r,1]
strainmax = measured_data[measured_data[:,0] == r,3]
mpl.plot(f,strainmax,'^', color=colormap_r.get(r,'k'),label='r=%d' % r)
mpl.plot(f,strainmax,linestyle='--', color=colormap_r.get(r,'k'))
mpl.xlabel('f')
mpl.ylabel('Strain at the time of failure')
#mpl.gca().yaxis.set_major_formatter(NullFormatter())
mpl.legend(loc=0)
mpl.savefig('f_vs_strainmax.pdf')
mpl.figure(facecolor='white',figsize=(12,9))
for f in np.unique(measured_data[:,1]):
r = measured_data[measured_data[:,1] == f,0]
strainrate = measured_data[measured_data[:,1] == f,4]
if (f==0.010):
fit = np.polyfit(np.log(r), np.log(strainrate), deg=1)
fitr = r
mpl.plot(r,strainrate,'^', color=colormap_f.get(f,'k'),label='f=%f' % f)
mpl.plot(r,strainrate,linestyle='--', color=colormap_f.get(f,'k'))
mpl.plot(fitr,np.exp(np.polyval(fit,np.log(fitr))), label='Fit with exponent %f' % fit[0])
mpl.xlabel('r')
mpl.ylabel('Strain rate')
mpl.legend(loc=0)
mpl.gca().yaxis.set_major_formatter(NullFormatter())
mpl.savefig('r_vs_strainrate.pdf')
mpl.figure(facecolor='white',figsize=(12,9))
for r in np.unique(measured_data[:,0]):
f = measured_data[measured_data[:,0] == r,1]
strainrate = measured_data[measured_data[:,0] == r,4]
mpl.plot(f,strainrate,'^', color=colormap_r.get(r,'k'),label='r=%d' % r)
mpl.plot(f,strainrate,linestyle='--', color=colormap_r.get(r,'k'))
mpl.xlabel('f')
mpl.ylabel('Strain rate')
mpl.gca().yaxis.set_major_formatter(NullFormatter())
mpl.legend(loc=3)
mpl.savefig('f_vs_strainrate.pdf')
| mit |
devnewton/underthief | app/ui/MenuCursor.ts | 3799 | /// <reference path="../../typings/phaser.d.ts"/>
interface Togglable {
toggle?: Function;
}
export class MenuCursor extends Phaser.Text {
private buttons: Phaser.Group;
private currentButton = 0;
waitUntil: number = -1;
keyboardCursor = true;
gamepadCursor = true;
constructor(game: Phaser.Game, buttons: Phaser.Group) {
super(game, 0, 0, '👉', { font: "64px monospace", fontWeight: 'bold', fill: 'white' });
this.buttons = buttons;
this.visible = false;
}
firstPadConnected(): Phaser.SinglePad {
const gamepad = this.game.input.gamepad;
if (gamepad.pad1.connected) {
return gamepad.pad1;
} else if (gamepad.pad2.connected) {
return gamepad.pad2;
} else if (gamepad.pad3.connected) {
return gamepad.pad3;
} else if (gamepad.pad4.connected) {
return gamepad.pad4;
} else {
return null;
}
}
update() {
super.update();
if (this.parent.visible && this.game.time.time > this.waitUntil && (this.processPad() || this.processKeyboard())) {
this.waitUntil = this.game.time.time + 230;
}
}
processKeyboard(): boolean {
if (this.keyboardCursor) {
if (this.game.input.keyboard.isDown(Phaser.Keyboard.UP)) {
this.moveToButton(-1);
return true;
}
if (this.game.input.keyboard.isDown(Phaser.Keyboard.DOWN)) {
this.moveToButton(1);
return true;
}
if (this.game.input.keyboard.isDown(Phaser.Keyboard.ENTER)) {
this.activateButton();
return true;
}
}
return false;
}
processPad(): boolean {
if (this.gamepadCursor) {
const pad = this.firstPadConnected();
if (pad) {
for (let b = 0; b < 4; ++b) {
let button = pad.getButton(b);
if (button && button.isDown) {
this.activateButton();
return true;
}
}
for (let a = 0; a < 2; ++a) {
const axis = pad.axis(a);
if (axis > pad.deadZone) {
this.moveToButton(1);
return true;
} else if (axis < -pad.deadZone) {
this.moveToButton(-1);
return true;
}
}
}
}
return false;
}
moveToButton(direction: number) {
if (this.parent.visible && this.buttons.children.length > 0) {
if (!this.visible) {
this.visible = true;
} else {
this.currentButton += direction;
}
if (this.currentButton >= this.buttons.length) {
this.currentButton = 0;
}
if (this.currentButton < 0) {
this.currentButton = this.buttons.length - 1;
}
const button = this.buttons.children[this.currentButton];
this.x = button.x;
this.y = button.y;
}
}
activateButton() {
if (this.parent.visible) {
if (!this.visible) {
this.moveToButton(0);
} else if (this.buttons.children.length > 0) {
const button = <Togglable>this.buttons.children[this.currentButton];
if (button.toggle) {
button.toggle();
}
}
}
}
} | mit |
neo7530/wabcoin | src/qt/locale/bitcoin_lt.ts | 108298 | <?xml version="1.0" ?><!DOCTYPE TS><TS language="lt" version="2.0">
<defaultcodec>UTF-8</defaultcodec>
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About Wabcoin</source>
<translation>Apie Wabcoin</translation>
</message>
<message>
<location line="+39"/>
<source><b>Wabcoin</b> version</source>
<translation><b>Wabcoin</b> versija</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 ([email protected]) and UPnP software written by Thomas Bernard.</source>
<translation>Tai eksperimentinė programa.
Platinama pagal MIT/X11 licenciją, kurią rasite faile COPYING arba http://www.opensource.org/licenses/mit-license.php.
Šiame produkte yra OpenSSL projekto kuriamas OpenSSL Toolkit (http://www.openssl.org/), Eric Young parašyta kriptografinė programinė įranga bei Thomas Bernard sukurta UPnP programinė įranga.</translation>
</message>
<message>
<location filename="../aboutdialog.cpp" line="+14"/>
<source>Copyright</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The Wabcoin developers</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>Adresų knygelė</translation>
</message>
<message>
<location line="+19"/>
<source>Double-click to edit address or label</source>
<translation>Spragtelėkite, kad pakeistumėte adresą arba žymę</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>Sukurti naują adresą</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Kopijuoti esamą adresą į mainų atmintį</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation>&Naujas adresas</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+63"/>
<source>These are your Wabcoin 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>Tai yra jūsų Wabcoin adresai mokėjimų gavimui. Galite duoti skirtingus adresus atskiriems siuntėjams, kad galėtumėte sekti, kas jums moka.</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>&Copy Address</source>
<translation>&Kopijuoti adresą</translation>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation>Rodyti &QR kodą</translation>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a Wabcoin address</source>
<translation>Pasirašykite žinutę, kad įrodytume, jog esate Wabcoin adreso savininkas</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>Registruoti praneši&mą</translation>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Export the data in the current tab to a file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-44"/>
<source>Verify a message to ensure it was signed with a specified Wabcoin address</source>
<translation>Patikrinkite žinutę, jog įsitikintumėte, kad ją pasirašė nurodytas Wabcoin adresas</translation>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation>&Tikrinti žinutę</translation>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>&Trinti</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="-5"/>
<source>These are your Wabcoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Copy &Label</source>
<translation>Kopijuoti ž&ymę</translation>
</message>
<message>
<location line="+1"/>
<source>&Edit</source>
<translation>&Keisti</translation>
</message>
<message>
<location line="+1"/>
<source>Send &Coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+260"/>
<source>Export Address Book Data</source>
<translation>Eksportuoti adresų knygelės duomenis</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Kableliais išskirtas failas (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>Eksportavimo klaida</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Nepavyko įrašyti į failą %1.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>Žymė</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Adresas</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(nėra žymės)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation>Slaptafrazės dialogas</translation>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>Įvesti slaptafrazę</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>Nauja slaptafrazė</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>Pakartokite naują slaptafrazę</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>Įveskite naują piniginės slaptafrazę.<br/>Prašome naudoti slaptafrazę iš <b> 10 ar daugiau atsitiktinių simbolių</b> arba <b>aštuonių ar daugiau žodžių</b>.</translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>Užšifruoti piniginę</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Ši operacija reikalauja jūsų piniginės slaptafrazės jai atrakinti.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>Atrakinti piniginę</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Ši operacija reikalauja jūsų piniginės slaptafrazės jai iššifruoti.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>Iššifruoti piniginę</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>Pakeisti slaptafrazę</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Įveskite seną ir naują piniginės slaptafrazes.</translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>Patvirtinkite piniginės užšifravimą</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR WABCOINS</b>!</source>
<translation>Dėmesio: jei užšifruosite savo piniginę ir pamesite slaptafrazę, jūs<b>PRARASITE VISUS SAVO WABCOINUS</b>! </translation>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>Ar tikrai norite šifruoti savo piniginę?</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 type="unfinished"/>
</message>
<message>
<location line="+100"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation>Įspėjimas: įjungtas Caps Lock klavišas!</translation>
</message>
<message>
<location line="-130"/>
<location line="+58"/>
<source>Wallet encrypted</source>
<translation>Piniginė užšifruota</translation>
</message>
<message>
<location line="-56"/>
<source>Wabcoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your wabcoins from being stolen by malware infecting your computer.</source>
<translation>Wabcoin dabar užsidarys šifravimo proceso pabaigai. Atminkite, kad piniginės šifravimas negali pilnai apsaugoti wabcoinų vagysčių kai tinkle esančios kenkėjiškos programos patenka į jūsų kompiuterį.</translation>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+42"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>Nepavyko užšifruoti piniginę</translation>
</message>
<message>
<location line="-54"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Dėl vidinės klaidos nepavyko užšifruoti piniginę.Piniginė neužšifruota.</translation>
</message>
<message>
<location line="+7"/>
<location line="+48"/>
<source>The supplied passphrases do not match.</source>
<translation>Įvestos slaptafrazės nesutampa.</translation>
</message>
<message>
<location line="-37"/>
<source>Wallet unlock failed</source>
<translation>Nepavyko atrakinti piniginę</translation>
</message>
<message>
<location line="+1"/>
<location line="+11"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>Neteisingai įvestas slaptažodis piniginės iššifravimui.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>Nepavyko iššifruoti piniginės</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>Piniginės slaptažodis sėkmingai pakeistas.</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+233"/>
<source>Sign &message...</source>
<translation>Pasirašyti ži&nutę...</translation>
</message>
<message>
<location line="+280"/>
<source>Synchronizing with network...</source>
<translation>Sinchronizavimas su tinklu ...</translation>
</message>
<message>
<location line="-349"/>
<source>&Overview</source>
<translation>&Apžvalga</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation>Rodyti piniginės bendrą apžvalgą</translation>
</message>
<message>
<location line="+20"/>
<source>&Transactions</source>
<translation>&Sandoriai</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>Apžvelgti sandorių istoriją</translation>
</message>
<message>
<location line="+7"/>
<source>Edit the list of stored addresses and labels</source>
<translation>Redaguoti išsaugotus adresus bei žymes</translation>
</message>
<message>
<location line="-14"/>
<source>Show the list of addresses for receiving payments</source>
<translation>Parodyti adresų sąraša mokėjimams gauti</translation>
</message>
<message>
<location line="+31"/>
<source>E&xit</source>
<translation>&Išeiti</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>Išjungti programą</translation>
</message>
<message>
<location line="+4"/>
<source>Show information about Wabcoin</source>
<translation>Rodyti informaciją apie Wabcoin</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>Apie &Qt</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>Rodyti informaciją apie Qt</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>&Parinktys...</translation>
</message>
<message>
<location line="+6"/>
<source>&Encrypt Wallet...</source>
<translation>&Užšifruoti piniginę...</translation>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation>&Backup piniginę...</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>&Keisti slaptafrazę...</translation>
</message>
<message>
<location line="+285"/>
<source>Importing blocks from disk...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Reindexing blocks on disk...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-347"/>
<source>Send coins to a Wabcoin address</source>
<translation>Siųsti monetas Wabcoin adresui</translation>
</message>
<message>
<location line="+49"/>
<source>Modify configuration options for Wabcoin</source>
<translation>Keisti wabcoin konfigūracijos galimybes</translation>
</message>
<message>
<location line="+9"/>
<source>Backup wallet to another location</source>
<translation>Daryti piniginės atsarginę kopiją</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Pakeisti slaptafrazę naudojamą piniginės užšifravimui</translation>
</message>
<message>
<location line="+6"/>
<source>&Debug window</source>
<translation>&Derinimo langas</translation>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation>Atverti derinimo ir diagnostikos konsolę</translation>
</message>
<message>
<location line="-4"/>
<source>&Verify message...</source>
<translation>&Tikrinti žinutę...</translation>
</message>
<message>
<location line="-165"/>
<location line="+530"/>
<source>Wabcoin</source>
<translation>Wabcoin</translation>
</message>
<message>
<location line="-530"/>
<source>Wallet</source>
<translation>Piniginė</translation>
</message>
<message>
<location line="+101"/>
<source>&Send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Receive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>&Addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>&About Wabcoin</source>
<translation>&Apie Wabcoin</translation>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation>&Rodyti / Slėpti</translation>
</message>
<message>
<location line="+1"/>
<source>Show or hide the main Window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Encrypt the private keys that belong to your wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Sign messages with your Wabcoin addresses to prove you own them</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Verify messages to ensure they were signed with specified Wabcoin addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>&File</source>
<translation>&Failas</translation>
</message>
<message>
<location line="+7"/>
<source>&Settings</source>
<translation>&Nustatymai</translation>
</message>
<message>
<location line="+6"/>
<source>&Help</source>
<translation>&Pagalba</translation>
</message>
<message>
<location line="+9"/>
<source>Tabs toolbar</source>
<translation>Kortelių įrankinė</translation>
</message>
<message>
<location line="+17"/>
<location line="+10"/>
<source>[testnet]</source>
<translation>[testavimotinklas]</translation>
</message>
<message>
<location line="+47"/>
<source>Wabcoin client</source>
<translation>Wabcoin klientas</translation>
</message>
<message numerus="yes">
<location line="+141"/>
<source>%n active connection(s) to Wabcoin network</source>
<translation><numerusform>%n Wabcoin tinklo aktyvus ryšys</numerusform><numerusform>%n Wabcoin tinklo aktyvūs ryšiai</numerusform><numerusform>%n Wabcoin tinklo aktyvūs ryšiai</numerusform></translation>
</message>
<message>
<location line="+22"/>
<source>No block source available...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Processed %1 of %2 (estimated) blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Processed %1 blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+20"/>
<source>%n hour(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n week(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>%1 behind</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Last received block was generated %1 ago.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Transactions after this will not yet be visible.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>Error</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Information</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="-140"/>
<source>Up to date</source>
<translation>Atnaujinta</translation>
</message>
<message>
<location line="+31"/>
<source>Catching up...</source>
<translation>Vejamasi...</translation>
</message>
<message>
<location line="+113"/>
<source>Confirm transaction fee</source>
<translation>Patvirtinti sandorio mokestį</translation>
</message>
<message>
<location line="+8"/>
<source>Sent transaction</source>
<translation>Sandoris nusiųstas</translation>
</message>
<message>
<location line="+0"/>
<source>Incoming transaction</source>
<translation>Ateinantis sandoris</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Data: %1
Suma: %2
Tipas: %3
Adresas: %4</translation>
</message>
<message>
<location line="+33"/>
<location line="+23"/>
<source>URI handling</source>
<translation>URI apdorojimas</translation>
</message>
<message>
<location line="-23"/>
<location line="+23"/>
<source>URI can not be parsed! This can be caused by an invalid Wabcoin address or malformed URI parameters.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Piniginė <b>užšifruota</b> ir šiuo metu <b>atrakinta</b></translation>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Piniginė <b>užšifruota</b> ir šiuo metu <b>užrakinta</b></translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="+111"/>
<source>A fatal error occurred. Wabcoin can no longer continue safely and will quit.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+104"/>
<source>Network Alert</source>
<translation>Tinklo įspėjimas</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Keisti adresą</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>Ž&ymė</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation>Žymė yra susieta su šios adresų knygelęs turiniu</translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>&Adresas</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>Adresas yra susietas su šios adresų knygelęs turiniu. Tai gali būti keičiama tik siuntimo adresams.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+21"/>
<source>New receiving address</source>
<translation>Naujas gavimo adresas</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>Naujas siuntimo adresas</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>Keisti gavimo adresą</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>Keisti siuntimo adresą</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>Įvestas adresas „%1“ jau yra adresų knygelėje.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid Wabcoin address.</source>
<translation>Įvestas adresas „%1“ nėra galiojantis Wabcoin adresas.</translation>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>Nepavyko atrakinti piniginės.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>Naujo rakto generavimas nepavyko.</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+424"/>
<location line="+12"/>
<source>Wabcoin-Qt</source>
<translation>Wabcoin-Qt</translation>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation>versija</translation>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation>Naudojimas:</translation>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation>komandinės eilutės parametrai</translation>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation>Naudotoji sąsajos parametrai</translation>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation>Nustatyti kalbą, pavyzdžiui "lt_LT" (numatyta: sistemos kalba)</translation>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation>Paleisti sumažintą</translation>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>Parinktys</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>&Pagrindinės</translation>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation>&Mokėti sandorio mokestį</translation>
</message>
<message>
<location line="+31"/>
<source>Automatically start Wabcoin after logging in to the system.</source>
<translation>Automatiškai paleisti Bitkoin programą įjungus sistemą.</translation>
</message>
<message>
<location line="+3"/>
<source>&Start Wabcoin on system login</source>
<translation>&Paleisti Wabcoin programą su window sistemos paleidimu</translation>
</message>
<message>
<location line="+35"/>
<source>Reset all client options to default.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Reset Options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>&Network</source>
<translation>&Tinklas</translation>
</message>
<message>
<location line="+6"/>
<source>Automatically open the Wabcoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>Automatiškai atidaryti Wabcoin kliento prievadą maršrutizatoriuje. Tai veikia tik tada, kai jūsų maršrutizatorius palaiko UPnP ir ji įjungta.</translation>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation>Persiųsti prievadą naudojant &UPnP</translation>
</message>
<message>
<location line="+7"/>
<source>Connect to the Wabcoin network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation>Jungtis į Bitkoin tinklą per socks proxy (pvz. jungiantis per Tor)</translation>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation>&Jungtis per SOCKS tarpinį serverį:</translation>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation>Tarpinio serverio &IP:</translation>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation>Tarpinio serverio IP adresas (pvz. 127.0.0.1)</translation>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation>&Prievadas:</translation>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation>Tarpinio serverio preivadas (pvz, 9050)</translation>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation>SOCKS &versija:</translation>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation>Tarpinio serverio SOCKS versija (pvz., 5)</translation>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation>&Langas</translation>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation>Po programos lango sumažinimo rodyti tik programos ikoną.</translation>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&M sumažinti langą bet ne užduočių juostą</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>Uždarant langą neuždaryti programos. Kai ši parinktis įjungta, programa bus uždaryta tik pasirinkus meniu komandą Baigti.</translation>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation>&Sumažinti uždarant</translation>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation>&Rodymas</translation>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation>Naudotojo sąsajos &kalba:</translation>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting Wabcoin.</source>
<translation>Čia gali būti nustatyta naudotojo sąsajos kalba. Šis nustatymas įsigalios iš naujo paleidus Wabcoin.</translation>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation>&Vienetai, kuriais rodyti sumas:</translation>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>Rodomų ir siunčiamų monetų kiekio matavimo vienetai</translation>
</message>
<message>
<location line="+9"/>
<source>Whether to show Wabcoin addresses in the transaction list or not.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation>&Rodyti adresus sandorių sąraše</translation>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>&Gerai</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>&Atšaukti</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation>&Pritaikyti</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+53"/>
<source>default</source>
<translation>numatyta</translation>
</message>
<message>
<location line="+130"/>
<source>Confirm options reset</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Some settings may require a client restart to take effect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Do you want to proceed?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+42"/>
<location line="+9"/>
<source>Warning</source>
<translation>Įspėjimas</translation>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting Wabcoin.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation>Nurodytas tarpinio serverio adresas negalioja.</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>Forma</translation>
</message>
<message>
<location line="+50"/>
<location line="+166"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the Wabcoin network after a connection is established, but this process has not completed yet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-124"/>
<source>Balance:</source>
<translation>Balansas:</translation>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation>Nepatvirtinti:</translation>
</message>
<message>
<location line="-78"/>
<source>Wallet</source>
<translation>Piniginė</translation>
</message>
<message>
<location line="+107"/>
<source>Immature:</source>
<translation>Nepribrendę:</translation>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation><b>Naujausi sandoriai</b></translation>
</message>
<message>
<location line="-101"/>
<source>Your current balance</source>
<translation>Jūsų einamasis balansas</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>Iš viso sandorių, įskaitant tuos kurie dar turi būti patvirtinti, ir jie dar nėra įskaičiuotii į einamosios sąskaitos balansą</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="+116"/>
<location line="+1"/>
<source>out of sync</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+107"/>
<source>Cannot start wabcoin: click-to-pay handler</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation>QR kodo dialogas</translation>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation>Prašau išmokėti</translation>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation>Suma:</translation>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation>Žymė:</translation>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation>Žinutė:</translation>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation>Į&rašyti kaip...</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation>Klaida, koduojant URI į QR kodą.</translation>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation>Įvesta suma neteisinga, prašom patikrinti.</translation>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation>Įrašyti QR kodą</translation>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation>PNG paveikslėliai (*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation>Kliento pavadinimas</translation>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<location line="+23"/>
<location filename="../rpcconsole.cpp" line="+339"/>
<source>N/A</source>
<translation>nėra</translation>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation>Kliento versija</translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation>&Informacija</translation>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation>Naudojama OpenSSL versija</translation>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation>Paleidimo laikas</translation>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>Tinklas</translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation>Prisijungimų kiekis</translation>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation>Testnete</translation>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation>Blokų grandinė</translation>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation>Dabartinis blokų skaičius</translation>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation>Paskutinio bloko laikas</translation>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation>&Atverti</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation>Komandinės eilutės parametrai</translation>
</message>
<message>
<location line="+7"/>
<source>Show the Wabcoin-Qt help message to get a list with possible Wabcoin command-line options.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation>&Rodyti</translation>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation>&Konsolė</translation>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation>Kompiliavimo data</translation>
</message>
<message>
<location line="-104"/>
<source>Wabcoin - Debug window</source>
<translation>Wabcoin - Derinimo langas</translation>
</message>
<message>
<location line="+25"/>
<source>Wabcoin Core</source>
<translation>Wabcoin branduolys</translation>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation>Derinimo žurnalo failas</translation>
</message>
<message>
<location line="+7"/>
<source>Open the Wabcoin debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation>Išvalyti konsolę</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-30"/>
<source>Welcome to the Wabcoin RPC console.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation type="unfinished"/>
</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>Siųsti monetas</translation>
</message>
<message>
<location line="+50"/>
<source>Send to multiple recipients at once</source>
<translation>Siųsti keliems gavėjams vienu metu</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation>&A Pridėti gavėją</translation>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation>Pašalinti visus sandorio laukus</translation>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>Išvalyti &viską</translation>
</message>
<message>
<location line="+22"/>
<source>Balance:</source>
<translation>Balansas:</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>Patvirtinti siuntimo veiksmą</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation>&Siųsti</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-59"/>
<source><b>%1</b> to %2 (%3)</source>
<translation><b>%1</b> to %2 (%3)</translation>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>Patvirtinti monetų siuntimą</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation>Ar tikrai norite siųsti %1?</translation>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation> ir </translation>
</message>
<message>
<location line="+23"/>
<source>The recipient address is not valid, please recheck.</source>
<translation>Negaliojantis gavėjo adresas. Patikrinkite.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>Apmokėjimo suma turi būti didesnė nei 0.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation>Suma viršija jūsų balansą.</translation>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>Jei pridedame sandorio mokestį %1 bendra suma viršija jūsų balansą.</translation>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>Rastas adreso dublikatas.</translation>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed!</source>
<translation type="unfinished"/>
</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>Klaida: sandoris buvo atmestas.Tai gali įvykti, jei kai kurios monetos iš jūsų piniginėje jau buvo panaudotos, pvz. jei naudojote wallet.dat kopiją ir monetos buvo išleistos kopijoje, bet nepažymėtos kaip skirtos išleisti čia.</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation>Forma</translation>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation>Su&ma:</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>Mokėti &gavėjui:</translation>
</message>
<message>
<location line="+34"/>
<source>The address to send the payment to (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation type="unfinished"/>
</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>Įveskite žymę šiam adresui kad galėtumėte įtraukti ją į adresų knygelę</translation>
</message>
<message>
<location line="-78"/>
<source>&Label:</source>
<translation>Ž&ymė:</translation>
</message>
<message>
<location line="+28"/>
<source>Choose address from address book</source>
<translation>Pasirinkite adresą iš adresų knygelės</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>Įvesti adresą iš mainų atminties</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>Pašalinti šį gavėją</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a Wabcoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Įveskite bitkoinų adresą (pvz. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>&Sign Message</source>
<translation>&Pasirašyti žinutę</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 type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Įveskite bitkoinų adresą (pvz. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="+10"/>
<location line="+213"/>
<source>Choose an address from the address book</source>
<translation>Pasirinkite adresą iš adresų knygelės</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>Įvesti adresą iš mainų atminties</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>Įveskite pranešimą, kurį norite pasirašyti čia</translation>
</message>
<message>
<location line="+7"/>
<source>Signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Copy the current signature to the system clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this Wabcoin address</source>
<translation>Registruotis žinute įrodymuii, kad turite šį adresą</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Reset all sign message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>Išvalyti &viską</translation>
</message>
<message>
<location line="-87"/>
<source>&Verify Message</source>
<translation>&Patikrinti žinutę</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 type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Įveskite bitkoinų adresą (pvz. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified Wabcoin address</source>
<translation>Patikrinkite žinutę, jog įsitikintumėte, kad ją pasirašė nurodytas Wabcoin adresas</translation>
</message>
<message>
<location line="+3"/>
<source>Verify &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Reset all verify message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a Wabcoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Įveskite bitkoinų adresą (pvz. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation>Spragtelėkite "Registruotis žinutę" tam, kad gauti parašą</translation>
</message>
<message>
<location line="+3"/>
<source>Enter Wabcoin signature</source>
<translation>Įveskite Wabcoin parašą</translation>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation>Įvestas adresas negalioja.</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>Prašom patikrinti adresą ir bandyti iš naujo.</translation>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation>Piniginės atrakinimas atšauktas.</translation>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation>Žinutės pasirašymas nepavyko.</translation>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation>Žinutė pasirašyta.</translation>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation>Nepavyko iškoduoti parašo.</translation>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation>Prašom patikrinti parašą ir bandyti iš naujo.</translation>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation>Parašas neatitinka žinutės.</translation>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation>Žinutės tikrinimas nepavyko.</translation>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation>Žinutė patikrinta.</translation>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<location filename="../splashscreen.cpp" line="+22"/>
<source>The Wabcoin developers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>[testnet]</source>
<translation>[testavimotinklas]</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+20"/>
<source>Open until %1</source>
<translation>Atidaryta iki %1</translation>
</message>
<message>
<location line="+6"/>
<source>%1/offline</source>
<translation>%1/neprisijungęs</translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/nepatvirtintas</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 patvirtinimų</translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation>Būsena</translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>Data</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation>Šaltinis</translation>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation>Sugeneruotas</translation>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation>Nuo</translation>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation>Kam</translation>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation>savo adresas</translation>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation>žymė</translation>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation>Kreditas</translation>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation>nepriimta</translation>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation>Debitas</translation>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation>Sandorio mokestis</translation>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation>Neto suma</translation>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>Žinutė</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation>Komentaras</translation>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation>Sandorio 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>Išgautos monetos turi sulaukti 120 blokų, kol jos gali būti naudojamos. Kai sukūrėte šį bloką, jis buvo transliuojamas tinkle ir turėjo būti įtrauktas į blokų grandinę. Jei nepavyksta patekti į grandinę, bus pakeista į "nepriėmė", o ne "vartojamas". Tai kartais gali atsitikti, jei kitas mazgas per keletą sekundžių sukuria bloką po jūsų bloko.</translation>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation>Derinimo informacija</translation>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>Sandoris</translation>
</message>
<message>
<location line="+3"/>
<source>Inputs</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation>Suma</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation>tiesa</translation>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation>netiesa</translation>
</message>
<message>
<location line="-209"/>
<source>, has not been successfully broadcast yet</source>
<translation>, transliavimas dar nebuvo sėkmingas</translation>
</message>
<message numerus="yes">
<location line="-35"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+70"/>
<source>unknown</source>
<translation>nežinomas</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>Sandorio detelės</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>Šis langas sandorio detalų aprašymą</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+225"/>
<source>Date</source>
<translation>Data</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>Tipas</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Adresas</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>Suma</translation>
</message>
<message numerus="yes">
<location line="+57"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+3"/>
<source>Open until %1</source>
<translation>Atidaryta iki %1</translation>
</message>
<message>
<location line="+3"/>
<source>Offline (%1 confirmations)</source>
<translation>Atjungta (%1 patvirtinimai)</translation>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation>Nepatvirtintos (%1 iš %2 patvirtinimų)</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Patvirtinta (%1 patvirtinimai)</translation>
</message>
<message numerus="yes">
<location line="+8"/>
<source>Mined balance will be available when it matures in %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></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>Šis blokas negautas nė vienu iš mazgų ir matomai nepriimtas</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>Išgauta bet nepriimta</translation>
</message>
<message>
<location line="+43"/>
<source>Received with</source>
<translation>Gauta su</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>Gauta iš</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>Siųsta </translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>Mokėjimas sau</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>Išgauta</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>nepasiekiama</translation>
</message>
<message>
<location line="+199"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Sandorio būklė. Užvedus pelės žymeklį ant šios srities matysite patvirtinimų skaičių.</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>Sandorio gavimo data ir laikas</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>Sandorio tipas.</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>Sandorio paskirties adresas</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>Suma pridėta ar išskaičiuota iš balanso</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+52"/>
<location line="+16"/>
<source>All</source>
<translation>Visi</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>Šiandien</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>Šią savaitę</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>Šį mėnesį</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>Paskutinį mėnesį</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>Šiais metais</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>Intervalas...</translation>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation>Gauta su</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>Išsiųsta</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>Skirta sau</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>Išgauta</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>Kita</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>Įveskite adresą ar žymę į paiešką</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>Minimali suma</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>Kopijuoti adresą</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Kopijuoti žymę</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Kopijuoti sumą</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>Taisyti žymę</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation>Rodyti sandėrio detales</translation>
</message>
<message>
<location line="+139"/>
<source>Export Transaction Data</source>
<translation>Sandorio duomenų eksportavimas</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Kableliais atskirtų duomenų failas (*.csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>Patvirtintas</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>Data</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>Tipas</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>Žymė</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Adresas</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>Suma</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>Eksportavimo klaida</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Neįmanoma įrašyti į failą %1.</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>Grupė:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>skirta</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+193"/>
<source>Send Coins</source>
<translation>Siųsti monetas</translation>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<location filename="../walletview.cpp" line="+42"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Export the data in the current tab to a file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+193"/>
<source>Backup Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Backup Successful</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The wallet data was successfully saved to the new location.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+94"/>
<source>Wabcoin version</source>
<translation>Wabcoin versija</translation>
</message>
<message>
<location line="+102"/>
<source>Usage:</source>
<translation>Naudojimas:</translation>
</message>
<message>
<location line="-29"/>
<source>Send command to -server or wabcoind</source>
<translation>Siųsti komandą serveriui arba wabcoind</translation>
</message>
<message>
<location line="-23"/>
<source>List commands</source>
<translation>Komandų sąrašas</translation>
</message>
<message>
<location line="-12"/>
<source>Get help for a command</source>
<translation>Suteikti pagalba komandai</translation>
</message>
<message>
<location line="+24"/>
<source>Options:</source>
<translation>Parinktys:</translation>
</message>
<message>
<location line="+24"/>
<source>Specify configuration file (default: wabcoin.conf)</source>
<translation>Nurodyti konfigūracijos failą (pagal nutylėjimąt: wabcoin.conf)</translation>
</message>
<message>
<location line="+3"/>
<source>Specify pid file (default: wabcoind.pid)</source>
<translation>Nurodyti pid failą (pagal nutylėjimą: wabcoind.pid)</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>Nustatyti duomenų aplanką</translation>
</message>
<message>
<location line="-9"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-28"/>
<source>Listen for connections on <port> (default: 11333 or testnet: 111333)</source>
<translation>Sujungimo klausymas prijungčiai <port> (pagal nutylėjimą: 11333 arba testnet: 111333)</translation>
</message>
<message>
<location line="+5"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Palaikyti ne daugiau <n> jungčių kolegoms (pagal nutylėjimą: 125)</translation>
</message>
<message>
<location line="-48"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<source>Specify your own public address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>Atjungimo dėl netinkamo kolegų elgesio riba (pagal nutylėjimą: 100)</translation>
</message>
<message>
<location line="-134"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>Sekundžių kiekis eikiamas palaikyti ryšį dėl lygiarangių nestabilumo (pagal nutylėjimą: 86.400)</translation>
</message>
<message>
<location line="-29"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Listen for JSON-RPC connections on <port> (default: 11332 or testnet: 111332)</source>
<translation>Klausymas JSON-RPC sujungimui prijungčiai <port> (pagal nutylėjimą: 11332 or testnet: 111332)</translation>
</message>
<message>
<location line="+37"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Priimti komandinę eilutę ir JSON-RPC komandas</translation>
</message>
<message>
<location line="+76"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Dirbti fone kaip šešėlyje ir priimti komandas</translation>
</message>
<message>
<location line="+37"/>
<source>Use the test network</source>
<translation>Naudoti testavimo tinklą</translation>
</message>
<message>
<location line="-112"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation type="unfinished"/>
</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=wabcoinrpc
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 "Wabcoin Alert" [email protected]
</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. Wabcoin is probably already running.</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</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>Įspėjimas: -paytxfee yra nustatytas per didelis. Tai sandorio mokestis, kurį turėsite mokėti, jei siųsite sandorį.</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 type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong Wabcoin will not work properly.</source>
<translation>Įspėjimas: Patikrinkite, kad kompiuterio data ir laikas yra teisingi.Jei Jūsų laikrodis neteisingai nustatytas Wabcoin, veiks netinkamai.</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 type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Block creation options:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Connect only to the specified node(s)</source>
<translation>Prisijungti tik prie nurodyto mazgo</translation>
</message>
<message>
<location line="+3"/>
<source>Corrupted block database detected</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Do you want to rebuild the block database now?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error initializing block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error initializing wallet database environment %s!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error loading block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error opening block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error: Disk space is low!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: Wallet locked, unable to create transaction!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: system error: </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to read block info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to read block</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to sync block index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write file info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write to coin database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write transaction index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write undo data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Find peers using DNS lookup (default: 1 unless -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Generate coins (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 288, 0 = all)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-4, default: 3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Not enough file descriptors available.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Rebuild block chain index from current blk000??.dat files</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+26"/>
<source>Verifying blocks...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Verifying wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-69"/>
<source>Imports blocks from external blk000??.dat file</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="+77"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Invalid -tor address: '%s'</source>
<translation>Neteisingas tor adresas: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -minrelaytxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -mintxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Maintain a full transaction index (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation>Maksimalus buferis priėmimo sujungimui <n>*1000 bitų (pagal nutylėjimą: 5000)</translation>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation>Maksimalus buferis siuntimo sujungimui <n>*1000 bitų (pagal nutylėjimą: 1000)</translation>
</message>
<message>
<location line="+2"/>
<source>Only accept block chain matching built-in checkpoints (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation>Išvesti papildomą derinimo informaciją. Numanomi visi kiti -debug* parametrai</translation>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation>Išvesti papildomą tinklo derinimo informaciją</translation>
</message>
<message>
<location line="+2"/>
<source>Prepend debug output with timestamp</source>
<translation>Prideėti laiko žymę derinimo rezultatams</translation>
</message>
<message>
<location line="+5"/>
<source>SSL options: (see the Wabcoin Wiki for SSL setup instructions)</source>
<translation>SSL opcijos (žr.e Wabcoin Wiki for SSL setup instructions)</translation>
</message>
<message>
<location line="+1"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Siųsti atsekimo/derinimo info į konsolę vietoj debug.log failo</translation>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation>Siųsti sekimo/derinimo info derintojui</translation>
</message>
<message>
<location line="+5"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Signing transaction failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation>Nustatyti sujungimo trukmę milisekundėmis (pagal nutylėjimą: 5000)</translation>
</message>
<message>
<location line="+4"/>
<source>System error: </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Transaction amount too small</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction amounts must be positive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction too large</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation>Bandymas naudoti UPnP struktūra klausymosi prievadui (default: 0)</translation>
</message>
<message>
<location line="+1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation>Bandymas naudoti UPnP struktūra klausymosi prievadui (default: 1 when listening)</translation>
</message>
<message>
<location line="+1"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Username for JSON-RPC connections</source>
<translation>Vartotojo vardas JSON-RPC jungimuisi</translation>
</message>
<message>
<location line="+4"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>You need to rebuild the databases using -reindex to change -txindex</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-50"/>
<source>Password for JSON-RPC connections</source>
<translation>Slaptažodis JSON-RPC sujungimams</translation>
</message>
<message>
<location line="-67"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Leisti JSON-RPC tik iš nurodytų IP adresų</translation>
</message>
<message>
<location line="+76"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Siųsti komandą mazgui dirbančiam <ip> (pagal nutylėjimą: 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 type="unfinished"/>
</message>
<message>
<location line="+147"/>
<source>Upgrade wallet to latest format</source>
<translation>Atnaujinti piniginę į naujausią formatą</translation>
</message>
<message>
<location line="-21"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Nustatyti rakto apimties dydį <n> (pagal nutylėjimą: 100)</translation>
</message>
<message>
<location line="-12"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Ieškoti prarastų piniginės sandorių blokų grandinėje</translation>
</message>
<message>
<location line="+35"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>Naudoti OpenSSL (https) jungimuisi JSON-RPC </translation>
</message>
<message>
<location line="-26"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Serverio sertifikato failas (pagal nutylėjimą: server.cert)</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>Serverio privatus raktas (pagal nutylėjimą: server.pem)</translation>
</message>
<message>
<location line="-151"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation>Priimtini šifrai (pagal nutylėjimą: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation>
</message>
<message>
<location line="+165"/>
<source>This help message</source>
<translation>Pagelbos žinutė</translation>
</message>
<message>
<location line="+6"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>Nepavyko susieti šiame kompiuteryje prievado %s (bind returned error %d, %s)</translation>
</message>
<message>
<location line="-91"/>
<source>Connect through socks proxy</source>
<translation>Jungtis per socks tarpinį serverį</translation>
</message>
<message>
<location line="-10"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>Leisti DNS paiešką sujungimui ir mazgo pridėjimui</translation>
</message>
<message>
<location line="+55"/>
<source>Loading addresses...</source>
<translation>Užkraunami adresai...</translation>
</message>
<message>
<location line="-35"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation> wallet.dat pakrovimo klaida, wallet.dat sugadintas</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat: Wallet requires newer version of Wabcoin</source>
<translation> wallet.dat pakrovimo klaida, wallet.dat reikalauja naujasnės Wabcoin versijos</translation>
</message>
<message>
<location line="+93"/>
<source>Wallet needed to be rewritten: restart Wabcoin to complete</source>
<translation>Piniginė turi būti prrašyta: įvykdymui perkraukite Wabcoin</translation>
</message>
<message>
<location line="-95"/>
<source>Error loading wallet.dat</source>
<translation> wallet.dat pakrovimo klaida</translation>
</message>
<message>
<location line="+28"/>
<source>Invalid -proxy address: '%s'</source>
<translation>Neteisingas proxy adresas: '%s'</translation>
</message>
<message>
<location line="+56"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-96"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+44"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>Neteisinga suma -paytxfee=<amount>: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount</source>
<translation>Neteisinga suma</translation>
</message>
<message>
<location line="-6"/>
<source>Insufficient funds</source>
<translation>Nepakanka lėšų</translation>
</message>
<message>
<location line="+10"/>
<source>Loading block index...</source>
<translation>Įkeliamas blokų indeksas...</translation>
</message>
<message>
<location line="-57"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Pridėti mazgą prie sujungti su and attempt to keep the connection open</translation>
</message>
<message>
<location line="-25"/>
<source>Unable to bind to %s on this computer. Wabcoin is probably already running.</source>
<translation>Nepavyko susieti šiame kompiuteryje prievado %s. Wabcoin tikriausiai jau veikia.</translation>
</message>
<message>
<location line="+64"/>
<source>Fee per KB to add to transactions you send</source>
<translation>Įtraukti mokestį už kB siunčiamiems sandoriams</translation>
</message>
<message>
<location line="+19"/>
<source>Loading wallet...</source>
<translation>Užkraunama piniginė...</translation>
</message>
<message>
<location line="-52"/>
<source>Cannot downgrade wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Cannot write default address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+64"/>
<source>Rescanning...</source>
<translation>Peržiūra</translation>
</message>
<message>
<location line="-57"/>
<source>Done loading</source>
<translation>Įkėlimas baigtas</translation>
</message>
<message>
<location line="+82"/>
<source>To use the %s option</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-74"/>
<source>Error</source>
<translation>Klaida</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 type="unfinished"/>
</message>
</context>
</TS> | mit |
satellitejs/react-boilerplate | generate/generators/util.js | 736 | const utils = require('../utils');
const BASE_DIR = './src/utils';
const TEST_DIR = './src/utils/test';
function generateUtil(args) {
if (!args[0]) {
return utils.printError('Invalid number of arguments. Must specify a name for the util.');
}
if (!utils.checkDirectoryExists(BASE_DIR)) {
return utils.printError(`Cannot find directory for utils: ${BASE_DIR}`);
}
if (!utils.checkDirectoryExists(TEST_DIR)) {
return utils.printError(`Cannot find directory for util tests: ${TEST_DIR}`);
}
return utils.createFiles(BASE_DIR, [ `${args[0]}.js`, `test/${args[0]}.js` ]);
}
module.exports = {
description: 'Creates a new util.',
alias: 'u',
examples: ['util MyUtil', 'u MyUtil'],
fn: generateUtil,
};
| mit |
kimchanyoung/kimchanyoung.github.io | js/app.js | 969 | $(document).ready(function(){
$("#to-about").click(function() {
$('html, body').animate({
scrollTop: $("#about").offset().top
}, 1000);
});
$("#to-skills").click(function() {
$('html, body').animate({
scrollTop: $("#skills").offset().top
}, 1000);
});
$("#to-portfolio").click(function() {
$('html, body').animate({
scrollTop: $("#portfolio").offset().top
}, 1000);
});
$("#to-blog").click(function() {
$('html, body').animate({
scrollTop: $("#blog").offset().top
}, 1000);
});
$("#to-contact").click(function() {
$('html, body').animate({
scrollTop: $("#contact").offset().top
}, 1000);
});
$("#contact-btn").click(function() {
$('html, body').animate({
scrollTop: $("#contact").offset().top
}, 1000);
});
$("#opening-btn").click(function() {
$('html, body').animate({
scrollTop: $("#about").offset().top
}, 1000);
});
}) | mit |
DanielTomlinson/Propeller | Propeller/config/environments/development.rb | 1117 | Propeller::Application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations
config.active_record.migration_error = :page_load
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
end
| mit |
linfx/LinFx | src/LinFx/Extensions/DynamicProxy/IMethodInvocation.cs | 854 | using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading.Tasks;
namespace LinFx.Extensions.DynamicProxy
{
/// <summary>
/// 调用方法
/// </summary>
public interface IMethodInvocation
{
object[] Arguments { get; }
IReadOnlyDictionary<string, object> ArgumentsDictionary { get; }
Type[] GenericArguments { get; }
/// <summary>
/// 目标对象
/// </summary>
object TargetObject { get; }
/// <summary>
/// 方法
/// </summary>
MethodInfo Method { get; }
/// <summary>
/// 返回值
/// </summary>
object ReturnValue { get; set; }
/// <summary>
/// 处理
/// </summary>
/// <returns></returns>
Task ProceedAsync();
}
} | mit |
joedeller/pymine | howbig.py | 1387 | #! /usr/bin/python
# Joe Deller 2014
# Find out how big our template buildings stored in their csv files are
# Level : Intermediate
# Uses : Libraries, variables, operators, loops, files
# Our CSV files that contain blue prints for buildings do not
# contain any information about how big they are
# This program simply scans them and works out their size
# We could then modify the blue prints to store this information
import os.path
import sys
import csv
build_file = "swimming.csv"
if (len(sys.argv) >= 2):
build_file = sys.argv[1]
if (os.path.isfile(build_file)):
print "Going to measure " + build_file
else:
print "Sorry, I can't find the file called:" + build_file
print "Stopping."
exit()
lines = 0
height = 0
width = 0
# Open the file we typed or use build_file if nothing was typed
with open(build_file, 'rb') as csvfile:
data = csv.reader(csvfile, delimiter=',', quotechar='|')
for row in data:
if (row[0].startswith("L")):
height = height + 1
else:
# The width of the building should always be the same
# so if we've worked it out once, no need to do it again
if (width == 0):
width = len(row)
lines = lines + 1
depth = lines / height
print (build_file + " is " + str(height) +" high, " +str(depth) + " deep, " + str(width) +" wide")
| mit |
veggerby/Veggerby.Algorithm | src/Veggerby.Algorithm/LinearAlgebra/Matrix.cs | 8033 | using System;
using System.Collections.Generic;
using System.Linq;
namespace Veggerby.Algorithm.LinearAlgebra
{
public class Matrix
{
public static Matrix Identity(int n)
{
if (n <= 0)
{
throw new ArgumentOutOfRangeException(nameof(n));
}
return new Matrix(Enumerable.Range(0, n).Select(r => new Vector(Enumerable.Range(0, n).Select(c => r == c ? 1D : 0).ToArray())));
}
public Matrix(int rows, int cols)
{
if (rows <= 0)
{
throw new ArgumentOutOfRangeException(nameof(rows));
}
if (cols <= 0)
{
throw new ArgumentOutOfRangeException(nameof(cols));
}
_values = new double[rows, cols];
}
public Matrix(double[,] values)
{
if (values == null)
{
throw new ArgumentNullException(nameof(values));
}
if (values.GetLength(0) == 0 || values.GetLength(1) == 0)
{
throw new ArgumentOutOfRangeException(nameof(values));
}
_values = values;
}
public Matrix(IEnumerable<Vector> rows)
{
if (rows == null)
{
throw new ArgumentNullException(nameof(rows));
}
if (!rows.Any())
{
throw new ArgumentException("Rows cannot be empty list", nameof(rows));
}
var size = rows.First().Size;
if (rows.Any(x => x.Size != size))
{
throw new ArgumentException("All row vectors must have same dimension", nameof(rows));
}
_values = rows.ToArray();
}
private readonly double[,] _values;
public int RowCount => _values.GetLength(0);
public int ColCount => _values.GetLength(1);
public IEnumerable<Vector> Rows => Enumerable.Range(0, RowCount).Select(GetRow);
public IEnumerable<Vector> Cols => Enumerable.Range(0, ColCount).Select(GetCol);
public double this[int r, int c]
{
get
{
if (r < 0 || r >= RowCount)
{
throw new ArgumentOutOfRangeException(nameof(r));
}
if (c < 0 || c >= ColCount)
{
throw new ArgumentOutOfRangeException(nameof(c));
}
return _values[r, c];
}
}
public Vector GetRow(int r)
{
if (r < 0 || r >= RowCount)
{
throw new ArgumentOutOfRangeException(nameof(r));
}
return new Vector(Enumerable.Range(0, ColCount).Select(c => this[r, c]));
}
public Vector GetCol(int c)
{
if (c < 0 || c >= ColCount)
{
throw new ArgumentOutOfRangeException(nameof(c));
}
return new Vector(Enumerable.Range(0, RowCount).Select(r => this[r, c]));
}
public double[,] ToArray() => Rows.ToArray();
public double Determinant
{
get
{
if (!this.IsSquare())
{
throw new IndexOutOfRangeException("Cannot calculate determinant for non-square matrix");
}
var v = ToArray();
var n = ColCount - 1;
double det = 1;
for (var k = 0; k <= n; k++)
{
if (Math.Abs(v[k, k]) < double.Epsilon)
{
var j = k;
while ((j < n) && (Math.Abs(v[k, j]) < double.Epsilon))
{
j = j + 1;
}
if (Math.Abs(v[k, j]) < double.Epsilon)
{
return 0;
}
for (var i = k; i <= n; i++)
{
var save = v[i, j];
v[i, j] = v[i, k];
v[i, k] = save;
}
det = -det;
}
var vk = v[k, k];
det = det * vk;
if (k < n)
{
int k1 = k + 1;
for (var i = k1; i <= n; i++)
{
for (var j = k1; j <= n; j++)
{
v[i, j] = v[i, j] - v[i, k] * (v[k, j] / vk);
}
}
}
}
return det;
}
}
public static Matrix operator +(Matrix m1, Matrix m2)
{
if ((m1.RowCount != m2.RowCount) || (m1.ColCount != m2.ColCount))
{
throw new ArgumentException(nameof(m2), "Cannot add matrices with different dimensions");
}
return new Matrix(m1.Rows.Zip(m2.Rows, (r1, r2) => r1 + r2));
}
public static Matrix operator -(Matrix m1, Matrix m2)
{
if ((m1.RowCount != m2.RowCount) || (m1.ColCount != m2.ColCount))
{
throw new ArgumentException(nameof(m2), "Cannot add matrices with different dimensions");
}
return new Matrix(m1.Rows.Zip(m2.Rows, (r1, r2) => r1 - r2));
}
public static Matrix operator *(double factor, Matrix m)
{
return new Matrix(m.Rows.Select(x => new Vector(x.ToArray().Select(y => factor * y))));
}
public static Matrix operator *(Matrix m1, Matrix m2)
{
if (m1.ColCount != m2.RowCount)
{
throw new ArgumentException(nameof(m2), "m1 must have same number of columns as m2 has rows");
}
int r = 0;
var result = new double[m1.RowCount, m2.ColCount];
foreach (var r1 in m1.Rows)
{
int c = 0;
foreach (var c2 in m2.Cols)
{
result[r, c] = r1.ToArray().Zip(c2.ToArray(), (rv, cv) => rv * cv).Sum();
c++;
}
r++;
}
return new Matrix(result);
}
public static Vector operator *(Matrix m, Vector v)
{
if (m.ColCount != v.Size)
{
throw new ArgumentException(nameof(v), "m must have same number of columns as v has rows");
}
int r = 0;
var result = new double[m.RowCount];
foreach (var r1 in m.Rows)
{
result[r] = r1.ToArray().Zip(v.ToArray(), (rv, cv) => rv * cv).Sum();
r++;
}
return new Vector(result);
}
public static bool operator ==(Matrix m1, Matrix m2) => Equals(m1, m2);
public static bool operator !=(Matrix m1, Matrix m2) => !Equals(m1, m2);
public override string ToString() => "(" + string.Join(Environment.NewLine, Rows.Select(x => x.ToString())) + ")";
protected bool Equals(Matrix other) => Rows.SequenceEqual(other.Rows);
public override bool Equals(object obj) => Equals(obj as Matrix);
public override int GetHashCode()
{
unchecked
{
var hashCode = _values?.GetHashCode() ?? 0;
return hashCode;
}
}
}
}
| mit |
sjohnsonaz/cascade | src/cascade/Cascade.test.ts | 2599 | import Cascade from './Cascade';
import { IHash } from '../graph/IObservable';
describe('Cascade', function () {
describe('createObservable', function () {
it('should initialize to undefined', function () {
class ViewModel {
value: number;
constructor() {
Cascade.createObservable(this, 'value');
}
}
var viewModel = new ViewModel();
expect(viewModel.value).toBeUndefined();
});
it('should initialize in the constructor to a value', function () {
class ViewModel {
value: number;
constructor() {
Cascade.createObservable(this, 'value', 1);
}
}
var viewModel = new ViewModel();
expect(viewModel.value).toBe(1);
});
});
describe('createObservableArray', function () {
it('should initialize undefined to empty', function () {
class ViewModel {
value: number[];
constructor() {
Cascade.createObservableArray(this, 'value');
}
}
var viewModel = new ViewModel();
expect(viewModel.value.length).toBe(0);
});
it('should initialize in the constructor to a value', function () {
class ViewModel {
value: number[];
constructor() {
Cascade.createObservableArray(this, 'value', [1]);
}
}
var viewModel = new ViewModel();
expect(viewModel.value.length).toBe(1);
});
});
describe('createObservableHash', function () {
it('should initialize undefined to empty', function () {
class ViewModel {
value: IHash<number>;
constructor() {
Cascade.createObservableHash(this, 'value');
}
}
var viewModel = new ViewModel();
expect(viewModel.value).toBeInstanceOf(Object);
});
it('should initialize in the constructor to a value', function () {
class ViewModel {
value: IHash<number>;
constructor() {
Cascade.createObservableHash(this, 'value', {
property: 10,
});
}
}
var viewModel = new ViewModel();
expect(viewModel.value['property']).toBe(10);
});
});
});
| mit |
juniormesquitadandao/report4all | lib/src/net/sf/jasperreports/engine/export/GenericElementsFilterDecorator.java | 2484 | /*
* JasperReports - Free Java Reporting Library.
* Copyright (C) 2001 - 2014 TIBCO Software Inc. All rights reserved.
* http://www.jaspersoft.com
*
* Unless you have purchased a commercial license agreement from Jaspersoft,
* the following license terms apply:
*
* This program is part of JasperReports.
*
* JasperReports is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* JasperReports 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 JasperReports. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.jasperreports.engine.export;
import net.sf.jasperreports.engine.JRGenericPrintElement;
import net.sf.jasperreports.engine.JRPrintElement;
import net.sf.jasperreports.engine.JasperReportsContext;
/**
* @author Lucian Chirita ([email protected])
* @version $Id: GenericElementsFilterDecorator.java 7199 2014-08-27 13:58:10Z teodord $
*/
public class GenericElementsFilterDecorator implements ResetableExporterFilter
{
private final ExporterFilter filter;
private final String exporterKey;
private final GenericElementHandlerEnviroment handlerEnvironment;
public GenericElementsFilterDecorator(JasperReportsContext jasperReportsContext, String exporterKey, ExporterFilter filter)
{
this.filter = filter;
this.exporterKey = exporterKey;
this.handlerEnvironment = GenericElementHandlerEnviroment.getInstance(jasperReportsContext);
}
@Override
public boolean isToExport(JRPrintElement element)
{
if (element instanceof JRGenericPrintElement)
{
JRGenericPrintElement genericElement = (JRGenericPrintElement) element;
GenericElementHandler handler = handlerEnvironment.getElementHandler(
genericElement.getGenericType(), exporterKey);
if (handler == null || !handler.toExport(genericElement))
{
return false;
}
}
return filter == null || filter.isToExport(element);
}
@Override
public void reset()
{
if (filter instanceof ResetableExporterFilter)
{
((ResetableExporterFilter) filter).reset();
}
}
}
| mit |
polinom/iceream | project_name/static/js/app/config/DesktopInit.js | 2181 | if (!window.settings){
window.settings['STATIC_URL'] = '';
}
require.config({
baseUrl: window.settings.STATIC_URL+"/js/",
// 3rd party script alias names (Easier to type "jquery" than "libs/jquery, etc")
// probably a good idea to keep version numbers in the file names for updates checking
paths:{
// Core Libraries
"jquery":"libs/jquery",
"jqueryui":"libs/jqueryui",
"underscore":"libs/lodash",
"backbone":"libs/backbone",
"marionette":"libs/backbone.marionette",
"handlebars":"libs/handlebars",
// Plugins
"backbone.validateAll":"libs/plugins/Backbone.validateAll",
"bootstrap":"libs/plugins/bootstrap",
"text":"libs/plugins/text",
// Application Folders
"collections":"app/collections",
"models":"app/models",
"routers":"app/routers",
"templates":"app/templates",
"config":"app/config",
"controllers":"app/controllers",
"views":"app/views",
"parts":"app/parts"
},
// Sets the configuration for your third party scripts that are not AMD compatible
shim:{
// Twitter Bootstrap jQuery plugins
"bootstrap":["jquery"],
// jQueryUI
"jqueryui":["jquery"],
// Backbone
"backbone":{
// Depends on underscore/lodash and jQuery
"deps":["underscore", "jquery"],
// Exports the global window.Backbone object
"exports":"Backbone"
},
//Marionette
"marionette":{
"deps":["underscore", "backbone", "jquery"],
"exports":"Marionette"
},
//Handlebars
"handlebars":{
"exports":"Handlebars"
},
// Backbone.validateAll plugin that depends on Backbone
"backbone.validateAll":["backbone"]
}
});
// Includes Desktop Specific JavaScript files here (or inside of your Desktop router)
require(["jquery", "backbone", "marionette", "app/App", "jqueryui", "bootstrap", "backbone.validateAll"],
function () {
// Start Marionette Application in desktop mode (default)
App.start();
}); | mit |
vinecopulib/pyvinecopulib | src/main.cpp | 26401 | #include "docstr.hpp"
#include <pybind11/eigen.h>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <vinecopulib.hpp>
namespace py = pybind11;
using namespace vinecopulib;
PYBIND11_MODULE(pyvinecopulib, pv)
{
constexpr auto& doc = pyvinecopulib_doc;
constexpr auto& tools_stat_doc = doc.vinecopulib.tools_stats;
constexpr auto& bicop_doc = doc.vinecopulib.Bicop;
constexpr auto& bicopfamily_doc = doc.vinecopulib.BicopFamily;
constexpr auto& fitcontrolsbicop_doc = doc.vinecopulib.FitControlsBicop;
constexpr auto& rvinestructure_doc = doc.vinecopulib.RVineStructure;
constexpr auto& dvinestructure_doc = doc.vinecopulib.DVineStructure;
constexpr auto& cvinestructure_doc = doc.vinecopulib.CVineStructure;
constexpr auto& vinecop_doc = doc.vinecopulib.Vinecop;
constexpr auto& fitcontrolsvinecop_doc = doc.vinecopulib.FitControlsVinecop;
pv.doc() = R"pbdoc(
The pyvinecopulib package
-------------------------
)pbdoc";
py::enum_<BicopFamily>(pv, "BicopFamily", py::arithmetic(), R"pbdoc(
A bivariate copula family identifier.
The following convenient sets of families are also provided:
- ``all`` contains all the families,
- ``parametric`` contains the parametric families (all except ``tll``),
- ``nonparametric`` contains the nonparametric families
(``indep`` and ``tll``)
- ``one_par`` contains the parametric families with a single parameter,
(``gaussian``, ``clayton``, ``gumbel``, ``frank``, and ``joe``),
- ``two_par`` contains the parametric families with two parameters
(``student``, ``bb1``, ``bb6``, ``bb7``, and ``bb8``),
- ``elliptical`` contains the elliptical families,
- ``archimedean`` contains the archimedean families,
- ``bb`` contains the BB families,
- ``itau`` families for which estimation by Kendall's tau inversion is
available (``indep``, ``gaussian``, ``student``, ``clayton``,
``gumbel``, ``frank``, ``joe``),
- ``lt`` contains the families that are lower-tail dependent,
- ``ut`` contains the families that are upper-tail dependent.
)pbdoc")
.value("indep", BicopFamily::indep, bicopfamily_doc.indep.doc)
.value("gaussian", BicopFamily::gaussian, bicopfamily_doc.gaussian.doc)
.value("student", BicopFamily::student, bicopfamily_doc.student.doc)
.value("clayton", BicopFamily::clayton, bicopfamily_doc.clayton.doc)
.value("gumbel", BicopFamily::gumbel, bicopfamily_doc.gumbel.doc)
.value("frank", BicopFamily::frank, bicopfamily_doc.frank.doc)
.value("joe", BicopFamily::joe, bicopfamily_doc.joe.doc)
.value("bb1", BicopFamily::bb1, bicopfamily_doc.bb1.doc)
.value("bb6", BicopFamily::bb6, bicopfamily_doc.bb6.doc)
.value("bb7", BicopFamily::bb7, bicopfamily_doc.bb7.doc)
.value("bb8", BicopFamily::bb8, bicopfamily_doc.bb8.doc)
.value("tll", BicopFamily::tll, bicopfamily_doc.tll.doc)
.export_values();
pv.attr("all") = bicop_families::all;
pv.attr("parametric") = bicop_families::parametric;
pv.attr("nonparametric") = bicop_families::nonparametric;
pv.attr("one_par") = bicop_families::one_par;
pv.attr("two_par") = bicop_families::two_par;
pv.attr("elliptical") = bicop_families::elliptical;
pv.attr("archimedean") = bicop_families::archimedean;
pv.attr("bb") = bicop_families::bb;
pv.attr("lt") = bicop_families::lt;
pv.attr("ut") = bicop_families::ut;
pv.attr("itau") = bicop_families::itau;
py::class_<FitControlsBicop>(pv, "FitControlsBicop", fitcontrolsbicop_doc.doc)
.def(py::init<std::vector<BicopFamily>,
std::string,
std::string,
double,
std::string,
const Eigen::VectorXd&,
double,
bool,
size_t>(),
fitcontrolsbicop_doc.ctor.doc_9args,
py::arg("family_set") = bicop_families::all,
py::arg("parametric_method") = "mle",
py::arg("nonparametric_method") = "quadratic",
py::arg("nonparametric_mult") = 1.0,
py::arg("selection_criterion") = "bic",
py::arg("weights") = Eigen::VectorXd(),
py::arg("psi0") = 0.9,
py::arg("preselect_families") = true,
py::arg("num_threads") = 1)
/* .def(py::init<std::string>(), */
// "creates default controls except for the parameteric method.",
// py::arg("parametric_method"))
// .def(py::init<std::string, double>(),
// "creates default controls except for the nonparametric method.",
/* py::arg("nonparametric_method"), py::arg("mult") = 1.0) */
.def_property("family_set",
&FitControlsBicop::get_family_set,
&FitControlsBicop::set_family_set,
"The family set.")
.def_property("parametric_method",
&FitControlsBicop::get_parametric_method,
&FitControlsBicop::set_parametric_method,
"The fit method for parametric families.")
.def_property("nonparametric_method",
&FitControlsBicop::get_nonparametric_method,
&FitControlsBicop::set_nonparametric_method,
"The fit method for nonparametric families.")
.def_property("nonparametric_mult",
&FitControlsBicop::get_nonparametric_mult,
&FitControlsBicop::set_nonparametric_method,
"The multiplier for the smoothing parameters.")
.def_property("selection_criterion",
&FitControlsBicop::get_selection_criterion,
&FitControlsBicop::set_selection_criterion,
"The selection criterion.")
.def_property("weights",
&FitControlsBicop::get_weights,
&FitControlsBicop::set_weights,
"The weights for the observations.")
.def_property("psi0",
&FitControlsBicop::get_psi0,
&FitControlsBicop::set_psi0,
"The prior probability of non-independence.")
.def_property("preselect_families",
&FitControlsBicop::get_preselect_families,
&FitControlsBicop::set_preselect_families,
"Whether to exclude families based on symmetry properties "
"(see ``FitControlsBicop``)")
.def_property("num_threads",
&FitControlsBicop::get_num_threads,
&FitControlsBicop::set_num_threads,
"The number of threads.")
.def("__repr__",
[](const FitControlsBicop& controls) {
return "<pyvinecopulib.FitControlsBicop>\n" + controls.str();
})
.def("str", &FitControlsBicop::str, fitcontrolsbicop_doc.str.doc);
py::class_<Bicop>(pv, "Bicop", bicop_doc.doc)
.def(py::init<const BicopFamily,
const int,
const Eigen::MatrixXd&,
const std::vector<std::string>&>(),
py::arg("family") = BicopFamily::indep,
py::arg("rotation") = 0,
py::arg("parameters") = Eigen::MatrixXd(),
py::arg("var_types") = std::vector<std::string>(2, "c"),
bicop_doc.ctor.doc_4args_family_rotation_parameters_var_types)
.def(py::init<const Eigen::Matrix<double, Eigen::Dynamic, 2>&,
const FitControlsBicop&,
const std::vector<std::string>&>(),
py::arg("data"),
py::arg_v("controls", FitControlsBicop(), "FitControlsBicop()"),
py::arg("var_types") = std::vector<std::string>(2, "c"),
bicop_doc.ctor.doc_3args_data_controls_var_types)
.def(py::init<const std::string>(),
py::arg("filename"),
bicop_doc.ctor.doc_1args_filename)
.def("to_json", &Bicop::to_file, py::arg("filename"), bicop_doc.to_file.doc)
.def_property("rotation",
&Bicop::get_rotation,
&Bicop::set_rotation,
"The copula rotation.")
.def_property("parameters",
&Bicop::get_parameters,
&Bicop::set_parameters,
"The copula parameter(s).")
.def_property("var_types",
&Bicop::get_var_types,
&Bicop::set_var_types,
"The type of the two variables.")
.def_property_readonly("family", &Bicop::get_family, "The copula family.")
.def_property_readonly("tau", &Bicop::get_tau, "The Kendall's tau.")
.def_property_readonly("npars",
&Bicop::get_npars,
"The number of parameters (for nonparametric "
"families, a conceptually similar definition).")
.def("loglik",
&Bicop::loglik,
py::arg("u") = Eigen::Matrix<double, Eigen::Dynamic, 2>(),
bicop_doc.loglik.doc)
.def_property_readonly(
"nobs",
&Bicop::get_nobs,
"The number of observations (only for fitted objects).")
.def("aic",
&Bicop::aic,
py::arg("u") = Eigen::Matrix<double, Eigen::Dynamic, 2>(),
bicop_doc.aic.doc)
.def("bic",
&Bicop::bic,
py::arg("u") = Eigen::Matrix<double, Eigen::Dynamic, 2>(),
bicop_doc.bic.doc)
.def("mbic",
&Bicop::mbic,
py::arg("u") = Eigen::Matrix<double, Eigen::Dynamic, 2>(),
py::arg("psi0") = 0.9,
bicop_doc.mbic.doc)
.def("__repr__",
[](const Bicop& cop) { return "<pyvinecopulib.Bicop>\n" + cop.str(); })
.def("str", &Bicop::str, bicop_doc.str.doc)
.def("parameters_to_tau",
&Bicop::parameters_to_tau,
py::arg("parameters"),
bicop_doc.parameters_to_tau.doc)
.def("tau_to_parameters",
&Bicop::tau_to_parameters,
py::arg("tau"),
bicop_doc.tau_to_parameters.doc)
.def("parameters_lower_bounds",
&Bicop::get_parameters_lower_bounds,
bicop_doc.get_parameters_lower_bounds.doc)
.def("parameters_upper_bounds",
&Bicop::get_parameters_upper_bounds,
bicop_doc.get_parameters_upper_bounds.doc)
.def("pdf", &Bicop::pdf, py::arg("u"), bicop_doc.pdf.doc)
.def("cdf", &Bicop::cdf, py::arg("u"), bicop_doc.cdf.doc)
.def("hfunc1", &Bicop::hfunc1, py::arg("u"), bicop_doc.hfunc1.doc)
.def("hfunc2", &Bicop::hfunc2, py::arg("u"), bicop_doc.hfunc2.doc)
.def("hinv1", &Bicop::hinv1, py::arg("u"), bicop_doc.hinv1.doc)
.def("hinv2", &Bicop::hinv2, py::arg("u"), bicop_doc.hinv2.doc)
.def("simulate",
&Bicop::simulate,
py::arg("n"),
py::arg("qrng") = false,
py::arg("seeds") = std::vector<int>(),
bicop_doc.simulate.doc)
.def("fit",
&Bicop::fit,
py::arg("data"),
py::arg_v("controls", FitControlsBicop(), "FitControlsBicop()"),
bicop_doc.fit.doc)
.def("select",
&Bicop::select,
py::arg("data"),
py::arg_v("controls", FitControlsBicop(), "FitControlsBicop()"),
bicop_doc.select.doc);
py::class_<RVineStructure>(pv, "RVineStructure", rvinestructure_doc.doc)
.def(py::init<const size_t&, const size_t&>(),
py::arg("d") = static_cast<size_t>(1),
py::arg("trunc_lvl") = std::numeric_limits<size_t>::max(),
rvinestructure_doc.ctor.doc_2args_d_trunc_lvl)
.def(py::init<const Eigen::Matrix<size_t, Eigen::Dynamic, Eigen::Dynamic>&,
bool>(),
py::arg("mat"),
py::arg("check") = true,
rvinestructure_doc.ctor.doc_2args_mat_check)
.def(py::init<const std::vector<size_t>&, const size_t&, bool>(),
py::arg("order"),
py::arg("trunc_lvl") = std::numeric_limits<size_t>::max(),
py::arg("check") = true,
rvinestructure_doc.ctor.doc_3args_order_trunc_lvl_check)
.def(py::init<const std::string, bool>(),
py::arg("filename"),
py::arg("check") = true,
rvinestructure_doc.ctor.doc_2args_filename_check)
.def("to_json",
&RVineStructure::to_file,
py::arg("filename"),
rvinestructure_doc.to_file.doc)
.def_property_readonly("dim", &RVineStructure::get_dim, "The dimension.")
.def_property_readonly(
"trunc_lvl", &RVineStructure::get_trunc_lvl, "The truncation level.")
.def_property_readonly("order",
(std::vector<size_t>(RVineStructure::*)() const) &
RVineStructure::get_order,
"The variable order.")
.def("struct_array",
&RVineStructure::struct_array,
py::arg("tree"),
py::arg("edge"),
py::arg("natural_order") = false,
rvinestructure_doc.struct_array.doc)
.def("truncate",
&RVineStructure::truncate,
py::arg("trunc_lvl"),
rvinestructure_doc.truncate.doc)
.def_static("simulate",
&RVineStructure::simulate,
py::arg("d"),
py::arg("natural order") = false,
py::arg("seeds") = std::vector<size_t>(),
rvinestructure_doc.simulate.doc)
.def("__repr__",
[](const RVineStructure& rvs) {
return "<pyvinecopulib.RVineStructure>\n" + rvs.str();
})
.def("str", &RVineStructure::str, rvinestructure_doc.str.doc);
py::class_<DVineStructure, RVineStructure>(
pv, "DVineStructure", dvinestructure_doc.doc)
.def(py::init<const std::vector<size_t>&>(),
py::arg("order"),
dvinestructure_doc.ctor.doc_1args)
.def(py::init<const std::vector<size_t>&, size_t>(),
py::arg("order"),
py::arg("trunc_lvl"),
dvinestructure_doc.ctor.doc_2args)
.def("__repr__", [](const DVineStructure& rvs) {
return "<pyvinecopulib.DVineStructure>\n" + rvs.str();
});
py::class_<CVineStructure, RVineStructure>(
pv, "CVineStructure", cvinestructure_doc.doc)
.def(py::init<const std::vector<size_t>&>(),
cvinestructure_doc.ctor.doc_1args,
py::arg("order"))
.def(py::init<const std::vector<size_t>&, size_t>(),
py::arg("order"),
py::arg("trunc_lvl"),
cvinestructure_doc.ctor.doc_2args)
.def("__repr__", [](const CVineStructure& rvs) {
return "<pyvinecopulib.CVineStructure>\n" + rvs.str();
});
py::class_<FitControlsVinecop>(
pv, "FitControlsVinecop", fitcontrolsvinecop_doc.doc)
.def(py::init<std::vector<BicopFamily>,
std::string,
std::string,
double,
size_t,
std::string,
double,
std::string,
const Eigen::VectorXd&,
double,
bool,
bool,
bool,
bool,
size_t>(),
py::arg("family_set") = bicop_families::all,
py::arg("parametric_method") = "mle",
py::arg("nonparametric_method") = "quadratic",
py::arg("nonparametric_mult") = 1.0,
py::arg("trunc_lvl") = std::numeric_limits<size_t>::max(),
py::arg("tree_criterion") = "tau",
py::arg("threshold") = 0.0,
py::arg("selection_criterion") = "bic",
py::arg("weights") = Eigen::VectorXd(),
py::arg("psi0") = 0.9,
py::arg("preselect_families") = true,
py::arg("select_trunc_lvl") = false,
py::arg("select_threshold") = false,
py::arg("show_trace") = false,
py::arg("num_threads") = 1,
fitcontrolsvinecop_doc.ctor.doc_15args)
.def_property("family_set",
&FitControlsVinecop::get_family_set,
&FitControlsVinecop::set_family_set,
"The family set.")
.def_property("parametric_method",
&FitControlsVinecop::get_parametric_method,
&FitControlsVinecop::set_parametric_method,
"The fit method for parametric families.")
.def_property("nonparametric_method",
&FitControlsVinecop::get_nonparametric_method,
&FitControlsVinecop::set_nonparametric_method,
"The fit method for nonparametric families.")
.def_property("nonparametric_mult",
&FitControlsVinecop::get_nonparametric_mult,
&FitControlsVinecop::set_nonparametric_method,
"The multiplier for the smoothing parameters.")
.def_property("trunc_lvl",
&FitControlsVinecop::get_trunc_lvl,
&FitControlsVinecop::set_trunc_lvl,
"The truncation level.")
.def_property("tree_criterion",
&FitControlsVinecop::get_tree_criterion,
&FitControlsVinecop::set_tree_criterion,
"The tree criterion.")
.def_property("threshold",
&FitControlsVinecop::get_threshold,
&FitControlsVinecop::set_threshold,
"The threshold.")
.def_property("selection_criterion",
&FitControlsVinecop::get_selection_criterion,
&FitControlsVinecop::set_selection_criterion,
"The selection criterion.")
.def_property("weights",
&FitControlsVinecop::get_weights,
&FitControlsVinecop::set_weights,
"The weights for the observations.")
.def_property("psi0",
&FitControlsVinecop::get_psi0,
&FitControlsVinecop::set_psi0,
"The prior probability of non-independence.")
.def_property(
"preselect_families",
&FitControlsVinecop::get_preselect_families,
&FitControlsVinecop::set_preselect_families,
"Preselection based on symmetry properties (see ``__init__``).")
.def_property("select_trunc_lvl",
&FitControlsVinecop::get_select_trunc_lvl,
&FitControlsVinecop::set_select_trunc_lvl,
"Whether to select the truncation level.")
.def_property("select_threshold",
&FitControlsVinecop::get_select_threshold,
&FitControlsVinecop::set_select_threshold,
"Whether to select the threshold.")
.def_property("show_trace",
&FitControlsVinecop::get_show_trace,
&FitControlsVinecop::set_show_trace,
"Whether to show the trace.")
.def_property("num_threads",
&FitControlsVinecop::get_num_threads,
&FitControlsVinecop::set_num_threads,
"The number of threads.")
.def("__repr__",
[](const FitControlsVinecop& controls) {
return "<pyvinecopulib.FitControlsVinecop>\n" + controls.str();
})
.def("str", &FitControlsVinecop::str, fitcontrolsvinecop_doc.str.doc);
py::class_<Vinecop>(pv, "Vinecop", vinecop_doc.doc)
.def(py::init<const size_t>(), vinecop_doc.ctor.doc_1args_d, py::arg("d"))
.def(py::init<const RVineStructure&,
const std::vector<std::vector<Bicop>>&,
const std::vector<std::string>&>(),
py::arg("structure"),
py::arg("pair_copulas") = std::vector<size_t>(),
py::arg("var_types") = std::vector<std::string>(),
vinecop_doc.ctor.doc_3args_structure_pair_copulas_var_types)
.def(py::init<Eigen::Matrix<size_t, Eigen::Dynamic, Eigen::Dynamic>&,
const std::vector<std::vector<Bicop>>&,
const std::vector<std::string>&>(),
py::arg("matrix"),
py::arg("pair_copulas") = std::vector<size_t>(),
py::arg("var_types") = std::vector<std::string>(),
vinecop_doc.ctor.doc_3args_matrix_pair_copulas_var_types)
.def(py::init<const Eigen::MatrixXd&,
const RVineStructure&,
const std::vector<std::string>&,
const FitControlsVinecop&>(),
py::arg("data"),
py::arg("structure") = RVineStructure(),
py::arg("var_types") = std::vector<std::string>(),
py::arg_v("controls", FitControlsVinecop(), "FitControlsVinecop()"),
vinecop_doc.ctor.doc_4args_data_structure_var_types_controls)
.def(py::init<const Eigen::MatrixXd&,
const Eigen::Matrix<size_t, Eigen::Dynamic, Eigen::Dynamic>&,
const std::vector<std::string>&,
const FitControlsVinecop&>(),
py::arg("data"),
py::arg("matrix") =
Eigen::Matrix<size_t, Eigen::Dynamic, Eigen::Dynamic>(),
py::arg("var_types") = std::vector<std::string>(),
py::arg_v("controls", FitControlsVinecop(), "FitControlsVinecop()"),
vinecop_doc.ctor.doc_4args_data_matrix_var_types_controls)
.def(py::init<const std::string, bool>(),
py::arg("filename"),
py::arg("check") = true,
vinecop_doc.ctor.doc_2args_filename_check)
.def("to_json",
&Vinecop::to_file,
py::arg("filename"),
vinecop_doc.to_file.doc)
.def_property("var_types",
&Vinecop::get_var_types,
&Vinecop::set_var_types,
"The types of each variables.")
.def_property_readonly(
"trunc_lvl", &Vinecop::get_trunc_lvl, "The truncation level.")
.def_property_readonly("dim", &Vinecop::get_dim, "The dimension.")
.def("get_pair_copula",
&Vinecop::get_pair_copula,
"Gets a pair-copula.",
py::arg("tree"),
py::arg("edge"))
.def("get_family",
&Vinecop::get_family,
"Gets the family of a pair-copula.",
py::arg("tree"),
py::arg("edge"))
.def("get_rotation",
&Vinecop::get_rotation,
"Gets the rotation of a pair-copula.",
py::arg("tree"),
py::arg("edge"))
.def("get_parameters",
&Vinecop::get_parameters,
"Gets the parameters of a pair-copula.",
py::arg("tree"),
py::arg("edge"))
.def("get_tau",
&Vinecop::get_tau,
"Gets the kendall's tau of a pair-copula.",
py::arg("tree"),
py::arg("edge"))
.def_property_readonly(
"pair_copulas", &Vinecop::get_all_pair_copulas, "All pair-copulas.")
.def_property_readonly(
"families", &Vinecop::get_all_families, "Families of all pair-copulas.")
.def_property_readonly("rotations",
&Vinecop::get_all_rotations,
"The rotations of all pair-copulas.")
.def_property_readonly("parameters",
&Vinecop::get_all_parameters,
"The parameters of all pair-copulas.")
.def_property_readonly(
"taus", &Vinecop::get_all_taus, "The Kendall's taus of all pair-copulas.")
.def_property_readonly(
"order", &Vinecop::get_order, "The R-vine structure's order.")
.def_property_readonly(
"matrix", &Vinecop::get_matrix, "The R-vine structure's matrix.")
.def_property_readonly(
"structure", &Vinecop::get_rvine_structure, "The R-vine structure.")
.def_property_readonly(
"npars", &Vinecop::get_npars, "The total number of parameters.")
.def_property_readonly(
"nobs",
&Vinecop::get_nobs,
"The number of observations (for fitted objects only).")
.def_property_readonly("threshold",
&Vinecop::get_threshold,
"The threshold (for thresholded copulas only).")
.def("select",
&Vinecop::select,
py::arg("data"),
py::arg_v("controls", FitControlsVinecop(), "FitControlsVinecop()"),
vinecop_doc.select.doc)
.def("pdf",
&Vinecop::pdf,
py::arg("u"),
py::arg("num_threads") = 1,
vinecop_doc.pdf.doc)
.def("cdf",
&Vinecop::cdf,
py::arg("u"),
py::arg("N") = 10000,
py::arg("num_threads") = 1,
py::arg("seeds") = std::vector<int>(),
vinecop_doc.cdf.doc)
.def("simulate",
&Vinecop::simulate,
py::arg("n"),
py::arg("qrng") = false,
py::arg("num_threads") = 1,
py::arg("seeds") = std::vector<int>(),
vinecop_doc.simulate.doc)
.def("rosenblatt",
&Vinecop::rosenblatt,
py::arg("u"),
py::arg("num_threads") = 1,
vinecop_doc.rosenblatt.doc)
.def("inverse_rosenblatt",
&Vinecop::inverse_rosenblatt,
py::arg("u"),
py::arg("num_threads") = 1,
vinecop_doc.inverse_rosenblatt.doc)
.def("loglik",
&Vinecop::loglik,
py::arg("u") = Eigen::MatrixXd(),
py::arg("num_threads") = 1,
vinecop_doc.loglik.doc)
.def("aic",
&Vinecop::aic,
py::arg("u") = Eigen::MatrixXd(),
py::arg("num_threads") = 1,
vinecop_doc.aic.doc)
.def("bic",
&Vinecop::bic,
py::arg("u") = Eigen::MatrixXd(),
py::arg("num_threads") = 1,
vinecop_doc.bic.doc)
.def("mbicv",
&Vinecop::mbicv,
py::arg("u") = Eigen::MatrixXd(),
py::arg("psi0") = 0.9,
py::arg("num_threads") = 1,
vinecop_doc.mbicv.doc)
.def("__repr__",
[](const Vinecop& cop) {
return "<pyvinecopulib.Vinecop>\n" + cop.str();
})
.def("str", &Vinecop::str, vinecop_doc.str.doc)
.def("truncate",
&Vinecop::truncate,
py::arg("trunc_lvl"),
vinecop_doc.truncate.doc);
pv.def("simulate_uniform",
&tools_stats::simulate_uniform,
tools_stat_doc.simulate_uniform.doc,
py::arg("n"),
py::arg("d"),
py::arg("qrng") = false,
py::arg("seeds") = std::vector<int>());
pv.def("sobol",
&tools_stats::sobol,
tools_stat_doc.sobol.doc,
py::arg("n"),
py::arg("d"),
py::arg("seeds") = std::vector<int>());
pv.def("ghalton",
&tools_stats::ghalton,
tools_stat_doc.ghalton.doc,
py::arg("n"),
py::arg("d"),
py::arg("seeds") = std::vector<int>());
pv.def("to_pseudo_obs",
&tools_stats::to_pseudo_obs,
tools_stat_doc.to_pseudo_obs.doc,
py::arg("x"),
py::arg("ties_method") = "average");
#ifdef VERSION_INFO
pv.attr("__version__") = VERSION_INFO;
#else
pv.attr("__version__") = "dev";
#endif
}
| mit |
yndongyong/fast-dev-library | example/src/main/java/org/fastandroid/myapplication/StaggeredActivity.java | 6992 | package org.fastandroid.myapplication;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.widget.Toast;
import com.afollestad.materialdialogs.internal.MDAdapter;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;
import org.yndongyong.fastandroid.base.FaBaseActivity;
import org.yndongyong.fastandroid.component.refreshlayout.DataSource;
import org.yndongyong.fastandroid.component.refreshlayout.RefreshLayout;
import java.util.ArrayList;
import java.util.List;
import cn.bingoogolapple.refreshlayout.BGANormalRefreshViewHolder;
import cn.bingoogolapple.refreshlayout.BGARefreshViewHolder;
import jp.wasabeef.recyclerview.animators.FadeInLeftAnimator;
@EActivity
public class StaggeredActivity extends FaBaseActivity {
@ViewById(R.id.refreshLayout)
RefreshLayout mRefreshLayout;
@ViewById(R.id.rv_photos)
RecyclerView mRecyclerView;
PhotoAdapter mAdapter;
List<PhotoEntity> lists = new ArrayList<>();
int pageNum = 1;
@Override
protected int getContentViewLayoutID() {
return R.layout.activity_staggered;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
mTransitionMode = TransitionMode.RIGHT;
super.onCreate(savedInstanceState);
}
@AfterViews
public void afterViews() {
mRefreshLayout.setEmptyImage(R.mipmap.ico_empty);
mRefreshLayout.setErrorImage(R.mipmap.ico_empty);
BGARefreshViewHolder viewholder = new BGANormalRefreshViewHolder(this, true);
viewholder.setLoadingMoreText("正在卖力加载...");
//禁止下拉刷新
// mRefreshLayout.setPullDownRefreshEnable(false);
mRefreshLayout.setRefreshViewHolder(viewholder, true);
mRefreshLayout.setDataSource(new DataSource(this) {
@Override
public void refreshData() {
pageNum=1;
refresh();
}
@Override
public boolean loadMore() {
pageNum++;
return load();
}
});
mAdapter = new PhotoAdapter(this,lists);
mRecyclerView.setAdapter(mAdapter);
StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(3,
StaggeredGridLayoutManager.VERTICAL);
mRecyclerView.setLayoutManager(layoutManager);
// GridLayoutManager layoutManager1 = new GridLayoutManager(this, 3);
// mRecyclerView.setLayoutManager(layoutManager1);
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
refresh();
}
private void refresh() {
mAdapter.clear();
// mRefreshLayout.showLoadingView();
List<PhotoEntity> list = new ArrayList<>();
list.add(new PhotoEntity("http://ww1.sinaimg.cn/mw690/718878b5jw1f4rcmu8tl1j21jk111e6s.jpg", "分类一", 20160708));
list.add(new PhotoEntity("http://pic25.nipic.com/20121112/5955207_224247025000_2.jpg", "分类一", 20160708));
list.add(new PhotoEntity("http://m2.quanjing.com/2m/fod_liv002/fo-11171537.jpg", "分类一", 20160708));
list.add(new PhotoEntity("http://pic14.nipic.com/20110615/1347158_233357498344_2.jpg", "分类一", 20160708));
list.add(new PhotoEntity("http://pic17.nipic.com/20111109/7674259_144501034328_2.jpg", "分类二", 20160709));
list.add(new PhotoEntity("http://pic14.nipic.com/20110427/2944718_000916112196_2.jpg", "分类二", 20160709));
list.add(new PhotoEntity("http://pic14.nipic.com/20110529/7011463_085102601343_2.jpg", "分类二", 20160709));
list.add(new PhotoEntity("http://pic10.nipic.com/20101001/4438138_140843092127_2.jpg", "分类二", 20160709));
list.add(new PhotoEntity("http://pic41.nipic.com/20140509/18696269_121755386187_2.png", "分类二", 20160709));
list.add(new PhotoEntity("http://h.hiphotos.baidu.com/image/h%3D200/sign=cd65e7fa13d5ad6eb5f963eab1cb39a3/377adab44aed2e7394aa5a128f01a18b87d6fa49.jpg", "分类二", 20160709));
list.add(new PhotoEntity("http://pic24.nipic.com/20121003/10754047_140022530392_2.jpg", "分类二", 20160709));
list.add(new PhotoEntity("http://pic24.nipic.com/20121009/4744012_103328385000_2.jpg", "分类二", 20160709));
mAdapter = new PhotoAdapter(this,list);
mRecyclerView.setAdapter(mAdapter);
// mAdapter.setData(list);
mRefreshLayout.showContentView();
}
private boolean load() {
if (pageNum > 2) {
Toast.makeText(mContext, "load all!", Toast.LENGTH_SHORT).show();
return false;
}
List<PhotoEntity> list = new ArrayList<>();
list.add(new PhotoEntity("http://ww1.sinaimg.cn/mw690/718878b5jw1f4rcmu8tl1j21jk111e6s" +
".jpg", "分类三", 20160710));
list.add(new PhotoEntity("http://pic25.nipic.com/20121112/5955207_224247025000_2.jpg",
"分类三", 20160710));
list.add(new PhotoEntity("http://m2.quanjing.com/2m/fod_liv002/fo-11171537.jpg", "分类三",
20160710));
list.add(new PhotoEntity("http://pic14.nipic.com/20110615/1347158_233357498344_2.jpg",
"分类三", 20160710));
list.add(new PhotoEntity("http://pic17.nipic.com/20111109/7674259_144501034328_2.jpg",
"分类三", 20160710));
list.add(new PhotoEntity("http://pic14.nipic.com/20110427/2944718_000916112196_2.jpg",
"分类三", 20160710));
list.add(new PhotoEntity("http://pic14.nipic.com/20110529/7011463_085102601343_2.jpg",
"分类四", 20160711));
list.add(new PhotoEntity("http://pic10.nipic.com/20101001/4438138_140843092127_2.jpg",
"分类四", 20160711));
list.add(new PhotoEntity("http://pic41.nipic.com/20140509/18696269_121755386187_2.png",
"分类四", 20160711));
list.add(new PhotoEntity("http://h.hiphotos.baidu.com/image/h%3D200/sign=cd65e7fa13d5ad6eb5f963eab1cb39a3/377adab44aed2e7394aa5a128f01a18b87d6fa49.jpg",
"分类四", 20160711));
list.add(new PhotoEntity("http://pic24.nipic.com/20121003/10754047_140022530392_2.jpg",
"分类四", 20160711));
list.add(new PhotoEntity("http://pic24.nipic.com/20121009/4744012_103328385000_2.jpg",
"分类四", 20160711));
mAdapter.setData(list);
// 使用第三方的动画框架,不能使用这个
// mUserInfoAdapter.notifyDataSetChanged();
mRefreshLayout.endLoadingMore();
return false;
}
}
| mit |
gbelwariar/Self-Made-Projects | Tic-Tac-Toe/Tic_Tac_Toe.cpp | 4658 | // A C++ Program to play tic-tac-toe
#include<bits/stdc++.h>
using namespace std;
#define COMPUTER 1
#define HUMAN 2
#define SIDE 3 // Length of the board
// Computer will move with 'O'
// and human with 'X'
#define COMPUTERMOVE 'O'
#define HUMANMOVE 'X'
// A function to show the current board status
void showBoard(char board[][SIDE])
{
printf("\n\n");
printf("\t\t\t %c | %c | %c \n", board[0][0],
board[0][1], board[0][2]);
printf("\t\t\t--------------\n");
printf("\t\t\t %c | %c | %c \n", board[1][0],
board[1][1], board[1][2]);
printf("\t\t\t--------------\n");
printf("\t\t\t %c | %c | %c \n\n", board[2][0],
board[2][1], board[2][2]);
return;
}
// A function to show the instructions
void showInstructions()
{
printf("\t\t\t Tic-Tac-Toe\n\n");
printf("Choose a cell numbered from 1 to 9 as below"
" and play\n\n");
printf("\t\t\t 1 | 2 | 3 \n");
printf("\t\t\t--------------\n");
printf("\t\t\t 4 | 5 | 6 \n");
printf("\t\t\t--------------\n");
printf("\t\t\t 7 | 8 | 9 \n\n");
printf("-\t-\t-\t-\t-\t-\t-\t-\t-\t-\n\n");
return;
}
// A function to initialise the game
void initialise(char board[][SIDE], int moves[])
{
// Initiate the random number generator so that
// the same configuration doesn't arises
srand(time(NULL));
// Initially the board is empty
for (int i=0; i<SIDE; i++)
{
for (int j=0; j<SIDE; j++)
board[i][j] = ' ';
}
// Fill the moves with numbers
for (int i=0; i<SIDE*SIDE; i++)
moves[i] = i;
// randomise the moves
random_shuffle(moves, moves + SIDE*SIDE);
return;
}
// A function to declare the winner of the game
void declareWinner(int whoseTurn)
{
if (whoseTurn == COMPUTER)
printf("COMPUTER has won\n");
else
printf("HUMAN has won\n");
return;
}
// A function that returns true if any of the row
// is crossed with the same player's move
bool rowCrossed(char board[][SIDE])
{
for (int i=0; i<SIDE; i++)
{
if (board[i][0] == board[i][1] &&
board[i][1] == board[i][2] &&
board[i][0] != ' ')
return (true);
}
return(false);
}
// A function that returns true if any of the column
// is crossed with the same player's move
bool columnCrossed(char board[][SIDE])
{
for (int i=0; i<SIDE; i++)
{
if (board[0][i] == board[1][i] &&
board[1][i] == board[2][i] &&
board[0][i] != ' ')
return (true);
}
return(false);
}
// A function that returns true if any of the diagonal
// is crossed with the same player's move
bool diagonalCrossed(char board[][SIDE])
{
if (board[0][0] == board[1][1] &&
board[1][1] == board[2][2] &&
board[0][0] != ' ')
return(true);
if (board[0][2] == board[1][1] &&
board[1][1] == board[2][0] &&
board[0][2] != ' ')
return(true);
return(false);
}
// A function that returns true if the game is over
// else it returns a false
bool gameOver(char board[][SIDE])
{
return(rowCrossed(board) || columnCrossed(board)
|| diagonalCrossed(board) );
}
// A function to play Tic-Tac-Toe
void playTicTacToe(int whoseTurn)
{
// A 3*3 Tic-Tac-Toe board for playing
char board[SIDE][SIDE];
int moves[SIDE*SIDE];
// Initialise the game
initialise(board, moves);
// Show the instructions before playing
showInstructions();
int moveIndex = 0, x, y;
// Keep playing till the game is over or it is a draw
while (gameOver(board) == false &&
moveIndex != SIDE*SIDE)
{
if (whoseTurn == COMPUTER)
{
x = moves[moveIndex] / SIDE;
y = moves[moveIndex] % SIDE;
board[x][y] = COMPUTERMOVE;
printf("COMPUTER has put a %c in cell %d\n",
COMPUTERMOVE, moves[moveIndex]+1);
showBoard(board);
moveIndex ++;
whoseTurn = HUMAN;
}
else if (whoseTurn == HUMAN)
{
x = moves[moveIndex] / SIDE;
y = moves[moveIndex] % SIDE;
board[x][y] = HUMANMOVE;
printf ("HUMAN has put a %c in cell %d\n",
HUMANMOVE, moves[moveIndex]+1);
showBoard(board);
moveIndex ++;
whoseTurn = COMPUTER;
}
}
// If the game has drawn
if (gameOver(board) == false &&
moveIndex == SIDE * SIDE)
printf("It's a draw\n");
else
{
// Toggling the user to declare the actual
// winner
if (whoseTurn == COMPUTER)
whoseTurn = HUMAN;
else if (whoseTurn == HUMAN)
whoseTurn = COMPUTER;
// Declare the winner
declareWinner(whoseTurn);
}
return;
}
// Driver program
int main()
{
// Let us play the game with COMPUTER starting first
playTicTacToe(COMPUTER);
return (0);
}
| mit |
matrharr/restful_task_api | task_app/spec/controllers/api/v1/user_tasks_controller_spec.rb | 1140 | require 'spec_helper'
require 'rails_helper'
describe Api::V1::UserTasksController do
describe "POST #create" do
context "when user task is successfully created" do
before(:each) do
@user_task_attributes = FactoryGirl.attributes_for :user_task
post :create, { user_task: @user_task_attributes }
end
it "renders the json of user_task record just created" do
user_task_response = json_response
expect(user_task_response[:user_id]).to eql @user_task_attributes[:user_id]
end
end
context "when creation is unsuccessful" do
before(:each) do
@invalid_user_task_attributes = { user_id: 'string'}
post :create, { user_task: @invalid_user_task_attributes }
end
it "renders an errors json" do
user_task_response = json_response
expect(user_task_response).to have_key(:errors)
end
it "renders the json errors why the user_task could not be created" do
user_task_response = json_response
expect(user_task_response[:errors][:user_id]).to include "is not a number"
end
end
end
end | mit |
yogeshsaroya/new-cdnjs | ajax/libs/localforage/0.9.0/localforage.js | 130 | version https://git-lfs.github.com/spec/v1
oid sha256:f86dedd52fc930afb21fbbf28b7b54676911dc7b953c1dc4bb09a4fc0db1a9d2
size 73258
| mit |
hf/stun | src/test/java/me/stojan/stun/message/attribute/STUNAttributeSoftwareTest.java | 3431 | /*
* Copyright (c) 2016 Stojan Dimitrovski
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package me.stojan.stun.message.attribute;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Created by vuk on 03/12/16.
*/
public class STUNAttributeSoftwareTest {
@Test(expected = UnsupportedOperationException.class)
public void noInstances() {
new STUNAttributeSoftware();
}
@Test
public void TYPE() {
assertEquals(0x8022, STUNAttributeSoftware.TYPE);
}
@Test(expected = IllegalArgumentException.class)
public void value_nullArgument() throws Exception {
STUNAttributeSoftware.value(null);
}
@Test
public void value_utf8ASCII() throws Exception {
final String software = "12345678";
final byte[] value = STUNAttributeSoftware.value(software);
assertNotNull(value);
assertEquals(software.length(), value.length);
assertEquals(software, new String(value, "UTF-8"));
}
@Test
public void value_software_max128Chars() throws Exception {
final StringBuilder builder = new StringBuilder(129);
for (int i = 0; i < 130; i++) {
builder.append('!');
}
final String software = builder.toString();
assertTrue(software.length() > 128);
final byte[] value = STUNAttributeSoftware.value(software);
assertNotNull(value);
final String softwareRet = STUNAttributeSoftware.software(value);
assertNotNull(softwareRet);
assertEquals(128, softwareRet.length());
assertEquals(software.substring(0, 128), softwareRet);
}
@Test(expected = IllegalArgumentException.class)
public void software_nullValue() throws Exception {
STUNAttributeSoftware.software(null);
}
@Test(expected = InvalidSTUNAttributeException.class)
public void software_moreThan763Bytes() throws Exception {
STUNAttributeSoftware.software(new byte[764]);
}
@Test
public void software_correctValue() throws Exception {
final String software = "Hello, this is Cyrillic: Здраво!";
final byte[] value = STUNAttributeSoftware.value(software);
assertNotNull(value);
final String softwareRet = STUNAttributeSoftware.software(value);
assertNotNull(softwareRet);
assertEquals(software, softwareRet);
}
}
| mit |
andela/suyabay | database/migrations/2015_11_29_214941_add_roleField_to_user_table.php | 686 | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddRoleFieldToUserTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->integer('role_id')->unsigned()->default(1);
$table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('roles', function (Blueprint $table) {
//
});
}
}
| mit |
matt-way/jsBinarySchemaParser | example/index.js | 281 | import fs from 'fs'
import { parse } from '../src'
import { buildStream } from '../src/parsers/uint8'
import { GIF } from '../src/schemas'
debugger
const data = fs.readFileSync('./example/dog.gif')
const result = parse(buildStream(new Uint8Array(data)), GIF)
console.log(result)
| mit |
DoFabien/OsmGo | src/app/components/about/about.ts | 931 | import { Component } from '@angular/core';
import { Platform, ModalController, NavController } from '@ionic/angular';
import { ToastController } from '@ionic/angular';
import { ConfigService } from '../../services/config.service';
@Component({
selector: 'page-about',
templateUrl: './about.html'
})
export class AboutPage {
constructor(
public configService: ConfigService,
public platform: Platform,
public viewCtrl: ModalController,
public navCtrl: NavController,
public toastController: ToastController) {
}
async presentToast() {
const toast = await this.toastController.create({
message: 'You have activated the developer mode!',
duration: 2000
});
toast.present();
}
async tap(e){
if (e.tapCount == 5){
await this.presentToast()
this.configService.setIsDevMode(true);
}
}
dismiss(data = null) {
this.viewCtrl.dismiss(data);
}
}
| mit |
aabustamante/Semantic-UI-React | docs/app/Components/Layout.js | 1360 | import AnchorJS from 'anchor-js'
import PropTypes from 'prop-types'
import React, { Component } from 'react'
import Sidebar from 'docs/app/Components/Sidebar/Sidebar'
import style from 'docs/app/Style'
import TAAttribution from 'docs/app/Components/TAAttribution/TAAttribution'
import { scrollToAnchor } from 'docs/app/utils'
const anchors = new AnchorJS({
icon: '#',
})
export default class Layout extends Component {
static propTypes = {
children: PropTypes.node,
}
componentDidMount() {
this.resetPage()
}
componentDidUpdate(prevProps, prevState) {
this.resetPage()
}
componentWillUnmount() {
clearTimeout(this.scrollStartTimeout)
}
resetPage = () => {
// only reset the page when changing routes
if (this.pathname === location.pathname) return
clearTimeout(this.scrollStartTimeout)
scrollTo(0, 0)
anchors.add('h2, h3, h4, h5, h6')
anchors.remove([1, 2, 3, 4, 5, 6].map(n => `.rendered-example h${n}`).join(', '))
anchors.remove('.no-anchor')
this.scrollStartTimeout = setTimeout(scrollToAnchor, 500)
this.pathname = location.pathname
}
render() {
return (
<div style={style.container}>
<Sidebar style={style.menu} />
<div style={style.main}>
{this.props.children}
<TAAttribution />
</div>
</div>
)
}
}
| mit |
Karasiq/scalajs-highcharts | src/main/scala/com/highstock/config/PlotOptionsMapStatesNormal.scala | 1615 | /**
* Automatically generated file. Please do not edit.
* @author Highcharts Config Generator by Karasiq
* @see [[http://api.highcharts.com/highstock]]
*/
package com.highstock.config
import scalajs.js, js.`|`
import com.highcharts.CleanJsObject
import com.highcharts.HighchartsUtils._
/**
* @note JavaScript name: <code>plotOptions-map-states-normal</code>
*/
@js.annotation.ScalaJSDefined
class PlotOptionsMapStatesNormal extends com.highcharts.HighchartsGenericObject {
/**
* <p>Animation options for the fill color when returning from hover
* state to normal state. The animation adds some latency in order
* to reduce the effect of flickering when hovering in and out of
* for example an uneven coastline.</p>
* @example <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/maps/plotoptions/series-states-animation-false/">No animation of fill color</a>
*/
val animation: js.UndefOr[Boolean] = js.undefined
}
object PlotOptionsMapStatesNormal {
/**
* @param animation <p>Animation options for the fill color when returning from hover. state to normal state. The animation adds some latency in order. to reduce the effect of flickering when hovering in and out of. for example an uneven coastline.</p>
*/
def apply(animation: js.UndefOr[Boolean] = js.undefined): PlotOptionsMapStatesNormal = {
val animationOuter: js.UndefOr[Boolean] = animation
com.highcharts.HighchartsGenericObject.toCleanObject(new PlotOptionsMapStatesNormal {
override val animation: js.UndefOr[Boolean] = animationOuter
})
}
}
| mit |
shtse8/miningcore | src/Native/libcryptonote/common/base58.cpp | 9192 | // Copyright (c) 2014-2017, The Monero Project
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other
// materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers
#include "base58.h"
#include <assert.h>
#include <string>
#include <vector>
#include "crypto/hash.h"
#include "int-util.h"
// OW: unused #include "util.h"
#include "varint.h"
namespace tools
{
namespace base58
{
namespace
{
const char alphabet[] = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
const size_t alphabet_size = sizeof(alphabet) - 1;
const size_t encoded_block_sizes[] = {0, 2, 3, 5, 6, 7, 9, 10, 11};
const size_t full_block_size = sizeof(encoded_block_sizes) / sizeof(encoded_block_sizes[0]) - 1;
const size_t full_encoded_block_size = encoded_block_sizes[full_block_size];
const size_t addr_checksum_size = 4;
struct reverse_alphabet
{
reverse_alphabet()
{
m_data.resize(alphabet[alphabet_size - 1] - alphabet[0] + 1, -1);
for (size_t i = 0; i < alphabet_size; ++i)
{
size_t idx = static_cast<size_t>(alphabet[i] - alphabet[0]);
m_data[idx] = static_cast<int8_t>(i);
}
}
int operator()(char letter) const
{
size_t idx = static_cast<size_t>(letter - alphabet[0]);
return idx < m_data.size() ? m_data[idx] : -1;
}
static reverse_alphabet instance;
private:
std::vector<int8_t> m_data;
};
reverse_alphabet reverse_alphabet::instance;
struct decoded_block_sizes
{
decoded_block_sizes()
{
m_data.resize(encoded_block_sizes[full_block_size] + 1, -1);
for (size_t i = 0; i <= full_block_size; ++i)
{
m_data[encoded_block_sizes[i]] = static_cast<int>(i);
}
}
int operator()(size_t encoded_block_size) const
{
assert(encoded_block_size <= full_encoded_block_size);
return m_data[encoded_block_size];
}
static decoded_block_sizes instance;
private:
std::vector<int> m_data;
};
decoded_block_sizes decoded_block_sizes::instance;
uint64_t uint_8be_to_64(const uint8_t* data, size_t size)
{
assert(1 <= size && size <= sizeof(uint64_t));
uint64_t res = 0;
switch (9 - size)
{
case 1: res |= *data++;
case 2: res <<= 8; res |= *data++;
case 3: res <<= 8; res |= *data++;
case 4: res <<= 8; res |= *data++;
case 5: res <<= 8; res |= *data++;
case 6: res <<= 8; res |= *data++;
case 7: res <<= 8; res |= *data++;
case 8: res <<= 8; res |= *data; break;
default: assert(false);
}
return res;
}
void uint_64_to_8be(uint64_t num, size_t size, uint8_t* data)
{
assert(1 <= size && size <= sizeof(uint64_t));
uint64_t num_be = SWAP64BE(num);
memcpy(data, reinterpret_cast<uint8_t*>(&num_be) + sizeof(uint64_t) - size, size);
}
void encode_block(const char* block, size_t size, char* res)
{
assert(1 <= size && size <= full_block_size);
uint64_t num = uint_8be_to_64(reinterpret_cast<const uint8_t*>(block), size);
int i = static_cast<int>(encoded_block_sizes[size]) - 1;
while (0 < num)
{
uint64_t remainder = num % alphabet_size;
num /= alphabet_size;
res[i] = alphabet[remainder];
--i;
}
}
bool decode_block(const char* block, size_t size, char* res)
{
assert(1 <= size && size <= full_encoded_block_size);
int res_size = decoded_block_sizes::instance(size);
if (res_size <= 0)
return false; // Invalid block size
uint64_t res_num = 0;
uint64_t order = 1;
for (size_t i = size - 1; i < size; --i)
{
int digit = reverse_alphabet::instance(block[i]);
if (digit < 0)
return false; // Invalid symbol
uint64_t product_hi;
uint64_t tmp = res_num + mul128(order, digit, &product_hi);
if (tmp < res_num || 0 != product_hi)
return false; // Overflow
res_num = tmp;
order *= alphabet_size; // Never overflows, 58^10 < 2^64
}
if (static_cast<size_t>(res_size) < full_block_size && (UINT64_C(1) << (8 * res_size)) <= res_num)
return false; // Overflow
uint_64_to_8be(res_num, res_size, reinterpret_cast<uint8_t*>(res));
return true;
}
}
std::string encode(const std::string& data)
{
if (data.empty())
return std::string();
size_t full_block_count = data.size() / full_block_size;
size_t last_block_size = data.size() % full_block_size;
size_t res_size = full_block_count * full_encoded_block_size + encoded_block_sizes[last_block_size];
std::string res(res_size, alphabet[0]);
for (size_t i = 0; i < full_block_count; ++i)
{
encode_block(data.data() + i * full_block_size, full_block_size, &res[i * full_encoded_block_size]);
}
if (0 < last_block_size)
{
encode_block(data.data() + full_block_count * full_block_size, last_block_size, &res[full_block_count * full_encoded_block_size]);
}
return res;
}
bool decode(const std::string& enc, std::string& data)
{
if (enc.empty())
{
data.clear();
return true;
}
size_t full_block_count = enc.size() / full_encoded_block_size;
size_t last_block_size = enc.size() % full_encoded_block_size;
int last_block_decoded_size = decoded_block_sizes::instance(last_block_size);
if (last_block_decoded_size < 0)
return false; // Invalid enc length
size_t data_size = full_block_count * full_block_size + last_block_decoded_size;
data.resize(data_size, 0);
for (size_t i = 0; i < full_block_count; ++i)
{
if (!decode_block(enc.data() + i * full_encoded_block_size, full_encoded_block_size, &data[i * full_block_size]))
return false;
}
if (0 < last_block_size)
{
if (!decode_block(enc.data() + full_block_count * full_encoded_block_size, last_block_size,
&data[full_block_count * full_block_size]))
return false;
}
return true;
}
std::string encode_addr(uint64_t tag, const std::string& data)
{
std::string buf = get_varint_data(tag);
buf += data;
crypto::hash hash = crypto::cn_fast_hash(buf.data(), buf.size());
const char* hash_data = reinterpret_cast<const char*>(&hash);
buf.append(hash_data, addr_checksum_size);
return encode(buf);
}
bool decode_addr(std::string addr, uint64_t& tag, std::string& data)
{
std::string addr_data;
bool r = decode(addr, addr_data);
if (!r) return false;
if (addr_data.size() <= addr_checksum_size) return false;
std::string checksum(addr_checksum_size, '\0');
checksum = addr_data.substr(addr_data.size() - addr_checksum_size);
addr_data.resize(addr_data.size() - addr_checksum_size);
crypto::hash hash = crypto::cn_fast_hash(addr_data.data(), addr_data.size());
std::string expected_checksum(reinterpret_cast<const char*>(&hash), addr_checksum_size);
if (expected_checksum != checksum) return false;
int read = tools::read_varint(addr_data.begin(), addr_data.end(), tag);
if (read <= 0) return false;
data = addr_data.substr(read);
return true;
}
}
}
| mit |
mose/fany | app/controllers/fany/application_controller.rb | 101 | class Fany::ApplicationController < ActionController::Base
def tr
render text: "ok"
end
end | mit |
finleysg/bhmc2 | src/app/features/results/major/major-results.component.ts | 2176 | import { Component, OnInit } from '@angular/core';
import { EventDocument, DocumentService, DocumentType, EventType, Photo, PhotoType } from '../../../core';
import { ConfigService } from '../../../app-config.service';
@Component({
moduleId: module.id,
templateUrl: 'major-results.component.html',
styleUrls: ['major-results.component.css']
})
export class MajorResultsComponent implements OnInit {
currentYear: EventDocument[];
archives: EventDocument[];
clubChampion: Photo;
seniorChampion: Photo;
years: number[];
selectedYear: number;
constructor(private configService: ConfigService,
private documentService: DocumentService) {
}
ngOnInit(): void {
this.years = [2016, 2015, 2014, 2013];
this.selectedYear = 2016;
this.documentService.getDocuments(DocumentType.Results, null, EventType.Major)
.subscribe(docs => {
this.currentYear = docs.filter(d => d.year === this.configService.config.year);
this.archives = docs.filter(d => d.year !== this.configService.config.year);
});
this.documentService.getPhotos(PhotoType.ClubChampion)
.subscribe(pics => {
const f = pics.sort(function(a, b) {
if (a.lastUpdate.isBefore(b.lastUpdate)) {
return 1;
}
if (a.lastUpdate.isAfter(b.lastUpdate)) {
return -1;
}
return 0;
});
if (f && f.length > 0) this.clubChampion = f[0];
});
this.documentService.getPhotos(PhotoType.SeniorChampion)
.subscribe(pics => {
const f = pics.sort(function(a, b) {
if (a.lastUpdate.isBefore(b.lastUpdate)) {
return 1;
}
if (a.lastUpdate.isAfter(b.lastUpdate)) {
return -1;
}
return 0;
});
if (f && f.length > 0) this.seniorChampion = f[0];
});
}
}
| mit |
fotinakis/travis-web | app/components/sync-button.js | 300 | import Ember from 'ember';
const { service } = Ember.inject;
const { alias } = Ember.computed;
export default Ember.Component.extend({
auth: service(),
user: alias('auth.currentUser'),
classNames: ['sync-button'],
actions: {
sync() {
return this.get('user').sync();
}
}
});
| mit |
ZeusTheTrueGod/background-geolocation-console | src/server/database/migrate.js | 776 | /**
* Migrate records created from before Sequalize was introduced
*/
var path = require('path');
var sqlite3 = require('sqlite3').verbose();
var fs = require('fs');
var DB_FILE = path.resolve(__dirname, 'background-geolocation.db');
var LocationModel = require('./LocationModel.js');
var dbh;
if (!fs.existsSync(DB_FILE)) {
console.log('- Failed to find background-geolocation.db: ', DB_FILE);
} else {
dbh = new sqlite3.Database(DB_FILE);
var query = 'SELECT * FROM locations';
var onQuery = function (err, rows) {
if (err) {
console.log('ERROR: ', err);
return;
}
rows.forEach(function (row) {
var id = row.id;
delete row.id;
LocationModel.update(row, { where: { id: id } });
});
};
dbh.all(query, onQuery);
}
| mit |
g-yonchev/TelerikAcademy | Homeworks/C# 2/04. Numeral Systems/08. BinaryShort/BinaryShort.cs | 916 | /* Problem 8. Binary short
Write a program that shows the binary representation of given 16-bit signed integer number (the C# type short).
*/
namespace BinaryShort
{
using System;
class BinaryShort
{
static void Main()
{
Console.Write("Enter signed short: ");
short input = short.Parse(Console.ReadLine());
string result = "";
if (input < 0)
result = "1" + ToBin((short)(32768 + input)).PadLeft(15, '0');
else
result = ToBin(input).PadLeft(16, '0');
Console.WriteLine(result);
}
static string ToBin(short input)
{
string result = "";
while (input > 0)
{
result = (input % 2).ToString() + result;
input = (short)(input / 2);
}
return result;
}
}
} | mit |
mtbbendigo/mtbbendigo | blocks/left_text_right_img_news/edit.php | 1910 | <?php defined('C5_EXECUTE') or die("Access Denied.");
$al = Loader::helper('concrete/asset_library');
$ps = Loader::helper('form/page_selector');
Loader::element('editor_config');
?>
<style type="text/css" media="screen">
.ccm-block-field-group h2 { margin-bottom: 5px; }
.ccm-block-field-group td { vertical-align: middle; }
</style>
<div class="ccm-block-field-group">
<h2>News Article Title</h2>
<?php echo $form->text('field_1_textbox_text', $field_1_textbox_text, array('style' => 'width: 95%;')); ?>
</div>
<div class="ccm-block-field-group">
<h2>News Content</h2>
<?php Loader::element('editor_controls'); ?>
<textarea id="field_2_wysiwyg_content" name="field_2_wysiwyg_content" class="ccm-advanced-editor"><?php echo $field_2_wysiwyg_content; ?></textarea>
</div>
<div class="ccm-block-field-group">
<h2>News Image External Link</h2>
<?php echo $al->image('field_3_image_fID', 'field_3_image_fID', 'Choose Image', $field_3_image); ?>
<table border="0" cellspacing="3" cellpadding="0" style="width: 95%; margin-top: 5px;">
<tr>
<td align="right" nowrap="nowrap"><label for="field_3_image_externalLinkURL">Link to URL:</label> </td>
<td align="left" style="width: 100%;"><?php echo $form->text('field_3_image_externalLinkURL', $field_3_image_externalLinkURL, array('style' => 'width: 100%;')); ?></td>
</tr>
</table>
</div>
<div class="ccm-block-field-group">
<h2>News Image Internal or No Link</h2>
<?php echo $al->image('field_4_image_fID', 'field_4_image_fID', 'Choose Image', $field_4_image); ?>
<table border="0" cellspacing="3" cellpadding="0" style="width: 95%;">
<tr>
<td align="right" nowrap="nowrap"><label for="field_4_image_internalLinkCID">Link to Page:</label> </td>
<td align="left" style="width: 100%;"><?php echo $ps->selectPage('field_4_image_internalLinkCID', $field_4_image_internalLinkCID); ?></td>
</tr>
</table>
</div>
| mit |
nem0/LumixEngine | src/gui/editor/gui_plugins.cpp | 31205 | #include <imgui/imgui.h>
#include "editor/asset_browser.h"
#include "editor/asset_compiler.h"
#include "editor/settings.h"
#include "editor/studio_app.h"
#include "editor/utils.h"
#include "editor/world_editor.h"
#include "engine/crc32.h"
#include "engine/crt.h"
#include "engine/engine.h"
#include "engine/geometry.h"
#include "engine/log.h"
#include "engine/math.h"
#include "engine/os.h"
#include "engine/path.h"
#include "engine/reflection.h"
#include "engine/resource_manager.h"
#include "engine/universe.h"
#include "gui/gui_scene.h"
#include "gui/sprite.h"
#include "renderer/draw2d.h"
#include "renderer/gpu/gpu.h"
#include "renderer/pipeline.h"
#include "renderer/renderer.h"
#include "renderer/texture.h"
using namespace Lumix;
namespace
{
static const ComponentType GUI_RECT_TYPE = reflection::getComponentType("gui_rect");
static const ComponentType GUI_IMAGE_TYPE = reflection::getComponentType("gui_image");
static const ComponentType GUI_TEXT_TYPE = reflection::getComponentType("gui_text");
static const ComponentType GUI_BUTTON_TYPE = reflection::getComponentType("gui_button");
static const ComponentType GUI_RENDER_TARGET_TYPE = reflection::getComponentType("gui_render_target");
struct SpritePlugin final : AssetBrowser::IPlugin, AssetCompiler::IPlugin
{
SpritePlugin(StudioApp& app)
: m_app(app)
{
m_app.getAssetCompiler().registerExtension("spr", Sprite::TYPE);
}
bool compile(const Path& src) override {
return m_app.getAssetCompiler().copyCompile(src);
}
bool canCreateResource() const override { return true; }
const char* getFileDialogFilter() const override { return "Sprite\0*.spr\0"; }
const char* getFileDialogExtensions() const override { return "spr"; }
const char* getDefaultExtension() const override { return "spr"; }
bool createResource(const char* path) override {
os::OutputFile file;
if (!file.open(path)) {
logError("Failed to create ", path);
return false;
}
file << "type \"simple\"";
file.close();
return true;
}
void onGUI(Span<Resource*> resources) override
{
if (resources.length() > 1) return;
Sprite* sprite = (Sprite*)resources[0];
if (!sprite->isReady()) return;
if (ImGui::Button(ICON_FA_SAVE "Save")) saveSprite(*sprite);
ImGui::SameLine();
if (ImGui::Button(ICON_FA_EXTERNAL_LINK_ALT "Open externally")) m_app.getAssetBrowser().openInExternalEditor(sprite);
char tmp[LUMIX_MAX_PATH];
Texture* tex = sprite->getTexture();
copyString(tmp, tex ? tex->getPath().c_str() : "");
ImGuiEx::Label("Texture");
if (m_app.getAssetBrowser().resourceInput("texture", Span(tmp), Texture::TYPE))
{
sprite->setTexture(Path(tmp));
}
static const char* TYPES_STR[] = { "9 patch", "Simple" };
ImGuiEx::Label("type");
if (ImGui::BeginCombo("##type", TYPES_STR[sprite->type]))
{
if (ImGui::Selectable("9 patch")) sprite->type = Sprite::Type::PATCH9;
if (ImGui::Selectable("Simple")) sprite->type = Sprite::Type::SIMPLE;
ImGui::EndCombo();
}
switch (sprite->type)
{
case Sprite::Type::PATCH9:
ImGuiEx::Label("Top");
ImGui::InputInt("##top", &sprite->top);
ImGuiEx::Label("Right");
ImGui::InputInt("##right", &sprite->right);
ImGuiEx::Label("Bottom");
ImGui::InputInt("##bottom", &sprite->bottom);
ImGuiEx::Label("Left");
ImGui::InputInt("##left", &sprite->left);
patch9edit(sprite);
break;
case Sprite::Type::SIMPLE: break;
default: ASSERT(false); break;
}
}
void patch9edit(Sprite* sprite)
{
Texture* texture = sprite->getTexture();
if (sprite->type != Sprite::Type::PATCH9 || !texture || !texture->isReady()) return;
ImVec2 size;
size.x = minimum(ImGui::GetContentRegionAvail().x, texture->width * 2.0f);
size.y = size.x / texture->width * texture->height;
float scale = size.x / texture->width;
ImGui::Dummy(size);
ImDrawList* draw = ImGui::GetWindowDrawList();
ImVec2 a = ImGui::GetItemRectMin();
ImVec2 b = ImGui::GetItemRectMax();
draw->AddImage(texture->handle, a, b);
auto drawHandle = [&](const char* id, const ImVec2& a, const ImVec2& b, int* value, bool vertical) {
const float SIZE = 5;
ImVec2 rect_pos((a.x + b.x) * 0.5f, (a.y + b.y) * 0.5f);
if (vertical)
{
rect_pos.x = a.x + (sprite->left + sprite->right) * 0.5f * scale;
}
else
{
rect_pos.y = a.y + (sprite->top + sprite->bottom) * 0.5f * scale;
}
ImGui::SetCursorScreenPos({ rect_pos.x - SIZE, rect_pos.y - SIZE });
ImGui::InvisibleButton(id, { SIZE * 2, SIZE * 2 });
bool changed = false;
if (ImGui::IsItemActive())
{
static int start_drag_value;
if (ImGui::IsMouseDragging(ImGuiMouseButton_Left))
{
ImVec2 drag = ImGui::GetMouseDragDelta();
if (vertical)
{
*value = int(start_drag_value + drag.y / scale);
}
else
{
*value = int(start_drag_value + drag.x / scale);
}
}
else if (ImGui::IsMouseClicked(0))
{
start_drag_value = *value;
}
changed = true;
}
bool is_hovered = ImGui::IsItemHovered();
draw->AddLine(a, b, 0xffff00ff);
draw->AddRectFilled(ImGui::GetItemRectMin(), ImGui::GetItemRectMax(), is_hovered ? 0xffffffff : 0x77ffFFff);
draw->AddRect(ImGui::GetItemRectMin(), ImGui::GetItemRectMax(), 0xff777777);
return changed;
};
ImVec2 cp = ImGui::GetCursorScreenPos();
drawHandle("left", { a.x + sprite->left * scale, a.y }, { a.x + sprite->left * scale, b.y }, &sprite->left, false);
drawHandle("right", { a.x + sprite->right * scale, a.y }, { a.x + sprite->right * scale, b.y }, &sprite->right, false);
drawHandle("top", { a.x, a.y + sprite->top * scale }, { b.x, a.y + sprite->top * scale }, &sprite->top, true);
drawHandle("bottom", { a.x, a.y + sprite->bottom * scale }, { b.x, a.y + sprite->bottom * scale }, &sprite->bottom, true);
ImGui::SetCursorScreenPos(cp);
}
void saveSprite(Sprite& sprite)
{
if (OutputMemoryStream* file = m_app.getAssetBrowser().beginSaveResource(sprite))
{
bool success = true;
if (!sprite.save(*file))
{
success = false;
logError("Could not save file ", sprite.getPath());
}
m_app.getAssetBrowser().endSaveResource(sprite, *file, success);
}
}
void onResourceUnloaded(Resource* resource) override {}
const char* getName() const override { return "Sprite"; }
ResourceType getResourceType() const override { return Sprite::TYPE; }
StudioApp& m_app;
};
struct GUIEditor final : StudioApp::GUIPlugin
{
enum class EdgeMask
{
LEFT = 1 << 0,
RIGHT = 1 << 1,
TOP = 1 << 2,
BOTTOM = 1 << 3,
CENTER_HORIZONTAL = 1 << 4,
CENTER_VERTICAL = 1 << 5,
ALL = LEFT | RIGHT | TOP | BOTTOM,
HORIZONTAL = LEFT | RIGHT,
VERTICAL = TOP | BOTTOM
};
public:
GUIEditor(StudioApp& app)
: m_app(app)
{
m_toggle_ui.init("GUI Editor", "Toggle gui editor", "gui_editor", "", true);
m_toggle_ui.func.bind<&GUIEditor::onAction>(this);
m_toggle_ui.is_selected.bind<&GUIEditor::isOpen>(this);
app.addWindowAction(&m_toggle_ui);
}
void init() {
Engine& engine = m_app.getEngine();
Renderer& renderer = *static_cast<Renderer*>(engine.getPluginManager().getPlugin("renderer"));
PipelineResource* pres = engine.getResourceManager().load<PipelineResource>(Path("pipelines/gui_editor.pln"));
m_pipeline = Pipeline::create(renderer, pres, "", m_app.getAllocator());
}
~GUIEditor() {
m_app.removeAction(&m_toggle_ui);
}
private:
enum class MouseMode {
NONE,
RESIZE,
MOVE
};
void onSettingsLoaded() override {
m_is_window_open = m_app.getSettings().getValue(Settings::GLOBAL, "is_gui_editor_open", false);
}
void onBeforeSettingsSaved() override {
m_app.getSettings().setValue(Settings::GLOBAL, "is_gui_editor_open", m_is_window_open);
}
void onAction() { m_is_window_open = !m_is_window_open; }
bool isOpen() const { return m_is_window_open; }
MouseMode drawGizmo(Draw2D& draw, GUIScene& scene, const Vec2& canvas_size, const ImVec2& mouse_canvas_pos, Span<const EntityRef> selected_entities)
{
if (selected_entities.length() != 1) return MouseMode::NONE;
EntityRef e = selected_entities[0];
if (!scene.hasGUI(e)) return MouseMode::NONE;
const EntityPtr parent = scene.getUniverse().getParent(e);
const GUIScene::Rect rect = scene.getRectEx(e, canvas_size);
GUIScene::Rect parent_rect = scene.getRectEx(parent, canvas_size);
const float br = scene.getRectBottomRelative(e);
const float tr = scene.getRectTopRelative(e);
const float lr = scene.getRectLeftRelative(e);
const float rr = scene.getRectRightRelative(e);
const Vec2 bottom_right = { rect.x + rect.w, rect.y + rect.h };
draw.addRect({ rect.x, rect.y }, bottom_right, Color::BLACK, 1);
draw.addRect({ rect.x - 1, rect.y - 1 }, bottom_right + Vec2(1, 1), Color::WHITE, 1);
const Vec2 mid = { rect.x + rect.w * 0.5f, rect.y + rect.h * 0.5f };
auto drawAnchor = [&draw](const Vec2& pos, bool top, bool left){
const float SIZE = 10;
const Vec2 h = left ? Vec2(-SIZE, 0) : Vec2(SIZE, 0);
const Vec2 v = top ? Vec2(0, -SIZE) : Vec2(0, SIZE);
draw.addLine(pos, pos + v, Color::RED, 1);
draw.addLine(pos + h, pos + v, Color::RED, 1);
draw.addLine(pos + h, pos, Color::RED, 1);
};
drawAnchor(Vec2(parent_rect.x + parent_rect.w * lr, parent_rect.y + parent_rect.h * tr), true, true);
drawAnchor(Vec2(parent_rect.x + parent_rect.w * lr, parent_rect.y + parent_rect.h * br), false, true);
drawAnchor(Vec2(parent_rect.x + parent_rect.w * rr, parent_rect.y + parent_rect.h * br), false, false);
drawAnchor(Vec2(parent_rect.x + parent_rect.w * rr, parent_rect.y + parent_rect.h * tr), true, false);
auto drawHandle = [&](const Vec2& pos, const ImVec2& mouse_pos) {
const float SIZE = 5;
float dx = pos.x - mouse_pos.x;
float dy = pos.y - mouse_pos.y;
bool is_hovered = fabsf(dx) < SIZE && fabsf(dy) < SIZE;
draw.addRectFilled(pos - Vec2(SIZE, SIZE), pos + Vec2(SIZE, SIZE), is_hovered ? Color::WHITE : Color{0xff, 0xff, 0xff, 0x77});
draw.addRect(pos - Vec2(SIZE, SIZE), pos + Vec2(SIZE, SIZE), Color::BLACK, 1);
return is_hovered && ImGui::IsMouseClicked(0);
};
MouseMode ret = MouseMode::NONE;
if (drawHandle(bottom_right, mouse_canvas_pos))
{
m_bottom_right_start_transform.x = scene.getRectRightPoints(e);
m_bottom_right_start_transform.y = scene.getRectBottomPoints(e);
ret = MouseMode::RESIZE;
}
if (drawHandle(mid, mouse_canvas_pos))
{
m_bottom_right_start_transform.x = scene.getRectRightPoints(e);
m_bottom_right_start_transform.y = scene.getRectBottomPoints(e);
m_top_left_start_move.y = scene.getRectTopPoints(e);
m_top_left_start_move.x = scene.getRectLeftPoints(e);
ret = MouseMode::MOVE;
}
return ret;
}
static Vec2 toLumix(const ImVec2& value)
{
return { value.x, value.y };
}
struct CopyPositionBufferItem
{
const char* prop;
float value;
void set(GUIScene* scene, EntityRef e, const char* prop_name)
{
const bool found = reflection::getPropertyValue(*scene, e, GUI_RECT_TYPE, prop_name, value);
ASSERT(found);
prop = prop_name;
}
} m_copy_position_buffer[8];
int m_copy_position_buffer_count = 0;
void copy(EntityRef e, u8 mask, WorldEditor& editor)
{
GUIScene* scene = (GUIScene*)editor.getUniverse()->getScene("gui");
m_copy_position_buffer_count = 0;
if (mask & (u8)EdgeMask::TOP)
{
m_copy_position_buffer[m_copy_position_buffer_count].set(scene, e, "Top Points");
m_copy_position_buffer[m_copy_position_buffer_count+1].set(scene, e, "Top Relative");
m_copy_position_buffer_count += 2;
}
if (mask & (u8)EdgeMask::BOTTOM)
{
m_copy_position_buffer[m_copy_position_buffer_count].set(scene, e, "Bottom Points");
m_copy_position_buffer[m_copy_position_buffer_count + 1].set(scene, e, "Bottom Relative");
m_copy_position_buffer_count += 2;
}
if (mask & (u8)EdgeMask::LEFT)
{
m_copy_position_buffer[m_copy_position_buffer_count].set(scene, e, "Left Points");
m_copy_position_buffer[m_copy_position_buffer_count + 1].set(scene, e, "Left Relative");
m_copy_position_buffer_count += 2;
}
if (mask & (u8)EdgeMask::RIGHT)
{
m_copy_position_buffer[m_copy_position_buffer_count].set(scene, e, "Right Points");
m_copy_position_buffer[m_copy_position_buffer_count + 1].set(scene, e, "Right Relative");
m_copy_position_buffer_count += 2;
}
}
void paste(EntityRef e, WorldEditor& editor)
{
editor.beginCommandGroup("gui_editor_paste");
for (int i = 0; i < m_copy_position_buffer_count; ++i)
{
CopyPositionBufferItem& item = m_copy_position_buffer[i];
editor.setProperty(GUI_RECT_TYPE, "", -1, item.prop, Span(&e, 1), item.value);
}
editor.endCommandGroup();
}
void onWindowGUI() override
{
if (!m_is_window_open) return;
if (ImGui::Begin("GUIEditor", &m_is_window_open))
{
WorldEditor& editor = m_app.getWorldEditor();
ImVec2 mouse_canvas_pos = ImGui::GetMousePos();
mouse_canvas_pos.x -= ImGui::GetCursorScreenPos().x;
mouse_canvas_pos.y -= ImGui::GetCursorScreenPos().y;
ImVec2 size = ImGui::GetContentRegionAvail();
if (!m_pipeline->isReady() || size.x == 0 || size.y == 0) {
ImGui::End();
return;
}
m_pipeline->setUniverse(editor.getUniverse());
GUIScene* scene = (GUIScene*)editor.getUniverse()->getScene("gui");
scene->render(*m_pipeline, { size.x, size.y }, false);
MouseMode new_mode = drawGizmo(m_pipeline->getDraw2D(), *scene, { size.x, size.y }, mouse_canvas_pos, editor.getSelectedEntities());
if (m_mouse_mode == MouseMode::NONE) m_mouse_mode = new_mode; //-V1051
if (ImGui::IsMouseReleased(0)) m_mouse_mode = MouseMode::NONE;
if (editor.getSelectedEntities().size() == 1)
{
EntityRef e = editor.getSelectedEntities()[0];
switch (m_mouse_mode)
{
case MouseMode::NONE: break;
case MouseMode::RESIZE:
{
editor.beginCommandGroup("gui_mouse_resize");
float b = m_bottom_right_start_transform.y + ImGui::GetMouseDragDelta(0).y;
setRectProperty(e, "Bottom Points", b, editor);
float r = m_bottom_right_start_transform.x + ImGui::GetMouseDragDelta(0).x;
setRectProperty(e, "Right Points", r, editor);
editor.endCommandGroup();
}
break;
case MouseMode::MOVE:
{
editor.beginCommandGroup("gui_mouse_move");
float b = m_bottom_right_start_transform.y + ImGui::GetMouseDragDelta(0).y;
setRectProperty(e, "Bottom Points", b, editor);
float r = m_bottom_right_start_transform.x + ImGui::GetMouseDragDelta(0).x;
setRectProperty(e, "Right Points", r, editor);
float t = m_top_left_start_move.y + ImGui::GetMouseDragDelta(0).y;
setRectProperty(e, "Top Points", t, editor);
float l = m_top_left_start_move.x + ImGui::GetMouseDragDelta(0).x;
setRectProperty(e, "Left Points", l, editor);
editor.endCommandGroup();
}
break;
}
}
Viewport vp = {};
vp.w = (int)size.x;
vp.h = (int)size.y;
m_pipeline->setViewport(vp);
if (m_pipeline->render(true)) {
m_texture_handle = m_pipeline->getOutput();
if(m_texture_handle) {
if (gpu::isOriginBottomLeft()) {
ImGui::Image(m_texture_handle, size, ImVec2(0, 1), ImVec2(1, 0));
}
else {
ImGui::Image(m_texture_handle, size);
}
}
}
if (ImGui::IsMouseClicked(0) && ImGui::IsItemHovered() && m_mouse_mode == MouseMode::NONE)
{
const Array<EntityRef>& selected = editor.getSelectedEntities();
EntityPtr e = scene->getRectAtEx(toLumix(mouse_canvas_pos), toLumix(size), selected.empty() ? INVALID_ENTITY : selected[0]);
if (!e.isValid()) {
e = scene->getRectAtEx(toLumix(mouse_canvas_pos), toLumix(size), INVALID_ENTITY);
}
if (e.isValid()) {
EntityRef r = (EntityRef)e;
editor.selectEntities(Span(&r, 1), false);
}
}
bool has_rect = false;
if (editor.getSelectedEntities().size() == 1)
{
has_rect = editor.getUniverse()->hasComponent(editor.getSelectedEntities()[0], GUI_RECT_TYPE);
}
if (has_rect && ImGui::BeginPopupContextItem("context"))
{
EntityRef e = editor.getSelectedEntities()[0];
if (ImGui::BeginMenu("Create child"))
{
if (ImGui::MenuItem("Button")) createChild(e, GUI_BUTTON_TYPE, editor);
if (ImGui::MenuItem("Image")) createChild(e, GUI_IMAGE_TYPE, editor);
if (ImGui::MenuItem("Rect")) createChild(e, GUI_RECT_TYPE, editor);
if (ImGui::MenuItem("Text")) createChild(e, GUI_TEXT_TYPE, editor);
if (ImGui::MenuItem("Render target")) createChild(e, GUI_RENDER_TARGET_TYPE, editor);
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Align"))
{
if (ImGui::MenuItem("Top")) align(e, (u8)EdgeMask::TOP, editor);
if (ImGui::MenuItem("Right")) align(e, (u8)EdgeMask::RIGHT, editor);
if (ImGui::MenuItem("Bottom")) align(e, (u8)EdgeMask::BOTTOM, editor);
if (ImGui::MenuItem("Left")) align(e, (u8)EdgeMask::LEFT, editor);
if (ImGui::MenuItem("Center horizontal")) align(e, (u8)EdgeMask::CENTER_HORIZONTAL, editor);
if (ImGui::MenuItem("Center vertical")) align(e, (u8)EdgeMask::CENTER_VERTICAL, editor);
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Expand"))
{
if (ImGui::MenuItem("All")) expand(e, (u8)EdgeMask::ALL, editor);
if (ImGui::MenuItem("Top")) expand(e, (u8)EdgeMask::TOP, editor);
if (ImGui::MenuItem("Right")) expand(e, (u8)EdgeMask::RIGHT, editor);
if (ImGui::MenuItem("Bottom")) expand(e, (u8)EdgeMask::BOTTOM, editor);
if (ImGui::MenuItem("Left")) expand(e, (u8)EdgeMask::LEFT, editor);
if (ImGui::MenuItem("Horizontal")) expand(e, (u8)EdgeMask::HORIZONTAL, editor);
if (ImGui::MenuItem("Vertical")) expand(e, (u8)EdgeMask::VERTICAL, editor);
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Make relative"))
{
if (ImGui::MenuItem("All")) makeRelative(e, toLumix(size), (u8)EdgeMask::ALL, editor);
if (ImGui::MenuItem("Top")) makeRelative(e, toLumix(size), (u8)EdgeMask::TOP, editor);
if (ImGui::MenuItem("Right")) makeRelative(e, toLumix(size), (u8)EdgeMask::RIGHT, editor);
if (ImGui::MenuItem("Bottom")) makeRelative(e, toLumix(size), (u8)EdgeMask::BOTTOM, editor);
if (ImGui::MenuItem("Left")) makeRelative(e, toLumix(size), (u8)EdgeMask::LEFT, editor);
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Make absolute"))
{
if (ImGui::MenuItem("All")) makeAbsolute(e, toLumix(size), (u8)EdgeMask::ALL, editor);
if (ImGui::MenuItem("Top")) makeAbsolute(e, toLumix(size), (u8)EdgeMask::TOP, editor);
if (ImGui::MenuItem("Right")) makeAbsolute(e, toLumix(size), (u8)EdgeMask::RIGHT, editor);
if (ImGui::MenuItem("Bottom")) makeAbsolute(e, toLumix(size), (u8)EdgeMask::BOTTOM, editor);
if (ImGui::MenuItem("Left")) makeAbsolute(e, toLumix(size), (u8)EdgeMask::LEFT, editor);
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Anchor")) {
if (ImGui::MenuItem("Center")) anchor(e, (u8)EdgeMask::CENTER_HORIZONTAL | (u8)EdgeMask::CENTER_VERTICAL, editor);
if (ImGui::MenuItem("Left middle")) anchor(e, (u8)EdgeMask::LEFT | (u8)EdgeMask::CENTER_VERTICAL, editor);
if (ImGui::MenuItem("Right middle")) anchor(e, (u8)EdgeMask::RIGHT | (u8)EdgeMask::CENTER_VERTICAL, editor);
if (ImGui::MenuItem("Top center")) anchor(e, (u8)EdgeMask::TOP | (u8)EdgeMask::CENTER_HORIZONTAL, editor);
if (ImGui::MenuItem("Bottom center")) anchor(e, (u8)EdgeMask::BOTTOM | (u8)EdgeMask::CENTER_HORIZONTAL, editor);
if (ImGui::MenuItem("Top left")) anchor(e, (u8)EdgeMask::TOP | (u8)EdgeMask::LEFT, editor);
if (ImGui::MenuItem("Top right")) anchor(e, (u8)EdgeMask::TOP | (u8)EdgeMask::RIGHT, editor);
if (ImGui::MenuItem("Bottom left")) anchor(e, (u8)EdgeMask::BOTTOM | (u8)EdgeMask::LEFT, editor);
if (ImGui::MenuItem("Bottom right")) anchor(e, (u8)EdgeMask::BOTTOM | (u8)EdgeMask::RIGHT, editor);
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Copy position"))
{
if (ImGui::MenuItem("All")) copy(e, (u8)EdgeMask::ALL, editor);
if (ImGui::MenuItem("Top")) copy(e, (u8)EdgeMask::TOP, editor);
if (ImGui::MenuItem("Right")) copy(e, (u8)EdgeMask::RIGHT, editor);
if (ImGui::MenuItem("Bottom")) copy(e, (u8)EdgeMask::BOTTOM, editor);
if (ImGui::MenuItem("Left")) copy(e, (u8)EdgeMask::LEFT, editor);
if (ImGui::MenuItem("Horizontal")) copy(e, (u8)EdgeMask::HORIZONTAL, editor);
if (ImGui::MenuItem("Vertical")) copy(e, (u8)EdgeMask::VERTICAL, editor);
ImGui::EndMenu();
}
if (ImGui::MenuItem("Paste")) paste(e, editor);
if (ImGui::BeginMenu("Layout")) {
static int cols = 1;
static int row_height = 20;
static int row_spacing = 0;
static int col_spacing = 0;
ImGui::InputInt("Columns", &cols);
ImGui::InputInt("Row height", &row_height);
ImGui::InputInt("Row spacing", &row_spacing);
ImGui::InputInt("Column spacing", &col_spacing);
if (editor.getSelectedEntities().empty()) {
ImGui::TextUnformatted("Please select an entity");
}
else {
if (ImGui::Button("Do")) {
layout(cols, row_height, row_spacing, col_spacing, editor);
}
}
ImGui::EndMenu();
}
ImGui::EndPopup();
}
}
ImGui::End();
}
void layout(u32 cols, u32 row_height, u32 row_spacing, u32 col_spacing, WorldEditor& editor) {
const Array<EntityRef>& selected = editor.getSelectedEntities();
ASSERT(!selected.empty());
ASSERT(cols > 0);
const Universe& universe = *editor.getUniverse();
const EntityRef e = selected[0];
editor.beginCommandGroup("layout_gui");
u32 y = 0;
u32 col = 0;
for (EntityPtr child = universe.getFirstChild(e); child.isValid(); child = universe.getNextSibling((EntityRef)child)) {
const EntityRef ch = (EntityRef)child;
if (!universe.hasComponent(ch, GUI_RECT_TYPE)) continue;
setRectProperty(ch, "Top Points", (float)y, editor);
setRectProperty(ch, "Bottom Points", (float)y + row_height, editor);
const float l = col / (float)cols;
const float r = (col + 1) / (float)cols;
setRectProperty(ch, "Left Relative", l, editor);
setRectProperty(ch, "Right Points", -(float)(col_spacing / 2), editor);
setRectProperty(ch, "Left Points", (float)((col_spacing + 1) / 2), editor);
setRectProperty(ch, "Right Relative", r, editor);
++col;
if (col == cols) {
col = 0;
y += row_height + row_spacing;
}
}
editor.endCommandGroup();
}
void createChild(EntityRef entity, ComponentType child_type, WorldEditor& editor)
{
editor.beginCommandGroup("create_gui_rect_child");
EntityRef child = editor.addEntity();
editor.makeParent(entity, child);
editor.selectEntities(Span(&child, 1), false);
editor.addComponent(Span(&child, 1), GUI_RECT_TYPE);
if (child_type != GUI_RECT_TYPE) {
editor.addComponent(Span(&child, 1), child_type);
}
editor.endCommandGroup();
}
void setRectProperty(EntityRef e, const char* prop_name, float value, WorldEditor& editor)
{
editor.setProperty(GUI_RECT_TYPE, "", -1, prop_name, Span(&e, 1), value);
}
void makeAbsolute(EntityRef entity, const Vec2& canvas_size, u8 mask, WorldEditor& editor) {
GUIScene* scene = (GUIScene*)editor.getUniverse()->getScene("gui");
EntityRef parent = (EntityRef)scene->getUniverse().getParent(entity);
GUIScene::Rect parent_rect = scene->getRectEx(parent, canvas_size);
GUIScene::Rect child_rect = scene->getRectEx(entity, canvas_size);
editor.beginCommandGroup("make_gui_rect_absolute");
if (mask & (u8)EdgeMask::TOP) {
setRectProperty(entity, "Top Relative", 0, editor);
setRectProperty(entity, "Top Points", child_rect.y - parent_rect.y, editor);
}
if (mask & (u8)EdgeMask::LEFT) {
setRectProperty(entity, "Left Relative", 0, editor);
setRectProperty(entity, "Left Points", child_rect.x - parent_rect.x, editor);
}
if (mask & (u8)EdgeMask::RIGHT) {
setRectProperty(entity, "Right Relative", 0, editor);
setRectProperty(entity, "Right Points", child_rect.x + child_rect.w - parent_rect.x, editor);
}
if (mask & (u8)EdgeMask::BOTTOM) {
setRectProperty(entity, "Bottom Relative", 0, editor);
setRectProperty(entity, "Bottom Points", child_rect.y + child_rect.h - parent_rect.y, editor);
}
editor.endCommandGroup();
}
void anchor(EntityRef entity, u8 mask, WorldEditor& editor) {
editor.beginCommandGroup("anchor_gui_rect");
if (mask & (u8)EdgeMask::TOP) {
setRectProperty(entity, "Bottom Relative", 0, editor);
setRectProperty(entity, "Top Relative", 0, editor);
}
if (mask & (u8)EdgeMask::LEFT) {
setRectProperty(entity, "Right Relative", 0, editor);
setRectProperty(entity, "Left Relative", 0, editor);
}
if (mask & (u8)EdgeMask::RIGHT) {
setRectProperty(entity, "Left Relative", 1, editor);
setRectProperty(entity, "Right Relative", 1, editor);
}
if (mask & (u8)EdgeMask::BOTTOM) {
setRectProperty(entity, "Top Relative", 1, editor);
setRectProperty(entity, "Bottom Relative", 1, editor);
}
if (mask & (u8)EdgeMask::CENTER_VERTICAL) {
setRectProperty(entity, "Top Relative", 0.5f, editor);
setRectProperty(entity, "Bottom Relative", 0.5f, editor);
}
if (mask & (u8)EdgeMask::CENTER_HORIZONTAL) {
setRectProperty(entity, "Left Relative", 0.5f, editor);
setRectProperty(entity, "Right Relative", 0.5f, editor);
}
editor.endCommandGroup();
}
void align(EntityRef entity, u8 mask, WorldEditor& editor)
{
GUIScene* scene = (GUIScene*)editor.getUniverse()->getScene("gui");
editor.beginCommandGroup("align_gui_rect");
float br = scene->getRectBottomRelative(entity);
float bp = scene->getRectBottomPoints(entity);
float tr = scene->getRectTopRelative(entity);
float tp = scene->getRectTopPoints(entity);
float rr = scene->getRectRightRelative(entity);
float rp = scene->getRectRightPoints(entity);
float lr = scene->getRectLeftRelative(entity);
float lp = scene->getRectLeftPoints(entity);
if (mask & (u8)EdgeMask::TOP)
{
setRectProperty(entity, "Bottom Relative", br - tr, editor);
setRectProperty(entity, "Bottom Points", bp - tp, editor);
setRectProperty(entity, "Top Relative", 0, editor);
setRectProperty(entity, "Top Points", 0, editor);
}
if (mask & (u8)EdgeMask::LEFT)
{
setRectProperty(entity, "Right Relative", rr - lr, editor);
setRectProperty(entity, "Right Points", rp - lp, editor);
setRectProperty(entity, "Left Relative", 0, editor);
setRectProperty(entity, "Left Points", 0, editor);
}
if (mask & (u8)EdgeMask::RIGHT)
{
setRectProperty(entity, "Left Relative", lr + 1 - rr, editor);
setRectProperty(entity, "Left Points", lp - rp, editor);
setRectProperty(entity, "Right Relative", 1, editor);
setRectProperty(entity, "Right Points", 0, editor);
}
if (mask & (u8)EdgeMask::BOTTOM)
{
setRectProperty(entity, "Top Relative", tr + 1 - br, editor);
setRectProperty(entity, "Top Points", tp - bp, editor);
setRectProperty(entity, "Bottom Relative", 1, editor);
setRectProperty(entity, "Bottom Points", 0, editor);
}
if (mask & (u8)EdgeMask::CENTER_VERTICAL)
{
setRectProperty(entity, "Top Relative", 0.5f - (br - tr) * 0.5f, editor);
setRectProperty(entity, "Top Points", -(bp - tp) * 0.5f, editor);
setRectProperty(entity, "Bottom Relative", 0.5f + (br - tr) * 0.5f, editor);
setRectProperty(entity, "Bottom Points", (bp - tp) * 0.5f, editor);
}
if (mask & (u8)EdgeMask::CENTER_HORIZONTAL)
{
setRectProperty(entity, "Left Relative", 0.5f - (rr - lr) * 0.5f, editor);
setRectProperty(entity, "Left Points", -(rp - lp) * 0.5f, editor);
setRectProperty(entity, "Right Relative", 0.5f + (rr - lr) * 0.5f, editor);
setRectProperty(entity, "Right Points", (rp - lp) * 0.5f, editor);
}
editor.endCommandGroup();
}
void expand(EntityRef entity, u8 mask, WorldEditor& editor)
{
editor.beginCommandGroup("expand_gui_rect");
if (mask & (u8)EdgeMask::TOP)
{
setRectProperty(entity, "Top Points", 0, editor);
setRectProperty(entity, "Top Relative", 0, editor);
}
if (mask & (u8)EdgeMask::RIGHT)
{
setRectProperty(entity, "Right Points", 0, editor);
setRectProperty(entity, "Right Relative", 1, editor);
}
if (mask & (u8)EdgeMask::LEFT)
{
setRectProperty(entity, "Left Points", 0, editor);
setRectProperty(entity, "Left Relative", 0, editor);
}
if (mask & (u8)EdgeMask::BOTTOM)
{
setRectProperty(entity, "Bottom Points", 0, editor);
setRectProperty(entity, "Bottom Relative", 1, editor);
}
editor.endCommandGroup();
}
void makeRelative(EntityRef entity, const Vec2& canvas_size, u8 mask, WorldEditor& editor)
{
GUIScene* scene = (GUIScene*)editor.getUniverse()->getScene("gui");
EntityPtr parent = scene->getUniverse().getParent(entity);
GUIScene::Rect parent_rect = scene->getRectEx(parent, canvas_size);
GUIScene::Rect child_rect = scene->getRectEx(entity, canvas_size);
editor.beginCommandGroup("make_gui_rect_relative");
if (mask & (u8)EdgeMask::TOP)
{
setRectProperty(entity, "Top Points", 0, editor);
setRectProperty(entity, "Top Relative", (child_rect.y - parent_rect.y) / parent_rect.h, editor);
}
if (mask & (u8)EdgeMask::RIGHT)
{
setRectProperty(entity, "Right Points", 0, editor);
setRectProperty(entity, "Right Relative", (child_rect.x + child_rect.w - parent_rect.x) / parent_rect.w, editor);
}
if (mask & (u8)EdgeMask::LEFT)
{
setRectProperty(entity, "Left Points", 0, editor);
setRectProperty(entity, "Left Relative", (child_rect.x - parent_rect.x) / parent_rect.w, editor);
}
if (mask & (u8)EdgeMask::BOTTOM)
{
setRectProperty(entity, "Bottom Points", 0, editor);
setRectProperty(entity, "Bottom Relative", (child_rect.y + child_rect.h - parent_rect.y) / parent_rect.h, editor);
}
editor.endCommandGroup();
}
void update(float) override {}
const char* getName() const override { return "gui_editor"; }
StudioApp& m_app;
Action m_toggle_ui;
UniquePtr<Pipeline> m_pipeline;
bool m_is_window_open = false;
gpu::TextureHandle m_texture_handle;
MouseMode m_mouse_mode = MouseMode::NONE;
Vec2 m_bottom_right_start_transform;
Vec2 m_top_left_start_move;
};
struct StudioAppPlugin : StudioApp::IPlugin
{
StudioAppPlugin(StudioApp& app)
: m_app(app)
, m_sprite_plugin(app)
, m_gui_editor(app)
{
}
const char* getName() const override { return "gui"; }
bool dependsOn(IPlugin& plugin) const override { return equalStrings(plugin.getName(), "renderer"); }
void init() override {
m_gui_editor.init();
m_app.addPlugin(m_gui_editor);
m_app.getAssetBrowser().addPlugin(m_sprite_plugin);
const char* sprite_exts[] = {"spr", nullptr};
m_app.getAssetCompiler().addPlugin(m_sprite_plugin, sprite_exts);
}
bool showGizmo(UniverseView&, ComponentUID) override { return false; }
~StudioAppPlugin() {
m_app.removePlugin(m_gui_editor);
m_app.getAssetCompiler().removePlugin(m_sprite_plugin);
m_app.getAssetBrowser().removePlugin(m_sprite_plugin);
}
StudioApp& m_app;
GUIEditor m_gui_editor;
SpritePlugin m_sprite_plugin;
};
} // anonymous namespace
LUMIX_STUDIO_ENTRY(gui)
{
IAllocator& allocator = app.getAllocator();
return LUMIX_NEW(allocator, StudioAppPlugin)(app);
}
| mit |
emonkak/js-enumerable | src/hof/groupBy.ts | 758 | import groupByFn from '../groupBy';
export default function groupBy<TSource, TKey>(keySelector: (element: TSource) => TKey): (source: Iterable<TSource>) => Iterable<[TKey, TSource]>;
export default function groupBy<TSource, TKey, TElement>(keySelector: (element: TSource) => TKey, elementSelector: (element: TSource) => TElement): (source: Iterable<TSource>) => Iterable<[TKey, TElement]>;
export default function groupBy<TSource, TKey, TElement, TResult>(keySelector: (element: TSource) => TKey, elementSelector?: (element: TSource) => TElement, resultSelector?: (key: TKey, elements: TElement[]) => TResult): (source: Iterable<TSource>) => Iterable<TResult> {
return (source) => groupByFn.call(source, keySelector, elementSelector, resultSelector);
}
| mit |
bob2000/BookReviews | BookReviews.AccountsManager.Nh/NhModel/Group.cs | 1284 | using BookReviews.AccountsManager.Nh.NhModel.Mappings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BookReviews.AccountsManager.Nh.NhModel
{
public class Group
{
public Group()
{
Claims = new List<GroupClaim>();
Accounts = new List<AccountGroup>();
}
public Group(long idGroup)
{
IDGroup = idGroup;
}
public virtual void Create(string name)
{
Name = name;
}
public virtual void UpdateName(string name)
{
Name = name;
}
public virtual void UpdateClaims(IList<GroupClaim> claims)
{
Claims = claims;
}
public virtual long IDGroup { get; protected internal set; }
public virtual string Name { get; protected internal set; }
//public virtual IList<Claim> Claims { get; protected internal set; }
public virtual IList<GroupClaim> Claims { get; protected internal set; }
public virtual IList<AccountGroup> Accounts { get; protected internal set; }
//public virtual Iesi.Collections.Generic.ISet<Account> Accounts { get; protected internal set; }
}
}
| mit |
michalper/ipresso_api | tests/SegmentationTest.php | 5351 | <?php
use PHPUnit\Framework\TestCase;
/**
* Class SegmentationTest
*/
class SegmentationTest extends TestCase
{
public static $config = [
'url' => '',
'login' => '',
'password' => '',
'customerKey' => '',
'token' => '',
];
/**
* @var iPresso
*/
private $class;
/**
* SegmentationTest constructor.
* @param string|null $name
* @param array $data
* @param string $dataName
* @throws Exception
*/
public function __construct(string $name = null, array $data = [], string $dataName = '')
{
parent::__construct($name, $data, $dataName);
$this->class = (new iPresso())
->setLogin(self::$config['login'])
->setPassword(self::$config['password'])
->setCustomerKey(self::$config['customerKey'])
->setToken(self::$config['token'])
->setUrl(self::$config['url']);
}
public function testSegmentationClass()
{
$this->assertInstanceOf(\iPresso\Service\SegmentationService::class, $this->class->segmentation);
}
/**
* @throws Exception
*/
public function testSegmentationAddWrong()
{
$type = new \iPresso\Model\Segmentation();
$this->expectException(Exception::class);
$type->getSegmentation();
}
/**
* @depends testSegmentationClass
* @throws Exception
*/
public function testSegmentationGetAll()
{
$response = $this->class->segmentation->get();
$this->assertInstanceOf(\iPresso\Service\Response::class, $response);
$this->assertEquals(\iPresso\Service\Response::STATUS_OK, $response->getCode());
$this->assertObjectHasAttribute('segmentation', $response->getData());
}
/**
* @return integer
* @throws Exception
*/
public function testSegmentationAdd()
{
$type = new \iPresso\Model\Segmentation();
$type->setName('Unit tests');
$type->setLiveTime(1);
$response = $this->class->segmentation->add($type);
$this->assertInstanceOf(\iPresso\Service\Response::class, $response);
$this->assertContains($response->getCode(), [\iPresso\Service\Response::STATUS_CREATED]);
$this->assertObjectHasAttribute('id', $response->getData());
return (integer)$response->getData()->id;
}
/**
* @return integer
* @throws Exception
*/
public function testContactAdd()
{
$contact = new \iPresso\Model\Contact();
$contact->setEmail('[email protected]');
$response = $this->class->contact->add($contact);
$this->assertInstanceOf(\iPresso\Service\Response::class, $response);
$this->assertContains($response->getCode(), [\iPresso\Service\Response::STATUS_OK]);
$this->assertObjectHasAttribute('contact', $response->getData());
$contact = reset($response->getData()->contact);
$this->assertContains($contact->code, [\iPresso\Service\Response::STATUS_CREATED, \iPresso\Service\Response::STATUS_FOUND, \iPresso\Service\Response::STATUS_SEE_OTHER]);
$this->assertGreaterThan(0, $contact->id);
return (integer)$contact->id;
}
/**
* @depends testSegmentationAdd
* @depends testContactAdd
* @param integer $idSegmentation
* @param int $idContact
* @throws Exception
*/
public function testAddContactToSegmentation(int $idSegmentation, int $idContact)
{
$this->assertGreaterThan(0, $idSegmentation);
$this->assertGreaterThan(0, $idContact);
$segmentation = new \iPresso\Model\Segmentation();
$segmentation->addContact($idContact);
$segmentation->setContactOrigin(\iPresso\Model\Segmentation::CONTACT_ORIGIN_ID);
$response = $this->class->segmentation->addContact($idSegmentation, $segmentation);
$this->assertInstanceOf(\iPresso\Service\Response::class, $response);
$this->assertContains($response->getCode(), [\iPresso\Service\Response::STATUS_CREATED]);
}
/**
* @depends testSegmentationAdd
* @depends testContactAdd
* @param int $idSegmentation
* @param int $idContact
* @throws Exception
*/
public function testGetContactInSegmentation(int $idSegmentation, int $idContact)
{
$this->assertGreaterThan(0, $idSegmentation);
$this->assertGreaterThan(0, $idContact);
$response = $this->class->segmentation->getContact($idSegmentation);
$this->assertInstanceOf(\iPresso\Service\Response::class, $response);
$this->assertContains($response->getCode(), [\iPresso\Service\Response::STATUS_OK]);
$this->assertObjectHasAttribute('contact', $response->getData());
$this->assertNotEmpty($response->getData()->contact->$idContact);
}
/**
* @depends testSegmentationAdd
* @param int $idSegmentation
* @throws Exception
*/
public function testDeleteSegmentation(int $idSegmentation)
{
$this->assertGreaterThan(0, $idSegmentation);
$response = $this->class->segmentation->delete($idSegmentation);
$this->assertInstanceOf(\iPresso\Service\Response::class, $response);
$this->assertContains($response->getCode(), [\iPresso\Service\Response::STATUS_OK]);
}
} | mit |
tcdev0/ecb | src/KIJ/Bundle/EcbBundle/Ecb/ParserInterface.php | 199 | <?php
namespace KIJ\Bundle\EcbBundle\Ecb;
interface ParserInterface
{
/**
* @param $rawData
* @return mixed
*/
function parse($rawData);
} | mit |
archimatetool/archi | com.archimatetool.editor/src/com/archimatetool/editor/actions/ShowPropertiesManagerHandler.java | 1198 | /**
* This program and the accompanying materials
* are made available under the terms of the License
* which accompanies this distribution in the file LICENSE.txt
*/
package com.archimatetool.editor.actions;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.handlers.HandlerUtil;
import com.archimatetool.editor.propertysections.UserPropertiesManagerDialog;
import com.archimatetool.model.IArchimateModel;
/**
* Show Properties Manager
*
* @author Phillip Beauvoir
*/
public class ShowPropertiesManagerHandler extends AbstractHandler {
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
IWorkbenchPart part = HandlerUtil.getActivePart(event);
IArchimateModel model = part != null ? part.getAdapter(IArchimateModel.class) : null;
if(model != null) {
UserPropertiesManagerDialog dialog = new UserPropertiesManagerDialog(HandlerUtil.getActiveShell(event), model);
dialog.open();
}
return null;
}
}
| mit |
starkandwayne/shield | db/schema_v6.go | 2280 | package db
import (
"github.com/shieldproject/shield/timespec"
)
type v6Schema struct{}
func (s v6Schema) Deploy(db *DB) error {
var err error
// set the tenant_uuid column to NOT NULL
err = db.Exec(`CREATE TABLE jobs_new (
uuid UUID PRIMARY KEY,
target_uuid UUID NOT NULL,
store_uuid UUID NOT NULL,
tenant_uuid UUID NOT NULL,
name TEXT,
summary TEXT,
schedule TEXT NOT NULL,
keep_n INTEGER NOT NULL DEFAULT 0,
keep_days INTEGER NOT NULL DEFAULT 0,
next_run INTEGER DEFAULT 0,
priority INTEGER DEFAULT 50,
paused BOOLEAN,
fixed_key INTEGER DEFAULT 0,
healthy BOOLEAN
)`)
if err != nil {
return err
}
err = db.Exec(`INSERT INTO jobs_new (uuid, target_uuid, store_uuid, tenant_uuid,
schedule, next_run, keep_days,
priority, paused, name, summary, healthy)
SELECT j.uuid, j.target_uuid, j.store_uuid, j.tenant_uuid,
j.schedule, j.next_run, r.expiry / 86400,
j.priority, j.paused, j.name, j.summary, j.healthy
FROM jobs j INNER JOIN retention r
ON j.retention_uuid = r.uuid`)
if err != nil {
return err
}
err = db.Exec(`DROP TABLE jobs`)
if err != nil {
return err
}
err = db.Exec(`ALTER TABLE jobs_new RENAME TO jobs`)
if err != nil {
return err
}
err = db.Exec(`DROP TABLE retention`)
if err != nil {
return err
}
/* fix keep_n on all jobs */
jobs, err := db.GetAllJobs(nil)
if err != nil {
return err
}
for _, job := range jobs {
if sched, err := timespec.Parse(job.Schedule); err != nil {
job.KeepN = sched.KeepN(job.KeepDays)
err = db.UpdateJob(job)
if err != nil {
return err
}
}
}
err = db.Exec(`UPDATE schema_info set version = 6`)
if err != nil {
return err
}
return nil
}
| mit |
arindampaul007/arindampaul007.github.io | js/bootstrap.js | 69710 | pop/*!
* Bootstrap v3.3.7 (http://getbootstrap.com)
* Copyright 2011-2016 Twitter, Inc.
* Licensed under the MIT license
*/
if (typeof jQuery === 'undefined') {
throw new Error('Bootstrap\'s JavaScript requires jQuery')
}
+function ($) {
'use strict';
var version = $.fn.jquery.split(' ')[0].split('.')
if ((version[0] < 2 && version[1] < 9) || (version[0] == 1 && version[1] == 9 && version[2] < 1) || (version[0] > 3)) {
throw new Error('Bootstrap\'s JavaScript requires jQuery version 1.9.1 or higher, but lower than version 4')
}
}(jQuery);
/* ========================================================================
* Bootstrap: transition.js v3.3.7
* http://getbootstrap.com/javascript/#transitions
* ========================================================================
* Copyright 2011-2016 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/)
// ============================================================
function transitionEnd() {
var el = document.createElement('bootstrap')
var transEndEventNames = {
WebkitTransition : 'webkitTransitionEnd',
MozTransition : 'transitionend',
OTransition : 'oTransitionEnd otransitionend',
transition : 'transitionend'
}
for (var name in transEndEventNames) {
if (el.style[name] !== undefined) {
return { end: transEndEventNames[name] }
}
}
return false // explicit for ie8 ( ._.)
}
// http://blog.alexmaccaw.com/css-transitions
$.fn.emulateTransitionEnd = function (duration) {
var called = false
var $el = this
$(this).one('bsTransitionEnd', function () { called = true })
var callback = function () { if (!called) $($el).trigger($.support.transition.end) }
setTimeout(callback, duration)
return this
}
$(function () {
$.support.transition = transitionEnd()
if (!$.support.transition) return
$.event.special.bsTransitionEnd = {
bindType: $.support.transition.end,
delegateType: $.support.transition.end,
handle: function (e) {
if ($(e.target).is(this)) return e.handleObj.handler.apply(this, arguments)
}
}
})
}(jQuery);
/* ========================================================================
* Bootstrap: alert.js v3.3.7
* http://getbootstrap.com/javascript/#alerts
* ========================================================================
* Copyright 2011-2016 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// ALERT CLASS DEFINITION
// ======================
var dismiss = '[data-dismiss="alert"]'
var Alert = function (el) {
$(el).on('click', dismiss, this.close)
}
Alert.VERSION = '3.3.7'
Alert.TRANSITION_DURATION = 150
Alert.prototype.close = function (e) {
var $this = $(this)
var selector = $this.attr('data-target')
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
}
var $parent = $(selector === '#' ? [] : selector)
if (e) e.preventDefault()
if (!$parent.length) {
$parent = $this.closest('.alert')
}
$parent.trigger(e = $.Event('close.bs.alert'))
if (e.isDefaultPrevented()) return
$parent.removeClass('in')
function removeElement() {
// detach from parent, fire event then clean up data
$parent.detach().trigger('closed.bs.alert').remove()
}
$.support.transition && $parent.hasClass('fade') ?
$parent
.one('bsTransitionEnd', removeElement)
.emulateTransitionEnd(Alert.TRANSITION_DURATION) :
removeElement()
}
// ALERT PLUGIN DEFINITION
// =======================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.alert')
if (!data) $this.data('bs.alert', (data = new Alert(this)))
if (typeof option == 'string') data[option].call($this)
})
}
var old = $.fn.alert
$.fn.alert = Plugin
$.fn.alert.Constructor = Alert
// ALERT NO CONFLICT
// =================
$.fn.alert.noConflict = function () {
$.fn.alert = old
return this
}
// ALERT DATA-API
// ==============
$(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close)
}(jQuery);
/* ========================================================================
* Bootstrap: button.js v3.3.7
* http://getbootstrap.com/javascript/#buttons
* ========================================================================
* Copyright 2011-2016 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// BUTTON PUBLIC CLASS DEFINITION
// ==============================
var Button = function (element, options) {
this.$element = $(element)
this.options = $.extend({}, Button.DEFAULTS, options)
this.isLoading = false
}
Button.VERSION = '3.3.7'
Button.DEFAULTS = {
loadingText: 'loading...'
}
Button.prototype.setState = function (state) {
var d = 'disabled'
var $el = this.$element
var val = $el.is('input') ? 'val' : 'html'
var data = $el.data()
state += 'Text'
if (data.resetText == null) $el.data('resetText', $el[val]())
// push to event loop to allow forms to submit
setTimeout($.proxy(function () {
$el[val](data[state] == null ? this.options[state] : data[state])
if (state == 'loadingText') {
this.isLoading = true
$el.addClass(d).attr(d, d).prop(d, true)
} else if (this.isLoading) {
this.isLoading = false
$el.removeClass(d).removeAttr(d).prop(d, false)
}
}, this), 0)
}
Button.prototype.toggle = function () {
var changed = true
var $parent = this.$element.closest('[data-toggle="buttons"]')
if ($parent.length) {
var $input = this.$element.find('input')
if ($input.prop('type') == 'radio') {
if ($input.prop('checked')) changed = false
$parent.find('.active').removeClass('active')
this.$element.addClass('active')
} else if ($input.prop('type') == 'checkbox') {
if (($input.prop('checked')) !== this.$element.hasClass('active')) changed = false
this.$element.toggleClass('active')
}
$input.prop('checked', this.$element.hasClass('active'))
if (changed) $input.trigger('change')
} else {
this.$element.attr('aria-pressed', !this.$element.hasClass('active'))
this.$element.toggleClass('active')
}
}
// BUTTON PLUGIN DEFINITION
// ========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.button')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.button', (data = new Button(this, options)))
if (option == 'toggle') data.toggle()
else if (option) data.setState(option)
})
}
var old = $.fn.button
$.fn.button = Plugin
$.fn.button.Constructor = Button
// BUTTON NO CONFLICT
// ==================
$.fn.button.noConflict = function () {
$.fn.button = old
return this
}
// BUTTON DATA-API
// ===============
$(document)
.on('click.bs.button.data-api', '[data-toggle^="button"]', function (e) {
var $btn = $(e.target).closest('.btn')
Plugin.call($btn, 'toggle')
if (!($(e.target).is('input[type="radio"], input[type="checkbox"]'))) {
// Prevent double click on radios, and the double selections (so cancellation) on checkboxes
e.preventDefault()
// The target component still receive the focus
if ($btn.is('input,button')) $btn.trigger('focus')
else $btn.find('input:visible,button:visible').first().trigger('focus')
}
})
.on('focus.bs.button.data-api blur.bs.button.data-api', '[data-toggle^="button"]', function (e) {
$(e.target).closest('.btn').toggleClass('focus', /^focus(in)?$/.test(e.type))
})
}(jQuery);
/* ========================================================================
* Bootstrap: carousel.js v3.3.7
* http://getbootstrap.com/javascript/#carousel
* ========================================================================
* Copyright 2011-2016 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// CAROUSEL CLASS DEFINITION
// =========================
var Carousel = function (element, options) {
this.$element = $(element)
this.$indicators = this.$element.find('.carousel-indicators')
this.options = options
this.paused = null
this.sliding = null
this.interval = null
this.$active = null
this.$items = null
this.options.keyboard && this.$element.on('keydown.bs.carousel', $.proxy(this.keydown, this))
this.options.pause == 'hover' && !('ontouchstart' in document.documentElement) && this.$element
.on('mouseenter.bs.carousel', $.proxy(this.pause, this))
.on('mouseleave.bs.carousel', $.proxy(this.cycle, this))
}
Carousel.VERSION = '3.3.7'
Carousel.TRANSITION_DURATION = 600
Carousel.DEFAULTS = {
interval: 5000,
pause: 'hover',
wrap: true,
keyboard: true
}
Carousel.prototype.keydown = function (e) {
if (/input|textarea/i.test(e.target.tagName)) return
switch (e.which) {
case 37: this.prev(); break
case 39: this.next(); break
default: return
}
e.preventDefault()
}
Carousel.prototype.cycle = function (e) {
e || (this.paused = false)
this.interval && clearInterval(this.interval)
this.options.interval
&& !this.paused
&& (this.interval = setInterval($.proxy(this.next, this), this.options.interval))
return this
}
Carousel.prototype.getItemIndex = function (item) {
this.$items = item.parent().children('.item')
return this.$items.index(item || this.$active)
}
Carousel.prototype.getItemForDirection = function (direction, active) {
var activeIndex = this.getItemIndex(active)
var willWrap = (direction == 'prev' && activeIndex === 0)
|| (direction == 'next' && activeIndex == (this.$items.length - 1))
if (willWrap && !this.options.wrap) return active
var delta = direction == 'prev' ? -1 : 1
var itemIndex = (activeIndex + delta) % this.$items.length
return this.$items.eq(itemIndex)
}
Carousel.prototype.to = function (pos) {
var that = this
var activeIndex = this.getItemIndex(this.$active = this.$element.find('.item.active'))
if (pos > (this.$items.length - 1) || pos < 0) return
if (this.sliding) return this.$element.one('slid.bs.carousel', function () { that.to(pos) }) // yes, "slid"
if (activeIndex == pos) return this.pause().cycle()
return this.slide(pos > activeIndex ? 'next' : 'prev', this.$items.eq(pos))
}
Carousel.prototype.pause = function (e) {
e || (this.paused = true)
if (this.$element.find('.next, .prev').length && $.support.transition) {
this.$element.trigger($.support.transition.end)
this.cycle(true)
}
this.interval = clearInterval(this.interval)
return this
}
Carousel.prototype.next = function () {
if (this.sliding) return
return this.slide('next')
}
Carousel.prototype.prev = function () {
if (this.sliding) return
return this.slide('prev')
}
Carousel.prototype.slide = function (type, next) {
var $active = this.$element.find('.item.active')
var $next = next || this.getItemForDirection(type, $active)
var isCycling = this.interval
var direction = type == 'next' ? 'left' : 'right'
var that = this
if ($next.hasClass('active')) return (this.sliding = false)
var relatedTarget = $next[0]
var slideEvent = $.Event('slide.bs.carousel', {
relatedTarget: relatedTarget,
direction: direction
})
this.$element.trigger(slideEvent)
if (slideEvent.isDefaultPrevented()) return
this.sliding = true
isCycling && this.pause()
if (this.$indicators.length) {
this.$indicators.find('.active').removeClass('active')
var $nextIndicator = $(this.$indicators.children()[this.getItemIndex($next)])
$nextIndicator && $nextIndicator.addClass('active')
}
var slidEvent = $.Event('slid.bs.carousel', { relatedTarget: relatedTarget, direction: direction }) // yes, "slid"
if ($.support.transition && this.$element.hasClass('slide')) {
$next.addClass(type)
$next[0].offsetWidth // force reflow
$active.addClass(direction)
$next.addClass(direction)
$active
.one('bsTransitionEnd', function () {
$next.removeClass([type, direction].join(' ')).addClass('active')
$active.removeClass(['active', direction].join(' '))
that.sliding = false
setTimeout(function () {
that.$element.trigger(slidEvent)
}, 0)
})
.emulateTransitionEnd(Carousel.TRANSITION_DURATION)
} else {
$active.removeClass('active')
$next.addClass('active')
this.sliding = false
this.$element.trigger(slidEvent)
}
isCycling && this.cycle()
return this
}
// CAROUSEL PLUGIN DEFINITION
// ==========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.carousel')
var options = $.extend({}, Carousel.DEFAULTS, $this.data(), typeof option == 'object' && option)
var action = typeof option == 'string' ? option : options.slide
if (!data) $this.data('bs.carousel', (data = new Carousel(this, options)))
if (typeof option == 'number') data.to(option)
else if (action) data[action]()
else if (options.interval) data.pause().cycle()
})
}
var old = $.fn.carousel
$.fn.carousel = Plugin
$.fn.carousel.Constructor = Carousel
// CAROUSEL NO CONFLICT
// ====================
$.fn.carousel.noConflict = function () {
$.fn.carousel = old
return this
}
// CAROUSEL DATA-API
// =================
var clickHandler = function (e) {
var href
var $this = $(this)
var $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) // strip for ie7
if (!$target.hasClass('carousel')) return
var options = $.extend({}, $target.data(), $this.data())
var slideIndex = $this.attr('data-slide-to')
if (slideIndex) options.interval = false
Plugin.call($target, options)
if (slideIndex) {
$target.data('bs.carousel').to(slideIndex)
}
e.preventDefault()
}
$(document)
.on('click.bs.carousel.data-api', '[data-slide]', clickHandler)
.on('click.bs.carousel.data-api', '[data-slide-to]', clickHandler)
$(window).on('load', function () {
$('[data-ride="carousel"]').each(function () {
var $carousel = $(this)
Plugin.call($carousel, $carousel.data())
})
})
}(jQuery);
/* ========================================================================
* Bootstrap: collapse.js v3.3.7
* http://getbootstrap.com/javascript/#collapse
* ========================================================================
* Copyright 2011-2016 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
/* jshint latedef: false */
+function ($) {
'use strict';
// COLLAPSE PUBLIC CLASS DEFINITION
// ================================
var Collapse = function (element, options) {
this.$element = $(element)
this.options = $.extend({}, Collapse.DEFAULTS, options)
this.$trigger = $('[data-toggle="collapse"][href="#' + element.id + '"],' +
'[data-toggle="collapse"][data-target="#' + element.id + '"]')
this.transitioning = null
if (this.options.parent) {
this.$parent = this.getParent()
} else {
this.addAriaAndCollapsedClass(this.$element, this.$trigger)
}
if (this.options.toggle) this.toggle()
}
Collapse.VERSION = '3.3.7'
Collapse.TRANSITION_DURATION = 350
Collapse.DEFAULTS = {
toggle: true
}
Collapse.prototype.dimension = function () {
var hasWidth = this.$element.hasClass('width')
return hasWidth ? 'width' : 'height'
}
Collapse.prototype.show = function () {
if (this.transitioning || this.$element.hasClass('in')) return
var activesData
var actives = this.$parent && this.$parent.children('.panel').children('.in, .collapsing')
if (actives && actives.length) {
activesData = actives.data('bs.collapse')
if (activesData && activesData.transitioning) return
}
var startEvent = $.Event('show.bs.collapse')
this.$element.trigger(startEvent)
if (startEvent.isDefaultPrevented()) return
if (actives && actives.length) {
Plugin.call(actives, 'hide')
activesData || actives.data('bs.collapse', null)
}
var dimension = this.dimension()
this.$element
.removeClass('collapse')
.addClass('collapsing')[dimension](0)
.attr('aria-expanded', true)
this.$trigger
.removeClass('collapsed')
.attr('aria-expanded', true)
this.transitioning = 1
var complete = function () {
this.$element
.removeClass('collapsing')
.addClass('collapse in')[dimension]('')
this.transitioning = 0
this.$element
.trigger('shown.bs.collapse')
}
if (!$.support.transition) return complete.call(this)
var scrollSize = $.camelCase(['scroll', dimension].join('-'))
this.$element
.one('bsTransitionEnd', $.proxy(complete, this))
.emulateTransitionEnd(Collapse.TRANSITION_DURATION)[dimension](this.$element[0][scrollSize])
}
Collapse.prototype.hide = function () {
if (this.transitioning || !this.$element.hasClass('in')) return
var startEvent = $.Event('hide.bs.collapse')
this.$element.trigger(startEvent)
if (startEvent.isDefaultPrevented()) return
var dimension = this.dimension()
this.$element[dimension](this.$element[dimension]())[0].offsetHeight
this.$element
.addClass('collapsing')
.removeClass('collapse in')
.attr('aria-expanded', false)
this.$trigger
.addClass('collapsed')
.attr('aria-expanded', false)
this.transitioning = 1
var complete = function () {
this.transitioning = 0
this.$element
.removeClass('collapsing')
.addClass('collapse')
.trigger('hidden.bs.collapse')
}
if (!$.support.transition) return complete.call(this)
this.$element
[dimension](0)
.one('bsTransitionEnd', $.proxy(complete, this))
.emulateTransitionEnd(Collapse.TRANSITION_DURATION)
}
Collapse.prototype.toggle = function () {
this[this.$element.hasClass('in') ? 'hide' : 'show']()
}
Collapse.prototype.getParent = function () {
return $(this.options.parent)
.find('[data-toggle="collapse"][data-parent="' + this.options.parent + '"]')
.each($.proxy(function (i, element) {
var $element = $(element)
this.addAriaAndCollapsedClass(getTargetFromTrigger($element), $element)
}, this))
.end()
}
Collapse.prototype.addAriaAndCollapsedClass = function ($element, $trigger) {
var isOpen = $element.hasClass('in')
$element.attr('aria-expanded', isOpen)
$trigger
.toggleClass('collapsed', !isOpen)
.attr('aria-expanded', isOpen)
}
function getTargetFromTrigger($trigger) {
var href
var target = $trigger.attr('data-target')
|| (href = $trigger.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') // strip for ie7
return $(target)
}
// COLLAPSE PLUGIN DEFINITION
// ==========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.collapse')
var options = $.extend({}, Collapse.DEFAULTS, $this.data(), typeof option == 'object' && option)
if (!data && options.toggle && /show|hide/.test(option)) options.toggle = false
if (!data) $this.data('bs.collapse', (data = new Collapse(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.collapse
$.fn.collapse = Plugin
$.fn.collapse.Constructor = Collapse
// COLLAPSE NO CONFLICT
// ====================
$.fn.collapse.noConflict = function () {
$.fn.collapse = old
return this
}
// COLLAPSE DATA-API
// =================
$(document).on('click.bs.collapse.data-api', '[data-toggle="collapse"]', function (e) {
var $this = $(this)
if (!$this.attr('data-target')) e.preventDefault()
var $target = getTargetFromTrigger($this)
var data = $target.data('bs.collapse')
var option = data ? 'toggle' : $this.data()
Plugin.call($target, option)
})
}(jQuery);
/* ========================================================================
* Bootstrap: dropdown.js v3.3.7
* http://getbootstrap.com/javascript/#dropdowns
* ========================================================================
* Copyright 2011-2016 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// DROPDOWN CLASS DEFINITION
// =========================
var backdrop = '.dropdown-backdrop'
var toggle = '[data-toggle="dropdown"]'
var Dropdown = function (element) {
$(element).on('click.bs.dropdown', this.toggle)
}
Dropdown.VERSION = '3.3.7'
function getParent($this) {
var selector = $this.attr('data-target')
if (!selector) {
selector = $this.attr('href')
selector = selector && /#[A-Za-z]/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
}
var $parent = selector && $(selector)
return $parent && $parent.length ? $parent : $this.parent()
}
function clearMenus(e) {
if (e && e.which === 3) return
$(backdrop).remove()
$(toggle).each(function () {
var $this = $(this)
var $parent = getParent($this)
var relatedTarget = { relatedTarget: this }
if (!$parent.hasClass('open')) return
if (e && e.type == 'click' && /input|textarea/i.test(e.target.tagName) && $.contains($parent[0], e.target)) return
$parent.trigger(e = $.Event('hide.bs.dropdown', relatedTarget))
if (e.isDefaultPrevented()) return
$this.attr('aria-expanded', 'false')
$parent.removeClass('open').trigger($.Event('hidden.bs.dropdown', relatedTarget))
})
}
Dropdown.prototype.toggle = function (e) {
var $this = $(this)
if ($this.is('.disabled, :disabled')) return
var $parent = getParent($this)
var isActive = $parent.hasClass('open')
clearMenus()
if (!isActive) {
if ('ontouchstart' in document.documentElement && !$parent.closest('.navbar-nav').length) {
// if mobile we use a backdrop because click events don't delegate
$(document.createElement('div'))
.addClass('dropdown-backdrop')
.insertAfter($(this))
.on('click', clearMenus)
}
var relatedTarget = { relatedTarget: this }
$parent.trigger(e = $.Event('show.bs.dropdown', relatedTarget))
if (e.isDefaultPrevented()) return
$this
.trigger('focus')
.attr('aria-expanded', 'true')
$parent
.toggleClass('open')
.trigger($.Event('shown.bs.dropdown', relatedTarget))
}
return false
}
Dropdown.prototype.keydown = function (e) {
if (!/(38|40|27|32)/.test(e.which) || /input|textarea/i.test(e.target.tagName)) return
var $this = $(this)
e.preventDefault()
e.stopPropagation()
if ($this.is('.disabled, :disabled')) return
var $parent = getParent($this)
var isActive = $parent.hasClass('open')
if (!isActive && e.which != 27 || isActive && e.which == 27) {
if (e.which == 27) $parent.find(toggle).trigger('focus')
return $this.trigger('click')
}
var desc = ' li:not(.disabled):visible a'
var $items = $parent.find('.dropdown-menu' + desc)
if (!$items.length) return
var index = $items.index(e.target)
if (e.which == 38 && index > 0) index-- // up
if (e.which == 40 && index < $items.length - 1) index++ // down
if (!~index) index = 0
$items.eq(index).trigger('focus')
}
// DROPDOWN PLUGIN DEFINITION
// ==========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.dropdown')
if (!data) $this.data('bs.dropdown', (data = new Dropdown(this)))
if (typeof option == 'string') data[option].call($this)
})
}
var old = $.fn.dropdown
$.fn.dropdown = Plugin
$.fn.dropdown.Constructor = Dropdown
// DROPDOWN NO CONFLICT
// ====================
$.fn.dropdown.noConflict = function () {
$.fn.dropdown = old
return this
}
// APPLY TO STANDARD DROPDOWN ELEMENTS
// ===================================
$(document)
.on('click.bs.dropdown.data-api', clearMenus)
.on('click.bs.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() })
.on('click.bs.dropdown.data-api', toggle, Dropdown.prototype.toggle)
.on('keydown.bs.dropdown.data-api', toggle, Dropdown.prototype.keydown)
.on('keydown.bs.dropdown.data-api', '.dropdown-menu', Dropdown.prototype.keydown)
}(jQuery);
/* ========================================================================
* Bootstrap: modal.js v3.3.7
* http://getbootstrap.com/javascript/#modals
* ========================================================================
* Copyright 2011-2016 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// MODAL CLASS DEFINITION
// ======================
var Modal = function (element, options) {
this.options = options
this.$body = $(document.body)
this.$element = $(element)
this.$dialog = this.$element.find('.modal-dialog')
this.$backdrop = null
this.isShown = null
this.originalBodyPad = null
this.scrollbarWidth = 0
this.ignoreBackdropClick = false
if (this.options.remote) {
this.$element
.find('.modal-content')
.load(this.options.remote, $.proxy(function () {
this.$element.trigger('loaded.bs.modal')
}, this))
}
}
Modal.VERSION = '3.3.7'
Modal.TRANSITION_DURATION = 300
Modal.BACKDROP_TRANSITION_DURATION = 150
Modal.DEFAULTS = {
backdrop: true,
keyboard: true,
show: true
}
Modal.prototype.toggle = function (_relatedTarget) {
return this.isShown ? this.hide() : this.show(_relatedTarget)
}
Modal.prototype.show = function (_relatedTarget) {
var that = this
var e = $.Event('show.bs.modal', { relatedTarget: _relatedTarget })
this.$element.trigger(e)
if (this.isShown || e.isDefaultPrevented()) return
this.isShown = true
this.checkScrollbar()
this.setScrollbar()
this.$body.addClass('modal-open')
this.escape()
this.resize()
this.$element.on('click.dismiss.bs.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this))
this.$dialog.on('mousedown.dismiss.bs.modal', function () {
that.$element.one('mouseup.dismiss.bs.modal', function (e) {
if ($(e.target).is(that.$element)) that.ignoreBackdropClick = true
})
})
this.backdrop(function () {
var transition = $.support.transition && that.$element.hasClass('fade')
if (!that.$element.parent().length) {
that.$element.appendTo(that.$body) // don't move modals dom position
}
that.$element
.show()
.scrollTop(0)
that.adjustDialog()
if (transition) {
that.$element[0].offsetWidth // force reflow
}
that.$element.addClass('in')
that.enforceFocus()
var e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget })
transition ?
that.$dialog // wait for modal to slide in
.one('bsTransitionEnd', function () {
that.$element.trigger('focus').trigger(e)
})
.emulateTransitionEnd(Modal.TRANSITION_DURATION) :
that.$element.trigger('focus').trigger(e)
})
}
Modal.prototype.hide = function (e) {
if (e) e.preventDefault()
e = $.Event('hide.bs.modal')
this.$element.trigger(e)
if (!this.isShown || e.isDefaultPrevented()) return
this.isShown = false
this.escape()
this.resize()
$(document).off('focusin.bs.modal')
this.$element
.removeClass('in')
.off('click.dismiss.bs.modal')
.off('mouseup.dismiss.bs.modal')
this.$dialog.off('mousedown.dismiss.bs.modal')
$.support.transition && this.$element.hasClass('fade') ?
this.$element
.one('bsTransitionEnd', $.proxy(this.hideModal, this))
.emulateTransitionEnd(Modal.TRANSITION_DURATION) :
this.hideModal()
}
Modal.prototype.enforceFocus = function () {
$(document)
.off('focusin.bs.modal') // guard against infinite focus loop
.on('focusin.bs.modal', $.proxy(function (e) {
if (document !== e.target &&
this.$element[0] !== e.target &&
!this.$element.has(e.target).length) {
this.$element.trigger('focus')
}
}, this))
}
Modal.prototype.escape = function () {
if (this.isShown && this.options.keyboard) {
this.$element.on('keydown.dismiss.bs.modal', $.proxy(function (e) {
e.which == 27 && this.hide()
}, this))
} else if (!this.isShown) {
this.$element.off('keydown.dismiss.bs.modal')
}
}
Modal.prototype.resize = function () {
if (this.isShown) {
$(window).on('resize.bs.modal', $.proxy(this.handleUpdate, this))
} else {
$(window).off('resize.bs.modal')
}
}
Modal.prototype.hideModal = function () {
var that = this
this.$element.hide()
this.backdrop(function () {
that.$body.removeClass('modal-open')
that.resetAdjustments()
that.resetScrollbar()
that.$element.trigger('hidden.bs.modal')
})
}
Modal.prototype.removeBackdrop = function () {
this.$backdrop && this.$backdrop.remove()
this.$backdrop = null
}
Modal.prototype.backdrop = function (callback) {
var that = this
var animate = this.$element.hasClass('fade') ? 'fade' : ''
if (this.isShown && this.options.backdrop) {
var doAnimate = $.support.transition && animate
this.$backdrop = $(document.createElement('div'))
.addClass('modal-backdrop ' + animate)
.appendTo(this.$body)
this.$element.on('click.dismiss.bs.modal', $.proxy(function (e) {
if (this.ignoreBackdropClick) {
this.ignoreBackdropClick = false
return
}
if (e.target !== e.currentTarget) return
this.options.backdrop == 'static'
? this.$element[0].focus()
: this.hide()
}, this))
if (doAnimate) this.$backdrop[0].offsetWidth // force reflow
this.$backdrop.addClass('in')
if (!callback) return
doAnimate ?
this.$backdrop
.one('bsTransitionEnd', callback)
.emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) :
callback()
} else if (!this.isShown && this.$backdrop) {
this.$backdrop.removeClass('in')
var callbackRemove = function () {
that.removeBackdrop()
callback && callback()
}
$.support.transition && this.$element.hasClass('fade') ?
this.$backdrop
.one('bsTransitionEnd', callbackRemove)
.emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) :
callbackRemove()
} else if (callback) {
callback()
}
}
// these following methods are used to handle overflowing modals
Modal.prototype.handleUpdate = function () {
this.adjustDialog()
}
Modal.prototype.adjustDialog = function () {
var modalIsOverflowing = this.$element[0].scrollHeight > document.documentElement.clientHeight
this.$element.css({
paddingLeft: !this.bodyIsOverflowing && modalIsOverflowing ? this.scrollbarWidth : '',
paddingRight: this.bodyIsOverflowing && !modalIsOverflowing ? this.scrollbarWidth : ''
})
}
Modal.prototype.resetAdjustments = function () {
this.$element.css({
paddingLeft: '',
paddingRight: ''
})
}
Modal.prototype.checkScrollbar = function () {
var fullWindowWidth = window.innerWidth
if (!fullWindowWidth) { // workaround for missing window.innerWidth in IE8
var documentElementRect = document.documentElement.getBoundingClientRect()
fullWindowWidth = documentElementRect.right - Math.abs(documentElementRect.left)
}
this.bodyIsOverflowing = document.body.clientWidth < fullWindowWidth
this.scrollbarWidth = this.measureScrollbar()
}
Modal.prototype.setScrollbar = function () {
var bodyPad = parseInt((this.$body.css('padding-right') || 0), 10)
this.originalBodyPad = document.body.style.paddingRight || ''
if (this.bodyIsOverflowing) this.$body.css('padding-right', bodyPad + this.scrollbarWidth)
}
Modal.prototype.resetScrollbar = function () {
this.$body.css('padding-right', this.originalBodyPad)
}
Modal.prototype.measureScrollbar = function () { // thx walsh
var scrollDiv = document.createElement('div')
scrollDiv.className = 'modal-scrollbar-measure'
this.$body.append(scrollDiv)
var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth
this.$body[0].removeChild(scrollDiv)
return scrollbarWidth
}
// MODAL PLUGIN DEFINITION
// =======================
function Plugin(option, _relatedTarget) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.modal')
var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option)
if (!data) $this.data('bs.modal', (data = new Modal(this, options)))
if (typeof option == 'string') data[option](_relatedTarget)
else if (options.show) data.show(_relatedTarget)
})
}
var old = $.fn.modal
$.fn.modal = Plugin
$.fn.modal.Constructor = Modal
// MODAL NO CONFLICT
// =================
$.fn.modal.noConflict = function () {
$.fn.modal = old
return this
}
// MODAL DATA-API
// ==============
$(document).on('click.bs.modal.data-api', '[data-toggle="modal"]', function (e) {
var $this = $(this)
var href = $this.attr('href')
var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) // strip for ie7
var option = $target.data('bs.modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data())
if ($this.is('a')) e.preventDefault()
$target.one('show.bs.modal', function (showEvent) {
if (showEvent.isDefaultPrevented()) return // only register focus restorer if modal will actually get shown
$target.one('hidden.bs.modal', function () {
$this.is(':visible') && $this.trigger('focus')
})
})
Plugin.call($target, option, this)
})
}(jQuery);
/* ========================================================================
* Bootstrap: tooltip.js v3.3.7
* http://getbootstrap.com/javascript/#tooltip
* Inspired by the original jQuery.tipsy by Jason Frame
* ========================================================================
* Copyright 2011-2016 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// TOOLTIP PUBLIC CLASS DEFINITION
// ===============================
var Tooltip = function (element, options) {
this.type = null
this.options = null
this.enabled = null
this.timeout = null
this.hoverState = null
this.$element = null
this.inState = null
this.init('tooltip', element, options)
}
Tooltip.VERSION = '3.3.7'
Tooltip.TRANSITION_DURATION = 150
Tooltip.DEFAULTS = {
animation: true,
placement: 'top',
selector: false,
template: '<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',
trigger: 'hover focus',
title: '',
delay: 0,
html: false,
container: false,
viewport: {
selector: 'body',
padding: 0
}
}
Tooltip.prototype.init = function (type, element, options) {
this.enabled = true
this.type = type
this.$element = $(element)
this.options = this.getOptions(options)
this.$viewport = this.options.viewport && $($.isFunction(this.options.viewport) ? this.options.viewport.call(this, this.$element) : (this.options.viewport.selector || this.options.viewport))
this.inState = { click: false, hover: false, focus: false }
if (this.$element[0] instanceof document.constructor && !this.options.selector) {
throw new Error('`selector` option must be specified when initializing ' + this.type + ' on the window.document object!')
}
var triggers = this.options.trigger.split(' ')
for (var i = triggers.length; i--;) {
var trigger = triggers[i]
if (trigger == 'click') {
this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this))
} else if (trigger != 'manual') {
var eventIn = trigger == 'hover' ? 'mouseenter' : 'focusin'
var eventOut = trigger == 'hover' ? 'mouseleave' : 'focusout'
this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this))
this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this))
}
}
this.options.selector ?
(this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) :
this.fixTitle()
}
Tooltip.prototype.getDefaults = function () {
return Tooltip.DEFAULTS
}
Tooltip.prototype.getOptions = function (options) {
options = $.extend({}, this.getDefaults(), this.$element.data(), options)
if (options.delay && typeof options.delay == 'number') {
options.delay = {
show: options.delay,
hide: options.delay
}
}
return options
}
Tooltip.prototype.getDelegateOptions = function () {
var options = {}
var defaults = this.getDefaults()
this._options && $.each(this._options, function (key, value) {
if (defaults[key] != value) options[key] = value
})
return options
}
Tooltip.prototype.enter = function (obj) {
var self = obj instanceof this.constructor ?
obj : $(obj.currentTarget).data('bs.' + this.type)
if (!self) {
self = new this.constructor(obj.currentTarget, this.getDelegateOptions())
$(obj.currentTarget).data('bs.' + this.type, self)
}
if (obj instanceof $.Event) {
self.inState[obj.type == 'focusin' ? 'focus' : 'hover'] = true
}
if (self.tip().hasClass('in') || self.hoverState == 'in') {
self.hoverState = 'in'
return
}
clearTimeout(self.timeout)
self.hoverState = 'in'
if (!self.options.delay || !self.options.delay.show) return self.show()
self.timeout = setTimeout(function () {
if (self.hoverState == 'in') self.show()
}, self.options.delay.show)
}
Tooltip.prototype.isInStateTrue = function () {
for (var key in this.inState) {
if (this.inState[key]) return true
}
return false
}
Tooltip.prototype.leave = function (obj) {
var self = obj instanceof this.constructor ?
obj : $(obj.currentTarget).data('bs.' + this.type)
if (!self) {
self = new this.constructor(obj.currentTarget, this.getDelegateOptions())
$(obj.currentTarget).data('bs.' + this.type, self)
}
if (obj instanceof $.Event) {
self.inState[obj.type == 'focusout' ? 'focus' : 'hover'] = false
}
if (self.isInStateTrue()) return
clearTimeout(self.timeout)
self.hoverState = 'out'
if (!self.options.delay || !self.options.delay.hide) return self.hide()
self.timeout = setTimeout(function () {
if (self.hoverState == 'out') self.hide()
}, self.options.delay.hide)
}
Tooltip.prototype.show = function () {
var e = $.Event('show.bs.' + this.type)
if (this.hasContent() && this.enabled) {
this.$element.trigger(e)
var inDom = $.contains(this.$element[0].ownerDocument.documentElement, this.$element[0])
if (e.isDefaultPrevented() || !inDom) return
var that = this
var $tip = this.tip()
var tipId = this.getUID(this.type)
this.setContent()
$tip.attr('id', tipId)
this.$element.attr('aria-describedby', tipId)
if (this.options.animation) $tip.addClass('fade')
var placement = typeof this.options.placement == 'function' ?
this.options.placement.call(this, $tip[0], this.$element[0]) :
this.options.placement
var autoToken = /\s?auto?\s?/i
var autoPlace = autoToken.test(placement)
if (autoPlace) placement = placement.replace(autoToken, '') || 'top'
$tip
.detach()
.css({ top: 0, left: 0, display: 'block' })
.addClass(placement)
.data('bs.' + this.type, this)
this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element)
this.$element.trigger('inserted.bs.' + this.type)
var pos = this.getPosition()
var actualWidth = $tip[0].offsetWidth
var actualHeight = $tip[0].offsetHeight
if (autoPlace) {
var orgPlacement = placement
var viewportDim = this.getPosition(this.$viewport)
placement = placement == 'bottom' && pos.bottom + actualHeight > viewportDim.bottom ? 'top' :
placement == 'top' && pos.top - actualHeight < viewportDim.top ? 'bottom' :
placement == 'right' && pos.right + actualWidth > viewportDim.width ? 'left' :
placement == 'left' && pos.left - actualWidth < viewportDim.left ? 'right' :
placement
$tip
.removeClass(orgPlacement)
.addClass(placement)
}
var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight)
this.applyPlacement(calculatedOffset, placement)
var complete = function () {
var prevHoverState = that.hoverState
that.$element.trigger('shown.bs.' + that.type)
that.hoverState = null
if (prevHoverState == 'out') that.leave(that)
}
$.support.transition && this.$tip.hasClass('fade') ?
$tip
.one('bsTransitionEnd', complete)
.emulateTransitionEnd(Tooltip.TRANSITION_DURATION) :
complete()
}
}
Tooltip.prototype.applyPlacement = function (offset, placement) {
var $tip = this.tip()
var width = $tip[0].offsetWidth
var height = $tip[0].offsetHeight
// manually read margins because getBoundingClientRect includes difference
var marginTop = parseInt($tip.css('margin-top'), 10)
var marginLeft = parseInt($tip.css('margin-left'), 10)
// we must check for NaN for ie 8/9
if (isNaN(marginTop)) marginTop = 0
if (isNaN(marginLeft)) marginLeft = 0
offset.top += marginTop
offset.left += marginLeft
// $.fn.offset doesn't round pixel values
// so we use setOffset directly with our own function B-0
$.offset.setOffset($tip[0], $.extend({
using: function (props) {
$tip.css({
top: Math.round(props.top),
left: Math.round(props.left)
})
}
}, offset), 0)
$tip.addClass('in')
// check to see if placing tip in new offset caused the tip to resize itself
var actualWidth = $tip[0].offsetWidth
var actualHeight = $tip[0].offsetHeight
if (placement == 'top' && actualHeight != height) {
offset.top = offset.top + height - actualHeight
}
var delta = this.getViewportAdjustedDelta(placement, offset, actualWidth, actualHeight)
if (delta.left) offset.left += delta.left
else offset.top += delta.top
var isVertical = /top|bottom/.test(placement)
var arrowDelta = isVertical ? delta.left * 2 - width + actualWidth : delta.top * 2 - height + actualHeight
var arrowOffsetPosition = isVertical ? 'offsetWidth' : 'offsetHeight'
$tip.offset(offset)
this.replaceArrow(arrowDelta, $tip[0][arrowOffsetPosition], isVertical)
}
Tooltip.prototype.replaceArrow = function (delta, dimension, isVertical) {
this.arrow()
.css(isVertical ? 'left' : 'top', 50 * (1 - delta / dimension) + '%')
.css(isVertical ? 'top' : 'left', '')
}
Tooltip.prototype.setContent = function () {
var $tip = this.tip()
var title = this.getTitle()
$tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title)
$tip.removeClass('fade in top bottom left right')
}
Tooltip.prototype.hide = function (callback) {
var that = this
var $tip = $(this.$tip)
var e = $.Event('hide.bs.' + this.type)
function complete() {
if (that.hoverState != 'in') $tip.detach()
if (that.$element) { // TODO: Check whether guarding this code with this `if` is really necessary.
that.$element
.removeAttr('aria-describedby')
.trigger('hidden.bs.' + that.type)
}
callback && callback()
}
this.$element.trigger(e)
if (e.isDefaultPrevented()) return
$tip.removeClass('in')
$.support.transition && $tip.hasClass('fade') ?
$tip
.one('bsTransitionEnd', complete)
.emulateTransitionEnd(Tooltip.TRANSITION_DURATION) :
complete()
this.hoverState = null
return this
}
Tooltip.prototype.fixTitle = function () {
var $e = this.$element
if ($e.attr('title') || typeof $e.attr('data-original-title') != 'string') {
$e.attr('data-original-title', $e.attr('title') || '').attr('title', '')
}
}
Tooltip.prototype.hasContent = function () {
return this.getTitle()
}
Tooltip.prototype.getPosition = function ($element) {
$element = $element || this.$element
var el = $element[0]
var isBody = el.tagName == 'BODY'
var elRect = el.getBoundingClientRect()
if (elRect.width == null) {
// width and height are missing in IE8, so compute them manually; see https://github.com/twbs/bootstrap/issues/14093
elRect = $.extend({}, elRect, { width: elRect.right - elRect.left, height: elRect.bottom - elRect.top })
}
var isSvg = window.SVGElement && el instanceof window.SVGElement
// Avoid using $.offset() on SVGs since it gives incorrect results in jQuery 3.
// See https://github.com/twbs/bootstrap/issues/20280
var elOffset = isBody ? { top: 0, left: 0 } : (isSvg ? null : $element.offset())
var scroll = { scroll: isBody ? document.documentElement.scrollTop || document.body.scrollTop : $element.scrollTop() }
var outerDims = isBody ? { width: $(window).width(), height: $(window).height() } : null
return $.extend({}, elRect, scroll, outerDims, elOffset)
}
Tooltip.prototype.getCalculatedOffset = function (placement, pos, actualWidth, actualHeight) {
return placement == 'bottom' ? { top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2 } :
placement == 'top' ? { top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2 } :
placement == 'left' ? { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth } :
/* placement == 'right' */ { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width }
}
Tooltip.prototype.getViewportAdjustedDelta = function (placement, pos, actualWidth, actualHeight) {
var delta = { top: 0, left: 0 }
if (!this.$viewport) return delta
var viewportPadding = this.options.viewport && this.options.viewport.padding || 0
var viewportDimensions = this.getPosition(this.$viewport)
if (/right|left/.test(placement)) {
var topEdgeOffset = pos.top - viewportPadding - viewportDimensions.scroll
var bottomEdgeOffset = pos.top + viewportPadding - viewportDimensions.scroll + actualHeight
if (topEdgeOffset < viewportDimensions.top) { // top overflow
delta.top = viewportDimensions.top - topEdgeOffset
} else if (bottomEdgeOffset > viewportDimensions.top + viewportDimensions.height) { // bottom overflow
delta.top = viewportDimensions.top + viewportDimensions.height - bottomEdgeOffset
}
} else {
var leftEdgeOffset = pos.left - viewportPadding
var rightEdgeOffset = pos.left + viewportPadding + actualWidth
if (leftEdgeOffset < viewportDimensions.left) { // left overflow
delta.left = viewportDimensions.left - leftEdgeOffset
} else if (rightEdgeOffset > viewportDimensions.right) { // right overflow
delta.left = viewportDimensions.left + viewportDimensions.width - rightEdgeOffset
}
}
return delta
}
Tooltip.prototype.getTitle = function () {
var title
var $e = this.$element
var o = this.options
title = $e.attr('data-original-title')
|| (typeof o.title == 'function' ? o.title.call($e[0]) : o.title)
return title
}
Tooltip.prototype.getUID = function (prefix) {
do prefix += ~~(Math.random() * 1000000)
while (document.getElementById(prefix))
return prefix
}
Tooltip.prototype.tip = function () {
if (!this.$tip) {
this.$tip = $(this.options.template)
if (this.$tip.length != 1) {
throw new Error(this.type + ' `template` option must consist of exactly 1 top-level element!')
}
}
return this.$tip
}
Tooltip.prototype.arrow = function () {
return (this.$arrow = this.$arrow || this.tip().find('.tooltip-arrow'))
}
Tooltip.prototype.enable = function () {
this.enabled = true
}
Tooltip.prototype.disable = function () {
this.enabled = false
}
Tooltip.prototype.toggleEnabled = function () {
this.enabled = !this.enabled
}
Tooltip.prototype.toggle = function (e) {
var self = this
if (e) {
self = $(e.currentTarget).data('bs.' + this.type)
if (!self) {
self = new this.constructor(e.currentTarget, this.getDelegateOptions())
$(e.currentTarget).data('bs.' + this.type, self)
}
}
if (e) {
self.inState.click = !self.inState.click
if (self.isInStateTrue()) self.enter(self)
else self.leave(self)
} else {
self.tip().hasClass('in') ? self.leave(self) : self.enter(self)
}
}
Tooltip.prototype.destroy = function () {
var that = this
clearTimeout(this.timeout)
this.hide(function () {
that.$element.off('.' + that.type).removeData('bs.' + that.type)
if (that.$tip) {
that.$tip.detach()
}
that.$tip = null
that.$arrow = null
that.$viewport = null
that.$element = null
})
}
// TOOLTIP PLUGIN DEFINITION
// =========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.tooltip')
var options = typeof option == 'object' && option
if (!data && /destroy|hide/.test(option)) return
if (!data) $this.data('bs.tooltip', (data = new Tooltip(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.tooltip
$.fn.tooltip = Plugin
$.fn.tooltip.Constructor = Tooltip
// TOOLTIP NO CONFLICT
// ===================
$.fn.tooltip.noConflict = function () {
$.fn.tooltip = old
return this
}
}(jQuery);
/* ========================================================================
* Bootstrap: popover.js v3.3.7
* http://getbootstrap.com/javascript/#popovers
* ========================================================================
* Copyright 2011-2016 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// POPOVER PUBLIC CLASS DEFINITION
// ===============================
var Popover = function (element, options) {
this.init('popover', element, options)
}
if (!$.fn.tooltip) throw new Error('Popover requires tooltip.js')
Popover.VERSION = '3.3.7'
Popover.DEFAULTS = $.extend({}, $.fn.tooltip.Constructor.DEFAULTS, {
placement: 'right',
trigger: 'click',
content: '',
template: '<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'
})
// NOTE: POPOVER EXTENDS tooltip.js
// ================================
Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype)
Popover.prototype.constructor = Popover
Popover.prototype.getDefaults = function () {
return Popover.DEFAULTS
}
Popover.prototype.setContent = function () {
var $tip = this.tip()
var title = this.getTitle()
var content = this.getContent()
$tip.find('.popover-title')[this.options.html ? 'html' : 'text'](title)
$tip.find('.popover-content').children().detach().end()[ // we use append for html objects to maintain js events
this.options.html ? (typeof content == 'string' ? 'html' : 'append') : 'text'
](content)
$tip.removeClass('fade top bottom left right in')
// IE8 doesn't accept hiding via the `:empty` pseudo selector, we have to do
// this manually by checking the contents.
if (!$tip.find('.popover-title').html()) $tip.find('.popover-title').hide()
}
Popover.prototype.hasContent = function () {
return this.getTitle() || this.getContent()
}
Popover.prototype.getContent = function () {
var $e = this.$element
var o = this.options
return $e.attr('data-content')
|| (typeof o.content == 'function' ?
o.content.call($e[0]) :
o.content)
}
Popover.prototype.arrow = function () {
return (this.$arrow = this.$arrow || this.tip().find('.arrow'))
}
// POPOVER PLUGIN DEFINITION
// =========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.popover')
var options = typeof option == 'object' && option
if (!data && /destroy|hide/.test(option)) return
if (!data) $this.data('bs.popover', (data = new Popover(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.popover
$.fn.popover = Plugin
$.fn.popover.Constructor = Popover
// POPOVER NO CONFLICT
// ===================
$.fn.popover.noConflict = function () {
$.fn.popover = old
return this
}
}(jQuery);
/* ========================================================================
* Bootstrap: scrollspy.js v3.3.7
* http://getbootstrap.com/javascript/#scrollspy
* ========================================================================
* Copyright 2011-2016 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// SCROLLSPY CLASS DEFINITION
// ==========================
function ScrollSpy(element, options) {
this.$body = $(document.body)
this.$scrollElement = $(element).is(document.body) ? $(window) : $(element)
this.options = $.extend({}, ScrollSpy.DEFAULTS, options)
this.selector = (this.options.target || '') + ' .nav li > a'
this.offsets = []
this.targets = []
this.activeTarget = null
this.scrollHeight = 0
this.$scrollElement.on('scroll.bs.scrollspy', $.proxy(this.process, this))
this.refresh()
this.process()
}
ScrollSpy.VERSION = '3.3.7'
ScrollSpy.DEFAULTS = {
offset: 10
}
ScrollSpy.prototype.getScrollHeight = function () {
return this.$scrollElement[0].scrollHeight || Math.max(this.$body[0].scrollHeight, document.documentElement.scrollHeight)
}
ScrollSpy.prototype.refresh = function () {
var that = this
var offsetMethod = 'offset'
var offsetBase = 0
this.offsets = []
this.targets = []
this.scrollHeight = this.getScrollHeight()
if (!$.isWindow(this.$scrollElement[0])) {
offsetMethod = 'position'
offsetBase = this.$scrollElement.scrollTop()
}
this.$body
.find(this.selector)
.map(function () {
var $el = $(this)
var href = $el.data('target') || $el.attr('href')
var $href = /^#./.test(href) && $(href)
return ($href
&& $href.length
&& $href.is(':visible')
&& [[$href[offsetMethod]().top + offsetBase, href]]) || null
})
.sort(function (a, b) { return a[0] - b[0] })
.each(function () {
that.offsets.push(this[0])
that.targets.push(this[1])
})
}
ScrollSpy.prototype.process = function () {
var scrollTop = this.$scrollElement.scrollTop() + this.options.offset
var scrollHeight = this.getScrollHeight()
var maxScroll = this.options.offset + scrollHeight - this.$scrollElement.height()
var offsets = this.offsets
var targets = this.targets
var activeTarget = this.activeTarget
var i
if (this.scrollHeight != scrollHeight) {
this.refresh()
}
if (scrollTop >= maxScroll) {
return activeTarget != (i = targets[targets.length - 1]) && this.activate(i)
}
if (activeTarget && scrollTop < offsets[0]) {
this.activeTarget = null
return this.clear()
}
for (i = offsets.length; i--;) {
activeTarget != targets[i]
&& scrollTop >= offsets[i]
&& (offsets[i + 1] === undefined || scrollTop < offsets[i + 1])
&& this.activate(targets[i])
}
}
ScrollSpy.prototype.activate = function (target) {
this.activeTarget = target
this.clear()
var selector = this.selector +
'[data-target="' + target + '"],' +
this.selector + '[href="' + target + '"]'
var active = $(selector)
.parents('li')
.addClass('active')
if (active.parent('.dropdown-menu').length) {
active = active
.closest('li.dropdown')
.addClass('active')
}
active.trigger('activate.bs.scrollspy')
}
ScrollSpy.prototype.clear = function () {
$(this.selector)
.parentsUntil(this.options.target, '.active')
.removeClass('active')
}
// SCROLLSPY PLUGIN DEFINITION
// ===========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.scrollspy')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.scrollspy', (data = new ScrollSpy(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.scrollspy
$.fn.scrollspy = Plugin
$.fn.scrollspy.Constructor = ScrollSpy
// SCROLLSPY NO CONFLICT
// =====================
$.fn.scrollspy.noConflict = function () {
$.fn.scrollspy = old
return this
}
// SCROLLSPY DATA-API
// ==================
$(window).on('load.bs.scrollspy.data-api', function () {
$('[data-spy="scroll"]').each(function () {
var $spy = $(this)
Plugin.call($spy, $spy.data())
})
})
}(jQuery);
/* ========================================================================
* Bootstrap: tab.js v3.3.7
* http://getbootstrap.com/javascript/#tabs
* ========================================================================
* Copyright 2011-2016 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// TAB CLASS DEFINITION
// ====================
var Tab = function (element) {
// jscs:disable requireDollarBeforejQueryAssignment
this.element = $(element)
// jscs:enable requireDollarBeforejQueryAssignment
}
Tab.VERSION = '3.3.7'
Tab.TRANSITION_DURATION = 150
Tab.prototype.show = function () {
var $this = this.element
var $ul = $this.closest('ul:not(.dropdown-menu)')
var selector = $this.data('target')
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
}
if ($this.parent('li').hasClass('active')) return
var $previous = $ul.find('.active:last a')
var hideEvent = $.Event('hide.bs.tab', {
relatedTarget: $this[0]
})
var showEvent = $.Event('show.bs.tab', {
relatedTarget: $previous[0]
})
$previous.trigger(hideEvent)
$this.trigger(showEvent)
if (showEvent.isDefaultPrevented() || hideEvent.isDefaultPrevented()) return
var $target = $(selector)
this.activate($this.closest('li'), $ul)
this.activate($target, $target.parent(), function () {
$previous.trigger({
type: 'hidden.bs.tab',
relatedTarget: $this[0]
})
$this.trigger({
type: 'shown.bs.tab',
relatedTarget: $previous[0]
})
})
}
Tab.prototype.activate = function (element, container, callback) {
var $active = container.find('> .active')
var transition = callback
&& $.support.transition
&& ($active.length && $active.hasClass('fade') || !!container.find('> .fade').length)
function next() {
$active
.removeClass('active')
.find('> .dropdown-menu > .active')
.removeClass('active')
.end()
.find('[data-toggle="tab"]')
.attr('aria-expanded', false)
element
.addClass('active')
.find('[data-toggle="tab"]')
.attr('aria-expanded', true)
if (transition) {
element[0].offsetWidth // reflow for transition
element.addClass('in')
} else {
element.removeClass('fade')
}
if (element.parent('.dropdown-menu').length) {
element
.closest('li.dropdown')
.addClass('active')
.end()
.find('[data-toggle="tab"]')
.attr('aria-expanded', true)
}
callback && callback()
}
$active.length && transition ?
$active
.one('bsTransitionEnd', next)
.emulateTransitionEnd(Tab.TRANSITION_DURATION) :
next()
$active.removeClass('in')
}
// TAB PLUGIN DEFINITION
// =====================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.tab')
if (!data) $this.data('bs.tab', (data = new Tab(this)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.tab
$.fn.tab = Plugin
$.fn.tab.Constructor = Tab
// TAB NO CONFLICT
// ===============
$.fn.tab.noConflict = function () {
$.fn.tab = old
return this
}
// TAB DATA-API
// ============
var clickHandler = function (e) {
e.preventDefault()
Plugin.call($(this), 'show')
}
$(document)
.on('click.bs.tab.data-api', '[data-toggle="tab"]', clickHandler)
.on('click.bs.tab.data-api', '[data-toggle="pill"]', clickHandler)
}(jQuery);
/* ========================================================================
* Bootstrap: affix.js v3.3.7
* http://getbootstrap.com/javascript/#affix
* ========================================================================
* Copyright 2011-2016 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// AFFIX CLASS DEFINITION
// ======================
var Affix = function (element, options) {
this.options = $.extend({}, Affix.DEFAULTS, options)
this.$target = $(this.options.target)
.on('scroll.bs.affix.data-api', $.proxy(this.checkPosition, this))
.on('click.bs.affix.data-api', $.proxy(this.checkPositionWithEventLoop, this))
this.$element = $(element)
this.affixed = null
this.unpin = null
this.pinnedOffset = null
this.checkPosition()
}
Affix.VERSION = '3.3.7'
Affix.RESET = 'affix affix-top affix-bottom'
Affix.DEFAULTS = {
offset: 0,
target: window
}
Affix.prototype.getState = function (scrollHeight, height, offsetTop, offsetBottom) {
var scrollTop = this.$target.scrollTop()
var position = this.$element.offset()
var targetHeight = this.$target.height()
if (offsetTop != null && this.affixed == 'top') return scrollTop < offsetTop ? 'top' : false
if (this.affixed == 'bottom') {
if (offsetTop != null) return (scrollTop + this.unpin <= position.top) ? false : 'bottom'
return (scrollTop + targetHeight <= scrollHeight - offsetBottom) ? false : 'bottom'
}
var initializing = this.affixed == null
var colliderTop = initializing ? scrollTop : position.top
var colliderHeight = initializing ? targetHeight : height
if (offsetTop != null && scrollTop <= offsetTop) return 'top'
if (offsetBottom != null && (colliderTop + colliderHeight >= scrollHeight - offsetBottom)) return 'bottom'
return false
}
Affix.prototype.getPinnedOffset = function () {
if (this.pinnedOffset) return this.pinnedOffset
this.$element.removeClass(Affix.RESET).addClass('affix')
var scrollTop = this.$target.scrollTop()
var position = this.$element.offset()
return (this.pinnedOffset = position.top - scrollTop)
}
Affix.prototype.checkPositionWithEventLoop = function () {
setTimeout($.proxy(this.checkPosition, this), 1)
}
Affix.prototype.checkPosition = function () {
if (!this.$element.is(':visible')) return
var height = this.$element.height()
var offset = this.options.offset
var offsetTop = offset.top
var offsetBottom = offset.bottom
var scrollHeight = Math.max($(document).height(), $(document.body).height())
if (typeof offset != 'object') offsetBottom = offsetTop = offset
if (typeof offsetTop == 'function') offsetTop = offset.top(this.$element)
if (typeof offsetBottom == 'function') offsetBottom = offset.bottom(this.$element)
var affix = this.getState(scrollHeight, height, offsetTop, offsetBottom)
if (this.affixed != affix) {
if (this.unpin != null) this.$element.css('top', '')
var affixType = 'affix' + (affix ? '-' + affix : '')
var e = $.Event(affixType + '.bs.affix')
this.$element.trigger(e)
if (e.isDefaultPrevented()) return
this.affixed = affix
this.unpin = affix == 'bottom' ? this.getPinnedOffset() : null
this.$element
.removeClass(Affix.RESET)
.addClass(affixType)
.trigger(affixType.replace('affix', 'affixed') + '.bs.affix')
}
if (affix == 'bottom') {
this.$element.offset({
top: scrollHeight - height - offsetBottom
})
}
}
// AFFIX PLUGIN DEFINITION
// =======================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.affix')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.affix', (data = new Affix(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.affix
$.fn.affix = Plugin
$.fn.affix.Constructor = Affix
// AFFIX NO CONFLICT
// =================
$.fn.affix.noConflict = function () {
$.fn.affix = old
return this
}
// AFFIX DATA-API
// ==============
$(window).on('load', function () {
$('[data-spy="affix"]').each(function () {
var $spy = $(this)
var data = $spy.data()
data.offset = data.offset || {}
if (data.offsetBottom != null) data.offset.bottom = data.offsetBottom
if (data.offsetTop != null) data.offset.top = data.offsetTop
Plugin.call($spy, data)
})
})
}(jQuery);
| mit |
aseber/YoutubeFileDownloader | YoutubeFileDownloaderGui/Program.cs | 525 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace YoutubeFileDownloaderGui
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
| mit |
Aly91/TheGreatAdventure | TheAmazingAdventure/src/Bullet.java | 628 | import org.newdawn.slick.AppGameContainer;
import org.newdawn.slick.state.StateBasedGame;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.SlickException;
public class Bullet extends Game
{
float bulletX;
float bulletY;
float bulletSpeed;
public void bullet()
{
bulletX = 10;
bulletY= 10;
bulletSpeed = 10.0f;
}
public void render(GameContainer gameContainer, StateBasedGame game, Graphics g)
{
g.drawLine(bulletX,10, bulletY,10);
}
public void update(GameContainer gameContainer, StateBasedGame game, Graphics g, int delta)
{
}
} | mit |
gampleman/ice_cube | spec/examples/monthly_rule_spec.rb | 4610 | require File.dirname(__FILE__) + '/../spec_helper'
module IceCube
describe MonthlyRule do
it 'should produce the correct number of days for @interval = 1' do
schedule = Schedule.new(t0 = Time.now)
schedule.add_recurrence_rule Rule.monthly
#check assumption
schedule.occurrences(t0 + 50 * ONE_DAY).size.should == 2
end
it 'should produce the correct number of days for @interval = 2' do
schedule = Schedule.new(t0 = Time.now)
schedule.add_recurrence_rule Rule.monthly(2)
schedule.occurrences(t0 + 50 * ONE_DAY).size.should == 1
end
it 'should produce the correct number of days for @interval = 1 with only the 1st and 15th' do
schedule = Schedule.new(t0 = Time.utc(2010, 1, 1))
schedule.add_recurrence_rule Rule.monthly.day_of_month(1, 15)
#check assumption (1) (15) (1) (15)
schedule.occurrences(t0 + 50 * ONE_DAY).map(&:day).should == [1, 15, 1, 15]
end
it 'should produce the correct number of days for @interval = 1 with only the 1st and last' do
schedule = Schedule.new(t0 = Time.utc(2010, 1, 1))
schedule.add_recurrence_rule Rule.monthly.day_of_month(1, -1)
#check assumption (1) (31) (1)
schedule.occurrences(t0 + 60 * ONE_DAY).map(&:day).should == [1, 31, 1, 28, 1]
end
it 'should produce the correct number of days for @interval = 1 with only the first mondays' do
schedule = Schedule.new(t0 = Time.utc(2010, 1, 1))
schedule.add_recurrence_rule Rule.monthly.day_of_week(:monday => [1])
#check assumption (month 1 monday) (month 2 monday)
schedule.occurrences(t0 + 50 * ONE_DAY).size.should == 2
end
it 'should produce the correct number of days for @interval = 1 with only the last mondays' do
schedule = Schedule.new(t0 = Time.utc(2010, 1, 1))
schedule.add_recurrence_rule Rule.monthly.day_of_week(:monday => [-1])
#check assumption (month 1 monday)
schedule.occurrences(t0 + 40 * ONE_DAY).size.should == 1
end
it 'should produce the correct number of days for @interval = 1 with only the first and last mondays' do
t0 = Time.utc(2010, 1, 1)
t1 = Time.utc(2010, 12, 31)
schedule = Schedule.new(t0)
schedule.add_recurrence_rule Rule.monthly.day_of_week(:monday => [1, -2])
#check assumption (12 months - 2 dates each)
schedule.occurrences(t1).size.should == 24
end
it 'should occur on every first day of a month at midnight and not skip months when DST ends' do
[:sunday, :monday, :tuesday, :wednesday, :thursday, :friday, :saturday].each_with_index do |weekday, wday|
schedule = Schedule.new(t0 = Time.local(2011, 8, 1))
schedule.add_recurrence_rule Rule.monthly.day_of_week(weekday => [1])
last_date = nil
schedule.first(48).each do |current_date|
current_date.wday.should == wday
current_date.hour.should == 0
if last_date then
month_interval = (current_date.year * 12 + current_date.month) -
(last_date.year * 12 + last_date.month)
# should not skip months
month_interval.should == 1
end
last_date = current_date
end
end
end
it 'should produce dates on a monthly interval for the last day of the month' do
schedule = Schedule.new(t0 = Time.utc(2010, 3, 31, 0, 0, 0))
schedule.add_recurrence_rule Rule.monthly
schedule.first(10).should == [
Time.utc(2010, 3, 31, 0, 0, 0), Time.utc(2010, 4, 30, 0, 0, 0),
Time.utc(2010, 5, 31, 0, 0, 0), Time.utc(2010, 6, 30, 0, 0, 0),
Time.utc(2010, 7, 31, 0, 0, 0), Time.utc(2010, 8, 31, 0, 0, 0),
Time.utc(2010, 9, 30, 0, 0, 0), Time.utc(2010, 10, 31, 0, 0, 0),
Time.utc(2010, 11, 30, 0, 0, 0), Time.utc(2010, 12, 31, 0, 0, 0)
]
end
it 'should produce dates on a monthly interval for latter days in the month near February' do
schedule = Schedule.new(t0 = Time.utc(2010, 1, 29, 0, 0, 0))
schedule.add_recurrence_rule Rule.monthly
schedule.first(3).should == [
Time.utc(2010, 1, 29, 0, 0, 0),
Time.utc(2010, 2, 28, 0, 0, 0),
Time.utc(2010, 3, 29, 0, 0, 0)
]
end
it 'should restrict to available days of month when specified' do
schedule = Schedule.new(t0 = Time.utc(2013,1,31))
schedule.add_recurrence_rule Rule.monthly.day_of_month(31)
schedule.first(3).should == [
Time.utc(2013, 1, 31),
Time.utc(2013, 3, 31),
Time.utc(2013, 5, 31)
]
end
end
end
| mit |
zeusdeux/password-manager | webpack.config.babel.js | 2454 | /**
* This config handles jsx compilation, es6 compilation
* and css handling.
*
* JS & JSX:
* --------
* babel-loader is used in conjuction with the setup in
* .babelrc to transpile JS and transform JSX into calls
* that utilize `h` from preact instead of what React
* provides.
*
* CSS (OLD WAY):
* -------------
* style-loader/url is used to convert import './style.css'
* into a url that is injected into the page that uses the module
* that had imported the style.css file.
* file-loader is used to emit the required object as file and to
* return its public url. publicPath helps form the public url
* and maps it to the where the bundle is written (output.path)
*
* CSS (CURRENT WAY):
* -----------------
* All css text is extracted using the extract-text-webpack-plugin.
* It is then written to output.path with the contenthash (same as
* chunkhash but extract text plugin calls it contenthash) appended
* to the filename. The contenthash depends on the content of the
* file hence it remains constant across builds if the file contents
* are the same. Same goes for chunkhash used with javascript files.
*
* HTML:
* ----
* index.html is now generated by webpack using index.template.html
* The html-webpack-plugin adds all the assets (which have hashes in
* their file names) to the generated index.html. It adds styles
* in the <head> and by default the js just before </body>.
* This makes it straightforward to add assets that have hashes
* in their file names.
*
*/
import { resolve } from 'path'
import ExtractTextPlugin from 'extract-text-webpack-plugin'
import HtmlWebpackPlugin from 'html-webpack-plugin'
export default {
entry: './views/app.js',
output: {
filename: 'app.[chunkhash].bundle.js',
path: resolve(__dirname, './views/public/')
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: 'babel-loader'
},
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: 'css-loader'
})
}
]
},
plugins: [
new ExtractTextPlugin({
filename: 'app.[contenthash].css',
disable: false,
allChunks: true
}),
new HtmlWebpackPlugin({
template: 'views/index.template.html',
filename: 'index.html',
showErrors: true,
inject: true
})
],
devtool: 'inline-source-map',
target: 'electron'
}
| mit |
Juanjors/Spring-MVC | SpringGit/src/curso/microforum/jee/spring/RajoyController.java | 805 | package curso.microforum.jee.spring;
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.support.RequestContextUtils;
@Controller
public class RajoyController {
@RequestMapping("/rajoy")
public String rajao(){
return "rajoy";
}
@RequestMapping("/rajoyi")
public String rajaoDefecto(HttpServletRequest request,HttpServletResponse response){
LocaleResolver locale = RequestContextUtils.getLocaleResolver(request);
Locale loc = new Locale("IT");
locale.setLocale(request, response, loc);
return "rajoyi";
}
}
| mit |
joetde/LucyTheMoocher | LucyTheMoocher/app/src/main/java/com/lucythemoocher/graphics/Background.java | 3584 | package com.lucythemoocher.graphics;
import com.lucythemoocher.R;
import com.lucythemoocher.Globals.Globals;
import com.lucythemoocher.util.MathUtil;
/**
* Background of the level\n
* Randomly generated with elementary blocks.\n
* The sizes of images (in the grids) must be multiples.
* Can be rendered by the Camera
* @see Camera#drawBackground(Background)
*
*/
public class Background implements Drawable {
private Grid backgroundUp_;
private Grid backgroundDown_;
private Grid backgroundMiddle_;
private int[][] mapping_;
private float pxH_;
private float pxW_;
private int nbBoxH_;
private int nbBoxW_;
/**
* Constructor
* @todo
*/
public Background() {
backgroundUp_ = new Grid(R.drawable.background_up);
backgroundDown_ = new Grid(R.drawable.background_down);
backgroundMiddle_ = new Grid(R.drawable.background_middle);
pxH_ = Globals.getInstance().getGame().getMap().pxH()*Camera.BACKGROUNDSPEED + 2*Globals.getInstance().getCamera().h();
pxW_ = Globals.getInstance().getGame().getMap().pxW()*Camera.BACKGROUNDSPEED + 2*Globals.getInstance().getCamera().w();
nbBoxH_ = (int) (pxH_/backgroundDown_.boxH());
nbBoxW_ = (int) (pxW_/backgroundDown_.boxW());
mapping_ = new int[nbBoxH_][nbBoxW_];
for (int i=0; i<nbBoxH_; i++) {
for (int j=0; j<nbBoxW_; j++) {
if ( i == pxH_/2 ) {
mapping_[i][j] = MathUtil.uniform(0, backgroundMiddle_.getSize()-1);
} else if ( i < pxH_/2 ) {
mapping_[i][j] = MathUtil.uniform(0, backgroundUp_.getSize()-1);
} else {
mapping_[i][j] = MathUtil.uniform(0, backgroundDown_.getSize()-1);
}
}
}
}
/**
* Draw the Background properly in the Camera
* (according to the Camera's position)
* @see Camera
*/
public void draw() {
Globals.getInstance().getCamera().drawBackground(this);
}
/**
* Action asked by the camera
* @param x position of the screen in function of the background
* @param y position of the screen in function of the background
* @see Camera
*/
void draw(float x, float y) {
int i = (int) (y/backgroundUp_.boxW());
int j = (int) (x/backgroundUp_.boxH());
int h = (int) (Globals.getInstance().getCamera().h()/backgroundUp_.boxH())+2;
int w = (int) (Globals.getInstance().getCamera().w()/backgroundUp_.boxW())+2;
float offsetX = x-j*backgroundUp_.boxH();
float offsetY = y-i*backgroundUp_.boxW();
for ( int ii=i; ii<i+h && ii<nbBoxH_ ; ii++) {
if ( ii == nbBoxH_/2 ) {
if ( j%(backgroundMiddle_.boxW()/backgroundUp_.boxW()) != 0 ) {
Globals.getInstance().getCamera().drawBackground(
getImage(ii,
(int) (j-j%(backgroundMiddle_.boxW()/backgroundUp_.boxW()))),
(-j%(backgroundMiddle_.boxW()/backgroundUp_.boxW()))*backgroundUp_.boxW()-offsetX,
(ii-i)*backgroundUp_.boxH()-offsetY);
}
}
for ( int jj=j; jj<j+w && jj<nbBoxW_ ; jj++ ) {
if ( ii == nbBoxH_/2 ) {
if ( jj%(backgroundMiddle_.boxW()/backgroundUp_.boxW()) == 0 ) {
Globals.getInstance().getCamera().drawBackground(
getImage(ii,jj), (jj-j)*backgroundUp_.boxW()-offsetX, (ii-i)*backgroundUp_.boxH()-offsetY);
}
} else {
Globals.getInstance().getCamera().drawBackground(
getImage(ii,jj), (jj-j)*backgroundUp_.boxW()-offsetX, (ii-i)*backgroundUp_.boxH()-offsetY);
}
}
}
}
private Image getImage(int i, int j) {
if ( i == nbBoxH_/2 ) {
return backgroundMiddle_.getImage(mapping_[i][j]);
} else if ( i < nbBoxH_/2 ) {
return backgroundUp_.getImage(mapping_[i][j]);
} else {
return backgroundDown_.getImage(mapping_[i][j]);
}
}
}
| mit |
venanciolm/afirma-ui-miniapplet_x_x | afirma_ui_miniapplet/src/main/java/es/gob/afirma/keystores/AOKeyStoreManager.java | 12208 | /* Copyright (C) 2011 [Gobierno de Espana]
* This file is part of "Cliente @Firma".
* "Cliente @Firma" 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.
* - or The European Software License; either version 1.1 or (at your option) any later version.
* Date: 11/01/11
* You may contact the copyright holder at: [email protected]
*/
package es.gob.afirma.keystores;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableEntryException;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Logger;
import javax.security.auth.callback.PasswordCallback;
import es.gob.afirma.core.keystores.KeyStoreManager;
/** Clase gestora de claves y certificados. Básicamente se encarga de
* crear KeyStores de distintos tipos, utilizando el proveedor JCA apropiado para cada caso
* @version 0.4 */
public class AOKeyStoreManager implements KeyStoreManager {
protected static final Logger LOGGER = Logger.getLogger("es.gob.afirma"); //$NON-NLS-1$
private String[] cachedAliases = null;
protected void resetCachedAliases() {
this.cachedAliases = null;
}
protected String[] getCachedAliases() {
return this.cachedAliases;
}
protected void setCachedAliases(final String[] ca) {
this.cachedAliases = ca.clone();
}
/** Tipo de almacén. */
private AOKeyStore ksType;
/** Almacenes de claves. */
private KeyStore ks;
protected void setKeyStore(final KeyStore k) {
if (k == null) {
throw new IllegalArgumentException("El almacen no puede ser nulo"); //$NON-NLS-1$
}
this.ks = k;
}
protected KeyStore getKeyStore() {
return this.ks;
}
@Override
public void refresh() throws IOException {
resetCachedAliases();
try {
this.init(this.ksType, this.storeIs, this.callBack, this.storeParams, true);
}
catch (final AOKeyStoreManagerException e) {
throw new IOException("Error al refrescar el almacen: " + e, e); //$NON-NLS-1$
}
}
protected boolean lacksKeyStores() {
return this.ks == null;
}
protected final void setKeyStoreType(final AOKeyStore type) {
this.ksType = type;
}
/** Devuelve el tipo de almacén de claves.
* @return Tipo de almacén de claves */
public AOKeyStore getType() {
return this.ksType;
}
private InputStream storeIs;
private PasswordCallback callBack;
private Object[] storeParams;
/** Inicializa el almacén. Se encarga también de añadir o
* retirar los <i>Provider</i> necesarios para operar con dicho almacén
* @param type Tipo del almacén de claves
* @param store Flujo para la lectura directa del almacén de claves
* (solo para los almacenes en disco)
* @param pssCallBack CallBack encargado de recuperar la contraseña del Keystore
* @param params Parámetros adicionales (dependen del tipo de almacén)
* @param forceReset Fuerza un reinicio del almacén, no se reutiliza una instancia previa
* @throws AOKeyStoreManagerException Cuando ocurre cualquier problema durante la inicialización
* @throws IOException Se ha insertado una contraseña incorrecta para la apertura del
* almacén de certificados.
* @throws es.gob.afirma.core.MissingLibraryException Cuando faltan bibliotecas necesarias para la inicialización
* @throws es.gob.afirma.core.InvalidOSException Cuando se pide un almacén disponible solo en un sistema operativo
* distinto al actual */
public void init(final AOKeyStore type,
final InputStream store,
final PasswordCallback pssCallBack,
final Object[] params,
final boolean forceReset) throws AOKeyStoreManagerException,
IOException {
if (type == null) {
throw new IllegalArgumentException("Se ha solicitado inicializar un AOKeyStore nulo"); //$NON-NLS-1$
}
LOGGER.info("Inicializamos el almacen de tipo: " + type); //$NON-NLS-1$
resetCachedAliases();
// Guardamos los parametros de inicializacion por si hay que reiniciar
this.ksType = type;
this.storeIs = store;
this.callBack = pssCallBack;
if (params == null) {
this.storeParams = null;
}
else {
// Copia defensiva ante mutaciones
this.storeParams = new Object[params.length];
System.arraycopy(params, 0, this.storeParams, 0, params.length);
}
switch(this.ksType) {
case SINGLE:
this.ks = AOKeyStoreManagerHelperSingle.initSingle(store, pssCallBack);
break;
case CERES:
this.ks = AOKeyStoreManagerHelperFullJava.initCeresJava(
params != null && params.length > 0 ? params[0] : null
);
break;
case DNIEJAVA:
// En el "params" debemos traer los parametros:
// [0] -parent: Componente padre para la modalidad
this.ks = AOKeyStoreManagerHelperFullJava.initDnieJava(
pssCallBack,
params != null && params.length > 0 ? params[0] : null
);
break;
case JAVACE:
case JCEKS:
this.ks = AOKeyStoreManagerHelperJava.initJava(store, pssCallBack, this.ksType);
break;
case WINCA:
case WINADDRESSBOOK:
this.ks = AOKeyStoreManagerHelperCapiAddressBook.initCAPIAddressBook(this.ksType);
break;
case PKCS11:
// En el "params" debemos traer los parametros:
// [0] -p11lib: Biblioteca PKCS#11, debe estar en el Path (Windows) o en el LD_LIBRARY_PATH (UNIX, Linux, Mac OS X)
// [1] -desc: Descripcion del token PKCS#11 (opcional)
// [2] -slot: Numero de lector de tarjeta (Sistema Operativo) [OPCIONAL]
// Hacemos una copia por la mutabilidad
Object[] newParams = null;
if (params != null) {
newParams = new Object[params.length];
System.arraycopy(params, 0, newParams, 0, params.length);
}
this.ks = AOKeyStoreManagerHelperPkcs11.initPKCS11(pssCallBack, newParams);
break;
case APPLE:
this.ks = AOKeyStoreManagerHelperApple.initApple(store);
break;
default:
throw new UnsupportedOperationException("Tipo de almacen no soportado: " + store); //$NON-NLS-1$
}
}
@Override
public KeyStore.PrivateKeyEntry getKeyEntry(final String alias,
final PasswordCallback pssCallback) throws KeyStoreException,
NoSuchAlgorithmException,
UnrecoverableEntryException {
if (this.ks == null) {
throw new IllegalStateException("Se han pedido claves a un almacen no inicializado"); //$NON-NLS-1$
}
if (alias == null) {
throw new IllegalArgumentException("El alias no puede ser nulo"); //$NON-NLS-1$
}
return (KeyStore.PrivateKeyEntry) this.ks.getEntry(alias, pssCallback != null ? new KeyStore.PasswordProtection(pssCallback.getPassword()) : null);
}
@Override
public X509Certificate getCertificate(final String alias) {
if (alias == null) {
LOGGER.warning("El alias del certificado es nulo, se devolvera null"); //$NON-NLS-1$
return null;
}
if (this.ks == null) {
LOGGER.warning(
"No se ha podido recuperar el certificado con alias '" + alias + "' porque el KeyStore no estaba inicializado, se devolvera null" //$NON-NLS-1$ //$NON-NLS-2$
);
return null;
}
try {
return (X509Certificate) this.ks.getCertificate(alias);
}
catch(final Exception e) {
LOGGER.severe(
"Error intentando recuperar el certificado con el alias '" + alias + "', se devolvera null: " + e //$NON-NLS-1$ //$NON-NLS-2$
);
return null;
}
}
@Override
public X509Certificate[] getCertificateChain(final String alias) {
if (alias == null) {
LOGGER.warning("El alias del certificado es nulo, se devolvera una cadena vacia"); //$NON-NLS-1$
return new X509Certificate[0];
}
if (this.ks == null) {
LOGGER.warning(
"No se ha podido recuperar el certificado con alias '" + alias + "' porque el KeyStore no estaba inicializado, se devolvera una cadena vacia" //$NON-NLS-1$ //$NON-NLS-2$
);
return new X509Certificate[0];
}
try {
// No hacemos directamente el Cast de Certificate[] a X509Certificate[] porque
// en ciertas ocasiones encontramos errores en el proceso, especialmente en OS X
final Certificate[] certs = this.ks.getCertificateChain(alias);
if (certs == null) {
return new X509Certificate[0];
}
final List<X509Certificate> ret = new ArrayList<X509Certificate>();
for (final Certificate c : certs) {
if (c instanceof X509Certificate) {
ret.add((X509Certificate) c);
}
}
return ret.toArray(new X509Certificate[0]);
}
catch(final Exception e) {
LOGGER.severe(
"Error intentando recuperar la cadena del certificado con alias '" + alias + "', se continuara con el siguiente almacen: " + e //$NON-NLS-1$ //$NON-NLS-2$
);
}
LOGGER.warning("El almacen no contiene ningun certificado con el alias '" + alias + "', se devolvera una cadena vacia"); //$NON-NLS-1$ //$NON-NLS-2$
return new X509Certificate[0];
}
@Override
public String[] getAliases() {
if (this.ks == null) {
throw new IllegalStateException("Se han pedido alias a un almacen no inicializado"); //$NON-NLS-1$
}
if (this.cachedAliases != null) {
return this.cachedAliases;
}
try {
this.cachedAliases = Collections.list(this.ks.aliases()).toArray(new String[0]);
}
catch (final KeyStoreException e) {
LOGGER.severe(
"Error intentando recuperar los alias, se devolvera una lista vacia: " + e //$NON-NLS-1$
);
return new String[0];
}
return this.cachedAliases;
}
@Override
public String toString() {
final StringBuilder ret = new StringBuilder("Gestor de almacenes de claves"); //$NON-NLS-1$
if (this.ksType != null) {
String tmpStr = this.ksType.getName();
if (tmpStr != null) {
ret.append(" de tipo "); //$NON-NLS-1$
ret.append(tmpStr);
}
tmpStr = this.ksType.getName();
if (tmpStr != null) {
ret.append(" con nombre "); //$NON-NLS-1$
ret.append(tmpStr);
}
ret.append(" de clase "); //$NON-NLS-1$
ret.append(this.ksType.toString());
}
return ret.toString();
}
@Override
public boolean isKeyEntry(final String alias) throws KeyStoreException {
return getKeyStore().isKeyEntry(alias);
}
}
| mit |
openforis/collect-mobile | android/src/main/java/org/openforis/collect/android/gui/input/AverageAngle.java | 1439 | package org.openforis.collect.android.gui.input;
public class AverageAngle {
private double[] mValues;
private int mCurrentIndex;
private int mNumberOfFrames;
private boolean mIsFull;
private double mAverageValue = Double.NaN;
public AverageAngle(int frames) {
this.mNumberOfFrames = frames;
this.mCurrentIndex = 0;
this.mValues = new double[frames];
}
public void putValue(double d) {
mValues[mCurrentIndex] = d;
if (mCurrentIndex == mNumberOfFrames - 1) {
mCurrentIndex = 0;
mIsFull = true;
} else {
mCurrentIndex++;
}
updateAverageValue();
}
public double getAverage() {
return this.mAverageValue;
}
private void updateAverageValue() {
int numberOfElementsToConsider = mNumberOfFrames;
if (!mIsFull) {
numberOfElementsToConsider = mCurrentIndex + 1;
}
if (numberOfElementsToConsider == 1) {
this.mAverageValue = mValues[0];
return;
}
// Formula: http://en.wikipedia.org/wiki/Circular_mean
double sumSin = 0.0;
double sumCos = 0.0;
for (int i = 0; i < numberOfElementsToConsider; i++) {
double v = mValues[i];
sumSin += Math.sin(v);
sumCos += Math.cos(v);
}
this.mAverageValue = Math.atan2(sumSin, sumCos);
}
} | mit |
Noneatme/iLife-SA | client/Quests/Scripts/56.lua | 4195 |
--[[
/////// //////////////////
/////// PROJECT: MTA iLife - German Fun Reallife Gamemode
/////// VERSION: 1.7.2
/////// DEVELOPERS: See DEVELOPERS.md in the top folder
/////// LICENSE: See LICENSE.md in the top folder
/////// /////////////////
]]
local QuestID = 56
local Quest = Quests[QuestID]
local QuestFunctions = {}
local QuestElements = {}
--Set this true to lock this script.
local QuestLocked = false
--[[
ACCEPT TRIGGERS HERE
]]
-- ID: QuestID
-- State = Aktueller Queststatus
-- tblData = Zu übertragende Daten
local CallClientQuestScript = function(ID, State, Data)
if (ID == QuestID) and (not QuestLocked) then
if (State == "Accepted") then
QuestFunctions.spawnRaceStartMarker()
end
if (State == "Finished") or (State == "Aborted") then
QuestFunctions.clearQuestScript()
end
end
end
addEventHandler("onClientQuestScript", getRootElement(), CallClientQuestScript)
--[[
TRIGGERS END
]]
--[[
INSERT OWN LOGIC HERE
]]
QuestFunctions.spawnRaceStartMarker = function()
QuestElements["RaceStartMarker"] = createMarker(1346.1611328125, -2356.0732421875, 13.375, "checkpoint", 5, 0, 0, 255)
addEventHandler("onClientMarkerHit", QuestElements["RaceStartMarker"], QuestFunctions.hitRaceStartMarker)
end
QuestFunctions.hitRaceStartMarker = function(hitElement, matching)
if ( hitElement == localPlayer ) and matching then
if isPedInVehicle(hitElement) then
removeEventHandler("onClientMarkerHit", QuestElements["RaceStartMarker"], QuestFunctions.hitRaceStartMarker)
destroyElement(QuestElements["RaceStartMarker"])
QuestElements["RaceFinishMarker"] = createMarker(-2466.0625, 2249.146484375, 4.7998533248901, "checkpoint", 5, 0, 255, 0)
addEventHandler("onClientMarkerHit", QuestElements["RaceFinishMarker"], QuestFunctions.hitRaceFinishMarker)
QuestElements["RaceStartTick"] = getTickCount()
outputChatBox("Fahre zum Parkplatz am Leuchtturm in BaySide!", 0, 180, 0)
else
outputChatBox("Du ben\\oetigst ein Fahrzeug!", 180, 0, 0)
end
end
end
QuestFunctions.hitRaceFinishMarker = function(hitElement, matching)
if ( hitElement == localPlayer ) and matching then
removeEventHandler("onClientMarkerHit", QuestElements["RaceFinishMarker"], QuestFunctions.hitRaceFinishMarker)
destroyElement(QuestElements["RaceFinishMarker"])
QuestElements["RaceFinishTick"] = getTickCount()
QuestElements["RaceTickDiff"] = QuestElements["RaceFinishTick"] - QuestElements["RaceStartTick"]
if ( QuestElements["RaceTickDiff"] <= 240000 ) then
outputChatBox("Du hast es geschafft!", 0, 180, 0)
if ( QuestElements["RaceTickDiff"] <= 160000 ) then
triggerServerQuestScript(QuestID, "RaceFinishedFast", nil)
else
triggerServerQuestScript(QuestID, "RaceFinished", nil)
end
else
QuestElements["RaceStartTick"] = nil
QuestElements["RaceFinishTick"] = nil
QuestElements["RaceTickDiff"] = nil
outputChatBox("Du warst leider zu langsam. Versuche es noch einmal!", 180, 0, 0)
QuestFunctions.spawnRaceStartMarker()
end
end
end
QuestFunctions.clearEventHandler = function()
if isElement(QuestElements["RaceStartMarker"]) then
removeEventHandler("onClientMarkerHit", QuestElements["RaceStartMarker"], QuestFunctions.hitRaceStartMarker)
end
if isElement(QuestElements["RaceFinishMarker"]) then
removeEventHandler("onClientMarkerHit", QuestElements["RaceFinishMarker"], QuestFunctions.hitRaceFinishMarker)
end
end
--[[
OWN LOGIC END
]]
QuestFunctions.clearQuestScript = function()
outputDebugString("Unloading Questscript: client/Quests/Scripts/"..tostring(QuestID)..".lua")
--Lock Script
QuestLocked = true
--Unload Script
QuestFunctions.clearEventHandler()
removeEventHandler("onClientQuestScript", getRootElement(), CallClientQuestScript)
CallClientQuestScript = nil
Quest = nil
QuestID = nil
for k,v in pairs(QuestFunctions) do
QuestFunctions[k] = nil
end
QuestFunctions = nil
for k,v in pairs(QuestElements) do
if (isElement(v)) then
destroyElement(v)
end
QuestElements[k] = nil
end
QuestElements = nil
QuestFunctions = nil
QuestLocked = nil
--Unloading done!
end
outputDebugString("Loaded Questscript: client/Quests/Scripts/"..tostring(QuestID)..".lua") | mit |
ttokutake/kic | src/command/version.rs | 453 | use error::{CliError, Usage, UsageKind};
use super::Command;
use constant::VERSION;
#[derive(Debug)]
pub struct Version;
impl Command for Version {
fn allow_to_check_current_dir(&self) -> bool { false }
fn allow_to_check_settings(&self) -> bool { false }
fn usage(&self) -> Usage {
return Usage::new(UsageKind::Version);
}
fn main(&self) -> Result<(), CliError> {
println!("{}", VERSION);
Ok(())
}
}
| mit |
tm1990/MiscItemsAndBlocks | common/Mod/Block/ModBlockOrangeLeaf.java | 12329 | package Mod.Block;
import java.util.ArrayList;
import java.util.Random;
import net.minecraft.block.Block;
import net.minecraft.block.BlockLeaves;
import net.minecraft.block.BlockLeavesBase;
import net.minecraft.block.material.Material;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.texture.IconRegister;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.Icon;
import net.minecraft.world.ColorizerFoliage;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.common.IShearable;
import Mod.Items.ModItems;
import Mod.Lib.Refrence;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class ModBlockOrangeLeaf extends BlockLeavesBase implements IShearable
{
int[] adjacentTreeBlocks;
private int iconType;
protected ModBlockOrangeLeaf(int par1)
{
super(par1, Material.leaves, false);
this.setTickRandomly(true);
this.setStepSound(soundGrassFootstep);
this.setHardness(0.7F);
}
@SideOnly(Side.CLIENT)
public int getBlockColor()
{
double d0 = 0.5D;
double d1 = 1.0D;
return ColorizerFoliage.getFoliageColor(d0, d1);
}
@SideOnly(Side.CLIENT)
public int colorMultiplier(IBlockAccess par1IBlockAccess, int par2, int par3, int par4)
{
int l = par1IBlockAccess.getBlockMetadata(par2, par3, par4);
if ((l & 3) == 1)
{
return ColorizerFoliage.getFoliageColorPine();
}
else if ((l & 3) == 2)
{
return ColorizerFoliage.getFoliageColorBirch();
}
else
{
int i1 = 0;
int j1 = 0;
int k1 = 0;
for (int l1 = -1; l1 <= 1; ++l1)
{
for (int i2 = -1; i2 <= 1; ++i2)
{
int j2 = par1IBlockAccess.getBiomeGenForCoords(par2 + i2, par4 + l1).getBiomeFoliageColor();
i1 += (j2 & 16711680) >> 16;
j1 += (j2 & 65280) >> 8;
k1 += j2 & 255;
}
}
return (i1 / 9 & 255) << 16 | (j1 / 9 & 255) << 8 | k1 / 9 & 255;
}
}
public boolean isOpaqueCube()
{
return false;
}
@SideOnly(Side.CLIENT)
public int getRenderColor(int par1)
{
return (par1 & 3) == 1 ? ColorizerFoliage.getFoliageColorPine() : ((par1 & 3) == 2 ? ColorizerFoliage.getFoliageColorBirch() : ColorizerFoliage.getFoliageColorBasic());
}
public void breakBlock(World par1World, int par2, int par3, int par4, int par5, int par6)
{
byte b0 = 1;
int j1 = b0 + 1;
if (par1World.checkChunksExist(par2 - j1, par3 - j1, par4 - j1, par2 + j1, par3 + j1, par4 + j1))
{
for (int k1 = -b0; k1 <= b0; ++k1)
{
for (int l1 = -b0; l1 <= b0; ++l1)
{
for (int i2 = -b0; i2 <= b0; ++i2)
{
int j2 = par1World.getBlockId(par2 + k1, par3 + l1, par4 + i2);
if (Block.blocksList[j2] != null)
{
Block.blocksList[j2].beginLeavesDecay(par1World, par2 + k1, par3 + l1, par4 + i2);
}
}
}
}
}
}
public void updateTick(World par1World, int par2, int par3, int par4, Random par5Random)
{
if (!par1World.isRemote)
{
int l = par1World.getBlockMetadata(par2, par3, par4);
if ((l & 8) != 0 && (l & 4) == 0)
{
byte b0 = 4;
int i1 = b0 + 1;
byte b1 = 32;
int j1 = b1 * b1;
int k1 = b1 / 2;
if (this.adjacentTreeBlocks == null)
{
this.adjacentTreeBlocks = new int[b1 * b1 * b1];
}
int l1;
if (par1World.checkChunksExist(par2 - i1, par3 - i1, par4 - i1, par2 + i1, par3 + i1, par4 + i1))
{
int i2;
int j2;
int k2;
for (l1 = -b0; l1 <= b0; ++l1)
{
for (i2 = -b0; i2 <= b0; ++i2)
{
for (j2 = -b0; j2 <= b0; ++j2)
{
k2 = par1World.getBlockId(par2 + l1, par3 + i2, par4 + j2);
Block block = Block.blocksList[k2];
if (block != null && block.canSustainLeaves(par1World, par2 + l1, par3 + i2, par4 + j2))
{
this.adjacentTreeBlocks[(l1 + k1) * j1 + (i2 + k1) * b1 + j2 + k1] = 0;
}
else if (block != null && block.isLeaves(par1World, par2 + l1, par3 + i2, par4 + j2))
{
this.adjacentTreeBlocks[(l1 + k1) * j1 + (i2 + k1) * b1 + j2 + k1] = -2;
}
else
{
this.adjacentTreeBlocks[(l1 + k1) * j1 + (i2 + k1) * b1 + j2 + k1] = -1;
}
}
}
}
for (l1 = 1; l1 <= 4; ++l1)
{
for (i2 = -b0; i2 <= b0; ++i2)
{
for (j2 = -b0; j2 <= b0; ++j2)
{
for (k2 = -b0; k2 <= b0; ++k2)
{
if (this.adjacentTreeBlocks[(i2 + k1) * j1 + (j2 + k1) * b1 + k2 + k1] == l1 - 1)
{
if (this.adjacentTreeBlocks[(i2 + k1 - 1) * j1 + (j2 + k1) * b1 + k2 + k1] == -2)
{
this.adjacentTreeBlocks[(i2 + k1 - 1) * j1 + (j2 + k1) * b1 + k2 + k1] = l1;
}
if (this.adjacentTreeBlocks[(i2 + k1 + 1) * j1 + (j2 + k1) * b1 + k2 + k1] == -2)
{
this.adjacentTreeBlocks[(i2 + k1 + 1) * j1 + (j2 + k1) * b1 + k2 + k1] = l1;
}
if (this.adjacentTreeBlocks[(i2 + k1) * j1 + (j2 + k1 - 1) * b1 + k2 + k1] == -2)
{
this.adjacentTreeBlocks[(i2 + k1) * j1 + (j2 + k1 - 1) * b1 + k2 + k1] = l1;
}
if (this.adjacentTreeBlocks[(i2 + k1) * j1 + (j2 + k1 + 1) * b1 + k2 + k1] == -2)
{
this.adjacentTreeBlocks[(i2 + k1) * j1 + (j2 + k1 + 1) * b1 + k2 + k1] = l1;
}
if (this.adjacentTreeBlocks[(i2 + k1) * j1 + (j2 + k1) * b1 + (k2 + k1 - 1)] == -2)
{
this.adjacentTreeBlocks[(i2 + k1) * j1 + (j2 + k1) * b1 + (k2 + k1 - 1)] = l1;
}
if (this.adjacentTreeBlocks[(i2 + k1) * j1 + (j2 + k1) * b1 + k2 + k1 + 1] == -2)
{
this.adjacentTreeBlocks[(i2 + k1) * j1 + (j2 + k1) * b1 + k2 + k1 + 1] = l1;
}
}
}
}
}
}
}
l1 = this.adjacentTreeBlocks[k1 * j1 + k1 * b1 + k1];
if (l1 >= 0)
{
par1World.setBlockMetadataWithNotify(par2, par3, par4, l & -9, 4);
}
else
{
this.removeLeaves(par1World, par2, par3, par4);
}
}
}
}
@SideOnly(Side.CLIENT)
public void randomDisplayTick(World par1World, int par2, int par3, int par4, Random par5Random)
{
if (par1World.canLightningStrikeAt(par2, par3 + 1, par4) && !par1World.doesBlockHaveSolidTopSurface(par2, par3 - 1, par4) && par5Random.nextInt(15) == 1)
{
double d0 = (double)((float)par2 + par5Random.nextFloat());
double d1 = (double)par3 - 0.05D;
double d2 = (double)((float)par4 + par5Random.nextFloat());
par1World.spawnParticle("dripWater", d0, d1, d2, 0.0D, 0.0D, 0.0D);
}
}
private void removeLeaves(World par1World, int par2, int par3, int par4)
{
this.dropBlockAsItem(par1World, par2, par3, par4, par1World.getBlockMetadata(par2, par3, par4), 0);
par1World.setBlockToAir(par2, par3, par4);
}
public int quantityDropped(Random par1Random)
{
return par1Random.nextInt(20) == 0 ? 1 : 0;
}
public int idDropped(int par1, Random par2Random, int par3)
{
return ModBlocks.OrangeSapling.blockID;
}
@Override
public void dropBlockAsItemWithChance(World par1World, int par2, int par3, int par4, int par5, float par6, int par7)
{
if (!par1World.isRemote)
{
int j1 = 20;
if ((par5 & 3) == 3)
{
j1 = 40;
}
if (par7 > 0)
{
j1 -= 2 << par7;
if (j1 < 10)
{
j1 = 10;
}
}
if (par1World.rand.nextInt(j1) == 0)
{
int k1 = this.idDropped(par5, par1World.rand, par7);
this.dropBlockAsItem_do(par1World, par2, par3, par4, new ItemStack(k1, 1, this.damageDropped(par5)));
}
if ((par5 & 3) == 0 && par1World.rand.nextInt(20) == 0)
{
this.dropBlockAsItem_do(par1World, par2, par3, par4, new ItemStack(ModItems.Orange, 1, 0));
}
}
}
public void harvestBlock(World par1World, EntityPlayer par2EntityPlayer, int par3, int par4, int par5, int par6)
{
super.harvestBlock(par1World, par2EntityPlayer, par3, par4, par5, par6);
}
public int damageDropped(int par1)
{
return par1 & 3;
}
@SideOnly(Side.CLIENT)
public Icon getIcon(int par1, int meta)
{
return this.blockIcon;
}
@SideOnly(Side.CLIENT)
protected ItemStack createStackedBlock(int par1)
{
return new ItemStack(this.blockID, 1, par1 & 3);
}
@SideOnly(Side.CLIENT)
public void registerIcons(IconRegister par1IconRegister)
{
this.blockIcon = par1IconRegister.registerIcon(Refrence.Mod_Id + ":" + "OrangeLeaf");
}
@Override
public boolean isShearable(ItemStack item, World world, int x, int y, int z)
{
return true;
}
@Override
public ArrayList<ItemStack> onSheared(ItemStack item, World world, int x, int y, int z, int fortune)
{
ArrayList<ItemStack> ret = new ArrayList<ItemStack>();
ret.add(new ItemStack(this, 1, world.getBlockMetadata(x, y, z) & 3));
return ret;
}
@Override
public void beginLeavesDecay(World world, int x, int y, int z)
{
world.setBlockMetadataWithNotify(x, y, z, world.getBlockMetadata(x, y, z) | 8, 4);
}
@Override
public boolean isLeaves(World world, int x, int y, int z)
{
return true;
}
public int getRenderBlockPass()
{
return 0;
}
}
| mit |
GalleonBank/galleon | src/qt/locale/bitcoin_fi.ts | 112910 | <?xml version="1.0" ?><!DOCTYPE TS><TS language="fi" version="2.0">
<defaultcodec>UTF-8</defaultcodec>
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About Galleon</source>
<translation>Tietoa Bitcoinista</translation>
</message>
<message>
<location line="+39"/>
<source><b>Galleon</b> version</source>
<translation><b>Galleon</b> versio</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 ([email protected]) and UPnP software written by Thomas Bernard.</source>
<translation>
Tämä on kokeellinen ohjelmisto.
Levitetään MIT/X11 ohjelmistolisenssin alaisuudessa. Tarkemmat tiedot löytyvät tiedostosta COPYING tai osoitteesta http://www.opensource.org/licenses/mit-license.php.
Tämä ohjelma sisältää OpenSSL projektin OpenSSL työkalupakin (http://www.openssl.org/), Eric Youngin ([email protected]) kehittämän salausohjelmiston sekä Thomas Bernardin UPnP ohjelmiston.
</translation>
</message>
<message>
<location filename="../aboutdialog.cpp" line="+14"/>
<source>Copyright</source>
<translation>Tekijänoikeus</translation>
</message>
<message>
<location line="+0"/>
<source>The Galleon developers</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>Osoitekirja</translation>
</message>
<message>
<location line="+19"/>
<source>Double-click to edit address or label</source>
<translation>Kaksoisnapauta muokataksesi osoitetta tai nimeä</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>Luo uusi osoite</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Kopioi valittu osoite leikepöydälle</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation>&Uusi Osoite</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+63"/>
<source>These are your Galleon 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>Nämä ovat Galleon-osoitteesi joihin voit vastaanottaa maksuja. Voit haluta antaa jokaiselle maksajalle omansa, että pystyt seuraamaan keneltä maksut tulevat.</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>&Copy Address</source>
<translation>&Kopioi Osoite</translation>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation>Näytä &QR-koodi</translation>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a Galleon address</source>
<translation>Allekirjoita viesti todistaaksesi, että omistat Galleon-osoitteen</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>Allekirjoita &viesti</translation>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation>Poista valittu osoite listalta</translation>
</message>
<message>
<location line="+27"/>
<source>Export the data in the current tab to a file</source>
<translation>Vie auki olevan välilehden tiedot tiedostoon</translation>
</message>
<message>
<location line="+3"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-44"/>
<source>Verify a message to ensure it was signed with a specified Galleon address</source>
<translation>Tarkista viestin allekirjoitus varmistaaksesi, että se allekirjoitettiin tietyllä Galleon-osoitteella</translation>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation>&Varmista viesti...</translation>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>&Poista</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="-5"/>
<source>These are your Galleon addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Copy &Label</source>
<translation>Kopioi &Nimi</translation>
</message>
<message>
<location line="+1"/>
<source>&Edit</source>
<translation>&Muokkaa</translation>
</message>
<message>
<location line="+1"/>
<source>Send &Coins</source>
<translation>Lähetä &Rahaa</translation>
</message>
<message>
<location line="+260"/>
<source>Export Address Book Data</source>
<translation>Vie osoitekirja</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Comma separated file (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>Virhe viedessä osoitekirjaa</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Ei voida kirjoittaa tiedostoon %1.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>Nimi</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Osoite</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(ei nimeä)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation>Tunnuslauseen Dialogi</translation>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>Kirjoita tunnuslause</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>Uusi tunnuslause</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>Kiroita uusi tunnuslause uudelleen</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>Anna lompakolle uusi tunnuslause.<br/>Käytä tunnuslausetta, jossa on ainakin <b>10 satunnaista mekkiä</b> tai <b>kahdeksan sanaa</b>.</translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>Salaa lompakko</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Tätä toimintoa varten sinun täytyy antaa lompakon tunnuslause sen avaamiseksi.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>Avaa lompakko</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Tätä toimintoa varten sinun täytyy antaa lompakon tunnuslause salauksen purkuun.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>Pura lompakon salaus</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>Vaihda tunnuslause</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Anna vanha ja uusi tunnuslause.</translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>Vahvista lompakon salaus</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR BITCOINS</b>!</source>
<translation>Varoitus: Jos salaat lompakkosi ja menetät tunnuslauseesi, <b>MENETÄT KAIKKI BITCOINISI</b>!</translation>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>Haluatko varmasti salata lompakkosi?</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>TÄRKEÄÄ: Kaikki vanhat lompakon varmuuskopiot pitäisi korvata uusilla suojatuilla varmuuskopioilla. Turvallisuussyistä edelliset varmuuskopiot muuttuvat turhiksi, kun aloitat suojatun lompakon käytön.</translation>
</message>
<message>
<location line="+100"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation>Varoitus: Caps Lock on käytössä!</translation>
</message>
<message>
<location line="-130"/>
<location line="+58"/>
<source>Wallet encrypted</source>
<translation>Lompakko salattu</translation>
</message>
<message>
<location line="-56"/>
<source>Galleon will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your bitcoins from being stolen by malware infecting your computer.</source>
<translation>Galleon sulkeutuu lopettaakseen salausprosessin. Muista, että salattukaan lompakko ei täysin suojaa sitä haittaohjelmien aiheuttamilta varkauksilta.</translation>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+42"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>Lompakon salaus epäonnistui</translation>
</message>
<message>
<location line="-54"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Lompakon salaaminen epäonnistui sisäisen virheen vuoksi. Lompakkoasi ei salattu.</translation>
</message>
<message>
<location line="+7"/>
<location line="+48"/>
<source>The supplied passphrases do not match.</source>
<translation>Annetut tunnuslauseet eivät täsmää.</translation>
</message>
<message>
<location line="-37"/>
<source>Wallet unlock failed</source>
<translation>Lompakon avaaminen epäonnistui.</translation>
</message>
<message>
<location line="+1"/>
<location line="+11"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>Annettu tunnuslause oli väärä.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>Lompakon salauksen purku epäonnistui.</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>Lompakon tunnuslause vaihdettiin onnistuneesti.</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+233"/>
<source>Sign &message...</source>
<translation>&Allekirjoita viesti...</translation>
</message>
<message>
<location line="+280"/>
<source>Synchronizing with network...</source>
<translation>Synkronoidaan verkon kanssa...</translation>
</message>
<message>
<location line="-349"/>
<source>&Overview</source>
<translation>&Yleisnäkymä</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation>Lompakon tilanteen yleiskatsaus</translation>
</message>
<message>
<location line="+20"/>
<source>&Transactions</source>
<translation>&Rahansiirrot</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>Selaa rahansiirtohistoriaa</translation>
</message>
<message>
<location line="+7"/>
<source>Edit the list of stored addresses and labels</source>
<translation>Muokkaa tallennettujen nimien ja osoitteiden listaa</translation>
</message>
<message>
<location line="-14"/>
<source>Show the list of addresses for receiving payments</source>
<translation>Näytä Bitcoinien vastaanottamiseen käytetyt osoitteet</translation>
</message>
<message>
<location line="+31"/>
<source>E&xit</source>
<translation>L&opeta</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>Sulje ohjelma</translation>
</message>
<message>
<location line="+4"/>
<source>Show information about Galleon</source>
<translation>Näytä tietoa Galleon-projektista</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>Tietoja &Qt</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>Näytä tietoja QT:ta</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>&Asetukset...</translation>
</message>
<message>
<location line="+6"/>
<source>&Encrypt Wallet...</source>
<translation>&Salaa lompakko...</translation>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation>&Varmuuskopioi Lompakko...</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>&Vaihda Tunnuslause...</translation>
</message>
<message>
<location line="+285"/>
<source>Importing blocks from disk...</source>
<translation>Tuodaan lohkoja levyltä</translation>
</message>
<message>
<location line="+3"/>
<source>Reindexing blocks on disk...</source>
<translation>Ladataan lohkoindeksiä...</translation>
</message>
<message>
<location line="-347"/>
<source>Send coins to a Galleon address</source>
<translation>Lähetä kolikoita Galleon-osoitteeseen</translation>
</message>
<message>
<location line="+49"/>
<source>Modify configuration options for Galleon</source>
<translation>Muuta Bitcoinin konfiguraatioasetuksia</translation>
</message>
<message>
<location line="+9"/>
<source>Backup wallet to another location</source>
<translation>Varmuuskopioi lompakko toiseen sijaintiin</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Vaihda lompakon salaukseen käytettävä tunnuslause</translation>
</message>
<message>
<location line="+6"/>
<source>&Debug window</source>
<translation>&Testausikkuna</translation>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation>Avaa debuggaus- ja diagnostiikkakonsoli</translation>
</message>
<message>
<location line="-4"/>
<source>&Verify message...</source>
<translation>Varmista &viesti...</translation>
</message>
<message>
<location line="-165"/>
<location line="+530"/>
<source>Galleon</source>
<translation>Galleon</translation>
</message>
<message>
<location line="-530"/>
<source>Wallet</source>
<translation>Lompakko</translation>
</message>
<message>
<location line="+101"/>
<source>&Send</source>
<translation>&Lähetä</translation>
</message>
<message>
<location line="+7"/>
<source>&Receive</source>
<translation>&Vastaanota</translation>
</message>
<message>
<location line="+14"/>
<source>&Addresses</source>
<translation>&Osoitteet</translation>
</message>
<message>
<location line="+22"/>
<source>&About Galleon</source>
<translation>&Tietoa Bitcoinista</translation>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation>&Näytä / Piilota</translation>
</message>
<message>
<location line="+1"/>
<source>Show or hide the main Window</source>
<translation>Näytä tai piilota Galleon-ikkuna</translation>
</message>
<message>
<location line="+3"/>
<source>Encrypt the private keys that belong to your wallet</source>
<translation>Suojaa yksityiset avaimet, jotka kuuluvat lompakkoosi</translation>
</message>
<message>
<location line="+7"/>
<source>Sign messages with your Galleon addresses to prove you own them</source>
<translation>Allekirjoita viestisi omalla Galleon -osoitteellasi todistaaksesi, että omistat ne</translation>
</message>
<message>
<location line="+2"/>
<source>Verify messages to ensure they were signed with specified Galleon addresses</source>
<translation>Varmista, että viestisi on allekirjoitettu määritetyllä Galleon -osoitteella</translation>
</message>
<message>
<location line="+28"/>
<source>&File</source>
<translation>&Tiedosto</translation>
</message>
<message>
<location line="+7"/>
<source>&Settings</source>
<translation>&Asetukset</translation>
</message>
<message>
<location line="+6"/>
<source>&Help</source>
<translation>&Apua</translation>
</message>
<message>
<location line="+9"/>
<source>Tabs toolbar</source>
<translation>Välilehtipalkki</translation>
</message>
<message>
<location line="+17"/>
<location line="+10"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
<message>
<location line="+47"/>
<source>Galleon client</source>
<translation>Galleon-asiakas</translation>
</message>
<message numerus="yes">
<location line="+141"/>
<source>%n active connection(s) to Galleon network</source>
<translation><numerusform>%n aktiivinen yhteys Galleon-verkkoon</numerusform><numerusform>%n aktiivista yhteyttä Galleon-verkkoon</numerusform></translation>
</message>
<message>
<location line="+22"/>
<source>No block source available...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Processed %1 of %2 (estimated) blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Processed %1 blocks of transaction history.</source>
<translation>Käsitelty %1 lohkoa rahansiirtohistoriasta</translation>
</message>
<message numerus="yes">
<location line="+20"/>
<source>%n hour(s)</source>
<translation><numerusform>%n tunti</numerusform><numerusform>%n tuntia</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n week(s)</source>
<translation><numerusform>%n viikko</numerusform><numerusform>%n viikkoa</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>%1 behind</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Last received block was generated %1 ago.</source>
<translation>Viimeisin vastaanotettu lohko tuotettu %1.</translation>
</message>
<message>
<location line="+2"/>
<source>Transactions after this will not yet be visible.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>Error</source>
<translation>Virhe</translation>
</message>
<message>
<location line="+3"/>
<source>Warning</source>
<translation>Varoitus</translation>
</message>
<message>
<location line="+3"/>
<source>Information</source>
<translation>Tietoa</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 type="unfinished"/>
</message>
<message>
<location line="-140"/>
<source>Up to date</source>
<translation>Rahansiirtohistoria on ajan tasalla</translation>
</message>
<message>
<location line="+31"/>
<source>Catching up...</source>
<translation>Saavutetaan verkkoa...</translation>
</message>
<message>
<location line="+113"/>
<source>Confirm transaction fee</source>
<translation>Vahvista maksukulu</translation>
</message>
<message>
<location line="+8"/>
<source>Sent transaction</source>
<translation>Lähetetyt rahansiirrot</translation>
</message>
<message>
<location line="+0"/>
<source>Incoming transaction</source>
<translation>Saapuva rahansiirto</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Päivä: %1
Määrä: %2
Tyyppi: %3
Osoite: %4</translation>
</message>
<message>
<location line="+33"/>
<location line="+23"/>
<source>URI handling</source>
<translation>URI käsittely</translation>
</message>
<message>
<location line="-23"/>
<location line="+23"/>
<source>URI can not be parsed! This can be caused by an invalid Galleon address or malformed URI parameters.</source>
<translation>URIa ei voitu jäsentää! Tämä voi johtua kelvottomasta Galleon-osoitteesta tai virheellisistä URI parametreista.</translation>
</message>
<message>
<location line="+17"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Lompakko on <b>salattu</b> ja tällä hetkellä <b>avoinna</b></translation>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Lompakko on <b>salattu</b> ja tällä hetkellä <b>lukittuna</b></translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="+111"/>
<source>A fatal error occurred. Galleon can no longer continue safely and will quit.</source>
<translation>Peruuttamaton virhe on tapahtunut. Galleon ei voi enää jatkaa turvallisesti ja sammutetaan.</translation>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+104"/>
<source>Network Alert</source>
<translation>Verkkohälytys</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Muokkaa osoitetta</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>&Nimi</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation>Tähän osoitteeseen liitetty nimi</translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>&Osoite</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>Osoite, joka liittyy tämän osoitekirjan merkintään. Tätä voidaan muuttaa vain lähtevissä osoitteissa.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+21"/>
<source>New receiving address</source>
<translation>Uusi vastaanottava osoite</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>Uusi lähettävä osoite</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>Muokkaa vastaanottajan osoitetta</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>Muokkaa lähtevää osoitetta</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>Osoite "%1" on jo osoitekirjassa.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid Galleon address.</source>
<translation>Antamasi osoite "%1" ei ole validi Galleon-osoite.</translation>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>Lompakkoa ei voitu avata.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>Uuden avaimen luonti epäonnistui.</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+424"/>
<location line="+12"/>
<source>Galleon-Qt</source>
<translation>Galleon-Qt</translation>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation>versio</translation>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation>Käyttö:</translation>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation>komentorivi parametrit</translation>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation>Käyttöliittymäasetukset</translation>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation>Set language, for example "de_DE" (default: system locale)</translation>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation>Käynnistä pienennettynä</translation>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation>Näytä aloitusruutu käynnistettäessä (oletus: 1)</translation>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>Asetukset</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>&Yleiset</translation>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation>Maksa rahansiirtopalkkio</translation>
</message>
<message>
<location line="+31"/>
<source>Automatically start Galleon after logging in to the system.</source>
<translation>Käynnistä Galleon kirjautumisen yhteydessä.</translation>
</message>
<message>
<location line="+3"/>
<source>&Start Galleon on system login</source>
<translation>&Käynnistä Galleon kirjautumisen yhteydessä</translation>
</message>
<message>
<location line="+35"/>
<source>Reset all client options to default.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Reset Options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>&Network</source>
<translation>&Verkko</translation>
</message>
<message>
<location line="+6"/>
<source>Automatically open the Galleon client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>Avaa Galleon-asiakasohjelman portti reitittimellä automaattisesti. Tämä toimii vain, jos reitittimesi tukee UPnP:tä ja se on käytössä.</translation>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation>Portin uudelleenohjaus &UPnP:llä</translation>
</message>
<message>
<location line="+7"/>
<source>Connect to the Galleon network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation>Ota yhteys Galleon-verkkoon SOCKS-proxyn läpi (esimerkiksi kun haluat käyttää Tor-verkkoa).</translation>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation>&Ota yhteys SOCKS-proxyn kautta:</translation>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation>Proxyn &IP:</translation>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation>Välityspalvelimen IP-osoite (esim. 127.0.0.1)</translation>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation>&Portti</translation>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation>Proxyn Portti (esim. 9050)</translation>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation>SOCKS &Versio:</translation>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation>Proxyn SOCKS-versio (esim. 5)</translation>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation>&Ikkuna</translation>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation>Näytä ainoastaan ilmaisinalueella ikkunan pienentämisen jälkeen.</translation>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&Pienennä ilmaisinalueelle työkalurivin sijasta</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>Ikkunaa suljettaessa vain pienentää Galleon-ohjelman ikkunan lopettamatta itse ohjelmaa. Kun tämä asetus on valittuna, ohjelman voi sulkea vain valitsemalla Lopeta ohjelman valikosta.</translation>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation>P&ienennä suljettaessa</translation>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation>&Käyttöliittymä</translation>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation>&Käyttöliittymän kieli</translation>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting Galleon.</source>
<translation>Tässä voit määritellä käyttöliittymän kielen. Muutokset astuvat voimaan seuraavan kerran, kun Galleon käynnistetään.</translation>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation>Yksikkö jona bitcoin-määrät näytetään</translation>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>Valitse mitä yksikköä käytetään ensisijaisesti bitcoin-määrien näyttämiseen.</translation>
</message>
<message>
<location line="+9"/>
<source>Whether to show Galleon addresses in the transaction list or not.</source>
<translation>Näytetäänkö Galleon-osoitteet rahansiirrot listassa vai ei.</translation>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation>&Näytä osoitteet rahansiirrot listassa</translation>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>&OK</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>&Peruuta</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation>&Hyväksy</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+53"/>
<source>default</source>
<translation>oletus</translation>
</message>
<message>
<location line="+130"/>
<source>Confirm options reset</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Some settings may require a client restart to take effect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Do you want to proceed?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+42"/>
<location line="+9"/>
<source>Warning</source>
<translation>Varoitus</translation>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting Galleon.</source>
<translation>Tämä asetus astuu voimaan seuraavalla kerralla, kun Galleon käynnistetään.</translation>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation>Antamasi proxy-osoite on virheellinen.</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>Lomake</translation>
</message>
<message>
<location line="+50"/>
<location line="+166"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the Galleon network after a connection is established, but this process has not completed yet.</source>
<translation>Näytetyt tiedot eivät välttämättä ole ajantasalla. Lompakkosi synkronoituu Galleon-verkon kanssa automaattisesti yhteyden muodostamisen jälkeen, mutta synkronointi on vielä meneillään.</translation>
</message>
<message>
<location line="-124"/>
<source>Balance:</source>
<translation>Saldo:</translation>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation>Vahvistamatta:</translation>
</message>
<message>
<location line="-78"/>
<source>Wallet</source>
<translation>Lompakko</translation>
</message>
<message>
<location line="+107"/>
<source>Immature:</source>
<translation>Epäkypsää:</translation>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation>Louhittu saldo, joka ei ole vielä kypsynyt</translation>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation><b>Viimeisimmät rahansiirrot</b></translation>
</message>
<message>
<location line="-101"/>
<source>Your current balance</source>
<translation>Tililläsi tällä hetkellä olevien Bitcoinien määrä</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>Niiden saapuvien rahansiirtojen määrä, joita Galleon-verkko ei vielä ole ehtinyt vahvistaa ja siten eivät vielä näy saldossa.</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="+116"/>
<location line="+1"/>
<source>out of sync</source>
<translation>Ei ajan tasalla</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+107"/>
<source>Cannot start bitcoin: click-to-pay handler</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation>QR-koodi Dialogi</translation>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation>Vastaanota maksu</translation>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation>Määrä:</translation>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation>Tunniste:</translation>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation>Viesti:</translation>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation>&Tallenna nimellä...</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation>Virhe käännettäessä URI:a QR-koodiksi.</translation>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation>Syötetty määrä on virheellinen. Tarkista kirjoitusasu.</translation>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation>Tuloksen URI liian pitkä, yritä lyhentää otsikon tekstiä / viestiä.</translation>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation>Tallenna QR-koodi</translation>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation>PNG kuvat (*png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation>Pääteohjelman nimi</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>Ei saatavilla</translation>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation>Pääteohjelman versio</translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation>T&ietoa</translation>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation>Käytössä oleva OpenSSL-versio</translation>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation>Käynnistysaika</translation>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>Verkko</translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation>Yhteyksien lukumäärä</translation>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation>Käyttää testiverkkoa</translation>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation>Lohkoketju</translation>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation>Nykyinen Lohkojen määrä</translation>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation>Arvioitu lohkojen kokonaismäärä</translation>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation>Viimeisimmän lohkon aika</translation>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation>&Avaa</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation>Komentorivi parametrit</translation>
</message>
<message>
<location line="+7"/>
<source>Show the Galleon-Qt help message to get a list with possible Galleon command-line options.</source>
<translation>Näytä Galleon-Qt komentoriviparametrien ohjesivu, jossa on listattuna mahdolliset komentoriviparametrit.</translation>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation>&Näytä</translation>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation>&Konsoli</translation>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation>Kääntöpäiväys</translation>
</message>
<message>
<location line="-104"/>
<source>Galleon - Debug window</source>
<translation>Galleon - Debug ikkuna</translation>
</message>
<message>
<location line="+25"/>
<source>Galleon Core</source>
<translation>Galleon-ydin</translation>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation>Debug lokitiedosto</translation>
</message>
<message>
<location line="+7"/>
<source>Open the Galleon debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation>Avaa lokitiedosto nykyisestä data-kansiosta. Tämä voi viedä useamman sekunnin, jos lokitiedosto on iso.</translation>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation>Tyhjennä konsoli</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-30"/>
<source>Welcome to the Galleon RPC console.</source>
<translation>Tervetuloa Galleon RPC konsoliin.</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>Ylös- ja alas-nuolet selaavat historiaa ja <b>Ctrl-L</b> tyhjentää ruudun.</translation>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation>Kirjoita <b>help</b> nähdäksesi yleiskatsauksen käytettävissä olevista komennoista.</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>Lähetä Bitcoineja</translation>
</message>
<message>
<location line="+50"/>
<source>Send to multiple recipients at once</source>
<translation>Lähetä monelle vastaanottajalle</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation>Lisää &Vastaanottaja</translation>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation>Poista kaikki rahansiirtokentät</translation>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>&Tyhjennnä Kaikki</translation>
</message>
<message>
<location line="+22"/>
<source>Balance:</source>
<translation>Saldo:</translation>
</message>
<message>
<location line="+10"/>
<source>123.456 GLN</source>
<translation>123,456 GLN</translation>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation>Vahvista lähetys</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation>&Lähetä</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-59"/>
<source><b>%1</b> to %2 (%3)</source>
<translation><b>%1</b> to %2 (%3)</translation>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>Hyväksy Bitcoinien lähettäminen</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation>Haluatko varmasti lähettää %1?</translation>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation> ja </translation>
</message>
<message>
<location line="+23"/>
<source>The recipient address is not valid, please recheck.</source>
<translation>Vastaanottajan osoite on virheellinen. Tarkista osoite.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>Maksettavan summan tulee olla suurempi kuin 0 Bitcoinia.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation>Määrä ylittää käytettävissä olevan saldon.</translation>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>Kokonaismäärä ylittää saldosi kun %1 maksukulu lisätään summaan.</translation>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>Sama osoite toistuu useamman kerran. Samaan osoitteeseen voi lähettää vain kerran per maksu.</translation>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed!</source>
<translation type="unfinished"/>
</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>Virhe: Rahansiirto hylättiin. Tämä voi tapahtua jos jotkin bitcoineistasi on jo käytetty, esimerkiksi jos olet käyttänyt kopiota wallet.dat-lompakkotiedostosta ja bitcoinit on merkitty käytetyksi vain kopiossa.</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation>Lomake</translation>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation>M&äärä:</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>Maksun saaja:</translation>
</message>
<message>
<location line="+34"/>
<source>The address to send the payment to (e.g. GaHow4sH2pvAYdg41YfgDmGKtzc6suGp9K)</source>
<translation type="unfinished"/>
</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>Anna nimi tälle osoitteelle, jos haluat lisätä sen osoitekirjaan</translation>
</message>
<message>
<location line="-78"/>
<source>&Label:</source>
<translation>&Nimi:</translation>
</message>
<message>
<location line="+28"/>
<source>Choose address from address book</source>
<translation>Valitse osoite osoitekirjasta</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>Liitä osoite leikepöydältä</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>Poista </translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a Galleon address (e.g. GaHow4sH2pvAYdg41YfgDmGKtzc6suGp9K)</source>
<translation>Anna Galleon-osoite (esim. GaHow4sH2pvAYdg41YfgDmGKtzc6suGp9K)</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation>Allekirjoitukset - Allekirjoita / Varmista viesti</translation>
</message>
<message>
<location line="+13"/>
<source>&Sign Message</source>
<translation>&Allekirjoita viesti</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>Voit allekirjoittaa viestit omalla osoitteellasi todistaaksesi että omistat ne. Ole huolellinen, että et allekirjoita mitään epämääräistä, phishing-hyökkääjät voivat huijata sinua allekirjoittamaan luovuttamalla henkilöllisyytesi. Allekirjoita selvitys täysin yksityiskohtaisesti mihin olet sitoutunut.</translation>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. GaHow4sH2pvAYdg41YfgDmGKtzc6suGp9K)</source>
<translation>Osoite, jolla viesti allekirjoitetaan (esimerkiksi GaHow4sH2pvAYdg41YfgDmGKtzc6suGp9K)</translation>
</message>
<message>
<location line="+10"/>
<location line="+213"/>
<source>Choose an address from the address book</source>
<translation>Valitse osoite osoitekirjasta</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>Liitä osoite leikepöydältä</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>Kirjoita tähän viesti minkä haluat allekirjoittaa</translation>
</message>
<message>
<location line="+7"/>
<source>Signature</source>
<translation>Allekirjoitus</translation>
</message>
<message>
<location line="+27"/>
<source>Copy the current signature to the system clipboard</source>
<translation>Kopioi tämänhetkinen allekirjoitus leikepöydälle</translation>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this Galleon address</source>
<translation>Allekirjoita viesti todistaaksesi, että omistat tämän Galleon-osoitteen</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>Allekirjoita &viesti</translation>
</message>
<message>
<location line="+14"/>
<source>Reset all sign message fields</source>
<translation>Tyhjennä kaikki allekirjoita-viesti-kentät</translation>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>&Tyhjennä Kaikki</translation>
</message>
<message>
<location line="-87"/>
<source>&Verify Message</source>
<translation>&Varmista viesti</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>Syötä allekirjoittava osoite, viesti ja allekirjoitus alla oleviin kenttiin varmistaaksesi allekirjoituksen aitouden. Varmista että kopioit kaikki kentät täsmälleen oikein, myös rivinvaihdot, välilyönnit, tabulaattorit, jne.</translation>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. GaHow4sH2pvAYdg41YfgDmGKtzc6suGp9K)</source>
<translation>Osoite, jolla viesti allekirjoitettiin (esimerkiksi GaHow4sH2pvAYdg41YfgDmGKtzc6suGp9K)</translation>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified Galleon address</source>
<translation>Tarkista viestin allekirjoitus varmistaaksesi, että se allekirjoitettiin tietyllä Galleon-osoitteella</translation>
</message>
<message>
<location line="+3"/>
<source>Verify &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Reset all verify message fields</source>
<translation>Tyhjennä kaikki varmista-viesti-kentät</translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a Galleon address (e.g. GaHow4sH2pvAYdg41YfgDmGKtzc6suGp9K)</source>
<translation>Anna Galleon-osoite (esim. GaHow4sH2pvAYdg41YfgDmGKtzc6suGp9K)</translation>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation>Klikkaa "Allekirjoita Viesti luodaksesi allekirjoituksen </translation>
</message>
<message>
<location line="+3"/>
<source>Enter Galleon signature</source>
<translation>Syötä Galleon-allekirjoitus</translation>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation>Syötetty osoite on virheellinen.</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>Tarkista osoite ja yritä uudelleen.</translation>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation>Syötetyn osoitteen avainta ei löydy.</translation>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation>Lompakon avaaminen peruttiin.</translation>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation>Yksityistä avainta syötetylle osoitteelle ei ole saatavilla.</translation>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation>Viestin allekirjoitus epäonnistui.</translation>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation>Viesti allekirjoitettu.</translation>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation>Allekirjoitusta ei pystytty tulkitsemaan.</translation>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation>Tarkista allekirjoitus ja yritä uudelleen.</translation>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation>Allekirjoitus ei täsmää viestin tiivisteeseen.</translation>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation>Viestin varmistus epäonnistui.</translation>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation>Viesti varmistettu.</translation>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<location filename="../splashscreen.cpp" line="+22"/>
<source>The Galleon developers</source>
<translation type="unfinished"/>
</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>Avoinna %1 asti</translation>
</message>
<message>
<location line="+6"/>
<source>%1/offline</source>
<translation>%1/offline</translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/vahvistamaton</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 vahvistusta</translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation>Tila</translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation><numerusform>lähetetty %n noodin läpi</numerusform><numerusform>lähetetty %n noodin läpi</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>Päivämäärä</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation>Lähde</translation>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation>Generoitu</translation>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation>Lähettäjä</translation>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation>Saaja</translation>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation>oma osoite</translation>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation>nimi</translation>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation>Credit</translation>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation><numerusform>kypsyy %n lohkon kuluttua</numerusform><numerusform>kypsyy %n lohkon kuluttua</numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation>ei hyväksytty</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>Maksukulu</translation>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation>Netto määrä</translation>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>Viesti</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation>Viesti</translation>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation>Siirtotunnus</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>Generoitujen kolikoiden täytyy kypsyä 120 lohkon ajan ennen kuin ne voidaan lähettää. Kun loit tämän lohkon, se lähetettiin verkkoon lisättäväksi lohkoketjuun. Jos se ei päädy osaksi lohkoketjua, sen tila vaihtuu "ei hyväksytty" ja sitä ei voida lähettää. Näin voi joskus käydä, jos toinen noodi löytää lohkon muutamaa sekuntia ennen tai jälkeen sinun lohkosi löytymisen.</translation>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation>Debug tiedot</translation>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>Rahansiirto</translation>
</message>
<message>
<location line="+3"/>
<source>Inputs</source>
<translation>Sisääntulot</translation>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation>Määrä</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation>tosi</translation>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation>epätosi</translation>
</message>
<message>
<location line="-209"/>
<source>, has not been successfully broadcast yet</source>
<translation>, ei ole vielä onnistuneesti lähetetty</translation>
</message>
<message numerus="yes">
<location line="-35"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+70"/>
<source>unknown</source>
<translation>tuntematon</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>Rahansiirron yksityiskohdat</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>Tämä ruutu näyttää yksityiskohtaisen tiedon rahansiirrosta</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+225"/>
<source>Date</source>
<translation>Päivämäärä</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>Laatu</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Osoite</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>Määrä</translation>
</message>
<message numerus="yes">
<location line="+57"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+3"/>
<source>Open until %1</source>
<translation>Avoinna %1 asti</translation>
</message>
<message>
<location line="+3"/>
<source>Offline (%1 confirmations)</source>
<translation>Ei yhteyttä verkkoon (%1 vahvistusta)</translation>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation>Vahvistamatta (%1/%2 vahvistusta)</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Vahvistettu (%1 vahvistusta)</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>Louhittu saldo on käytettävissä kun se kypsyy %n lohkon päästä</numerusform><numerusform>Louhittu saldo on käytettävissä kun se kypsyy %n lohkon päästä</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>Tätä lohkoa ei vastaanotettu mistään muusta solmusta ja sitä ei mahdollisesti hyväksytä!</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>Generoitu mutta ei hyväksytty</translation>
</message>
<message>
<location line="+43"/>
<source>Received with</source>
<translation>Vastaanotettu osoitteella</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>Vastaanotettu</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>Saaja</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>Maksu itsellesi</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>Louhittu</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>(ei saatavilla)</translation>
</message>
<message>
<location line="+199"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Rahansiirron tila. Siirrä osoitin kentän päälle nähdäksesi vahvistusten lukumäärä.</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>Rahansiirron vastaanottamisen päivämäärä ja aika.</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>Rahansiirron laatu.</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>Rahansiirron kohteen Galleon-osoite</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>Saldoon lisätty tai siitä vähennetty määrä.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+52"/>
<location line="+16"/>
<source>All</source>
<translation>Kaikki</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>Tänään</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>Tällä viikolla</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>Tässä kuussa</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>Viime kuussa</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>Tänä vuonna</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>Alue...</translation>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation>Vastaanotettu osoitteella</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>Saaja</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>Itsellesi</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>Louhittu</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>Muu</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>Anna etsittävä osoite tai tunniste</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>Minimimäärä</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>Kopioi osoite</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Kopioi nimi</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Kopioi määrä</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>Muokkaa nimeä</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation>Näytä rahansiirron yksityiskohdat</translation>
</message>
<message>
<location line="+139"/>
<source>Export Transaction Data</source>
<translation>Vie rahansiirron tiedot</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Comma separated file (*.csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>Vahvistettu</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>Aika</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>Laatu</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>Nimi</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Osoite</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>Määrä</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>Virhe tietojen viennissä</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Ei voida kirjoittaa tiedostoon %1.</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>Alue:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>kenelle</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+193"/>
<source>Send Coins</source>
<translation>Lähetä Bitcoineja</translation>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<location filename="../walletview.cpp" line="+42"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Export the data in the current tab to a file</source>
<translation>Vie auki olevan välilehden tiedot tiedostoon</translation>
</message>
<message>
<location line="+193"/>
<source>Backup Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Backup Successful</source>
<translation>Varmuuskopio Onnistui</translation>
</message>
<message>
<location line="+0"/>
<source>The wallet data was successfully saved to the new location.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+94"/>
<source>Galleon version</source>
<translation>Bitcoinin versio</translation>
</message>
<message>
<location line="+102"/>
<source>Usage:</source>
<translation>Käyttö:</translation>
</message>
<message>
<location line="-29"/>
<source>Send command to -server or bitcoind</source>
<translation>Lähetä käsky palvelimelle tai bitcoind:lle</translation>
</message>
<message>
<location line="-23"/>
<source>List commands</source>
<translation>Lista komennoista</translation>
</message>
<message>
<location line="-12"/>
<source>Get help for a command</source>
<translation>Hanki apua käskyyn</translation>
</message>
<message>
<location line="+24"/>
<source>Options:</source>
<translation>Asetukset:</translation>
</message>
<message>
<location line="+24"/>
<source>Specify configuration file (default: bitcoin.conf)</source>
<translation>Määritä asetustiedosto (oletus: bitcoin.conf)</translation>
</message>
<message>
<location line="+3"/>
<source>Specify pid file (default: bitcoind.pid)</source>
<translation>Määritä pid-tiedosto (oletus: bitcoin.pid)</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>Määritä data-hakemisto</translation>
</message>
<message>
<location line="-9"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>Aseta tietokannan välimuistin koko megatavuina (oletus: 25)</translation>
</message>
<message>
<location line="-28"/>
<source>Listen for connections on <port> (default: 8669 or testnet: 18669)</source>
<translation>Kuuntele yhteyksiä portista <port> (oletus: 8669 tai testnet: 18669)</translation>
</message>
<message>
<location line="+5"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Pidä enintään <n> yhteyttä verkkoihin (oletus: 125)</translation>
</message>
<message>
<location line="-48"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation>Yhdistä noodiin hakeaksesi naapurien osoitteet ja katkaise yhteys</translation>
</message>
<message>
<location line="+82"/>
<source>Specify your own public address</source>
<translation>Määritä julkinen osoitteesi</translation>
</message>
<message>
<location line="+3"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>Kynnysarvo aikakatkaisulle heikosti toimiville verkoille (oletus: 100)</translation>
</message>
<message>
<location line="-134"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>Sekuntien määrä, kuinka kauan uudelleenkytkeydytään verkkoihin (oletus: 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>Virhe valmisteltaessa RPC-portin %u avaamista kuunneltavaksi: %s</translation>
</message>
<message>
<location line="+27"/>
<source>Listen for JSON-RPC connections on <port> (default: 8669 or testnet: 18669)</source>
<translation>Kuuntele JSON-RPC -yhteyksiä portista <port> (oletus: 8669 or testnet: 18669)</translation>
</message>
<message>
<location line="+37"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Hyväksy merkkipohjaiset- ja JSON-RPC-käskyt</translation>
</message>
<message>
<location line="+76"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Aja taustalla daemonina ja hyväksy komennot</translation>
</message>
<message>
<location line="+37"/>
<source>Use the test network</source>
<translation>Käytä test -verkkoa</translation>
</message>
<message>
<location line="-112"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation>Hyväksy yhteyksiä ulkopuolelta (vakioasetus: 1 jos -proxy tai -connect ei määritelty)</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=bitcoinrpc
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 "Galleon Alert" [email protected]
</source>
<translation type="unfinished"/>
</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>Virhe ilmennyt asetettaessa RPC-porttia %u IPv6:n kuuntelemiseksi, palataan takaisin IPv4:ään %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 type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. Galleon is probably already running.</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation>Aseta suurin korkean prioriteetin / matalan palkkion siirron koko tavuissa (vakioasetus: 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 type="unfinished"/>
</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>Varoitus: -paytxfee on asetettu erittäin korkeaksi! Tämä on maksukulu jonka tulet maksamaan kun lähetät siirron.</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>Varoitus: Näytetyt siirrot eivät välttämättä pidä paikkaansa! Sinun tai toisten noodien voi olla tarpeen asentaa päivitys.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong Galleon will not work properly.</source>
<translation>Varoitus: Tarkista että tietokoneesi kellonaika ja päivämäärä ovat paikkansapitäviä! Galleon ei toimi oikein väärällä päivämäärällä ja/tai kellonajalla.</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 type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Block creation options:</source>
<translation>Lohkon luonnin asetukset:</translation>
</message>
<message>
<location line="+5"/>
<source>Connect only to the specified node(s)</source>
<translation>Yhidstä ainoastaan määrättyihin noodeihin</translation>
</message>
<message>
<location line="+3"/>
<source>Corrupted block database detected</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation>Hae oma IP osoite (vakioasetus: 1 kun kuuntelemassa ja ei -externalip)</translation>
</message>
<message>
<location line="+1"/>
<source>Do you want to rebuild the block database now?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error initializing block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error initializing wallet database environment %s!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error loading block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error opening block database</source>
<translation>Virhe avattaessa lohkoindeksiä</translation>
</message>
<message>
<location line="+2"/>
<source>Error: Disk space is low!</source>
<translation>Varoitus: Levytila on vähissä!</translation>
</message>
<message>
<location line="+1"/>
<source>Error: Wallet locked, unable to create transaction!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: system error: </source>
<translation>Virhe: Järjestelmävirhe</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation>Ei onnistuttu kuuntelemaan missään portissa. Käytä -listen=0 jos haluat tätä.</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to read block info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to read block</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to sync block index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block</source>
<translation>Lohkon kirjoitus epäonnistui</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write file info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write to coin database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write transaction index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write undo data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Find peers using DNS lookup (default: 1 unless -connect)</source>
<translation>Hae naapureita DNS hauilla (vakioasetus: 1 paitsi jos -connect)</translation>
</message>
<message>
<location line="+1"/>
<source>Generate coins (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 288, 0 = all)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-4, default: 3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Not enough file descriptors available.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Rebuild block chain index from current blk000??.dat files</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+26"/>
<source>Verifying blocks...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Verifying wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-69"/>
<source>Imports blocks from external blk000??.dat file</source>
<translation>Tuodaan lohkoja ulkoisesta blk000??.dat tiedostosta</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 type="unfinished"/>
</message>
<message>
<location line="+77"/>
<source>Information</source>
<translation>Tietoa</translation>
</message>
<message>
<location line="+3"/>
<source>Invalid -tor address: '%s'</source>
<translation>Virheellinen -tor osoite '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -minrelaytxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -mintxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Maintain a full transaction index (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation>Suurin vastaanottopuskuri yksittäiselle yhteydelle, <n>*1000 tavua (vakioasetus: 5000)</translation>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation>Suurin lähetyspuskuri yksittäiselle yhteydelle, <n>*1000 tavua (vakioasetus: 1000)</translation>
</message>
<message>
<location line="+2"/>
<source>Only accept block chain matching built-in checkpoints (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation>Yhdistä vain noodeihin verkossa <net> (IPv4, IPv6 tai Tor)</translation>
</message>
<message>
<location line="+2"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation>Tulosta enemmän debug tietoa. Aktivoi kaikki -debug* asetukset</translation>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation>Tulosta lisää verkkoyhteys debug tietoa</translation>
</message>
<message>
<location line="+2"/>
<source>Prepend debug output with timestamp</source>
<translation>Lisää debuggaustiedon tulostukseen aikaleima</translation>
</message>
<message>
<location line="+5"/>
<source>SSL options: (see the Galleon Wiki for SSL setup instructions)</source>
<translation>SSL asetukset (katso Galleon Wikistä tarkemmat SSL ohjeet)</translation>
</message>
<message>
<location line="+1"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation>Valitse käytettävän SOCKS-proxyn versio (4-5, vakioasetus: 5)</translation>
</message>
<message>
<location line="+3"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Lähetä jäljitys/debug-tieto konsoliin, debug.log-tiedoston sijaan</translation>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation>Lähetä jäljitys/debug-tieto debuggeriin</translation>
</message>
<message>
<location line="+5"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation>Aseta suurin lohkon koko tavuissa (vakioasetus: 250000)</translation>
</message>
<message>
<location line="+1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation>Asetan pienin lohkon koko tavuissa (vakioasetus: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation>Pienennä debug.log tiedosto käynnistyksen yhteydessä (vakioasetus: 1 kun ei -debug)</translation>
</message>
<message>
<location line="+1"/>
<source>Signing transaction failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation>Määritä yhteyden aikakataisu millisekunneissa (vakioasetus: 5000)</translation>
</message>
<message>
<location line="+4"/>
<source>System error: </source>
<translation>Järjestelmävirhe:</translation>
</message>
<message>
<location line="+4"/>
<source>Transaction amount too small</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction amounts must be positive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction too large</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation>Käytä UPnP:tä kuunneltavan portin avaamiseen (vakioasetus: 0)</translation>
</message>
<message>
<location line="+1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation>Käytä UPnP:tä kuunneltavan portin avaamiseen (vakioasetus: 1 kun kuuntelemassa)</translation>
</message>
<message>
<location line="+1"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation>Käytä proxyä tor yhteyksien avaamiseen (vakioasetus: sama kuin -proxy)</translation>
</message>
<message>
<location line="+2"/>
<source>Username for JSON-RPC connections</source>
<translation>Käyttäjätunnus JSON-RPC-yhteyksille</translation>
</message>
<message>
<location line="+4"/>
<source>Warning</source>
<translation>Varoitus</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation>Varoitus: Tämä versio on vanhentunut, päivitys tarpeen!</translation>
</message>
<message>
<location line="+1"/>
<source>You need to rebuild the databases using -reindex to change -txindex</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-50"/>
<source>Password for JSON-RPC connections</source>
<translation>Salasana JSON-RPC-yhteyksille</translation>
</message>
<message>
<location line="-67"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Salli JSON-RPC yhteydet tietystä ip-osoitteesta</translation>
</message>
<message>
<location line="+76"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Lähetä käskyjä solmuun osoitteessa <ip> (oletus: 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>Suorita käsky kun paras lohko muuttuu (%s cmd on vaihdettu block hashin kanssa)</translation>
</message>
<message>
<location line="+147"/>
<source>Upgrade wallet to latest format</source>
<translation>Päivitä lompakko uusimpaan formaattiin</translation>
</message>
<message>
<location line="-21"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Aseta avainpoolin koko arvoon <n> (oletus: 100)</translation>
</message>
<message>
<location line="-12"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Skannaa uudelleen lohkoketju lompakon puuttuvien rahasiirtojen vuoksi</translation>
</message>
<message>
<location line="+35"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>Käytä OpenSSL:ää (https) JSON-RPC-yhteyksille</translation>
</message>
<message>
<location line="-26"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Palvelimen sertifikaatti-tiedosto (oletus: server.cert)</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>Palvelimen yksityisavain (oletus: server.pem)</translation>
</message>
<message>
<location line="-151"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation>Hyväksyttävä salaus (oletus:
TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation>
</message>
<message>
<location line="+165"/>
<source>This help message</source>
<translation>Tämä ohjeviesti</translation>
</message>
<message>
<location line="+6"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>Kytkeytyminen %s tällä tietokonella ei onnistu (kytkeytyminen palautti virheen %d, %s)</translation>
</message>
<message>
<location line="-91"/>
<source>Connect through socks proxy</source>
<translation>Yhdistä socks proxyn läpi</translation>
</message>
<message>
<location line="-10"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>Salli DNS kyselyt -addnode, -seednode ja -connect yhteydessä</translation>
</message>
<message>
<location line="+55"/>
<source>Loading addresses...</source>
<translation>Ladataan osoitteita...</translation>
</message>
<message>
<location line="-35"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>Virhe ladattaessa wallet.dat-tiedostoa: Lompakko vioittunut</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat: Wallet requires newer version of Galleon</source>
<translation>Virhe ladattaessa wallet.dat-tiedostoa: Tarvitset uudemman version Bitcoinista</translation>
</message>
<message>
<location line="+93"/>
<source>Wallet needed to be rewritten: restart Galleon to complete</source>
<translation>Lompakko tarvitsee uudelleenkirjoittaa: käynnistä Galleon uudelleen</translation>
</message>
<message>
<location line="-95"/>
<source>Error loading wallet.dat</source>
<translation>Virhe ladattaessa wallet.dat-tiedostoa</translation>
</message>
<message>
<location line="+28"/>
<source>Invalid -proxy address: '%s'</source>
<translation>Virheellinen proxy-osoite '%s'</translation>
</message>
<message>
<location line="+56"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>Tuntematon verkko -onlynet parametrina: '%s'</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation>Tuntematon -socks proxy versio pyydetty: %i</translation>
</message>
<message>
<location line="-96"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation>-bind osoitteen '%s' selvittäminen epäonnistui</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation>-externalip osoitteen '%s' selvittäminen epäonnistui</translation>
</message>
<message>
<location line="+44"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>-paytxfee=<amount>: '%s' on virheellinen</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount</source>
<translation>Virheellinen määrä</translation>
</message>
<message>
<location line="-6"/>
<source>Insufficient funds</source>
<translation>Lompakon saldo ei riitä</translation>
</message>
<message>
<location line="+10"/>
<source>Loading block index...</source>
<translation>Ladataan lohkoindeksiä...</translation>
</message>
<message>
<location line="-57"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Linää solmu mihin liittyä pitääksesi yhteyden auki</translation>
</message>
<message>
<location line="-25"/>
<source>Unable to bind to %s on this computer. Galleon is probably already running.</source>
<translation>Kytkeytyminen %s ei onnistu tällä tietokoneella. Galleon on todennäköisesti jo ajamassa.</translation>
</message>
<message>
<location line="+64"/>
<source>Fee per KB to add to transactions you send</source>
<translation>Rahansiirtopalkkio per KB lisätään lähettämääsi rahansiirtoon</translation>
</message>
<message>
<location line="+19"/>
<source>Loading wallet...</source>
<translation>Ladataan lompakkoa...</translation>
</message>
<message>
<location line="-52"/>
<source>Cannot downgrade wallet</source>
<translation>Et voi päivittää lompakkoasi vanhempaan versioon</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot write default address</source>
<translation>Oletusosoitetta ei voi kirjoittaa</translation>
</message>
<message>
<location line="+64"/>
<source>Rescanning...</source>
<translation>Skannataan uudelleen...</translation>
</message>
<message>
<location line="-57"/>
<source>Done loading</source>
<translation>Lataus on valmis</translation>
</message>
<message>
<location line="+82"/>
<source>To use the %s option</source>
<translation>Käytä %s optiota</translation>
</message>
<message>
<location line="-74"/>
<source>Error</source>
<translation>Virhe</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>Sinun täytyy asettaa rpcpassword=<password> asetustiedostoon:
%s
Jos tiedostoa ei ole, niin luo se ainoastaan omistajan kirjoitusoikeuksin.</translation>
</message>
</context>
</TS> | mit |
gabriprat/hoshinplan | app/models/clockwork_event.rb | 994 | class ClockworkEvent < ApplicationRecord
hobo_model # Don't put anything above this
fields do
name :string
job :string
frequency_quantity :integer
frequency_period HoboFields::Types::EnumString.for(:second, :minute, :hour, :day, :week, :month)
at :string
options :string
timestamps
end
attr_accessible :name, :job, :frequency_quantity, :frequency_period, :at, :options
# Used by clockwork to schedule how frequently this event should be run
# Should be the intended number of seconds between executions
def frequency
frequency_quantity.send(frequency_period.to_s)
end
def jobClass
::Jobs.const_get(job)
end
# --- Permissions --- #
def create_permitted?
acting_user.administrator?
end
def update_permitted?
acting_user.administrator?
end
def destroy_permitted?
acting_user.administrator?
end
def view_permitted?(field)
true
end
end
| mit |
kfields/decision-tree-workshop | DecisionTreeWorkshop/obj/Debug/Gui/DtWpfGraphPanel.g.i.cs | 4653 | #pragma checksum "..\..\..\Gui\DtWpfGraphPanel.xaml" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "CA3DCF7411DE522523A6B5D32FAD257A"
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.225
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using DtWorkshop;
using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms.Integration;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Effects;
using System.Windows.Media.Imaging;
using System.Windows.Media.Media3D;
using System.Windows.Media.TextFormatting;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Shell;
namespace DtWorkshop {
/// <summary>
/// DtWpfGraphPanel
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
public partial class DtWpfGraphPanel : System.Windows.Controls.UserControl, System.Windows.Markup.IComponentConnector {
#line 8 "..\..\..\Gui\DtWpfGraphPanel.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Slider zoomSlider;
#line default
#line hidden
#line 9 "..\..\..\Gui\DtWpfGraphPanel.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.ScrollViewer scrollViewer1;
#line default
#line hidden
#line 10 "..\..\..\Gui\DtWpfGraphPanel.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal DtWorkshop.DtTreeCanvas treeCanvas;
#line default
#line hidden
private bool _contentLoaded;
/// <summary>
/// InitializeComponent
/// </summary>
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
public void InitializeComponent() {
if (_contentLoaded) {
return;
}
_contentLoaded = true;
System.Uri resourceLocater = new System.Uri("/DtWorkshop;component/gui/dtwpfgraphpanel.xaml", System.UriKind.Relative);
#line 1 "..\..\..\Gui\DtWpfGraphPanel.xaml"
System.Windows.Application.LoadComponent(this, resourceLocater);
#line default
#line hidden
}
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal System.Delegate _CreateDelegate(System.Type delegateType, string handler) {
return System.Delegate.CreateDelegate(delegateType, this, handler);
}
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) {
switch (connectionId)
{
case 1:
this.zoomSlider = ((System.Windows.Controls.Slider)(target));
return;
case 2:
this.scrollViewer1 = ((System.Windows.Controls.ScrollViewer)(target));
return;
case 3:
this.treeCanvas = ((DtWorkshop.DtTreeCanvas)(target));
return;
}
this._contentLoaded = true;
}
}
}
| mit |
LagoLunatic/DSVEdit | dsvlib.rb | 1610 |
require_relative 'dsvlib/crc16'
require_relative 'dsvlib/free_space_manager'
require_relative 'dsvlib/nds_file_system'
require_relative 'dsvlib/gba_dummy_filesystem'
require_relative 'dsvlib/gba_lz77'
require_relative 'dsvlib/bitfield'
require_relative 'dsvlib/game'
require_relative 'dsvlib/area'
require_relative 'dsvlib/sector'
require_relative 'dsvlib/room'
require_relative 'dsvlib/layer'
require_relative 'dsvlib/tileset'
require_relative 'dsvlib/entity'
require_relative 'dsvlib/door'
require_relative 'dsvlib/map'
require_relative 'dsvlib/generic_editable'
require_relative 'dsvlib/enemy_dna'
require_relative 'dsvlib/text'
require_relative 'dsvlib/text_database'
require_relative 'dsvlib/sprite'
require_relative 'dsvlib/special_object_type'
require_relative 'dsvlib/sprite_info'
require_relative 'dsvlib/sprite_skeleton'
require_relative 'dsvlib/weapon_gfx'
require_relative 'dsvlib/skill_gfx'
require_relative 'dsvlib/item_pool'
require_relative 'dsvlib/gfx_wrapper'
require_relative 'dsvlib/palette_wrapper'
require_relative 'dsvlib/player'
require_relative 'dsvlib/weapon_synth'
require_relative 'dsvlib/shop_item_pool'
require_relative 'dsvlib/magic_seal'
require_relative 'dsvlib/quest'
require_relative 'dsvlib/renderer'
require_relative 'dsvlib/tmx_interface'
require_relative 'dsvlib/darkfunction_interface.rb'
require_relative 'dsvlib/spriter_interface.rb'
if defined?(Ocra)
orig_verbosity = $VERBOSE
$VERBOSE = nil
require_relative 'constants/dos_constants'
require_relative 'constants/por_constants'
require_relative 'constants/ooe_constants'
$VERBOSE = orig_verbosity
end
| mit |
spajus/tank_island | lib/entities/hud.rb | 1825 | class HUD
attr_accessor :active
def initialize(object_pool, tank)
@object_pool = object_pool
@tank = tank
@radar = Radar.new(@object_pool, tank)
end
def player=(tank)
@tank = tank
@radar.target = tank
end
def update
@radar.update
end
def health_image
if @health.nil? || @tank.health.health != @health
@health = @tank.health.health
@health_image = Gosu::Image.from_text(
"Health: #{@health}", 20, font: Utils.main_font)
end
@health_image
end
def stats_image
stats = @tank.input.stats
if @stats_image.nil? || stats.changed_at <= Gosu.milliseconds
@stats_image = Gosu::Image.from_text(
"Kills: #{stats.kills}", 20, font: Utils.main_font)
end
@stats_image
end
def fire_rate_image
if @tank.fire_rate_modifier > 1
if @fire_rate != @tank.fire_rate_modifier
@fire_rate = @tank.fire_rate_modifier
@fire_rate_image = Gosu::Image.from_text(
"Fire rate: #{@fire_rate.round(2)}X",
20, font: Utils.main_font)
end
else
@fire_rate_image = nil
end
@fire_rate_image
end
def speed_image
if @tank.speed_modifier > 1
if @speed != @tank.speed_modifier
@speed = @tank.speed_modifier
@speed_image = Gosu::Image.from_text(
"Speed: #{@speed.round(2)}X",
20, font: Utils.main_font)
end
else
@speed_image = nil
end
@speed_image
end
def draw
if @active
@object_pool.camera.draw_crosshair
end
@radar.draw
offset = 20
health_image.draw(20, offset, 1000)
stats_image.draw(20, offset += 30, 1000)
if fire_rate_image
fire_rate_image.draw(20, offset += 30, 1000)
end
if speed_image
speed_image.draw(20, offset += 30, 1000)
end
end
end
| mit |
jimkyndemeyer/js-graphql-intellij-plugin | src/main/com/intellij/lang/jsgraphql/types/execution/instrumentation/parameters/InstrumentationCreateStateParameters.java | 2019 | /*
The MIT License (MIT)
Copyright (c) 2015 Andreas Marek and Contributors
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files
(the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.intellij.lang.jsgraphql.types.execution.instrumentation.parameters;
import com.intellij.lang.jsgraphql.types.ExecutionInput;
import com.intellij.lang.jsgraphql.types.PublicApi;
import com.intellij.lang.jsgraphql.types.schema.GraphQLSchema;
/**
* Parameters sent to {@link com.intellij.lang.jsgraphql.types.execution.instrumentation.Instrumentation} methods
*/
@PublicApi
public class InstrumentationCreateStateParameters {
private final GraphQLSchema schema;
private final ExecutionInput executionInput;
public InstrumentationCreateStateParameters(GraphQLSchema schema, ExecutionInput executionInput) {
this.schema = schema;
this.executionInput = executionInput;
}
public GraphQLSchema getSchema() {
return schema;
}
public ExecutionInput getExecutionInput() {
return executionInput;
}
}
| mit |
moszinet/BKKCrypt | Rust/src/bin.rs | 406 | use std::env;
use std::process;
extern crate bkkcrypt_lib;
fn main() {
let args: Vec<_> = env::args().collect();
if args.len() != 2 {
println!(
"Please provide a single parameter to encrypt with the famous BKKCrypt algorithm."
);
process::exit(1);
}
let ref item = &args[1];
let result = bkkcrypt_lib::encrypt(item);
println!("{}", result);
} | mit |
InnovateUKGitHub/innovation-funding-service | ifs-data-layer/ifs-data-service/src/main/java/org/innovateuk/ifs/organisation/repository/SimpleOrganisationRepository.java | 451 | package org.innovateuk.ifs.organisation.repository;
import org.innovateuk.ifs.organisation.domain.SimpleOrganisation;
import org.springframework.data.repository.CrudRepository;
/**
* This interface is used to generate Spring Data Repositories.
* For more info:
* http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories
*/
public interface SimpleOrganisationRepository extends CrudRepository<SimpleOrganisation, Long> {
}
| mit |
Petr-Economissa/gvidon | src/test/compress_tests.cpp | 1936 | // Copyright (c) 2012-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "compressor.h"
#include "util.h"
#include "test/test_gvidon.h"
#include <stdint.h>
#include <boost/test/unit_test.hpp>
// amounts 0.00000001 .. 0.00100000
#define NUM_MULTIPLES_UNIT 100000
// amounts 0.01 .. 100.00
#define NUM_MULTIPLES_CENT 10000
// amounts 1 .. 10000
#define NUM_MULTIPLES_1BTC 10000
// amounts 50 .. 21000000
#define NUM_MULTIPLES_50BTC 420000
BOOST_FIXTURE_TEST_SUITE(compress_tests, BasicTestingSetup)
bool static TestEncode(uint64_t in) {
return in == CTxOutCompressor::DecompressAmount(CTxOutCompressor::CompressAmount(in));
}
bool static TestDecode(uint64_t in) {
return in == CTxOutCompressor::CompressAmount(CTxOutCompressor::DecompressAmount(in));
}
bool static TestPair(uint64_t dec, uint64_t enc) {
return CTxOutCompressor::CompressAmount(dec) == enc &&
CTxOutCompressor::DecompressAmount(enc) == dec;
}
BOOST_AUTO_TEST_CASE(compress_amounts)
{
BOOST_CHECK(TestPair( 0, 0x0));
BOOST_CHECK(TestPair( 1, 0x1));
BOOST_CHECK(TestPair( CENT, 0x7));
BOOST_CHECK(TestPair( COIN, 0x9));
BOOST_CHECK(TestPair( 50*COIN, 0x32));
BOOST_CHECK(TestPair(21000000*COIN, 0x1406f40));
for (uint64_t i = 1; i <= NUM_MULTIPLES_UNIT; i++)
BOOST_CHECK(TestEncode(i));
for (uint64_t i = 1; i <= NUM_MULTIPLES_CENT; i++)
BOOST_CHECK(TestEncode(i * CENT));
for (uint64_t i = 1; i <= NUM_MULTIPLES_1BTC; i++)
BOOST_CHECK(TestEncode(i * COIN));
for (uint64_t i = 1; i <= NUM_MULTIPLES_50BTC; i++)
BOOST_CHECK(TestEncode(i * 50 * COIN));
for (uint64_t i = 0; i < 100000; i++)
BOOST_CHECK(TestDecode(i));
}
BOOST_AUTO_TEST_SUITE_END()
| mit |
MortenChristiansen/DDDTools.SpecGen | DDDTools.SpecGen/Spec/Feature.cs | 384 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DDDTools.SpecGen.Spec
{
class Feature : SpecificationItem
{
public List<RequirementGroup> RequirementGroups { get; set; }
public Feature()
{
RequirementGroups = new List<RequirementGroup>();
}
}
}
| mit |
1dv024/exercise-solution-proposals | exercise-static-adding/StaticAdding/Program.cs | 774 | using System;
namespace StaticAdding
{
/// <summary>
/// Represents the main place where the program starts the execution.
/// </summary>
class Program
{
/// <summary>
/// The starting point of the application.
/// </summary>
static void Main(string[] args)
{
// Which static method is called?
int sum = MyMath.Add(123, 456);
Console.WriteLine($"Summan är: {sum}\n");
// Which static method is called?
double anotherSum = MyMath.Add(9.87, 6.54);
Console.WriteLine($"Summan är: {anotherSum}\n");
// Which static method is called?
Console.WriteLine("Summan är: {0}\n", MyMath.Add(123, 6.54));
}
}
}
| mit |
MihaZelnik/Django-Unchained | setup.py | 599 | # -*- coding: utf-8 -*-
"""
setup
"""
from setuptools import find_packages, setup
setup(
name="Django Unchained",
version="0.0.1",
description="Django skeleton",
url="https://github.com/MihaZelnik/Django-Unchained",
license="MIT",
author="Miha Zelnik",
author_email="[email protected]",
# packaging
packages=find_packages("src"),
package_dir={
"": "src"
},
include_package_data=True,
zip_safe=True,
# scripts
entry_points={
"console_scripts": [
"django = project.manage:run",
],
},
)
| mit |
botorabi/Meet4Eat | src/main/java/net/m4e/system/deployment/UpdateInit.java | 6217 | /*
* Copyright (c) 2017-2019 by Botorabi. All rights reserved.
* https://github.com/botorabi/Meet4Eat
*
* License: MIT License (MIT), read the LICENSE text in
* main directory for more details.
*/
package net.m4e.system.deployment;
import net.m4e.app.auth.AuthRole;
import net.m4e.app.auth.AuthorityConfig;
import net.m4e.app.auth.PermissionEntity;
import net.m4e.app.auth.RoleEntity;
import net.m4e.app.resources.StatusEntity;
import net.m4e.app.user.business.UserEntity;
import net.m4e.common.Entities;
import net.m4e.system.core.AppUpdateBaseHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.persistence.EntityManager;
import java.lang.invoke.MethodHandles;
import java.util.*;
/**
* Deployment updater for initial version of app installation.
* This is meant to be used for the very first app start. It is a good place
* to setup initial database structures, etc.
*
* @author boto
* Date of creation Aug 22, 2017
*/
public class UpdateInit extends AppUpdateBaseHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
/**
* Make sure to increment this number for every new update class.
*/
private static final int INC_NUMBER = 0;
/**
* Application version this update belongs to
*/
private static final String APP_VERSION = "0.0.0";
public UpdateInit() {
incUpdateNumber = INC_NUMBER;
appVersion = APP_VERSION;
}
/**
* Perform the update.
*
* @param entityManager For the case that any entity structure manipulation is needed
* @param entities Entities instance used for common entity operations
*/
@Override
public void performUpdate(EntityManager entityManager, Entities entities) {
LOGGER.debug("Initial deployment setup, version: " + appVersion + " (" + incUpdateNumber + ")");
setupPermissions(entities);
setupRoles(entities);
setupAdminUser(entities);
}
/**
* Setup all permissions.
*
* @param entities The Entities instance
*/
private void setupPermissions(Entities entities) {
LOGGER.debug(" Setup permissions in database");
for (String permname: AuthorityConfig.getInstance().getApplicationPermissions()) {
// check if the permission already exists in database (should actually not happen)
if (entities.findByField(PermissionEntity.class, "name", permname).size() > 0) {
LOGGER.debug(" Permission " + permname + " already exists, skip its creation");
continue;
}
LOGGER.debug(" Create permission: " + permname);
PermissionEntity pe = new PermissionEntity();
pe.setName(permname);
entities.create(pe);
}
}
/**
* Setup all roles.
*
* @param entities The Entities instance
*/
private void setupRoles(Entities entities) {
LOGGER.debug(" Setup roles in database");
for (Map.Entry<String, List<String>> role: AuthorityConfig.getInstance().getApplicationRoles().entrySet()) {
String rolename = role.getKey();
List<String> perms = role.getValue();
// check if the role already exists in database (should actually not happen)
if (entities.findByField(RoleEntity.class, "name", rolename).size() > 0) {
LOGGER.debug(" Role " + rolename + " already exists, skip its creation");
continue;
}
LOGGER.debug(" Create role: " + rolename);
RoleEntity roleentity = new RoleEntity();
roleentity.setName(rolename);
entities.create(roleentity);
// set all associated permissions
List<PermissionEntity> permentities = new ArrayList<>();
for (String perm: perms) {
// find the permission by its name
List<PermissionEntity> pe = entities.findByField(PermissionEntity.class, "name", perm);
if (pe.size() > 1) {
LOGGER.warn("*** More than one permisson entry found '" + perm + "' for role '" + rolename + "', taking the first one");
}
else if (pe.size() < 1) {
LOGGER.error("*** Could not find permission '" + perm + "' for role '" + rolename + "'");
continue;
}
permentities.addAll(pe);
}
String text = "";
for (PermissionEntity ent: permentities) {
text += " | " + ent.getName();
}
LOGGER.debug(" Setting role permissions: " + text);
// update the role entity with assigned permissions
roleentity.setPermissions(permentities);
entities.update(roleentity);
}
}
/**
* Setup a user with administrator rights.
*
* @param entities The Entities instance
*/
private void setupAdminUser(Entities entities) {
LOGGER.debug(" Create user: admin");
UserEntity user = new UserEntity();
user.setName("Administrator");
user.setLogin("admin");
user.setEmail("dummy AT mail.com");
user.setPassword(AuthorityConfig.getInstance().createPassword("admin"));
entities.create(user);
// setup the entity status
StatusEntity status = new StatusEntity();
status.setIdCreator(user.getId());
status.setIdOwner(user.getId());
Date now = new Date();
status.setDateCreation(now.getTime());
status.setDateLastUpdate(now.getTime());
user.setStatus(status);
// setup the roles
List<RoleEntity> roles = entities.findByField(RoleEntity.class, "name", AuthRole.USER_ROLE_ADMIN);
if (roles.size() < 1) {
LOGGER.error("*** Counld not find role '" + AuthRole.USER_ROLE_ADMIN + "' for admin user");
return;
}
user.setRoles(Arrays.asList(roles.get(0)));
entities.update(user);
LOGGER.debug(" User 'admin' was successfully created.");
}
}
| mit |
wialon/wialon-app-drivinglogbook | lang/da.js | 3318 | TRANSLATIONS = {
"Driving Logbook": "Kørebog",
"Logbook": "Logbog",
"Unit": "Enhed",
"From": "Fra",
"To": "Til",
"OK": "Ok",
"Beginning": "Start",
"End": "Slut",
"Duration": "Varighed",
"Initial location": "Start adresse",
"Final location": "Slut adresse",
"Initial mileage": "Start kilometer",
"Final mileage": "Slut kilometer",
"Mileage": "kilometertal",
"Driver": "Chauffør",
"User": "Bruger",
"Last changes": "Seneste ændringer",
"Trip status": "Tur status",
"Business": "Erhver",
"Personal": "Privat",
"Notes": "Noter",
"Page ": "Side ",
" of ": " af ",
"Apply": "Anvend",
"Displaying %d to %d of %d items": "Viser %d til %d af %d elementer",
"List of units empty.": "Liste af fravalgte enheder.",
"Login error.": "Login fejl.",
"Please select unit.": "Vælg venligst enheden.",
"Please select time interval.": "Vælg venligst tidsperiode",
"No data for selected interval.": "Ingen data for valgte interval.",
"km": "km",
"mi": "mi",
"%d pages_1": "%d side",
"%d pages_2": "%d sider",
"%d pages_5": "%d sider",
"Start": "Start",
"Prev": "Forrige",
"Next": "Næste",
"Print": "Udskriv",
"Yesterday": "I går",
"Today": "I dag",
"Week": "Uge",
"Month": "Måned",
"Custom": "Brugerdefinerede",
"Home-Office-Home": "Hjem-Kontor-Hjem",
"Drive home-office": "Kør hjem-kontor",
"Drive office-home": "Kør kontor-hjem",
"You have unsaved changes. Are you sure you want to leave?": "Du har ikke-gemte ændringer. Er du sikker",
"You have unsaved changes. Do you want to discard these changes?": "Du har ikke-gemte ændringer. ",
"Choose geofences": "Vælg geografiske områder",
"Home": "Hjem",
"Office": "Kontor",
"Cancel": "Anullere",
"Save": "Gem",
"Settings": "Indstillinger",
"Social Security no.": "CPR-nummer",
"Name": "Navn",
"Address": "Adresse",
"ZIP code": "Post nr.",
"City": "By",
"Declaration holder": "Erklæring ",
"Vehicle": "Køretøj",
"Available from": "Tilgængelig fra",
"Available to": "Tilgængelig til",
"Type": "Type",
"Brand": "Mærke",
"Employee": "Medarbejder",
"Correction": "Rettelse",
"Difference": "Forskel",
"Show": "vis",
"Header": "Sidehoved",
"Footer": "Sidefod",
"Taxable payment": "Kørselsgodtgørelse",
"Payment mileage": "SKAT km grænse",
"Total refund": "Samlet tilbagebetaling",
"Show payment": "Vis betaling",
"Date": "Dato",
"Signature": "Underskrift",
"Driver no.": "Chauffører nr.",
"License no.": "Nummerplade",
"IT service provider": "IT service udbyde",
"Company name": "Firmanavn",
"Company reg. no.": "CVR-nummer",
"RRS type and version no.": "RRS typen og version nr.",
"Template": "Skabelon",
"Error while export to xls": "Fejl ved eksport til excel",
"Interface": "Tabel",
"Group by day": "Gruppe efter dato",
"Show summary": "Vis resume",
"Mileage source": "Datakilde",
"Internal trips odometer": "Intern algoritme",
"Absolute mileage sensor": "kilometer sensor",
"Mileage counter": "kilometerstand",
"Initial and final mileage": "Beregnet Kilometer"
}; | mit |
Dasl0ki/secmjam | config/config.php | 355 | <?php
/**
* Created by PhpStorm.
* User: Loki
* Date: 13.10.2015
* Time: 08:53
*/
$config = parse_ini_file('../../mysqli_config.ini', TRUE);
$strQuery = "SET character_set_results = 'utf8',
character_set_client = 'utf8',
character_set_connection = 'utf8',
character_set_database = 'utf8',
character_set_server = 'utf8'";
| mit |
dragosbdi/bitcredit-2.0 | src/qt/rpcconsole.cpp | 33904 | // Copyright (c) 2011-2015 The Bitcredit Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include "config/bitcredit-config.h"
#endif
#include "rpcconsole.h"
#include "ui_debugwindow.h"
#include "bantablemodel.h"
#include "clientmodel.h"
#include "guiutil.h"
#include "platformstyle.h"
#include "bantablemodel.h"
#include "chainparams.h"
#include "rpc/server.h"
#include "rpc/client.h"
#include "util.h"
#include <openssl/crypto.h>
#include <univalue.h>
#ifdef ENABLE_WALLET
#include <db_cxx.h>
#endif
#include <QKeyEvent>
#include <QMenu>
#include <QScrollBar>
#include <QSettings>
#include <QSignalMapper>
#include <QThread>
#include <QTime>
#include <QTimer>
#include <QStringList>
#if QT_VERSION < 0x050000
#include <QUrl>
#endif
// TODO: add a scrollback limit, as there is currently none
// TODO: make it possible to filter out categories (esp debug messages when implemented)
// TODO: receive errors and debug messages through ClientModel
const int CONSOLE_HISTORY = 50;
const int INITIAL_TRAFFIC_GRAPH_MINS = 30;
const QSize FONT_RANGE(4, 40);
const char fontSizeSettingsKey[] = "consoleFontSize";
const struct {
const char *url;
const char *source;
} ICON_MAPPING[] = {
{"cmd-request", ":/icons/tx_input"},
{"cmd-reply", ":/icons/tx_output"},
{"cmd-error", ":/icons/tx_output"},
{"misc", ":/icons/tx_inout"},
{NULL, NULL}
};
/* Object for executing console RPC commands in a separate thread.
*/
class RPCExecutor : public QObject
{
Q_OBJECT
public Q_SLOTS:
void request(const QString &command);
Q_SIGNALS:
void reply(int category, const QString &command);
};
/** Class for handling RPC timers
* (used for e.g. re-locking the wallet after a timeout)
*/
class QtRPCTimerBase: public QObject, public RPCTimerBase
{
Q_OBJECT
public:
QtRPCTimerBase(boost::function<void(void)>& func, int64_t millis):
func(func)
{
timer.setSingleShot(true);
connect(&timer, SIGNAL(timeout()), this, SLOT(timeout()));
timer.start(millis);
}
~QtRPCTimerBase() {}
private Q_SLOTS:
void timeout() { func(); }
private:
QTimer timer;
boost::function<void(void)> func;
};
class QtRPCTimerInterface: public RPCTimerInterface
{
public:
~QtRPCTimerInterface() {}
const char *Name() { return "Qt"; }
RPCTimerBase* NewTimer(boost::function<void(void)>& func, int64_t millis)
{
return new QtRPCTimerBase(func, millis);
}
};
#include "rpcconsole.moc"
/**
* Split shell command line into a list of arguments. Aims to emulate \c bash and friends.
*
* - Arguments are delimited with whitespace
* - Extra whitespace at the beginning and end and between arguments will be ignored
* - Text can be "double" or 'single' quoted
* - The backslash \c \ is used as escape character
* - Outside quotes, any character can be escaped
* - Within double quotes, only escape \c " and backslashes before a \c " or another backslash
* - Within single quotes, no escaping is possible and no special interpretation takes place
*
* @param[out] args Parsed arguments will be appended to this list
* @param[in] strCommand Command line to split
*/
bool parseCommandLine(std::vector<std::string> &args, const std::string &strCommand)
{
enum CmdParseState
{
STATE_EATING_SPACES,
STATE_ARGUMENT,
STATE_SINGLEQUOTED,
STATE_DOUBLEQUOTED,
STATE_ESCAPE_OUTER,
STATE_ESCAPE_DOUBLEQUOTED
} state = STATE_EATING_SPACES;
std::string curarg;
Q_FOREACH(char ch, strCommand)
{
switch(state)
{
case STATE_ARGUMENT: // In or after argument
case STATE_EATING_SPACES: // Handle runs of whitespace
switch(ch)
{
case '"': state = STATE_DOUBLEQUOTED; break;
case '\'': state = STATE_SINGLEQUOTED; break;
case '\\': state = STATE_ESCAPE_OUTER; break;
case ' ': case '\n': case '\t':
if(state == STATE_ARGUMENT) // Space ends argument
{
args.push_back(curarg);
curarg.clear();
}
state = STATE_EATING_SPACES;
break;
default: curarg += ch; state = STATE_ARGUMENT;
}
break;
case STATE_SINGLEQUOTED: // Single-quoted string
switch(ch)
{
case '\'': state = STATE_ARGUMENT; break;
default: curarg += ch;
}
break;
case STATE_DOUBLEQUOTED: // Double-quoted string
switch(ch)
{
case '"': state = STATE_ARGUMENT; break;
case '\\': state = STATE_ESCAPE_DOUBLEQUOTED; break;
default: curarg += ch;
}
break;
case STATE_ESCAPE_OUTER: // '\' outside quotes
curarg += ch; state = STATE_ARGUMENT;
break;
case STATE_ESCAPE_DOUBLEQUOTED: // '\' in double-quoted text
if(ch != '"' && ch != '\\') curarg += '\\'; // keep '\' for everything but the quote and '\' itself
curarg += ch; state = STATE_DOUBLEQUOTED;
break;
}
}
switch(state) // final state
{
case STATE_EATING_SPACES:
return true;
case STATE_ARGUMENT:
args.push_back(curarg);
return true;
default: // ERROR to end in one of the other states
return false;
}
}
void RPCExecutor::request(const QString &command)
{
std::vector<std::string> args;
if(!parseCommandLine(args, command.toStdString()))
{
Q_EMIT reply(RPCConsole::CMD_ERROR, QString("Parse error: unbalanced ' or \""));
return;
}
if(args.empty())
return; // Nothing to do
try
{
std::string strPrint;
// Convert argument list to JSON objects in method-dependent way,
// and pass it along with the method name to the dispatcher.
UniValue result = tableRPC.execute(
args[0],
RPCConvertValues(args[0], std::vector<std::string>(args.begin() + 1, args.end())));
// Format result reply
if (result.isNull())
strPrint = "";
else if (result.isStr())
strPrint = result.get_str();
else
strPrint = result.write(2);
Q_EMIT reply(RPCConsole::CMD_REPLY, QString::fromStdString(strPrint));
}
catch (UniValue& objError)
{
try // Nice formatting for standard-format error
{
int code = find_value(objError, "code").get_int();
std::string message = find_value(objError, "message").get_str();
Q_EMIT reply(RPCConsole::CMD_ERROR, QString::fromStdString(message) + " (code " + QString::number(code) + ")");
}
catch (const std::runtime_error&) // raised when converting to invalid type, i.e. missing code or message
{ // Show raw JSON object
Q_EMIT reply(RPCConsole::CMD_ERROR, QString::fromStdString(objError.write()));
}
}
catch (const std::exception& e)
{
Q_EMIT reply(RPCConsole::CMD_ERROR, QString("Error: ") + QString::fromStdString(e.what()));
}
}
RPCConsole::RPCConsole(const PlatformStyle *platformStyle, QWidget *parent) :
QWidget(parent),
ui(new Ui::RPCConsole),
clientModel(0),
historyPtr(0),
cachedNodeid(-1),
platformStyle(platformStyle),
peersTableContextMenu(0),
banTableContextMenu(0),
consoleFontSize(0)
{
ui->setupUi(this);
GUIUtil::restoreWindowGeometry("nRPCConsoleWindow", this->size(), this);
ui->openDebugLogfileButton->setToolTip(ui->openDebugLogfileButton->toolTip().arg(tr(PACKAGE_NAME)));
if (platformStyle->getImagesOnButtons()) {
ui->openDebugLogfileButton->setIcon(platformStyle->SingleColorIcon(":/icons/export"));
}
ui->clearButton->setIcon(platformStyle->SingleColorIcon(":/icons/remove"));
ui->fontBiggerButton->setIcon(platformStyle->SingleColorIcon(":/icons/fontbigger"));
ui->fontSmallerButton->setIcon(platformStyle->SingleColorIcon(":/icons/fontsmaller"));
// Install event filter for up and down arrow
ui->lineEdit->installEventFilter(this);
ui->messagesWidget->installEventFilter(this);
connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear()));
connect(ui->fontBiggerButton, SIGNAL(clicked()), this, SLOT(fontBigger()));
connect(ui->fontSmallerButton, SIGNAL(clicked()), this, SLOT(fontSmaller()));
connect(ui->btnClearTrafficGraph, SIGNAL(clicked()), ui->trafficGraph, SLOT(clear()));
// set library version labels
#ifdef ENABLE_WALLET
ui->berkeleyDBVersion->setText(DbEnv::version(0, 0, 0));
#else
ui->label_berkeleyDBVersion->hide();
ui->berkeleyDBVersion->hide();
#endif
// Register RPC timer interface
rpcTimerInterface = new QtRPCTimerInterface();
// avoid accidentally overwriting an existing, non QTThread
// based timer interface
RPCSetTimerInterfaceIfUnset(rpcTimerInterface);
startExecutor();
setTrafficGraphRange(INITIAL_TRAFFIC_GRAPH_MINS);
ui->detailWidget->hide();
ui->peerHeading->setText(tr("Select a peer to view detailed information."));
QSettings settings;
consoleFontSize = settings.value(fontSizeSettingsKey, QFontInfo(QFont()).pointSize()).toInt();
clear();
}
RPCConsole::~RPCConsole()
{
GUIUtil::saveWindowGeometry("nRPCConsoleWindow", this);
Q_EMIT stopExecutor();
RPCUnsetTimerInterface(rpcTimerInterface);
delete rpcTimerInterface;
delete ui;
}
bool RPCConsole::eventFilter(QObject* obj, QEvent *event)
{
if(event->type() == QEvent::KeyPress) // Special key handling
{
QKeyEvent *keyevt = static_cast<QKeyEvent*>(event);
int key = keyevt->key();
Qt::KeyboardModifiers mod = keyevt->modifiers();
switch(key)
{
case Qt::Key_Up: if(obj == ui->lineEdit) { browseHistory(-1); return true; } break;
case Qt::Key_Down: if(obj == ui->lineEdit) { browseHistory(1); return true; } break;
case Qt::Key_PageUp: /* pass paging keys to messages widget */
case Qt::Key_PageDown:
if(obj == ui->lineEdit)
{
QApplication::postEvent(ui->messagesWidget, new QKeyEvent(*keyevt));
return true;
}
break;
default:
// Typing in messages widget brings focus to line edit, and redirects key there
// Exclude most combinations and keys that emit no text, except paste shortcuts
if(obj == ui->messagesWidget && (
(!mod && !keyevt->text().isEmpty() && key != Qt::Key_Tab) ||
((mod & Qt::ControlModifier) && key == Qt::Key_V) ||
((mod & Qt::ShiftModifier) && key == Qt::Key_Insert)))
{
ui->lineEdit->setFocus();
QApplication::postEvent(ui->lineEdit, new QKeyEvent(*keyevt));
return true;
}
}
}
return QWidget::eventFilter(obj, event);
}
void RPCConsole::setClientModel(ClientModel *model)
{
clientModel = model;
ui->trafficGraph->setClientModel(model);
if (model && clientModel->getPeerTableModel() && clientModel->getBanTableModel()) {
// Keep up to date with client
setNumConnections(model->getNumConnections());
connect(model, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int)));
setNumBlocks(model->getNumBlocks(), model->getLastBlockDate(), model->getVerificationProgress(NULL));
connect(model, SIGNAL(numBlocksChanged(int,QDateTime,double)), this, SLOT(setNumBlocks(int,QDateTime,double)));
updateTrafficStats(model->getTotalBytesRecv(), model->getTotalBytesSent());
connect(model, SIGNAL(bytesChanged(quint64,quint64)), this, SLOT(updateTrafficStats(quint64, quint64)));
connect(model, SIGNAL(mempoolSizeChanged(long,size_t)), this, SLOT(setMempoolSize(long,size_t)));
// set up peer table
ui->peerWidget->setModel(model->getPeerTableModel());
ui->peerWidget->verticalHeader()->hide();
ui->peerWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
ui->peerWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
ui->peerWidget->setSelectionMode(QAbstractItemView::SingleSelection);
ui->peerWidget->setContextMenuPolicy(Qt::CustomContextMenu);
ui->peerWidget->setColumnWidth(PeerTableModel::Address, ADDRESS_COLUMN_WIDTH);
ui->peerWidget->setColumnWidth(PeerTableModel::Subversion, SUBVERSION_COLUMN_WIDTH);
ui->peerWidget->setColumnWidth(PeerTableModel::Ping, PING_COLUMN_WIDTH);
ui->peerWidget->horizontalHeader()->setStretchLastSection(true);
// create peer table context menu actions
QAction* disconnectAction = new QAction(tr("&Disconnect Node"), this);
QAction* banAction1h = new QAction(tr("Ban Node for") + " " + tr("1 &hour"), this);
QAction* banAction24h = new QAction(tr("Ban Node for") + " " + tr("1 &day"), this);
QAction* banAction7d = new QAction(tr("Ban Node for") + " " + tr("1 &week"), this);
QAction* banAction365d = new QAction(tr("Ban Node for") + " " + tr("1 &year"), this);
// create peer table context menu
peersTableContextMenu = new QMenu();
peersTableContextMenu->addAction(disconnectAction);
peersTableContextMenu->addAction(banAction1h);
peersTableContextMenu->addAction(banAction24h);
peersTableContextMenu->addAction(banAction7d);
peersTableContextMenu->addAction(banAction365d);
// Add a signal mapping to allow dynamic context menu arguments.
// We need to use int (instead of int64_t), because signal mapper only supports
// int or objects, which is okay because max bantime (1 year) is < int_max.
QSignalMapper* signalMapper = new QSignalMapper(this);
signalMapper->setMapping(banAction1h, 60*60);
signalMapper->setMapping(banAction24h, 60*60*24);
signalMapper->setMapping(banAction7d, 60*60*24*7);
signalMapper->setMapping(banAction365d, 60*60*24*365);
connect(banAction1h, SIGNAL(triggered()), signalMapper, SLOT(map()));
connect(banAction24h, SIGNAL(triggered()), signalMapper, SLOT(map()));
connect(banAction7d, SIGNAL(triggered()), signalMapper, SLOT(map()));
connect(banAction365d, SIGNAL(triggered()), signalMapper, SLOT(map()));
connect(signalMapper, SIGNAL(mapped(int)), this, SLOT(banSelectedNode(int)));
// peer table context menu signals
connect(ui->peerWidget, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(showPeersTableContextMenu(const QPoint&)));
connect(disconnectAction, SIGNAL(triggered()), this, SLOT(disconnectSelectedNode()));
// peer table signal handling - update peer details when selecting new node
connect(ui->peerWidget->selectionModel(), SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)),
this, SLOT(peerSelected(const QItemSelection &, const QItemSelection &)));
// peer table signal handling - update peer details when new nodes are added to the model
connect(model->getPeerTableModel(), SIGNAL(layoutChanged()), this, SLOT(peerLayoutChanged()));
// set up ban table
ui->banlistWidget->setModel(model->getBanTableModel());
ui->banlistWidget->verticalHeader()->hide();
ui->banlistWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
ui->banlistWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
ui->banlistWidget->setSelectionMode(QAbstractItemView::SingleSelection);
ui->banlistWidget->setContextMenuPolicy(Qt::CustomContextMenu);
ui->banlistWidget->setColumnWidth(BanTableModel::Address, BANSUBNET_COLUMN_WIDTH);
ui->banlistWidget->setColumnWidth(BanTableModel::Bantime, BANTIME_COLUMN_WIDTH);
ui->banlistWidget->horizontalHeader()->setStretchLastSection(true);
// create ban table context menu action
QAction* unbanAction = new QAction(tr("&Unban Node"), this);
// create ban table context menu
banTableContextMenu = new QMenu();
banTableContextMenu->addAction(unbanAction);
// ban table context menu signals
connect(ui->banlistWidget, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(showBanTableContextMenu(const QPoint&)));
connect(unbanAction, SIGNAL(triggered()), this, SLOT(unbanSelectedNode()));
// ban table signal handling - clear peer details when clicking a peer in the ban table
connect(ui->banlistWidget, SIGNAL(clicked(const QModelIndex&)), this, SLOT(clearSelectedNode()));
// ban table signal handling - ensure ban table is shown or hidden (if empty)
connect(model->getBanTableModel(), SIGNAL(layoutChanged()), this, SLOT(showOrHideBanTableIfRequired()));
showOrHideBanTableIfRequired();
// Provide initial values
ui->clientVersion->setText(model->formatFullVersion());
ui->clientUserAgent->setText(model->formatSubVersion());
ui->clientName->setText(model->clientName());
ui->buildDate->setText(model->formatBuildDate());
ui->startupTime->setText(model->formatClientStartupTime());
ui->networkName->setText(QString::fromStdString(Params().NetworkIDString()));
//Setup autocomplete and attach it
QStringList wordList;
std::vector<std::string> commandList = tableRPC.listCommands();
for (size_t i = 0; i < commandList.size(); ++i)
{
wordList << commandList[i].c_str();
}
autoCompleter = new QCompleter(wordList, this);
ui->lineEdit->setCompleter(autoCompleter);
}
}
static QString categoryClass(int category)
{
switch(category)
{
case RPCConsole::CMD_REQUEST: return "cmd-request"; break;
case RPCConsole::CMD_REPLY: return "cmd-reply"; break;
case RPCConsole::CMD_ERROR: return "cmd-error"; break;
default: return "misc";
}
}
void RPCConsole::fontBigger()
{
setFontSize(consoleFontSize+1);
}
void RPCConsole::fontSmaller()
{
setFontSize(consoleFontSize-1);
}
void RPCConsole::setFontSize(int newSize)
{
QSettings settings;
//don't allow a insane font size
if (newSize < FONT_RANGE.width() || newSize > FONT_RANGE.height())
return;
// temp. store the console content
QString str = ui->messagesWidget->toHtml();
// replace font tags size in current content
str.replace(QString("font-size:%1pt").arg(consoleFontSize), QString("font-size:%1pt").arg(newSize));
// store the new font size
consoleFontSize = newSize;
settings.setValue(fontSizeSettingsKey, consoleFontSize);
// clear console (reset icon sizes, default stylesheet) and re-add the content
float oldPosFactor = 1.0 / ui->messagesWidget->verticalScrollBar()->maximum() * ui->messagesWidget->verticalScrollBar()->value();
clear(false);
ui->messagesWidget->setHtml(str);
ui->messagesWidget->verticalScrollBar()->setValue(oldPosFactor * ui->messagesWidget->verticalScrollBar()->maximum());
}
void RPCConsole::clear(bool clearHistory)
{
ui->messagesWidget->clear();
if(clearHistory)
{
history.clear();
historyPtr = 0;
}
ui->lineEdit->clear();
ui->lineEdit->setFocus();
// Add smoothly scaled icon images.
// (when using width/height on an img, Qt uses nearest instead of linear interpolation)
for(int i=0; ICON_MAPPING[i].url; ++i)
{
ui->messagesWidget->document()->addResource(
QTextDocument::ImageResource,
QUrl(ICON_MAPPING[i].url),
platformStyle->SingleColorImage(ICON_MAPPING[i].source).scaled(QSize(consoleFontSize*2, consoleFontSize*2), Qt::IgnoreAspectRatio, Qt::SmoothTransformation));
}
// Set default style sheet
QFontInfo fixedFontInfo(GUIUtil::fixedPitchFont());
ui->messagesWidget->document()->setDefaultStyleSheet(
QString(
"table { }"
"td.time { color: #808080; font-size: %2; padding-top: 3px; } "
"td.message { font-family: %1; font-size: %2; white-space:pre-wrap; } "
"td.cmd-request { color: #006060; } "
"td.cmd-error { color: red; } "
"b { color: #006060; } "
).arg(fixedFontInfo.family(), QString("%1pt").arg(consoleFontSize))
);
message(CMD_REPLY, (tr("Welcome to the %1 RPC console.").arg(tr(PACKAGE_NAME)) + "<br>" +
tr("Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.") + "<br>" +
tr("Type <b>help</b> for an overview of available commands.")), true);
}
void RPCConsole::keyPressEvent(QKeyEvent *event)
{
if(windowType() != Qt::Widget && event->key() == Qt::Key_Escape)
{
close();
}
}
void RPCConsole::message(int category, const QString &message, bool html)
{
QTime time = QTime::currentTime();
QString timeString = time.toString();
QString out;
out += "<table><tr><td class=\"time\" width=\"65\">" + timeString + "</td>";
out += "<td class=\"icon\" width=\"32\"><img src=\"" + categoryClass(category) + "\"></td>";
out += "<td class=\"message " + categoryClass(category) + "\" valign=\"middle\">";
if(html)
out += message;
else
out += GUIUtil::HtmlEscape(message, false);
out += "</td></tr></table>";
ui->messagesWidget->append(out);
}
void RPCConsole::setNumConnections(int count)
{
if (!clientModel)
return;
QString connections = QString::number(count) + " (";
connections += tr("In:") + " " + QString::number(clientModel->getNumConnections(CONNECTIONS_IN)) + " / ";
connections += tr("Out:") + " " + QString::number(clientModel->getNumConnections(CONNECTIONS_OUT)) + ")";
ui->numberOfConnections->setText(connections);
}
void RPCConsole::setNumBlocks(int count, const QDateTime& blockDate, double nVerificationProgress)
{
ui->numberOfBlocks->setText(QString::number(count));
ui->lastBlockTime->setText(blockDate.toString());
}
void RPCConsole::setMempoolSize(long numberOfTxs, size_t dynUsage)
{
ui->mempoolNumberTxs->setText(QString::number(numberOfTxs));
if (dynUsage < 1000000)
ui->mempoolSize->setText(QString::number(dynUsage/1000.0, 'f', 2) + " KB");
else
ui->mempoolSize->setText(QString::number(dynUsage/1000000.0, 'f', 2) + " MB");
}
void RPCConsole::on_lineEdit_returnPressed()
{
QString cmd = ui->lineEdit->text();
ui->lineEdit->clear();
if(!cmd.isEmpty())
{
message(CMD_REQUEST, cmd);
Q_EMIT cmdRequest(cmd);
// Remove command, if already in history
history.removeOne(cmd);
// Append command to history
history.append(cmd);
// Enforce maximum history size
while(history.size() > CONSOLE_HISTORY)
history.removeFirst();
// Set pointer to end of history
historyPtr = history.size();
// Scroll console view to end
scrollToEnd();
}
}
void RPCConsole::browseHistory(int offset)
{
historyPtr += offset;
if(historyPtr < 0)
historyPtr = 0;
if(historyPtr > history.size())
historyPtr = history.size();
QString cmd;
if(historyPtr < history.size())
cmd = history.at(historyPtr);
ui->lineEdit->setText(cmd);
}
void RPCConsole::startExecutor()
{
QThread *thread = new QThread;
RPCExecutor *executor = new RPCExecutor();
executor->moveToThread(thread);
// Replies from executor object must go to this object
connect(executor, SIGNAL(reply(int,QString)), this, SLOT(message(int,QString)));
// Requests from this object must go to executor
connect(this, SIGNAL(cmdRequest(QString)), executor, SLOT(request(QString)));
// On stopExecutor signal
// - queue executor for deletion (in execution thread)
// - quit the Qt event loop in the execution thread
connect(this, SIGNAL(stopExecutor()), executor, SLOT(deleteLater()));
connect(this, SIGNAL(stopExecutor()), thread, SLOT(quit()));
// Queue the thread for deletion (in this thread) when it is finished
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
// Default implementation of QThread::run() simply spins up an event loop in the thread,
// which is what we want.
thread->start();
}
void RPCConsole::on_tabWidget_currentChanged(int index)
{
if (ui->tabWidget->widget(index) == ui->tab_console)
ui->lineEdit->setFocus();
else if (ui->tabWidget->widget(index) != ui->tab_peers)
clearSelectedNode();
}
void RPCConsole::on_openDebugLogfileButton_clicked()
{
GUIUtil::openDebugLogfile();
}
void RPCConsole::scrollToEnd()
{
QScrollBar *scrollbar = ui->messagesWidget->verticalScrollBar();
scrollbar->setValue(scrollbar->maximum());
}
void RPCConsole::on_sldGraphRange_valueChanged(int value)
{
const int multiplier = 5; // each position on the slider represents 5 min
int mins = value * multiplier;
setTrafficGraphRange(mins);
}
QString RPCConsole::FormatBytes(quint64 bytes)
{
if(bytes < 1024)
return QString(tr("%1 B")).arg(bytes);
if(bytes < 1024 * 1024)
return QString(tr("%1 KB")).arg(bytes / 1024);
if(bytes < 1024 * 1024 * 1024)
return QString(tr("%1 MB")).arg(bytes / 1024 / 1024);
return QString(tr("%1 GB")).arg(bytes / 1024 / 1024 / 1024);
}
void RPCConsole::setTrafficGraphRange(int mins)
{
ui->trafficGraph->setGraphRangeMins(mins);
ui->lblGraphRange->setText(GUIUtil::formatDurationStr(mins * 60));
}
void RPCConsole::updateTrafficStats(quint64 totalBytesIn, quint64 totalBytesOut)
{
ui->lblBytesIn->setText(FormatBytes(totalBytesIn));
ui->lblBytesOut->setText(FormatBytes(totalBytesOut));
}
void RPCConsole::peerSelected(const QItemSelection &selected, const QItemSelection &deselected)
{
Q_UNUSED(deselected);
if (!clientModel || !clientModel->getPeerTableModel() || selected.indexes().isEmpty())
return;
const CNodeCombinedStats *stats = clientModel->getPeerTableModel()->getNodeStats(selected.indexes().first().row());
if (stats)
updateNodeDetail(stats);
}
void RPCConsole::peerLayoutChanged()
{
if (!clientModel || !clientModel->getPeerTableModel())
return;
const CNodeCombinedStats *stats = NULL;
bool fUnselect = false;
bool fReselect = false;
if (cachedNodeid == -1) // no node selected yet
return;
// find the currently selected row
int selectedRow = -1;
QModelIndexList selectedModelIndex = ui->peerWidget->selectionModel()->selectedIndexes();
if (!selectedModelIndex.isEmpty()) {
selectedRow = selectedModelIndex.first().row();
}
// check if our detail node has a row in the table (it may not necessarily
// be at selectedRow since its position can change after a layout change)
int detailNodeRow = clientModel->getPeerTableModel()->getRowByNodeId(cachedNodeid);
if (detailNodeRow < 0)
{
// detail node disappeared from table (node disconnected)
fUnselect = true;
}
else
{
if (detailNodeRow != selectedRow)
{
// detail node moved position
fUnselect = true;
fReselect = true;
}
// get fresh stats on the detail node.
stats = clientModel->getPeerTableModel()->getNodeStats(detailNodeRow);
}
if (fUnselect && selectedRow >= 0) {
clearSelectedNode();
}
if (fReselect)
{
ui->peerWidget->selectRow(detailNodeRow);
}
if (stats)
updateNodeDetail(stats);
}
void RPCConsole::updateNodeDetail(const CNodeCombinedStats *stats)
{
// Update cached nodeid
cachedNodeid = stats->nodeStats.nodeid;
// update the detail ui with latest node information
QString peerAddrDetails(QString::fromStdString(stats->nodeStats.addrName) + " ");
peerAddrDetails += tr("(node id: %1)").arg(QString::number(stats->nodeStats.nodeid));
if (!stats->nodeStats.addrLocal.empty())
peerAddrDetails += "<br />" + tr("via %1").arg(QString::fromStdString(stats->nodeStats.addrLocal));
ui->peerHeading->setText(peerAddrDetails);
ui->peerServices->setText(GUIUtil::formatServicesStr(stats->nodeStats.nServices));
ui->peerLastSend->setText(stats->nodeStats.nLastSend ? GUIUtil::formatDurationStr(GetTime() - stats->nodeStats.nLastSend) : tr("never"));
ui->peerLastRecv->setText(stats->nodeStats.nLastRecv ? GUIUtil::formatDurationStr(GetTime() - stats->nodeStats.nLastRecv) : tr("never"));
ui->peerBytesSent->setText(FormatBytes(stats->nodeStats.nSendBytes));
ui->peerBytesRecv->setText(FormatBytes(stats->nodeStats.nRecvBytes));
ui->peerConnTime->setText(GUIUtil::formatDurationStr(GetTime() - stats->nodeStats.nTimeConnected));
ui->peerPingTime->setText(GUIUtil::formatPingTime(stats->nodeStats.dPingTime));
ui->peerPingWait->setText(GUIUtil::formatPingTime(stats->nodeStats.dPingWait));
ui->timeoffset->setText(GUIUtil::formatTimeOffset(stats->nodeStats.nTimeOffset));
ui->peerVersion->setText(QString("%1").arg(QString::number(stats->nodeStats.nVersion)));
ui->peerSubversion->setText(QString::fromStdString(stats->nodeStats.cleanSubVer));
ui->peerDirection->setText(stats->nodeStats.fInbound ? tr("Inbound") : tr("Outbound"));
ui->peerHeight->setText(QString("%1").arg(QString::number(stats->nodeStats.nStartingHeight)));
ui->peerWhitelisted->setText(stats->nodeStats.fWhitelisted ? tr("Yes") : tr("No"));
// This check fails for example if the lock was busy and
// nodeStateStats couldn't be fetched.
if (stats->fNodeStateStatsAvailable) {
// Ban score is init to 0
ui->peerBanScore->setText(QString("%1").arg(stats->nodeStateStats.nMisbehavior));
// Sync height is init to -1
if (stats->nodeStateStats.nSyncHeight > -1)
ui->peerSyncHeight->setText(QString("%1").arg(stats->nodeStateStats.nSyncHeight));
else
ui->peerSyncHeight->setText(tr("Unknown"));
// Common height is init to -1
if (stats->nodeStateStats.nCommonHeight > -1)
ui->peerCommonHeight->setText(QString("%1").arg(stats->nodeStateStats.nCommonHeight));
else
ui->peerCommonHeight->setText(tr("Unknown"));
}
ui->detailWidget->show();
}
void RPCConsole::resizeEvent(QResizeEvent *event)
{
QWidget::resizeEvent(event);
}
void RPCConsole::showEvent(QShowEvent *event)
{
QWidget::showEvent(event);
if (!clientModel || !clientModel->getPeerTableModel())
return;
// start PeerTableModel auto refresh
clientModel->getPeerTableModel()->startAutoRefresh();
}
void RPCConsole::hideEvent(QHideEvent *event)
{
QWidget::hideEvent(event);
if (!clientModel || !clientModel->getPeerTableModel())
return;
// stop PeerTableModel auto refresh
clientModel->getPeerTableModel()->stopAutoRefresh();
}
void RPCConsole::showPeersTableContextMenu(const QPoint& point)
{
QModelIndex index = ui->peerWidget->indexAt(point);
if (index.isValid())
peersTableContextMenu->exec(QCursor::pos());
}
void RPCConsole::showBanTableContextMenu(const QPoint& point)
{
QModelIndex index = ui->banlistWidget->indexAt(point);
if (index.isValid())
banTableContextMenu->exec(QCursor::pos());
}
void RPCConsole::disconnectSelectedNode()
{
// Get currently selected peer address
QString strNode = GUIUtil::getEntryData(ui->peerWidget, 0, PeerTableModel::Address);
// Find the node, disconnect it and clear the selected node
if (CNode *bannedNode = FindNode(strNode.toStdString())) {
bannedNode->fDisconnect = true;
clearSelectedNode();
}
}
void RPCConsole::banSelectedNode(int bantime)
{
if (!clientModel)
return;
// Get currently selected peer address
QString strNode = GUIUtil::getEntryData(ui->peerWidget, 0, PeerTableModel::Address);
// Find possible nodes, ban it and clear the selected node
if (CNode *bannedNode = FindNode(strNode.toStdString())) {
std::string nStr = strNode.toStdString();
std::string addr;
int port = 0;
SplitHostPort(nStr, port, addr);
CNode::Ban(CNetAddr(addr), BanReasonManuallyAdded, bantime);
bannedNode->fDisconnect = true;
DumpBanlist();
clearSelectedNode();
clientModel->getBanTableModel()->refresh();
}
}
void RPCConsole::unbanSelectedNode()
{
if (!clientModel)
return;
// Get currently selected ban address
QString strNode = GUIUtil::getEntryData(ui->banlistWidget, 0, BanTableModel::Address);
CSubNet possibleSubnet(strNode.toStdString());
if (possibleSubnet.IsValid())
{
CNode::Unban(possibleSubnet);
DumpBanlist();
clientModel->getBanTableModel()->refresh();
}
}
void RPCConsole::clearSelectedNode()
{
ui->peerWidget->selectionModel()->clearSelection();
cachedNodeid = -1;
ui->detailWidget->hide();
ui->peerHeading->setText(tr("Select a peer to view detailed information."));
}
void RPCConsole::showOrHideBanTableIfRequired()
{
if (!clientModel)
return;
bool visible = clientModel->getBanTableModel()->shouldShow();
ui->banlistWidget->setVisible(visible);
ui->banHeading->setVisible(visible);
}
void RPCConsole::setTabFocus(enum TabTypes tabType)
{
ui->tabWidget->setCurrentIndex(tabType);
}
| mit |
OguzhanAydin61/SpotifyApi | spotify-api/src/main/java/oguzhan/spotify/webapi/android/models/AlbumSimple.java | 1822 | package oguzhan.spotify.webapi.android.models;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.List;
import java.util.Map;
public class AlbumSimple implements Parcelable {
public String album_type;
public List<String> available_markets;
public Map<String, String> external_urls;
public String href;
public String id;
public List<Image> images;
public String name;
public String type;
public String uri;
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.album_type);
dest.writeStringList(this.available_markets);
dest.writeMap(this.external_urls);
dest.writeString(this.href);
dest.writeString(this.id);
dest.writeTypedList(images);
dest.writeString(this.name);
dest.writeString(this.type);
dest.writeString(this.uri);
}
public AlbumSimple() {
}
protected AlbumSimple(Parcel in) {
this.album_type = in.readString();
this.available_markets = in.createStringArrayList();
this.external_urls = in.readHashMap(ClassLoader.getSystemClassLoader());
this.href = in.readString();
this.id = in.readString();
this.images = in.createTypedArrayList(Image.CREATOR);
this.name = in.readString();
this.type = in.readString();
this.uri = in.readString();
}
public static final Parcelable.Creator<AlbumSimple> CREATOR = new Parcelable.Creator<AlbumSimple>() {
public AlbumSimple createFromParcel(Parcel source) {
return new AlbumSimple(source);
}
public AlbumSimple[] newArray(int size) {
return new AlbumSimple[size];
}
};
}
| mit |
NsdWorkBook/DbLite | src/DbLite.Test/DeleteTests.cs | 1279 | namespace DbLite.Test
{
using Tables;
using System.Data;
using Xunit;
public abstract class DeleteTests<TDatabaseFixture, TConnection>
where TDatabaseFixture : DatabaseFixture<TConnection>
where TConnection : IDbConnection
{
private readonly TDatabaseFixture fixture;
public TDatabaseFixture Fixture
{
get
{
return fixture;
}
}
protected DeleteTests(TDatabaseFixture fixture)
{
this.fixture = fixture;
}
[Fact]
public void DeleteRecord()
{
using (var connection = Fixture.Open())
{
using (connection.OpenTransaction())
{
bool eventInvoked = false;
DbLiteConfiguration.BeforeDelete += (ss, ee) => eventInvoked = true;
var record = connection.Single<SimpleTable>("Interger1 = @Id", new { Id = 20 });
connection.Delete(record);
Assert.Null(connection.Single<SimpleTable>("Interger1 = @Id", new { Id = 20 }));
Assert.True(eventInvoked, "BeforeDelete was not invoked");
}
}
}
}
}
| mit |
cmccullough2/cmv-wab-widgets | cmv/js/gis/dijit/Identify/nls/pt-br/resource.js | 379 | /* ConfigurableMapViewerCMV
* version 2.0.0-beta.1
* Project: http://cmv.io/
*/
define({labels:{selectLayer:'Escolha "Todas Camadas Visíveis" ou uma camada única para Identificar:',allVisibleLayers:"*** Todas Camadas Visíveis ***"},rightClickMenuItem:{label:"Identifique aqui"},mapInfoWindow:{identifyingTitle:"Identificando..."}});
//# sourceMappingURL=resource.js.map | mit |
GeorgiPetrovGH/TelerikAcademy | 08.High-Quality-Code/Defensive Programming and Exceptions/Assertions_Exceptions/Exception_handling/Properties/AssemblyInfo.cs | 1412 | 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("Exception_handling")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Exception_handling")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[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("226279b2-08df-4af8-8aad-b326e7426a7c")]
// 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 |
BitFunnel/BitFunnel | tools/BitFunnel/src/SaveCommand.cpp | 2377 | // The MIT License (MIT)
// Copyright (c) 2016, Microsoft
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include <iostream>
#include "BitFunnel/Index/IIngestor.h"
#include "Environment.h"
#include "SaveCommand.h"
namespace BitFunnel
{
//*************************************************************************
//
// WriteSlicesCommand
//
//*************************************************************************
WriteSlicesCommand::WriteSlicesCommand(Environment & environment,
Id id,
char const * /*parameters*/)
: TaskBase(environment, id, Type::Synchronous)
{
}
void WriteSlicesCommand::Execute()
{
std::cout
<< "Saving all documents as slices. This may take a while . . ."
<< std::endl
<< std::endl;
auto & fileManager = GetEnvironment().GetSimpleIndex().GetFileManager();
GetEnvironment().GetIngestor().TemporaryWriteAllSlices(fileManager);
}
ICommand::Documentation WriteSlicesCommand::GetDocumentation()
{
return Documentation(
"save",
"Save all ingested documents to disk as slices.",
"save <path>\n"
" Save all ingested documents to disk as slices."
);
}
}
| mit |
tal/assette | lib/assette/post_processors/cache_buster.rb | 415 | module Assette
class PostProcessor::CacheBuster < Assette::PostProcessor(:css)
URL_MATCHER = /url\((?:["'])?(?!http)(?!\/\/)([\w\/\.\-\s\?=]+)(?:["'])?\)/i
def should_process?
Assette.config.compiling?
end
def processor
@@i ||= -1
@str.gsub(URL_MATCHER) do |s|
url = Assette.compiled_path @@i+=1, $1
%Q{url("#{url}")}
end
end
end
end
| mit |
1vasari/Guitar-Practice-App | gpa/app/urls.py | 140 |
from django.conf.urls import patterns, url
from app import views
urlpatterns = patterns(
'',
url(r'^$', views.app, name='app'),
)
| mit |
sachaudh/Genie-Server | public/models/userModel.js | 341 | var mongoose = require('mongoose');
var userSchema = new mongoose.Schema({
fb_id: String,
first_name: String,
last_name: String,
email: String,
gender: String,
image : String,
friends : [{ type: mongoose.Schema.Types.ObjectId, ref: 'User'}]
}, { versionKey: false });
module.exports = mongoose.model('User', userSchema); | mit |
nbkhope/phase-0 | week-4/shortest-string/my_solution.rb | 755 | # Shortest String
# I worked on this challenge [by myself, with: ].
# shortest_string is a method that takes an array of strings as its input
# and returns the shortest string
#
# +list_of_words+ is an array of strings
# shortest_string(array) should return the shortest string in the +list_of_words+
#
# If +list_of_words+ is empty the method should return nil
#Your Solution Below
def shortest_string(list_of_words)
# If given input is an empty array,
# return nil right away
if list_of_words.empty?
return nil
end
# Assume first word is the shortest
shortest = list_of_words[0]
# Go through each item in the array
list_of_words.each do |word|
if word.length < shortest.length
shortest = word
end
end
return shortest
end
| mit |
concord-consortium/rigse | admin-panel/react-admin-interface/src/entities/projectUser.js | 2330 | import React from "react"
import {
Edit, Create,
SimpleForm,
BooleanInput, ReferenceInput, SelectInput,
ReferenceField, TextField, FunctionField
} from "react-admin"
import { parse } from "query-string";
// Once created the project and user can't be changed
export const ProjectUserEdit = props => (
<Edit {...props}>
<SimpleForm redirect={(basePath, id, data) => `/User/${data.userId}`}>
<ReferenceField label="Project" source="projectId" reference="AdminProject">
<TextField source="name"/>
</ReferenceField>
<ReferenceField label="User" source="userId" reference="User">
<FunctionField render={record => `${record.firstName} ${record.lastName}`} />
</ReferenceField>
<BooleanInput source="isAdmin"/>
<BooleanInput source="isResearcher"/>
</SimpleForm>
</Edit>
);
// Create is always called from the User page with a userId so there isn't a need
// to edit the User field
export const ProjectUserCreate = props => {
// Read the userId from the location which is injected by React Router
// and passed to our component by react-admin automatically
const { userId } = parse(props.location.search);
const redirect = userId ? `/User/${userId}` : "/User";
// FIXME: This form doesn't have good error handling if a duplicate project is
// selected a notification will be shown below the form, but it disappears
// too quickly. And the notification is not very useful.
return (
<Create title="Add user to a project" {...props}>
<SimpleForm defaultValue={{userId}} redirect={redirect}>
<ReferenceInput label="User" source="userId" reference="User">
<SelectInput disabled={!!userId}
optionText={record => `${record.firstName} ${record.lastName}`}/>
</ReferenceInput>
{/* TODO: this doesn't remove projects that the user has already been added to.
the database has a unique index on projectId and userId so it should be rejected
but it'd be better if the form limited the list. */}
<ReferenceInput label="Project" source="projectId" reference="AdminProject">
<SelectInput optionText="name"/>
</ReferenceInput>
<BooleanInput source="isAdmin"/>
<BooleanInput source="isResearcher"/>
</SimpleForm>
</Create>
);
};
| mit |
mrmar096/businesspoweron | system/database/DB_driver.php | 45741 | <?php
/**
* CodeIgniter
*
* An open source application development framework for PHP
*
* This content is released under the MIT License (MIT)
*
* Copyright (c) 2014 - 2017, British Columbia Institute of Technology
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @package CodeIgniter
* @author EllisLab Dev Team
* @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/)
* @copyright Copyright (c) 2014 - 2017, British Columbia Institute of Technology (http://bcit.ca/)
* @license http://opensource.org/licenses/MIT MIT License
* @link https://codeigniter.com
* @since Version 1.0.0
* @filesource
*/
defined('BASEPATH') OR exit('No direct script access allowed');
/**
* Database Driver Class
*
* This is the platform-independent base DB implementation class.
* This class will not be called directly. Rather, the adapter
* class for the specific database will extend and instantiate it.
*
* @package CodeIgniter
* @subpackage Drivers
* @category Database
* @author EllisLab Dev Team
* @link https://codeigniter.com/user_guide/database/
*/
abstract class CI_DB_driver {
/**
* Data Source Name / Connect string
*
* @var string
*/
public $dsn;
/**
* Username
*
* @var string
*/
public $username;
/**
* Password
*
* @var string
*/
public $password;
/**
* Hostname
*
* @var string
*/
public $hostname;
/**
* Database name
*
* @var string
*/
public $database;
/**
* Database driver
*
* @var string
*/
public $dbdriver = 'mysqli';
/**
* Sub-driver
*
* @used-by CI_DB_pdo_driver
* @var string
*/
public $subdriver;
/**
* Table prefix
*
* @var string
*/
public $dbprefix = '';
/**
* Character set
*
* @var string
*/
public $char_set = 'utf8';
/**
* Collation
*
* @var string
*/
public $dbcollat = 'utf8_general_ci';
/**
* Encryption flag/data
*
* @var mixed
*/
public $encrypt = FALSE;
/**
* Swap Prefix
*
* @var string
*/
public $swap_pre = '';
/**
* Database port
*
* @var int
*/
public $port = '';
/**
* Persistent connection flag
*
* @var bool
*/
public $pconnect = FALSE;
/**
* Connection ID
*
* @var object|resource
*/
public $conn_id = FALSE;
/**
* Result ID
*
* @var object|resource
*/
public $result_id = FALSE;
/**
* Debug flag
*
* Whether to display error messages.
*
* @var bool
*/
public $db_debug = FALSE;
/**
* Benchmark time
*
* @var int
*/
public $benchmark = 0;
/**
* Executed queries count
*
* @var int
*/
public $query_count = 0;
/**
* Bind marker
*
* Character used to identify values in a prepared statement.
*
* @var string
*/
public $bind_marker = '?';
/**
* Save queries flag
*
* Whether to keep an in-memory history of queries for debugging purposes.
*
* @var bool
*/
public $save_queries = TRUE;
/**
* Queries list
*
* @see CI_DB_driver::$save_queries
* @var string[]
*/
public $queries = array();
/**
* Query times
*
* A list of times that queries took to execute.
*
* @var array
*/
public $query_times = array();
/**
* Data cache
*
* An internal generic value cache.
*
* @var array
*/
public $data_cache = array();
/**
* Transaction enabled flag
*
* @var bool
*/
public $trans_enabled = TRUE;
/**
* Strict transaction mode flag
*
* @var bool
*/
public $trans_strict = TRUE;
/**
* Transaction depth level
*
* @var int
*/
protected $_trans_depth = 0;
/**
* Transaction status flag
*
* Used with transactions to determine if a rollback should occur.
*
* @var bool
*/
protected $_trans_status = TRUE;
/**
* Transaction failure flag
*
* Used with transactions to determine if a transaction has failed.
*
* @var bool
*/
protected $_trans_failure = FALSE;
/**
* Cache On flag
*
* @var bool
*/
public $cache_on = FALSE;
/**
* Cache directory path
*
* @var bool
*/
public $cachedir = '';
/**
* Cache auto-delete flag
*
* @var bool
*/
public $cache_autodel = FALSE;
/**
* DB Cache object
*
* @see CI_DB_cache
* @var object
*/
public $CACHE;
/**
* Protect identifiers flag
*
* @var bool
*/
protected $_protect_identifiers = TRUE;
/**
* List of reserved identifiers
*
* Identifiers that must NOT be escaped.
*
* @var string[]
*/
protected $_reserved_identifiers = array('*');
/**
* Identifier escape character
*
* @var string
*/
protected $_escape_char = '"';
/**
* ESCAPE statement string
*
* @var string
*/
protected $_like_escape_str = " ESCAPE '%s' ";
/**
* ESCAPE character
*
* @var string
*/
protected $_like_escape_chr = '!';
/**
* ORDER BY random keyword
*
* @var array
*/
protected $_random_keyword = array('RAND()', 'RAND(%d)');
/**
* COUNT string
*
* @used-by CI_DB_driver::count_all()
* @used-by CI_DB_query_builder::count_all_results()
*
* @var string
*/
protected $_count_string = 'SELECT COUNT(*) AS ';
// --------------------------------------------------------------------
/**
* Class constructor
*
* @param array $params
* @return void
*/
public function __construct($params)
{
if (is_array($params))
{
foreach ($params as $key => $val)
{
$this->$key = $val;
}
}
log_message('info', 'Database Driver Class Initialized');
}
// --------------------------------------------------------------------
/**
* Initialize Database Settings
*
* @return bool
*/
public function initialize()
{
/* If an established connection is available, then there's
* no need to connect and select the database.
*
* Depending on the database driver, conn_id can be either
* boolean TRUE, a resource or an object.
*/
if ($this->conn_id)
{
return TRUE;
}
// ----------------------------------------------------------------
// Connect to the database and set the connection ID
$this->conn_id = $this->db_connect($this->pconnect);
// No connection resource? Check if there is a failover else throw an error
if ( ! $this->conn_id)
{
// Check if there is a failover set
if ( ! empty($this->failover) && is_array($this->failover))
{
// Go over all the failovers
foreach ($this->failover as $failover)
{
// Replace the current settings with those of the failover
foreach ($failover as $key => $val)
{
$this->$key = $val;
}
// Try to connect
$this->conn_id = $this->db_connect($this->pconnect);
// If a connection is made break the foreach loop
if ($this->conn_id)
{
break;
}
}
}
// We still don't have a connection?
if ( ! $this->conn_id)
{
log_message('error', 'Unable to connect to the database');
if ($this->db_debug)
{
$this->display_error('db_unable_to_connect');
}
return FALSE;
}
}
// Now we set the character set and that's all
return $this->db_set_charset($this->char_set);
}
// --------------------------------------------------------------------
/**
* DB connect
*
* This is just a dummy method that all drivers will override.
*
* @return mixed
*/
public function db_connect()
{
return TRUE;
}
// --------------------------------------------------------------------
/**
* Persistent database connection
*
* @return mixed
*/
public function db_pconnect()
{
return $this->db_connect(TRUE);
}
// --------------------------------------------------------------------
/**
* Reconnect
*
* Keep / reestablish the db connection if no queries have been
* sent for a length of time exceeding the server's idle timeout.
*
* This is just a dummy method to allow drivers without such
* functionality to not declare it, while others will override it.
*
* @return void
*/
public function reconnect()
{
}
// --------------------------------------------------------------------
/**
* Select database
*
* This is just a dummy method to allow drivers without such
* functionality to not declare it, while others will override it.
*
* @return bool
*/
public function db_select()
{
return TRUE;
}
// --------------------------------------------------------------------
/**
* Last error
*
* @return array
*/
public function error()
{
return array('code' => NULL, 'message' => NULL);
}
// --------------------------------------------------------------------
/**
* Set client character set
*
* @param string
* @return bool
*/
public function db_set_charset($charset)
{
if (method_exists($this, '_db_set_charset') && ! $this->_db_set_charset($charset))
{
log_message('error', 'Unable to set database connection charset: '.$charset);
if ($this->db_debug)
{
$this->display_error('db_unable_to_set_charset', $charset);
}
return FALSE;
}
return TRUE;
}
// --------------------------------------------------------------------
/**
* The name of the platform in use (mysql, mssql, etc...)
*
* @return string
*/
public function platform()
{
return $this->dbdriver;
}
// --------------------------------------------------------------------
/**
* Database version number
*
* Returns a string containing the version of the database being used.
* Most drivers will override this method.
*
* @return string
*/
public function version()
{
if (isset($this->data_cache['version']))
{
return $this->data_cache['version'];
}
if (FALSE === ($sql = $this->_version()))
{
return ($this->db_debug) ? $this->display_error('db_unsupported_function') : FALSE;
}
$query = $this->query($sql)->row();
return $this->data_cache['version'] = $query->ver;
}
// --------------------------------------------------------------------
/**
* Version number query string
*
* @return string
*/
protected function _version()
{
return 'SELECT VERSION() AS ver';
}
// --------------------------------------------------------------------
/**
* Execute the query
*
* Accepts an SQL string as input and returns a result object upon
* successful execution of a "read" type query. Returns boolean TRUE
* upon successful execution of a "write" type query. Returns boolean
* FALSE upon failure, and if the $db_debug variable is set to TRUE
* will raise an error.
*
* @param string $sql
* @param array $binds = FALSE An array of binding data
* @param bool $return_object = NULL
* @return mixed
*/
public function query($sql, $binds = FALSE, $return_object = NULL)
{
if ($sql === '')
{
log_message('error', 'Invalid query: '.$sql);
return ($this->db_debug) ? $this->display_error('db_invalid_query') : FALSE;
}
elseif ( ! is_bool($return_object))
{
$return_object = ! $this->is_write_type($sql);
}
// Verify table prefix and replace if necessary
if ($this->dbprefix !== '' && $this->swap_pre !== '' && $this->dbprefix !== $this->swap_pre)
{
$sql = preg_replace('/(\W)'.$this->swap_pre.'(\S+?)/', '\\1'.$this->dbprefix.'\\2', $sql);
}
// Compile binds if needed
if ($binds !== FALSE)
{
$sql = $this->compile_binds($sql, $binds);
}
// Is query caching enabled? If the query is a "read type"
// we will load the caching class and return the previously
// cached query if it exists
if ($this->cache_on === TRUE && $return_object === TRUE && $this->_cache_init())
{
$this->load_rdriver();
if (FALSE !== ($cache = $this->CACHE->read($sql)))
{
return $cache;
}
}
// Save the query for debugging
if ($this->save_queries === TRUE)
{
$this->queries[] = $sql;
}
// Start the Query Timer
$time_start = microtime(TRUE);
// Run the Query
if (FALSE === ($this->result_id = $this->simple_query($sql)))
{
if ($this->save_queries === TRUE)
{
$this->query_times[] = 0;
}
// This will trigger a rollback if transactions are being used
if ($this->_trans_depth !== 0)
{
$this->_trans_status = FALSE;
}
// Grab the error now, as we might run some additional queries before displaying the error
$error = $this->error();
// Log errors
log_message('error', 'Query error: '.$error['message'].' - Invalid query: '.$sql);
if ($this->db_debug)
{
// We call this function in order to roll-back queries
// if transactions are enabled. If we don't call this here
// the error message will trigger an exit, causing the
// transactions to remain in limbo.
while ($this->_trans_depth !== 0)
{
$trans_depth = $this->_trans_depth;
$this->trans_complete();
if ($trans_depth === $this->_trans_depth)
{
log_message('error', 'Database: Failure during an automated transaction commit/rollback!');
break;
}
}
// Display errors
return $this->display_error(array('Error Number: '.$error['code'], $error['message'], $sql));
}
return FALSE;
}
// Stop and aggregate the query time results
$time_end = microtime(TRUE);
$this->benchmark += $time_end - $time_start;
if ($this->save_queries === TRUE)
{
$this->query_times[] = $time_end - $time_start;
}
// Increment the query counter
$this->query_count++;
// Will we have a result object instantiated? If not - we'll simply return TRUE
if ($return_object !== TRUE)
{
// If caching is enabled we'll auto-cleanup any existing files related to this particular URI
if ($this->cache_on === TRUE && $this->cache_autodel === TRUE && $this->_cache_init())
{
$this->CACHE->delete();
}
return TRUE;
}
// Load and instantiate the result driver
$driver = $this->load_rdriver();
$RES = new $driver($this);
// Is query caching enabled? If so, we'll serialize the
// result object and save it to a cache file.
if ($this->cache_on === TRUE && $this->_cache_init())
{
// We'll create a new instance of the result object
// only without the platform specific driver since
// we can't use it with cached data (the query result
// resource ID won't be any good once we've cached the
// result object, so we'll have to compile the data
// and save it)
$CR = new CI_DB_result($this);
$CR->result_object = $RES->result_object();
$CR->result_array = $RES->result_array();
$CR->num_rows = $RES->num_rows();
// Reset these since cached objects can not utilize resource IDs.
$CR->conn_id = NULL;
$CR->result_id = NULL;
$this->CACHE->write($sql, $CR);
}
return $RES;
}
// --------------------------------------------------------------------
/**
* Load the result drivers
*
* @return string the name of the result class
*/
public function load_rdriver()
{
$driver = 'CI_DB_'.$this->dbdriver.'_result';
if ( ! class_exists($driver, FALSE))
{
require_once(BASEPATH.'database/DB_result.php');
require_once(BASEPATH.'database/drivers/'.$this->dbdriver.'/'.$this->dbdriver.'_result.php');
}
return $driver;
}
// --------------------------------------------------------------------
/**
* Simple Query
* This is a simplified version of the query() function. Internally
* we only use it when running transaction commands since they do
* not require all the features of the main query() function.
*
* @param string the sql query
* @return mixed
*/
public function simple_query($sql)
{
if ( ! $this->conn_id)
{
if ( ! $this->initialize())
{
return FALSE;
}
}
return $this->_execute($sql);
}
// --------------------------------------------------------------------
/**
* Disable Transactions
* This permits transactions to be disabled at run-time.
*
* @return void
*/
public function trans_off()
{
$this->trans_enabled = FALSE;
}
// --------------------------------------------------------------------
/**
* Enable/disable Transaction Strict Mode
*
* When strict mode is enabled, if you are running multiple groups of
* transactions, if one group fails all subsequent groups will be
* rolled back.
*
* If strict mode is disabled, each group is treated autonomously,
* meaning a failure of one group will not affect any others
*
* @param bool $mode = TRUE
* @return void
*/
public function trans_strict($mode = TRUE)
{
$this->trans_strict = is_bool($mode) ? $mode : TRUE;
}
// --------------------------------------------------------------------
/**
* Start Transaction
*
* @param bool $test_mode = FALSE
* @return bool
*/
public function trans_start($test_mode = FALSE)
{
if ( ! $this->trans_enabled)
{
return FALSE;
}
return $this->trans_begin($test_mode);
}
// --------------------------------------------------------------------
/**
* Complete Transaction
*
* @return bool
*/
public function trans_complete()
{
if ( ! $this->trans_enabled)
{
return FALSE;
}
// The query() function will set this flag to FALSE in the event that a query failed
if ($this->_trans_status === FALSE OR $this->_trans_failure === TRUE)
{
$this->trans_rollback();
// If we are NOT running in strict mode, we will reset
// the _trans_status flag so that subsequent groups of
// transactions will be permitted.
if ($this->trans_strict === FALSE)
{
$this->_trans_status = TRUE;
}
log_message('debug', 'DB Transaction Failure');
return FALSE;
}
return $this->trans_commit();
}
// --------------------------------------------------------------------
/**
* Lets you retrieve the transaction flag to determine if it has failed
*
* @return bool
*/
public function trans_status()
{
return $this->_trans_status;
}
// --------------------------------------------------------------------
/**
* Begin Transaction
*
* @param bool $test_mode
* @return bool
*/
public function trans_begin($test_mode = FALSE)
{
if ( ! $this->trans_enabled)
{
return FALSE;
}
// When transactions are nested we only begin/commit/rollback the outermost ones
elseif ($this->_trans_depth > 0)
{
$this->_trans_depth++;
return TRUE;
}
// Reset the transaction failure flag.
// If the $test_mode flag is set to TRUE transactions will be rolled back
// even if the queries produce a successful result.
$this->_trans_failure = ($test_mode === TRUE);
if ($this->_trans_begin())
{
$this->_trans_depth++;
return TRUE;
}
return FALSE;
}
// --------------------------------------------------------------------
/**
* Commit Transaction
*
* @return bool
*/
public function trans_commit()
{
if ( ! $this->trans_enabled OR $this->_trans_depth === 0)
{
return FALSE;
}
// When transactions are nested we only begin/commit/rollback the outermost ones
elseif ($this->_trans_depth > 1 OR $this->_trans_commit())
{
$this->_trans_depth--;
return TRUE;
}
return FALSE;
}
// --------------------------------------------------------------------
/**
* Rollback Transaction
*
* @return bool
*/
public function trans_rollback()
{
if ( ! $this->trans_enabled OR $this->_trans_depth === 0)
{
return FALSE;
}
// When transactions are nested we only begin/commit/rollback the outermost ones
elseif ($this->_trans_depth > 1 OR $this->_trans_rollback())
{
$this->_trans_depth--;
return TRUE;
}
return FALSE;
}
// --------------------------------------------------------------------
/**
* Compile Bindings
*
* @param string the sql statement
* @param array an array of bind data
* @return string
*/
public function compile_binds($sql, $binds)
{
if (empty($this->bind_marker) OR strpos($sql, $this->bind_marker) === FALSE)
{
return $sql;
}
elseif ( ! is_array($binds))
{
$binds = array($binds);
$bind_count = 1;
}
else
{
// Make sure we're using numeric keys
$binds = array_values($binds);
$bind_count = count($binds);
}
// We'll need the marker length later
$ml = strlen($this->bind_marker);
// Make sure not to replace a chunk inside a string that happens to match the bind marker
if ($c = preg_match_all("/'[^']*'|\"[^\"]*\"/i", $sql, $matches))
{
$c = preg_match_all('/'.preg_quote($this->bind_marker, '/').'/i',
str_replace($matches[0],
str_replace($this->bind_marker, str_repeat(' ', $ml), $matches[0]),
$sql, $c),
$matches, PREG_OFFSET_CAPTURE);
// Bind values' count must match the count of markers in the query
if ($bind_count !== $c)
{
return $sql;
}
}
elseif (($c = preg_match_all('/'.preg_quote($this->bind_marker, '/').'/i', $sql, $matches, PREG_OFFSET_CAPTURE)) !== $bind_count)
{
return $sql;
}
do
{
$c--;
$escaped_value = $this->escape($binds[$c]);
if (is_array($escaped_value))
{
$escaped_value = '('.implode(',', $escaped_value).')';
}
$sql = substr_replace($sql, $escaped_value, $matches[0][$c][1], $ml);
}
while ($c !== 0);
return $sql;
}
// --------------------------------------------------------------------
/**
* Determines if a query is a "write" type.
*
* @param string An SQL query string
* @return bool
*/
public function is_write_type($sql)
{
return (bool) preg_match('/^\s*"?(SET|INSERT|UPDATE|DELETE|REPLACE|CREATE|DROP|TRUNCATE|LOAD|COPY|ALTER|RENAME|GRANT|REVOKE|LOCK|UNLOCK|REINDEX)\s/i', $sql);
}
// --------------------------------------------------------------------
/**
* Calculate the aggregate query elapsed time
*
* @param int The number of decimal places
* @return string
*/
public function elapsed_time($decimals = 6)
{
return number_format($this->benchmark, $decimals);
}
// --------------------------------------------------------------------
/**
* Returns the total number of queries
*
* @return int
*/
public function total_queries()
{
return $this->query_count;
}
// --------------------------------------------------------------------
/**
* Returns the last query that was executed
*
* @return string
*/
public function last_query()
{
return end($this->queries);
}
// --------------------------------------------------------------------
/**
* "Smart" Escape String
*
* Escapes data based on type
* Sets boolean and null types
*
* @param string
* @return mixed
*/
public function escape($str)
{
if (is_array($str))
{
$str = array_map(array(&$this, 'escape'), $str);
return $str;
}
elseif (is_string($str) OR (is_object($str) && method_exists($str, '__toString')))
{
return "'".$this->escape_str($str)."'";
}
elseif (is_bool($str))
{
return ($str === FALSE) ? 0 : 1;
}
elseif ($str === NULL)
{
return 'NULL';
}
return $str;
}
// --------------------------------------------------------------------
/**
* Escape String
*
* @param string|string[] $str Input string
* @param bool $like Whether or not the string will be used in a LIKE condition
* @return string
*/
public function escape_str($str, $like = FALSE)
{
if (is_array($str))
{
foreach ($str as $key => $val)
{
$str[$key] = $this->escape_str($val, $like);
}
return $str;
}
$str = $this->_escape_str($str);
// escape LIKE condition wildcards
if ($like === TRUE)
{
return str_replace(
array($this->_like_escape_chr, '%', '_'),
array($this->_like_escape_chr.$this->_like_escape_chr, $this->_like_escape_chr.'%', $this->_like_escape_chr.'_'),
$str
);
}
return $str;
}
// --------------------------------------------------------------------
/**
* Escape LIKE String
*
* Calls the individual driver for platform
* specific escaping for LIKE conditions
*
* @param string|string[]
* @return mixed
*/
public function escape_like_str($str)
{
return $this->escape_str($str, TRUE);
}
// --------------------------------------------------------------------
/**
* Platform-dependant string escape
*
* @param string
* @return string
*/
protected function _escape_str($str)
{
return str_replace("'", "''", remove_invisible_characters($str));
}
// --------------------------------------------------------------------
/**
* Primary
*
* Retrieves the main key. It assumes that the row in the first
* position is the main key
*
* @param string $table Table name
* @return string
*/
public function primary($table)
{
$fields = $this->list_fields($table);
return is_array($fields) ? current($fields) : FALSE;
}
// --------------------------------------------------------------------
/**
* "Count All" query
*
* Generates a platform-specific query string that counts all records in
* the specified database
*
* @param string
* @return int
*/
public function count_all($table = '')
{
if ($table === '')
{
return 0;
}
$query = $this->query($this->_count_string.$this->escape_identifiers('numrows').' FROM '.$this->protect_identifiers($table, TRUE, NULL, FALSE));
if ($query->num_rows() === 0)
{
return 0;
}
$query = $query->row();
$this->_reset_select();
return (int) $query->numrows;
}
// --------------------------------------------------------------------
/**
* Returns an array of table names
*
* @param string $constrain_by_prefix = FALSE
* @return array
*/
public function list_tables($constrain_by_prefix = FALSE)
{
// Is there a cached result?
if (isset($this->data_cache['table_names']))
{
return $this->data_cache['table_names'];
}
if (FALSE === ($sql = $this->_list_tables($constrain_by_prefix)))
{
return ($this->db_debug) ? $this->display_error('db_unsupported_function') : FALSE;
}
$this->data_cache['table_names'] = array();
$query = $this->query($sql);
foreach ($query->result_array() as $row)
{
// Do we know from which column to get the table name?
if ( ! isset($key))
{
if (isset($row['table_name']))
{
$key = 'table_name';
}
elseif (isset($row['TABLE_NAME']))
{
$key = 'TABLE_NAME';
}
else
{
/* We have no other choice but to just get the first element's key.
* Due to array_shift() accepting its argument by reference, if
* E_STRICT is on, this would trigger a warning. So we'll have to
* assign it first.
*/
$key = array_keys($row);
$key = array_shift($key);
}
}
$this->data_cache['table_names'][] = $row[$key];
}
return $this->data_cache['table_names'];
}
// --------------------------------------------------------------------
/**
* Determine if a particular table exists
*
* @param string $table_name
* @return bool
*/
public function table_exists($table_name)
{
return in_array($this->protect_identifiers($table_name, TRUE, FALSE, FALSE), $this->list_tables());
}
// --------------------------------------------------------------------
/**
* Fetch Field Names
*
* @param string $table Table name
* @return array
*/
public function list_fields($table)
{
// Is there a cached result?
if (isset($this->data_cache['field_names'][$table]))
{
return $this->data_cache['field_names'][$table];
}
if (FALSE === ($sql = $this->_list_columns($table)))
{
return ($this->db_debug) ? $this->display_error('db_unsupported_function') : FALSE;
}
$query = $this->query($sql);
$this->data_cache['field_names'][$table] = array();
foreach ($query->result_array() as $row)
{
// Do we know from where to get the column's name?
if ( ! isset($key))
{
if (isset($row['column_name']))
{
$key = 'column_name';
}
elseif (isset($row['COLUMN_NAME']))
{
$key = 'COLUMN_NAME';
}
else
{
// We have no other choice but to just get the first element's key.
$key = key($row);
}
}
$this->data_cache['field_names'][$table][] = $row[$key];
}
return $this->data_cache['field_names'][$table];
}
// --------------------------------------------------------------------
/**
* Determine if a particular field exists
*
* @param string
* @param string
* @return bool
*/
public function field_exists($field_name, $table_name)
{
return in_array($field_name, $this->list_fields($table_name));
}
// --------------------------------------------------------------------
/**
* Returns an object with field data
*
* @param string $table the table name
* @return array
*/
public function field_data($table)
{
$query = $this->query($this->_field_data($this->protect_identifiers($table, TRUE, NULL, FALSE)));
return ($query) ? $query->field_data() : FALSE;
}
// --------------------------------------------------------------------
/**
* Escape the SQL Identifiers
*
* This function escapes column and table names
*
* @param mixed
* @return mixed
*/
public function escape_identifiers($item)
{
if ($this->_escape_char === '' OR empty($item) OR in_array($item, $this->_reserved_identifiers))
{
return $item;
}
elseif (is_array($item))
{
foreach ($item as $key => $value)
{
$item[$key] = $this->escape_identifiers($value);
}
return $item;
}
// Avoid breaking functions and literal values inside queries
elseif (ctype_digit($item) OR $item[0] === "'" OR ($this->_escape_char !== '"' && $item[0] === '"') OR strpos($item, '(') !== FALSE)
{
return $item;
}
static $preg_ec = array();
if (empty($preg_ec))
{
if (is_array($this->_escape_char))
{
$preg_ec = array(
preg_quote($this->_escape_char[0], '/'),
preg_quote($this->_escape_char[1], '/'),
$this->_escape_char[0],
$this->_escape_char[1]
);
}
else
{
$preg_ec[0] = $preg_ec[1] = preg_quote($this->_escape_char, '/');
$preg_ec[2] = $preg_ec[3] = $this->_escape_char;
}
}
foreach ($this->_reserved_identifiers as $id)
{
if (strpos($item, '.'.$id) !== FALSE)
{
return preg_replace('/'.$preg_ec[0].'?([^'.$preg_ec[1].'\.]+)'.$preg_ec[1].'?\./i', $preg_ec[2].'$1'.$preg_ec[3].'.', $item);
}
}
return preg_replace('/'.$preg_ec[0].'?([^'.$preg_ec[1].'\.]+)'.$preg_ec[1].'?(\.)?/i', $preg_ec[2].'$1'.$preg_ec[3].'$2', $item);
}
// --------------------------------------------------------------------
/**
* Generate an insert string
*
* @param string the table upon which the query will be performed
* @param array an associative array data of key/values
* @return string
*/
public function insert_string($table, $data)
{
$fields = $values = array();
foreach ($data as $key => $val)
{
$fields[] = $this->escape_identifiers($key);
$values[] = $this->escape($val);
}
return $this->_insert($this->protect_identifiers($table, TRUE, NULL, FALSE), $fields, $values);
}
// --------------------------------------------------------------------
/**
* Insert statement
*
* Generates a platform-specific insert string from the supplied data
*
* @param string the table name
* @param array the insert keys
* @param array the insert values
* @return string
*/
protected function _insert($table, $keys, $values)
{
return 'INSERT INTO '.$table.' ('.implode(', ', $keys).') VALUES ('.implode(', ', $values).')';
}
// --------------------------------------------------------------------
/**
* Generate an update string
*
* @param string the table upon which the query will be performed
* @param array an associative array data of key/values
* @param mixed the "where" statement
* @return string
*/
public function update_string($table, $data, $where)
{
if (empty($where))
{
return FALSE;
}
$this->where($where);
$fields = array();
foreach ($data as $key => $val)
{
$fields[$this->protect_identifiers($key)] = $this->escape($val);
}
$sql = $this->_update($this->protect_identifiers($table, TRUE, NULL, FALSE), $fields);
$this->_reset_write();
return $sql;
}
// --------------------------------------------------------------------
/**
* Update statement
*
* Generates a platform-specific update string from the supplied data
*
* @param string the table name
* @param array the update data
* @return string
*/
protected function _update($table, $values)
{
foreach ($values as $key => $val)
{
$valstr[] = $key.' = '.$val;
}
return 'UPDATE '.$table.' SET '.implode(', ', $valstr)
.$this->_compile_wh('qb_where')
.$this->_compile_order_by()
.($this->qb_limit ? ' LIMIT '.$this->qb_limit : '');
}
// --------------------------------------------------------------------
/**
* Tests whether the string has an SQL operator
*
* @param string
* @return bool
*/
protected function _has_operator($str)
{
return (bool) preg_match('/(<|>|!|=|\sIS NULL|\sIS NOT NULL|\sEXISTS|\sBETWEEN|\sLIKE|\sIN\s*\(|\s)/i', trim($str));
}
// --------------------------------------------------------------------
/**
* Returns the SQL string operator
*
* @param string
* @return string
*/
protected function _get_operator($str)
{
static $_operators;
if (empty($_operators))
{
$_les = ($this->_like_escape_str !== '')
? '\s+'.preg_quote(trim(sprintf($this->_like_escape_str, $this->_like_escape_chr)), '/')
: '';
$_operators = array(
'\s*(?:<|>|!)?=\s*', // =, <=, >=, !=
'\s*<>?\s*', // <, <>
'\s*>\s*', // >
'\s+IS NULL', // IS NULL
'\s+IS NOT NULL', // IS NOT NULL
'\s+EXISTS\s*\(.*\)', // EXISTS(sql)
'\s+NOT EXISTS\s*\(.*\)', // NOT EXISTS(sql)
'\s+BETWEEN\s+', // BETWEEN value AND value
'\s+IN\s*\(.*\)', // IN(list)
'\s+NOT IN\s*\(.*\)', // NOT IN (list)
'\s+LIKE\s+\S.*('.$_les.')?', // LIKE 'expr'[ ESCAPE '%s']
'\s+NOT LIKE\s+\S.*('.$_les.')?' // NOT LIKE 'expr'[ ESCAPE '%s']
);
}
return preg_match('/'.implode('|', $_operators).'/i', $str, $match)
? $match[0] : FALSE;
}
// --------------------------------------------------------------------
/**
* Enables a native PHP function to be run, using a platform agnostic wrapper.
*
* @param string $function Function name
* @return mixed
*/
public function call_function($function)
{
$driver = ($this->dbdriver === 'postgre') ? 'pg_' : $this->dbdriver.'_';
if (FALSE === strpos($driver, $function))
{
$function = $driver.$function;
}
if ( ! function_exists($function))
{
return ($this->db_debug) ? $this->display_error('db_unsupported_function') : FALSE;
}
return (func_num_args() > 1)
? call_user_func_array($function, array_slice(func_get_args(), 1))
: call_user_func($function);
}
// --------------------------------------------------------------------
/**
* Set Cache Directory Path
*
* @param string the path to the cache directory
* @return void
*/
public function cache_set_path($path = '')
{
$this->cachedir = $path;
}
// --------------------------------------------------------------------
/**
* Enable Query Caching
*
* @return bool cache_on value
*/
public function cache_on()
{
return $this->cache_on = TRUE;
}
// --------------------------------------------------------------------
/**
* Disable Query Caching
*
* @return bool cache_on value
*/
public function cache_off()
{
return $this->cache_on = FALSE;
}
// --------------------------------------------------------------------
/**
* Delete the cache files associated with a particular URI
*
* @param string $segment_one = ''
* @param string $segment_two = ''
* @return bool
*/
public function cache_delete($segment_one = '', $segment_two = '')
{
return $this->_cache_init()
? $this->CACHE->delete($segment_one, $segment_two)
: FALSE;
}
// --------------------------------------------------------------------
/**
* Delete All cache files
*
* @return bool
*/
public function cache_delete_all()
{
return $this->_cache_init()
? $this->CACHE->delete_all()
: FALSE;
}
// --------------------------------------------------------------------
/**
* Initialize the Cache Class
*
* @return bool
*/
protected function _cache_init()
{
if ( ! class_exists('CI_DB_Cache', FALSE))
{
require_once(BASEPATH.'database/DB_cache.php');
}
elseif (is_object($this->CACHE))
{
return TRUE;
}
$this->CACHE = new CI_DB_Cache($this); // pass db object to support multiple db connections and returned db objects
return TRUE;
}
// --------------------------------------------------------------------
/**
* Close DB Connection
*
* @return void
*/
public function close()
{
if ($this->conn_id)
{
$this->_close();
$this->conn_id = FALSE;
}
}
// --------------------------------------------------------------------
/**
* Close DB Connection
*
* This method would be overridden by most of the drivers.
*
* @return void
*/
protected function _close()
{
$this->conn_id = FALSE;
}
// --------------------------------------------------------------------
/**
* Display an error message
*
* @param string the error message
* @param string any "swap" values
* @param bool whether to localize the message
* @return string sends the application/views/errors/error_db.php template
*/
public function display_error($error = '', $swap = '', $native = FALSE)
{
$LANG =& load_class('Lang', 'core');
$LANG->load('db');
$heading = $LANG->line('db_error_heading');
if ($native === TRUE)
{
$message = (array) $error;
}
else
{
$message = is_array($error) ? $error : array(str_replace('%s', $swap, $LANG->line($error)));
}
// Find the most likely culprit of the error by going through
// the backtrace until the source file is no longer in the
// database folder.
$trace = debug_backtrace();
foreach ($trace as $call)
{
if (isset($call['file'], $call['class']))
{
// We'll need this on Windows, as APPPATH and BASEPATH will always use forward slashes
if (DIRECTORY_SEPARATOR !== '/')
{
$call['file'] = str_replace('\\', '/', $call['file']);
}
if (strpos($call['file'], BASEPATH.'database') === FALSE && strpos($call['class'], 'Loader') === FALSE)
{
// Found it - use a relative path for safety
$message[] = 'Filename: '.str_replace(array(APPPATH, BASEPATH), '', $call['file']);
$message[] = 'Line Number: '.$call['line'];
break;
}
}
}
$error =& load_class('Exceptions', 'core');
echo $error->show_error($heading, $message, 'error_db');
exit(8); // EXIT_DATABASE
}
// --------------------------------------------------------------------
/**
* Protect Identifiers
*
* This function is used extensively by the Query Builder class, and by
* a couple functions in this class.
* It takes a column or table name (optionally with an alias) and inserts
* the table prefix onto it. Some logic is necessary in order to deal with
* column names that include the path. Consider a query like this:
*
* SELECT hostname.database.table.column AS c FROM hostname.database.table
*
* Or a query with aliasing:
*
* SELECT m.member_id, m.member_name FROM members AS m
*
* Since the column name can include up to four segments (host, DB, table, column)
* or also have an alias prefix, we need to do a bit of work to figure this out and
* insert the table prefix (if it exists) in the proper position, and escape only
* the correct identifiers.
*
* @param string
* @param bool
* @param mixed
* @param bool
* @return string
*/
public function protect_identifiers($item, $prefix_single = FALSE, $protect_identifiers = NULL, $field_exists = TRUE)
{
if ( ! is_bool($protect_identifiers))
{
$protect_identifiers = $this->_protect_identifiers;
}
if (is_array($item))
{
$escaped_array = array();
foreach ($item as $k => $v)
{
$escaped_array[$this->protect_identifiers($k)] = $this->protect_identifiers($v, $prefix_single, $protect_identifiers, $field_exists);
}
return $escaped_array;
}
// This is basically a bug fix for queries that use MAX, MIN, etc.
// If a parenthesis is found we know that we do not need to
// escape the data or add a prefix. There's probably a more graceful
// way to deal with this, but I'm not thinking of it -- Rick
//
// Added exception for single quotes as well, we don't want to alter
// literal strings. -- Narf
if (strcspn($item, "()'") !== strlen($item))
{
return $item;
}
// Convert tabs or multiple spaces into single spaces
$item = preg_replace('/\s+/', ' ', trim($item));
// If the item has an alias declaration we remove it and set it aside.
// Note: strripos() is used in order to support spaces in table names
if ($offset = strripos($item, ' AS '))
{
$alias = ($protect_identifiers)
? substr($item, $offset, 4).$this->escape_identifiers(substr($item, $offset + 4))
: substr($item, $offset);
$item = substr($item, 0, $offset);
}
elseif ($offset = strrpos($item, ' '))
{
$alias = ($protect_identifiers)
? ' '.$this->escape_identifiers(substr($item, $offset + 1))
: substr($item, $offset);
$item = substr($item, 0, $offset);
}
else
{
$alias = '';
}
// Break the string apart if it contains periods, then insert the table prefix
// in the correct location, assuming the period doesn't indicate that we're dealing
// with an alias. While we're at it, we will escape the components
if (strpos($item, '.') !== FALSE)
{
$parts = explode('.', $item);
// Does the first segment of the exploded item match
// one of the aliases previously identified? If so,
// we have nothing more to do other than escape the item
//
// NOTE: The ! empty() condition prevents this method
// from breaking when QB isn't enabled.
if ( ! empty($this->qb_aliased_tables) && in_array($parts[0], $this->qb_aliased_tables))
{
if ($protect_identifiers === TRUE)
{
foreach ($parts as $key => $val)
{
if ( ! in_array($val, $this->_reserved_identifiers))
{
$parts[$key] = $this->escape_identifiers($val);
}
}
$item = implode('.', $parts);
}
return $item.$alias;
}
// Is there a table prefix defined in the config file? If not, no need to do anything
if ($this->dbprefix !== '')
{
// We now add the table prefix based on some logic.
// Do we have 4 segments (hostname.database.table.column)?
// If so, we add the table prefix to the column name in the 3rd segment.
if (isset($parts[3]))
{
$i = 2;
}
// Do we have 3 segments (database.table.column)?
// If so, we add the table prefix to the column name in 2nd position
elseif (isset($parts[2]))
{
$i = 1;
}
// Do we have 2 segments (table.column)?
// If so, we add the table prefix to the column name in 1st segment
else
{
$i = 0;
}
// This flag is set when the supplied $item does not contain a field name.
// This can happen when this function is being called from a JOIN.
if ($field_exists === FALSE)
{
$i++;
}
// Verify table prefix and replace if necessary
if ($this->swap_pre !== '' && strpos($parts[$i], $this->swap_pre) === 0)
{
$parts[$i] = preg_replace('/^'.$this->swap_pre.'(\S+?)/', $this->dbprefix.'\\1', $parts[$i]);
}
// We only add the table prefix if it does not already exist
elseif (strpos($parts[$i], $this->dbprefix) !== 0)
{
$parts[$i] = $this->dbprefix.$parts[$i];
}
// Put the parts back together
$item = implode('.', $parts);
}
if ($protect_identifiers === TRUE)
{
$item = $this->escape_identifiers($item);
}
return $item.$alias;
}
// Is there a table prefix? If not, no need to insert it
if ($this->dbprefix !== '')
{
// Verify table prefix and replace if necessary
if ($this->swap_pre !== '' && strpos($item, $this->swap_pre) === 0)
{
$item = preg_replace('/^'.$this->swap_pre.'(\S+?)/', $this->dbprefix.'\\1', $item);
}
// Do we prefix an item with no segments?
elseif ($prefix_single === TRUE && strpos($item, $this->dbprefix) !== 0)
{
$item = $this->dbprefix.$item;
}
}
if ($protect_identifiers === TRUE && ! in_array($item, $this->_reserved_identifiers))
{
$item = $this->escape_identifiers($item);
}
return $item.$alias;
}
// --------------------------------------------------------------------
/**
* Dummy method that allows Query Builder class to be disabled
* and keep count_all() working.
*
* @return void
*/
protected function _reset_select()
{
}
}
| mit |
AhmedMohamedAbdelaal/start.net | Start.Net/Entities/Charge.cs | 1328 | using Newtonsoft.Json;
using System;
namespace Start.Net.Entities
{
public class Charge
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("object")]
public string Object { get; set; }
[JsonProperty("amount")]
public int Amount { get; set; }
[JsonProperty("currency")]
public string Currency { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("email")]
public string Email { get; set; }
[JsonProperty("ip")]
public string Ip { get; set; }
[JsonProperty("state")]
public string State { get; set; }
[JsonProperty("captured_amount")]
public int CapturedAmount { get; set; }
[JsonProperty("refunded_amount")]
public int RefundedAmount { get; set; }
[JsonProperty("failure_reason")]
public string FailureReason { get; set; }
[JsonProperty("failure_code")]
public string FailureCode { get; set; }
[JsonProperty("created_at")]
public DateTime CreatedAt { get; set; }
[JsonProperty("updated_at")]
public DateTime? UpdatedAt{ get; set; }
[JsonProperty("card")]
public CardSummary Card { get; set; }
}
}
| mit |
ignat-zakrevsky/surf | lib/surf/callbacks/pull_request_logger.rb | 751 | # frozen_string_literal: true
require 'surf/registry'
module Surf
class PullRequestLogger
extend Configurable
cattr_accessor(:pull_request_webhook_class) { Surf::Registry.pull_request_webhook_class }
def initialize(context)
@context = context
@webhook = find_webhook
end
def call
Surf.logger.info(pull_request_info)
end
private
attr_reader :context, :webhook
def find_webhook
self.class.pull_request_webhook_class.new(context.raw_body)
end
def pull_request_info
"#{webhook.repository.full_name}##{webhook.pull_request.number}" \
" was #{webhook.action} by #{webhook.sender_login}" \
", current state: #{webhook.pull_request.state}"
end
end
end
| mit |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.