repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
talosdigital/TDJobs
db/migrate/20150710204352_create_invitations.rb
173
class CreateInvitations < ActiveRecord::Migration def change create_table :invitations do |t| t.string :status t.timestamps null: false end end end
mit
TheDreamSanctuary/DreamPlus
main/java/com/thedreamsanctuary/main/java/dreamplus/commands/DreamTrailCommand.java
2060
package com.thedreamsanctuary.main.java.dreamplus.commands; import com.thedreamsanctuary.main.java.dreamplus.DreamPlus; import com.thedreamsanctuary.main.java.dreamplus.listener.DPListener; import static com.thedreamsanctuary.main.java.dreamplus.listener.DPListener.trails; import java.util.regex.Pattern; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; /** * @author Ajcool1050 */ public class DreamTrailCommand implements CommandExecutor { final DreamPlus dp; public DreamTrailCommand(DreamPlus dp) { this.dp = dp; } @Override public boolean onCommand(CommandSender sender, Command command, String string, String[] args) { if (sender instanceof Player) { Player player = (Player) sender; if (player.hasPermission("dreamplus.command.dtrail")) { if (args.length == 1) { if (!Pattern.matches("[a-zA-Z]+", args[0])) { if (args[0].contains(":")) { DPListener.addPlayerToMap(player, args[0], trails); } else { DPListener.addPlayerToMap(player, args[0], trails); } } else if (args[0].toLowerCase().equals("off")) DPListener.removePlayerFromMap(player, trails); else player.sendMessage(ChatColor.GOLD + "Usage: /dtrail [off]or[Block Id:Data]]"); } else player.sendMessage(ChatColor.GOLD + "Usage: /dtrail [off]or[Block Id:Data]"); } else player.sendMessage(ChatColor.GOLD + "You are not able to execute that command."); } else sender.sendMessage("Must be and ingame player to execute command."); return false; } }
mit
malteclasen/AutomatedTestDemo
AutomatedTestDemo.Tests/NunitTest.cs
297
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NUnit.Framework; namespace AutomatedTestDemo.Tests { [TestFixture] public class NunitTest { [Test] public void OneEqualsOne() { Assert.AreEqual(1,1); } } }
mit
rcarmo/pngcanvas
setuputils.py
466
import codecs import os.path import re def read(*parts): file_path = os.path.join(os.path.dirname(__file__), *parts) return codecs.open(file_path, 'r').read() def find_version(*parts): version_file = read(*parts) version_match = re.search(r'^__version__ = [\'"]([^\'"]*)[\'"]', version_file, re.M) if version_match: return version_match.group(1) raise RuntimeError('Unable to find version string.')
mit
z1c0/HUGO
public/colors.js
3608
'use strict'; const colors = [ '#993366', '#CC6699', '#FF99CC', '#FF0099', '#990066', '#CC3399', '#FF66CC', '#CC0099', '#FF33CC', '#FF00CC', '#FF00FF', '#CC00CC', '#FF33FF', '#990099', '#CC33CC', '#FF66FF', '#660066', '#993399', '#CC66CC', '#FF99FF', '#330033', '#663366', '#996699', '#CC99CC', '#FFCCFF', '#CC00FF', '#9900CC', '#CC33FF', '#660099', '#9933CC', '#CC66FF', '#9900FF', '#330066', '#663399', '#9966CC', '#CC99FF', '#6600CC', '#9933FF', '#6600FF', '#330099', '#6633CC', '#9966FF', '#3300CC', '#6633FF', '#3300FF', '#0000FF', '#0000CC', '#000099', '#000066', '#000033', '#3333FF', '#3333CC', '#333399', '#333366', '#6666FF', '#6666CC', '#666699', '#9999FF', '#9999CC', '#CCCCFF', '#0033FF', '#0033CC', '#3366FF', '#003399', '#3366CC', '#6699FF', '#0066FF', '#0066CC', '#3399FF', '#003366', '#336699', '#6699CC', '#99CCFF', '#0099FF', '#006699', '#3399CC', '#66CCFF', '#0099CC', '#33CCFF', '#00CCFF', '#00FFFF', '#00CCCC', '#009999', '#006666', '#003333', '#33FFFF', '#33CCCC', '#339999', '#336666', '#66FFFF', '#66CCCC', '#669999', '#99FFFF', '#99CCCC', '#CCFFFF', '#00FFCC', '#00CC99', '#33FFCC', '#009966', '#33CC99', '#66FFCC', '#00FF99', '#006633', '#339966', '#66CC99', '#99FFCC', '#00CC66', '#33FF99', '#00FF66', '#009933', '#33CC66', '#66FF99', '#00CC33', '#33FF66', '#00FF33', '#00FF00', '#00CC00', '#009900', '#006600', '#003300', '#33FF33', '#33CC33', '#339933', '#336633', '#66FF66', '#66CC66', '#669966', '#99FF99', '#99CC99', '#CCFFCC', '#33FF00', '#33CC00', '#66FF33', '#339900', '#66CC33', '#99FF66', '#66FF00', '#66CC00', '#99FF33', '#336600', '#669933', '#99CC66', '#CCFF99', '#99FF00', '#669900', '#99CC33', '#CCFF66', '#99CC00', '#CCFF33', '#CCFF00', '#FFFF00', '#CCCC00', '#999900', '#666600', '#333300', '#FFFF33', '#CCCC33', '#999933', '#666633', '#FFFF66', '#CCCC66', '#999966', '#FFFF99', '#CCCC99', '#FFFFCC', '#FFCC00', '#CC9900', '#FFCC33', '#996600', '#CC9933', '#FFCC66', '#FF9900', '#663300', '#996633', '#CC9966', '#FFCC99', '#CC6600', '#FF9933', '#FF6600', '#993300', '#CC6633', '#FF9966', '#CC3300', '#FF6633', '#FF3300', '#FF0000', '#CC0000', '#990000', '#660000', '#330000', '#FF3333', '#CC3333', '#993333', '#663333', '#FF6666', '#CC6666', '#996666', '#FF9999', '#CC9999', '#FFCCCC', '#FF0033', '#CC0033', '#FF3366', '#990033', '#CC3366', '#FF6699', '#FF0066', '#CC0066', '#FF3399', '#660033', '#FFFFFF', '#CCCCCC', '#999999', '#666666', '#333333', '#000000' ]; function createColorChooser(elementName, callback, options) { var canvas = document.getElementById(elementName); var ctx = canvas.getContext('2d'); options = options || {}; if (options.maximize) { canvas.style.width='100%'; canvas.style.height='100%'; canvas.width = canvas.offsetWidth; canvas.height = canvas.offsetHeight; } const columns = 18; const rows = 12; const w = canvas.width / columns; const h = canvas.height / rows; for (var y = 0; y < rows; y++) { for (var x = 0; x < columns; x++) { ctx.fillStyle = colors[x + y * columns]; ctx.fillRect(x * w, y * h, w, h); } } $(canvas).click(function(e) { var rgb = ctx.getImageData(e.offsetX, e.offsetY, 1, 1).data; callback(rgb); }); }
mit
thatguystone/paratec
src/opts_test.cpp
1909
/** * @author Andrew Stone <[email protected]> * @copyright 2014 Andrew Stone * * This file is part of paratec and is released under the MIT License: * http://opensource.org/licenses/MIT */ #include <limits> #include <stdlib.h> #include "opts.hpp" #include "util_test.hpp" namespace pt { static struct { std::vector<const char *> args_; uint cnt; } _verbose[] = { { .args_ = { "paratec" }, .cnt = 0, }, { .args_ = { "paratec", "-vvv" }, .cnt = 2, }, { .args_ = { "paratec", "-v", "-v", "-v" }, .cnt = 3, }, }; TESTV(optsVerbose, _verbose) { Opts opts; opts.parse(_t->args_); pt_eq(opts.verbose_.get(), _t->cnt); } TEST(optsHelp, PTEXIT(1)) { Opts opts; opts.parse({ "paratec", "-h" }); } TEST(optsUnknown, PTEXIT(1)) { Opts opts; opts.parse({ "paratec", "--girls-just-want-to-have-fun" }); } TEST(optsFilter) { setenv("PTFILTER", "0", 1); Opts opts; opts.parse({ "paratec", "--filter=1,-2", "-f", "3,4", "-f", "5" }); // pt::eq(opts.filter_.filts_, std::vector<FilterOpt::F>({})); } TEST(optsJobs) { Opts opts; opts.parse({ "paratec", "--jobs", "4" }); pt_eq(opts.jobs_.get(), (uint)4); } TEST(optsPort) { Opts opts; opts.parse({ "paratec", "--port", "3333" }); pt_eq(opts.port_.get(), (uint16_t)3333); } TEST(optsPortLimits, PTEXIT(1)) { Opts opts; opts.parse({ "paratec", "--port", "-1" }); } TEST(optsPortError, PTEXIT(1)) { Opts opts; opts.parse({ "paratec", "--port", "abcd" }); } TEST(optsTimeout) { Opts opts; opts.parse({ "paratec", "-t", "3.3" }); pt_eq(opts.timeout_.get(), 3.3); } TEST(optsTimeoutInvalid, PTEXIT(1)) { Opts opts; opts.parse({ "paratec", "-t", "merp" }); } TEST(optsTimeoutError, PTEXIT(1)) { Opts opts; opts.parse({ "paratec", "-t", "-1" }); } TEST(optsTimeoutLimits, PTEXIT(1)) { Opts opts; auto max = "99" + std::to_string(std::numeric_limits<double>::max()); opts.parse({ "paratec", "-t", max.c_str() }); } }
mit
xs-embedded-llc/l2dbus
test/utils/traverse.lua
4608
------------------------------------------------------------------------------- -- This module implements a function that traverses all live objects. -- You can implement your own function to pass as a parameter of traverse -- and give you the information you want. As an example we have implemented -- countreferences and findallpaths -- -- Alexandra Barros - 2006.03.15 ------------------------------------------------------------------------------- module("traverse", package.seeall) local List = {} function List.new () return {first = 0, last = -1} end function List.push (list, value) local last = list.last + 1 list.last = last list[last] = value end function List.pop (list) local first = list.first if first > list.last then error("list is empty") end local value = list[first] list[first] = nil list.first = first + 1 return value end function List.isempty (list) return list.first > list.last end -- Counts all references for a given object function countreferences(value) local count = -1 local f = function(from, to, how, v) if to == value then count = count + 1 end end traverse({edge=f}, {count, f}) return count end -- Main function -- 'funcs' is a table that contains a funcation for every lua type and also the -- function edge edge (traverseedge). function traverse(funcs, ignoreobjs) -- The keys of the marked table are the objetcts (for example, table: 00442330). -- The value of each key is true if the object has been found and false -- otherwise. local env = {marked = {}, list=List.new(), funcs=funcs} if ignoreobjs then for i=1, #ignoreobjs do env.marked[ignoreobjs[i]] = true end end env.marked["traverse"] = true env.marked[traverse] = true -- marks and inserts on the list edge(env, nil, "_G", "isname", nil) edge(env, nil, _G, "value", "_G") -- traverses the active thread -- inserts the local variables -- interates over the function on the stack, starting from the one that -- called traverse for i=2, math.huge do local info = debug.getinfo(i, "f") if not info then break end for j=1, math.huge do local n, v = debug.getlocal(i, j) if not n then break end edge(env, nil, n, "isname", nil) edge(env, nil, v, "local", n) end end while not List.isempty(env.list) do local obj = List.pop(env.list) local t = type(obj) _M["traverse" .. t](env, obj) end end function traversetable(env, obj) local f = env.funcs.table if f then f(obj) end for key, value in pairs(obj) do edge(env, obj, key, "key", nil) edge(env, obj, value, "value", key) end local mtable = debug.getmetatable(obj) if mtable then edge(env, obj, mtable, "ismetatable", nil) end end function traversestring(env, obj) local f = env.funcs.string if f then f(obj) end end function traverseuserdata(env, obj) local f = env.funcs.userdata if f then f(obj) end local mtable = debug.getmetatable(obj) if mtable then edge(env, obj, mtable, "ismetatable", nil) end local fenv = debug.getfenv(obj) if fenv then edge(env, obj, fenv, "environment", nil) end end function traversefunction(env, obj) local f = env.funcs.func if f then f(obj) end -- gets the upvalues local i = 1 while true do local n, v = debug.getupvalue(obj, i) if not n then break end -- when there is no upvalues edge(env, obj, n, "isname", nil) edge(env, obj, v, "upvalue", n) i = i + 1 end local fenv = debug.getfenv(obj) edge(env, obj, fenv, "environment", nil) end function traversethread(env, t) local f = env.funcs.thread if f then f(t) end for i=1, math.huge do local info = debug.getinfo(t, i, "f") if not info then break end for j=1, math.huge do local n, v = debug.getlocal(t, i , j) if not n then break end print(n, v) edge(env, nil, n, "isname", nil) edge(env, nil, v, "local", n) end end local fenv = debug.getfenv(t) edge(env, t, fenv, "environment", nil) end -- 'how' is a string that identifies the content of 'to' and 'value': -- if 'how' is "key", then 'to' is a key and 'name' is nil. -- if 'how' is "value", then 'to' is an object and 'name' is the name of the -- key. function edge(env, from, to, how, name) local t = type(to) if to and (t~="boolean") and (t~="number") and (t~="new") then -- If the destination object has not been found yet if not env.marked[to] then env.marked[to] = true List.push(env.list, to) -- puts on the list to be traversed end local f = env.funcs.edge if f then f(from, to, how, name) end end end return _M;
mit
operator1/op1
op1/src/main/java/com/op1/iff/IffReader.java
2772
package com.op1.iff; import com.op1.iff.types.*; import java.io.Closeable; import java.io.DataInputStream; import java.io.EOFException; import java.io.IOException; public class IffReader implements Closeable { private final DataInputStream dataInputStream; public IffReader(DataInputStream dataInputStream) { this.dataInputStream = dataInputStream; } public SignedChar readSignedChar() throws IOException { return new SignedChar(dataInputStream.readByte()); } public UnsignedChar readUnsignedChar() throws IOException { return new UnsignedChar(dataInputStream.readByte()); } public SignedShort readSignedShort() throws IOException { return new SignedShort(readBytes(2)); } public UnsignedShort readUnsignedShort() throws IOException { return new UnsignedShort(readBytes(2)); } public SignedLong readSignedLong() throws IOException { return new SignedLong(readBytes(4)); } public UnsignedLong readUnsignedLong() throws IOException { return new UnsignedLong(readBytes(4)); } public Extended readExtended() throws IOException { return new Extended(readBytes(10)); } public PString readPString() throws IOException { // The first byte contains a count of the text textBytes that follow. final int numTextBytes = dataInputStream.readUnsignedByte(); // Read the text bytes. final byte[] textBytes = readBytes(numTextBytes); // The total number of textBytes should be even. A pad byte may have been added to satisfy this rule. int numPadBytes = (numTextBytes + 1) % 2; byte[] pStringBytes = new byte[1 + numTextBytes + numPadBytes]; pStringBytes[0] = (byte) numTextBytes; System.arraycopy(textBytes, 0, pStringBytes, 1, textBytes.length); if (numPadBytes == 1) { pStringBytes[pStringBytes.length - 1] = dataInputStream.readByte(); } return new PString(pStringBytes); } public ID readID() throws IOException { return new ID(readBytes(4)); } public OSType readOSType() throws IOException { return new OSType(readBytes(4)); } public byte[] readBytes(int numBytesToRead) throws IOException { final byte[] bytes = new byte[numBytesToRead]; final int numRead = dataInputStream.read(bytes); if (numRead != numBytesToRead) { throw new EOFException(String.format("numBytesToRead: %s, numRead: %s", numBytesToRead, numRead)); } return bytes; } public byte readByte() throws IOException { return dataInputStream.readByte(); } public void close() throws IOException { dataInputStream.close(); } }
mit
aanaedu/clementinejs-mod
app/routes/index.js
3347
'use strict'; var path = process.cwd(); var userController = require(path + '/app/controllers/userController.server.js'); var User = require(path + '/app/models/users.js'); module.exports = function (app, passport) { var userCtrl = new userController(); function isLoggedIn (req, res, next) { if (req.isAuthenticated()) { return next(); } // otherwise redirect to login res.redirect('/login'); } function isLoggedInAsAdmin (req, res, next) { if (req.isAuthenticated()) { if (req.user.local.isAdmin || req.user.google.isAdmin) { return next(); } } // otherwise redirect to index req.flash('error_msg', 'Unauthorised access'); res.redirect('/'); } app.route('/') .get(function (req, res) { res.render('index', { title:'Clementine.js'}); }); app.route('/login') .get(function (req, res) { res.render('login', { title:'Account Login'}); }) .post(passport.authenticate('local', {successRedirect: '/profile', failureRedirect: '/login', failureFlash: true }), function(req, res) { // If this function gets called, authentication was successful. // `req.user` contains the authenticated user. req.flash('success_msg', 'You have been successfully logged in'); res.redirect('/profile'); } ); app.route('/register') .get(function (req, res) { res.render('register', { title:'Register'}); }) .post(function (req, res) { var name = req.body.name; var username = req.body.username; var email = req.body.email; var password = req.body.password; // Validation req.checkBody('name', 'Name is required').notEmpty(); req.checkBody('email', 'Email is required').notEmpty(); req.checkBody('email', 'Email is not valid').isEmail(); req.checkBody('username', 'Username is required').notEmpty(); req.checkBody('password', 'Password is required').notEmpty(); req.checkBody('password2', 'Passwords do not match').equals(req.body.password); var errors = req.validationErrors(); if (errors) { res.render('register', { errors: errors }); } else { var newUser = new User(); newUser.local.name = name; newUser.local.username = username; newUser.local.email = email; newUser.local.password = password; newUser.local.isAdmin = false; userCtrl.createUser(newUser, function (err) { if (err) throw err; req.flash('success_msg', 'You are registered and can now login'); res.redirect('/login'); }); } }); app.route('/logout') .get(function (req, res) { req.logout(); res.redirect('/login'); }); app.route('/profile') .get(isLoggedIn, function (req, res) { res.render('profile', {title: 'User Profile', user: req.user }); }); app.route('/auth/google') .get(passport.authenticate('google', { scope : ['profile', 'email'] })); app.route('/auth/google/callback') .get(passport.authenticate('google', { successRedirect: '/profile', failureRedirect: '/login' })); app.route('/admin') .get(isLoggedInAsAdmin, function(req, res) { res.render('dashboard', { title: 'Dashboard' }); }); };
mit
elifesciences/builder
src/buildercore/cloudformation.py
12323
"""module concerns itself with the creation, updating and deleting of Cloudformation template instances. see `trop.py` for the *generation* of Cloudformation templates.""" from collections import namedtuple from contextlib import contextmanager import logging import json import os from pprint import pformat from functools import partial import backoff import botocore from . import config, core, keypair, trop from .utils import call_while, ensure LOG = logging.getLogger(__name__) def render_template(context): "generates an instance of a Cloudformation template using the given `context`." msg = 'could not render a CloudFormation template for %r' % context['project_name'] ensure('aws' in context, msg, ValueError) return trop.render(context) # --- def _give_up_backoff(e): return e.response['Error']['Code'] != 'Throttling' def _log_backoff(event): LOG.warning("Backing off in validating project %s", event['args'][0]) @backoff.on_exception(backoff.expo, botocore.exceptions.ClientError, on_backoff=_log_backoff, giveup=_give_up_backoff, max_time=30) def validate_template(rendered_template): "remote cloudformation template checks." if json.loads(rendered_template) == EMPTY_TEMPLATE: # empty templates are technically invalid, but they don't interact with CloudFormation at all return conn = core.boto_client('cloudformation', region='us-east-1') return conn.validate_template(TemplateBody=rendered_template) # --- class CloudFormationDelta(namedtuple('Delta', ['plus', 'edit', 'minus'])): """represents a delta between and old and new CloudFormation generated template, showing which resources are being added, updated, or removed Extends the namedtuple-generated class to add custom methods.""" @property def non_empty(self): return any([ self.plus['Resources'], self.plus['Outputs'], self.plus['Parameters'], self.edit['Resources'], self.edit['Outputs'], self.minus['Resources'], self.minus['Outputs'], self.minus['Parameters'], ]) _empty_cloudformation_dictionary = {'Resources': {}, 'Outputs': {}, 'Parameters': {}} CloudFormationDelta.__new__.__defaults__ = (_empty_cloudformation_dictionary, _empty_cloudformation_dictionary, _empty_cloudformation_dictionary) EMPTY_TEMPLATE = {'Resources': {}} def _noop(): pass @contextmanager def stack_creation(stackname, on_start=_noop, on_error=_noop): try: on_start() yield except StackTakingALongTimeToComplete as err: LOG.info("Stack taking a long time to complete: %s", err) raise except botocore.exceptions.ClientError as err: if err.response['Error']['Code'] == 'AlreadyExistsException': LOG.debug(err) return LOG.exception("unhandled boto ClientError attempting to create stack", extra={'stackname': stackname, 'response': err.response}) on_error() raise except BaseException: LOG.exception("unhandled exception attempting to create stack", extra={'stackname': stackname}) on_error() raise # todo: rename. nothing is being bootstrapped here. def bootstrap(stackname, context): "called by `bootstrap.create_stack` to generate a cloudformation template." parameters = [] on_start = _noop on_error = _noop if context['ec2']: parameters.append({'ParameterKey': 'KeyName', 'ParameterValue': stackname}) on_start = lambda: keypair.create_keypair(stackname) on_error = lambda: keypair.delete_keypair(stackname) stack_body = open(core.stack_path(stackname), 'r').read() if json.loads(stack_body) == EMPTY_TEMPLATE: LOG.warning("empty template: %s" % (core.stack_path(stackname),)) return if core.stack_is_active(stackname): LOG.info("stack exists") # avoid `on_start` handler return True with stack_creation(stackname, on_start=on_start, on_error=on_error): conn = core.boto_conn(stackname, 'cloudformation') # http://boto3.readthedocs.io/en/latest/reference/services/cloudformation.html#CloudFormation.ServiceResource.create_stack conn.create_stack(StackName=stackname, TemplateBody=stack_body, Parameters=parameters) _wait_until_in_progress(stackname) class StackTakingALongTimeToComplete(RuntimeError): pass def _wait_until_in_progress(stackname): def is_updating(stackname): stack_status = core.describe_stack(stackname).stack_status LOG.info("Stack status: %s", stack_status) return stack_status in ['CREATE_IN_PROGRESS'] call_while( partial(is_updating, stackname), timeout=7200, update_msg='Waiting for CloudFormation to finish creating stack ...', exception_class=StackTakingALongTimeToComplete ) final_stack = core.describe_stack(stackname) # NOTE: stack.events.all|filter|limit can take 5+ seconds to complete regardless of events returned events = [(e.resource_status, e.resource_status_reason) for e in final_stack.events.all()] ensure(final_stack.stack_status in core.ACTIVE_CFN_STATUS, "Failed to create stack: %s.\nEvents: %s" % (final_stack.stack_status, pformat(events))) def read_template(stackname): "returns the contents of a cloudformation template as a python data structure" output_fname = os.path.join(config.STACK_DIR, stackname + ".json") return json.load(open(output_fname, 'r')) def outputs_map(stackname): """returns a map of a stack's 'Output' keys to their values. performs a boto API call.""" data = core.describe_stack(stackname).meta.data # boto3 if not 'Outputs' in data: return {} return {o['OutputKey']: o.get('OutputValue') for o in data['Outputs']} def template_outputs_map(stackname): """returns a map of a stack template's 'Output' keys to their values. requires a stack to exist on the filesystem.""" stack = json.load(open(core.stack_path(stackname), 'r')) output_map = stack.get('Outputs', []) return {output_key: output['Value'] for output_key, output in output_map.items()} def template_using_elb_v1(stackname): "returns `True` if the stack template file is using an ELB v1 (vs an ALB v2)" return trop.ELB_TITLE in template_outputs_map(stackname) def read_output(stackname, key): """finds a literal `Output` from a cloudformation template matching given `key`. fails hard if expected key not found, or too many keys found. performs a boto API call.""" data = core.describe_stack(stackname).meta.data # boto3 ensure('Outputs' in data, "Outputs missing: %s" % data) selected_outputs = [o for o in data['Outputs'] if o['OutputKey'] == key] ensure(selected_outputs, "No outputs found for key %r" % (key,)) ensure(len(selected_outputs) == 1, "Too many outputs selected for key %r: %s" % (key, selected_outputs)) ensure('OutputValue' in selected_outputs[0], "Badly formed Output for key %r: %s" % (key, selected_outputs[0])) return selected_outputs[0]['OutputValue'] def apply_delta(template, delta): for component in delta.plus: ensure(component in ["Resources", "Outputs", "Parameters"], "Template component %s not recognized" % component) data = template.get(component, {}) data.update(delta.plus[component]) template[component] = data for component in delta.edit: ensure(component in ["Resources", "Outputs"], "Template component %s not recognized" % component) data = template.get(component, {}) data.update(delta.edit[component]) template[component] = data for component in delta.minus: ensure(component in ["Resources", "Outputs", "Parameters"], "Template component %s not recognized" % component) for title in delta.minus[component]: del template[component][title] def _merge_delta(stackname, delta): """Merges the new resources in delta in the local copy of the Cloudformation template""" template = read_template(stackname) apply_delta(template, delta) # TODO: possibly pre-write the cloudformation template # the source of truth can always be redownloaded from the CloudFormation API write_template(stackname, json.dumps(template)) return template def write_template(stackname, contents): "writes a json version of the python cloudformation template to the stacks directory" output_fname = os.path.join(config.STACK_DIR, stackname + ".json") with open(output_fname, 'w') as fp: fp.write(contents) return output_fname def update_template(stackname, delta): if delta.non_empty: new_template = _merge_delta(stackname, delta) _update_template(stackname, new_template) else: # attempting to apply an empty change set would result in an error LOG.info("Nothing to update on CloudFormation") def _update_template(stackname, template): parameters = [] pdata = core.project_data_for_stackname(stackname) if pdata['aws']['ec2']: parameters.append({'ParameterKey': 'KeyName', 'ParameterValue': stackname}) try: conn = core.describe_stack(stackname) print(json.dumps(template, indent=4)) conn.update(TemplateBody=json.dumps(template), Parameters=parameters) except botocore.exceptions.ClientError as ex: if ex.response['Error']['Message'] == 'No updates are to be performed.': LOG.info(str(ex), extra={'response': ex.response}) return raise def stack_is_updating(): return not core.stack_is(stackname, ['UPDATE_COMPLETE'], terminal_states=['UPDATE_ROLLBACK_COMPLETE']) waiting = "waiting for template of %s to be updated" % stackname done = "template of %s is in state UPDATE_COMPLETE" % stackname call_while(stack_is_updating, interval=2, timeout=7200, update_msg=waiting, done_msg=done) def destroy(stackname, context): try: core.describe_stack(stackname).delete() def is_deleting(stackname): try: return core.describe_stack(stackname).stack_status in ['DELETE_IN_PROGRESS'] except botocore.exceptions.ClientError as err: if err.response['Error']['Message'].endswith('does not exist'): return False raise # not sure what happened, but we're not handling it here. die. call_while(partial(is_deleting, stackname), timeout=3600, update_msg='Waiting for CloudFormation to finish deleting stack ...') _delete_stack_file(stackname) keypair.delete_keypair(stackname) # deletes the keypair wherever it can find it (locally, remotely) except botocore.exceptions.ClientError as ex: msg = "[%s: %s] %s (request-id: %s)" meta = ex.response['ResponseMetadata'] err = ex.response['Error'] # ll: [400: ValidationError] No updates are to be performed (request-id: dc28fd8f-4456-11e8-8851-d9346a742012) if "No updates are to be performed" in err['Message']: LOG.info("Stack %s does not need updates on CloudFormation", stackname) return # ClientError(u'An error occurred (ValidationError) when calling the DescribeStacks operation: Stack with id basebox--1234 does not exist',) # e.operation_name == 'DescribeStacks' # e.response['Error'] == {'Message': 'Stack with id basebox--1234 does not exist', 'Code': 'ValidationError', 'Type': 'Sender'} if ex.operation_name == 'DescribeStacks' and "does not exist" in err['Message']: LOG.info("Stack %s does not exist on CloudFormation", stackname) return LOG.exception(msg, meta['HTTPStatusCode'], err['Code'], err['Message'], meta['RequestId'], extra={'response': ex.response}) # ll: ClientError: An error occurred (ValidationError) when calling the DeleteStack operation: Stack [arn:aws:cloudformation:us-east-1:512686554592:stack/elife-bot--prod/a0b1af 60-793f-11e8-bd5a-5044763dbb7b] cannot be deleted while in status UPDATE_COMPLETE_CLEANUP_IN_PROGRESS raise def _delete_stack_file(stackname): path = os.path.join(config.STACK_DIR, stackname + ".json") if os.path.exists(path): os.unlink(path)
mit
alpsayin/radiotftp
doc/html/search/all_69.js
2731
var searchData= [ ['idle_5fflag',['idle_flag',['../radiotftp_8c.html#a02fecce62db76d446cceec8d87e330f9',1,'radiotftp.c']]], ['info',['info',['../structdev.html#a17b6b9e15213b3ba2719406193446c8a',1,'dev']]], ['initfcs',['INITFCS',['../ax25_8c.html#a60045958d81758eaafdc718a7d34e848',1,'ax25.c']]], ['io',['io',['../radiotftp_8c.html#a1a64ce69b7c519a04d2364a319e22769',1,'radiotftp.c']]], ['io_5fdriven',['IO_DRIVEN',['../radiotftp_8c.html#a5fab3ee704f99a74b636d2111747651f',1,'radiotftp.c']]], ['io_5fflag',['io_flag',['../radiotftp_8c.html#a4506902b6476e2c20a3cf30b0144443f',1,'radiotftp.c']]], ['ipv6_5fdestination_5flength',['IPV6_DESTINATION_LENGTH',['../udp__ip_8h.html#ac3fb8830c2af868429777020a6f53d46',1,'udp_ip.h']]], ['ipv6_5fdestination_5foffset',['IPV6_DESTINATION_OFFSET',['../udp__ip_8h.html#aa46f37c0ac6c99ff9f494b44252a0ce8',1,'udp_ip.h']]], ['ipv6_5fflow_5flabel_5flength',['IPV6_FLOW_LABEL_LENGTH',['../udp__ip_8h.html#a2bf089bc2b4b5482f70205b1a573247e',1,'udp_ip.h']]], ['ipv6_5fflow_5flabel_5foffset',['IPV6_FLOW_LABEL_OFFSET',['../udp__ip_8h.html#ab53df373a3682a6f27f4dff25eb4424d',1,'udp_ip.h']]], ['ipv6_5fhop_5flimit',['IPV6_HOP_LIMIT',['../udp__ip_8h.html#a15495e9c3d657b161f8c69727aee45e8',1,'udp_ip.h']]], ['ipv6_5fhop_5flimit_5flength',['IPV6_HOP_LIMIT_LENGTH',['../udp__ip_8h.html#a89f8f49c3c5f0e5370066e93e627ee69',1,'udp_ip.h']]], ['ipv6_5fhop_5flimit_5foffset',['IPV6_HOP_LIMIT_OFFSET',['../udp__ip_8h.html#a3b7bcce93982609482b18d1349341a97',1,'udp_ip.h']]], ['ipv6_5fnext_5fheader_5flength',['IPV6_NEXT_HEADER_LENGTH',['../udp__ip_8h.html#a1c33db587f6b5baa085146a822933bcc',1,'udp_ip.h']]], ['ipv6_5fnext_5fheader_5foffset',['IPV6_NEXT_HEADER_OFFSET',['../udp__ip_8h.html#ad635006084bf948852bda05c35dade6b',1,'udp_ip.h']]], ['ipv6_5fpayload_5flength_5flength',['IPV6_PAYLOAD_LENGTH_LENGTH',['../udp__ip_8h.html#a21983894fc606d02dd7907fff3be25a9',1,'udp_ip.h']]], ['ipv6_5fpayload_5flength_5foffset',['IPV6_PAYLOAD_LENGTH_OFFSET',['../udp__ip_8h.html#a63051ff430a55d099184c3fb90bc4b2c',1,'udp_ip.h']]], ['ipv6_5fpayload_5foffset',['IPV6_PAYLOAD_OFFSET',['../udp__ip_8h.html#a0d010530a42a8c6b3a96ab4624eb6ca7',1,'udp_ip.h']]], ['ipv6_5fsource_5flength',['IPV6_SOURCE_LENGTH',['../udp__ip_8h.html#a577d35587e3a7fc1ddd97cf6990cc296',1,'udp_ip.h']]], ['ipv6_5fsource_5foffset',['IPV6_SOURCE_OFFSET',['../udp__ip_8h.html#a7a66c69d8d5055b563a1d76a2d256dc3',1,'udp_ip.h']]], ['ipv6_5fversion_5fpriority_5flength',['IPV6_VERSION_PRIORITY_LENGTH',['../udp__ip_8h.html#a1c6b75dc6cdd1b4de1d7fde309c13dca',1,'udp_ip.h']]], ['ipv6_5fversion_5fpriority_5foffset',['IPV6_VERSION_PRIORITY_OFFSET',['../udp__ip_8h.html#a296d26ba5028b743cb9c21eb6e5d0a8e',1,'udp_ip.h']]] ];
mit
andrewgremlich/presence-keeper
pk_static_files_server/app/js/util/DataControl.js
369
class DataControl { constructor() { this.appData updateData() } updateData() { this.appData = fetcherama() } fetcherama() { lib.fetch(`http://localhost:8080/api/class/getNearbyClasses/${coor.long}/${coor.lat}`, opt, data => { if (data.success === true) { return data.classes } }) } } export default DataControl
mit
marvinpinto/charlesbot-rundeck
tests/test_lock_unlock_rundeck_job.py
2258
import asynctest from asynctest.mock import patch from asynctest.mock import call from charlesbot_rundeck.rundeck_job import RundeckJob class TestLockUnlockRundeckJob(asynctest.TestCase): def setUp(self): patcher1 = patch('charlesbot_rundeck.rundeck_lock.RundeckLock.seed_job_list') # NOQA self.addCleanup(patcher1.stop) self.mock_seed_job_list = patcher1.start() patcher2 = patch('charlesbot_rundeck.rundeck_lock.http_post_request') self.addCleanup(patcher2.stop) self.mock_http_post_request = patcher2.start() from charlesbot_rundeck.rundeck_lock import RundeckLock self.rd_lock = RundeckLock("token", "url", "channel", []) self.rd_job = RundeckJob(execution_enabled=False, href="job.com") self.headers = { "Accept": "application/json", "X-Rundeck-Auth-Token": "token", } def test_lock_invalid_response(self): self.mock_http_post_request.side_effect = [""] yield from self.rd_lock.lock_or_unlock_rundeck_job(self.rd_job, True) calls = [ call("job.com/execution/disable", self.headers) ] self.assertFalse(self.rd_job.execution_enabled) self.assertEqual(self.mock_http_post_request.mock_calls, calls) def test_lock_valid_response(self): self.mock_http_post_request.side_effect = ["200"] yield from self.rd_lock.lock_or_unlock_rundeck_job(self.rd_job, True) calls = [ call("job.com/execution/disable", self.headers) ] self.assertTrue(self.rd_job.execution_enabled) self.assertEqual(self.mock_http_post_request.mock_calls, calls) def test_unlock_valid_response(self): self.rd_job.execution_enabled = True self.mock_http_post_request.side_effect = ["200"] yield from self.rd_lock.lock_or_unlock_rundeck_job(self.rd_job, False) calls = [ call("job.com/execution/enable", self.headers) ] self.assertFalse(self.rd_job.execution_enabled) self.assertEqual(self.mock_http_post_request.mock_calls, calls)
mit
eliezedeck/goweb
validation/schemas.go
1391
package validation import ( "fmt" "log" "strings" "github.com/xeipuuv/gojsonschema" ) var schemaCache map[string]*gojsonschema.Schema func init() { schemaCache = make(map[string]*gojsonschema.Schema) } // LoadSchema loads a JSON Schema file from `path` and assigns it to the `schemaid`. // Note that any error here is fatal. func LoadSchema(path, schemaid string) { var loader gojsonschema.JSONLoader loader = gojsonschema.NewReferenceLoader(path) schema, err := gojsonschema.NewSchema(loader) if err != nil { log.Fatalf("Failed to load Schema for '%s': %s", schemaid, err) } schemaCache[schemaid] = schema log.Printf("Loaded Schema '%s'", schemaid) } // Validate validates `rawdata` using the cached `schemaid` and returns a // user-friendly error message (as a string) in case of any validation error func Validate(schemaid string, rawdata interface{}) (bool, string) { schema, ok := schemaCache[schemaid] if !ok { return false, "Schema not found" } jloader := gojsonschema.NewGoLoader(rawdata) result, err := schema.Validate(jloader) if err != nil { return false, "Validation error" } if result.Valid() { return true, "" } firsterror := result.Errors()[0] return false, formatValidationError(firsterror) } func formatValidationError(e gojsonschema.ResultError) string { return fmt.Sprintf("%s: %s", strings.Title(e.Field()), e.Description()) }
mit
madgik/exareme
Exareme-Docker/files/root/exareme/convert-csv-dataset-to-db.py
13753
#!/usr/bin/python3 # -*- coding: utf-8 -*- """ This script creates multiple dbs for each pathology folder containing a dataset csv file and a metadata json file. """ import csv import json import os import sqlite3 from argparse import ArgumentParser MAX_ROWS_TO_INSERT_INTO_SQL = 100 # This metadata dictionary contains only code and sqltype so that processing will be faster # It also includes the subjectcode def createMetadataDictionary(CDEsMetadataPath): CDEsMetadata = open(CDEsMetadataPath, "r", encoding="utf-8") metadataJSON = json.load(CDEsMetadata) metadataDictionary = {} metadataDictionary['subjectcode'] = 'text' metadataDictionary['dataset'] = 'text' metadataDictionary = addGroupVariablesToDictionary(metadataJSON, metadataDictionary) return metadataDictionary def addGroupVariablesToDictionary(groupMetadata, metadataDictionary): if 'variables' in groupMetadata: for variable in groupMetadata['variables']: if 'sql_type' not in variable: raise ValueError( 'The variable "' + variable['code'] + '" does not contain the sql_type field in the metadata.') metadataDictionary[variable['code']] = variable['sql_type'] if 'groups' in groupMetadata: for group in groupMetadata['groups']: metadataDictionary = addGroupVariablesToDictionary(group, metadataDictionary) return metadataDictionary # This metadata list is used to create the metadata table. It contains all the known information for each variable. def createMetadataList(CDEsMetadataPath): CDEsMetadata = open(CDEsMetadataPath, "r", encoding="utf-8") metadataJSON = json.load(CDEsMetadata) metadataList = [] metadataList = addGroupVariablesToList(metadataJSON, metadataList) return metadataList def addGroupVariablesToList(groupMetadata, metadataList): if 'variables' in groupMetadata: for variable in groupMetadata['variables']: variableDictionary = {} variableDictionary['code'] = variable['code'] if 'label' not in variable: raise ValueError( 'The variable "' + variable['code'] + '" does not contain the label field in the metadata.') variableDictionary['label'] = variable['label'] if 'sql_type' not in variable: raise ValueError( 'The variable "' + variable['code'] + '" does not contain the sql_type field in the metadata.') variableDictionary['sql_type'] = variable['sql_type'] if 'isCategorical' not in variable: raise ValueError( 'The variable "' + variable['code'] + '" does not contain the isCategorical field in the metadata.') variableDictionary['isCategorical'] = '1' if variable['isCategorical'] else '0' if variable['isCategorical'] and 'enumerations' not in variable: raise ValueError('The variable "' + variable[ 'code'] + '" does not contain enumerations even though it is categorical.') if 'enumerations' in variable: enumerations = [] for enumeration in variable['enumerations']: enumerations.append(str(enumeration['code'])) variableDictionary['enumerations'] = ','.join(enumerations) else: variableDictionary['enumerations'] = None if 'min' in variable: variableDictionary['min'] = variable['min'] else: variableDictionary['min'] = None if 'max' in variable: variableDictionary['max'] = variable['max'] else: variableDictionary['max'] = None metadataList.append(variableDictionary) if 'groups' in groupMetadata: for group in groupMetadata['groups']: metadataList = addGroupVariablesToList(group, metadataList) return metadataList def addMetadataInTheDatabase(CDEsMetadataPath, cur): # Transform the metadata json into a column name -> column type dictionary metadataList = createMetadataList(CDEsMetadataPath) # Create the query for the metadata table createMetadataTableQuery = 'CREATE TABLE METADATA(' createMetadataTableQuery += ' code TEXT PRIMARY KEY ASC CHECK (TYPEOF(code) = "text")' createMetadataTableQuery += ', label TEXT CHECK (TYPEOF(label) = "text")' createMetadataTableQuery += ', sql_type TEXT CHECK (TYPEOF(sql_type) = "text")' createMetadataTableQuery += ', isCategorical INTEGER CHECK (TYPEOF(isCategorical) = "integer")' createMetadataTableQuery += ', enumerations TEXT CHECK (TYPEOF(enumerations) = "text" OR TYPEOF(enumerations) = "null")' createMetadataTableQuery += ', min INTEGER CHECK (TYPEOF(min) = "integer" OR TYPEOF(min) = "null")' createMetadataTableQuery += ', max INTEGER CHECK (TYPEOF(max) = "integer" OR TYPEOF(max) = "null"))' # Create the metadata table cur.execute('DROP TABLE IF EXISTS METADATA') cur.execute(createMetadataTableQuery) # Add data to the metadata table columnsQuery = 'INSERT INTO METADATA (code, label, sql_type, isCategorical, enumerations, min, max) VALUES (' for variable in metadataList: insertVariableQuery = columnsQuery insertVariableQuery += "'" + variable['code'] + "'" insertVariableQuery += ", '" + variable['label'] + "'" insertVariableQuery += ", '" + variable['sql_type'] + "'" insertVariableQuery += ", " + variable['isCategorical'] if variable['enumerations']: insertVariableQuery += ", '" + variable['enumerations'] + "'" else: insertVariableQuery += ", NULL" if variable['min']: insertVariableQuery += ", '" + variable['min'] + "'" else: insertVariableQuery += ", NULL" if variable['max']: insertVariableQuery += ", '" + variable['max'] + "'" else: insertVariableQuery += ", NULL" insertVariableQuery += ");" try: cur.execute(insertVariableQuery) except sqlite3.IntegrityError: raise ValueError('Failed to execute query: ' + insertVariableQuery + ' , due to database constraints.') def createDataTable(metadataDictionary, cur): # Create the query for the sqlite data table createDataTableQuery = 'CREATE TABLE DATA(' for column in metadataDictionary: if metadataDictionary[column] in ['INT', 'int', 'Int']: createDataTableQuery += column + ' ' + metadataDictionary[ column] + ' CHECK (TYPEOF(' + column + ') = "integer" OR TYPEOF(' + column + ') = "null"), ' elif metadataDictionary[column] in ['REAL', 'real', 'Real']: createDataTableQuery += column + ' ' + metadataDictionary[ column] + ' CHECK (TYPEOF(' + column + ') = "real" OR TYPEOF(' + column + ') = "integer" OR TYPEOF(' + column + ') = "null"), ' elif metadataDictionary[column] in ['TEXT', 'text', 'Text']: createDataTableQuery += column + ' ' + metadataDictionary[ column] + ' CHECK (TYPEOF(' + column + ') = "text" OR TYPEOF(' + column + ') = "null"), ' # Remove the last comma createDataTableQuery = createDataTableQuery[:-2] createDataTableQuery += ')' # Create the data table cur.execute('DROP TABLE IF EXISTS DATA') cur.execute(createDataTableQuery) def addCSVInTheDataTable(csvFilePath, metadataDictionary, cur): # Open the csv csvFile = open(csvFilePath, "r", encoding="utf-8") csvReader = csv.reader(csvFile) # Create the csv INSERT statement csvHeader = next(csvReader) columnsString = csvHeader[0] for column in csvHeader[1:]: if column not in metadataDictionary: raise KeyError('Column ' + column + ' does not exist in the metadata!') columnsString += ', ' + column columnsSectionOfSQLQuery = 'INSERT INTO DATA (' + columnsString + ') VALUES ' # Insert data numberOfRows = 0 valuesSectionOfSQLQuery = '(' for row in csvReader: numberOfRows += 1 for (value, column) in zip(row, csvHeader): if metadataDictionary[column] == 'text': valuesSectionOfSQLQuery += "'" + value + "', " elif value == '': valuesSectionOfSQLQuery += 'null, ' else: valuesSectionOfSQLQuery += value + ", " if numberOfRows % int(MAX_ROWS_TO_INSERT_INTO_SQL) == 0: valuesSectionOfSQLQuery = valuesSectionOfSQLQuery[:-2] valuesSectionOfSQLQuery += ');' try: cur.execute(columnsSectionOfSQLQuery + valuesSectionOfSQLQuery) except: findErrorOnBulkInsertQuery(cur, valuesSectionOfSQLQuery, csvHeader, metadataDictionary, csvFilePath) raise ValueError("Error inserting the CSV to the database.") valuesSectionOfSQLQuery = '(' else: valuesSectionOfSQLQuery = valuesSectionOfSQLQuery[:-2] valuesSectionOfSQLQuery += '),(' if numberOfRows % int(MAX_ROWS_TO_INSERT_INTO_SQL) != 0: valuesSectionOfSQLQuery = valuesSectionOfSQLQuery[:-3] valuesSectionOfSQLQuery += ');' try: cur.execute(columnsSectionOfSQLQuery + valuesSectionOfSQLQuery) except: findErrorOnBulkInsertQuery(cur, valuesSectionOfSQLQuery, csvHeader, metadataDictionary, csvFilePath) def findErrorOnBulkInsertQuery(cur, valuesOfQuery, csvHeader, metadataDictionary, csvFilePath): # Removing the first and last parenthesis valuesOfQuery = valuesOfQuery[1:-2] # Removing the ' from character values valuesOfQuery = valuesOfQuery.replace("\'", "") # Call findErrorOnSqlQuery for each row in the bulk query for row in valuesOfQuery.split('),('): findErrorOnSqlQuery(cur, row.split(','), csvHeader, metadataDictionary, csvFilePath) def findErrorOnSqlQuery(cur, row, csvHeader, metadataDictionary, csvFilePath): # Insert the code column into the database and then update it for each row to find where the problem is firstRow = True for (value, column) in zip(row, csvHeader): if firstRow: firstRow = False code = value insertQuery = "INSERT INTO DATA (subjectcode) VALUES ('" + value + "');" cur.execute(insertQuery) continue; if metadataDictionary[column] == 'text': updateQuery = "UPDATE DATA SET " + column + " = '" + value + "' WHERE subjectcode = '" + code + "';"; elif value == '': updateQuery = "UPDATE DATA SET " + column + " = null WHERE subjectcode = '" + code + "';"; else: updateQuery = "UPDATE DATA SET " + column + " = " + value + " WHERE subjectcode = '" + code + "';"; try: cur.execute(updateQuery) except: raise ValueError( "Error inserting into the database. Could not insert value: '" + value + "', into column: '" + column + "', at row with subjectcode: " + code + ", while inserting csv: " + csvFilePath) def main(): # Read the parameters parser = ArgumentParser() parser.add_argument('-f', '--pathologiesFolderPath', required=True, help='The folder with the pathologies data.') parser.add_argument('-p', '--pathologies', required=False, help='Specific pathologies to parse. (Example: "dementia,tbi"' ) args = parser.parse_args() pathologiesFolderPath = os.path.abspath(args.pathologiesFolderPath) # Get all pathologies pathologiesList = next(os.walk(pathologiesFolderPath))[1] if args.pathologies != None: pathologiesToConvert = args.pathologies.split(",") pathologiesList = list(set(pathologiesList) & set(pathologiesToConvert)) print ("Converting csvs for pathologies: " + ",".join(pathologiesList)) # Create the datasets db for each pathology for pathologyName in pathologiesList: # Initializing metadata and output absolute path CDEsMetadataPath = os.path.join(pathologiesFolderPath, pathologyName, "CDEsMetadata.json") outputDBAbsPath = os.path.join(pathologiesFolderPath, pathologyName, "datasets.db") # Connect to the database con = sqlite3.connect(outputDBAbsPath) cur = con.cursor() # Add the metadata table + rows addMetadataInTheDatabase(CDEsMetadataPath, cur) # Transform the metadata json into a column name -> column type list metadataDictionary = createMetadataDictionary(CDEsMetadataPath) # Create the data table with the header createDataTable(metadataDictionary, cur) # Add all the csvs in the database for csv in os.listdir(os.path.join(pathologiesFolderPath, pathologyName)): if csv.endswith('.csv'): csvFilePath = os.path.join(pathologiesFolderPath, pathologyName, csv) addCSVInTheDataTable(csvFilePath, metadataDictionary, cur) con.commit() con.close() if __name__ == '__main__': main()
mit
lyuboasenov/scheduler
packages/AForge.NET Framework-2.2.5/Tools/DebuggerVisualizers/ImageView.cs
4484
// AForge debugging visualizers // AForge.NET framework // http://www.aforgenet.com/framework/ // // Copyright © AForge.NET, 2011 // [email protected] // using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Drawing.Imaging; using System.Windows.Forms; using System.IO; namespace AForge.DebuggerVisualizers { public partial class ImageView : Form { public ImageView( ) { InitializeComponent( ); } private void ImageView_Resize( object sender, EventArgs e ) { UpdateViewSize( ); } private void ImageView_Load( object sender, EventArgs e ) { if ( pictureBox.Image != null ) { // if image was already set by the time of form loading, update form's size int width = System.Math.Max( 64, System.Math.Min( 800, pictureBox.Image.Width ) ); int height = System.Math.Max( 64, System.Math.Min( 600, pictureBox.Image.Height ) ); this.Size = new Size( width + 80, height + 155 ); } } public void SetImage( Image image ) { pictureBox.Image = image; if ( image == null ) { Text = "Image not set"; saveButton.Enabled = false; clipboardButton.Enabled = false; } else { Text = string.Format( "Width: {0}, Height: {1}", image.Width, image.Height ); saveButton.Enabled = true; clipboardButton.Enabled = true; } UpdateViewSize( ); } private void UpdateViewSize( ) { pictureBox.SuspendLayout( ); int width = 160; int height = 120; if ( pictureBox.Image != null ) { width = pictureBox.Image.Width + 2; height = pictureBox.Image.Height + 2; } int x = ( width > imagePanel.ClientSize.Width ) ? 0 : ( imagePanel.ClientSize.Width - width ) / 2; int y = ( height > imagePanel.ClientSize.Height ) ? 0 : ( imagePanel.ClientSize.Height - height) / 2; pictureBox.Size = new Size( width, height ); pictureBox.Location = new System.Drawing.Point( x, y ); pictureBox.ResumeLayout( ); } // Put image into clipboard private void clipboardButton_Click( object sender, EventArgs e ) { if ( pictureBox.Image != null ) { Clipboard.SetDataObject( pictureBox.Image ); } } // Save image to file private void saveButton_Click( object sender, EventArgs e ) { if ( pictureBox.Image != null ) { if ( saveFileDialog.ShowDialog( ) == DialogResult.OK ) { ImageFormat format = ImageFormat.Jpeg; // resolve file format switch ( Path.GetExtension( saveFileDialog.FileName ).ToLower( ) ) { case ".jpg": format = ImageFormat.Jpeg; break; case ".bmp": format = ImageFormat.Bmp; break; case ".png": format = ImageFormat.Png; break; default: MessageBox.Show( this, "Unsupported image format was specified", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error ); return; } // save the image try { pictureBox.Image.Save( saveFileDialog.FileName, format ); } catch ( Exception ex ) { MessageBox.Show( this, "Failed writing image file.\r\n\r\n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error ); } } } } } }
mit
keripix/laravel42x
src/Illuminate/Foundation/Testing/Client.php
1076
<?php namespace Illuminate\Foundation\Testing; use Illuminate\Foundation\Application; use Symfony\Component\HttpKernel\HttpKernelBrowser; use Symfony\Component\BrowserKit\Request as DomRequest; class Client extends HttpKernelBrowser { /** * Convert a BrowserKit request into a Illuminate request. * * @param \Symfony\Component\BrowserKit\Request $request * @return \Illuminate\Http\Request */ protected function filterRequest(DomRequest $request) { $httpRequest = Application::onRequest('create', $this->getRequestParameters($request)); $httpRequest->files->replace($this->filterFiles($httpRequest->files->all())); return $httpRequest; } /** * Get the request parameters from a BrowserKit request. * * @param \Symfony\Component\BrowserKit\Request $request * @return array */ protected function getRequestParameters(DomRequest $request) { return array( $request->getUri(), $request->getMethod(), $request->getParameters(), $request->getCookies(), $request->getFiles(), $request->getServer(), $request->getContent() ); } }
mit
cartridge/cartridge-module-util
index.js
12600
'use strict'; var CONFIG_FILE = '/.cartridgerc'; var MATCH_REGEX = /(\[\/\/\]: <> \(Modules start\)\s)([^[]*)(\[\/\/\]: <> \(Modules end\)\s)/g; var EXIT_OK = 0; var EXIT_FAIL = 1; var path = require('path'); var chalk = require('chalk'); var template = require('lodash/template'); var Promise = require('bluebird'); var fs = Promise.promisifyAll(require('fs-extra')); var pathExists = require('path-exists'); var npmInstallPackage = require('npm-install-package'); var process = require('process'); var paths = { project: path.resolve('../../'), config: path.resolve('../../', '_config'), readme: path.resolve('../../', 'readme.md'), cartridge: path.resolve('../../_cartridge'), pkg: path.resolve('../../', 'package.json') }; // Checks if the project has been set up with Cartridge function hasCartridgeInstalled() { return pathExists.sync(paths.project + CONFIG_FILE); } function insertModulesInToReadme(readmeContents) { /* jshint validthis:true */ // In this instance this has been bound by updateReadme to be the rendered module table HTML return readmeContents.replace(MATCH_REGEX, this.renderedModules); /* jshint validthis:false */ } function updateReadme(renderedModuleTemplate) { return fs.readFileAsync(paths.readme, 'utf8') .bind({ renderedModules: renderedModuleTemplate }) .then(insertModulesInToReadme) .then(function(fileContent){ return fs.writeFileAsync(paths.readme, fileContent); }) .catch(function(err) { console.log('updateReadme error'); console.error(err); process.exit(EXIT_FAIL); }); } function updateJsonObj(obj, newObj, ignoreArr){ for (var key in newObj) { if (newObj.hasOwnProperty(key)) { for(var i = 0; i < ignoreArr.length; i++){ if(key !== ignoreArr[i]){ obj[key] = newObj[key]; } } } } return obj; } function removeDependency(obj, match){ for (var key in obj) { if(key === match) delete obj[key]; } return obj; } function jSonObjToNpmInstallArray(newObj, ignoreArr){ var npmArray = []; for (var key in newObj) { if (newObj.hasOwnProperty(key)) { for(var i = 0; i < ignoreArr.length; i++){ if(key !== ignoreArr[i]){ if (newObj.hasOwnProperty(key)) { npmArray.push(key); } } } } } return npmArray; } function compileTemplate(rawTemplate) { var compiledTemplate = template(rawTemplate); /* jshint validthis:true */ // In this instance this has been bound by updateReadmeModules to be the contents of the cartridgeRc return compiledTemplate(this); /* jshint validthis:false */ } function updateReadmeModules(rcData) { var filePath = path.join(paths.cartridge, 'modules.tpl'); return fs.readFileAsync(filePath, 'utf8') .bind(rcData) .then(compileTemplate) .then(updateReadme) .catch(function(err){ console.log('updateReadmeModules error'); console.error(err); console.trace(); process.exit(EXIT_FAIL); }); } function ensureProjectConfigPaths(projectConfig) { if(!projectConfig.hasOwnProperty('paths')) { projectConfig.paths = { src: {}, dest: {} }; } if(!projectConfig.paths.hasOwnProperty('src')) { projectConfig.paths.src = {}; } if(!projectConfig.paths.hasOwnProperty('dest')) { projectConfig.paths.dest = {}; } return projectConfig; } function getModuleId(modules, moduleName) { var i, moduleIndex; // Yes so check that this one doesn't already exist for(i = 0; i < modules.length; i++) { if(modules[i].name === moduleName) { moduleIndex = i; break; } } if(moduleIndex === undefined) { moduleIndex = modules.length; } return moduleIndex; } function removeModuleDataFromRcObject(data, moduleName) { var deleteLength = 1; for (var i = 0; i < data.modules.length; i++) { if(data.modules[i].name === moduleName) { data.modules.splice(i, deleteLength); } } return data; } function addModule(rcContent) { // This is bound to the module data var moduleIndex; // Check if any modules have been added to the rc yet if(!rcContent.hasOwnProperty('modules')) { // No so create the array rcContent.modules = []; moduleIndex = 0; } else { /* jshint validthis:true */ // In this instance this has been bound by addToRc to be the object containing the module information moduleIndex = getModuleId(rcContent.modules, this.name); /* jshint validthis:false */ } // Set the data /* jshint validthis:true */ // In this instance this has been bound by addToRc to be the object containing the module information rcContent.modules[moduleIndex] = this; /* jshint validthis:false */ return rcContent; } function writeJsonFile(fileContent) { /* jshint validthis:true */ // In this instance this has been bound by the calling function to be the path of the JSON file return fs.writeJsonAsync(this, fileContent) /* jshint validthis:false */ .then(function(){ return fileContent; }); } module.exports = function(packageConfig) { var cartridgeApi = {}; function _removeFromProjectDir(removePath, packageName) { var fullFileName = path.basename(removePath); var projectRemovePath = path.join(paths.project, removePath); return fs.removeAsync(projectRemovePath) .then(function(){ cartridgeApi.logMessage('Finished: Removing ' + fullFileName + ' for ' + packageName + ''); return Promise.resolve(); }); } cartridgeApi.logMessage = function logMessage(message) { console.log(message); }; cartridgeApi.copyFileToProject = function copyFileToProject(copyPath, destinationPath) { var fileName, destinationFile; destinationPath = (destinationPath) ? path.join(paths.project, destinationPath) : paths.project; fileName = path.basename(copyPath); destinationFile = path.join(destinationPath, fileName); if(pathExists.sync(destinationFile)) { cartridgeApi.logMessage('Skipping: Copying ' + fileName + ' file as it already exists'); return Promise.resolve(); } return fs.ensureDirAsync(destinationPath) .then(function() { return fs.copyAsync(copyPath, destinationFile); }) .then(function(){ cartridgeApi.logMessage('Finished: Copying ' + fileName + ' for ' + packageConfig.name + ''); return Promise.resolve(); }); }; cartridgeApi.exitIfDevEnvironment = function() { if(process.env.NODE_ENV === 'development') { cartridgeApi.logMessage('NODE_ENV is set to ' + chalk.underline('development')); cartridgeApi.logMessage('Skipping postinstall.js for ' + chalk.underline(packageConfig.name)); cartridgeApi.logMessage(''); process.exit(EXIT_OK); } }; cartridgeApi.ensureCartridgeExists = function ensureCartridgeExists() { if(!hasCartridgeInstalled()) { console.error(chalk.red('Cartridge is not set up in this directory. Please set it up first before installing this module')); process.exit(EXIT_FAIL); } }; // Adds the specified module to the .cartridgerc file cartridgeApi.addToRc = function addToRc() { var filePath = path.join(paths.project, CONFIG_FILE); var moduleConfig = { name: packageConfig.name, version: packageConfig.version, site: packageConfig.homepage, task: packageConfig.name + '/' + packageConfig.main }; cartridgeApi.logMessage('Adding ' + packageConfig.name + ' to .cartridgerc'); return fs.readJsonAsync(filePath) .bind(moduleConfig) .then(addModule) .bind(filePath) .then(writeJsonFile) .then(updateReadmeModules) .then(function() { cartridgeApi.logMessage('Finished: adding ' + packageConfig.name + ' to .cartridgerc'); return Promise.resolve(); }) .catch(function(err){ console.log('addToRc error'); console.error(err); process.exit(EXIT_FAIL); }); }; // Removes the specified module from the .cartridgerc file cartridgeApi.removeFromRc = function removeFromRc() { var filePath = path.join(paths.project, CONFIG_FILE); cartridgeApi.logMessage('Removing ' + packageConfig.name + ' from .cartridgerc'); return fs.readJsonAsync(filePath) .then(function(data) { return removeModuleDataFromRcObject(data, packageConfig.name); }) .bind(filePath) .then(writeJsonFile) .then(updateReadmeModules) .then(function() { cartridgeApi.logMessage('Finished: Removing ' + packageConfig.name + ' from .cartridgerc'); return Promise.resolve(); }) .catch(function(err){ console.log('removeFromRc error'); console.error(err); process.exit(EXIT_FAIL); }); }; // Modify the project configuration (project.json) with a transform function cartridgeApi.modifyProjectConfig = function modifyProjectConfig(transform) { var filePath = path.join(paths.config, '/project.json'); cartridgeApi.logMessage('Updating project config for ' + packageConfig.name); return fs.readJsonAsync(paths.config + '/project.json') .then(ensureProjectConfigPaths) .then(transform) .bind(filePath) .then(writeJsonFile) .then(function(){ cartridgeApi.logMessage('Finished: modifying project config for ' + packageConfig.name); return Promise.resolve(); }) .catch(function(err){ console.log('modifyProjectConfig error'); console.error(err); process.exit(EXIT_FAIL); }); }; // Add configuration files to the project _config directory for this module cartridgeApi.addModuleConfig = function addModuleConfig(configPath) { return cartridgeApi.copyFileToProject(configPath, '_config'); }; cartridgeApi.copyToProjectDir = function copyToProjectDir(fileList) { var copyTasks = []; for (var i = 0; i < fileList.length; i++) { copyTasks.push(cartridgeApi.copyFileToProject(fileList[i].copyPath, fileList[i].destinationPath)); } return Promise.all(copyTasks); }; // Remove configuration files from the project _config directory for this module cartridgeApi.removeModuleConfig = function removeModuleConfig(configPath) { var configFileName = path.basename(configPath); var projectModuleConfigPath = path.join(paths.config, configFileName); return fs.removeAsync(projectModuleConfigPath) .then(function(){ cartridgeApi.logMessage('Finished: Removed ' + packageConfig.name + ' config files'); return Promise.resolve(); }); }; cartridgeApi.removeFromProjectDir = function removeFromProjectDir(fileList) { var removeTasks = []; for (var i = 0; i < fileList.length; i++) { removeTasks.push(_removeFromProjectDir(fileList[i], packageConfig.name)); } return Promise.all(removeTasks); } cartridgeApi.addToPackage = function addToPackage(objToAdd, ignoreArr){ //get package.json var pkg = {}; return fs.readJsonAsync(paths.pkg) .then(function(data){ pkg = data; return updateJsonObj(data.dependencies, objToAdd, ignoreArr); }) .then(function(newPkg){ //update file with new values pkg.dependencies = newPkg; return fs.writeJsonAsync(paths.pkg, pkg, function (err) { console.log('write json error', err) }) .then(function(){ return pkg; }); }) .then(function(){ cartridgeApi.logMessage('Finished: modifying package.json for ' + packageConfig.name); return Promise.resolve(); }) .catch(function(err){ console.log('modifyPackageJson error'); console.error(err); process.exit(EXIT_FAIL); }); }; cartridgeApi.cleanExpansionPack = function cleanExpansionPack(){ var pkg = {}; return fs.readJsonAsync(paths.pkg) .then(function(data){ pkg = data; //remove from package json return removeDependency(data.dependencies, packageConfig.name); }) .then(function(newPkg){ //update file with new values pkg.dependencies = newPkg; return fs.writeJsonAsync(paths.pkg, pkg, function (err) { console.log('write json error', err) }); }) .then(function(){ //remove from node modules return fs.removeSync(path.resolve(__dirname + '../../../../' + packageConfig.name)); }) .then(function(){ cartridgeApi.logMessage('Finished: cleaned packages for ' + packageConfig.name); return Promise.resolve(); }) }; cartridgeApi.installDependencies = function installDependencies(dependencies, ignoreArr){ return new Promise(function (resolve){ process.chdir('../../'); return npmInstallPackage(jSonObjToNpmInstallArray(dependencies, ignoreArr), function(err){ if(err) throw err; cartridgeApi.logMessage('Finished: installing dependencies for ' + packageConfig.name); resolve(); }); }); }; cartridgeApi.finishInstall = function finishInstall() { cartridgeApi.logMessage('Finished: post install of ' + packageConfig.name); process.exit(EXIT_OK); }; return cartridgeApi; };
mit
Vizzuality/undp_cabo_verde
vendor/assets/javascripts/LeafletTextPath/leaflet.textpath.js
6282
/* * Inspired by Tom Mac Wright article : * http://mapbox.com/osmdev/2012/11/20/getting-serious-about-svg/ */ (function () { var __onAdd = L.Polyline.prototype.onAdd, __onRemove = L.Polyline.prototype.onRemove, __updatePath = L.Polyline.prototype._updatePath, __bringToFront = L.Polyline.prototype.bringToFront; var PolylineTextPath = { onAdd: function (map) { __onAdd.call(this, map); this._textRedraw(); }, onRemove: function (map) { map = map || this._map; if (map && this._textNode) map._pathRoot.removeChild(this._textNode); __onRemove.call(this, map); }, bringToFront: function () { __bringToFront.call(this); this._textRedraw(); }, _updatePath: function () { __updatePath.call(this); this._textRedraw(); }, _textRedraw: function () { var text = this._text, options = this._textOptions; if (text) { this.setText(null).setText(text, options); } }, setText: function (text, options) { this._text = text; this._textOptions = options; /* If not in SVG mode or Polyline not added to map yet return */ /* setText will be called by onAdd, using value stored in this._text */ if (!L.Browser.svg || typeof this._map === 'undefined') { return this; } var defaults = { repeat: false, fillColor: 'black', attributes: {}, below: false, }; options = L.Util.extend(defaults, options); /* If empty text, hide */ if (!text) { if (this._textNode && this._textNode.parentNode) { this._map._pathRoot.removeChild(this._textNode); /* delete the node, so it will not be removed a 2nd time if the layer is later removed from the map */ delete this._textNode; } return this; } text = text.replace(/ /g, '\u00A0'); // Non breakable spaces var id = 'pathdef-' + L.Util.stamp(this); var svg = this._map._pathRoot; this._path.setAttribute('id', id); if (options.repeat) { /* Compute single pattern length */ var pattern = L.Path.prototype._createElement('text'); for (var attr in options.attributes) pattern.setAttribute(attr, options.attributes[attr]); pattern.appendChild(document.createTextNode(text)); svg.appendChild(pattern); var alength = pattern.getComputedTextLength(); svg.removeChild(pattern); /* Create string as long as path */ text = new Array(Math.ceil(this._path.getTotalLength() / alength)).join(text); } /* Put it along the path using textPath */ var textNode = L.Path.prototype._createElement('text'), textPath = L.Path.prototype._createElement('textPath'); var dy = options.offset || this._path.getAttribute('stroke-width'); textPath.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", '#'+id); textNode.setAttribute('dy', dy); for (var attr in options.attributes) textNode.setAttribute(attr, options.attributes[attr]); textPath.appendChild(document.createTextNode(text)); textNode.appendChild(textPath); this._textNode = textNode; if (options.below) { svg.insertBefore(textNode, svg.firstChild); } else { svg.appendChild(textNode); } /* Center text according to the path's bounding box */ if (options.center) { var textLength = textNode.getComputedTextLength(); var pathLength = this._path.getTotalLength(); /* Set the position for the left side of the textNode */ textNode.setAttribute('dx', ((pathLength / 2) - (textLength / 2))); } /* ******************************** * * NOT PART OF THE ORIGINAL LIBRARY * * ******************************** */ if(options.class) { textPath.setAttribute('class', options.class); } /* If the second point of the line is inside the left half of the unit * circle, then we rotate by 180° the text so it's still legible */ var point1 = this._map.latLngToLayerPoint(this.getLatLngs()[0]), point2 = this._map.latLngToLayerPoint(this.getLatLngs()[1]), rotatecenterX = (textNode.getBBox().x + textNode.getBBox().width / 2), rotatecenterY = (textNode.getBBox().y + textNode.getBBox().height / 2), rotated = false; if(point2.x <= point1.x) { rotated = true; textNode.setAttribute('transform', 'rotate(180 ' + rotatecenterX + ' ' + rotatecenterY + ')'); } /* We add an arrow on the line to indicate the direction */ if(options.arrow) { var textAndArrow = rotated ? '◄ ' + text : text + ' ►'; textPath.removeChild(textPath.firstChild); textPath.appendChild(document.createTextNode(textAndArrow)); } /* ******************************** */ /* Initialize mouse events for the additional nodes */ if (this.options.clickable) { if (L.Browser.svg || !L.Browser.vml) { textPath.setAttribute('class', 'leaflet-clickable' + (options.class ? ' ' + options.class : '')); } L.DomEvent.on(textNode, 'click', this._onMouseClick, this); var events = ['dblclick', 'mousedown', 'mouseover', 'mouseout', 'mousemove', 'contextmenu']; for (var i = 0; i < events.length; i++) { L.DomEvent.on(textNode, events[i], this._fireMouseEvent, this); } } return this; } }; L.Polyline.include(PolylineTextPath); L.LayerGroup.include({ setText: function(text, options) { for (var layer in this._layers) { if (typeof this._layers[layer].setText === 'function') { this._layers[layer].setText(text, options); } } return this; } }); })();
mit
kristianmandrup/easy-table
spec/easy-table/table/base_spec.rb
3332
require 'spec_helper' require 'sugar-high/includes' require 'easy-table/namespaces' require 'easy-table/table' describe EasyTable::ViewExt::Table::Base do extend_view_with EasyTable::ViewExt, :table, :row, :cell, :tag before :each do @post = stub(:title => 'my post', :id => 1, :author => 'kristian' ) @post2 = stub(:title => 'my other post', :id => 2, :author => 'mike' ) @posts = [@post, @post2] end describe '#render_caption' do it 'should display a table caption' do with_engine(:erb) do |e| res = e.run_template do %{ <%= render_caption 'my caption' %> } end res.should match /<caption>my caption<\/caption>/ end end end describe '#table_body' do it 'should display a table body with rows' do with_engine(:erb) do |e| res = e.run_template_locals :posts => @posts do %{ <%= table_body posts do |post| %> <%= data_row post, %w{id title} %> <% end %> } end res.should match /<tr>/ res.should match /<td>1<\/td>/ res.should match /<td>my post<\/td>/ # puts res end end end describe '#render_tbody' do it 'should display a table body' do with_engine(:erb) do |e| res = e.run_template_locals :posts => @posts do %{ <%= render_tbody posts do |post| %> <%= data_row post, %w{id title} %> <% end %> } end res.should match /<tbody>/ res.should match /<tr>/ res.should match /<td>1<\/td>/ res.should match /<td>my post<\/td>/ # puts res end end end describe '#render_table' do it 'should display a table' do with_engine(:erb) do |e| res = e.run_template_locals :posts => @posts do %{ <%= render_table do %> <%= render_tbody posts do |post| %> <%= data_row post, %w{id title} %> <% end %> <% end %> } end res.should match /<table>/ res.should match /<tbody>/ res.should match /<tr>/ res.should match /<td>1<\/td>/ res.should match /<td>my post<\/td>/ end end it 'should display a blank table' do with_engine(:erb) do |e| res = e.run_template_locals :posts => @posts do %{ <%= render_table do %> hello <% end %> } end res.should match /<table>/ res.should match /hello/ puts res end end it 'should display a table with attributes' do with_engine(:erb) do |e| res = e.run_template_locals :posts => @posts do %{ <%= render_table :class => 'tables#posts', :id => 'posts_table' do %> <%= render_tbody posts do |post| %> <%= data_row post, %w{id title} %> <% end %> <% end %> } end res.should match /<table class="tables#posts" id="posts_table">/ res.should match /<tbody>/ res.should match /<tr>/ res.should match /<td>1<\/td>/ res.should match /<td>my post<\/td>/ # puts res end end end end
mit
DaveyEdwards/myiworlds
src/routes/createCircle/index.js
739
// /** // * React Starter Kit (https://www.reactstarterkit.com/) // * // * Copyright © 2014-present Kriasoft, LLC. All rights reserved. // * // * This source code is licensed under the MIT license found in the // * LICENSE.txt file in the root directory of this source tree. // */ import React from 'react'; import { graphql } from 'relay-runtime'; import CreateCircle from './CreateCircle'; export default { path: '/createCircle', async action({ api }) { const data = await api.fetchQuery(graphql` query createCircleQuery { viewer { ...CreateCircle_viewer } } `); return { title: 'CreateCircle', component: <CreateCircle viewer={data.viewer} />, }; }, };
mit
dr3am3r/nexttrack
src/3rd-party/sc.api.js
7323
var SC = SC || {}; SC.Widget = function(n) { function t(r) { if (e[r]) return e[r].exports; var o = e[r] = { exports: {}, id: r, loaded: !1 }; return n[r].call(o.exports, o, o.exports, t), o.loaded = !0, o.exports } var e = {}; return t.m = n, t.c = e, t.p = "", t(0) }([function(n, t, e) { function r(n) { return !!("" === n || n && n.charCodeAt && n.substr) } function o(n) { return !!(n && n.constructor && n.call && n.apply) } function i(n) { return !(!n || 1 !== n.nodeType || "IFRAME" !== n.nodeName.toUpperCase()) } function a(n) { var t, e = !1; for (t in b) if (b.hasOwnProperty(t) && b[t] === n) { e = !0; break } return e } function s(n) { var t, e, r; for (t = 0, e = I.length; t < e && (r = n(I[t]), r !== !1); t++); } function u(n) { var t, e, r, o = ""; for ("//" === n.substr(0, 2) && (n = window.location.protocol + n), r = n.split("/"), t = 0, e = r.length; t < e && t < 3; t++) o += r[t], t < 2 && (o += "/"); return o } function c(n) { return n.contentWindow ? n.contentWindow : n.contentDocument && "parentWindow" in n.contentDocument ? n.contentDocument.parentWindow : null } function l(n) { var t, e = []; for (t in n) n.hasOwnProperty(t) && e.push(n[t]); return e } function d(n, t, e) { e.callbacks[n] = e.callbacks[n] || [], e.callbacks[n].push(t) } function E(n, t) { var e, r = !0; return t.callbacks[n] = [], s(function(t) { if (e = t.callbacks[n] || [], e.length) return r = !1, !1 }), r } function f(n, t, e) { var r, o, i = c(e); return !!i.postMessage && (r = e.getAttribute("src").split("?")[0], o = JSON.stringify({ method: n, value: t }), "//" === r.substr(0, 2) && (r = window.location.protocol + r), r = r.replace(/http:\/\/(w|wt).soundcloud.com/, "https://$1.soundcloud.com"), void i.postMessage(o, r)) } function p(n) { var t; return s(function(e) { if (e.instance === n) return t = e, !1 }), t } function h(n) { var t; return s(function(e) { if (c(e.element) === n) return t = e, !1 }), t } function v(n, t) { return function(e) { var r = o(e), i = p(this), a = !r && t ? e : null, s = r && !t ? e : null; return s && d(n, s, i), f(n, a, i.element), this } } function S(n, t, e) { var r, o, i; for (r = 0, o = t.length; r < o; r++) i = t[r], n[i] = v(i, e) } function R(n, t, e) { return n + "?url=" + t + "&" + g(e) } function g(n) { var t, e, r = []; for (t in n) n.hasOwnProperty(t) && (e = n[t], r.push(t + "=" + ("start_track" === t ? parseInt(e, 10) : e ? "true" : "false"))); return r.join("&") } function m(n, t, e) { var r, o, i = n.callbacks[t] || []; for (r = 0, o = i.length; r < o; r++) i[r].apply(n.instance, e); (a(t) || t === L.READY) && (n.callbacks[t] = []) } function w(n) { var t, e, r, o, i; try { e = JSON.parse(n.data) } catch (a) { return !1 } return t = h(n.source), r = e.method, o = e.value, (!t || A(n.origin) === A(t.domain)) && (t ? (r === L.READY && (t.isReady = !0, m(t, C), E(C, t)), r !== L.PLAY || t.playEventFired || (t.playEventFired = !0), r !== L.PLAY_PROGRESS || t.playEventFired || (t.playEventFired = !0, m(t, L.PLAY, [o])), i = [], void 0 !== o && i.push(o), void m(t, r, i)) : (r === L.READY && T.push(n.source), !1)) } function A(n) { return n.replace(Y, "") } var _, y, O, D = e(1), b = e(2), P = e(3), L = D.api, N = D.bridge, T = [], I = [], C = "__LATE_BINDING__", k = "http://wt.soundcloud.dev:9200/", Y = /^http(?:s?)/; window.addEventListener ? window.addEventListener("message", w, !1) : window.attachEvent("onmessage", w), n.exports = O = function(n, t, e) { if (r(n) && (n = document.getElementById(n)), !i(n)) throw new Error("SC.Widget function should be given either iframe element or a string specifying id attribute of iframe element."); t && (e = e || {}, n.src = R(k, t, e)); var o, a, s = h(c(n)); return s && s.instance ? s.instance : (o = T.indexOf(c(n)) > -1, a = new _(n), I.push(new y(a, n, o)), a) }, O.Events = L, window.SC = window.SC || {}, window.SC.Widget = O, y = function(n, t, e) { this.instance = n, this.element = t, this.domain = u(t.getAttribute("src")), this.isReady = !!e, this.callbacks = {} }, _ = function() {}, _.prototype = { constructor: _, load: function(n, t) { if (n) { t = t || {}; var e = this, r = p(this), o = r.element, i = o.src, a = i.substr(0, i.indexOf("?")); r.isReady = !1, r.playEventFired = !1, o.onload = function() { e.bind(L.READY, function() { var n, e = r.callbacks; for (n in e) e.hasOwnProperty(n) && n !== L.READY && f(N.ADD_LISTENER, n, r.element); t.callback && t.callback() }) }, o.src = R(a, n, t) } }, bind: function(n, t) { var e = this, r = p(this); return r && r.element && (n === L.READY && r.isReady ? setTimeout(t, 1) : r.isReady ? (d(n, t, r), f(N.ADD_LISTENER, n, r.element)) : d(C, function() { e.bind(n, t) }, r)), this }, unbind: function(n) { var t, e = p(this); e && e.element && (t = E(n, e), n !== L.READY && t && f(N.REMOVE_LISTENER, n, e.element)) } }, S(_.prototype, l(b)), S(_.prototype, l(P), !0) }, function(n, t) { t.api = { LOAD_PROGRESS: "loadProgress", PLAY_PROGRESS: "playProgress", PLAY: "play", PAUSE: "pause", FINISH: "finish", SEEK: "seek", READY: "ready", OPEN_SHARE_PANEL: "sharePanelOpened", CLICK_DOWNLOAD: "downloadClicked", CLICK_BUY: "buyClicked", ERROR: "error" }, t.bridge = { REMOVE_LISTENER: "removeEventListener", ADD_LISTENER: "addEventListener" } }, function(n, t) { n.exports = { GET_VOLUME: "getVolume", GET_DURATION: "getDuration", GET_POSITION: "getPosition", GET_SOUNDS: "getSounds", GET_CURRENT_SOUND: "getCurrentSound", GET_CURRENT_SOUND_INDEX: "getCurrentSoundIndex", IS_PAUSED: "isPaused" } }, function(n, t) { n.exports = { PLAY: "play", PAUSE: "pause", TOGGLE: "toggle", SEEK_TO: "seekTo", SET_VOLUME: "setVolume", NEXT: "next", PREV: "prev", SKIP: "skip" } }]);
mit
bfontaine/99Scala
src/test/scala/P91Spec.scala
105
package org.bfn.ninetynineprobs import org.scalatest._ class P91Spec extends UnitSpec { // TODO }
mit
mind0n/hive
Cache/Libs/net46/wpf/src/Core/CSharp/System/Windows/Input/Command/KeyGesture.cs
11847
//--------------------------------------------------------------------------- // // <copyright file=KeyGesture.cs company=Microsoft> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // // Description: The KeyGesture class is used by the developer to create Keyboard Input Bindings // // See spec at : http://avalon/coreUI/Specs/Commanding%20--%20design.htm // //* KeyGesture class serves the purpose of Input Bindings for Keyboard Device. //* one will be passing the instance of this around with CommandLink to represent Accelerator Keys // // History: // 06/01/2003 : chandras - Created // //--------------------------------------------------------------------------- using System; using System.Globalization; using System.Windows.Input; using System.Windows; using System.Windows.Markup; using System.ComponentModel; using MS.Internal.PresentationCore; namespace System.Windows.Input { /// <summary> /// KeyGesture - Key and Modifier combination. /// Can be set on properties of KeyBinding and RoutedCommand. /// </summary> [TypeConverter(typeof(KeyGestureConverter))] [ValueSerializer(typeof(KeyGestureValueSerializer))] public class KeyGesture : InputGesture { //------------------------------------------------------ // // Constructors // //------------------------------------------------------ #region Constructors /// <summary> /// constructor /// </summary> /// <param name="key">key</param> public KeyGesture(Key key) : this(key, ModifierKeys.None) { } /// <summary> /// constructor /// </summary> /// <param name="modifiers">modifiers</param> /// <param name="key">key</param> public KeyGesture(Key key, ModifierKeys modifiers) : this(key, modifiers, String.Empty, true) { } /// <summary> /// constructor /// </summary> /// <param name="modifiers">modifiers</param> /// <param name="key">key</param> /// <param name="displayString">display string</param> public KeyGesture(Key key, ModifierKeys modifiers, string displayString) : this(key, modifiers, displayString, true) { } /// <summary> /// Internal constructor used by KeyBinding to avoid key and modifier validation /// This allows setting KeyBinding.Key and KeyBinding.Modifiers without regard /// to order. /// </summary> /// <param name="key">Key</param> /// <param name="modifiers">Modifiers</param> /// <param name="validateGesture">If true, throws an exception if the key and modifier are not valid</param> internal KeyGesture(Key key, ModifierKeys modifiers, bool validateGesture) : this(key, modifiers, String.Empty, validateGesture) { } /// <summary> /// Private constructor that does the real work. /// </summary> /// <param name="key">Key</param> /// <param name="modifiers">Modifiers</param> /// <param name="displayString">display string</param> /// <param name="validateGesture">If true, throws an exception if the key and modifier are not valid</param> private KeyGesture(Key key, ModifierKeys modifiers, string displayString, bool validateGesture) { if(!ModifierKeysConverter.IsDefinedModifierKeys(modifiers)) throw new InvalidEnumArgumentException("modifiers", (int)modifiers, typeof(ModifierKeys)); if(!IsDefinedKey(key)) throw new InvalidEnumArgumentException("key", (int)key, typeof(Key)); if (displayString == null) throw new ArgumentNullException("displayString"); if(validateGesture && !IsValid(key, modifiers)) { throw new NotSupportedException(SR.Get(SRID.KeyGesture_Invalid, modifiers, key)); } _modifiers = modifiers; _key = key; _displayString = displayString; } #endregion Constructors //------------------------------------------------------ // // Public Methods // //------------------------------------------------------ #region Public Methods /// <summary> /// Modifier /// </summary> public ModifierKeys Modifiers { get { return _modifiers; } } /// <summary> /// Key /// </summary> public Key Key { get { return _key; } } /// <summary> /// DisplayString /// </summary> public string DisplayString { get { return _displayString; } } /// <summary> /// Returns a string that can be used to display the KeyGesture. If the /// DisplayString was set by the constructor, it is returned. Otherwise /// a suitable string is created from the Key and Modifiers, with any /// conversions being governed by the given CultureInfo. /// </summary> /// <param name="culture">the culture used when creating a string from Key and Modifiers</param> public string GetDisplayStringForCulture(CultureInfo culture) { // return the DisplayString, if it was set by the ctor if (!String.IsNullOrEmpty(_displayString)) { return _displayString; } // otherwise use the type converter return (string)_keyGestureConverter.ConvertTo(null, culture, this, typeof(string)); } /// <summary> /// Compares InputEventArgs with current Input /// </summary> /// <param name="targetElement">the element to receive the command</param> /// <param name="inputEventArgs">inputEventArgs to compare to</param> /// <returns>True - KeyGesture matches, false otherwise. /// </returns> public override bool Matches(object targetElement, InputEventArgs inputEventArgs) { KeyEventArgs keyEventArgs = inputEventArgs as KeyEventArgs; if(keyEventArgs != null && IsDefinedKey(keyEventArgs.Key)) { return ( ( (int)Key == (int)keyEventArgs.RealKey ) && ( this.Modifiers == Keyboard.Modifiers ) ); } return false; } // Check for Valid enum, as any int can be casted to the enum. internal static bool IsDefinedKey(Key key) { return (key >= Key.None && key <= Key.OemClear); } #endregion Public Methods //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Methods ///<summary> /// Is Valid Keyboard input to process for commands ///</summary> internal static bool IsValid(Key key, ModifierKeys modifiers) { // // Don't enforce any rules on the Function keys or on the number pad keys. // if(!( ( key >= Key.F1 && key <= Key.F24 ) || ( key >= Key.NumPad0 && key <= Key.Divide ) )) { // // We check whether Control/Alt/Windows key is down for modifiers. We don't check // for shift at this time as Shift with any combination is already covered in above check. // Shift alone as modifier case, we defer to the next condition to avoid conflicing with // TextInput. if(( modifiers & ( ModifierKeys.Control | ModifierKeys.Alt | ModifierKeys.Windows ) ) != 0) { switch(key) { case Key.LeftCtrl: case Key.RightCtrl: case Key.LeftAlt: case Key.RightAlt: case Key.LWin: case Key.RWin: return false; default: return true; } } else if(( key >= Key.D0 && key <= Key.D9 ) || ( key >= Key.A && key <= Key.Z )) { return false; } } return true; } /// <summary> /// Decode the strings keyGestures and displayStrings, creating a sequence /// of KeyGestures. Add each KeyGesture to the given InputGestureCollection. /// The two input strings typically come from a resource file. /// </summary> internal static void AddGesturesFromResourceStrings(string keyGestures, string displayStrings, InputGestureCollection gestures) { while (!String.IsNullOrEmpty(keyGestures)) { string keyGestureToken; string keyDisplayString; // break apart first gesture from the rest int index = keyGestures.IndexOf(MULTIPLEGESTURE_DELIMITER, StringComparison.Ordinal); if (index >= 0) { // multiple gestures exist keyGestureToken = keyGestures.Substring(0, index); keyGestures = keyGestures.Substring(index + 1); } else { keyGestureToken = keyGestures; keyGestures = String.Empty; } // similarly, break apart first display string from the rest index = displayStrings.IndexOf(MULTIPLEGESTURE_DELIMITER, StringComparison.Ordinal); if (index >= 0) { // multiple display strings exist keyDisplayString = displayStrings.Substring(0, index); displayStrings = displayStrings.Substring(index + 1); } else { keyDisplayString = displayStrings; displayStrings = String.Empty; } KeyGesture keyGesture = CreateFromResourceStrings(keyGestureToken, keyDisplayString); if (keyGesture != null) { gestures.Add(keyGesture); } } } internal static KeyGesture CreateFromResourceStrings(string keyGestureToken, string keyDisplayString) { // combine the gesture and the display string, producing a string // that the type converter will recognize if (!String.IsNullOrEmpty(keyDisplayString)) { keyGestureToken += KeyGestureConverter.DISPLAYSTRING_SEPARATOR + keyDisplayString; } return _keyGestureConverter.ConvertFromInvariantString(keyGestureToken) as KeyGesture; } #endregion Internal Methods //------------------------------------------------------ // // Private Fields // //------------------------------------------------------ #region Private Fields private ModifierKeys _modifiers = ModifierKeys.None; private Key _key = Key.None; private string _displayString; private const string MULTIPLEGESTURE_DELIMITER = ";"; private static TypeConverter _keyGestureConverter = new KeyGestureConverter(); //private static bool _classRegistered = false; #endregion Private Fields } }
mit
ExpoSEJS/ExpoSE
Distributor/src/Strategies/Default.js
1952
/* Copyright (c) Royal Holloway, University of London | Contact Blake Loring ([email protected]), Duncan Mitchell ([email protected]), or Johannes Kinder ([email protected]) for details or support | LICENSE.md for license details */ class Strategy { constructor() { //Buckets can be sorted by fork point or randomly selected to change search strategy this._buckets = []; //Cache the length of the total remaining so we don't have to loop to identify len this._totalQueued = 0; this._totalEaten = 0; } _findOrCreate(id) { let found = this._buckets.find(x => x.id == id); if (!found) { found = { id: id, entries: [], seen: 0 }; this._buckets.push(found); } return found; } add(target, sourceInfo) { // Manually added paths and some edge-cases don't have a forkIid, just make one up const bucketId = sourceInfo ? sourceInfo.forkIid : 0; const bucket = this._findOrCreate(bucketId); bucket.entries.push(target); //Update total queued list this._totalQueued++; } _selectFromBucket(bucket) { return bucket.entries.shift(); } _selectLeastSeen() { //Sort buckets by seen, find the first non empty bucket and then use the entry this._buckets.sort((x, y) => x.seen - y.seen); const firstNonEmptyBucket = this._buckets.find((x) => x.entries.length); firstNonEmptyBucket.seen++; return this._selectFromBucket(firstNonEmptyBucket); } _selectRandomEntry() { const nonEmptyBuckets = this._buckets.filter(x => x.entries.length); const selectedBucket = nonEmptyBuckets[Math.floor(Math.random() * nonEmptyBuckets.length)]; return this._selectFromBucket(selectedBucket); } next() { this._totalQueued--; //1 in 3 test cases to be selected completely at random if ((this._totalEaten++) % 3 == 0) { return this._selectRandomEntry(); } else { return this._selectLeastSeen(); } } length() { return this._totalQueued; } } export default Strategy;
mit
conanite/reservation
spec/dummy/db/schema.rb
1857
# encoding: UTF-8 # This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your # database schema. If you need to create the application database on another # system, you should be using db:schema:load, not running all the migrations # from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended to check this file into your version control system. ActiveRecord::Schema.define(:version => 20130711174025) do create_table "contacts", :force => true do |t| t.string "name" t.string "type" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false end create_table "places", :force => true do |t| t.string "name" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false end create_table "reservation_events", :force => true do |t| t.datetime "start" t.datetime "finish" t.string "title" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false end create_table "reservation_reservations", :force => true do |t| t.integer "event_id" t.string "subject_type" t.integer "subject_id" t.string "reservation_status" t.string "role" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false end create_table "things", :force => true do |t| t.string "name" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false end end
mit
andpol5/QueryParsingForInlp
Part2/XMLScorer.py
5255
#This code has been developed by Daniel Duato Catalan, Luis Fabregues de los Santos and Javier Selva Castello import xml.etree.ElementTree as ET class Query: def __init__(self,query_no,query,local,query_what,query_type,geo_relation,query_where,lat_long): self.query_no=query_no self.query=query self.local=local self.query_what=query_what self.query_type=query_type self.geo_relation=geo_relation self.query_where=query_where self.lat_long=lat_long #Checks if the Query is the same Query than the other one #return: Boolean indicating whether the two Queries are the same or not def is_same_query(self,query2): return self.query_no==query2.query_no #Compares the Query object with the correct Query #return: Boolean indicating whether the Query is correct or not def is_correct(self,golden): return (self.local==golden.local and ' '.join(self.query_what.lower().split())==' '.join(golden.query_what.lower().split()) and self.query_type==golden.query_type and self.geo_relation==golden.geo_relation and str(golden.query_where).lower().split(',')[0] in str(self.query_where).lower().split(',')[0]) #Prints the Query object def show_query(self): print "QUERY_NO: ", self.query_no print "\tQUERY: ", self.query print "\tLOCAL: ", self.local print "\tQUERY_WHAT: ", self.query_what print "\tQUERY_TYPE: ", self.query_type print "\tGEO_RELATION: ", self.geo_relation print "\tQUERY_WHERE: ", self.query_where print "\tLAT_LONG: ", self.lat_long ''' Reads a .xml file containing all the Queries and formats them as objects @param: fileName - String containing the path and name of the .xml file to be parsed @return: List of Query objects with the queries that were in the pared file ''' def parser(fileName): # Using the xml parser from python libraries tree = ET.parse(fileName) root = tree.getroot() i = 0 query_list = [] # List of query objects to be returned curr_query = [] # Vector containing the data of the current query while i < len(root): if i % 8 == 0 and i > 0: # Queries have 7 fields, in the 8th iteration we create a Query object query_list.append(Query(curr_query[0], curr_query[1], curr_query[2], curr_query[3], curr_query[4], curr_query[5], curr_query[6], curr_query[7])) curr_query = [] curr_query.append(root[i].text) i += 1 # Appending last query data query_list.append(Query(curr_query[0], curr_query[1], curr_query[2], curr_query[3], curr_query[4], curr_query[5], curr_query[6], curr_query[7])) return query_list ''' Gets the precision, recall and score of a list of Query objects @params: to_test - A list of Query objects containing the queries to be tested golden - A list of Query objects containing the reference queries unsorted - (bool) Indicates whether or not the queries in "to_test" and "golden" are sorted and if all the queries in "golden" are also in "to_test" usepaper - (bool) Indicates whether or not to use the paper formulas for precision and recall. If set to False it will use the ACTUAL formulas for precision and recall. @return: precision - (float) recall - (float) score - (float) ''' def obtain_score(to_test,golden, unsorted = True, usepaper = False): if unsorted: q_num = {} # Arranges a dictionary from query_no -> index in the "golden" list for i in xrange(len(golden)): q_num[golden[i].query_no]=i size = len(to_test) correct = 0 # Amount of correctly tagged queries correct_local = 0 # Amount of local queries correctly tagged local = 0 # Total amount of local queries wrong_local = 0 # Amount of queries tagged wrongly as local for test_query, i in zip(to_test,range(size)): # If the current Query is correct if test_query.is_correct(golden[q_num[test_query.query_no] if unsorted else i]): correct += 1 if test_query.local=="True": correct_local += 1 else: test_query.correct = False if test_query.local=="True": wrong_local += 1 # print test_query.query # If the Query is local if golden[q_num[test_query.query_no] if unsorted else i].local == "True": local += 1 if usepaper: # Weird formulas precision = correct/float(size) recall = correct/float(local) else: # Nice formulas precision = correct_local/float((correct_local+wrong_local)) recall = correct_local/float(local) score = 2.0*precision*recall/(precision+recall) return precision, recall, score if __name__ == "__main__": # Tester queries = parser('ParsedQueries.xml') goldens = parser('GC_Test_Golden_100.xml') unsorted = True usepaper = True results = obtain_score(queries, goldens, unsorted, usepaper) print "Precision:", results[0] print "Recall:", results[1] print "F1-Score:", results[2]
mit
superdweebie/doctrine-extensions
tests/Sds/DoctrineExtensions/Test/Identity/CredentialTraitTest.php
2141
<?php namespace Sds\DoctrineExtensions\Test\Identity; use Sds\Common\Crypt\Hash; use Sds\DoctrineExtensions\Manifest; use Sds\DoctrineExtensions\Test\Identity\TestAsset\Document\CredentialTraitDoc; use Sds\DoctrineExtensions\Test\BaseTest; use Sds\DoctrineExtensions\Test\TestAsset\Identity; class CredentialTraitTest extends BaseTest { public function setUp(){ $manifest = new Manifest([ 'documents' => [ __NAMESPACE__ . '\TestAsset\Document' => __DIR__ . '/TestAsset/Document' ], 'extension_configs' => [ 'extension.crypt' => true ], 'document_manager' => 'testing.documentmanager', 'service_manager_config' => [ 'factories' => [ 'testing.documentmanager' => 'Sds\DoctrineExtensions\Test\TestAsset\DocumentManagerFactory', 'identity' => function(){ $identity = new Identity(); $identity->setIdentityName('toby'); return $identity; } ] ] ]); $this->documentManager = $manifest->getServiceManager()->get('testing.documentmanager'); } public function testPassword(){ $password = 'password1'; $doc = new CredentialTraitDoc(); $doc->setCredential($password); $this->documentManager->persist($doc); $this->documentManager->flush(); $this->assertNotEquals($password, $doc->getCredential()); $this->assertEquals($doc->getCredential(), Hash::hashCredential($doc, $password)); $this->assertNotEquals($doc->getCredential(), Hash::hashCredential($doc, 'not password')); $newPassword = 'new password'; $doc->setCredential($newPassword); $this->documentManager->flush(); $this->assertNotEquals($newPassword, $doc->getCredential()); $this->assertEquals($doc->getCredential(), Hash::hashCredential($doc, $newPassword)); $this->assertNotEquals($doc->getCredential(), Hash::hashCredential($doc, $password)); } }
mit
Jastrzebowski/algolia-search
src/components/Facets.js
917
import React, { PropTypes, Component } from "react" import Facet from "../components/Facet" const facetsLabels = { "category": "Category", "manufacturer": "Manufacturer", "salePrice_range": "Price range", "shipping": "Shipping", "type": "Type", } export default class Facets extends Component { static propTypes = { options: PropTypes.object.isRequired, facets: PropTypes.array.isRequired, onChanged: PropTypes.func.isRequired } render() { const { options, facets, onChanged } = this.props let refinements = options.disjunctiveFacetsRefinements || [] // [issue: 1] return <div className="col s3 facets"> {facets.map((facet, idx) => <Facet key={idx} title={facetsLabels[facet.name]} facetKey={facet.name} facet={facet.data} refinements={refinements[facet.name]} onChanged={onChanged} />)} </div> } }
mit
shing1630/hk_rain
server/src/app/repository/ForecastRepository.ts
2048
/** * Created by Josh Chan on 02-12-2016. */ import ForecastModel = require("./../model/ForecastModel"); import IForecastModel = require("./../model/interfaces/IForecastModel"); import ForecastSchema = require("./../dataAccess/schemas/ForecastSchema"); import RepositoryBase = require("./BaseRepository"); import mongoose = require("mongoose"); class ForecastRepository extends RepositoryBase<IForecastModel> { constructor() { super(ForecastSchema); } private _forecastmodel: mongoose.Model<mongoose.Document> = ForecastSchema; countByMonthDay(inputMonth: string, inputDay: string, callback: (error: any, result: any) => void) { this._forecastmodel.count({ $and: [ { month: inputMonth }, { day: inputDay }] }, callback); } findByMonthDay(inputMonth: string, inputDay: string, callback: (error: any, result: IForecastModel[]) => void) { this._forecastmodel.find({ $and: [ { month: inputMonth }, { day: inputDay }] }, callback); } findByMonthDayArray(inputMonth: number[], inputDay: number[], callback: (error: any, result: IForecastModel[]) => void) { this._forecastmodel.find({ $and: [ { month: { $in: inputMonth } }, { day: { $in: inputDay } }] }, {}, { sort: { year: 1, month: 1, day: 1 } }, callback); } findAll(callback: (error: any, result: IForecastModel[]) => void) { this._forecastmodel.find({}, {}, { sort: { month: 1, day: 1 } }, callback); } removeAllForecastExp(callback: (error: any) => void) { let date = new Date(); let currDay = date.getDate(); this._forecastmodel.remove( { day: { $ne: currDay } }, callback); } removeAllForecast(callback: (error: any) => void) { this._forecastmodel.remove( {}, callback); } } Object.seal(ForecastRepository); export = ForecastRepository;
mit
semyen/SimpleBTS
src/OroAcademic/Bundle/SimpleBTSBundle/Controller/Api/Rest/IssueController.php
7218
<?php namespace OroAcademic\Bundle\SimpleBTSBundle\Controller\Api\Rest; use OroAcademic\Bundle\SimpleBTSBundle\Entity\Issue; use OroAcademic\Bundle\SimpleBTSBundle\Form\Type\IssueApiType; use Oro\Bundle\SoapBundle\Controller\Api\Rest\RestController; use Oro\Bundle\SoapBundle\Entity\Manager\ApiEntityManager; use Oro\Bundle\SoapBundle\Form\Handler\ApiFormHandler; use Oro\Bundle\SoapBundle\Request\Parameters\Filter\HttpDateTimeParameterFilter; use Oro\Bundle\SoapBundle\Request\Parameters\Filter\IdentifierToReferenceFilter; use FOS\RestBundle\Routing\ClassResourceInterface; use FOS\RestBundle\Controller\Annotations\RouteResource; use FOS\RestBundle\Controller\Annotations\QueryParam; use FOS\RestBundle\Controller\Annotations\NamePrefix; use Nelmio\ApiDocBundle\Annotation\ApiDoc; use Symfony\Component\Form\FormInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Oro\Bundle\AddressBundle\Utils\AddressApiUtils; use Oro\Bundle\SecurityBundle\Annotation\Acl; use Oro\Bundle\SecurityBundle\Annotation\AclAncestor; /** * @RouteResource("api") * @NamePrefix("oro_academic_sbts_issue_") */ class IssueController extends RestController implements ClassResourceInterface { /** * REST GET list * * @QueryParam( * name="page", requirements="\d+", nullable=true, description="Page number, starting from 1. Defaults to 1." * ) * @QueryParam( * name="limit", requirements="\d+", nullable=true, description="Number of items per page. defaults to 10." * ) * @QueryParam( * name="createdAt", * requirements="\d{4}(-\d{2}(-\d{2}([T ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|([-+]\d{2}(:?\d{2})?))?)?)?)?", * nullable=true, * description="Date in RFC 3339 format. For example: 2009-11-05T13:15:30Z, 2008-07-01T22:35:17+08:00" * ) * @QueryParam( * name="updatedAt", * requirements="\d{4}(-\d{2}(-\d{2}([T ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|([-+]\d{2}(:?\d{2})?))?)?)?)?", * nullable=true, * description="Date in RFC 3339 format. For example: 2009-11-05T13:15:30Z, 2008-07-01T22:35:17+08:00" * ) * @QueryParam( * name="ownerId", * requirements="\d+", * nullable=true, * description="Id of owner user" * ) * @QueryParam( * name="ownerUsername", * requirements=".+", * nullable=true, * description="Username of owner user" * ) * @QueryParam( * name="reporterId", * requirements="\d+", * nullable=true, * description="Id of reporter user" * ) * @QueryParam( * name="reporterUsername", * requirements=".+", * nullable=true, * description="Username of reporter user" * ) * @QueryParam( * name="assigneeId", * requirements="\d+", * nullable=true, * description="Id of assignee" * ) * @QueryParam( * name="assigneeUsername", * requirements=".+", * nullable=true, * description="Username of assignee" * ) * @ApiDoc( * description="Get all issue items", * resource=true * ) * @AclAncestor("oro_academic_sbts_issue_view") * @param Request $request * @throws \Exception * @return Response */ public function cgetAction(Request $request) { $page = (int)$request->get('page', 1); $limit = (int)$request->get('limit', self::ITEMS_PER_PAGE); $filterParameters = [ 'createdAt' => new HttpDateTimeParameterFilter(), 'updatedAt' => new HttpDateTimeParameterFilter(), 'ownerId' => new IdentifierToReferenceFilter($this->getDoctrine(), 'OroUserBundle:User'), 'ownerUsername' => new IdentifierToReferenceFilter($this->getDoctrine(), 'OroUserBundle:User', 'username') , 'reporterId' => new IdentifierToReferenceFilter($this->getDoctrine(), 'OroUserBundle:User'), 'reporterUsername' => new IdentifierToReferenceFilter($this->getDoctrine(), 'OroUserBundle:User', 'username') , 'assigneeId' => new IdentifierToReferenceFilter($this->getDoctrine(), 'OroUserBundle:User'), 'assigneeUsername' => new IdentifierToReferenceFilter($this->getDoctrine(), 'OroUserBundle:User', 'username') , ]; $map = [ 'ownerId' => 'owner', 'ownerUsername' => 'owner', 'reporterId' => 'reporter', 'reporterUsername' => 'reporter', 'assigneeId' => 'assignee', 'assigneeUsername' => 'assignee', ]; $criteria = $this->getFilterCriteria($this->getSupportedQueryParameters('cgetAction'), $filterParameters, $map); return $this->handleGetListRequest($page, $limit, $criteria); } /** * REST GET item * * @param string $id * * @ApiDoc( * description="Get issue item", * resource=true * ) * @AclAncestor("oro_academic_sbts_issue_view") * @return Response */ public function getAction($id) { return $this->handleGetRequest($id); } /** * REST PUT * * @param int $id Issue item id * * @ApiDoc( * description="Update issue", * resource=true * ) * @AclAncestor("oro_academic_sbts_issue_update") * @return Response */ public function putAction($id) { return $this->handleUpdateRequest($id); } /** * Create new issue * * @ApiDoc( * description="Create new issue", * resource=true * ) * @AclAncestor("oro_academic_sbts_issue_create") */ public function postAction() { return $this->handleCreateRequest(); } /** * REST DELETE * * @param int $id * * @ApiDoc( * description="Delete issue", * resource=true * ) * @AclAncestor("oro_academic_sbts_issue_delete") * @return Response */ public function deleteAction($id) { return $this->handleDeleteRequest($id); } /** * Get entity Manager * * @return ApiEntityManager */ public function getManager() { return $this->get('oro_academic_sbts.issue.manager.api'); } /** * @return FormInterface */ public function getForm() { return $this->get('oro_academic_sbts.form.issue.api'); } /** * @return ApiFormHandler */ public function getFormHandler() { return $this->get('oro_academic_sbts.form.handler.issue.api'); } /** * @return string */ protected function getFormAlias() { return IssueApiType::NAME; } /** * {@inheritDoc} */ protected function fixFormData(array &$data, $entity) { /** @var Issue $entity */ parent::fixFormData($data, $entity); unset($data['id']); unset($data['updatedAt']); unset($data['createdAt']); return true; } }
mit
zdizzle6717/battle-comm
compiled-server/routes/api/newsPosts.js
3947
'use strict'; var _joi = require('joi'); var _joi2 = _interopRequireDefault(_joi); var _handlers = require('../handlers'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } module.exports = [ // News Posts { 'method': 'GET', 'path': '/api/newsPosts/{id}', 'config': { 'tags': ['api'], 'description': 'Get one newsPost by id', 'notes': 'Get one newsPost by id', 'validate': { 'params': { 'id': _joi2.default.number().required() } } }, 'handler': _handlers.newsPosts.get }, { 'method': 'GET', 'path': '/api/newsPosts', 'config': { 'tags': ['api'], 'description': 'Get all newsPosts', 'notes': 'Get all newsPosts' }, 'handler': _handlers.newsPosts.getAll }, { 'method': 'POST', 'path': '/api/newsPosts', 'config': { 'tags': ['api'], 'description': 'Add a new newsPost', 'notes': 'Add a new newsPost', 'auth': { 'strategy': 'jsonWebToken', 'scope': ['newsContributor', 'systemAdmin'] }, 'validate': { 'payload': { 'Files': _joi2.default.optional(), 'UserId': _joi2.default.number().required(), 'FactionId': _joi2.default.optional(), 'GameSystemId': _joi2.default.optional(), 'ManufacturerId': _joi2.default.optional(), 'title': _joi2.default.string().required(), 'callout': _joi2.default.string().required(), 'body': _joi2.default.string().required(), 'published': _joi2.default.boolean().required(), 'featured': _joi2.default.boolean().required(), 'tags': _joi2.default.optional(), 'manufacturerId': _joi2.default.optional(), 'gameSystemId': _joi2.default.optional(), 'category': _joi2.default.string().required() } } }, 'handler': _handlers.newsPosts.create }, { 'method': 'PUT', 'path': '/api/newsPosts/{id}', 'config': { 'tags': ['api'], 'description': 'Update a newsPost by id', 'notes': 'Update a newsPost by id', 'auth': { 'strategy': 'jsonWebToken', 'scope': ['newsContributor', 'systemAdmin'] }, 'validate': { 'params': { 'id': _joi2.default.number().required() }, 'payload': { 'id': _joi2.default.optional(), 'createdAt': _joi2.default.optional(), 'updatedAt': _joi2.default.optional(), 'ManufacturerId': _joi2.default.optional(), 'FactionId': _joi2.default.optional(), 'GameSystemId': _joi2.default.optional(), 'User': _joi2.default.optional(), 'Files': _joi2.default.optional(), 'UserId': _joi2.default.number().required(), 'title': _joi2.default.string().required(), 'callout': _joi2.default.string().required(), 'body': _joi2.default.string().required(), 'published': _joi2.default.boolean().required(), 'featured': _joi2.default.boolean().required(), 'tags': _joi2.default.optional(), 'manufacturerId': _joi2.default.optional(), 'gameSystemId': _joi2.default.optional(), 'category': _joi2.default.string().required() } } }, 'handler': _handlers.newsPosts.update }, { 'method': 'POST', 'path': '/api/search/newsPosts', 'config': { 'tags': ['api'], 'description': 'Return News Post search results', 'notes': 'Return News Post search results', 'validate': { 'payload': { 'maxResults': _joi2.default.optional(), 'searchQuery': _joi2.default.optional(), 'orderBy': _joi2.default.string().required(), 'searchBy': _joi2.default.optional(), 'pageNumber': _joi2.default.number().required(), 'pageSize': _joi2.default.optional(), 'published': _joi2.default.optional() } } }, 'handler': _handlers.newsPosts.search }, { 'method': 'DELETE', 'path': '/api/newsPosts/{id}', 'config': { 'tags': ['api'], 'description': 'Delete a newsPost by id', 'notes': 'Delete a newsPost by id', 'auth': { 'strategy': 'jsonWebToken', 'scope': ['newsContributor', 'systemAdmin'] }, 'validate': { 'params': { 'id': _joi2.default.number().required() } } }, 'handler': _handlers.newsPosts.delete }];
mit
i-den/SoftwareUniversity
Software University/04) PHP Web Development Basics/14) OOP FUNDAMENTS PART II - Exercises/05. Mass Effect/index.php
174
<?php use Game\Game; use Models\Ships\Cruiser; use Models\Ships\Dreadnought; use Models\Ships\Frigate; require './Core/autoload.php'; $game = new Game(); $game->start();
mit
Gushh/Viteltonemia
js/app.js
11263
var firstTimePhrases = [ 'Mmm, qué olor a pito. Te hubieses lavado los dientes por lo menos.', 'Wow sos un boludo que piensa que un micrófono puede detectar olores. ¿Qué te pensás, que estamos en el 2025? Forro.', 'Su soplido ha sido guardado con éxito. En 25 años lo vamos a clonar y alimentar a base de vitel toné' ]; var otherPhrases = [ 'No le cuentes a nadie que acabás de hacer esto porque vas quedar como un pelotudo.', 'Qué bien que soplás, deberías tocar la trompeta.', 'Ah, vos soplás cualquier cosa que te pongan enfrente.', 'Felicitaciones, sos el soplador número 1000. Te ganaste dos entradas para ir a ver Los Soplanos.', 'Ahora tenés un poco de tu baba en tu micrófono.', 'Te salió 0,25 mg de pelotudo en sangre.', 'Estás libre de vitel toné. No. No es un error. Si comiste vitel toné y no te dio positivo, es porque técnicamente estaba mal la receta.', 'Tu aliento a vitel toné no pudo ser procesado. Volvé a soplar pero como diciendo la letra “A” en secreto, tipo el sonido de los estadios alentando. Gracias.', 'Tenés que ir al dentista, se nota. Buscá en Google al Dr. Mendelbaum. Es muy bueno.', 'Pasaste el test de viteltonemia pero vas a tener que hacer el de pionononemia' ]; var finalPhrase = 'Bueno, ya está. Andá un ratito con tu familia. <br><br> Si no querés ser el único pelotudo que haya hecho esto, pasáselo a un amigo.'; var context, enabledToProccess = false, isRunning = false, successFull = false phraseCounter = 0, finished = false, errorCunter = 0; var CookiesOMG = Cookies.noConflict(); function canvasFillRect(leftX, topY, width, height) { var gradient = getCanvas().getContext('2d').createLinearGradient(0,0,0,300); gradient.addColorStop(1,'#656565'); gradient.addColorStop(0.75,'#656565'); gradient.addColorStop(0.25,'#CCC'); gradient.addColorStop(0,'#656565'); getCanvas().getContext('2d').fillStyle=gradient; getCanvas().getContext('2d').fillRect(leftX, topY, width, height); } function canvasInitialize(width, height) { getCanvas().getContext('2d').strokeStyle='#00FF00'; // Set canvas parameters getCanvas().width = width; getCanvas().height = height; // Outline getCanvas().getContext('2d').clearRect(0,0,width,height); getCanvas().getContext('2d').rect(0,0,width,height); getCanvas().getContext('2d').stroke(); } function onSuccess(stream) { // console.log(stream); // stream -> mediaSource -> javascriptNode -> destination context = new AudioContext(); var mediaStreamSource = context.createMediaStreamSource(stream); var analyser = context.createAnalyser(); analyser.smoothingTimeConstant = 0.3; analyser.fftSize = 2048; var javascriptNode = context.createScriptProcessor(2048, 1, 1); mediaStreamSource.connect(analyser); analyser.connect(javascriptNode); javascriptNode.connect(context.destination); javascriptNode.onaudioprocess = createProcessBuffer(analyser); } function createProcessBuffer(analyser) { var fftData = 0; return function processBuffer(fftData) { // console.log('transmiting...'); var fftData = 0; fftData = new Uint8Array(analyser.frequencyBinCount); // console.log(fftData); analyser.getByteFrequencyData(fftData); var width = $('#canvasContainer').width(); // console.log(); // clear canvas and draw border canvasInitialize(width,300); var average = 0; var length = fftData.length; for(var i=0; i < length; i++) { var sample = fftData[i]; canvasFillRect(i*5, 250-sample, 3, sample); average = average + sample; } // console.log(analyser.fftSize); average = average/length; if (enabledToProccess) { if (average > 25) { runCountDown(); } else { stopCountDown(); } } } // getLog().innerHTML = 'FFT Length:'+fftData.length + ' Average:' + average + '\n<br>'; } function onError() { $('#howTo').html('<strong>Error:</strong> Necesitamos usar tu micrófono').addClass('animated fadeInDown show'); $('#howTo2').removeClass('show').addClass('hide'); } // function getLog() { // return document.getElementById('mylog'); // } function getCanvas() { return document.getElementById('breath'); } function appStart() { $('#home').addClass('animated fadeOutRight hide'); // Preparando test... $('#loader').removeClass('hide').addClass('fadeInUpBig show') setTimeout(function () { $('#loader').removeClass('fadeInDownBig show').addClass('fadeOutUpBig hide'); $('#howTo').html('Acercate bien al micrófono y soplá constante durante 3 segundos').addClass('animated fadeInDown show'); $('#howTo2').addClass('animated fadeInDown show'); $('#breath').addClass('animated fadeInUp show'); var dataObject = {video: false, audio: true}; // dataObject.video, dataObject.audio if(navigator.getUserMedia) { navigator.getUserMedia(dataObject, onSuccess, onError); } else if(navigator.webkitGetUserMedia) { navigator.webkitGetUserMedia(dataObject, onSuccess, onError); } }, 3000); } function runCountDown () { if (!isRunning) { // console.log('Inicia contador'); isRunning = true; // console.log('creamos timeoutId'); timeoutId = setTimeout(badBreath, 1000); } } function stopCountDown () { if (isRunning) { isRunning = false; clearTimeout(timeoutId); // console.log('clearTimeout y isRunning:', isRunning); if (!successFull) { if (errorCunter === 0) { $('#howTo').removeClass('fadeInDown').addClass('shake'); errorCunter++; } else { if ($('#howTo').hasClass('shake')) { $('#howTo').removeClass('shake').addClass('flash'); } else { $('#howTo').removeClass('flash').addClass('shake'); } } // console.log('soplá 3 segundos seguidos papu!'); navigator.vibrate(1000); } } } function badBreath () { // console.log('suspendContext'); successFull = true; stopCountDown(); enabledToProccess = false; phraseCounter++; // console.log('comprobando counter', counter); var counter = CookiesOMG.get('counter'); counter++; CookiesOMG.set('counter', counter); if (CookiesOMG.get('counter') == 5) { var message = getRandomMessage(otherPhrases); otherPhrases.splice($.inArray(message, otherPhrases),1); CookiesOMG.set('otherPhrases', otherPhrases); var message = message + '<br/><br/>' + finalPhrase; finished = true; } else if (CookiesOMG.get('counter') == 1) { var message = getRandomMessage(firstTimePhrases); firstTimePhrases.splice($.inArray(message, firstTimePhrases),1); } else { var message = getRandomMessage(otherPhrases); otherPhrases.splice($.inArray(message, otherPhrases),1); CookiesOMG.set('otherPhrases', otherPhrases); } context.close().then(function() { $('#howTo').removeClass('fadeInDown show shake flash').addClass('bounceOutUp hide'); $('#howTo2').removeClass('fadeInDown show').addClass('bounceOutDown hide'); $('#breath').removeClass('fadeInUp show').addClass('bounceOutUp hide'); // $('#home').addClass('animated fadeOut hide'); $('#phrase').html('Estamos procesando tu baba...'); $('#phrase').addClass('animated bounceInUp show'); $('#result').addClass('animated bounceInUp show'); setTimeout(function () { $('footer').addClass('bottom'); $('#result').addClass('bounceInUp show'); $('#phrase').html(message); $('#phrase').removeClass('bounceInUp').addClass('fadeOut').removeClass('fadeOut').addClass('fadeIn') $('#twitter').removeClass('hide').addClass('animated fadeInLeftBig show'); $('#facebook').removeClass('hide').addClass('animated fadeInRightBig show'); if (finished) { $('#finish').addClass('animated fadeInUpBig show'); $('#links').addClass('animated fadeInDownBig show'); } else { $('#repeat').addClass('animated fadeInUpBig show'); } }, 3000); }); } function getRandomMessage(messages){ var rand = Math.random(); var length = messages.length; return messages[Math.floor(rand * length)]; // RANDOM LETTERS // var text = ""; // if (firsTime) { // var possible = "abc"; // } else { // var possible = "abcdefghij"; // } // return possible.charAt(Math.floor(Math.random() * possible.length)); } jQuery(function ($) { var currentBrowser = $.browserDetection(true); if (currentBrowser != 'Chrome') { $('#browserError').removeClass('hide').addClass('show'); } else { $('#start').removeClass('hide').addClass('show'); } $('#errorRepeat').on('click', function (e) { CookiesOMG.set('errorRepeat', 1); location.reload(); e.preventDefault(); }) $('#twitter, #twitterHome').on('click', function (e) { var url = 'http://viteltonemia.com'; var description = encodeURIComponent('¿Sentís que te comiste a Papá Noel entero? Medí tu concentración de Vitel Toné en sangre acá goo.gl/oZXVZ4') var sharer = 'https://twitter.com/intent/tweet?text=' + description + '&hashtags=TestDeViteltonemia'; window.open(sharer, true, 600, 300); e.preventDefault(); }) $('#facebook, #facebookHome').on('click', function (e) { var url = encodeURIComponent('https://perdonemifrances.com.ar/viteltonemia/'); var title = encodeURIComponent('Perdone mi francés | Test de Viteltonemia'); var description = encodeURIComponent('Test de Viteltonemia description'); var image = encodeURIComponent('https://perdonemifrances.com.ar/viteltonemia/img/fb.jpg'); var sharer = 'https://www.facebook.com/sharer.php?u=' + url; window.open(sharer, true, 600, 300); e.preventDefault(); }) // Check vibration api var supportsVibrate = "vibrate" in navigator; // counter = CookiesOMG.get('counter'); var val = CookiesOMG.get('counter'); var errorRepeat = CookiesOMG.get('errorRepeat'); if (errorRepeat === undefined) { CookiesOMG.set('errorRepeat', 0); } if (val === undefined || val == 5) { CookiesOMG.set('firstTimePhrases', firstTimePhrases); CookiesOMG.set('otherPhrases', otherPhrases); CookiesOMG.set('counter', 0); } else { firstTimePhrases = CookiesOMG.getJSON('firstTimePhrases'); otherPhrases = CookiesOMG.getJSON('otherPhrases'); } if (errorRepeat == 1) { $('#home').addClass('hide'); CookiesOMG.set('errorRepeat', 0); enabledToProccess = true; appStart(); } if (val > 0 && val != 5) { $('#home').addClass('hide'); enabledToProccess = true; appStart(); } $('#start').on('click', function (e) { $(this).addClass('animated bounceOutLeft'); enabledToProccess = true; appStart(); e.preventDefault(); }) $('#repeat').on('click', function (e) { location.reload(); e.preventDefault(); }) });
mit
Dario2023/Programacion4
Funcion Actualizar Condicion.php
1833
<?php function actualizarCondicion(&$notas,&$asistencia){ // 3)Completar la condición de cada alumno foreach ($notas as $nroPersona => $value) { // <--- recorro los id alumnos if ((($notas[$nroPersona] ["parcial_1"] + $notas[$nroPersona] ["parcial_2"])/2)<=6) { // <--- desaprobaron parciales if ((($notas[$nroPersona] ["parcial_1"] + $notas[$nroPersona] ["parcial_2"] + $notas[$nroPersona] ["recuperatorio"])/3)<=6){ // <--- desaprobaron recuperatorio $asistencia[$nroPersona] ["condicion"] = "libre";// <---guardo en array asistencia los libres } else { $asistencia[$nroPersona] ["condicion"] = "regular";} // <---guardo en array asistencia los aprobados en recuperatorios } else if ((($notas[$nroPersona] ["parcial_1"] + $notas[$nroPersona] ["parcial_2"])/2)>=8) { $asistencia[$nroPersona] ["condicion"] = "promocional";// <---guardo en array asistencia los promocionales } else {$asistencia[$nroPersona] ["condicion"] = "regular";}// <---guardo en array asistencia los regular } //condicion segun la asistencia foreach ($asistencia as $Alumn => $VALUE) { // <---recorro alumno foreach ($VALUE as $key => $val) { $ausente=0; $totalDia=0; if (is_array($val)){ // <--- si es el array (fecha) foreach ($val as $fecha => $asist) { // <---recorro las fechas if ($asist =="a"){ // <---total ausente $ausente+=1; // <---contador ausente } $totalDia+=1; // <---total dia contador } if (($ausente /$totalDia * 100) >= 20) { // <--- si el total 20% de falta quedan libres $asistencia[$Alumn] ["condicion"] = "libre"; } } } } } ?>
mit
jeeyoungk/exercise
java/src/main/java/com/kimjeeyoung/datastruct/LinkedQueue.java
858
// Copyright 2015 Square, Inc. package com.kimjeeyoung.datastruct; import java.util.NoSuchElementException; /** * Queue implemented in linked list */ public class LinkedQueue<T> implements Queue<T> { private static final class Node<T> { T value; Node<T> next; } private Node<T> head; private Node<T> tail; public LinkedQueue() { } public void add(T value) { Node<T> newTail = new Node<>(); newTail.value = value; synchronized (this) { if (head == null) { head = newTail; } if (tail != null) { tail.next = newTail; } tail = newTail; } } public T pop() { synchronized (this) { if (head != null) { T value = head.value; head = head.next; return value; } else { throw new NoSuchElementException(); } } } }
mit
spreemo/bcrypt_hmac
lib/bcrypt_hmac.rb
1163
require 'devise' require 'devise-encryptable' require 'bcrypt' require 'bcrypt_hmac/railtie' if defined?(Rails) module BcryptHmac class Encryptor < Devise::Encryptable::Encryptors::Base def self.digest(password, stretches = nil, _salt = nil, pepper = nil) pre_bcrypt_hash = prepare_for_bcrypt(password, pepper.to_s) if stretches BCrypt::Password.create(pre_bcrypt_hash, cost: stretches.to_i) else BCrypt::Password.create(pre_bcrypt_hash) end end def self.compare(encrypted_password, password, _stretches = nil, _salt = nil, pepper = nil) saved_password = BCrypt::Password.new(encrypted_password) proposed_password = prepare_for_bcrypt(password, pepper.to_s) saved_password == proposed_password end def self.prepare_for_bcrypt(password, hmac_key) Base64.encode64(sha256_hash(password, hmac_key)) end private_class_method :prepare_for_bcrypt def self.sha256_hash(password, hmac_key) sha256 = OpenSSL::Digest.new('sha256') OpenSSL::HMAC.digest(sha256, hmac_key, password) end private_class_method :sha256_hash end end
mit
nazar/wasters
vendor/gems/ri_cal-0.8.5/spec/spec_helper.rb
1505
#- ©2009 Rick DeNatale, All rights reserved. Refer to the file README.txt for the license require File.expand_path(File.join(File.dirname(__FILE__), %w[.. lib ri_cal])) require 'cgi' require 'tzinfo' module Kernel if ENV.keys.find {|env_var| env_var.match(/^TM_/)} def rputs(*args) puts( *["<pre>", args.collect {|a| CGI.escapeHTML(a.to_s)}, "</pre>"]) end else alias_method :rputs, :puts end end def date_time_with_zone(date_time, tzid = "US/Eastern") date_time.dup.set_tzid(tzid) end def dt_prop(date_time, tzid = "US/Eastern") RiCal::PropertyValue::DateTime.convert(nil, date_time_with_zone(date_time, tzid)) end def offset_for_tzid(year, month, day, hour, min, sec, tzid, alternate) tz = TZInfo::Timezone.get(tzid) rescue nil if tz Rational(tz.period_for_local(DateTime.civil(year, month, day, hour, min, sec)).utc_total_offset, 86400) else provided_offset end end def rectify_ical(string) string.gsub(/^\s+/, "") end if RiCal::TimeWithZone def result_time_in_zone(year, month, day, hour, min, sec, tzid, alternate_offset = nil) DateTime.civil(year, month, day, hour, min, sec, offset_for_tzid(year, month, day, hour, min, sec, tzid, alternate_offset)).in_time_zone(tzid) end else def result_time_in_zone(year, month, day, hour, min, sec, tzid, alternate_offset = nil) DateTime.civil(year, month, day, hour, min, sec, offset_for_tzid(year, month, day, hour, min, sec, tzid, alternate_offset)).set_tzid(tzid) end end
mit
markusjohnsson/cil.js
Tests/ComparisonTests/IsInstInterface.cs.ciljs.exe.js
12531
var CILJS = require("../CilJs.Runtime/Runtime"); var asm1 = {}; var asm = asm1; var asm0 = CILJS.findAssembly("mscorlib"); asm.FullName = "IsInstInterface.cs.ciljs, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null";/* A..ctor()*/ asm.x6000001 = function _ctor(arg0) { /* IL_00: ldarg.0 */ /* IL_01: call Void .ctor() */ /* IL_06: nop */ /* IL_07: ret */ return ; };;/* B..ctor()*/ asm.x6000002 = function _ctor(arg0) { /* IL_00: ldarg.0 */ /* IL_01: call Void .ctor() */ asm1.x6000001(arg0); /* IL_06: nop */ /* IL_07: ret */ return ; };;/* C..ctor()*/ asm.x6000003 = function _ctor(arg0) { /* IL_00: ldarg.0 */ /* IL_01: call Void .ctor() */ asm1.x6000001(arg0); /* IL_06: nop */ /* IL_07: ret */ return ; };;/* D..ctor()*/ asm.x6000004 = function _ctor(arg0) { /* IL_00: ldarg.0 */ /* IL_01: call Void .ctor() */ asm1.x6000003(arg0); /* IL_06: nop */ /* IL_07: ret */ return ; };;/* static System.Void Program.Main()*/ asm.x6000005_init = function () { (asm1.A().init)(); (asm1.B().init)(); (asm1.C().init)(); (asm1.D().init)(); asm.x6000005 = asm.x6000005_; };; asm.x6000005 = function () { asm.x6000005_init(); return asm.x6000005_(); };; asm.x6000005_ = function Main() { var t0; var t1; var t2; var t3; CILJS.initBaseTypes(); t0 = asm1.A(); t1 = asm1.B(); t2 = asm1.C(); t3 = asm1.D(); /* IL_00: nop */ /* IL_01: newobj Void .ctor() */ /* IL_06: call Void TestImpl(System.Object) */ asm1.x6000006(CILJS.newobj(t0,asm1.x6000001,[null])); /* IL_0B: nop */ /* IL_0C: newobj Void .ctor() */ /* IL_11: call Void TestImpl(System.Object) */ asm1.x6000006(CILJS.newobj(t1,asm1.x6000002,[null])); /* IL_16: nop */ /* IL_17: newobj Void .ctor() */ /* IL_1C: call Void TestImpl(System.Object) */ asm1.x6000006(CILJS.newobj(t2,asm1.x6000003,[null])); /* IL_21: nop */ /* IL_22: newobj Void .ctor() */ /* IL_27: call Void TestImpl(System.Object) */ asm1.x6000006(CILJS.newobj(t3,asm1.x6000004,[null])); /* IL_2C: nop */ /* IL_2D: ret */ return ; };/* static System.Void Program.TestImpl(Object)*/ asm.x6000006_init = function (arg0) { (asm1.I1().init)(); (asm1.I2().init)(); (asm1.I3().init)(); asm.x6000006 = asm.x6000006_; };; asm.x6000006 = function (arg0) { asm.x6000006_init(arg0); return asm.x6000006_(arg0); };; asm.x6000006_ = function TestImpl(arg0) { var t0; var t1; var t2; var t3; var st_02; var st_03; var st_04; var st_07; var st_08; var st_09; var st_0C; var st_0D; var st_0E; var in_block_0; var __pos__; t0 = asm1.I1(); t1 = asm0["System.Object"](); t2 = asm1.I2(); t3 = asm1.I3(); in_block_0 = true; __pos__ = 0x0; while (in_block_0){ switch (__pos__){ case 0x0: /* IL_00: nop */ /* IL_01: ldarg.0 */ /* IL_02: isinst I1 */ /* IL_07: brtrue.s IL_10 */ if (t0.IsInst(arg0)){ __pos__ = 0x10; continue; } /* IL_09: ldstr false */ st_03 = CILJS.newString("false"); /* IL_0E: br.s IL_15 */ __pos__ = 0x15; continue; case 0x10: /* IL_10: ldstr true */ st_03 = CILJS.newString("true"); case 0x15: /* IL_15: ldc.i4.0 */ st_02 = 0; /* IL_16: newarr System.Object */ st_04 = CILJS.newArray(t1,st_02); /* IL_1B: call Void WriteLine(System.String, System.Object[]) */ asm0.x6000073(st_03,st_04); /* IL_20: nop */ /* IL_21: ldarg.0 */ /* IL_22: isinst I2 */ /* IL_27: brtrue.s IL_30 */ if (t2.IsInst(arg0)){ __pos__ = 0x30; continue; } /* IL_29: ldstr false */ st_08 = CILJS.newString("false"); /* IL_2E: br.s IL_35 */ __pos__ = 0x35; continue; case 0x30: /* IL_30: ldstr true */ st_08 = CILJS.newString("true"); case 0x35: /* IL_35: ldc.i4.0 */ st_07 = 0; /* IL_36: newarr System.Object */ st_09 = CILJS.newArray(t1,st_07); /* IL_3B: call Void WriteLine(System.String, System.Object[]) */ asm0.x6000073(st_08,st_09); /* IL_40: nop */ /* IL_41: ldarg.0 */ /* IL_42: isinst I3 */ /* IL_47: brtrue.s IL_50 */ if (t3.IsInst(arg0)){ __pos__ = 0x50; continue; } /* IL_49: ldstr false */ st_0D = CILJS.newString("false"); /* IL_4E: br.s IL_55 */ __pos__ = 0x55; continue; case 0x50: /* IL_50: ldstr true */ st_0D = CILJS.newString("true"); case 0x55: /* IL_55: ldc.i4.0 */ st_0C = 0; /* IL_56: newarr System.Object */ st_0E = CILJS.newArray(t1,st_0C); /* IL_5B: call Void WriteLine(System.String, System.Object[]) */ asm0.x6000073(st_0D,st_0E); /* IL_60: nop */ /* IL_61: ret */ return ; } } };/* Program..ctor()*/ asm.x6000007 = function _ctor(arg0) { /* IL_00: ldarg.0 */ /* IL_01: call Void .ctor() */ /* IL_06: nop */ /* IL_07: ret */ return ; };; asm.I1 = CILJS.declareType( [], function () { return {}; }, function (type) { type.init = CILJS.nop; CILJS.initType(type,asm,"I1",false,false,true,false,false,[],[],null,CILJS.isInstInterface(type),Array,"asm1.t2000002",null); type.TypeMetadataName = "asm1.t2000002"; }, function () { return function I1() { I1.init(); }; }); asm.I2 = CILJS.declareType( [], function () { return {}; }, function (type) { type.init = CILJS.nop; CILJS.initType(type,asm,"I2",false,false,true,false,false,[],[],null,CILJS.isInstInterface(type),Array,"asm1.t2000003",null); type.TypeMetadataName = "asm1.t2000003"; }, function () { return function I2() { I2.init(); }; }); asm.I3 = CILJS.declareType( [], function () { return {}; }, function (type) { type.init = CILJS.nop; CILJS.initType(type,asm,"I3",false,false,true,false,false,[],[],null,CILJS.isInstInterface(type),Array,"asm1.t2000004",null); type.TypeMetadataName = "asm1.t2000004"; CILJS.implementInterface( type, [asm1.I2()], null); }, function () { return function I3() { I3.init(); }; }); asm.A = CILJS.declareType( [], function () { return asm0["System.Object"](); }, function (type) { type.init = CILJS.nop; CILJS.initType(type,asm,"A",false,false,false,false,false,[],[],asm0["System.Object"](),CILJS.isInstDefault(type),Array,"asm1.t2000005",null); type.TypeMetadataName = "asm1.t2000005"; CILJS.declareVirtual(type,"asm0.x600009b",asm0,"x600009b"); CILJS.declareVirtual(type,"asm0.x600009e",asm0,"x600009e"); CILJS.declareVirtual(type,"asm0.x600009f",asm0,"x600009f"); }, function () { return function A() { A.init(); }; }); asm.B = CILJS.declareType( [], function () { return asm1.A(); }, function (type) { type.init = CILJS.nop; CILJS.initType(type,asm,"B",false,false,false,false,false,[],[],asm1.A(),CILJS.isInstDefault(type),Array,"asm1.t2000006",null); type.TypeMetadataName = "asm1.t2000006"; CILJS.declareVirtual(type,"asm0.x600009b",asm0,"x600009b"); CILJS.declareVirtual(type,"asm0.x600009e",asm0,"x600009e"); CILJS.declareVirtual(type,"asm0.x600009f",asm0,"x600009f"); CILJS.implementInterface( type, [asm1.I1()], []); CILJS.implementInterface( type, [asm1.I2()], []); }, function () { return function B() { B.init(); }; }); asm.C = CILJS.declareType( [], function () { return asm1.A(); }, function (type) { type.init = CILJS.nop; CILJS.initType(type,asm,"C",false,false,false,false,false,[],[],asm1.A(),CILJS.isInstDefault(type),Array,"asm1.t2000007",null); type.TypeMetadataName = "asm1.t2000007"; CILJS.declareVirtual(type,"asm0.x600009b",asm0,"x600009b"); CILJS.declareVirtual(type,"asm0.x600009e",asm0,"x600009e"); CILJS.declareVirtual(type,"asm0.x600009f",asm0,"x600009f"); CILJS.implementInterface( type, [asm1.I3()], []); CILJS.implementInterface( type, [asm1.I2()], []); }, function () { return function C() { C.init(); }; }); asm.D = CILJS.declareType( [], function () { return asm1.C(); }, function (type) { type.init = CILJS.nop; CILJS.initType(type,asm,"D",false,false,false,false,false,[],[],asm1.C(),CILJS.isInstDefault(type),Array,"asm1.t2000008",null); type.TypeMetadataName = "asm1.t2000008"; CILJS.declareVirtual(type,"asm0.x600009b",asm0,"x600009b"); CILJS.declareVirtual(type,"asm0.x600009e",asm0,"x600009e"); CILJS.declareVirtual(type,"asm0.x600009f",asm0,"x600009f"); CILJS.implementInterface( type, [asm1.I2()], []); CILJS.implementInterface( type, [asm1.I3()], []); }, function () { return function D() { D.init(); }; }); asm.Program = CILJS.declareType( [], function () { return asm0["System.Object"](); }, function (type) { type.init = CILJS.nop; CILJS.initType(type,asm,"Program",false,false,false,false,false,[],[],asm0["System.Object"](),CILJS.isInstDefault(type),Array,"asm1.t2000009",null); type.TypeMetadataName = "asm1.t2000009"; CILJS.declareVirtual(type,"asm0.x600009b",asm0,"x600009b"); CILJS.declareVirtual(type,"asm0.x600009e",asm0,"x600009e"); CILJS.declareVirtual(type,"asm0.x600009f",asm0,"x600009f"); }, function () { return function Program() { Program.init(); }; }); asm.entryPoint = asm.x6000005; CILJS.declareAssembly("IsInstInterface.cs.ciljs",asm); if (typeof module != "undefined"){ module.exports = asm1; } //# sourceMappingURL=IsInstInterface.cs.ciljs.exe.js.map
mit
ChilliConnect/Samples
UnitySamples/PushNotifications/Assets/ChilliConnect/GeneratedSource/Responses/LogInUsingFacebookResponse.cs
4049
// // This file was auto-generated using the ChilliConnect SDK Generator. // // The MIT License (MIT) // // Copyright (c) 2015 Tag Games Ltd // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using SdkCore; namespace ChilliConnect { /// <summary> /// A container for information on the response from a LogInUsingFacebookRequest. /// </summary> public sealed class LogInUsingFacebookResponse { /// <summary> /// The player's ChilliConnectID. /// </summary> public string ChilliConnectId { get; private set; } /// <summary> /// The player's ChilliConnectSecret. /// </summary> public string ChilliConnectSecret { get; private set; } /// <summary> /// The player's Facebook account ID. /// </summary> public string FacebookId { get; private set; } /// <summary> /// The player's Facebook account name. /// </summary> public string FacebookName { get; private set; } /// <summary> /// Initialises the response with the given json dictionary. /// </summary> /// /// <param name="jsonDictionary">The dictionary containing the JSON data.</param> public LogInUsingFacebookResponse(IDictionary<string, object> jsonDictionary) { ReleaseAssert.IsNotNull(jsonDictionary, "JSON dictionary cannot be null."); ReleaseAssert.IsTrue(jsonDictionary.ContainsKey("ChilliConnectID"), "Json is missing required field 'ChilliConnectID'"); ReleaseAssert.IsTrue(jsonDictionary.ContainsKey("ChilliConnectSecret"), "Json is missing required field 'ChilliConnectSecret'"); ReleaseAssert.IsTrue(jsonDictionary.ContainsKey("FacebookID"), "Json is missing required field 'FacebookID'"); ReleaseAssert.IsTrue(jsonDictionary.ContainsKey("FacebookName"), "Json is missing required field 'FacebookName'"); foreach (KeyValuePair<string, object> entry in jsonDictionary) { // Chilli Connect Id if (entry.Key == "ChilliConnectID") { ReleaseAssert.IsTrue(entry.Value is string, "Invalid serialised type."); ChilliConnectId = (string)entry.Value; } // Chilli Connect Secret else if (entry.Key == "ChilliConnectSecret") { ReleaseAssert.IsTrue(entry.Value is string, "Invalid serialised type."); ChilliConnectSecret = (string)entry.Value; } // Facebook Id else if (entry.Key == "FacebookID") { ReleaseAssert.IsTrue(entry.Value is string, "Invalid serialised type."); FacebookId = (string)entry.Value; } // Facebook Name else if (entry.Key == "FacebookName") { ReleaseAssert.IsTrue(entry.Value is string, "Invalid serialised type."); FacebookName = (string)entry.Value; } // Connect Access Token else if (entry.Key == "ConnectAccessToken") { //Do nothing } } } } }
mit
i8wu/Converrency
android/app/src/main/java/com/converrency/MainActivity.java
367
package com.converrency; import com.facebook.react.ReactActivity; public class MainActivity extends ReactActivity { /** * Returns the name of the main component registered from JavaScript. * This is used to schedule rendering of the component. */ @Override protected String getMainComponentName() { return "Converrency"; } }
mit
krzysztofkolek/github-bugtracker
client/src/components/HomeComponent.js
461
'use strict'; require('styles//Home.css'); import React from 'react'; import { connect } from "react-redux" @connect((store) => { return { }; }) class HomeComponent extends React.Component { propTypes: { } defaultProps: { } constructor(props) { super(props); } render() { return ( <div className="home-component"> </div> ); } } HomeComponent.displayName = 'HomeComponent'; export default HomeComponent;
mit
lucionei/chamadotecnico
chamadosTecnicosFinal-app/node_modules/date-fns/esm/fp/getOverlappingDaysInIntervalsWithOptions/index.js
333
// This file is generated automatically by `scripts/build/fp.js`. Please, don't change it. import fn from '../../getOverlappingDaysInIntervals/index.js' import convertToFP from '../_lib/convertToFP/index.js' var getOverlappingDaysInIntervalsWithOptions = convertToFP(fn, 3) export default getOverlappingDaysInIntervalsWithOptions
mit
rberec/AlgorithmsCourse
src/UnionFind.cpp
1228
#include "UnionFind.hpp" void UnionFind::connect(uint64_t p, uint64_t q) { doConnect(p, q); } bool UnionFind::connected(uint64_t p, uint64_t q) { return doConnected(p, q); } bool QuickFindUF::doConnected(uint64_t p, uint64_t q) { return id_[p] == id_[q]; } void QuickFindUF::doConnect(uint64_t p, uint64_t q) { uint64_t pid = id_[p]; uint64_t qid = id_[q]; for (uint64_t i = 0; i < id_.size(); ++i) if (id_[i] == pid) id_[i] = qid; } uint64_t QuickUnionUF::root(uint64_t p) { while (p != id_[p]) p = id_[p]; return p; } bool QuickUnionUF::doConnected(uint64_t p, uint64_t q) { return root(p) == root(q); } void QuickUnionUF::doConnect(uint64_t p, uint64_t q) { uint64_t pid = root(p); uint64_t qid = root(q); id_[pid] = qid; } void WeightedQuickUnionUF::doConnect(uint64_t p, uint64_t q) { uint64_t pid = root(p); uint64_t qid = root(q); if (w_[pid] > w_[qid]) { id_[qid] = pid; w_[pid] += w_[qid]; } else { id_[pid] = qid; w_[qid] += w_[pid]; } } uint64_t PathCompressionWeightedQuickUnionUF::root(uint64_t p) { while (p != id_[p]) { id_[p] = id_[id_[p]]; p = id_[p]; } return p; }
mit
fredericlefeurmou/utravel
src/UTravel/AdminBundle/Entity/WelcomeWidget.php
1476
<?php namespace UTravel\AdminBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * WelcomeWidget * * @ORM\Table(name="widget") * @ORM\Entity */ class WelcomeWidget { /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var boolean * * @ORM\Column(name="is_video", type="boolean") */ private $isVideo; /** * @var string * * @ORM\Column(name="iframe_link", type="string", length=511, nullable=true) */ private $iframeLink; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set isVideo * * @param boolean $isVideo * @return WelcomeWidget */ public function setIsVideo($isVideo) { $this->isVideo = $isVideo; return $this; } /** * Get isVideo * * @return boolean */ public function getIsVideo() { return $this->isVideo; } /** * Set iframeLink * * @param string $iframeLink * @return WelcomeWidget */ public function setIframeLink($iframeLink) { $this->iframeLink = $iframeLink; return $this; } /** * Get iframeLink * * @return string */ public function getIframeLink() { return $this->iframeLink; } }
mit
Michayal/michayal.github.io
node_modules/mathjs/src/entry/dependenciesAny/dependenciesUnitClass.generated.js
1593
/** * THIS FILE IS AUTO-GENERATED * DON'T MAKE CHANGES HERE */ import { BigNumberDependencies } from './dependenciesBigNumberClass.generated' import { ComplexDependencies } from './dependenciesComplexClass.generated' import { FractionDependencies } from './dependenciesFractionClass.generated' import { absDependencies } from './dependenciesAbs.generated' import { addScalarDependencies } from './dependenciesAddScalar.generated' import { divideScalarDependencies } from './dependenciesDivideScalar.generated' import { equalDependencies } from './dependenciesEqual.generated' import { fixDependencies } from './dependenciesFix.generated' import { formatDependencies } from './dependenciesFormat.generated' import { isNumericDependencies } from './dependenciesIsNumeric.generated' import { multiplyScalarDependencies } from './dependenciesMultiplyScalar.generated' import { numberDependencies } from './dependenciesNumber.generated' import { powDependencies } from './dependenciesPow.generated' import { roundDependencies } from './dependenciesRound.generated' import { subtractDependencies } from './dependenciesSubtract.generated' import { createUnitClass } from '../../factoriesAny.js' export const UnitDependencies = { BigNumberDependencies, ComplexDependencies, FractionDependencies, absDependencies, addScalarDependencies, divideScalarDependencies, equalDependencies, fixDependencies, formatDependencies, isNumericDependencies, multiplyScalarDependencies, numberDependencies, powDependencies, roundDependencies, subtractDependencies, createUnitClass }
mit
shalles/fepro
src/proTpl/gulp/src/scripts/app-1.js
605
// new project please excute // $ bower install && npm install // $ gulp // at project build/base path same as package.json // about require more see https://github.com/shalles/gulp-fecmd // or https://www.npmjs.com/package/gulp-fecmd or fecmd var $ = require('jquery!!'); var utils = require('lib/utils'); var Calc = require('./lib/file.es6'); var PlaceSuggestion = require('./lib/ps'); var tpl = require('./tpl/html.tpl') console.log(new Calc.Calc().add(11,22)); console.log('json', require('data/data.json')); var start = new PlaceSuggestion({ name: 'start' }, $('.m-place-suggest.js-start'));
mit
FreezyBee/DoctrineFormMapper
tests/Mock/Entity/TestDate.php
939
<?php declare(strict_types=1); /* * This file is part of the some package. * (c) Jakub Janata <[email protected]> * For the full copyright and license information, please view the LICENSE file. */ namespace FreezyBee\DoctrineFormMapper\Tests\Mock\Entity; use DateTime; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity */ class TestDate { /** * @var int * @ORM\Id * @ORM\Column(type="integer") * @ORM\GeneratedValue */ private $id; /** * @var DateTime * @ORM\Column(type="datetime") */ private $date; /** * @param DateTime $date */ public function __construct(DateTime $date) { $this->date = $date; } /** * @return int */ public function getId(): int { return $this->id; } /** * @return DateTime */ public function getDate(): DateTime { return $this->date; } }
mit
makskay/Tidy
src/me/makskay/tidy/commands/InvestigateCommand.java
3360
/* * Copyright (c) 2012 Max Kreminski * * 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.makskay.tidy.commands; import me.makskay.tidy.IssueManager; import me.makskay.tidy.IssueReport; import me.makskay.tidy.PlayerManager; import me.makskay.tidy.TidyPlugin; import org.bukkit.Location; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class InvestigateCommand implements CommandExecutor { private IssueManager issueManager; private PlayerManager playerManager; public InvestigateCommand(TidyPlugin plugin) { issueManager = plugin.getIssueManager(); playerManager = plugin.getPlayerManager(); } public boolean onCommand (CommandSender sender, Command command, String commandLabel, String[] args) { if (args.length != 1) { return false; // needs exactly one argument: issue ID } if (!(sender instanceof Player)) { sender.sendMessage(TidyPlugin.ERROR_COLOR + "Only a player may investigate issues!"); return true; } Player player = (Player) sender; int uid; try { uid = Integer.parseInt(args[0]); } catch (NumberFormatException ex) { if (!args[0].equalsIgnoreCase("-end")) { sender.sendMessage(TidyPlugin.ERROR_COLOR + "\"" + args[0] + "\" isn't a valid issue ID number!"); return true; } // handle a request to end the issue investigation Location location = playerManager.getSavedLocationOf(player); if (location == null) { player.sendMessage(TidyPlugin.ERROR_COLOR + "You aren't currently investigating any issues!"); return true; } player.teleport(location); playerManager.clearSavedLocationOf(player); player.sendMessage(TidyPlugin.NEUTRAL_COLOR + "Issue investigation ended."); return true; } IssueReport issue = issueManager.getIssue(uid); if (issue == null) { player.sendMessage(TidyPlugin.ERROR_COLOR + "Couldn't find issue #" + uid); return true; } playerManager.saveLocationOf(player); player.teleport(issue.getLocation()); player.sendMessage(TidyPlugin.NEUTRAL_COLOR + "Now investigating issue #" + uid); player.sendMessage(TidyPlugin.NEUTRAL_COLOR + "Type /investigate -end when you're done to return to where you left off."); return true; } }
mit
SingularInversions/FaceGenBaseLibrary
source/LibTpBoost/boost_1_67_0/boost/asio/ip/address_v6.hpp
10281
// // ip/address_v6.hpp // ~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef BOOST_ASIO_IP_ADDRESS_V6_HPP #define BOOST_ASIO_IP_ADDRESS_V6_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <string> #include <boost/asio/detail/array.hpp> #include <boost/asio/detail/socket_types.hpp> #include <boost/asio/detail/string_view.hpp> #include <boost/asio/detail/winsock_init.hpp> #include <boost/system/error_code.hpp> #include <boost/asio/ip/address_v4.hpp> #if !defined(BOOST_ASIO_NO_IOSTREAM) # include <iosfwd> #endif // !defined(BOOST_ASIO_NO_IOSTREAM) #include <boost/asio/detail/push_options.hpp> namespace boost { namespace asio { namespace ip { template <typename> class basic_address_iterator; /// Implements IP version 6 style addresses. /** * The boost::asio::ip::address_v6 class provides the ability to use and * manipulate IP version 6 addresses. * * @par Thread Safety * @e Distinct @e objects: Safe.@n * @e Shared @e objects: Unsafe. */ class address_v6 { public: /// The type used to represent an address as an array of bytes. /** * @note This type is defined in terms of the C++0x template @c std::array * when it is available. Otherwise, it uses @c boost:array. */ #if defined(GENERATING_DOCUMENTATION) typedef array<unsigned char, 16> bytes_type; #else typedef boost::asio::detail::array<unsigned char, 16> bytes_type; #endif /// Default constructor. BOOST_ASIO_DECL address_v6(); /// Construct an address from raw bytes and scope ID. BOOST_ASIO_DECL explicit address_v6(const bytes_type& bytes, unsigned long scope_id = 0); /// Copy constructor. BOOST_ASIO_DECL address_v6(const address_v6& other); #if defined(BOOST_ASIO_HAS_MOVE) /// Move constructor. BOOST_ASIO_DECL address_v6(address_v6&& other); #endif // defined(BOOST_ASIO_HAS_MOVE) /// Assign from another address. BOOST_ASIO_DECL address_v6& operator=(const address_v6& other); #if defined(BOOST_ASIO_HAS_MOVE) /// Move-assign from another address. BOOST_ASIO_DECL address_v6& operator=(address_v6&& other); #endif // defined(BOOST_ASIO_HAS_MOVE) /// The scope ID of the address. /** * Returns the scope ID associated with the IPv6 address. */ unsigned long scope_id() const { return scope_id_; } /// The scope ID of the address. /** * Modifies the scope ID associated with the IPv6 address. */ void scope_id(unsigned long id) { scope_id_ = id; } /// Get the address in bytes, in network byte order. BOOST_ASIO_DECL bytes_type to_bytes() const; /// Get the address as a string. BOOST_ASIO_DECL std::string to_string() const; #if !defined(BOOST_ASIO_NO_DEPRECATED) /// (Deprecated: Use other overload.) Get the address as a string. BOOST_ASIO_DECL std::string to_string(boost::system::error_code& ec) const; /// (Deprecated: Use make_address_v6().) Create an IPv6 address from an IP /// address string. static address_v6 from_string(const char* str); /// (Deprecated: Use make_address_v6().) Create an IPv6 address from an IP /// address string. static address_v6 from_string( const char* str, boost::system::error_code& ec); /// (Deprecated: Use make_address_v6().) Create an IPv6 address from an IP /// address string. static address_v6 from_string(const std::string& str); /// (Deprecated: Use make_address_v6().) Create an IPv6 address from an IP /// address string. static address_v6 from_string( const std::string& str, boost::system::error_code& ec); /// (Deprecated: Use make_address_v4().) Converts an IPv4-mapped or /// IPv4-compatible address to an IPv4 address. BOOST_ASIO_DECL address_v4 to_v4() const; #endif // !defined(BOOST_ASIO_NO_DEPRECATED) /// Determine whether the address is a loopback address. BOOST_ASIO_DECL bool is_loopback() const; /// Determine whether the address is unspecified. BOOST_ASIO_DECL bool is_unspecified() const; /// Determine whether the address is link local. BOOST_ASIO_DECL bool is_link_local() const; /// Determine whether the address is site local. BOOST_ASIO_DECL bool is_site_local() const; /// Determine whether the address is a mapped IPv4 address. BOOST_ASIO_DECL bool is_v4_mapped() const; #if !defined(BOOST_ASIO_NO_DEPRECATED) /// (Deprecated: No replacement.) Determine whether the address is an /// IPv4-compatible address. BOOST_ASIO_DECL bool is_v4_compatible() const; #endif // !defined(BOOST_ASIO_NO_DEPRECATED) /// Determine whether the address is a multicast address. BOOST_ASIO_DECL bool is_multicast() const; /// Determine whether the address is a global multicast address. BOOST_ASIO_DECL bool is_multicast_global() const; /// Determine whether the address is a link-local multicast address. BOOST_ASIO_DECL bool is_multicast_link_local() const; /// Determine whether the address is a node-local multicast address. BOOST_ASIO_DECL bool is_multicast_node_local() const; /// Determine whether the address is a org-local multicast address. BOOST_ASIO_DECL bool is_multicast_org_local() const; /// Determine whether the address is a site-local multicast address. BOOST_ASIO_DECL bool is_multicast_site_local() const; /// Compare two addresses for equality. BOOST_ASIO_DECL friend bool operator==( const address_v6& a1, const address_v6& a2); /// Compare two addresses for inequality. friend bool operator!=(const address_v6& a1, const address_v6& a2) { return !(a1 == a2); } /// Compare addresses for ordering. BOOST_ASIO_DECL friend bool operator<( const address_v6& a1, const address_v6& a2); /// Compare addresses for ordering. friend bool operator>(const address_v6& a1, const address_v6& a2) { return a2 < a1; } /// Compare addresses for ordering. friend bool operator<=(const address_v6& a1, const address_v6& a2) { return !(a2 < a1); } /// Compare addresses for ordering. friend bool operator>=(const address_v6& a1, const address_v6& a2) { return !(a1 < a2); } /// Obtain an address object that represents any address. static address_v6 any() { return address_v6(); } /// Obtain an address object that represents the loopback address. BOOST_ASIO_DECL static address_v6 loopback(); #if !defined(BOOST_ASIO_NO_DEPRECATED) /// (Deprecated: Use make_address_v6().) Create an IPv4-mapped IPv6 address. BOOST_ASIO_DECL static address_v6 v4_mapped(const address_v4& addr); /// (Deprecated: No replacement.) Create an IPv4-compatible IPv6 address. BOOST_ASIO_DECL static address_v6 v4_compatible(const address_v4& addr); #endif // !defined(BOOST_ASIO_NO_DEPRECATED) private: friend class basic_address_iterator<address_v6>; // The underlying IPv6 address. boost::asio::detail::in6_addr_type addr_; // The scope ID associated with the address. unsigned long scope_id_; }; /// Create an IPv6 address from raw bytes and scope ID. /** * @relates address_v6 */ inline address_v6 make_address_v6(const address_v6::bytes_type& bytes, unsigned long scope_id = 0) { return address_v6(bytes, scope_id); } /// Create an IPv6 address from an IP address string. /** * @relates address_v6 */ BOOST_ASIO_DECL address_v6 make_address_v6(const char* str); /// Create an IPv6 address from an IP address string. /** * @relates address_v6 */ BOOST_ASIO_DECL address_v6 make_address_v6( const char* str, boost::system::error_code& ec); /// Createan IPv6 address from an IP address string. /** * @relates address_v6 */ BOOST_ASIO_DECL address_v6 make_address_v6(const std::string& str); /// Create an IPv6 address from an IP address string. /** * @relates address_v6 */ BOOST_ASIO_DECL address_v6 make_address_v6( const std::string& str, boost::system::error_code& ec); #if defined(BOOST_ASIO_HAS_STRING_VIEW) \ || defined(GENERATING_DOCUMENTATION) /// Create an IPv6 address from an IP address string. /** * @relates address_v6 */ BOOST_ASIO_DECL address_v6 make_address_v6(string_view str); /// Create an IPv6 address from an IP address string. /** * @relates address_v6 */ BOOST_ASIO_DECL address_v6 make_address_v6( string_view str, boost::system::error_code& ec); #endif // defined(BOOST_ASIO_HAS_STRING_VIEW) // || defined(GENERATING_DOCUMENTATION) /// Tag type used for distinguishing overloads that deal in IPv4-mapped IPv6 /// addresses. enum v4_mapped_t { v4_mapped }; /// Create an IPv4 address from a IPv4-mapped IPv6 address. /** * @relates address_v4 */ BOOST_ASIO_DECL address_v4 make_address_v4( v4_mapped_t, const address_v6& v6_addr); /// Create an IPv4-mapped IPv6 address from an IPv4 address. /** * @relates address_v6 */ BOOST_ASIO_DECL address_v6 make_address_v6( v4_mapped_t, const address_v4& v4_addr); #if !defined(BOOST_ASIO_NO_IOSTREAM) /// Output an address as a string. /** * Used to output a human-readable string for a specified address. * * @param os The output stream to which the string will be written. * * @param addr The address to be written. * * @return The output stream. * * @relates boost::asio::ip::address_v6 */ template <typename Elem, typename Traits> std::basic_ostream<Elem, Traits>& operator<<( std::basic_ostream<Elem, Traits>& os, const address_v6& addr); #endif // !defined(BOOST_ASIO_NO_IOSTREAM) } // namespace ip } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> #include <boost/asio/ip/impl/address_v6.hpp> #if defined(BOOST_ASIO_HEADER_ONLY) # include <boost/asio/ip/impl/address_v6.ipp> #endif // defined(BOOST_ASIO_HEADER_ONLY) #endif // BOOST_ASIO_IP_ADDRESS_V6_HPP
mit
uniter/uniter-jquery
build/fs.js
665
/* * Demo of packaging PHP files up with Browserify+Uniter * * MIT license. */ 'use strict'; var fs = require('fs'), globby = require('globby'), path = require('path'), files = globby.sync([ __dirname + '/../php/**/*.php', '!' + __dirname + '/../php/src/Demo/PhpQuery/**', '!' + __dirname + '/../php/src/Demo/QueryPath/**' ]), fileData = {}, root = __dirname + '/..'; files.forEach(function (filePath) { fileData[path.relative(root, filePath)] = fs.readFileSync(filePath).toString(); }); fs.writeFileSync( __dirname + '/../dist/fileData.js', 'module.exports = ' + JSON.stringify(fileData) + ';' );
mit
StasPiv/playzone
src/CoreBundle/Model/Request/Call/CallDeleteAcceptRequest.php
996
<?php /** * Created by PhpStorm. * User: stas * Date: 17.01.16 * Time: 20:58 */ namespace CoreBundle\Model\Request\Call; use CoreBundle\Model\Request\SecurityRequestAwareTrait; use CoreBundle\Model\Request\SecurityRequestInterface; use JMS\Serializer\Annotation as JMS; use Symfony\Component\Validator\Constraints as Assert; /** * Class CallDeleteAcceptRequest * @package CoreBundle\Model\Request\Call */ class CallDeleteAcceptRequest extends CallRequest implements SecurityRequestInterface { use SecurityRequestAwareTrait; /** * @var string * * @JMS\Expose() * @JMS\Type("string") * * @Assert\NotBlank( * message = "Call id is required for this request" * ) */ private $callId; /** * @return string */ public function getCallId() { return $this->callId; } /** * @param string $callId */ public function setCallId($callId) { $this->callId = $callId; } }
mit
scen/ionlib
src/sdk/hl2_ob/game/client/c_baseentity.cpp
176903
//===== Copyright © 1996-2005, Valve Corporation, All rights reserved. ======// // // Purpose: // // $NoKeywords: $ //===========================================================================// #include "cbase.h" #include "c_baseentity.h" #include "prediction.h" #include "model_types.h" #include "iviewrender_beams.h" #include "dlight.h" #include "iviewrender.h" #include "view.h" #include "iefx.h" #include "c_team.h" #include "clientmode.h" #include "usercmd.h" #include "engine/IEngineSound.h" #include "crtdbg.h" #include "engine/IEngineTrace.h" #include "engine/ivmodelinfo.h" #include "tier0/vprof.h" #include "fx_line.h" #include "interface.h" #include "materialsystem/IMaterialSystem.h" #include "soundinfo.h" #include "mathlib/vmatrix.h" #include "isaverestore.h" #include "interval.h" #include "engine/ivdebugoverlay.h" #include "c_ai_basenpc.h" #include "apparent_velocity_helper.h" #include "c_baseanimatingoverlay.h" #include "tier1/KeyValues.h" #include "hltvcamera.h" #include "datacache/imdlcache.h" #include "toolframework/itoolframework.h" #include "toolframework_client.h" #include "decals.h" #include "cdll_bounded_cvars.h" #include "inetchannelinfo.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" #ifdef INTERPOLATEDVAR_PARANOID_MEASUREMENT int g_nInterpolatedVarsChanged = 0; bool g_bRestoreInterpolatedVarValues = false; #endif static bool g_bWasSkipping = (bool)-1; static bool g_bWasThreaded =(bool)-1; static int g_nThreadModeTicks = 0; static ConVar cl_interp_threadmodeticks( "cl_interp_threadmodeticks", "0", 0, "Additional interpolation ticks to use when interpolating with threaded engine mode set." ); void cc_cl_interp_all_changed( IConVar *pConVar, const char *pOldString, float flOldValue ) { ConVarRef var( pConVar ); if ( var.GetInt() ) { C_BaseEntityIterator iterator; C_BaseEntity *pEnt; while ( (pEnt = iterator.Next()) != NULL ) { if ( pEnt->ShouldInterpolate() ) { pEnt->AddToInterpolationList(); } } } } static ConVar cl_extrapolate( "cl_extrapolate", "1", FCVAR_CHEAT, "Enable/disable extrapolation if interpolation history runs out." ); static ConVar cl_interp_npcs( "cl_interp_npcs", "0.0", FCVAR_USERINFO, "Interpolate NPC positions starting this many seconds in past (or cl_interp, if greater)" ); static ConVar cl_interp_all( "cl_interp_all", "0", 0, "Disable interpolation list optimizations.", 0, 0, 0, 0, cc_cl_interp_all_changed ); ConVar r_drawmodeldecals( "r_drawmodeldecals", "1" ); extern ConVar cl_showerror; int C_BaseEntity::m_nPredictionRandomSeed = -1; C_BasePlayer *C_BaseEntity::m_pPredictionPlayer = NULL; bool C_BaseEntity::s_bAbsQueriesValid = true; bool C_BaseEntity::s_bAbsRecomputationEnabled = true; bool C_BaseEntity::s_bInterpolate = true; bool C_BaseEntity::sm_bDisableTouchFuncs = false; // Disables PhysicsTouch and PhysicsStartTouch function calls static ConVar r_drawrenderboxes( "r_drawrenderboxes", "0", FCVAR_CHEAT ); static bool g_bAbsRecomputationStack[8]; static unsigned short g_iAbsRecomputationStackPos = 0; // All the entities that want Interpolate() called on them. static CUtlLinkedList<C_BaseEntity*, unsigned short> g_InterpolationList; static CUtlLinkedList<C_BaseEntity*, unsigned short> g_TeleportList; #if !defined( NO_ENTITY_PREDICTION ) //----------------------------------------------------------------------------- // Purpose: Maintains a list of predicted or client created entities //----------------------------------------------------------------------------- class CPredictableList : public IPredictableList { public: virtual C_BaseEntity *GetPredictable( int slot ); virtual int GetPredictableCount( void ); protected: void AddToPredictableList( ClientEntityHandle_t add ); void RemoveFromPredictablesList( ClientEntityHandle_t remove ); private: CUtlVector< ClientEntityHandle_t > m_Predictables; friend class C_BaseEntity; }; // Create singleton static CPredictableList g_Predictables; IPredictableList *predictables = &g_Predictables; //----------------------------------------------------------------------------- // Purpose: Add entity to list // Input : add - // Output : int //----------------------------------------------------------------------------- void CPredictableList::AddToPredictableList( ClientEntityHandle_t add ) { // This is a hack to remap slot to index if ( m_Predictables.Find( add ) != m_Predictables.InvalidIndex() ) { return; } // Add to general list m_Predictables.AddToTail( add ); // Maintain sort order by entindex int count = m_Predictables.Size(); if ( count < 2 ) return; int i, j; for ( i = 0; i < count; i++ ) { for ( j = i + 1; j < count; j++ ) { ClientEntityHandle_t h1 = m_Predictables[ i ]; ClientEntityHandle_t h2 = m_Predictables[ j ]; C_BaseEntity *p1 = cl_entitylist->GetBaseEntityFromHandle( h1 ); C_BaseEntity *p2 = cl_entitylist->GetBaseEntityFromHandle( h2 ); if ( !p1 || !p2 ) { Assert( 0 ); continue; } if ( p1->entindex() != -1 && p2->entindex() != -1 ) { if ( p1->entindex() < p2->entindex() ) continue; } if ( p2->entindex() == -1 ) continue; m_Predictables[ i ] = h2; m_Predictables[ j ] = h1; } } } //----------------------------------------------------------------------------- // Purpose: // Input : remove - //----------------------------------------------------------------------------- void CPredictableList::RemoveFromPredictablesList( ClientEntityHandle_t remove ) { m_Predictables.FindAndRemove( remove ); } //----------------------------------------------------------------------------- // Purpose: // Input : slot - // Output : C_BaseEntity //----------------------------------------------------------------------------- C_BaseEntity *CPredictableList::GetPredictable( int slot ) { return cl_entitylist->GetBaseEntityFromHandle( m_Predictables[ slot ] ); } //----------------------------------------------------------------------------- // Purpose: // Output : int //----------------------------------------------------------------------------- int CPredictableList::GetPredictableCount( void ) { return m_Predictables.Count(); } //----------------------------------------------------------------------------- // Purpose: Searc predictables for previously created entity (by testId) // Input : testId - // Output : static C_BaseEntity //----------------------------------------------------------------------------- static C_BaseEntity *FindPreviouslyCreatedEntity( CPredictableId& testId ) { int c = predictables->GetPredictableCount(); int i; for ( i = 0; i < c; i++ ) { C_BaseEntity *e = predictables->GetPredictable( i ); if ( !e || !e->IsClientCreated() ) continue; // Found it, note use of operator == if ( testId == e->m_PredictableID ) { return e; } } return NULL; } #endif abstract_class IRecordingList { public: virtual ~IRecordingList() {}; virtual void AddToList( ClientEntityHandle_t add ) = 0; virtual void RemoveFromList( ClientEntityHandle_t remove ) = 0; virtual int Count() = 0; virtual IClientRenderable *Get( int index ) = 0; }; class CRecordingList : public IRecordingList { public: virtual void AddToList( ClientEntityHandle_t add ); virtual void RemoveFromList( ClientEntityHandle_t remove ); virtual int Count(); IClientRenderable *Get( int index ); private: CUtlVector< ClientEntityHandle_t > m_Recording; }; static CRecordingList g_RecordingList; IRecordingList *recordinglist = &g_RecordingList; //----------------------------------------------------------------------------- // Purpose: Add entity to list // Input : add - // Output : int //----------------------------------------------------------------------------- void CRecordingList::AddToList( ClientEntityHandle_t add ) { // This is a hack to remap slot to index if ( m_Recording.Find( add ) != m_Recording.InvalidIndex() ) { return; } // Add to general list m_Recording.AddToTail( add ); } //----------------------------------------------------------------------------- // Purpose: // Input : remove - //----------------------------------------------------------------------------- void CRecordingList::RemoveFromList( ClientEntityHandle_t remove ) { m_Recording.FindAndRemove( remove ); } //----------------------------------------------------------------------------- // Purpose: // Input : slot - // Output : IClientRenderable //----------------------------------------------------------------------------- IClientRenderable *CRecordingList::Get( int index ) { return cl_entitylist->GetClientRenderableFromHandle( m_Recording[ index ] ); } //----------------------------------------------------------------------------- // Purpose: // Output : int //----------------------------------------------------------------------------- int CRecordingList::Count() { return m_Recording.Count(); } // Should these be somewhere else? #define PITCH 0 // HACK HACK: 3/28/02 ywb Had to proxy around this or interpolation is borked in multiplayer, not sure what // the issue is, just a global optimizer bug I presume #pragma optimize( "g", off ) //----------------------------------------------------------------------------- // Purpose: Decodes animtime and notes when it changes // Input : *pStruct - ( C_BaseEntity * ) used to flag animtime is changine // *pVarData - // *pIn - // objectID - //----------------------------------------------------------------------------- void RecvProxy_AnimTime( const CRecvProxyData *pData, void *pStruct, void *pOut ) { C_BaseEntity *pEntity = ( C_BaseEntity * )pStruct; Assert( pOut == &pEntity->m_flAnimTime ); int t; int tickbase; int addt; // Unpack the data. addt = pData->m_Value.m_Int; // Note, this needs to be encoded relative to packet timestamp, not raw client clock tickbase = gpGlobals->GetNetworkBase( gpGlobals->tickcount, pEntity->entindex() ); t = tickbase; // and then go back to floating point time. t += addt; // Add in an additional up to 256 100ths from the server // center m_flAnimTime around current time. while (t < gpGlobals->tickcount - 127) t += 256; while (t > gpGlobals->tickcount + 127) t -= 256; pEntity->m_flAnimTime = ( t * TICK_INTERVAL ); } void RecvProxy_SimulationTime( const CRecvProxyData *pData, void *pStruct, void *pOut ) { C_BaseEntity *pEntity = ( C_BaseEntity * )pStruct; Assert( pOut == &pEntity->m_flSimulationTime ); int t; int tickbase; int addt; // Unpack the data. addt = pData->m_Value.m_Int; // Note, this needs to be encoded relative to packet timestamp, not raw client clock tickbase = gpGlobals->GetNetworkBase( gpGlobals->tickcount, pEntity->entindex() ); t = tickbase; // and then go back to floating point time. t += addt; // Add in an additional up to 256 100ths from the server // center m_flSimulationTime around current time. while (t < gpGlobals->tickcount - 127) t += 256; while (t > gpGlobals->tickcount + 127) t -= 256; pEntity->m_flSimulationTime = ( t * TICK_INTERVAL ); } void RecvProxy_LocalVelocity( const CRecvProxyData *pData, void *pStruct, void *pOut ) { CBaseEntity *pEnt = (CBaseEntity *)pStruct; Vector vecVelocity; vecVelocity.x = pData->m_Value.m_Vector[0]; vecVelocity.y = pData->m_Value.m_Vector[1]; vecVelocity.z = pData->m_Value.m_Vector[2]; // SetLocalVelocity checks to see if the value has changed pEnt->SetLocalVelocity( vecVelocity ); } void RecvProxy_ToolRecording( const CRecvProxyData *pData, void *pStruct, void *pOut ) { if ( !ToolsEnabled() ) return; CBaseEntity *pEnt = (CBaseEntity *)pStruct; pEnt->SetToolRecording( pData->m_Value.m_Int != 0 ); } #pragma optimize( "g", on ) // Expose it to the engine. IMPLEMENT_CLIENTCLASS(C_BaseEntity, DT_BaseEntity, CBaseEntity); static void RecvProxy_MoveType( const CRecvProxyData *pData, void *pStruct, void *pOut ) { ((C_BaseEntity*)pStruct)->SetMoveType( (MoveType_t)(pData->m_Value.m_Int) ); } static void RecvProxy_MoveCollide( const CRecvProxyData *pData, void *pStruct, void *pOut ) { ((C_BaseEntity*)pStruct)->SetMoveCollide( (MoveCollide_t)(pData->m_Value.m_Int) ); } static void RecvProxy_Solid( const CRecvProxyData *pData, void *pStruct, void *pOut ) { ((C_BaseEntity*)pStruct)->SetSolid( (SolidType_t)pData->m_Value.m_Int ); } static void RecvProxy_SolidFlags( const CRecvProxyData *pData, void *pStruct, void *pOut ) { ((C_BaseEntity*)pStruct)->SetSolidFlags( pData->m_Value.m_Int ); } void RecvProxy_EffectFlags( const CRecvProxyData *pData, void *pStruct, void *pOut ) { ((C_BaseEntity*)pStruct)->SetEffects( pData->m_Value.m_Int ); } BEGIN_RECV_TABLE_NOBASE( C_BaseEntity, DT_AnimTimeMustBeFirst ) RecvPropInt( RECVINFO(m_flAnimTime), 0, RecvProxy_AnimTime ), END_RECV_TABLE() #ifndef NO_ENTITY_PREDICTION BEGIN_RECV_TABLE_NOBASE( C_BaseEntity, DT_PredictableId ) RecvPropPredictableId( RECVINFO( m_PredictableID ) ), RecvPropInt( RECVINFO( m_bIsPlayerSimulated ) ), END_RECV_TABLE() #endif BEGIN_RECV_TABLE_NOBASE(C_BaseEntity, DT_BaseEntity) RecvPropDataTable( "AnimTimeMustBeFirst", 0, 0, &REFERENCE_RECV_TABLE(DT_AnimTimeMustBeFirst) ), RecvPropInt( RECVINFO(m_flSimulationTime), 0, RecvProxy_SimulationTime ), RecvPropVector( RECVINFO_NAME( m_vecNetworkOrigin, m_vecOrigin ) ), #if PREDICTION_ERROR_CHECK_LEVEL > 1 RecvPropVector( RECVINFO_NAME( m_angNetworkAngles, m_angRotation ) ), #else RecvPropQAngles( RECVINFO_NAME( m_angNetworkAngles, m_angRotation ) ), #endif RecvPropInt(RECVINFO(m_nModelIndex) ), RecvPropInt(RECVINFO(m_fEffects), 0, RecvProxy_EffectFlags ), RecvPropInt(RECVINFO(m_nRenderMode)), RecvPropInt(RECVINFO(m_nRenderFX)), RecvPropInt(RECVINFO(m_clrRender)), RecvPropInt(RECVINFO(m_iTeamNum)), RecvPropInt(RECVINFO(m_CollisionGroup)), RecvPropFloat(RECVINFO(m_flElasticity)), RecvPropFloat(RECVINFO(m_flShadowCastDistance)), RecvPropEHandle( RECVINFO(m_hOwnerEntity) ), RecvPropEHandle( RECVINFO(m_hEffectEntity) ), RecvPropInt( RECVINFO_NAME(m_hNetworkMoveParent, moveparent), 0, RecvProxy_IntToMoveParent ), RecvPropInt( RECVINFO( m_iParentAttachment ) ), RecvPropInt( "movetype", 0, SIZEOF_IGNORE, 0, RecvProxy_MoveType ), RecvPropInt( "movecollide", 0, SIZEOF_IGNORE, 0, RecvProxy_MoveCollide ), RecvPropDataTable( RECVINFO_DT( m_Collision ), 0, &REFERENCE_RECV_TABLE(DT_CollisionProperty) ), RecvPropInt( RECVINFO ( m_iTextureFrameIndex ) ), #if !defined( NO_ENTITY_PREDICTION ) RecvPropDataTable( "predictable_id", 0, 0, &REFERENCE_RECV_TABLE( DT_PredictableId ) ), #endif RecvPropInt ( RECVINFO( m_bSimulatedEveryTick ), 0, RecvProxy_InterpolationAmountChanged ), RecvPropInt ( RECVINFO( m_bAnimatedEveryTick ), 0, RecvProxy_InterpolationAmountChanged ), RecvPropBool ( RECVINFO( m_bAlternateSorting ) ), END_RECV_TABLE() BEGIN_PREDICTION_DATA_NO_BASE( C_BaseEntity ) // These have a special proxy to handle send/receive DEFINE_PRED_TYPEDESCRIPTION( m_Collision, CCollisionProperty ), DEFINE_PRED_FIELD( m_MoveType, FIELD_CHARACTER, FTYPEDESC_INSENDTABLE ), DEFINE_PRED_FIELD( m_MoveCollide, FIELD_CHARACTER, FTYPEDESC_INSENDTABLE ), DEFINE_FIELD( m_vecAbsVelocity, FIELD_VECTOR ), DEFINE_PRED_FIELD_TOL( m_vecVelocity, FIELD_VECTOR, FTYPEDESC_INSENDTABLE, 0.5f ), // DEFINE_PRED_FIELD( m_fEffects, FIELD_INTEGER, FTYPEDESC_INSENDTABLE ), DEFINE_PRED_FIELD( m_nRenderMode, FIELD_CHARACTER, FTYPEDESC_INSENDTABLE ), DEFINE_PRED_FIELD( m_nRenderFX, FIELD_CHARACTER, FTYPEDESC_INSENDTABLE ), // DEFINE_PRED_FIELD( m_flAnimTime, FIELD_FLOAT, FTYPEDESC_INSENDTABLE ), // DEFINE_PRED_FIELD( m_flSimulationTime, FIELD_FLOAT, FTYPEDESC_INSENDTABLE ), DEFINE_PRED_FIELD( m_fFlags, FIELD_INTEGER, FTYPEDESC_INSENDTABLE ), DEFINE_PRED_FIELD_TOL( m_vecViewOffset, FIELD_VECTOR, FTYPEDESC_INSENDTABLE, 0.25f ), DEFINE_PRED_FIELD( m_nModelIndex, FIELD_SHORT, FTYPEDESC_INSENDTABLE | FTYPEDESC_MODELINDEX ), DEFINE_PRED_FIELD( m_flFriction, FIELD_FLOAT, FTYPEDESC_INSENDTABLE ), DEFINE_PRED_FIELD( m_iTeamNum, FIELD_INTEGER, FTYPEDESC_INSENDTABLE ), DEFINE_PRED_FIELD( m_hOwnerEntity, FIELD_EHANDLE, FTYPEDESC_INSENDTABLE ), // DEFINE_FIELD( m_nSimulationTick, FIELD_INTEGER ), DEFINE_PRED_FIELD( m_hNetworkMoveParent, FIELD_EHANDLE, FTYPEDESC_INSENDTABLE ), // DEFINE_PRED_FIELD( m_pMoveParent, FIELD_EHANDLE ), // DEFINE_PRED_FIELD( m_pMoveChild, FIELD_EHANDLE ), // DEFINE_PRED_FIELD( m_pMovePeer, FIELD_EHANDLE ), // DEFINE_PRED_FIELD( m_pMovePrevPeer, FIELD_EHANDLE ), DEFINE_PRED_FIELD_TOL( m_vecNetworkOrigin, FIELD_VECTOR, FTYPEDESC_INSENDTABLE, 0.002f ), DEFINE_PRED_FIELD( m_angNetworkAngles, FIELD_VECTOR, FTYPEDESC_INSENDTABLE | FTYPEDESC_NOERRORCHECK ), DEFINE_FIELD( m_vecAbsOrigin, FIELD_VECTOR ), DEFINE_FIELD( m_angAbsRotation, FIELD_VECTOR ), DEFINE_FIELD( m_vecOrigin, FIELD_VECTOR ), DEFINE_FIELD( m_angRotation, FIELD_VECTOR ), // DEFINE_FIELD( m_hGroundEntity, FIELD_EHANDLE ), DEFINE_FIELD( m_nWaterLevel, FIELD_CHARACTER ), DEFINE_FIELD( m_nWaterType, FIELD_CHARACTER ), DEFINE_FIELD( m_vecAngVelocity, FIELD_VECTOR ), // DEFINE_FIELD( m_vecAbsAngVelocity, FIELD_VECTOR ), // DEFINE_FIELD( model, FIELD_INTEGER ), // writing pointer literally // DEFINE_FIELD( index, FIELD_INTEGER ), // DEFINE_FIELD( m_ClientHandle, FIELD_SHORT ), // DEFINE_FIELD( m_Partition, FIELD_SHORT ), // DEFINE_FIELD( m_hRender, FIELD_SHORT ), DEFINE_FIELD( m_bDormant, FIELD_BOOLEAN ), // DEFINE_FIELD( current_position, FIELD_INTEGER ), // DEFINE_FIELD( m_flLastMessageTime, FIELD_FLOAT ), DEFINE_FIELD( m_vecBaseVelocity, FIELD_VECTOR ), DEFINE_FIELD( m_iEFlags, FIELD_INTEGER ), DEFINE_FIELD( m_flGravity, FIELD_FLOAT ), // DEFINE_FIELD( m_ModelInstance, FIELD_SHORT ), DEFINE_FIELD( m_flProxyRandomValue, FIELD_FLOAT ), // DEFINE_FIELD( m_PredictableID, FIELD_INTEGER ), // DEFINE_FIELD( m_pPredictionContext, FIELD_POINTER ), // Stuff specific to rendering and therefore not to be copied back and forth // DEFINE_PRED_FIELD( m_clrRender, color32, FTYPEDESC_INSENDTABLE ), // DEFINE_FIELD( m_bReadyToDraw, FIELD_BOOLEAN ), // DEFINE_FIELD( anim, CLatchedAnim ), // DEFINE_FIELD( mouth, CMouthInfo ), // DEFINE_FIELD( GetAbsOrigin(), FIELD_VECTOR ), // DEFINE_FIELD( GetAbsAngles(), FIELD_VECTOR ), // DEFINE_FIELD( m_nNumAttachments, FIELD_SHORT ), // DEFINE_FIELD( m_pAttachmentAngles, FIELD_VECTOR ), // DEFINE_FIELD( m_pAttachmentOrigin, FIELD_VECTOR ), // DEFINE_FIELD( m_listentry, CSerialEntity ), // DEFINE_FIELD( m_ShadowHandle, ClientShadowHandle_t ), // DEFINE_FIELD( m_hThink, ClientThinkHandle_t ), // Definitely private and not copied around // DEFINE_FIELD( m_bPredictable, FIELD_BOOLEAN ), // DEFINE_FIELD( m_CollisionGroup, FIELD_INTEGER ), // DEFINE_FIELD( m_DataChangeEventRef, FIELD_INTEGER ), #if !defined( CLIENT_DLL ) // DEFINE_FIELD( m_bPredictionEligible, FIELD_BOOLEAN ), #endif END_PREDICTION_DATA() //----------------------------------------------------------------------------- // Helper functions. //----------------------------------------------------------------------------- void SpewInterpolatedVar( CInterpolatedVar< Vector > *pVar ) { Msg( "--------------------------------------------------\n" ); int i = pVar->GetHead(); CApparentVelocity<Vector> apparent; float prevtime = 0.0f; while ( 1 ) { float changetime; Vector *pVal = pVar->GetHistoryValue( i, changetime ); if ( !pVal ) break; float vel = apparent.AddSample( changetime, *pVal ); Msg( "%6.6f: (%.2f %.2f %.2f), vel: %.2f [dt %.1f]\n", changetime, VectorExpand( *pVal ), vel, prevtime == 0.0f ? 0.0f : 1000.0f * ( changetime - prevtime ) ); i = pVar->GetNext( i ); prevtime = changetime; } Msg( "--------------------------------------------------\n" ); } void SpewInterpolatedVar( CInterpolatedVar< Vector > *pVar, float flNow, float flInterpAmount, bool bSpewAllEntries = true ) { float target = flNow - flInterpAmount; Msg( "--------------------------------------------------\n" ); int i = pVar->GetHead(); CApparentVelocity<Vector> apparent; float newtime = 999999.0f; Vector newVec( 0, 0, 0 ); bool bSpew = true; while ( 1 ) { float changetime; Vector *pVal = pVar->GetHistoryValue( i, changetime ); if ( !pVal ) break; if ( bSpew && target >= changetime ) { Vector o; pVar->DebugInterpolate( &o, flNow ); bool bInterp = newtime != 999999.0f; float frac = 0.0f; char desc[ 32 ]; if ( bInterp ) { frac = ( target - changetime ) / ( newtime - changetime ); Q_snprintf( desc, sizeof( desc ), "interpolated [%.2f]", frac ); } else { bSpew = true; int savei = i; i = pVar->GetNext( i ); float oldtertime = 0.0f; pVar->GetHistoryValue( i, oldtertime ); if ( changetime != oldtertime ) { frac = ( target - changetime ) / ( changetime - oldtertime ); } Q_snprintf( desc, sizeof( desc ), "extrapolated [%.2f]", frac ); i = savei; } if ( bSpew ) { Msg( " > %6.6f: (%.2f %.2f %.2f) %s for %.1f msec\n", target, VectorExpand( o ), desc, 1000.0f * ( target - changetime ) ); bSpew = false; } } float vel = apparent.AddSample( changetime, *pVal ); if ( bSpewAllEntries ) { Msg( " %6.6f: (%.2f %.2f %.2f), vel: %.2f [dt %.1f]\n", changetime, VectorExpand( *pVal ), vel, newtime == 999999.0f ? 0.0f : 1000.0f * ( newtime - changetime ) ); } i = pVar->GetNext( i ); newtime = changetime; newVec = *pVal; } Msg( "--------------------------------------------------\n" ); } void SpewInterpolatedVar( CInterpolatedVar< float > *pVar ) { Msg( "--------------------------------------------------\n" ); int i = pVar->GetHead(); CApparentVelocity<float> apparent; while ( 1 ) { float changetime; float *pVal = pVar->GetHistoryValue( i, changetime ); if ( !pVal ) break; float vel = apparent.AddSample( changetime, *pVal ); Msg( "%6.6f: (%.2f), vel: %.2f\n", changetime, *pVal, vel ); i = pVar->GetNext( i ); } Msg( "--------------------------------------------------\n" ); } template<class T> void GetInterpolatedVarTimeRange( CInterpolatedVar<T> *pVar, float &flMin, float &flMax ) { flMin = 1e23; flMax = -1e23; int i = pVar->GetHead(); CApparentVelocity<Vector> apparent; while ( 1 ) { float changetime; if ( !pVar->GetHistoryValue( i, changetime ) ) return; flMin = MIN( flMin, changetime ); flMax = MAX( flMax, changetime ); i = pVar->GetNext( i ); } } //----------------------------------------------------------------------------- // Global methods related to when abs data is correct //----------------------------------------------------------------------------- void C_BaseEntity::SetAbsQueriesValid( bool bValid ) { // @MULTICORE: Always allow in worker threads, assume higher level code is handling correctly if ( !ThreadInMainThread() ) return; if ( !bValid ) { s_bAbsQueriesValid = false; } else { s_bAbsQueriesValid = true; } } bool C_BaseEntity::IsAbsQueriesValid( void ) { if ( !ThreadInMainThread() ) return true; return s_bAbsQueriesValid; } void C_BaseEntity::PushEnableAbsRecomputations( bool bEnable ) { if ( !ThreadInMainThread() ) return; if ( g_iAbsRecomputationStackPos < ARRAYSIZE( g_bAbsRecomputationStack ) ) { g_bAbsRecomputationStack[g_iAbsRecomputationStackPos] = s_bAbsRecomputationEnabled; ++g_iAbsRecomputationStackPos; s_bAbsRecomputationEnabled = bEnable; } else { Assert( false ); } } void C_BaseEntity::PopEnableAbsRecomputations() { if ( !ThreadInMainThread() ) return; if ( g_iAbsRecomputationStackPos > 0 ) { --g_iAbsRecomputationStackPos; s_bAbsRecomputationEnabled = g_bAbsRecomputationStack[g_iAbsRecomputationStackPos]; } else { Assert( false ); } } void C_BaseEntity::EnableAbsRecomputations( bool bEnable ) { if ( !ThreadInMainThread() ) return; // This should only be called at the frame level. Use PushEnableAbsRecomputations // if you're blocking out a section of code. Assert( g_iAbsRecomputationStackPos == 0 ); s_bAbsRecomputationEnabled = bEnable; } bool C_BaseEntity::IsAbsRecomputationsEnabled() { if ( !ThreadInMainThread() ) return true; return s_bAbsRecomputationEnabled; } int C_BaseEntity::GetTextureFrameIndex( void ) { return m_iTextureFrameIndex; } void C_BaseEntity::SetTextureFrameIndex( int iIndex ) { m_iTextureFrameIndex = iIndex; } //----------------------------------------------------------------------------- // Purpose: // Input : *map - //----------------------------------------------------------------------------- void C_BaseEntity::Interp_SetupMappings( VarMapping_t *map ) { if( !map ) return; int c = map->m_Entries.Count(); for ( int i = 0; i < c; i++ ) { VarMapEntry_t *e = &map->m_Entries[ i ]; IInterpolatedVar *watcher = e->watcher; void *data = e->data; int type = e->type; watcher->Setup( data, type ); watcher->SetInterpolationAmount( GetInterpolationAmount( watcher->GetType() ) ); } } void C_BaseEntity::Interp_RestoreToLastNetworked( VarMapping_t *map ) { PREDICTION_TRACKVALUECHANGESCOPE_ENTITY( this, "restoretolastnetworked" ); Vector oldOrigin = GetLocalOrigin(); QAngle oldAngles = GetLocalAngles(); int c = map->m_Entries.Count(); for ( int i = 0; i < c; i++ ) { VarMapEntry_t *e = &map->m_Entries[ i ]; IInterpolatedVar *watcher = e->watcher; watcher->RestoreToLastNetworked(); } BaseInterpolatePart2( oldOrigin, oldAngles, 0 ); } void C_BaseEntity::Interp_UpdateInterpolationAmounts( VarMapping_t *map ) { if( !map ) return; int c = map->m_Entries.Count(); for ( int i = 0; i < c; i++ ) { VarMapEntry_t *e = &map->m_Entries[ i ]; IInterpolatedVar *watcher = e->watcher; watcher->SetInterpolationAmount( GetInterpolationAmount( watcher->GetType() ) ); } } void C_BaseEntity::Interp_HierarchyUpdateInterpolationAmounts() { Interp_UpdateInterpolationAmounts( GetVarMapping() ); for ( C_BaseEntity *pChild = FirstMoveChild(); pChild; pChild = pChild->NextMovePeer() ) { pChild->Interp_HierarchyUpdateInterpolationAmounts(); } } inline int C_BaseEntity::Interp_Interpolate( VarMapping_t *map, float currentTime ) { int bNoMoreChanges = 1; if ( currentTime < map->m_lastInterpolationTime ) { for ( int i = 0; i < map->m_nInterpolatedEntries; i++ ) { VarMapEntry_t *e = &map->m_Entries[ i ]; e->m_bNeedsToInterpolate = true; } } map->m_lastInterpolationTime = currentTime; for ( int i = 0; i < map->m_nInterpolatedEntries; i++ ) { VarMapEntry_t *e = &map->m_Entries[ i ]; if ( !e->m_bNeedsToInterpolate ) continue; IInterpolatedVar *watcher = e->watcher; Assert( !( watcher->GetType() & EXCLUDE_AUTO_INTERPOLATE ) ); if ( watcher->Interpolate( currentTime ) ) e->m_bNeedsToInterpolate = false; else bNoMoreChanges = 0; } return bNoMoreChanges; } //----------------------------------------------------------------------------- // Functions. //----------------------------------------------------------------------------- C_BaseEntity::C_BaseEntity() : m_iv_vecOrigin( "C_BaseEntity::m_iv_vecOrigin" ), m_iv_angRotation( "C_BaseEntity::m_iv_angRotation" ) { AddVar( &m_vecOrigin, &m_iv_vecOrigin, LATCH_SIMULATION_VAR ); AddVar( &m_angRotation, &m_iv_angRotation, LATCH_SIMULATION_VAR ); m_DataChangeEventRef = -1; m_EntClientFlags = 0; m_iParentAttachment = 0; m_nRenderFXBlend = 255; SetPredictionEligible( false ); m_bPredictable = false; m_bSimulatedEveryTick = false; m_bAnimatedEveryTick = false; m_pPhysicsObject = NULL; #ifdef _DEBUG m_vecAbsOrigin = vec3_origin; m_angAbsRotation = vec3_angle; m_vecNetworkOrigin.Init(); m_angNetworkAngles.Init(); m_vecAbsOrigin.Init(); // m_vecAbsAngVelocity.Init(); m_vecVelocity.Init(); m_vecAbsVelocity.Init(); m_vecViewOffset.Init(); m_vecBaseVelocity.Init(); m_iCurrentThinkContext = NO_THINK_CONTEXT; #endif m_nSimulationTick = -1; // Assume drawing everything m_bReadyToDraw = true; m_flProxyRandomValue = 0.0f; m_fBBoxVisFlags = 0; #if !defined( NO_ENTITY_PREDICTION ) m_pPredictionContext = NULL; #endif Clear(); m_InterpolationListEntry = 0xFFFF; m_TeleportListEntry = 0xFFFF; #ifndef NO_TOOLFRAMEWORK m_bEnabledInToolView = true; m_bToolRecording = false; m_ToolHandle = 0; m_nLastRecordedFrame = -1; m_bRecordInTools = true; #endif ParticleProp()->Init( this ); } //----------------------------------------------------------------------------- // Purpose: // Input : // Output : //----------------------------------------------------------------------------- C_BaseEntity::~C_BaseEntity() { Term(); ClearDataChangedEvent( m_DataChangeEventRef ); #if !defined( NO_ENTITY_PREDICTION ) delete m_pPredictionContext; #endif RemoveFromInterpolationList(); RemoveFromTeleportList(); } void C_BaseEntity::Clear( void ) { m_bDormant = true; m_nCreationTick = -1; m_RefEHandle.Term(); m_ModelInstance = MODEL_INSTANCE_INVALID; m_ShadowHandle = CLIENTSHADOW_INVALID_HANDLE; m_hRender = INVALID_CLIENT_RENDER_HANDLE; m_hThink = INVALID_THINK_HANDLE; m_AimEntsListHandle = INVALID_AIMENTS_LIST_HANDLE; index = -1; m_Collision.Init( this ); SetLocalOrigin( vec3_origin ); SetLocalAngles( vec3_angle ); model = NULL; m_vecAbsOrigin.Init(); m_angAbsRotation.Init(); m_vecVelocity.Init(); ClearFlags(); m_vecViewOffset.Init(); m_vecBaseVelocity.Init(); m_nModelIndex = 0; m_flAnimTime = 0; m_flSimulationTime = 0; SetSolid( SOLID_NONE ); SetSolidFlags( 0 ); SetMoveCollide( MOVECOLLIDE_DEFAULT ); SetMoveType( MOVETYPE_NONE ); ClearEffects(); m_iEFlags = 0; m_nRenderMode = 0; m_nOldRenderMode = 0; SetRenderColor( 255, 255, 255, 255 ); m_nRenderFX = 0; m_flFriction = 0.0f; m_flGravity = 0.0f; SetCheckUntouch( false ); m_ShadowDirUseOtherEntity = NULL; m_nLastThinkTick = gpGlobals->tickcount; // Remove prediction context if it exists #if !defined( NO_ENTITY_PREDICTION ) delete m_pPredictionContext; m_pPredictionContext = NULL; #endif // Do not enable this on all entities. It forces bone setup for entities that // don't need it. //AddEFlags( EFL_USE_PARTITION_WHEN_NOT_SOLID ); UpdateVisibility(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void C_BaseEntity::Spawn( void ) { } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void C_BaseEntity::Activate() { } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void C_BaseEntity::SpawnClientEntity( void ) { } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void C_BaseEntity::Precache( void ) { } //----------------------------------------------------------------------------- // Purpose: Attach to entity // Input : *pEnt - // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool C_BaseEntity::Init( int entnum, int iSerialNum ) { Assert( entnum >= 0 && entnum < NUM_ENT_ENTRIES ); index = entnum; cl_entitylist->AddNetworkableEntity( GetIClientUnknown(), entnum, iSerialNum ); CollisionProp()->CreatePartitionHandle(); Interp_SetupMappings( GetVarMapping() ); m_nCreationTick = gpGlobals->tickcount; return true; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool C_BaseEntity::InitializeAsClientEntity( const char *pszModelName, RenderGroup_t renderGroup ) { int nModelIndex; if ( pszModelName != NULL ) { nModelIndex = modelinfo->GetModelIndex( pszModelName ); if ( nModelIndex == -1 ) { // Model could not be found Assert( !"Model could not be found, index is -1" ); return false; } } else { nModelIndex = -1; } Interp_SetupMappings( GetVarMapping() ); return InitializeAsClientEntityByIndex( nModelIndex, renderGroup ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool C_BaseEntity::InitializeAsClientEntityByIndex( int iIndex, RenderGroup_t renderGroup ) { // Setup model data. SetModelByIndex( iIndex ); // Add the client entity to the master entity list. cl_entitylist->AddNonNetworkableEntity( GetIClientUnknown() ); Assert( GetClientHandle() != ClientEntityList().InvalidHandle() ); // Add the client entity to the renderable "leaf system." (Renderable) AddToLeafSystem( renderGroup ); // Add the client entity to the spatial partition. (Collidable) CollisionProp()->CreatePartitionHandle(); index = -1; SpawnClientEntity(); return true; } void C_BaseEntity::Term() { C_BaseEntity::PhysicsRemoveTouchedList( this ); C_BaseEntity::PhysicsRemoveGroundList( this ); DestroyAllDataObjects(); #if !defined( NO_ENTITY_PREDICTION ) // Remove from the predictables list if ( GetPredictable() || IsClientCreated() ) { g_Predictables.RemoveFromPredictablesList( GetClientHandle() ); } // If it's play simulated, remove from simulation list if the player still exists... if ( IsPlayerSimulated() && C_BasePlayer::GetLocalPlayer() ) { C_BasePlayer::GetLocalPlayer()->RemoveFromPlayerSimulationList( this ); } #endif if ( GetClientHandle() != INVALID_CLIENTENTITY_HANDLE ) { if ( GetThinkHandle() != INVALID_THINK_HANDLE ) { ClientThinkList()->RemoveThinkable( GetClientHandle() ); } // Remove from the client entity list. ClientEntityList().RemoveEntity( GetClientHandle() ); m_RefEHandle = INVALID_CLIENTENTITY_HANDLE; } // Are we in the partition? CollisionProp()->DestroyPartitionHandle(); // If Client side only entity index will be -1 if ( index != -1 ) { beams->KillDeadBeams( this ); } // Clean up the model instance DestroyModelInstance(); // Clean up drawing RemoveFromLeafSystem(); RemoveFromAimEntsList(); } void C_BaseEntity::SetRefEHandle( const CBaseHandle &handle ) { m_RefEHandle = handle; } const CBaseHandle& C_BaseEntity::GetRefEHandle() const { return m_RefEHandle; } //----------------------------------------------------------------------------- // Purpose: Free beams and destroy object //----------------------------------------------------------------------------- void C_BaseEntity::Release() { { C_BaseAnimating::AutoAllowBoneAccess boneaccess( true, true ); UnlinkFromHierarchy(); } // Note that this must be called from here, not the destructor, because otherwise the // vtable is hosed and the derived classes function is not going to get called!!! if ( IsIntermediateDataAllocated() ) { DestroyIntermediateData(); } UpdateOnRemove(); delete this; } //----------------------------------------------------------------------------- // Only meant to be called from subclasses. // Returns true if instance valid, false otherwise //----------------------------------------------------------------------------- void C_BaseEntity::CreateModelInstance() { if ( m_ModelInstance == MODEL_INSTANCE_INVALID ) { m_ModelInstance = modelrender->CreateInstance( this ); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void C_BaseEntity::DestroyModelInstance() { if (m_ModelInstance != MODEL_INSTANCE_INVALID) { modelrender->DestroyInstance( m_ModelInstance ); m_ModelInstance = MODEL_INSTANCE_INVALID; } } void C_BaseEntity::SetRemovalFlag( bool bRemove ) { if (bRemove) m_iEFlags |= EFL_KILLME; else m_iEFlags &= ~EFL_KILLME; } //----------------------------------------------------------------------------- // VPhysics objects.. //----------------------------------------------------------------------------- int C_BaseEntity::VPhysicsGetObjectList( IPhysicsObject **pList, int listMax ) { IPhysicsObject *pPhys = VPhysicsGetObject(); if ( pPhys ) { // multi-object entities must implement this function Assert( !(pPhys->GetGameFlags() & FVPHYSICS_MULTIOBJECT_ENTITY) ); if ( listMax > 0 ) { pList[0] = pPhys; return 1; } } return 0; } bool C_BaseEntity::VPhysicsIsFlesh( void ) { IPhysicsObject *pList[VPHYSICS_MAX_OBJECT_LIST_COUNT]; int count = VPhysicsGetObjectList( pList, ARRAYSIZE(pList) ); for ( int i = 0; i < count; i++ ) { int material = pList[i]->GetMaterialIndex(); const surfacedata_t *pSurfaceData = physprops->GetSurfaceData( material ); // Is flesh ?, don't allow pickup if ( pSurfaceData->game.material == CHAR_TEX_ANTLION || pSurfaceData->game.material == CHAR_TEX_FLESH || pSurfaceData->game.material == CHAR_TEX_BLOODYFLESH || pSurfaceData->game.material == CHAR_TEX_ALIENFLESH ) return true; } return false; } //----------------------------------------------------------------------------- // Returns the health fraction //----------------------------------------------------------------------------- float C_BaseEntity::HealthFraction() const { if (GetMaxHealth() == 0) return 1.0f; float flFraction = (float)GetHealth() / (float)GetMaxHealth(); flFraction = clamp( flFraction, 0.0f, 1.0f ); return flFraction; } //----------------------------------------------------------------------------- // Purpose: Retrieves the coordinate frame for this entity. // Input : forward - Receives the entity's forward vector. // right - Receives the entity's right vector. // up - Receives the entity's up vector. //----------------------------------------------------------------------------- void C_BaseEntity::GetVectors(Vector* pForward, Vector* pRight, Vector* pUp) const { // This call is necessary to cause m_rgflCoordinateFrame to be recomputed const matrix3x4_t &entityToWorld = EntityToWorldTransform(); if (pForward != NULL) { MatrixGetColumn( entityToWorld, 0, *pForward ); } if (pRight != NULL) { MatrixGetColumn( entityToWorld, 1, *pRight ); *pRight *= -1.0f; } if (pUp != NULL) { MatrixGetColumn( entityToWorld, 2, *pUp ); } } void C_BaseEntity::UpdateVisibility() { if ( ShouldDraw() && !IsDormant() && ( !ToolsEnabled() || IsEnabledInToolView() ) ) { // add/update leafsystem AddToLeafSystem(); } else { // remove from leaf system RemoveFromLeafSystem(); } } //----------------------------------------------------------------------------- // Purpose: Returns whether object should render. //----------------------------------------------------------------------------- bool C_BaseEntity::ShouldDraw() { // Only test this in tf2 #if defined( INVASION_CLIENT_DLL ) // Let the client mode (like commander mode) reject drawing entities. if (g_pClientMode && !g_pClientMode->ShouldDrawEntity(this) ) return false; #endif // Some rendermodes prevent rendering if ( m_nRenderMode == kRenderNone ) return false; return (model != 0) && !IsEffectActive(EF_NODRAW) && (index != 0); } bool C_BaseEntity::TestCollision( const Ray_t& ray, unsigned int mask, trace_t& trace ) { return false; } bool C_BaseEntity::TestHitboxes( const Ray_t &ray, unsigned int fContentsMask, trace_t& tr ) { return false; } //----------------------------------------------------------------------------- // Used when the collision prop is told to ask game code for the world-space surrounding box //----------------------------------------------------------------------------- void C_BaseEntity::ComputeWorldSpaceSurroundingBox( Vector *pVecWorldMins, Vector *pVecWorldMaxs ) { // This should only be called if you're using USE_GAME_CODE on the server // and you forgot to implement the client-side version of this method. Assert(0); } //----------------------------------------------------------------------------- // Purpose: Derived classes will have to write their own message cracking routines!!! // Input : length - // *data - //----------------------------------------------------------------------------- void C_BaseEntity::ReceiveMessage( int classID, bf_read &msg ) { // BaseEntity doesn't have a base class we could relay this message to Assert( classID == GetClientClass()->m_ClassID ); int messageType = msg.ReadByte(); switch( messageType ) { case BASEENTITY_MSG_REMOVE_DECALS: RemoveAllDecals(); break; } } void* C_BaseEntity::GetDataTableBasePtr() { return this; } //----------------------------------------------------------------------------- // Should this object cast shadows? //----------------------------------------------------------------------------- ShadowType_t C_BaseEntity::ShadowCastType() { if (IsEffectActive(EF_NODRAW | EF_NOSHADOW)) return SHADOWS_NONE; int modelType = modelinfo->GetModelType( model ); return (modelType == mod_studio) ? SHADOWS_RENDER_TO_TEXTURE : SHADOWS_NONE; } //----------------------------------------------------------------------------- // Per-entity shadow cast distance + direction //----------------------------------------------------------------------------- bool C_BaseEntity::GetShadowCastDistance( float *pDistance, ShadowType_t shadowType ) const { if ( m_flShadowCastDistance != 0.0f ) { *pDistance = m_flShadowCastDistance; return true; } return false; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- C_BaseEntity *C_BaseEntity::GetShadowUseOtherEntity( void ) const { return m_ShadowDirUseOtherEntity; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void C_BaseEntity::SetShadowUseOtherEntity( C_BaseEntity *pEntity ) { m_ShadowDirUseOtherEntity = pEntity; } CInterpolatedVar< QAngle >& C_BaseEntity::GetRotationInterpolator() { return m_iv_angRotation; } CInterpolatedVar< Vector >& C_BaseEntity::GetOriginInterpolator() { return m_iv_vecOrigin; } //----------------------------------------------------------------------------- // Purpose: Return a per-entity shadow cast direction //----------------------------------------------------------------------------- bool C_BaseEntity::GetShadowCastDirection( Vector *pDirection, ShadowType_t shadowType ) const { if ( m_ShadowDirUseOtherEntity ) return m_ShadowDirUseOtherEntity->GetShadowCastDirection( pDirection, shadowType ); return false; } //----------------------------------------------------------------------------- // Should this object receive shadows? //----------------------------------------------------------------------------- bool C_BaseEntity::ShouldReceiveProjectedTextures( int flags ) { Assert( flags & SHADOW_FLAGS_PROJECTED_TEXTURE_TYPE_MASK ); if ( IsEffectActive( EF_NODRAW ) ) return false; if( flags & SHADOW_FLAGS_FLASHLIGHT ) { if ( GetRenderMode() > kRenderNormal && GetRenderColor().a == 0 ) return false; return true; } Assert( flags & SHADOW_FLAGS_SHADOW ); if ( IsEffectActive( EF_NORECEIVESHADOW ) ) return false; if (modelinfo->GetModelType( model ) == mod_studio) return false; return true; } //----------------------------------------------------------------------------- // Shadow-related methods //----------------------------------------------------------------------------- bool C_BaseEntity::IsShadowDirty( ) { return IsEFlagSet( EFL_DIRTY_SHADOWUPDATE ); } void C_BaseEntity::MarkShadowDirty( bool bDirty ) { if ( bDirty ) { AddEFlags( EFL_DIRTY_SHADOWUPDATE ); } else { RemoveEFlags( EFL_DIRTY_SHADOWUPDATE ); } } IClientRenderable *C_BaseEntity::GetShadowParent() { C_BaseEntity *pParent = GetMoveParent(); return pParent ? pParent->GetClientRenderable() : NULL; } IClientRenderable *C_BaseEntity::FirstShadowChild() { C_BaseEntity *pChild = FirstMoveChild(); return pChild ? pChild->GetClientRenderable() : NULL; } IClientRenderable *C_BaseEntity::NextShadowPeer() { C_BaseEntity *pPeer = NextMovePeer(); return pPeer ? pPeer->GetClientRenderable() : NULL; } //----------------------------------------------------------------------------- // Purpose: Returns index into entities list for this entity // Output : Index //----------------------------------------------------------------------------- int C_BaseEntity::entindex( void ) const { return index; } int C_BaseEntity::GetSoundSourceIndex() const { #ifdef _DEBUG if ( index != -1 ) { Assert( index == GetRefEHandle().GetEntryIndex() ); } #endif return GetRefEHandle().GetEntryIndex(); } //----------------------------------------------------------------------------- // Get render origin and angles //----------------------------------------------------------------------------- const Vector& C_BaseEntity::GetRenderOrigin( void ) { return GetAbsOrigin(); } const QAngle& C_BaseEntity::GetRenderAngles( void ) { return GetAbsAngles(); } const matrix3x4_t &C_BaseEntity::RenderableToWorldTransform() { return EntityToWorldTransform(); } IPVSNotify* C_BaseEntity::GetPVSNotifyInterface() { return NULL; } //----------------------------------------------------------------------------- // Purpose: // Input : theMins - // theMaxs - //----------------------------------------------------------------------------- void C_BaseEntity::GetRenderBounds( Vector& theMins, Vector& theMaxs ) { int nModelType = modelinfo->GetModelType( model ); if (nModelType == mod_studio || nModelType == mod_brush) { modelinfo->GetModelRenderBounds( GetModel(), theMins, theMaxs ); } else { // By default, we'll just snack on the collision bounds, transform // them into entity-space, and call it a day. if ( GetRenderAngles() == CollisionProp()->GetCollisionAngles() ) { theMins = CollisionProp()->OBBMins(); theMaxs = CollisionProp()->OBBMaxs(); } else { Assert( CollisionProp()->GetCollisionAngles() == vec3_angle ); if ( IsPointSized() ) { //theMins = CollisionProp()->GetCollisionOrigin(); //theMaxs = theMins; theMins = theMaxs = vec3_origin; } else { // NOTE: This shouldn't happen! Or at least, I haven't run // into a valid case where it should yet. // Assert(0); IRotateAABB( EntityToWorldTransform(), CollisionProp()->OBBMins(), CollisionProp()->OBBMaxs(), theMins, theMaxs ); } } } } void C_BaseEntity::GetRenderBoundsWorldspace( Vector& mins, Vector& maxs ) { DefaultRenderBoundsWorldspace( this, mins, maxs ); } void C_BaseEntity::GetShadowRenderBounds( Vector &mins, Vector &maxs, ShadowType_t shadowType ) { m_EntClientFlags |= ENTCLIENTFLAG_GETTINGSHADOWRENDERBOUNDS; GetRenderBounds( mins, maxs ); m_EntClientFlags &= ~ENTCLIENTFLAG_GETTINGSHADOWRENDERBOUNDS; } //----------------------------------------------------------------------------- // Purpose: Last received origin // Output : const float //----------------------------------------------------------------------------- const Vector& C_BaseEntity::GetAbsOrigin( void ) const { Assert( s_bAbsQueriesValid ); const_cast<C_BaseEntity*>(this)->CalcAbsolutePosition(); return m_vecAbsOrigin; } //----------------------------------------------------------------------------- // Purpose: Last received angles // Output : const //----------------------------------------------------------------------------- const QAngle& C_BaseEntity::GetAbsAngles( void ) const { Assert( s_bAbsQueriesValid ); const_cast<C_BaseEntity*>(this)->CalcAbsolutePosition(); return m_angAbsRotation; } //----------------------------------------------------------------------------- // Purpose: // Input : org - //----------------------------------------------------------------------------- void C_BaseEntity::SetNetworkOrigin( const Vector& org ) { m_vecNetworkOrigin = org; } //----------------------------------------------------------------------------- // Purpose: // Input : ang - //----------------------------------------------------------------------------- void C_BaseEntity::SetNetworkAngles( const QAngle& ang ) { m_angNetworkAngles = ang; } //----------------------------------------------------------------------------- // Purpose: // Output : const Vector& //----------------------------------------------------------------------------- const Vector& C_BaseEntity::GetNetworkOrigin() const { return m_vecNetworkOrigin; } //----------------------------------------------------------------------------- // Purpose: // Output : const QAngle& //----------------------------------------------------------------------------- const QAngle& C_BaseEntity::GetNetworkAngles() const { return m_angNetworkAngles; } //----------------------------------------------------------------------------- // Purpose: Get current model pointer for this entity // Output : const struct model_s //----------------------------------------------------------------------------- const model_t *C_BaseEntity::GetModel( void ) const { return model; } //----------------------------------------------------------------------------- // Purpose: Get model index for this entity // Output : int - model index //----------------------------------------------------------------------------- int C_BaseEntity::GetModelIndex( void ) const { return m_nModelIndex; } //----------------------------------------------------------------------------- // Purpose: // Input : index - //----------------------------------------------------------------------------- void C_BaseEntity::SetModelIndex( int index ) { m_nModelIndex = index; const model_t *pModel = modelinfo->GetModel( m_nModelIndex ); SetModelPointer( pModel ); } void C_BaseEntity::SetModelPointer( const model_t *pModel ) { if ( pModel != model ) { DestroyModelInstance(); model = pModel; OnNewModel(); UpdateVisibility(); } } //----------------------------------------------------------------------------- // Purpose: // Input : val - // moveCollide - //----------------------------------------------------------------------------- void C_BaseEntity::SetMoveType( MoveType_t val, MoveCollide_t moveCollide /*= MOVECOLLIDE_DEFAULT*/ ) { // Make sure the move type + move collide are compatible... #ifdef _DEBUG if ((val != MOVETYPE_FLY) && (val != MOVETYPE_FLYGRAVITY)) { Assert( moveCollide == MOVECOLLIDE_DEFAULT ); } #endif m_MoveType = val; SetMoveCollide( moveCollide ); } void C_BaseEntity::SetMoveCollide( MoveCollide_t val ) { m_MoveCollide = val; } //----------------------------------------------------------------------------- // Purpose: Get rendermode // Output : int - the render mode //----------------------------------------------------------------------------- bool C_BaseEntity::IsTransparent( void ) { bool modelIsTransparent = modelinfo->IsTranslucent(model); return modelIsTransparent || (m_nRenderMode != kRenderNormal); } bool C_BaseEntity::IsTwoPass( void ) { return modelinfo->IsTranslucentTwoPass( GetModel() ); } bool C_BaseEntity::UsesPowerOfTwoFrameBufferTexture() { return false; } bool C_BaseEntity::UsesFullFrameBufferTexture() { return false; } //----------------------------------------------------------------------------- // Purpose: Get pointer to CMouthInfo data // Output : CMouthInfo //----------------------------------------------------------------------------- CMouthInfo *C_BaseEntity::GetMouth( void ) { return NULL; } //----------------------------------------------------------------------------- // Purpose: Retrieve sound spatialization info for the specified sound on this entity // Input : info - // Output : Return false to indicate sound is not audible //----------------------------------------------------------------------------- bool C_BaseEntity::GetSoundSpatialization( SpatializationInfo_t& info ) { // World is always audible if ( entindex() == 0 ) { return true; } // Out of PVS if ( IsDormant() ) { return false; } // pModel might be NULL, but modelinfo can handle that const model_t *pModel = GetModel(); if ( info.pflRadius ) { *info.pflRadius = modelinfo->GetModelRadius( pModel ); } if ( info.pOrigin ) { *info.pOrigin = GetAbsOrigin(); // move origin to middle of brush if ( modelinfo->GetModelType( pModel ) == mod_brush ) { Vector mins, maxs, center; modelinfo->GetModelBounds( pModel, mins, maxs ); VectorAdd( mins, maxs, center ); VectorScale( center, 0.5f, center ); (*info.pOrigin) += center; } } if ( info.pAngles ) { VectorCopy( GetAbsAngles(), *info.pAngles ); } return true; } //----------------------------------------------------------------------------- // Purpose: Get attachment point by index // Input : number - which point // Output : float * - the attachment point //----------------------------------------------------------------------------- bool C_BaseEntity::GetAttachment( int number, Vector &origin, QAngle &angles ) { origin = GetAbsOrigin(); angles = GetAbsAngles(); return true; } bool C_BaseEntity::GetAttachment( int number, Vector &origin ) { origin = GetAbsOrigin(); return true; } bool C_BaseEntity::GetAttachment( int number, matrix3x4_t &matrix ) { MatrixCopy( EntityToWorldTransform(), matrix ); return true; } bool C_BaseEntity::GetAttachmentVelocity( int number, Vector &originVel, Quaternion &angleVel ) { originVel = GetAbsVelocity(); angleVel.Init(); return true; } //----------------------------------------------------------------------------- // Purpose: Get this entity's rendering clip plane if one is defined // Output : float * - The clip plane to use, or NULL if no clip plane is defined //----------------------------------------------------------------------------- float *C_BaseEntity::GetRenderClipPlane( void ) { if( m_bEnableRenderingClipPlane ) return m_fRenderingClipPlane; else return NULL; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- int C_BaseEntity::DrawBrushModel( bool bSort, bool bShadowDepth ) { VPROF_BUDGET( "C_BaseEntity::DrawBrushModel", VPROF_BUDGETGROUP_BRUSHMODEL_RENDERING ); // Identity brushes are drawn in view->DrawWorld as an optimization Assert ( modelinfo->GetModelType( model ) == mod_brush ); if ( bShadowDepth ) { render->DrawBrushModelShadowDepth( this, (model_t *)model, GetAbsOrigin(), GetAbsAngles(), bSort ); } else { render->DrawBrushModel( this, (model_t *)model, GetAbsOrigin(), GetAbsAngles(), bSort ); } return 1; } //----------------------------------------------------------------------------- // Purpose: Draws the object // Input : flags - //----------------------------------------------------------------------------- int C_BaseEntity::DrawModel( int flags ) { if ( !m_bReadyToDraw ) return 0; int drawn = 0; if ( !model ) { return drawn; } int modelType = modelinfo->GetModelType( model ); switch ( modelType ) { case mod_brush: drawn = DrawBrushModel( flags & STUDIO_TRANSPARENCY ? true : false, flags & STUDIO_SHADOWDEPTHTEXTURE ? true : false ); break; case mod_studio: // All studio models must be derived from C_BaseAnimating. Issue warning. Warning( "ERROR: Can't draw studio model %s because %s is not derived from C_BaseAnimating\n", modelinfo->GetModelName( model ), GetClientClass()->m_pNetworkName ? GetClientClass()->m_pNetworkName : "unknown" ); break; case mod_sprite: //drawn = DrawSprite(); Warning( "ERROR: Sprite model's not supported any more except in legacy temp ents\n" ); break; default: break; } // If we're visualizing our bboxes, draw them DrawBBoxVisualizations(); return drawn; } //----------------------------------------------------------------------------- // Purpose: Setup the bones for drawing //----------------------------------------------------------------------------- bool C_BaseEntity::SetupBones( matrix3x4_t *pBoneToWorldOut, int nMaxBones, int boneMask, float currentTime ) { return true; } //----------------------------------------------------------------------------- // Purpose: Setup vertex weights for drawing //----------------------------------------------------------------------------- void C_BaseEntity::SetupWeights( const matrix3x4_t *pBoneToWorld, int nFlexWeightCount, float *pFlexWeights, float *pFlexDelayedWeights ) { } //----------------------------------------------------------------------------- // Purpose: Process any local client-side animation events //----------------------------------------------------------------------------- void C_BaseEntity::DoAnimationEvents( ) { } void C_BaseEntity::UpdatePartitionListEntry() { // Don't add the world entity CollideType_t shouldCollide = GetCollideType(); // Choose the list based on what kind of collisions we want int list = PARTITION_CLIENT_NON_STATIC_EDICTS; if (shouldCollide == ENTITY_SHOULD_COLLIDE) list |= PARTITION_CLIENT_SOLID_EDICTS; else if (shouldCollide == ENTITY_SHOULD_RESPOND) list |= PARTITION_CLIENT_RESPONSIVE_EDICTS; // add the entity to the KD tree so we will collide against it partition->RemoveAndInsert( PARTITION_CLIENT_SOLID_EDICTS | PARTITION_CLIENT_RESPONSIVE_EDICTS | PARTITION_CLIENT_NON_STATIC_EDICTS, list, CollisionProp()->GetPartitionHandle() ); } void C_BaseEntity::NotifyShouldTransmit( ShouldTransmitState_t state ) { // Init should have been called before we get in here. Assert( CollisionProp()->GetPartitionHandle() != PARTITION_INVALID_HANDLE ); if ( entindex() < 0 ) return; switch( state ) { case SHOULDTRANSMIT_START: { // We've just been sent by the server. Become active. SetDormant( false ); UpdatePartitionListEntry(); #if !defined( NO_ENTITY_PREDICTION ) // Note that predictables get a chance to hook up to their server counterparts here if ( m_PredictableID.IsActive() ) { // Find corresponding client side predicted entity and remove it from predictables m_PredictableID.SetAcknowledged( true ); C_BaseEntity *otherEntity = FindPreviouslyCreatedEntity( m_PredictableID ); if ( otherEntity ) { Assert( otherEntity->IsClientCreated() ); Assert( otherEntity->m_PredictableID.IsActive() ); Assert( ClientEntityList().IsHandleValid( otherEntity->GetClientHandle() ) ); otherEntity->m_PredictableID.SetAcknowledged( true ); if ( OnPredictedEntityRemove( false, otherEntity ) ) { // Mark it for delete after receive all network data otherEntity->Release(); } } } #endif } break; case SHOULDTRANSMIT_END: { // Clear out links if we're out of the picture... UnlinkFromHierarchy(); // We're no longer being sent by the server. Become dormant. SetDormant( true ); // remove the entity from the KD tree so we won't collide against it partition->Remove( PARTITION_CLIENT_SOLID_EDICTS | PARTITION_CLIENT_RESPONSIVE_EDICTS | PARTITION_CLIENT_NON_STATIC_EDICTS, CollisionProp()->GetPartitionHandle() ); } break; default: Assert( 0 ); break; } } //----------------------------------------------------------------------------- // Call this in PostDataUpdate if you don't chain it down! //----------------------------------------------------------------------------- void C_BaseEntity::MarkMessageReceived() { m_flLastMessageTime = engine->GetLastTimeStamp(); } //----------------------------------------------------------------------------- // Purpose: Entity is about to be decoded from the network stream // Input : bnewentity - is this a new entity this update? //----------------------------------------------------------------------------- void C_BaseEntity::PreDataUpdate( DataUpdateType_t updateType ) { // Register for an OnDataChanged call and call OnPreDataChanged(). if ( AddDataChangeEvent( this, updateType, &m_DataChangeEventRef ) ) { OnPreDataChanged( updateType ); } // Need to spawn on client before receiving original network data // in case it overrides any values set up in spawn ( e.g., m_iState ) bool bnewentity = (updateType == DATA_UPDATE_CREATED); if ( !bnewentity ) { Interp_RestoreToLastNetworked( GetVarMapping() ); } if ( bnewentity && !IsClientCreated() ) { m_flSpawnTime = engine->GetLastTimeStamp(); MDLCACHE_CRITICAL_SECTION(); Spawn(); } #if 0 // Yahn suggesting commenting this out as a fix to demo recording not working // If the entity moves itself every FRAME on the server but doesn't update animtime, // then use the current server time as the time for interpolation. if ( IsSelfAnimating() ) { m_flAnimTime = engine->GetLastTimeStamp(); } #endif m_vecOldOrigin = GetNetworkOrigin(); m_vecOldAngRotation = GetNetworkAngles(); m_flOldAnimTime = m_flAnimTime; m_flOldSimulationTime = m_flSimulationTime; m_nOldRenderMode = m_nRenderMode; if ( m_hRender != INVALID_CLIENT_RENDER_HANDLE ) { ClientLeafSystem()->EnableAlternateSorting( m_hRender, m_bAlternateSorting ); } } const Vector& C_BaseEntity::GetOldOrigin() { return m_vecOldOrigin; } void C_BaseEntity::UnlinkChild( C_BaseEntity *pParent, C_BaseEntity *pChild ) { Assert( pChild ); Assert( pParent != pChild ); Assert( pChild->GetMoveParent() == pParent ); // Unlink from parent // NOTE: pParent *may well be NULL*! This occurs // when a child has unlinked from a parent, and the child // remains in the PVS but the parent has not if (pParent && (pParent->m_pMoveChild == pChild)) { Assert( !(pChild->m_pMovePrevPeer.IsValid()) ); pParent->m_pMoveChild = pChild->m_pMovePeer; } // Unlink from siblings... if (pChild->m_pMovePrevPeer) { pChild->m_pMovePrevPeer->m_pMovePeer = pChild->m_pMovePeer; } if (pChild->m_pMovePeer) { pChild->m_pMovePeer->m_pMovePrevPeer = pChild->m_pMovePrevPeer; } pChild->m_pMovePeer = NULL; pChild->m_pMovePrevPeer = NULL; pChild->m_pMoveParent = NULL; pChild->RemoveFromAimEntsList(); Interp_HierarchyUpdateInterpolationAmounts(); } void C_BaseEntity::LinkChild( C_BaseEntity *pParent, C_BaseEntity *pChild ) { Assert( !pChild->m_pMovePeer.IsValid() ); Assert( !pChild->m_pMovePrevPeer.IsValid() ); Assert( !pChild->m_pMoveParent.IsValid() ); Assert( pParent != pChild ); #ifdef _DEBUG // Make sure the child isn't already in this list C_BaseEntity *pExistingChild; for ( pExistingChild = pParent->FirstMoveChild(); pExistingChild; pExistingChild = pExistingChild->NextMovePeer() ) { Assert( pChild != pExistingChild ); } #endif pChild->m_pMovePrevPeer = NULL; pChild->m_pMovePeer = pParent->m_pMoveChild; if (pChild->m_pMovePeer) { pChild->m_pMovePeer->m_pMovePrevPeer = pChild; } pParent->m_pMoveChild = pChild; pChild->m_pMoveParent = pParent; pChild->AddToAimEntsList(); Interp_HierarchyUpdateInterpolationAmounts(); } CUtlVector< C_BaseEntity * > g_AimEntsList; //----------------------------------------------------------------------------- // Moves all aiments //----------------------------------------------------------------------------- void C_BaseEntity::MarkAimEntsDirty() { // FIXME: With the dirty bits hooked into cycle + sequence, it's unclear // that this is even necessary any more (provided aiments are always accessing // joints or attachments of the move parent). // // NOTE: This is a tricky algorithm. This list does not actually contain // all aim-ents in its list. It actually contains all hierarchical children, // of which aim-ents are a part. We can tell if something is an aiment if it has // the EF_BONEMERGE effect flag set. // // We will first iterate over all aiments and clear their DIRTY_ABSTRANSFORM flag, // which is necessary to cause them to recompute their aim-ent origin // the next time CalcAbsPosition is called. Because CalcAbsPosition calls MoveToAimEnt // and MoveToAimEnt calls SetAbsOrigin/SetAbsAngles, that is how CalcAbsPosition // will cause the aim-ent's (and all its children's) dirty state to be correctly updated. // // Then we will iterate over the loop a second time and call CalcAbsPosition on them, int i; int c = g_AimEntsList.Count(); for ( i = 0; i < c; ++i ) { C_BaseEntity *pEnt = g_AimEntsList[ i ]; Assert( pEnt && pEnt->GetMoveParent() ); if ( pEnt->IsEffectActive(EF_BONEMERGE | EF_PARENT_ANIMATES) ) { pEnt->AddEFlags( EFL_DIRTY_ABSTRANSFORM ); } } } void C_BaseEntity::CalcAimEntPositions() { VPROF("CalcAimEntPositions"); int i; int c = g_AimEntsList.Count(); for ( i = 0; i < c; ++i ) { C_BaseEntity *pEnt = g_AimEntsList[ i ]; Assert( pEnt ); Assert( pEnt->GetMoveParent() ); if ( pEnt->IsEffectActive(EF_BONEMERGE) ) { pEnt->CalcAbsolutePosition( ); } } } void C_BaseEntity::AddToAimEntsList() { // Already in list if ( m_AimEntsListHandle != INVALID_AIMENTS_LIST_HANDLE ) return; m_AimEntsListHandle = g_AimEntsList.AddToTail( this ); } void C_BaseEntity::RemoveFromAimEntsList() { // Not in list yet if ( INVALID_AIMENTS_LIST_HANDLE == m_AimEntsListHandle ) { return; } unsigned int c = g_AimEntsList.Count(); Assert( m_AimEntsListHandle < c ); unsigned int last = c - 1; if ( last == m_AimEntsListHandle ) { // Just wipe the final entry g_AimEntsList.FastRemove( last ); } else { C_BaseEntity *lastEntity = g_AimEntsList[ last ]; // Remove the last entry g_AimEntsList.FastRemove( last ); // And update it's handle to point to this slot. lastEntity->m_AimEntsListHandle = m_AimEntsListHandle; g_AimEntsList[ m_AimEntsListHandle ] = lastEntity; } // Invalidate our handle no matter what. m_AimEntsListHandle = INVALID_AIMENTS_LIST_HANDLE; } //----------------------------------------------------------------------------- // Update move-parent if needed. For SourceTV. //----------------------------------------------------------------------------- void C_BaseEntity::HierarchyUpdateMoveParent() { if ( m_hNetworkMoveParent.ToInt() == m_pMoveParent.ToInt() ) return; HierarchySetParent( m_hNetworkMoveParent ); } //----------------------------------------------------------------------------- // Connects us up to hierarchy //----------------------------------------------------------------------------- void C_BaseEntity::HierarchySetParent( C_BaseEntity *pNewParent ) { // NOTE: When this is called, we expect to have a valid // local origin, etc. that we received from network daa EHANDLE newParentHandle; newParentHandle.Set( pNewParent ); if (newParentHandle.ToInt() == m_pMoveParent.ToInt()) return; if (m_pMoveParent.IsValid()) { UnlinkChild( m_pMoveParent, this ); } if (pNewParent) { LinkChild( pNewParent, this ); } InvalidatePhysicsRecursive( POSITION_CHANGED | ANGLES_CHANGED | VELOCITY_CHANGED ); } //----------------------------------------------------------------------------- // Unlinks from hierarchy //----------------------------------------------------------------------------- void C_BaseEntity::SetParent( C_BaseEntity *pParentEntity, int iParentAttachment ) { // NOTE: This version is meant to be called *outside* of PostDataUpdate // as it assumes the moveparent has a valid handle EHANDLE newParentHandle; newParentHandle.Set( pParentEntity ); if (newParentHandle.ToInt() == m_pMoveParent.ToInt()) return; // NOTE: Have to do this before the unlink to ensure local coords are valid Vector vecAbsOrigin = GetAbsOrigin(); QAngle angAbsRotation = GetAbsAngles(); Vector vecAbsVelocity = GetAbsVelocity(); // First deal with unlinking if (m_pMoveParent.IsValid()) { UnlinkChild( m_pMoveParent, this ); } if (pParentEntity) { LinkChild( pParentEntity, this ); } m_iParentAttachment = iParentAttachment; m_vecAbsOrigin.Init( FLT_MAX, FLT_MAX, FLT_MAX ); m_angAbsRotation.Init( FLT_MAX, FLT_MAX, FLT_MAX ); m_vecAbsVelocity.Init( FLT_MAX, FLT_MAX, FLT_MAX ); SetAbsOrigin(vecAbsOrigin); SetAbsAngles(angAbsRotation); SetAbsVelocity(vecAbsVelocity); } //----------------------------------------------------------------------------- // Unlinks from hierarchy //----------------------------------------------------------------------------- void C_BaseEntity::UnlinkFromHierarchy() { // Clear out links if we're out of the picture... if ( m_pMoveParent.IsValid() ) { UnlinkChild( m_pMoveParent, this ); } //Adrian: This was causing problems with the local network backdoor with entities coming in and out of the PVS at certain times. //This would work fine if a full entity update was coming (caused by certain factors like too many entities entering the pvs at once). //but otherwise it would not detect the change on the client (since the server and client shouldn't be out of sync) and the var would not be updated like it should. //m_iParentAttachment = 0; // unlink also all move children C_BaseEntity *pChild = FirstMoveChild(); while( pChild ) { if ( pChild->m_pMoveParent != this ) { Warning( "C_BaseEntity::UnlinkFromHierarchy(): Entity has a child with the wrong parent!\n" ); Assert( 0 ); UnlinkChild( this, pChild ); pChild->UnlinkFromHierarchy(); } else pChild->UnlinkFromHierarchy(); pChild = FirstMoveChild(); } } //----------------------------------------------------------------------------- // Purpose: Make sure that the correct model is referenced for this entity //----------------------------------------------------------------------------- void C_BaseEntity::ValidateModelIndex( void ) { SetModelByIndex( m_nModelIndex ); } //----------------------------------------------------------------------------- // Purpose: Entity data has been parsed and unpacked. Now do any necessary decoding, munging // Input : bnewentity - was this entity new in this update packet? //----------------------------------------------------------------------------- void C_BaseEntity::PostDataUpdate( DataUpdateType_t updateType ) { MDLCACHE_CRITICAL_SECTION(); PREDICTION_TRACKVALUECHANGESCOPE_ENTITY( this, "postdataupdate" ); // NOTE: This *has* to happen first. Otherwise, Origin + angles may be wrong if ( m_nRenderFX == kRenderFxRagdoll && updateType == DATA_UPDATE_CREATED ) { MoveToLastReceivedPosition( true ); } else { MoveToLastReceivedPosition( false ); } // If it's the world, force solid flags if ( index == 0 ) { m_nModelIndex = 1; SetSolid( SOLID_BSP ); // FIXME: Should these be assertions? SetAbsOrigin( vec3_origin ); SetAbsAngles( vec3_angle ); } if ( m_nOldRenderMode != m_nRenderMode ) { SetRenderMode( (RenderMode_t)m_nRenderMode, true ); } bool animTimeChanged = ( m_flAnimTime != m_flOldAnimTime ) ? true : false; bool originChanged = ( m_vecOldOrigin != GetLocalOrigin() ) ? true : false; bool anglesChanged = ( m_vecOldAngRotation != GetLocalAngles() ) ? true : false; bool simTimeChanged = ( m_flSimulationTime != m_flOldSimulationTime ) ? true : false; // Detect simulation changes bool simulationChanged = originChanged || anglesChanged || simTimeChanged; bool bPredictable = GetPredictable(); // For non-predicted and non-client only ents, we need to latch network values into the interpolation histories if ( !bPredictable && !IsClientCreated() ) { if ( animTimeChanged ) { OnLatchInterpolatedVariables( LATCH_ANIMATION_VAR ); } if ( simulationChanged ) { OnLatchInterpolatedVariables( LATCH_SIMULATION_VAR ); } } // For predictables, we also need to store off the last networked value else if ( bPredictable ) { // Just store off last networked value for use in prediction OnStoreLastNetworkedValue(); } // Deal with hierarchy. Have to do it here (instead of in a proxy) // because this is the only point at which all entities are loaded // If this condition isn't met, then a child was sent without its parent Assert( m_hNetworkMoveParent.Get() || !m_hNetworkMoveParent.IsValid() ); HierarchySetParent(m_hNetworkMoveParent); MarkMessageReceived(); // Make sure that the correct model is referenced for this entity ValidateModelIndex(); // If this entity was new, then latch in various values no matter what. if ( updateType == DATA_UPDATE_CREATED ) { // Construct a random value for this instance m_flProxyRandomValue = random->RandomFloat( 0, 1 ); ResetLatched(); m_nCreationTick = gpGlobals->tickcount; } CheckInitPredictable( "PostDataUpdate" ); // It's possible that a new entity will need to be forceably added to the // player simulation list. If so, do this here #if !defined( NO_ENTITY_PREDICTION ) C_BasePlayer *local = C_BasePlayer::GetLocalPlayer(); if ( IsPlayerSimulated() && ( NULL != local ) && ( local == m_hOwnerEntity ) ) { // Make sure player is driving simulation (field is only ever sent to local player) SetPlayerSimulated( local ); } #endif UpdatePartitionListEntry(); // Add the entity to the nointerp list. if ( !IsClientCreated() ) { if ( Teleported() || IsEffectActive(EF_NOINTERP) ) AddToTeleportList(); } // if we changed parents, recalculate visibility if ( m_hOldMoveParent != m_hNetworkMoveParent ) { UpdateVisibility(); } } //----------------------------------------------------------------------------- // Purpose: // Input : *context - //----------------------------------------------------------------------------- void C_BaseEntity::CheckInitPredictable( const char *context ) { #if !defined( NO_ENTITY_PREDICTION ) // Prediction is disabled if ( !cl_predict->GetInt() ) return; C_BasePlayer *player = C_BasePlayer::GetLocalPlayer(); if ( !player ) return; if ( !GetPredictionEligible() ) { if ( m_PredictableID.IsActive() && ( player->index - 1 ) == m_PredictableID.GetPlayer() ) { // If it comes through with an ID, it should be eligible SetPredictionEligible( true ); } else { return; } } if ( IsClientCreated() ) return; if ( !ShouldPredict() ) return; if ( IsIntermediateDataAllocated() ) return; // Msg( "Predicting init %s at %s\n", GetClassname(), context ); InitPredictable(); #endif } bool C_BaseEntity::IsSelfAnimating() { return true; } //----------------------------------------------------------------------------- // EFlags.. //----------------------------------------------------------------------------- int C_BaseEntity::GetEFlags() const { return m_iEFlags; } void C_BaseEntity::SetEFlags( int iEFlags ) { m_iEFlags = iEFlags; } //----------------------------------------------------------------------------- // Sets the model... //----------------------------------------------------------------------------- void C_BaseEntity::SetModelByIndex( int nModelIndex ) { SetModelIndex( nModelIndex ); } //----------------------------------------------------------------------------- // Set model... (NOTE: Should only be used by client-only entities //----------------------------------------------------------------------------- bool C_BaseEntity::SetModel( const char *pModelName ) { if ( pModelName ) { int nModelIndex = modelinfo->GetModelIndex( pModelName ); SetModelByIndex( nModelIndex ); return ( nModelIndex != -1 ); } else { SetModelByIndex( -1 ); return false; } } void C_BaseEntity::OnStoreLastNetworkedValue() { bool bRestore = false; Vector savePos; QAngle saveAng; // Kind of a hack, but we want to latch the actual networked value for origin/angles, not what's sitting in m_vecOrigin in the // ragdoll case where we don't copy it over in MoveToLastNetworkOrigin if ( m_nRenderFX == kRenderFxRagdoll && GetPredictable() ) { bRestore = true; savePos = GetLocalOrigin(); saveAng = GetLocalAngles(); MoveToLastReceivedPosition( true ); } int c = m_VarMap.m_Entries.Count(); for ( int i = 0; i < c; i++ ) { VarMapEntry_t *e = &m_VarMap.m_Entries[ i ]; IInterpolatedVar *watcher = e->watcher; int type = watcher->GetType(); if ( type & EXCLUDE_AUTO_LATCH ) continue; watcher->NoteLastNetworkedValue(); } if ( bRestore ) { SetLocalOrigin( savePos ); SetLocalAngles( saveAng ); } } //----------------------------------------------------------------------------- // Purpose: The animtime is about to be changed in a network update, store off various fields so that // we can use them to do blended sequence transitions, etc. // Input : *pState - the (mostly) previous state data //----------------------------------------------------------------------------- void C_BaseEntity::OnLatchInterpolatedVariables( int flags ) { float changetime = GetLastChangeTime( flags ); bool bUpdateLastNetworkedValue = !(flags & INTERPOLATE_OMIT_UPDATE_LAST_NETWORKED) ? true : false; PREDICTION_TRACKVALUECHANGESCOPE_ENTITY( this, bUpdateLastNetworkedValue ? "latch+net" : "latch" ); int c = m_VarMap.m_Entries.Count(); for ( int i = 0; i < c; i++ ) { VarMapEntry_t *e = &m_VarMap.m_Entries[ i ]; IInterpolatedVar *watcher = e->watcher; int type = watcher->GetType(); if ( !(type & flags) ) continue; if ( type & EXCLUDE_AUTO_LATCH ) continue; if ( watcher->NoteChanged( changetime, bUpdateLastNetworkedValue ) ) e->m_bNeedsToInterpolate = true; } if ( ShouldInterpolate() ) { AddToInterpolationList(); } } int CBaseEntity::BaseInterpolatePart1( float &currentTime, Vector &oldOrigin, QAngle &oldAngles, int &bNoMoreChanges ) { // Don't mess with the world!!! bNoMoreChanges = 1; // These get moved to the parent position automatically if ( IsFollowingEntity() || !IsInterpolationEnabled() ) { // Assume current origin ( no interpolation ) MoveToLastReceivedPosition(); return INTERPOLATE_STOP; } if ( GetPredictable() || IsClientCreated() ) { C_BasePlayer *localplayer = C_BasePlayer::GetLocalPlayer(); if ( localplayer && currentTime == gpGlobals->curtime ) { currentTime = localplayer->GetFinalPredictedTime(); currentTime -= TICK_INTERVAL; currentTime += ( gpGlobals->interpolation_amount * TICK_INTERVAL ); } } oldOrigin = m_vecOrigin; oldAngles = m_angRotation; bNoMoreChanges = Interp_Interpolate( GetVarMapping(), currentTime ); if ( cl_interp_all.GetInt() || (m_EntClientFlags & ENTCLIENTFLAG_ALWAYS_INTERPOLATE) ) bNoMoreChanges = 0; return INTERPOLATE_CONTINUE; } #if 0 static ConVar cl_watchplayer( "cl_watchplayer", "-1", 0 ); #endif void C_BaseEntity::BaseInterpolatePart2( Vector &oldOrigin, QAngle &oldAngles, int nChangeFlags ) { if ( m_vecOrigin != oldOrigin ) { nChangeFlags |= POSITION_CHANGED; } if( m_angRotation != oldAngles ) { nChangeFlags |= ANGLES_CHANGED; } if ( nChangeFlags != 0 ) { InvalidatePhysicsRecursive( nChangeFlags ); } #if 0 if ( IsPlayer() && cl_watchplayer.GetInt() == entindex() && C_BasePlayer::GetLocalPlayer() && GetTeam() == C_BasePlayer::GetLocalPlayer()->GetTeam() ) { // SpewInterpolatedVar( &m_iv_vecOrigin, gpGlobals->curtime, GetInterpolationAmount( LATCH_SIMULATION_VAR ), false ); Vector vel; EstimateAbsVelocity( vel ); float spd = vel.Length(); Msg( "estimated %f\n", spd ); } #endif } //----------------------------------------------------------------------------- // Purpose: Default interpolation for entities // Output : true means entity should be drawn, false means probably not //----------------------------------------------------------------------------- bool C_BaseEntity::Interpolate( float currentTime ) { VPROF( "C_BaseEntity::Interpolate" ); Vector oldOrigin; QAngle oldAngles; int bNoMoreChanges; int retVal = BaseInterpolatePart1( currentTime, oldOrigin, oldAngles, bNoMoreChanges ); // If all the Interpolate() calls returned that their values aren't going to // change anymore, then get us out of the interpolation list. if ( bNoMoreChanges ) RemoveFromInterpolationList(); if ( retVal == INTERPOLATE_STOP ) return true; int nChangeFlags = 0; BaseInterpolatePart2( oldOrigin, oldAngles, nChangeFlags ); return true; } CStudioHdr *C_BaseEntity::OnNewModel() { return NULL; } void C_BaseEntity::OnNewParticleEffect( const char *pszParticleName, CNewParticleEffect *pNewParticleEffect ) { return; } // Above this velocity and we'll assume a warp/teleport #define MAX_INTERPOLATE_VELOCITY 4000.0f #define MAX_INTERPOLATE_VELOCITY_PLAYER 1250.0f //----------------------------------------------------------------------------- // Purpose: Determine whether entity was teleported ( so we can disable interpolation ) // Input : *ent - // Output : bool //----------------------------------------------------------------------------- bool C_BaseEntity::Teleported( void ) { // Disable interpolation when hierarchy changes if (m_hOldMoveParent != m_hNetworkMoveParent || m_iOldParentAttachment != m_iParentAttachment) { return true; } return false; } //----------------------------------------------------------------------------- // Purpose: Is this a submodel of the world ( model name starts with * )? // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool C_BaseEntity::IsSubModel( void ) { if ( model && modelinfo->GetModelType( model ) == mod_brush && modelinfo->GetModelName( model )[0] == '*' ) { return true; } return false; } //----------------------------------------------------------------------------- // Purpose: Create entity lighting effects //----------------------------------------------------------------------------- void C_BaseEntity::CreateLightEffects( void ) { dlight_t *dl; // Is this for player flashlights only, if so move to linkplayers? if ( index == render->GetViewEntity() ) return; if (IsEffectActive(EF_BRIGHTLIGHT)) { dl = effects->CL_AllocDlight ( index ); dl->origin = GetAbsOrigin(); dl->origin[2] += 16; dl->color.r = dl->color.g = dl->color.b = 250; dl->radius = random->RandomFloat(400,431); dl->die = gpGlobals->curtime + 0.001; } if (IsEffectActive(EF_DIMLIGHT)) { dl = effects->CL_AllocDlight ( index ); dl->origin = GetAbsOrigin(); dl->color.r = dl->color.g = dl->color.b = 100; dl->radius = random->RandomFloat(200,231); dl->die = gpGlobals->curtime + 0.001; } } void C_BaseEntity::MoveToLastReceivedPosition( bool force ) { if ( force || ( m_nRenderFX != kRenderFxRagdoll ) ) { SetLocalOrigin( GetNetworkOrigin() ); SetLocalAngles( GetNetworkAngles() ); } } bool C_BaseEntity::ShouldInterpolate() { if ( render->GetViewEntity() == index ) return true; if ( index == 0 || !GetModel() ) return false; // always interpolate if visible if ( IsVisible() ) return true; // if any movement child needs interpolation, we have to interpolate too C_BaseEntity *pChild = FirstMoveChild(); while( pChild ) { if ( pChild->ShouldInterpolate() ) return true; pChild = pChild->NextMovePeer(); } // don't interpolate return false; } void C_BaseEntity::ProcessTeleportList() { int iNext; for ( int iCur=g_TeleportList.Head(); iCur != g_TeleportList.InvalidIndex(); iCur=iNext ) { iNext = g_TeleportList.Next( iCur ); C_BaseEntity *pCur = g_TeleportList[iCur]; bool teleport = pCur->Teleported(); bool ef_nointerp = pCur->IsEffectActive(EF_NOINTERP); if ( teleport || ef_nointerp ) { // Undo the teleport flag.. pCur->m_hOldMoveParent = pCur->m_hNetworkMoveParent; pCur->m_iOldParentAttachment = pCur->m_iParentAttachment; // Zero out all but last update. pCur->MoveToLastReceivedPosition( true ); pCur->ResetLatched(); } else { // Get it out of the list as soon as we can. pCur->RemoveFromTeleportList(); } } } void C_BaseEntity::CheckInterpolatedVarParanoidMeasurement() { // What we're doing here is to check all the entities that were not in the interpolation // list and make sure that there's no entity that should be in the list that isn't. #ifdef INTERPOLATEDVAR_PARANOID_MEASUREMENT int iHighest = ClientEntityList().GetHighestEntityIndex(); for ( int i=0; i <= iHighest; i++ ) { C_BaseEntity *pEnt = ClientEntityList().GetBaseEntity( i ); if ( !pEnt || pEnt->m_InterpolationListEntry != 0xFFFF || !pEnt->ShouldInterpolate() ) continue; // Player angles always generates this error when the console is up. if ( pEnt->entindex() == 1 && engine->Con_IsVisible() ) continue; // View models tend to screw up this test unnecesarily because they modify origin, // angles, and if ( dynamic_cast<C_BaseViewModel*>( pEnt ) ) continue; g_bRestoreInterpolatedVarValues = true; g_nInterpolatedVarsChanged = 0; pEnt->Interpolate( gpGlobals->curtime ); g_bRestoreInterpolatedVarValues = false; if ( g_nInterpolatedVarsChanged > 0 ) { static int iWarningCount = 0; Warning( "(%d): An entity (%d) should have been in g_InterpolationList.\n", iWarningCount++, pEnt->entindex() ); break; } } #endif } void C_BaseEntity::ProcessInterpolatedList() { CheckInterpolatedVarParanoidMeasurement(); // Interpolate the minimal set of entities that need it. int iNext; for ( int iCur=g_InterpolationList.Head(); iCur != g_InterpolationList.InvalidIndex(); iCur=iNext ) { iNext = g_InterpolationList.Next( iCur ); C_BaseEntity *pCur = g_InterpolationList[iCur]; pCur->m_bReadyToDraw = pCur->Interpolate( gpGlobals->curtime ); } } //----------------------------------------------------------------------------- // Purpose: Add entity to visibile entities list //----------------------------------------------------------------------------- void C_BaseEntity::AddEntity( void ) { // Don't ever add the world, it's drawn separately if ( index == 0 ) return; // Create flashlight effects, etc. CreateLightEffects(); } //----------------------------------------------------------------------------- // Returns the aiment render origin + angles //----------------------------------------------------------------------------- void C_BaseEntity::GetAimEntOrigin( IClientEntity *pAttachedTo, Vector *pOrigin, QAngle *pAngles ) { // Should be overridden for things that attach to attchment points // Slam origin to the origin of the entity we are attached to... *pOrigin = pAttachedTo->GetAbsOrigin(); *pAngles = pAttachedTo->GetAbsAngles(); } void C_BaseEntity::StopFollowingEntity( ) { Assert( IsFollowingEntity() ); SetParent( NULL ); RemoveEffects( EF_BONEMERGE ); RemoveSolidFlags( FSOLID_NOT_SOLID ); SetMoveType( MOVETYPE_NONE ); } bool C_BaseEntity::IsFollowingEntity() { return IsEffectActive(EF_BONEMERGE) && (GetMoveType() == MOVETYPE_NONE) && GetMoveParent(); } C_BaseEntity *CBaseEntity::GetFollowedEntity() { if (!IsFollowingEntity()) return NULL; return GetMoveParent(); } //----------------------------------------------------------------------------- // Default implementation for GetTextureAnimationStartTime //----------------------------------------------------------------------------- float C_BaseEntity::GetTextureAnimationStartTime() { return m_flSpawnTime; } //----------------------------------------------------------------------------- // Default implementation, indicates that a texture animation has wrapped //----------------------------------------------------------------------------- void C_BaseEntity::TextureAnimationWrapped() { } void C_BaseEntity::ClientThink() { } void C_BaseEntity::Simulate() { AddEntity(); // Legacy support. Once-per-frame stuff should go in Simulate(). } // Defined in engine static ConVar cl_interpolate( "cl_interpolate", "1.0f", FCVAR_USERINFO | FCVAR_DEVELOPMENTONLY ); // (static function) void C_BaseEntity::InterpolateServerEntities() { VPROF_BUDGET( "C_BaseEntity::InterpolateServerEntities", VPROF_BUDGETGROUP_INTERPOLATION ); s_bInterpolate = cl_interpolate.GetBool(); // Don't interpolate during timedemo playback if ( engine->IsPlayingTimeDemo() ) { s_bInterpolate = false; } // Don't interpolate, either, if we are timing out INetChannelInfo *nci = engine->GetNetChannelInfo(); if ( nci && nci->GetTimeSinceLastReceived() > 0.5f ) { s_bInterpolate = false; } if ( IsSimulatingOnAlternateTicks() != g_bWasSkipping || IsEngineThreaded() != g_bWasThreaded || cl_interp_threadmodeticks.GetInt() != g_nThreadModeTicks ) { g_bWasSkipping = IsSimulatingOnAlternateTicks(); g_bWasThreaded = IsEngineThreaded(); g_nThreadModeTicks = cl_interp_threadmodeticks.GetInt(); C_BaseEntityIterator iterator; C_BaseEntity *pEnt; while ( (pEnt = iterator.Next()) != NULL ) { pEnt->Interp_UpdateInterpolationAmounts( pEnt->GetVarMapping() ); } } // Enable extrapolation? CInterpolationContext context; context.SetLastTimeStamp( engine->GetLastTimeStamp() ); if ( cl_extrapolate.GetBool() && !engine->IsPaused() ) { context.EnableExtrapolation( true ); } // Smoothly interpolate position for server entities. ProcessTeleportList(); ProcessInterpolatedList(); } // (static function) void C_BaseEntity::AddVisibleEntities() { #if !defined( NO_ENTITY_PREDICTION ) VPROF_BUDGET( "C_BaseEntity::AddVisibleEntities", VPROF_BUDGETGROUP_WORLD_RENDERING ); // Let non-dormant client created predictables get added, too int c = predictables->GetPredictableCount(); for ( int i = 0 ; i < c ; i++ ) { C_BaseEntity *pEnt = predictables->GetPredictable( i ); if ( !pEnt ) continue; if ( !pEnt->IsClientCreated() ) continue; // Only draw until it's ack'd since that means a real entity has arrived if ( pEnt->m_PredictableID.GetAcknowledged() ) continue; // Don't draw if dormant if ( pEnt->IsDormantPredictable() ) continue; pEnt->UpdateVisibility(); } #endif } //----------------------------------------------------------------------------- // Purpose: // Input : type - //----------------------------------------------------------------------------- void C_BaseEntity::OnPreDataChanged( DataUpdateType_t type ) { m_hOldMoveParent = m_hNetworkMoveParent; m_iOldParentAttachment = m_iParentAttachment; } void C_BaseEntity::OnDataChanged( DataUpdateType_t type ) { // See if it needs to allocate prediction stuff CheckInitPredictable( "OnDataChanged" ); // Set up shadows; do it here so that objects can change shadowcasting state CreateShadow(); if ( type == DATA_UPDATE_CREATED ) { UpdateVisibility(); } } ClientThinkHandle_t C_BaseEntity::GetThinkHandle() { return m_hThink; } void C_BaseEntity::SetThinkHandle( ClientThinkHandle_t hThink ) { m_hThink = hThink; } //----------------------------------------------------------------------------- // Purpose: This routine modulates renderamt according to m_nRenderFX's value // This is a client side effect and will not be in-sync on machines across a // network game. // Input : origin - // alpha - // Output : int //----------------------------------------------------------------------------- void C_BaseEntity::ComputeFxBlend( void ) { // Don't recompute if we've already computed this frame if ( m_nFXComputeFrame == gpGlobals->framecount ) return; MDLCACHE_CRITICAL_SECTION(); int blend=0; float offset; offset = ((int)index) * 363.0;// Use ent index to de-sync these fx switch( m_nRenderFX ) { case kRenderFxPulseSlowWide: blend = m_clrRender->a + 0x40 * sin( gpGlobals->curtime * 2 + offset ); break; case kRenderFxPulseFastWide: blend = m_clrRender->a + 0x40 * sin( gpGlobals->curtime * 8 + offset ); break; case kRenderFxPulseFastWider: blend = ( 0xff * fabs(sin( gpGlobals->curtime * 12 + offset ) ) ); break; case kRenderFxPulseSlow: blend = m_clrRender->a + 0x10 * sin( gpGlobals->curtime * 2 + offset ); break; case kRenderFxPulseFast: blend = m_clrRender->a + 0x10 * sin( gpGlobals->curtime * 8 + offset ); break; // JAY: HACK for now -- not time based case kRenderFxFadeSlow: if ( m_clrRender->a > 0 ) { SetRenderColorA( m_clrRender->a - 1 ); } else { SetRenderColorA( 0 ); } blend = m_clrRender->a; break; case kRenderFxFadeFast: if ( m_clrRender->a > 3 ) { SetRenderColorA( m_clrRender->a - 4 ); } else { SetRenderColorA( 0 ); } blend = m_clrRender->a; break; case kRenderFxSolidSlow: if ( m_clrRender->a < 255 ) { SetRenderColorA( m_clrRender->a + 1 ); } else { SetRenderColorA( 255 ); } blend = m_clrRender->a; break; case kRenderFxSolidFast: if ( m_clrRender->a < 252 ) { SetRenderColorA( m_clrRender->a + 4 ); } else { SetRenderColorA( 255 ); } blend = m_clrRender->a; break; case kRenderFxStrobeSlow: blend = 20 * sin( gpGlobals->curtime * 4 + offset ); if ( blend < 0 ) { blend = 0; } else { blend = m_clrRender->a; } break; case kRenderFxStrobeFast: blend = 20 * sin( gpGlobals->curtime * 16 + offset ); if ( blend < 0 ) { blend = 0; } else { blend = m_clrRender->a; } break; case kRenderFxStrobeFaster: blend = 20 * sin( gpGlobals->curtime * 36 + offset ); if ( blend < 0 ) { blend = 0; } else { blend = m_clrRender->a; } break; case kRenderFxFlickerSlow: blend = 20 * (sin( gpGlobals->curtime * 2 ) + sin( gpGlobals->curtime * 17 + offset )); if ( blend < 0 ) { blend = 0; } else { blend = m_clrRender->a; } break; case kRenderFxFlickerFast: blend = 20 * (sin( gpGlobals->curtime * 16 ) + sin( gpGlobals->curtime * 23 + offset )); if ( blend < 0 ) { blend = 0; } else { blend = m_clrRender->a; } break; case kRenderFxHologram: case kRenderFxDistort: { Vector tmp; float dist; VectorCopy( GetAbsOrigin(), tmp ); VectorSubtract( tmp, CurrentViewOrigin(), tmp ); dist = DotProduct( tmp, CurrentViewForward() ); // Turn off distance fade if ( m_nRenderFX == kRenderFxDistort ) { dist = 1; } if ( dist <= 0 ) { blend = 0; } else { SetRenderColorA( 180 ); if ( dist <= 100 ) blend = m_clrRender->a; else blend = (int) ((1.0 - (dist - 100) * (1.0 / 400.0)) * m_clrRender->a); blend += random->RandomInt(-32,31); } } break; case kRenderFxNone: case kRenderFxClampMinScale: default: if (m_nRenderMode == kRenderNormal) blend = 255; else blend = m_clrRender->a; break; } blend = clamp( blend, 0, 255 ); // Look for client-side fades unsigned char nFadeAlpha = GetClientSideFade(); if ( nFadeAlpha != 255 ) { float flBlend = blend / 255.0f; float flFade = nFadeAlpha / 255.0f; blend = (int)( flBlend * flFade * 255.0f + 0.5f ); blend = clamp( blend, 0, 255 ); } m_nRenderFXBlend = blend; m_nFXComputeFrame = gpGlobals->framecount; // Update the render group if ( GetRenderHandle() != INVALID_CLIENT_RENDER_HANDLE ) { ClientLeafSystem()->SetRenderGroup( GetRenderHandle(), GetRenderGroup() ); } // Tell our shadow if ( m_ShadowHandle != CLIENTSHADOW_INVALID_HANDLE ) { g_pClientShadowMgr->SetFalloffBias( m_ShadowHandle, (255 - m_nRenderFXBlend) ); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- int C_BaseEntity::GetFxBlend( void ) { Assert( m_nFXComputeFrame == gpGlobals->framecount ); return m_nRenderFXBlend; } //----------------------------------------------------------------------------- // Determine the color modulation amount //----------------------------------------------------------------------------- void C_BaseEntity::GetColorModulation( float* color ) { color[0] = m_clrRender->r / 255.0f; color[1] = m_clrRender->g / 255.0f; color[2] = m_clrRender->b / 255.0f; } //----------------------------------------------------------------------------- // Returns true if we should add this to the collision list //----------------------------------------------------------------------------- CollideType_t C_BaseEntity::GetCollideType( void ) { if ( !m_nModelIndex || !model ) return ENTITY_SHOULD_NOT_COLLIDE; if ( !IsSolid( ) ) return ENTITY_SHOULD_NOT_COLLIDE; // If the model is a bsp or studio (i.e. it can collide with the player if ( ( modelinfo->GetModelType( model ) != mod_brush ) && ( modelinfo->GetModelType( model ) != mod_studio ) ) return ENTITY_SHOULD_NOT_COLLIDE; // Don't get stuck on point sized entities ( world doesn't count ) if ( m_nModelIndex != 1 ) { if ( IsPointSized() ) return ENTITY_SHOULD_NOT_COLLIDE; } return ENTITY_SHOULD_COLLIDE; } //----------------------------------------------------------------------------- // Is this a brush model? //----------------------------------------------------------------------------- bool C_BaseEntity::IsBrushModel() const { int modelType = modelinfo->GetModelType( model ); return (modelType == mod_brush); } //----------------------------------------------------------------------------- // This method works when we've got a studio model //----------------------------------------------------------------------------- void C_BaseEntity::AddStudioDecal( const Ray_t& ray, int hitbox, int decalIndex, bool doTrace, trace_t& tr, int maxLODToDecal ) { if (doTrace) { enginetrace->ClipRayToEntity( ray, MASK_SHOT, this, &tr ); // Trace the ray against the entity if (tr.fraction == 1.0f) return; // Set the trace index appropriately... tr.m_pEnt = this; } // Exit out after doing the trace so any other effects that want to happen can happen. if ( !r_drawmodeldecals.GetBool() ) return; // Found the point, now lets apply the decals CreateModelInstance(); // FIXME: Pass in decal up? Vector up(0, 0, 1); if (doTrace && (GetSolid() == SOLID_VPHYSICS) && !tr.startsolid && !tr.allsolid) { // Choose a more accurate normal direction // Also, since we have more accurate info, we can avoid pokethru Vector temp; VectorSubtract( tr.endpos, tr.plane.normal, temp ); Ray_t betterRay; betterRay.Init( tr.endpos, temp ); modelrender->AddDecal( m_ModelInstance, betterRay, up, decalIndex, GetStudioBody(), true, maxLODToDecal ); } else { modelrender->AddDecal( m_ModelInstance, ray, up, decalIndex, GetStudioBody(), false, maxLODToDecal ); } } //----------------------------------------------------------------------------- // This method works when we've got a brush model //----------------------------------------------------------------------------- void C_BaseEntity::AddBrushModelDecal( const Ray_t& ray, const Vector& decalCenter, int decalIndex, bool doTrace, trace_t& tr ) { if ( doTrace ) { enginetrace->ClipRayToEntity( ray, MASK_SHOT, this, &tr ); if ( tr.fraction == 1.0f ) return; } effects->DecalShoot( decalIndex, index, model, GetAbsOrigin(), GetAbsAngles(), decalCenter, 0, 0 ); } //----------------------------------------------------------------------------- // A method to apply a decal to an entity //----------------------------------------------------------------------------- void C_BaseEntity::AddDecal( const Vector& rayStart, const Vector& rayEnd, const Vector& decalCenter, int hitbox, int decalIndex, bool doTrace, trace_t& tr, int maxLODToDecal ) { Ray_t ray; ray.Init( rayStart, rayEnd ); // FIXME: Better bloat? // Bloat a little bit so we get the intersection ray.m_Delta *= 1.1f; int modelType = modelinfo->GetModelType( model ); switch ( modelType ) { case mod_studio: AddStudioDecal( ray, hitbox, decalIndex, doTrace, tr, maxLODToDecal ); break; case mod_brush: AddBrushModelDecal( ray, decalCenter, decalIndex, doTrace, tr ); break; default: // By default, no collision tr.fraction = 1.0f; break; } } //----------------------------------------------------------------------------- // A method to remove all decals from an entity //----------------------------------------------------------------------------- void C_BaseEntity::RemoveAllDecals( void ) { // For now, we only handle removing decals from studiomodels if ( modelinfo->GetModelType( model ) == mod_studio ) { CreateModelInstance(); modelrender->RemoveAllDecals( m_ModelInstance ); } } bool C_BaseEntity::SnatchModelInstance( C_BaseEntity *pToEntity ) { if ( !modelrender->ChangeInstance( GetModelInstance(), pToEntity ) ) return false; // engine could move modle handle // remove old handle from toentity if any if ( pToEntity->GetModelInstance() != MODEL_INSTANCE_INVALID ) pToEntity->DestroyModelInstance(); // move the handle to other entity pToEntity->SetModelInstance( GetModelInstance() ); // delete own reference SetModelInstance( MODEL_INSTANCE_INVALID ); return true; } #include "tier0/memdbgoff.h" //----------------------------------------------------------------------------- // C_BaseEntity new/delete // All fields in the object are all initialized to 0. //----------------------------------------------------------------------------- void *C_BaseEntity::operator new( size_t stAllocateBlock ) { Assert( stAllocateBlock != 0 ); MEM_ALLOC_CREDIT(); void *pMem = g_pMemAlloc->Alloc( stAllocateBlock ); memset( pMem, 0, stAllocateBlock ); return pMem; } void *C_BaseEntity::operator new[]( size_t stAllocateBlock ) { Assert( stAllocateBlock != 0 ); MEM_ALLOC_CREDIT(); void *pMem = g_pMemAlloc->Alloc( stAllocateBlock ); memset( pMem, 0, stAllocateBlock ); return pMem; } void *C_BaseEntity::operator new( size_t stAllocateBlock, int nBlockUse, const char *pFileName, int nLine ) { Assert( stAllocateBlock != 0 ); void *pMem = g_pMemAlloc->Alloc( stAllocateBlock, pFileName, nLine ); memset( pMem, 0, stAllocateBlock ); return pMem; } void *C_BaseEntity::operator new[]( size_t stAllocateBlock, int nBlockUse, const char *pFileName, int nLine ) { Assert( stAllocateBlock != 0 ); void *pMem = g_pMemAlloc->Alloc( stAllocateBlock, pFileName, nLine ); memset( pMem, 0, stAllocateBlock ); return pMem; } //----------------------------------------------------------------------------- // Purpose: // Input : *pMem - //----------------------------------------------------------------------------- void C_BaseEntity::operator delete( void *pMem ) { #ifdef _DEBUG // set the memory to a known value int size = g_pMemAlloc->GetSize( pMem ); Q_memset( pMem, 0xdd, size ); #endif // get the engine to free the memory g_pMemAlloc->Free( pMem ); } #include "tier0/memdbgon.h" //======================================================================================== // TEAM HANDLING //======================================================================================== C_Team *C_BaseEntity::GetTeam( void ) { return GetGlobalTeam( m_iTeamNum ); } //----------------------------------------------------------------------------- // Purpose: // Output : int //----------------------------------------------------------------------------- int C_BaseEntity::GetTeamNumber( void ) const { return m_iTeamNum; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- int C_BaseEntity::GetRenderTeamNumber( void ) { return GetTeamNumber(); } //----------------------------------------------------------------------------- // Purpose: Returns true if these entities are both in at least one team together //----------------------------------------------------------------------------- bool C_BaseEntity::InSameTeam( C_BaseEntity *pEntity ) { if ( !pEntity ) return false; return ( pEntity->GetTeam() == GetTeam() ); } //----------------------------------------------------------------------------- // Purpose: Returns true if the entity's on the same team as the local player //----------------------------------------------------------------------------- bool C_BaseEntity::InLocalTeam( void ) { return ( GetTeam() == GetLocalTeam() ); } void C_BaseEntity::SetNextClientThink( float nextThinkTime ) { Assert( GetClientHandle() != INVALID_CLIENTENTITY_HANDLE ); ClientThinkList()->SetNextClientThink( GetClientHandle(), nextThinkTime ); } void C_BaseEntity::AddToLeafSystem() { AddToLeafSystem( GetRenderGroup() ); } void C_BaseEntity::AddToLeafSystem( RenderGroup_t group ) { if( m_hRender == INVALID_CLIENT_RENDER_HANDLE ) { // create new renderer handle ClientLeafSystem()->AddRenderable( this, group ); ClientLeafSystem()->EnableAlternateSorting( m_hRender, m_bAlternateSorting ); } else { // handle already exists, just update group & origin ClientLeafSystem()->SetRenderGroup( m_hRender, group ); ClientLeafSystem()->RenderableChanged( m_hRender ); } } //----------------------------------------------------------------------------- // Creates the shadow (if it doesn't already exist) based on shadow cast type //----------------------------------------------------------------------------- void C_BaseEntity::CreateShadow() { ShadowType_t shadowType = ShadowCastType(); if (shadowType == SHADOWS_NONE) { DestroyShadow(); } else { if (m_ShadowHandle == CLIENTSHADOW_INVALID_HANDLE) { int flags = SHADOW_FLAGS_SHADOW; if (shadowType != SHADOWS_SIMPLE) flags |= SHADOW_FLAGS_USE_RENDER_TO_TEXTURE; if (shadowType == SHADOWS_RENDER_TO_TEXTURE_DYNAMIC) flags |= SHADOW_FLAGS_ANIMATING_SOURCE; m_ShadowHandle = g_pClientShadowMgr->CreateShadow(GetClientHandle(), flags); } } } //----------------------------------------------------------------------------- // Removes the shadow //----------------------------------------------------------------------------- void C_BaseEntity::DestroyShadow() { // NOTE: This will actually cause the shadow type to be recomputed // if the entity doesn't immediately go away if (m_ShadowHandle != CLIENTSHADOW_INVALID_HANDLE) { g_pClientShadowMgr->DestroyShadow(m_ShadowHandle); m_ShadowHandle = CLIENTSHADOW_INVALID_HANDLE; } } //----------------------------------------------------------------------------- // Removes the entity from the leaf system //----------------------------------------------------------------------------- void C_BaseEntity::RemoveFromLeafSystem() { // Detach from the leaf lists. if( m_hRender != INVALID_CLIENT_RENDER_HANDLE ) { ClientLeafSystem()->RemoveRenderable( m_hRender ); m_hRender = INVALID_CLIENT_RENDER_HANDLE; } DestroyShadow(); } //----------------------------------------------------------------------------- // Purpose: Flags this entity as being inside or outside of this client's PVS // on the server. // NOTE: this is meaningless for client-side only entities. // Input : inside_pvs - //----------------------------------------------------------------------------- void C_BaseEntity::SetDormant( bool bDormant ) { Assert( IsServerEntity() ); m_bDormant = bDormant; // Kill drawing if we became dormant. UpdateVisibility(); ParticleProp()->OwnerSetDormantTo( bDormant ); } //----------------------------------------------------------------------------- // Purpose: Returns whether this entity is dormant. Client/server entities become // dormant when they leave the PVS on the server. Client side entities // can decide for themselves whether to become dormant. //----------------------------------------------------------------------------- bool C_BaseEntity::IsDormant( void ) { if ( IsServerEntity() ) { return m_bDormant; } return false; } //----------------------------------------------------------------------------- // Purpose: Tells the entity that it's about to be destroyed due to the client receiving // an uncompressed update that's caused it to destroy all entities & recreate them. //----------------------------------------------------------------------------- void C_BaseEntity::SetDestroyedOnRecreateEntities( void ) { // Robin: We need to destroy all our particle systems immediately, because // we're about to be recreated, and their owner EHANDLEs will match up to // the new entity, but it won't know anything about them. ParticleProp()->StopEmissionAndDestroyImmediately(); } //----------------------------------------------------------------------------- // These methods recompute local versions as well as set abs versions //----------------------------------------------------------------------------- void C_BaseEntity::SetAbsOrigin( const Vector& absOrigin ) { // This is necessary to get the other fields of m_rgflCoordinateFrame ok CalcAbsolutePosition(); if ( m_vecAbsOrigin == absOrigin ) return; // All children are invalid, but we are not InvalidatePhysicsRecursive( POSITION_CHANGED ); RemoveEFlags( EFL_DIRTY_ABSTRANSFORM ); m_vecAbsOrigin = absOrigin; MatrixSetColumn( absOrigin, 3, m_rgflCoordinateFrame ); C_BaseEntity *pMoveParent = GetMoveParent(); if (!pMoveParent) { m_vecOrigin = absOrigin; return; } // Moveparent case: transform the abs position into local space VectorITransform( absOrigin, pMoveParent->EntityToWorldTransform(), (Vector&)m_vecOrigin ); } void C_BaseEntity::SetAbsAngles( const QAngle& absAngles ) { // This is necessary to get the other fields of m_rgflCoordinateFrame ok CalcAbsolutePosition(); // FIXME: The normalize caused problems in server code like momentary_rot_button that isn't // handling things like +/-180 degrees properly. This should be revisited. //QAngle angleNormalize( AngleNormalize( absAngles.x ), AngleNormalize( absAngles.y ), AngleNormalize( absAngles.z ) ); if ( m_angAbsRotation == absAngles ) return; InvalidatePhysicsRecursive( ANGLES_CHANGED ); RemoveEFlags( EFL_DIRTY_ABSTRANSFORM ); m_angAbsRotation = absAngles; AngleMatrix( absAngles, m_rgflCoordinateFrame ); MatrixSetColumn( m_vecAbsOrigin, 3, m_rgflCoordinateFrame ); C_BaseEntity *pMoveParent = GetMoveParent(); if (!pMoveParent) { m_angRotation = absAngles; return; } // Moveparent case: we're aligned with the move parent if ( m_angAbsRotation == pMoveParent->GetAbsAngles() ) { m_angRotation.Init( ); } else { // Moveparent case: transform the abs transform into local space matrix3x4_t worldToParent, localMatrix; MatrixInvert( pMoveParent->EntityToWorldTransform(), worldToParent ); ConcatTransforms( worldToParent, m_rgflCoordinateFrame, localMatrix ); MatrixAngles( localMatrix, (QAngle &)m_angRotation ); } } void C_BaseEntity::SetAbsVelocity( const Vector &vecAbsVelocity ) { if ( m_vecAbsVelocity == vecAbsVelocity ) return; // The abs velocity won't be dirty since we're setting it here InvalidatePhysicsRecursive( VELOCITY_CHANGED ); m_iEFlags &= ~EFL_DIRTY_ABSVELOCITY; m_vecAbsVelocity = vecAbsVelocity; C_BaseEntity *pMoveParent = GetMoveParent(); if (!pMoveParent) { m_vecVelocity = vecAbsVelocity; return; } // First subtract out the parent's abs velocity to get a relative // velocity measured in world space Vector relVelocity; VectorSubtract( vecAbsVelocity, pMoveParent->GetAbsVelocity(), relVelocity ); // Transform velocity into parent space VectorIRotate( relVelocity, pMoveParent->EntityToWorldTransform(), m_vecVelocity ); } /* void C_BaseEntity::SetAbsAngularVelocity( const QAngle &vecAbsAngVelocity ) { // The abs velocity won't be dirty since we're setting it here InvalidatePhysicsRecursive( EFL_DIRTY_ABSANGVELOCITY ); m_iEFlags &= ~EFL_DIRTY_ABSANGVELOCITY; m_vecAbsAngVelocity = vecAbsAngVelocity; C_BaseEntity *pMoveParent = GetMoveParent(); if (!pMoveParent) { m_vecAngVelocity = vecAbsAngVelocity; return; } // First subtract out the parent's abs velocity to get a relative // angular velocity measured in world space QAngle relAngVelocity; relAngVelocity = vecAbsAngVelocity - pMoveParent->GetAbsAngularVelocity(); matrix3x4_t entityToWorld; AngleMatrix( relAngVelocity, entityToWorld ); // Moveparent case: transform the abs angular vel into local space matrix3x4_t worldToParent, localMatrix; MatrixInvert( pMoveParent->EntityToWorldTransform(), worldToParent ); ConcatTransforms( worldToParent, entityToWorld, localMatrix ); MatrixAngles( localMatrix, m_vecAngVelocity ); } */ // Prevent these for now until hierarchy is properly networked const Vector& C_BaseEntity::GetLocalOrigin( void ) const { return m_vecOrigin; } vec_t C_BaseEntity::GetLocalOriginDim( int iDim ) const { return m_vecOrigin[iDim]; } // Prevent these for now until hierarchy is properly networked void C_BaseEntity::SetLocalOrigin( const Vector& origin ) { if (m_vecOrigin != origin) { InvalidatePhysicsRecursive( POSITION_CHANGED ); m_vecOrigin = origin; } } void C_BaseEntity::SetLocalOriginDim( int iDim, vec_t flValue ) { if (m_vecOrigin[iDim] != flValue) { InvalidatePhysicsRecursive( POSITION_CHANGED ); m_vecOrigin[iDim] = flValue; } } // Prevent these for now until hierarchy is properly networked const QAngle& C_BaseEntity::GetLocalAngles( void ) const { return m_angRotation; } vec_t C_BaseEntity::GetLocalAnglesDim( int iDim ) const { return m_angRotation[iDim]; } // Prevent these for now until hierarchy is properly networked void C_BaseEntity::SetLocalAngles( const QAngle& angles ) { // NOTE: The angle normalize is a little expensive, but we can save // a bunch of time in interpolation if we don't have to invalidate everything // and sometimes it's off by a normalization amount // FIXME: The normalize caused problems in server code like momentary_rot_button that isn't // handling things like +/-180 degrees properly. This should be revisited. //QAngle angleNormalize( AngleNormalize( angles.x ), AngleNormalize( angles.y ), AngleNormalize( angles.z ) ); if (m_angRotation != angles) { // This will cause the velocities of all children to need recomputation InvalidatePhysicsRecursive( ANGLES_CHANGED ); m_angRotation = angles; } } void C_BaseEntity::SetLocalAnglesDim( int iDim, vec_t flValue ) { flValue = AngleNormalize( flValue ); if (m_angRotation[iDim] != flValue) { // This will cause the velocities of all children to need recomputation InvalidatePhysicsRecursive( ANGLES_CHANGED ); m_angRotation[iDim] = flValue; } } void C_BaseEntity::SetLocalVelocity( const Vector &vecVelocity ) { if (m_vecVelocity != vecVelocity) { InvalidatePhysicsRecursive( VELOCITY_CHANGED ); m_vecVelocity = vecVelocity; } } void C_BaseEntity::SetLocalAngularVelocity( const QAngle &vecAngVelocity ) { if (m_vecAngVelocity != vecAngVelocity) { // InvalidatePhysicsRecursive( ANG_VELOCITY_CHANGED ); m_vecAngVelocity = vecAngVelocity; } } //----------------------------------------------------------------------------- // Sets the local position from a transform //----------------------------------------------------------------------------- void C_BaseEntity::SetLocalTransform( const matrix3x4_t &localTransform ) { Vector vecLocalOrigin; QAngle vecLocalAngles; MatrixGetColumn( localTransform, 3, vecLocalOrigin ); MatrixAngles( localTransform, vecLocalAngles ); SetLocalOrigin( vecLocalOrigin ); SetLocalAngles( vecLocalAngles ); } //----------------------------------------------------------------------------- // FIXME: REMOVE!!! //----------------------------------------------------------------------------- void C_BaseEntity::MoveToAimEnt( ) { Vector vecAimEntOrigin; QAngle vecAimEntAngles; GetAimEntOrigin( GetMoveParent(), &vecAimEntOrigin, &vecAimEntAngles ); SetAbsOrigin( vecAimEntOrigin ); SetAbsAngles( vecAimEntAngles ); } void C_BaseEntity::BoneMergeFastCullBloat( Vector &localMins, Vector &localMaxs, const Vector &thisEntityMins, const Vector &thisEntityMaxs ) const { // By default, we bloat the bbox for fastcull ents by the maximum length it could hang out of the parent bbox, // it one corner were touching the edge of the parent's box, and the whole diagonal stretched out. float flExpand = (thisEntityMaxs - thisEntityMins).Length(); localMins.x -= flExpand; localMins.y -= flExpand; localMins.z -= flExpand; localMaxs.x += flExpand; localMaxs.y += flExpand; localMaxs.z += flExpand; } matrix3x4_t& C_BaseEntity::GetParentToWorldTransform( matrix3x4_t &tempMatrix ) { CBaseEntity *pMoveParent = GetMoveParent(); if ( !pMoveParent ) { Assert( false ); SetIdentityMatrix( tempMatrix ); return tempMatrix; } if ( m_iParentAttachment != 0 ) { Vector vOrigin; QAngle vAngles; if ( pMoveParent->GetAttachment( m_iParentAttachment, vOrigin, vAngles ) ) { AngleMatrix( vAngles, vOrigin, tempMatrix ); return tempMatrix; } } // If we fall through to here, then just use the move parent's abs origin and angles. return pMoveParent->EntityToWorldTransform(); } //----------------------------------------------------------------------------- // Purpose: Calculates the absolute position of an edict in the world // assumes the parent's absolute origin has already been calculated //----------------------------------------------------------------------------- void C_BaseEntity::CalcAbsolutePosition( ) { // There are periods of time where we're gonna have to live with the // fact that we're in an indeterminant state and abs queries (which // shouldn't be happening at all; I have assertions for those), will // just have to accept stale data. if (!s_bAbsRecomputationEnabled) return; // FIXME: Recompute absbox!!! if ((m_iEFlags & EFL_DIRTY_ABSTRANSFORM) == 0) { // quick check to make sure we really don't need an update // Assert( m_pMoveParent || m_vecAbsOrigin == GetLocalOrigin() ); return; } AUTO_LOCK( m_CalcAbsolutePositionMutex ); if ((m_iEFlags & EFL_DIRTY_ABSTRANSFORM) == 0) // need second check in event another thread grabbed mutex and did the calculation { return; } RemoveEFlags( EFL_DIRTY_ABSTRANSFORM ); if (!m_pMoveParent) { // Construct the entity-to-world matrix // Start with making an entity-to-parent matrix AngleMatrix( GetLocalAngles(), GetLocalOrigin(), m_rgflCoordinateFrame ); m_vecAbsOrigin = GetLocalOrigin(); m_angAbsRotation = GetLocalAngles(); NormalizeAngles( m_angAbsRotation ); return; } if ( IsEffectActive(EF_BONEMERGE) ) { MoveToAimEnt(); return; } // Construct the entity-to-world matrix // Start with making an entity-to-parent matrix matrix3x4_t matEntityToParent; AngleMatrix( GetLocalAngles(), matEntityToParent ); MatrixSetColumn( GetLocalOrigin(), 3, matEntityToParent ); // concatenate with our parent's transform matrix3x4_t scratchMatrix; ConcatTransforms( GetParentToWorldTransform( scratchMatrix ), matEntityToParent, m_rgflCoordinateFrame ); // pull our absolute position out of the matrix MatrixGetColumn( m_rgflCoordinateFrame, 3, m_vecAbsOrigin ); // if we have any angles, we have to extract our absolute angles from our matrix if ( m_angRotation == vec3_angle && m_iParentAttachment == 0 ) { // just copy our parent's absolute angles VectorCopy( m_pMoveParent->GetAbsAngles(), m_angAbsRotation ); } else { MatrixAngles( m_rgflCoordinateFrame, m_angAbsRotation ); } // This is necessary because it's possible that our moveparent's CalculateIKLocks will trigger its move children // (ie: this entity) to call GetAbsOrigin(), and they'll use the moveparent's OLD bone transforms to get their attachments // since the moveparent is right in the middle of setting up new transforms. // // So here, we keep our absorigin invalidated. It means we're returning an origin that is a frame old to CalculateIKLocks, // but we'll still render with the right origin. if ( m_iParentAttachment != 0 && (m_pMoveParent->GetFlags() & EFL_SETTING_UP_BONES) ) { m_iEFlags |= EFL_DIRTY_ABSTRANSFORM; } } void C_BaseEntity::CalcAbsoluteVelocity() { if ((m_iEFlags & EFL_DIRTY_ABSVELOCITY ) == 0) return; AUTO_LOCK( m_CalcAbsoluteVelocityMutex ); if ((m_iEFlags & EFL_DIRTY_ABSVELOCITY) == 0) // need second check in event another thread grabbed mutex and did the calculation { return; } m_iEFlags &= ~EFL_DIRTY_ABSVELOCITY; CBaseEntity *pMoveParent = GetMoveParent(); if ( !pMoveParent ) { m_vecAbsVelocity = m_vecVelocity; return; } VectorRotate( m_vecVelocity, pMoveParent->EntityToWorldTransform(), m_vecAbsVelocity ); // Add in the attachments velocity if it exists if ( m_iParentAttachment != 0 ) { Vector vOriginVel; Quaternion vAngleVel; if ( pMoveParent->GetAttachmentVelocity( m_iParentAttachment, vOriginVel, vAngleVel ) ) { m_vecAbsVelocity += vOriginVel; return; } } // Now add in the parent abs velocity m_vecAbsVelocity += pMoveParent->GetAbsVelocity(); } /* void C_BaseEntity::CalcAbsoluteAngularVelocity() { if ((m_iEFlags & EFL_DIRTY_ABSANGVELOCITY ) == 0) return; m_iEFlags &= ~EFL_DIRTY_ABSANGVELOCITY; CBaseEntity *pMoveParent = GetMoveParent(); if ( !pMoveParent ) { m_vecAbsAngVelocity = m_vecAngVelocity; return; } matrix3x4_t angVelToParent, angVelToWorld; AngleMatrix( m_vecAngVelocity, angVelToParent ); ConcatTransforms( pMoveParent->EntityToWorldTransform(), angVelToParent, angVelToWorld ); MatrixAngles( angVelToWorld, m_vecAbsAngVelocity ); // Now add in the parent abs angular velocity m_vecAbsAngVelocity += pMoveParent->GetAbsAngularVelocity(); } */ //----------------------------------------------------------------------------- // Computes the abs position of a point specified in local space //----------------------------------------------------------------------------- void C_BaseEntity::ComputeAbsPosition( const Vector &vecLocalPosition, Vector *pAbsPosition ) { C_BaseEntity *pMoveParent = GetMoveParent(); if ( !pMoveParent ) { *pAbsPosition = vecLocalPosition; } else { VectorTransform( vecLocalPosition, pMoveParent->EntityToWorldTransform(), *pAbsPosition ); } } //----------------------------------------------------------------------------- // Computes the abs position of a point specified in local space //----------------------------------------------------------------------------- void C_BaseEntity::ComputeAbsDirection( const Vector &vecLocalDirection, Vector *pAbsDirection ) { C_BaseEntity *pMoveParent = GetMoveParent(); if ( !pMoveParent ) { *pAbsDirection = vecLocalDirection; } else { VectorRotate( vecLocalDirection, pMoveParent->EntityToWorldTransform(), *pAbsDirection ); } } //----------------------------------------------------------------------------- // Mark shadow as dirty //----------------------------------------------------------------------------- void C_BaseEntity::MarkRenderHandleDirty( ) { // Invalidate render leaf too ClientRenderHandle_t handle = GetRenderHandle(); if ( handle != INVALID_CLIENT_RENDER_HANDLE ) { ClientLeafSystem()->RenderableChanged( handle ); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void C_BaseEntity::ShutdownPredictable( void ) { #if !defined( NO_ENTITY_PREDICTION ) Assert( GetPredictable() ); g_Predictables.RemoveFromPredictablesList( GetClientHandle() ); DestroyIntermediateData(); SetPredictable( false ); #endif } //----------------------------------------------------------------------------- // Purpose: Turn entity into something the predicts locally //----------------------------------------------------------------------------- void C_BaseEntity::InitPredictable( void ) { #if !defined( NO_ENTITY_PREDICTION ) Assert( !GetPredictable() ); // Mark as predictable SetPredictable( true ); // Allocate buffers into which we copy data AllocateIntermediateData(); // Add to list of predictables g_Predictables.AddToPredictableList( GetClientHandle() ); // Copy everything from "this" into the original_state_data // object. Don't care about client local stuff, so pull from slot 0 which // should be empty anyway... PostNetworkDataReceived( 0 ); // Copy original data into all prediction slots, so we don't get an error saying we "mispredicted" any // values which are still at their initial values for ( int i = 0; i < MULTIPLAYER_BACKUP; i++ ) { SaveData( "InitPredictable", i, PC_EVERYTHING ); } #endif } //----------------------------------------------------------------------------- // Purpose: // Input : state - //----------------------------------------------------------------------------- void C_BaseEntity::SetPredictable( bool state ) { m_bPredictable = state; // update interpolation times Interp_UpdateInterpolationAmounts( GetVarMapping() ); } //----------------------------------------------------------------------------- // Purpose: // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool C_BaseEntity::GetPredictable( void ) const { return m_bPredictable; } //----------------------------------------------------------------------------- // Purpose: Transfer data for intermediate frame to current entity // Input : copyintermediate - // last_predicted - //----------------------------------------------------------------------------- void C_BaseEntity::PreEntityPacketReceived( int commands_acknowledged ) { #if !defined( NO_ENTITY_PREDICTION ) // Don't need to copy intermediate data if server did ack any new commands bool copyintermediate = ( commands_acknowledged > 0 ) ? true : false; Assert( GetPredictable() ); Assert( cl_predict->GetInt() ); // First copy in any intermediate predicted data for non-networked fields if ( copyintermediate ) { RestoreData( "PreEntityPacketReceived", commands_acknowledged - 1, PC_NON_NETWORKED_ONLY ); RestoreData( "PreEntityPacketReceived", SLOT_ORIGINALDATA, PC_NETWORKED_ONLY ); } else { RestoreData( "PreEntityPacketReceived(no commands ack)", SLOT_ORIGINALDATA, PC_EVERYTHING ); } // At this point the entity has original network data restored as of the last time the // networking was updated, and it has any intermediate predicted values properly copied over // Unpacked and OnDataChanged will fill in any changed, networked fields. // That networked data will be copied forward into the starting slot for the next prediction round #endif } //----------------------------------------------------------------------------- // Purpose: Called every time PreEntityPacket received is called // copy any networked data into original_state // Input : errorcheck - // last_predicted - //----------------------------------------------------------------------------- void C_BaseEntity::PostEntityPacketReceived( void ) { #if !defined( NO_ENTITY_PREDICTION ) Assert( GetPredictable() ); Assert( cl_predict->GetInt() ); // Always mark as changed AddDataChangeEvent( this, DATA_UPDATE_DATATABLE_CHANGED, &m_DataChangeEventRef ); // Save networked fields into "original data" store SaveData( "PostEntityPacketReceived", SLOT_ORIGINALDATA, PC_NETWORKED_ONLY ); #endif } //----------------------------------------------------------------------------- // Purpose: Called once per frame after all updating is done // Input : errorcheck - // last_predicted - //----------------------------------------------------------------------------- bool C_BaseEntity::PostNetworkDataReceived( int commands_acknowledged ) { bool haderrors = false; #if !defined( NO_ENTITY_PREDICTION ) Assert( GetPredictable() ); bool errorcheck = ( commands_acknowledged > 0 ) ? true : false; // Store network data into post networking pristine state slot (slot 64) SaveData( "PostNetworkDataReceived", SLOT_ORIGINALDATA, PC_EVERYTHING ); // Show any networked fields that are different bool showthis = cl_showerror.GetInt() >= 2; if ( cl_showerror.GetInt() < 0 ) { if ( entindex() == -cl_showerror.GetInt() ) { showthis = true; } else { showthis = false; } } if ( errorcheck ) { void *predicted_state_data = GetPredictedFrame( commands_acknowledged - 1 ); Assert( predicted_state_data ); const void *original_state_data = GetOriginalNetworkDataObject(); Assert( original_state_data ); bool counterrors = true; bool reporterrors = showthis; bool copydata = false; CPredictionCopy errorCheckHelper( PC_NETWORKED_ONLY, predicted_state_data, PC_DATA_PACKED, original_state_data, PC_DATA_PACKED, counterrors, reporterrors, copydata ); // Suppress debugging output int ecount = errorCheckHelper.TransferData( "", -1, GetPredDescMap() ); if ( ecount > 0 ) { haderrors = true; // Msg( "%i errors %i on entity %i %s\n", gpGlobals->tickcount, ecount, index, IsClientCreated() ? "true" : "false" ); } } #endif return haderrors; } // Stuff implemented for weapon prediction code void C_BaseEntity::SetSize( const Vector &vecMin, const Vector &vecMax ) { SetCollisionBounds( vecMin, vecMax ); } //----------------------------------------------------------------------------- // Purpose: Just look up index // Input : *name - // Output : int //----------------------------------------------------------------------------- int C_BaseEntity::PrecacheModel( const char *name ) { return modelinfo->GetModelIndex( name ); } //----------------------------------------------------------------------------- // Purpose: // Input : *obj - //----------------------------------------------------------------------------- void C_BaseEntity::Remove( ) { // Nothing for now, if it's a predicted entity, could flag as "delete" or dormant if ( GetPredictable() || IsClientCreated() ) { // Make it solid AddSolidFlags( FSOLID_NOT_SOLID ); SetMoveType( MOVETYPE_NONE ); AddEFlags( EFL_KILLME ); // Make sure to ignore further calls into here or UTIL_Remove. } Release(); } //----------------------------------------------------------------------------- // Purpose: // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool C_BaseEntity::GetPredictionEligible( void ) const { #if !defined( NO_ENTITY_PREDICTION ) return m_bPredictionEligible; #else return false; #endif } C_BaseEntity* C_BaseEntity::Instance( CBaseHandle hEnt ) { return ClientEntityList().GetBaseEntityFromHandle( hEnt ); } //----------------------------------------------------------------------------- // Purpose: // Input : iEnt - // Output : C_BaseEntity //----------------------------------------------------------------------------- C_BaseEntity *C_BaseEntity::Instance( int iEnt ) { return ClientEntityList().GetBaseEntity( iEnt ); } #pragma warning( push ) #include <typeinfo.h> #pragma warning( pop ) //----------------------------------------------------------------------------- // Purpose: // Output : char const //----------------------------------------------------------------------------- const char *C_BaseEntity::GetClassname( void ) { static char outstr[ 256 ]; outstr[ 0 ] = 0; bool gotname = false; #ifndef NO_ENTITY_PREDICTION if ( GetPredDescMap() ) { const char *mapname = GetClassMap().Lookup( GetPredDescMap()->dataClassName ); if ( mapname && mapname[ 0 ] ) { Q_snprintf( outstr, sizeof( outstr ), "%s", mapname ); gotname = true; } } #endif if ( !gotname ) { Q_strncpy( outstr, typeid( *this ).name(), sizeof( outstr ) ); } return outstr; } const char *C_BaseEntity::GetDebugName( void ) { return GetClassname(); } //----------------------------------------------------------------------------- // Purpose: Creates an entity by string name, but does not spawn it // Input : *className - // Output : C_BaseEntity //----------------------------------------------------------------------------- C_BaseEntity *CreateEntityByName( const char *className ) { C_BaseEntity *ent = GetClassMap().CreateEntity( className ); if ( ent ) { return ent; } Warning( "Can't find factory for entity: %s\n", className ); return NULL; } #ifdef _DEBUG CON_COMMAND( cl_sizeof, "Determines the size of the specified client class." ) { if ( args.ArgC() != 2 ) { Msg( "cl_sizeof <gameclassname>\n" ); return; } int size = GetClassMap().GetClassSize( args[ 1 ] ); Msg( "%s is %i bytes\n", args[ 1 ], size ); } #endif CON_COMMAND_F( dlight_debug, "Creates a dlight in front of the player", FCVAR_CHEAT ) { dlight_t *el = effects->CL_AllocDlight( 1 ); C_BasePlayer *player = C_BasePlayer::GetLocalPlayer(); if ( !player ) return; Vector start = player->EyePosition(); Vector forward; player->EyeVectors( &forward ); Vector end = start + forward * MAX_TRACE_LENGTH; trace_t tr; UTIL_TraceLine( start, end, MASK_SHOT_HULL & (~CONTENTS_GRATE), player, COLLISION_GROUP_NONE, &tr ); el->origin = tr.endpos - forward * 12.0f; el->radius = 200; el->decay = el->radius / 5.0f; el->die = gpGlobals->curtime + 5.0f; el->color.r = 255; el->color.g = 192; el->color.b = 64; el->color.exponent = 5; } //----------------------------------------------------------------------------- // Purpose: // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool C_BaseEntity::IsClientCreated( void ) const { #ifndef NO_ENTITY_PREDICTION if ( m_pPredictionContext != NULL ) { // For now can't be both Assert( !GetPredictable() ); return true; } #endif return false; } //----------------------------------------------------------------------------- // Purpose: // Input : *classname - // *module - // line - // Output : C_BaseEntity //----------------------------------------------------------------------------- C_BaseEntity *C_BaseEntity::CreatePredictedEntityByName( const char *classname, const char *module, int line, bool persist /*= false */ ) { #if !defined( NO_ENTITY_PREDICTION ) C_BasePlayer *player = C_BaseEntity::GetPredictionPlayer(); Assert( player ); Assert( player->m_pCurrentCommand ); Assert( prediction->InPrediction() ); C_BaseEntity *ent = NULL; // What's my birthday (should match server) int command_number = player->m_pCurrentCommand->command_number; // Who's my daddy? int player_index = player->entindex() - 1; // Create id/context CPredictableId testId; testId.Init( player_index, command_number, classname, module, line ); // If repredicting, should be able to find the entity in the previously created list if ( !prediction->IsFirstTimePredicted() ) { // Only find previous instance if entity was created with persist set if ( persist ) { ent = FindPreviouslyCreatedEntity( testId ); if ( ent ) { return ent; } } return NULL; } // Try to create it ent = CreateEntityByName( classname ); if ( !ent ) { return NULL; } // It's predictable ent->SetPredictionEligible( true ); // Set up "shared" id number ent->m_PredictableID.SetRaw( testId.GetRaw() ); // Get a context (mostly for debugging purposes) PredictionContext *context = new PredictionContext; context->m_bActive = true; context->m_nCreationCommandNumber = command_number; context->m_nCreationLineNumber = line; context->m_pszCreationModule = module; // Attach to entity ent->m_pPredictionContext = context; // Add to client entity list ClientEntityList().AddNonNetworkableEntity( ent ); // and predictables g_Predictables.AddToPredictableList( ent->GetClientHandle() ); // Duhhhh..., but might as well be safe Assert( !ent->GetPredictable() ); Assert( ent->IsClientCreated() ); // Add the client entity to the spatial partition. (Collidable) ent->CollisionProp()->CreatePartitionHandle(); // CLIENT ONLY FOR NOW!!! ent->index = -1; if ( AddDataChangeEvent( ent, DATA_UPDATE_CREATED, &ent->m_DataChangeEventRef ) ) { ent->OnPreDataChanged( DATA_UPDATE_CREATED ); } ent->Interp_UpdateInterpolationAmounts( ent->GetVarMapping() ); return ent; #else return NULL; #endif } //----------------------------------------------------------------------------- // Purpose: Called each packet that the entity is created on and finally gets called after the next packet // that doesn't have a create message for the "parent" entity so that the predicted version // can be removed. Return true to delete entity right away. //----------------------------------------------------------------------------- bool C_BaseEntity::OnPredictedEntityRemove( bool isbeingremoved, C_BaseEntity *predicted ) { #if !defined( NO_ENTITY_PREDICTION ) // Nothing right now, but in theory you could look at the error in origins and set // up something to smooth out the error PredictionContext *ctx = predicted->m_pPredictionContext; Assert( ctx ); if ( ctx ) { // Create backlink to actual entity ctx->m_hServerEntity = this; /* Msg( "OnPredictedEntity%s: %s created %s(%i) instance(%i)\n", isbeingremoved ? "Remove" : "Acknowledge", predicted->GetClassname(), ctx->m_pszCreationModule, ctx->m_nCreationLineNumber, predicted->m_PredictableID.GetInstanceNumber() ); */ } // If it comes through with an ID, it should be eligible SetPredictionEligible( true ); // Start predicting simulation forward from here CheckInitPredictable( "OnPredictedEntityRemove" ); // Always mark it dormant since we are the "real" entity now predicted->SetDormantPredictable( true ); InvalidatePhysicsRecursive( POSITION_CHANGED | ANGLES_CHANGED | VELOCITY_CHANGED ); // By default, signal that it should be deleted right away // If a derived class implements this method, it might chain to here but return // false if it wants to keep the dormant predictable around until the chain of // DATA_UPDATE_CREATED messages passes #endif return true; } //----------------------------------------------------------------------------- // Purpose: // Input : *pOwner - //----------------------------------------------------------------------------- void C_BaseEntity::SetOwnerEntity( C_BaseEntity *pOwner ) { m_hOwnerEntity = pOwner; } //----------------------------------------------------------------------------- // Purpose: Put the entity in the specified team //----------------------------------------------------------------------------- void C_BaseEntity::ChangeTeam( int iTeamNum ) { m_iTeamNum = iTeamNum; } //----------------------------------------------------------------------------- // Purpose: // Input : name - //----------------------------------------------------------------------------- void C_BaseEntity::SetModelName( string_t name ) { m_ModelName = name; } //----------------------------------------------------------------------------- // Purpose: // Output : string_t //----------------------------------------------------------------------------- string_t C_BaseEntity::GetModelName( void ) const { return m_ModelName; } //----------------------------------------------------------------------------- // Purpose: Nothing yet, could eventually supercede Term() //----------------------------------------------------------------------------- void C_BaseEntity::UpdateOnRemove( void ) { VPhysicsDestroyObject(); Assert( !GetMoveParent() ); UnlinkFromHierarchy(); SetGroundEntity( NULL ); } //----------------------------------------------------------------------------- // Purpose: // Input : canpredict - //----------------------------------------------------------------------------- void C_BaseEntity::SetPredictionEligible( bool canpredict ) { #if !defined( NO_ENTITY_PREDICTION ) m_bPredictionEligible = canpredict; #endif } //----------------------------------------------------------------------------- // Purpose: Returns a value that scales all damage done by this entity. //----------------------------------------------------------------------------- float C_BaseEntity::GetAttackDamageScale( void ) { float flScale = 1; // Not hooked up to prediction yet #if 0 FOR_EACH_LL( m_DamageModifiers, i ) { if ( !m_DamageModifiers[i]->IsDamageDoneToMe() ) { flScale *= m_DamageModifiers[i]->GetModifier(); } } #endif return flScale; } #if !defined( NO_ENTITY_PREDICTION ) //----------------------------------------------------------------------------- // Purpose: // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool C_BaseEntity::IsDormantPredictable( void ) const { return m_bDormantPredictable; } #endif //----------------------------------------------------------------------------- // Purpose: // Input : dormant - //----------------------------------------------------------------------------- void C_BaseEntity::SetDormantPredictable( bool dormant ) { #if !defined( NO_ENTITY_PREDICTION ) Assert( IsClientCreated() ); m_bDormantPredictable = true; m_nIncomingPacketEntityBecameDormant = prediction->GetIncomingPacketNumber(); // Do we need to do the following kinds of things? #if 0 // Remove from collisions SetSolid( SOLID_NOT ); // Don't render AddEffects( EF_NODRAW ); #endif #endif } //----------------------------------------------------------------------------- // Purpose: Used to determine when a dorman client predictable can be safely deleted // Note that it can be deleted earlier than this by OnPredictedEntityRemove returning true // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool C_BaseEntity::BecameDormantThisPacket( void ) const { #if !defined( NO_ENTITY_PREDICTION ) Assert( IsDormantPredictable() ); if ( m_nIncomingPacketEntityBecameDormant != prediction->GetIncomingPacketNumber() ) return false; return true; #else return false; #endif } //----------------------------------------------------------------------------- // Purpose: // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool C_BaseEntity::IsIntermediateDataAllocated( void ) const { #if !defined( NO_ENTITY_PREDICTION ) return m_pOriginalData != NULL ? true : false; #else return false; #endif } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void C_BaseEntity::AllocateIntermediateData( void ) { #if !defined( NO_ENTITY_PREDICTION ) if ( m_pOriginalData ) return; size_t allocsize = GetIntermediateDataSize(); Assert( allocsize > 0 ); m_pOriginalData = new unsigned char[ allocsize ]; Q_memset( m_pOriginalData, 0, allocsize ); for ( int i = 0; i < MULTIPLAYER_BACKUP; i++ ) { m_pIntermediateData[ i ] = new unsigned char[ allocsize ]; Q_memset( m_pIntermediateData[ i ], 0, allocsize ); } m_nIntermediateDataCount = 0; #endif } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void C_BaseEntity::DestroyIntermediateData( void ) { #if !defined( NO_ENTITY_PREDICTION ) if ( !m_pOriginalData ) return; for ( int i = 0; i < MULTIPLAYER_BACKUP; i++ ) { delete[] m_pIntermediateData[ i ]; m_pIntermediateData[ i ] = NULL; } delete[] m_pOriginalData; m_pOriginalData = NULL; m_nIntermediateDataCount = 0; #endif } //----------------------------------------------------------------------------- // Purpose: // Input : slots_to_remove - // number_of_commands_run - //----------------------------------------------------------------------------- void C_BaseEntity::ShiftIntermediateDataForward( int slots_to_remove, int number_of_commands_run ) { #if !defined( NO_ENTITY_PREDICTION ) Assert( m_pIntermediateData ); if ( !m_pIntermediateData ) return; Assert( number_of_commands_run >= slots_to_remove ); // Just moving pointers, yeah CUtlVector< unsigned char * > saved; // Remember first slots int i = 0; for ( ; i < slots_to_remove; i++ ) { saved.AddToTail( m_pIntermediateData[ i ] ); } // Move rest of slots forward up to last slot for ( ; i < number_of_commands_run; i++ ) { m_pIntermediateData[ i - slots_to_remove ] = m_pIntermediateData[ i ]; } // Put remembered slots onto end for ( i = 0; i < slots_to_remove; i++ ) { int slot = number_of_commands_run - slots_to_remove + i; m_pIntermediateData[ slot ] = saved[ i ]; } #endif } //----------------------------------------------------------------------------- // Purpose: // Input : framenumber - //----------------------------------------------------------------------------- void *C_BaseEntity::GetPredictedFrame( int framenumber ) { #if !defined( NO_ENTITY_PREDICTION ) Assert( framenumber >= 0 ); if ( !m_pOriginalData ) { Assert( 0 ); return NULL; } return (void *)m_pIntermediateData[ framenumber % MULTIPLAYER_BACKUP ]; #else return NULL; #endif } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void *C_BaseEntity::GetOriginalNetworkDataObject( void ) { #if !defined( NO_ENTITY_PREDICTION ) if ( !m_pOriginalData ) { Assert( 0 ); return NULL; } return (void *)m_pOriginalData; #else return NULL; #endif } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void C_BaseEntity::ComputePackedOffsets( void ) { #if !defined( NO_ENTITY_PREDICTION ) datamap_t *map = GetPredDescMap(); if ( !map ) return; if ( map->packed_offsets_computed ) return; ComputePackedSize_R( map ); Assert( map->packed_offsets_computed ); #endif } //----------------------------------------------------------------------------- // Purpose: // Output : int //----------------------------------------------------------------------------- int C_BaseEntity::GetIntermediateDataSize( void ) { #if !defined( NO_ENTITY_PREDICTION ) ComputePackedOffsets(); const datamap_t *map = GetPredDescMap(); Assert( map->packed_offsets_computed ); int size = map->packed_size; Assert( size > 0 ); // At least 4 bytes to avoid some really bad stuff return MAX( size, 4 ); #else return 0; #endif } static int g_FieldSizes[FIELD_TYPECOUNT] = { 0, // FIELD_VOID sizeof(float), // FIELD_FLOAT sizeof(int), // FIELD_STRING sizeof(Vector), // FIELD_VECTOR sizeof(Quaternion), // FIELD_QUATERNION sizeof(int), // FIELD_INTEGER sizeof(char), // FIELD_BOOLEAN sizeof(short), // FIELD_SHORT sizeof(char), // FIELD_CHARACTER sizeof(color32), // FIELD_COLOR32 sizeof(int), // FIELD_EMBEDDED (handled specially) sizeof(int), // FIELD_CUSTOM (handled specially) //--------------------------------- sizeof(int), // FIELD_CLASSPTR sizeof(EHANDLE), // FIELD_EHANDLE sizeof(int), // FIELD_EDICT sizeof(Vector), // FIELD_POSITION_VECTOR sizeof(float), // FIELD_TIME sizeof(int), // FIELD_TICK sizeof(int), // FIELD_MODELNAME sizeof(int), // FIELD_SOUNDNAME sizeof(int), // FIELD_INPUT (uses custom type) sizeof(int *), // FIELD_FUNCTION sizeof(VMatrix), // FIELD_VMATRIX sizeof(VMatrix), // FIELD_VMATRIX_WORLDSPACE sizeof(matrix3x4_t),// FIELD_MATRIX3X4_WORLDSPACE // NOTE: Use array(FIELD_FLOAT, 12) for matrix3x4_t NOT in worldspace sizeof(interval_t), // FIELD_INTERVAL sizeof(int), // FIELD_MODELINDEX }; //----------------------------------------------------------------------------- // Purpose: // Input : *map - // Output : int //----------------------------------------------------------------------------- int C_BaseEntity::ComputePackedSize_R( datamap_t *map ) { if ( !map ) { Assert( 0 ); return 0; } // Already computed if ( map->packed_offsets_computed ) { return map->packed_size; } int current_position = 0; // Recurse to base classes first... if ( map->baseMap ) { current_position += ComputePackedSize_R( map->baseMap ); } int c = map->dataNumFields; int i; typedescription_t *field; for ( i = 0; i < c; i++ ) { field = &map->dataDesc[ i ]; // Always descend into embedded types... if ( field->fieldType != FIELD_EMBEDDED ) { // Skip all private fields if ( field->flags & FTYPEDESC_PRIVATE ) continue; } switch ( field->fieldType ) { default: case FIELD_MODELINDEX: case FIELD_MODELNAME: case FIELD_SOUNDNAME: case FIELD_TIME: case FIELD_TICK: case FIELD_CUSTOM: case FIELD_CLASSPTR: case FIELD_EDICT: case FIELD_POSITION_VECTOR: case FIELD_FUNCTION: Assert( 0 ); break; case FIELD_EMBEDDED: { Assert( field->td != NULL ); int embeddedsize = ComputePackedSize_R( field->td ); field->fieldOffset[ TD_OFFSET_PACKED ] = current_position; current_position += embeddedsize; } break; case FIELD_FLOAT: case FIELD_VECTOR: case FIELD_QUATERNION: case FIELD_INTEGER: case FIELD_EHANDLE: { // These should be dword aligned current_position = (current_position + 3) & ~3; field->fieldOffset[ TD_OFFSET_PACKED ] = current_position; Assert( field->fieldSize >= 1 ); current_position += g_FieldSizes[ field->fieldType ] * field->fieldSize; } break; case FIELD_SHORT: { // This should be word aligned current_position = (current_position + 1) & ~1; field->fieldOffset[ TD_OFFSET_PACKED ] = current_position; Assert( field->fieldSize >= 1 ); current_position += g_FieldSizes[ field->fieldType ] * field->fieldSize; } break; case FIELD_STRING: case FIELD_COLOR32: case FIELD_BOOLEAN: case FIELD_CHARACTER: { field->fieldOffset[ TD_OFFSET_PACKED ] = current_position; Assert( field->fieldSize >= 1 ); current_position += g_FieldSizes[ field->fieldType ] * field->fieldSize; } break; case FIELD_VOID: { // Special case, just skip it } break; } } map->packed_size = current_position; map->packed_offsets_computed = true; return current_position; } // Convenient way to delay removing oneself void C_BaseEntity::SUB_Remove( void ) { if (m_iHealth > 0) { // this situation can screw up NPCs who can't tell their entity pointers are invalid. m_iHealth = 0; DevWarning( 2, "SUB_Remove called on entity with health > 0\n"); } Remove( ); } CBaseEntity *FindEntityInFrontOfLocalPlayer() { C_BasePlayer *pPlayer = C_BasePlayer::GetLocalPlayer(); if ( pPlayer ) { // Get the entity under my crosshair trace_t tr; Vector forward; pPlayer->EyeVectors( &forward ); UTIL_TraceLine( pPlayer->EyePosition(), pPlayer->EyePosition() + forward * MAX_COORD_RANGE, MASK_SOLID, pPlayer, COLLISION_GROUP_NONE, &tr ); if ( tr.fraction != 1.0 && tr.DidHitNonWorldEntity() ) { return tr.m_pEnt; } } return NULL; } //----------------------------------------------------------------------------- // Purpose: Debug command to wipe the decals off an entity //----------------------------------------------------------------------------- static void RemoveDecals_f( void ) { CBaseEntity *pHit = FindEntityInFrontOfLocalPlayer(); if ( pHit ) { pHit->RemoveAllDecals(); } } static ConCommand cl_removedecals( "cl_removedecals", RemoveDecals_f, "Remove the decals from the entity under the crosshair.", FCVAR_CHEAT ); //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void C_BaseEntity::ToggleBBoxVisualization( int fVisFlags ) { if ( m_fBBoxVisFlags & fVisFlags ) { m_fBBoxVisFlags &= ~fVisFlags; } else { m_fBBoxVisFlags |= fVisFlags; } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- static void ToggleBBoxVisualization( int fVisFlags, const CCommand &args ) { CBaseEntity *pHit; int iEntity = -1; if ( args.ArgC() >= 2 ) { iEntity = atoi( args[ 1 ] ); } if ( iEntity == -1 ) { pHit = FindEntityInFrontOfLocalPlayer(); } else { pHit = cl_entitylist->GetBaseEntity( iEntity ); } if ( pHit ) { pHit->ToggleBBoxVisualization( fVisFlags ); } } //----------------------------------------------------------------------------- // Purpose: Command to toggle visualizations of bboxes on the client //----------------------------------------------------------------------------- CON_COMMAND_F( cl_ent_bbox, "Displays the client's bounding box for the entity under the crosshair.", FCVAR_CHEAT ) { ToggleBBoxVisualization( CBaseEntity::VISUALIZE_COLLISION_BOUNDS, args ); } //----------------------------------------------------------------------------- // Purpose: Command to toggle visualizations of bboxes on the client //----------------------------------------------------------------------------- CON_COMMAND_F( cl_ent_absbox, "Displays the client's absbox for the entity under the crosshair.", FCVAR_CHEAT ) { ToggleBBoxVisualization( CBaseEntity::VISUALIZE_SURROUNDING_BOUNDS, args ); } //----------------------------------------------------------------------------- // Purpose: Command to toggle visualizations of bboxes on the client //----------------------------------------------------------------------------- CON_COMMAND_F( cl_ent_rbox, "Displays the client's render box for the entity under the crosshair.", FCVAR_CHEAT ) { ToggleBBoxVisualization( CBaseEntity::VISUALIZE_RENDER_BOUNDS, args ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void C_BaseEntity::DrawBBoxVisualizations( void ) { if ( m_fBBoxVisFlags & VISUALIZE_COLLISION_BOUNDS ) { debugoverlay->AddBoxOverlay( CollisionProp()->GetCollisionOrigin(), CollisionProp()->OBBMins(), CollisionProp()->OBBMaxs(), CollisionProp()->GetCollisionAngles(), 190, 190, 0, 0, 0.01 ); } if ( m_fBBoxVisFlags & VISUALIZE_SURROUNDING_BOUNDS ) { Vector vecSurroundMins, vecSurroundMaxs; CollisionProp()->WorldSpaceSurroundingBounds( &vecSurroundMins, &vecSurroundMaxs ); debugoverlay->AddBoxOverlay( vec3_origin, vecSurroundMins, vecSurroundMaxs, vec3_angle, 0, 255, 255, 0, 0.01 ); } if ( m_fBBoxVisFlags & VISUALIZE_RENDER_BOUNDS || r_drawrenderboxes.GetInt() ) { Vector vecRenderMins, vecRenderMaxs; GetRenderBounds( vecRenderMins, vecRenderMaxs ); debugoverlay->AddBoxOverlay( GetRenderOrigin(), vecRenderMins, vecRenderMaxs, GetRenderAngles(), 255, 0, 255, 0, 0.01 ); } } //----------------------------------------------------------------------------- // Sets the render mode //----------------------------------------------------------------------------- void C_BaseEntity::SetRenderMode( RenderMode_t nRenderMode, bool bForceUpdate ) { m_nRenderMode = nRenderMode; } //----------------------------------------------------------------------------- // Purpose: // Output : RenderGroup_t //----------------------------------------------------------------------------- RenderGroup_t C_BaseEntity::GetRenderGroup() { // Don't sort things that don't need rendering if ( m_nRenderMode == kRenderNone ) return RENDER_GROUP_OPAQUE_ENTITY; // When an entity has a material proxy, we have to recompute // translucency here because the proxy may have changed it. if (modelinfo->ModelHasMaterialProxy( GetModel() )) { modelinfo->RecomputeTranslucency( const_cast<model_t*>(GetModel()), GetSkin(), GetBody(), GetClientRenderable() ); } // NOTE: Bypassing the GetFXBlend protection logic because we want this to // be able to be called from AddToLeafSystem. int nTempComputeFrame = m_nFXComputeFrame; m_nFXComputeFrame = gpGlobals->framecount; int nFXBlend = GetFxBlend(); m_nFXComputeFrame = nTempComputeFrame; // Don't need to sort invisible stuff if ( nFXBlend == 0 ) return RENDER_GROUP_OPAQUE_ENTITY; // Figure out its RenderGroup. int modelType = modelinfo->GetModelType( model ); RenderGroup_t renderGroup = (modelType == mod_brush) ? RENDER_GROUP_OPAQUE_BRUSH : RENDER_GROUP_OPAQUE_ENTITY; if ( ( nFXBlend != 255 ) || IsTransparent() ) { if ( m_nRenderMode != kRenderEnvironmental ) { renderGroup = RENDER_GROUP_TRANSLUCENT_ENTITY; } else { renderGroup = RENDER_GROUP_OTHER; } } if ( ( renderGroup == RENDER_GROUP_TRANSLUCENT_ENTITY ) && ( modelinfo->IsTranslucentTwoPass( model ) ) ) { renderGroup = RENDER_GROUP_TWOPASS; } return renderGroup; } //----------------------------------------------------------------------------- // Purpose: Copy from this entity into one of the save slots (original or intermediate) // Input : slot - // type - // false - // false - // true - // false - // NULL - // Output : int //----------------------------------------------------------------------------- int C_BaseEntity::SaveData( const char *context, int slot, int type ) { #if !defined( NO_ENTITY_PREDICTION ) VPROF( "C_BaseEntity::SaveData" ); void *dest = ( slot == SLOT_ORIGINALDATA ) ? GetOriginalNetworkDataObject() : GetPredictedFrame( slot ); Assert( dest ); char sz[ 64 ]; if ( slot == SLOT_ORIGINALDATA ) { Q_snprintf( sz, sizeof( sz ), "%s SaveData(original)", context ); } else { Q_snprintf( sz, sizeof( sz ), "%s SaveData(slot %02i)", context, slot ); // Remember high water mark so that we can detect below if we are reading from a slot not yet predicted into... m_nIntermediateDataCount = slot; } CPredictionCopy copyHelper( type, dest, PC_DATA_PACKED, this, PC_DATA_NORMAL ); int error_count = copyHelper.TransferData( sz, entindex(), GetPredDescMap() ); return error_count; #else return 0; #endif } //----------------------------------------------------------------------------- // Purpose: Restore data from specified slot into current entity // Input : slot - // type - // false - // false - // true - // false - // NULL - // Output : int //----------------------------------------------------------------------------- int C_BaseEntity::RestoreData( const char *context, int slot, int type ) { #if !defined( NO_ENTITY_PREDICTION ) VPROF( "C_BaseEntity::RestoreData" ); const void *src = ( slot == SLOT_ORIGINALDATA ) ? GetOriginalNetworkDataObject() : GetPredictedFrame( slot ); Assert( src ); char sz[ 64 ]; if ( slot == SLOT_ORIGINALDATA ) { Q_snprintf( sz, sizeof( sz ), "%s RestoreData(original)", context ); } else { Q_snprintf( sz, sizeof( sz ), "%s RestoreData(slot %02i)", context, slot ); // This assert will fire if the server ack'd a CUserCmd which we hadn't predicted yet... // In that case, we'd be comparing "old" data from this "unused" slot with the networked data and reporting all kinds of prediction errors possibly. Assert( slot <= m_nIntermediateDataCount ); } // some flags shouldn't be predicted - as we find them, add them to the savedEFlagsMask const int savedEFlagsMask = EFL_DIRTY_SHADOWUPDATE; int savedEFlags = GetEFlags() & savedEFlagsMask; CPredictionCopy copyHelper( type, this, PC_DATA_NORMAL, src, PC_DATA_PACKED ); int error_count = copyHelper.TransferData( sz, entindex(), GetPredDescMap() ); // set non-predicting flags back to their prior state RemoveEFlags( savedEFlagsMask ); AddEFlags( savedEFlags ); OnPostRestoreData(); return error_count; #else return 0; #endif } void C_BaseEntity::OnPostRestoreData() { // HACK Force recomputation of origin InvalidatePhysicsRecursive( POSITION_CHANGED | ANGLES_CHANGED | VELOCITY_CHANGED ); if ( GetMoveParent() ) { AddToAimEntsList(); } // If our model index has changed, then make sure it's reflected in our model pointer. if ( GetModel() != modelinfo->GetModel( GetModelIndex() ) ) { MDLCACHE_CRITICAL_SECTION(); SetModelByIndex( GetModelIndex() ); } } //----------------------------------------------------------------------------- // Purpose: Determine approximate velocity based on updates from server // Input : vel - //----------------------------------------------------------------------------- void C_BaseEntity::EstimateAbsVelocity( Vector& vel ) { if ( this == C_BasePlayer::GetLocalPlayer() ) { vel = GetAbsVelocity(); return; } CInterpolationContext context; context.EnableExtrapolation( true ); m_iv_vecOrigin.GetDerivative_SmoothVelocity( &vel, gpGlobals->curtime ); } void C_BaseEntity::Interp_Reset( VarMapping_t *map ) { PREDICTION_TRACKVALUECHANGESCOPE_ENTITY( this, "reset" ); int c = map->m_Entries.Count(); for ( int i = 0; i < c; i++ ) { VarMapEntry_t *e = &map->m_Entries[ i ]; IInterpolatedVar *watcher = e->watcher; watcher->Reset(); } } void C_BaseEntity::ResetLatched() { if ( IsClientCreated() ) return; Interp_Reset( GetVarMapping() ); } //----------------------------------------------------------------------------- // Purpose: Fixme, this needs a better solution // Input : flags - // Output : float //----------------------------------------------------------------------------- static float AdjustInterpolationAmount( C_BaseEntity *pEntity, float baseInterpolation ) { if ( cl_interp_npcs.GetFloat() > 0 ) { const float minNPCInterpolationTime = cl_interp_npcs.GetFloat(); const float minNPCInterpolation = TICK_INTERVAL * ( TIME_TO_TICKS( minNPCInterpolationTime ) + 1 ); if ( minNPCInterpolation > baseInterpolation ) { while ( pEntity ) { if ( pEntity->IsNPC() ) return minNPCInterpolation; pEntity = pEntity->GetMoveParent(); } } } return baseInterpolation; } //------------------------------------- float C_BaseEntity::GetInterpolationAmount( int flags ) { // If single player server is "skipping ticks" everything needs to interpolate for a bit longer int serverTickMultiple = 1; if ( IsSimulatingOnAlternateTicks() ) { serverTickMultiple = 2; } if ( GetPredictable() || IsClientCreated() ) { return TICK_INTERVAL * serverTickMultiple; } // Always fully interpolate during multi-player or during demo playback... if ( ( gpGlobals->maxClients > 1 ) || engine->IsPlayingDemo() ) { return AdjustInterpolationAmount( this, TICKS_TO_TIME ( TIME_TO_TICKS( GetClientInterpAmount() ) + serverTickMultiple ) ); } int expandedServerTickMultiple = serverTickMultiple; if ( IsEngineThreaded() ) { expandedServerTickMultiple += cl_interp_threadmodeticks.GetInt(); } if ( IsAnimatedEveryTick() && IsSimulatedEveryTick() ) { return TICK_INTERVAL * expandedServerTickMultiple; } if ( ( flags & LATCH_ANIMATION_VAR ) && IsAnimatedEveryTick() ) { return TICK_INTERVAL * expandedServerTickMultiple; } if ( ( flags & LATCH_SIMULATION_VAR ) && IsSimulatedEveryTick() ) { return TICK_INTERVAL * expandedServerTickMultiple; } return AdjustInterpolationAmount( this, TICK_INTERVAL * ( TIME_TO_TICKS( GetClientInterpAmount() ) + serverTickMultiple ) ); } float C_BaseEntity::GetLastChangeTime( int flags ) { if ( GetPredictable() || IsClientCreated() ) { return gpGlobals->curtime; } // make sure not both flags are set, we can't resolve that Assert( !( (flags & LATCH_ANIMATION_VAR) && (flags & LATCH_SIMULATION_VAR) ) ); if ( flags & LATCH_ANIMATION_VAR ) { return GetAnimTime(); } if ( flags & LATCH_SIMULATION_VAR ) { float st = GetSimulationTime(); if ( st == 0.0f ) { return gpGlobals->curtime; } return st; } Assert( 0 ); return gpGlobals->curtime; } const Vector& C_BaseEntity::GetPrevLocalOrigin() const { return m_iv_vecOrigin.GetPrev(); } const QAngle& C_BaseEntity::GetPrevLocalAngles() const { return m_iv_angRotation.GetPrev(); } //----------------------------------------------------------------------------- // Simply here for game shared //----------------------------------------------------------------------------- bool C_BaseEntity::IsFloating() { // NOTE: This is only here because it's called by game shared. // The server uses it to lower falling impact damage return false; } BEGIN_DATADESC_NO_BASE( C_BaseEntity ) DEFINE_FIELD( m_ModelName, FIELD_STRING ), DEFINE_FIELD( m_vecAbsOrigin, FIELD_POSITION_VECTOR ), DEFINE_FIELD( m_angAbsRotation, FIELD_VECTOR ), DEFINE_ARRAY( m_rgflCoordinateFrame, FIELD_FLOAT, 12 ), // NOTE: MUST BE IN LOCAL SPACE, NOT POSITION_VECTOR!!! (see CBaseEntity::Restore) DEFINE_FIELD( m_fFlags, FIELD_INTEGER ), END_DATADESC() //----------------------------------------------------------------------------- // Purpose: // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool C_BaseEntity::ShouldSavePhysics() { return false; } //----------------------------------------------------------------------------- // handler to do stuff before you are saved //----------------------------------------------------------------------------- void C_BaseEntity::OnSave() { // Here, we must force recomputation of all abs data so it gets saved correctly // We can't leave the dirty bits set because the loader can't cope with it. CalcAbsolutePosition(); CalcAbsoluteVelocity(); } //----------------------------------------------------------------------------- // handler to do stuff after you are restored //----------------------------------------------------------------------------- void C_BaseEntity::OnRestore() { InvalidatePhysicsRecursive( POSITION_CHANGED | ANGLES_CHANGED | VELOCITY_CHANGED ); UpdatePartitionListEntry(); CollisionProp()->UpdatePartition(); UpdateVisibility(); } //----------------------------------------------------------------------------- // Purpose: Saves the current object out to disk, by iterating through the objects // data description hierarchy // Input : &save - save buffer which the class data is written to // Output : int - 0 if the save failed, 1 on success //----------------------------------------------------------------------------- int C_BaseEntity::Save( ISave &save ) { // loop through the data description list, saving each data desc block int status = SaveDataDescBlock( save, GetDataDescMap() ); return status; } //----------------------------------------------------------------------------- // Purpose: Recursively saves all the classes in an object, in reverse order (top down) // Output : int 0 on failure, 1 on success //----------------------------------------------------------------------------- int C_BaseEntity::SaveDataDescBlock( ISave &save, datamap_t *dmap ) { int nResult = save.WriteAll( this, dmap ); return nResult; } void C_BaseEntity::SetClassname( const char *className ) { m_iClassname = MAKE_STRING( className ); } //----------------------------------------------------------------------------- // Purpose: Restores the current object from disk, by iterating through the objects // data description hierarchy // Input : &restore - restore buffer which the class data is read from // Output : int - 0 if the restore failed, 1 on success //----------------------------------------------------------------------------- int C_BaseEntity::Restore( IRestore &restore ) { // loops through the data description list, restoring each data desc block in order int status = RestoreDataDescBlock( restore, GetDataDescMap() ); // NOTE: Do *not* use GetAbsOrigin() here because it will // try to recompute m_rgflCoordinateFrame! MatrixSetColumn( m_vecAbsOrigin, 3, m_rgflCoordinateFrame ); // Restablish ground entity if ( m_hGroundEntity != NULL ) { m_hGroundEntity->AddEntityToGroundList( this ); } return status; } //----------------------------------------------------------------------------- // Purpose: Recursively restores all the classes in an object, in reverse order (top down) // Output : int 0 on failure, 1 on success //----------------------------------------------------------------------------- int C_BaseEntity::RestoreDataDescBlock( IRestore &restore, datamap_t *dmap ) { return restore.ReadAll( this, dmap ); } //----------------------------------------------------------------------------- // capabilities //----------------------------------------------------------------------------- int C_BaseEntity::ObjectCaps( void ) { return 0; } //----------------------------------------------------------------------------- // Purpose: // Output : C_AI_BaseNPC //----------------------------------------------------------------------------- C_AI_BaseNPC *C_BaseEntity::MyNPCPointer( void ) { if ( IsNPC() ) { return assert_cast<C_AI_BaseNPC *>(this); } return NULL; } //----------------------------------------------------------------------------- // Purpose: For each client (only can be local client in client .dll ) checks the client has disabled CC and if so, removes them from // the recipient list. // Input : filter - //----------------------------------------------------------------------------- void C_BaseEntity::RemoveRecipientsIfNotCloseCaptioning( C_RecipientFilter& filter ) { extern ConVar closecaption; if ( !closecaption.GetBool() ) { filter.Reset(); } } //----------------------------------------------------------------------------- // Purpose: // Input : recording - // Output : inline void //----------------------------------------------------------------------------- void C_BaseEntity::EnableInToolView( bool bEnable ) { #ifndef NO_TOOLFRAMEWORK m_bEnabledInToolView = bEnable; UpdateVisibility(); #endif } void C_BaseEntity::SetToolRecording( bool recording ) { #ifndef NO_TOOLFRAMEWORK m_bToolRecording = recording; if ( m_bToolRecording ) { recordinglist->AddToList( GetClientHandle() ); } else { recordinglist->RemoveFromList( GetClientHandle() ); } #endif } bool C_BaseEntity::HasRecordedThisFrame() const { #ifndef NO_TOOLFRAMEWORK Assert( m_nLastRecordedFrame <= gpGlobals->framecount ); return m_nLastRecordedFrame == gpGlobals->framecount; #else return false; #endif } void C_BaseEntity::GetToolRecordingState( KeyValues *msg ) { Assert( ToolsEnabled() ); if ( !ToolsEnabled() ) return; VPROF_BUDGET( "C_BaseEntity::GetToolRecordingState", VPROF_BUDGETGROUP_TOOLS ); C_BaseEntity *pOwner = m_hOwnerEntity; static BaseEntityRecordingState_t state; state.m_flTime = gpGlobals->curtime; state.m_pModelName = modelinfo->GetModelName( GetModel() ); state.m_nOwner = pOwner ? pOwner->entindex() : -1; state.m_nEffects = m_fEffects; state.m_bVisible = ShouldDraw() && !IsDormant(); state.m_bRecordFinalVisibleSample = false; state.m_vecRenderOrigin = GetRenderOrigin(); state.m_vecRenderAngles = GetRenderAngles(); // use EF_NOINTERP if the owner or a hierarchical parent has NO_INTERP if ( pOwner && pOwner->IsEffectActive( EF_NOINTERP ) ) { state.m_nEffects |= EF_NOINTERP; } C_BaseEntity *pParent = GetMoveParent(); while ( pParent ) { if ( pParent->IsEffectActive( EF_NOINTERP ) ) { state.m_nEffects |= EF_NOINTERP; break; } pParent = pParent->GetMoveParent(); } msg->SetPtr( "baseentity", &state ); } void C_BaseEntity::CleanupToolRecordingState( KeyValues *msg ) { } void C_BaseEntity::RecordToolMessage() { Assert( IsToolRecording() ); if ( !IsToolRecording() ) return; if ( HasRecordedThisFrame() ) return; KeyValues *msg = new KeyValues( "entity_state" ); // Post a message back to all IToolSystems GetToolRecordingState( msg ); Assert( (int)GetToolHandle() != 0 ); ToolFramework_PostToolMessage( GetToolHandle(), msg ); CleanupToolRecordingState( msg ); msg->deleteThis(); m_nLastRecordedFrame = gpGlobals->framecount; } // (static function) void C_BaseEntity::ToolRecordEntities() { VPROF_BUDGET( "C_BaseEntity::ToolRecordEnties", VPROF_BUDGETGROUP_TOOLS ); if ( !ToolsEnabled() || !clienttools->IsInRecordingMode() ) return; // Let non-dormant client created predictables get added, too int c = recordinglist->Count(); for ( int i = 0 ; i < c ; i++ ) { IClientRenderable *pRenderable = recordinglist->Get( i ); if ( !pRenderable ) continue; pRenderable->RecordToolMessage(); } } void C_BaseEntity::AddToInterpolationList() { if ( m_InterpolationListEntry == 0xFFFF ) m_InterpolationListEntry = g_InterpolationList.AddToTail( this ); } void C_BaseEntity::RemoveFromInterpolationList() { if ( m_InterpolationListEntry != 0xFFFF ) { g_InterpolationList.Remove( m_InterpolationListEntry ); m_InterpolationListEntry = 0xFFFF; } } void C_BaseEntity::AddToTeleportList() { if ( m_TeleportListEntry == 0xFFFF ) m_TeleportListEntry = g_TeleportList.AddToTail( this ); } void C_BaseEntity::RemoveFromTeleportList() { if ( m_TeleportListEntry != 0xFFFF ) { g_TeleportList.Remove( m_TeleportListEntry ); m_TeleportListEntry = 0xFFFF; } } void C_BaseEntity::AddVar( void *data, IInterpolatedVar *watcher, int type, bool bSetup ) { // Only add it if it hasn't been added yet. bool bAddIt = true; for ( int i=0; i < m_VarMap.m_Entries.Count(); i++ ) { if ( m_VarMap.m_Entries[i].watcher == watcher ) { if ( (type & EXCLUDE_AUTO_INTERPOLATE) != (watcher->GetType() & EXCLUDE_AUTO_INTERPOLATE) ) { // Its interpolation mode changed, so get rid of it and re-add it. RemoveVar( m_VarMap.m_Entries[i].data, true ); } else { // They're adding something that's already there. No need to re-add it. bAddIt = false; } break; } } if ( bAddIt ) { // watchers must have a debug name set Assert( watcher->GetDebugName() != NULL ); VarMapEntry_t map; map.data = data; map.watcher = watcher; map.type = type; map.m_bNeedsToInterpolate = true; if ( type & EXCLUDE_AUTO_INTERPOLATE ) { m_VarMap.m_Entries.AddToTail( map ); } else { m_VarMap.m_Entries.AddToHead( map ); ++m_VarMap.m_nInterpolatedEntries; } } if ( bSetup ) { watcher->Setup( data, type ); watcher->SetInterpolationAmount( GetInterpolationAmount( watcher->GetType() ) ); } } void C_BaseEntity::RemoveVar( void *data, bool bAssert ) { for ( int i=0; i < m_VarMap.m_Entries.Count(); i++ ) { if ( m_VarMap.m_Entries[i].data == data ) { if ( !( m_VarMap.m_Entries[i].type & EXCLUDE_AUTO_INTERPOLATE ) ) --m_VarMap.m_nInterpolatedEntries; m_VarMap.m_Entries.Remove( i ); return; } } if ( bAssert ) { Assert( !"RemoveVar" ); } } void C_BaseEntity::CheckCLInterpChanged() { float flCurValue_Interp = GetClientInterpAmount(); static float flLastValue_Interp = flCurValue_Interp; float flCurValue_InterpNPCs = cl_interp_npcs.GetFloat(); static float flLastValue_InterpNPCs = flCurValue_InterpNPCs; if ( flLastValue_Interp != flCurValue_Interp || flLastValue_InterpNPCs != flCurValue_InterpNPCs ) { flLastValue_Interp = flCurValue_Interp; flLastValue_InterpNPCs = flCurValue_InterpNPCs; // Tell all the existing entities to update their interpolation amounts to account for the change. C_BaseEntityIterator iterator; C_BaseEntity *pEnt; while ( (pEnt = iterator.Next()) != NULL ) { pEnt->Interp_UpdateInterpolationAmounts( pEnt->GetVarMapping() ); } } } void C_BaseEntity::DontRecordInTools() { #ifndef NO_TOOLFRAMEWORK m_bRecordInTools = false; #endif } int C_BaseEntity::GetCreationTick() const { return m_nCreationTick; } //------------------------------------------------------------------------------ void CC_CL_Find_Ent( const CCommand& args ) { if ( args.ArgC() < 2 ) { Msg( "Format: cl_find_ent <substring>\n" ); return; } int iCount = 0; const char *pszSubString = args[1]; Msg("Searching for client entities with classname containing substring: '%s'\n", pszSubString ); C_BaseEntity *ent = NULL; while ( (ent = ClientEntityList().NextBaseEntity(ent)) != NULL ) { const char *pszClassname = ent->GetClassname(); bool bMatches = false; if ( pszClassname && pszClassname[0] ) { if ( Q_stristr( pszClassname, pszSubString ) ) { bMatches = true; } } if ( bMatches ) { iCount++; Msg(" '%s' (entindex %d) %s \n", pszClassname ? pszClassname : "[NO NAME]", ent->entindex(), ent->IsDormant() ? "(DORMANT)" : "" ); } } Msg("Found %d matches.\n", iCount); } static ConCommand cl_find_ent("cl_find_ent", CC_CL_Find_Ent, "Find and list all client entities with classnames that contain the specified substring.\nFormat: cl_find_ent <substring>\n", FCVAR_CHEAT); //------------------------------------------------------------------------------ void CC_CL_Find_Ent_Index( const CCommand& args ) { if ( args.ArgC() < 2 ) { Msg( "Format: cl_find_ent_index <index>\n" ); return; } int iIndex = atoi(args[1]); C_BaseEntity *ent = ClientEntityList().GetBaseEntity( iIndex ); if ( ent ) { const char *pszClassname = ent->GetClassname(); Msg(" '%s' (entindex %d) %s \n", pszClassname ? pszClassname : "[NO NAME]", iIndex, ent->IsDormant() ? "(DORMANT)" : "" ); } else { Msg("Found no entity at %d.\n", iIndex); } } static ConCommand cl_find_ent_index("cl_find_ent_index", CC_CL_Find_Ent_Index, "Display data for clientside entity matching specified index.\nFormat: cl_find_ent_index <index>\n", FCVAR_CHEAT);
mit
Philip-Trettner/GlmSharp
GlmSharp/GlmSharp/Mat2x3/gmat2x3.glm.cs
1035
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Numerics; using System.Linq; using GlmSharp.Swizzle; // ReSharper disable InconsistentNaming namespace GlmSharp { /// <summary> /// Static class that contains static glm functions /// </summary> public static partial class glm { /// <summary> /// Creates a 2D array with all values (address: Values[x, y]) /// </summary> public static T[,] Values<T>(gmat2x3<T> m) => m.Values; /// <summary> /// Creates a 1D array with all values (internal order) /// </summary> public static T[] Values1D<T>(gmat2x3<T> m) => m.Values1D; /// <summary> /// Returns an enumerator that iterates through all fields. /// </summary> public static IEnumerator<T> GetEnumerator<T>(gmat2x3<T> m) => m.GetEnumerator(); } }
mit
alanctgardner/gogen-avro
v8/generator/package.go
1236
// Utility methods for managing and writing generated code package generator import ( "fmt" gofmt "go/format" "io/ioutil" "path/filepath" "sort" ) // Package represents the output package type Package struct { name string header string files map[string]string } func NewPackage(name, header string) *Package { return &Package{name: name, header: header, files: make(map[string]string)} } func (p *Package) WriteFiles(targetDir string) error { for name, body := range p.files { targetFile := filepath.Join(targetDir, name) fileContent, err := gofmt.Source([]byte(fmt.Sprintf("%v\npackage %v\n%v", p.header, p.name, body))) if err != nil { return fmt.Errorf("Error writing file %v - %v", targetFile, err) } err = ioutil.WriteFile(targetFile, []byte(fileContent), 0640) if err != nil { return fmt.Errorf("Error writing file %v - %v", targetFile, err) } } return nil } func (p *Package) Files() []string { files := make([]string, 0) for file, _ := range p.files { files = append(files, file) } sort.Strings(files) return files } func (p *Package) HasFile(name string) bool { _, ok := p.files[name] return ok } func (p *Package) AddFile(name string, body string) { p.files[name] = body }
mit
koharjidan/bitcoin
src/qt/locale/bitcoin_it.ts
180363
<<<<<<< HEAD <<<<<<< HEAD <TS language="it" version="2.1"> <<<<<<< HEAD ======= <context> <name>AboutDialog</name> <message> <source>About Bitcoin Core</source> <translation>Info su Bitcoin Core</translation> </message> <message> <source>&lt;b&gt;Bitcoin Core&lt;/b&gt; version</source> <translation>Versione &lt;b&gt;Bitcoin Core&lt;/b&gt;</translation> </message> <message> <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> Questo è un software sperimentale. Distribuito sotto la licenza software MIT/X11, vedi il file COPYING incluso oppure su http://www.opensource.org/licenses/mit-license.php. Questo prodotto include software sviluppato dal progetto OpenSSL per l'uso del Toolkit OpenSSL (http://www.openssl.org/), software crittografico scritto da Eric Young ([email protected]) e software UPnP scritto da Thomas Bernard.</translation> </message> <message> <source>Copyright</source> <translation>Copyright</translation> </message> <message> <source>The Bitcoin Core developers</source> <translation>Gli sviluppatori del Bitcoin Core</translation> </message> <message> <source>(%1-bit)</source> <translation>(%1-bit)</translation> </message> </context> >>>>>>> 5b9f78d69ccf189bebe894b1921e34417103a046 ======= <TS language="it" version="2.0"> >>>>>>> 9ff0bc9beb90cf96fb0a9698de22e2bc60fed2f2 ======= <TS language="it" version="2.1"> >>>>>>> 80d1f2e48364f05b2cdf44239b3a1faa0277e58e <context> <name>AddressBookPage</name> <message> <source>Right-click to edit address or label</source> <translation>Fare clic con il tasto destro del mouse per modificare l'indirizzo o l'etichetta</translation> </message> <message> <source>Create a new address</source> <translation>Crea un nuovo indirizzo</translation> </message> <message> <source>&amp;New</source> <translation>&amp;Nuovo</translation> </message> <message> <source>Copy the currently selected address to the system clipboard</source> <translation>Copia negli appunti l'indirizzo attualmente selezionato</translation> </message> <message> <source>&amp;Copy</source> <translation>&amp;Copia</translation> </message> <message> <source>C&amp;lose</source> <translation>C&amp;hiudi</translation> </message> <message> <source>&amp;Copy Address</source> <translation>&amp;Copia l'indirizzo</translation> </message> <message> <source>Delete the currently selected address from the list</source> <translation>Rimuove dalla lista l'indirizzo attualmente selezionato</translation> </message> <message> <source>Export the data in the current tab to a file</source> <translation>Esporta su file i dati contenuti nella tabella corrente</translation> </message> <message> <source>&amp;Export</source> <translation>&amp;Esporta</translation> </message> <message> <source>&amp;Delete</source> <translation>&amp;Elimina</translation> </message> <message> <source>Choose the address to send coins to</source> <translation>Scegli l'indirizzo a cui inviare bitcoin</translation> </message> <message> <source>Choose the address to receive coins with</source> <translation>Scegli l'indirizzo con cui ricevere bitcoin</translation> </message> <message> <source>C&amp;hoose</source> <translation>Sc&amp;egli</translation> </message> <message> <source>Sending addresses</source> <translation>Indirizzi d'invio</translation> </message> <message> <source>Receiving addresses</source> <translation>Indirizzi di ricezione</translation> </message> <message> <source>These are your Bitcoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation>Questo è un elenco di indirizzi Bitcoin a cui puoi inviare pagamenti. Controlla sempre l'importo e l'indirizzo del beneficiario prima di inviare bitcoin.</translation> </message> <message> <source>These are your Bitcoin addresses for receiving payments. It is recommended to use a new receiving address for each transaction.</source> <translation>Questi sono i tuoi indirizzi Bitcoin che puoi usare per ricevere pagamenti. Si raccomanda di generare un nuovo indirizzo per ogni transazione.</translation> </message> <message> <source>Copy &amp;Label</source> <translation>Copia &amp;l'etichetta</translation> </message> <message> <source>&amp;Edit</source> <translation>&amp;Modifica</translation> </message> <message> <source>Export Address List</source> <translation>Esporta Lista Indirizzi</translation> </message> <message> <source>Comma separated file (*.csv)</source> <translation>Testo CSV (*.csv)</translation> </message> <message> <source>Exporting Failed</source> <translation>Esportazione Fallita.</translation> </message> <message> <source>There was an error trying to save the address list to %1. Please try again.</source> <translation>Si è verificato un errore tentando di salvare la lista degli indirizzi su %1. Si prega di riprovare.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <source>Label</source> <translation>Etichetta</translation> </message> <message> <source>Address</source> <translation>Indirizzo</translation> </message> <message> <source>(no label)</source> <translation>(nessuna etichetta)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <source>Passphrase Dialog</source> <translation>Finestra passphrase</translation> </message> <message> <source>Enter passphrase</source> <translation>Inserisci la passphrase</translation> </message> <message> <source>New passphrase</source> <translation>Nuova passphrase</translation> </message> <message> <source>Repeat new passphrase</source> <translation>Ripeti la nuova passphrase</translation> </message> <message> <source>Encrypt wallet</source> <translation>Cifra il portamonete</translation> </message> <message> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Questa operazione necessita della passphrase per sbloccare il portamonete.</translation> </message> <message> <source>Unlock wallet</source> <translation>Sblocca il portamonete</translation> </message> <message> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Quest'operazione necessita della passphrase per decifrare il portamonete,</translation> </message> <message> <source>Decrypt wallet</source> <translation>Decifra il portamonete</translation> </message> <message> <source>Change passphrase</source> <translation>Cambia la passphrase</translation> </message> <message> <source>Confirm wallet encryption</source> <translation>Conferma la cifratura del portamonete</translation> </message> <message> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR BITCOINS&lt;/b&gt;!</source> <translation>Attenzione: perdendo la passphrase di un portamonete cifrato &lt;b&gt;TUTTI I PROPRI BITCOIN ANDRANNO PERSI&lt;/b&gt;!</translation> </message> <message> <source>Are you sure you wish to encrypt your wallet?</source> <translation>Si è sicuri di voler cifrare il portamonete?</translation> </message> <message> <source>Bitcoin Core 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>Bitcoin Core si chiuderà per portare a termine il processo di cifratura. Si ricorda che la cifratura del portamonete non garantisce protezione totale contro i furti causati da infezioni malware.</translation> </message> <message> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation>IMPORTANTE: qualsiasi backup del file portamonete effettuato in precedenza dovrà essere sostituito con il file del portamonete cifrato appena generato. Per ragioni di sicurezza, i precedenti backup del file del portamonete non cifrato diventeranno inservibili non appena si inizierà ad utilizzare il nuovo portamonete cifrato.</translation> </message> <message> <source>Warning: The Caps Lock key is on!</source> <translation>Attenzione: il tasto Blocco maiuscole è attivo!</translation> </message> <message> <source>Wallet encrypted</source> <translation>Portamonete cifrato</translation> </message> <message> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;ten or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>Inserisci la nuova passphrase per il portamonete.&lt;br/&gt;Si consiglia di utilizzare &lt;b&gt;almeno dieci caratteri casuali&lt;/b&gt; oppure &lt;b&gt;otto o più parole&lt;/b&gt;.</translation> </message> <message> <source>Enter the old passphrase and new passphrase to the wallet.</source> <translation>Inserisci la vecchia e la nuova passphrase per il portamonete.</translation> </message> <message> <source>Wallet encryption failed</source> <translation>Cifratura del portamonete fallita</translation> </message> <message> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Cifratura del portamonete fallita a causa di un errore interno. Il portamonete non è stato cifrato.</translation> </message> <message> <source>The supplied passphrases do not match.</source> <translation>Le passphrase inserite non corrispondono.</translation> </message> <message> <source>Wallet unlock failed</source> <translation>Sblocco del portamonete fallito</translation> </message> <message> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>La passphrase inserita per la decifrazione del portamonete è errata.</translation> </message> <message> <source>Wallet decryption failed</source> <translation>Decifrazione del portamonete fallita</translation> </message> <message> <source>Wallet passphrase was successfully changed.</source> <translation>Passphrase del portamonete modificata con successo.</translation> </message> </context> <context> <name>BanTableModel</name> <message> <source>IP/Netmask</source> <translation>IP/Netmask</translation> </message> <message> <source>Banned Until</source> <translation>Bannato fino a</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <source>Sign &amp;message...</source> <translation>Firma &amp;messaggio...</translation> </message> <message> <source>Synchronizing with network...</source> <translation>Sincronizzazione con la rete in corso...</translation> </message> <message> <source>&amp;Overview</source> <translation>&amp;Sintesi</translation> </message> <message> <source>Node</source> <translation>Nodo</translation> </message> <message> <source>Show general overview of wallet</source> <translation>Mostra lo stato generale del portamonete</translation> </message> <message> <source>&amp;Transactions</source> <translation>&amp;Transazioni</translation> </message> <message> <source>Browse transaction history</source> <translation>Mostra la cronologia delle transazioni</translation> </message> <message> <source>E&amp;xit</source> <translation>&amp;Esci</translation> </message> <message> <source>Quit application</source> <translation>Chiudi applicazione</translation> </message> <message> <source>About &amp;Qt</source> <translation>Informazioni su &amp;Qt</translation> </message> <message> <source>Show information about Qt</source> <translation>Mostra le informazioni su Qt</translation> </message> <message> <source>&amp;Options...</source> <translation>&amp;Opzioni...</translation> </message> <message> <source>&amp;Encrypt Wallet...</source> <translation>&amp;Cifra il portamonete...</translation> </message> <message> <source>&amp;Backup Wallet...</source> <translation>&amp;Backup portamonete...</translation> </message> <message> <source>&amp;Change Passphrase...</source> <translation>&amp;Cambia passphrase...</translation> </message> <message> <source>&amp;Sending addresses...</source> <translation>&amp;Indirizzi d'invio...</translation> </message> <message> <source>&amp;Receiving addresses...</source> <translation>Indirizzi di &amp;ricezione...</translation> </message> <message> <source>Open &amp;URI...</source> <translation>Apri &amp;URI...</translation> </message> <message> <source>Bitcoin Core client</source> <translation>Bitcoin Core client</translation> </message> <message> <source>Importing blocks from disk...</source> <translation>Importazione blocchi dal disco...</translation> </message> <message> <source>Reindexing blocks on disk...</source> <translation>Re-indicizzazione blocchi su disco...</translation> </message> <message> <source>Send coins to a Bitcoin address</source> <translation>Invia fondi ad un indirizzo Bitcoin</translation> </message> <message> <source>Backup wallet to another location</source> <translation>Effettua il backup del portamonete</translation> </message> <message> <source>Change the passphrase used for wallet encryption</source> <translation>Cambia la passphrase utilizzata per la cifratura del portamonete</translation> </message> <message> <source>&amp;Debug window</source> <translation>Finestra di &amp;debug</translation> </message> <message> <source>Open debugging and diagnostic console</source> <translation>Apri la console di debugging e diagnostica</translation> </message> <message> <source>&amp;Verify message...</source> <translation>&amp;Verifica messaggio...</translation> </message> <message> <source>Bitcoin</source> <translation>Bitcoin</translation> </message> <message> <source>Wallet</source> <translation>Portamonete</translation> </message> <message> <source>&amp;Send</source> <translation>&amp;Invia</translation> </message> <message> <source>&amp;Receive</source> <translation>&amp;Ricevi</translation> </message> <message> <source>Show information about Bitcoin Core</source> <translation>Mostra le informazioni su Bitcoin Core</translation> </message> <message> <source>&amp;Show / Hide</source> <translation>&amp;Mostra / Nascondi</translation> </message> <message> <source>Show or hide the main Window</source> <translation>Mostra o nascondi la Finestra principale</translation> </message> <message> <source>Encrypt the private keys that belong to your wallet</source> <translation>Cifra le chiavi private che appartengono al tuo portamonete</translation> </message> <message> <source>Sign messages with your Bitcoin addresses to prove you own them</source> <translation>Firma messaggi con i tuoi indirizzi Bitcoin per dimostrarne il possesso</translation> </message> <message> <source>Verify messages to ensure they were signed with specified Bitcoin addresses</source> <translation>Verifica che i messaggi siano stati firmati con gli indirizzi Bitcoin specificati</translation> </message> <message> <source>&amp;File</source> <translation>&amp;File</translation> </message> <message> <source>&amp;Settings</source> <translation>&amp;Impostazioni</translation> </message> <message> <source>&amp;Help</source> <translation>&amp;Aiuto</translation> </message> <message> <source>Tabs toolbar</source> <<<<<<< HEAD <translation>Barra degli strumenti "Tabs"</translation> <<<<<<< HEAD ======= </message> <message> <source>[testnet]</source> <translation>[testnet]</translation> >>>>>>> 5b9f78d69ccf189bebe894b1921e34417103a046 ======= <translation>Barra degli strumenti</translation> >>>>>>> 80d1f2e48364f05b2cdf44239b3a1faa0277e58e </message> <message> <source>Bitcoin Core</source> <translation>Bitcoin Core</translation> </message> <message> <source>Request payments (generates QR codes and bitcoin: URIs)</source> <translation>Richiedi pagamenti (genera codici QR e bitcoin: URI)</translation> </message> <message> <source>&amp;About Bitcoin Core</source> <translation>&amp;Informazioni su Bitcoin Core</translation> </message> <message> <source>Modify configuration options for Bitcoin Core</source> <translation>Modifica opzioni di configurazione per Bitcoin Core</translation> </message> <message> <source>Show the list of used sending addresses and labels</source> <translation>Mostra la lista degli indirizzi di invio utilizzati</translation> </message> <message> <source>Show the list of used receiving addresses and labels</source> <translation>Mostra la lista degli indirizzi di ricezione utilizzati</translation> </message> <message> <source>Open a bitcoin: URI or payment request</source> <translation>Apri un bitcoin: URI o una richiesta di pagamento</translation> </message> <message> <source>&amp;Command-line options</source> <translation>Opzioni della riga di &amp;comando</translation> </message> <message> <source>Show the Bitcoin Core help message to get a list with possible Bitcoin command-line options</source> <translation>Mostra il messaggio di aiuto di Bitcoin Core per ottenere la lista delle opzioni della riga di comando valide.</translation> </message> <message numerus="yes"> <source>%n active connection(s) to Bitcoin network</source> <translation><numerusform>%n connessione attiva alla rete Bitcoin</numerusform><numerusform>%n connessioni alla rete Bitcoin attive</numerusform></translation> </message> <message> <source>No block source available...</source> <translation>Nessuna fonte di blocchi disponibile...</translation> </message> <message numerus="yes"> <source>Processed %n block(s) of transaction history.</source> <translation><numerusform>Elaborato %n blocco dello storico transazioni.</numerusform><numerusform>Elaborati %n blocchi dello storico transazioni.</numerusform></translation> </message> <message numerus="yes"> <source>%n hour(s)</source> <translation><numerusform>%n ora</numerusform><numerusform>%n ore</numerusform></translation> </message> <message numerus="yes"> <source>%n day(s)</source> <translation><numerusform>%n giorno</numerusform><numerusform>%n giorni</numerusform></translation> </message> <message numerus="yes"> <source>%n week(s)</source> <translation><numerusform>%n settimana</numerusform><numerusform>%n settimane</numerusform></translation> </message> <message> <source>%1 and %2</source> <translation>%1 e %2</translation> </message> <message numerus="yes"> <source>%n year(s)</source> <translation><numerusform>%n anno</numerusform><numerusform>%n anni</numerusform></translation> </message> <message> <source>%1 behind</source> <translation>Indietro di %1</translation> </message> <message> <source>Last received block was generated %1 ago.</source> <translation>L'ultimo blocco ricevuto è stato generato %1 fa.</translation> </message> <message> <source>Transactions after this will not yet be visible.</source> <translation>Le transazioni effettuate successivamente non sono ancora visibili.</translation> </message> <message> <source>Error</source> <translation>Errore</translation> </message> <message> <source>Warning</source> <translation>Attenzione</translation> </message> <message> <source>Information</source> <translation>Informazioni</translation> </message> <message> <source>Up to date</source> <translation>Aggiornato</translation> </message> <message> <source>Catching up...</source> <translation>In aggiornamento...</translation> </message> <message> <source>Date: %1 </source> <translation>Data: %1 </translation> </message> <message> <source>Amount: %1 </source> <translation>Quantità: %1 </translation> </message> <message> <source>Type: %1 </source> <translation>Tipo: %1 </translation> </message> <message> <source>Label: %1 </source> <translation>Etichetta: %1 </translation> </message> <message> <source>Address: %1 </source> <translation>Indirizzo: %1 </translation> </message> <message> <source>Sent transaction</source> <translation>Transazione inviata</translation> </message> <message> <source>Incoming transaction</source> <translation>Transazione ricevuta</translation> </message> <message> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>Il portamonete è &lt;b&gt;cifrato&lt;/b&gt; ed attualmente &lt;b&gt;sbloccato&lt;/b&gt;</translation> </message> <message> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>Il portamonete è &lt;b&gt;cifrato&lt;/b&gt; ed attualmente &lt;b&gt;bloccato&lt;/b&gt;</translation> </message> </context> <context> <name>ClientModel</name> <message> <source>Network Alert</source> <translation>Avviso di rete</translation> </message> </context> <context> <name>CoinControlDialog</name> <message> <source>Coin Selection</source> <translation>Selezione Input</translation> </message> <message> <source>Quantity:</source> <translation>Quantità:</translation> </message> <message> <source>Bytes:</source> <translation>Byte:</translation> </message> <message> <source>Amount:</source> <translation>Importo:</translation> </message> <message> <source>Priority:</source> <translation>Priorità:</translation> </message> <message> <source>Fee:</source> <translation>Commissione:</translation> </message> <message> <source>Dust:</source> <translation>Trascurabile:</translation> </message> <message> <source>After Fee:</source> <translation>Dopo Commissione:</translation> </message> <message> <source>Change:</source> <translation>Resto:</translation> </message> <message> <source>(un)select all</source> <translation>(de)seleziona tutto</translation> </message> <message> <source>Tree mode</source> <translation>Modalità Albero</translation> </message> <message> <source>List mode</source> <translation>Modalità Lista</translation> </message> <message> <source>Amount</source> <translation>Importo</translation> </message> <message> <source>Received with label</source> <translation>Ricevuto con l'etichetta</translation> </message> <message> <source>Received with address</source> <translation>Ricevuto con l'indirizzo</translation> </message> <message> <source>Date</source> <translation>Data</translation> </message> <message> <source>Confirmations</source> <translation>Conferme</translation> </message> <message> <source>Confirmed</source> <translation>Confermato</translation> </message> <message> <source>Priority</source> <translation>Priorità</translation> </message> <message> <source>Copy address</source> <translation>Copia l'indirizzo</translation> </message> <message> <source>Copy label</source> <translation>Copia l'etichetta</translation> </message> <message> <source>Copy amount</source> <translation>Copia importo</translation> </message> <message> <source>Copy transaction ID</source> <translation>Copia l'ID transazione</translation> </message> <message> <source>Lock unspent</source> <translation>Bloccare non spesi</translation> </message> <message> <source>Unlock unspent</source> <translation>Sbloccare non spesi</translation> </message> <message> <source>Copy quantity</source> <translation>Copia quantità</translation> </message> <message> <source>Copy fee</source> <translation>Copia commissione</translation> </message> <message> <source>Copy after fee</source> <translation>Copia dopo commissione</translation> </message> <message> <source>Copy bytes</source> <translation>Copia byte</translation> </message> <message> <source>Copy priority</source> <translation>Copia priorità</translation> </message> <message> <source>Copy dust</source> <translation>Copia trascurabile</translation> </message> <message> <source>Copy change</source> <translation>Copia resto</translation> </message> <message> <source>highest</source> <translation>massima</translation> </message> <message> <source>higher</source> <translation>molto alta</translation> </message> <message> <source>high</source> <translation>alta</translation> </message> <message> <source>medium-high</source> <translation>medio-alta</translation> </message> <message> <source>medium</source> <translation>media</translation> </message> <message> <source>low-medium</source> <translation>medio-bassa</translation> </message> <message> <source>low</source> <translation>bassa</translation> </message> <message> <source>lower</source> <translation>molto bassa</translation> </message> <message> <source>lowest</source> <translation>minima</translation> </message> <message> <source>(%1 locked)</source> <translation>(%1 bloccato)</translation> </message> <message> <source>none</source> <translation>nessuno</translation> </message> <message> <source>This label turns red if the transaction size is greater than 1000 bytes.</source> <translation>Questa etichetta diventerà rossa se la dimensione della transazione supererà i 1000 byte.</translation> </message> <message> <source>This label turns red if the priority is smaller than "medium".</source> <translation>Questa etichetta diventerà rossa se la priorità sarà inferiore a "media".</translation> </message> <message> <source>This label turns red if any recipient receives an amount smaller than %1.</source> <translation>Questa etichetta diventerà rossa se uno qualsiasi dei destinatari riceverà un importo inferiore a %1.</translation> </message> <message> <source>Can vary +/- %1 satoshi(s) per input.</source> <translation>Può variare di +/- %1 satoshi per input.</translation> </message> <message> <source>yes</source> <translation>sì</translation> </message> <message> <source>no</source> <translation>no</translation> </message> <message> <source>This means a fee of at least %1 per kB is required.</source> <translation>In tal caso sarà necessaria una commissione di almeno %1 per ogni kB.</translation> </message> <message> <source>Can vary +/- 1 byte per input.</source> <translation>Può variare di +/- 1 byte per input.</translation> </message> <message> <source>Transactions with higher priority are more likely to get included into a block.</source> <translation>Le transazioni con priorità più alta hanno più probabilità di essere incluse in un blocco.</translation> </message> <message> <source>(no label)</source> <translation>(nessuna etichetta)</translation> </message> <message> <source>change from %1 (%2)</source> <translation>resto da %1 (%2)</translation> </message> <message> <source>(change)</source> <translation>(resto)</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <source>Edit Address</source> <translation>Modifica l'indirizzo</translation> </message> <message> <source>&amp;Label</source> <translation>&amp;Etichetta</translation> </message> <message> <source>The label associated with this address list entry</source> <translation>L'etichetta associata con questa voce della lista degli indirizzi</translation> </message> <message> <source>The address associated with this address list entry. This can only be modified for sending addresses.</source> <translation>L'indirizzo associato con questa voce della lista degli indirizzi. Può essere modificato solo per gli indirizzi d'invio.</translation> </message> <message> <source>&amp;Address</source> <translation>&amp;Indirizzo</translation> </message> <message> <source>New receiving address</source> <translation>Nuovo indirizzo di ricezione</translation> </message> <message> <source>New sending address</source> <translation>Nuovo indirizzo d'invio</translation> </message> <message> <source>Edit receiving address</source> <translation>Modifica indirizzo di ricezione</translation> </message> <message> <source>Edit sending address</source> <translation>Modifica indirizzo d'invio</translation> </message> <message> <source>The entered address "%1" is already in the address book.</source> <translation>L'indirizzo "%1" è già presente in rubrica.</translation> </message> <message> <source>The entered address "%1" is not a valid Bitcoin address.</source> <translation>L'indirizzo "%1" non è un indirizzo bitcoin valido.</translation> </message> <message> <source>Could not unlock wallet.</source> <translation>Impossibile sbloccare il portamonete.</translation> </message> <message> <source>New key generation failed.</source> <translation>Generazione della nuova chiave non riuscita.</translation> </message> </context> <context> <name>FreespaceChecker</name> <message> <source>A new data directory will be created.</source> <translation>Sarà creata una nuova cartella dati.</translation> </message> <message> <source>name</source> <translation>nome</translation> </message> <message> <source>Directory already exists. Add %1 if you intend to create a new directory here.</source> <translation>Cartella già esistente. Aggiungi %1 se intendi creare qui una nuova cartella.</translation> </message> <message> <source>Path already exists, and is not a directory.</source> <translation>Il percorso è già esistente e non è una cartella.</translation> </message> <message> <source>Cannot create data directory here.</source> <translation>Impossibile creare una cartella dati qui.</translation> </message> </context> <context> <name>HelpMessageDialog</name> <message> <source>Bitcoin Core</source> <translation>Bitcoin Core</translation> </message> <message> <source>version</source> <translation>versione</translation> </message> <message> <source>(%1-bit)</source> <translation>(%1-bit)</translation> </message> <message> <source>About Bitcoin Core</source> <translation>Informazioni su Bitcoin Core</translation> </message> <message> <source>Command-line options</source> <translation>Opzioni della riga di comando</translation> </message> <message> <source>Usage:</source> <translation>Utilizzo:</translation> </message> <message> <source>command-line options</source> <translation>opzioni della riga di comando</translation> </message> <message> <source>UI Options:</source> <translation>Opzioni interfaccia:</translation> </message> <message> <source>Choose data directory on startup (default: %u)</source> <translation>Seleziona la directory dei dati all'avvio (default: %u)</translation> </message> <message> <source>Set language, for example "de_DE" (default: system locale)</source> <translation>Imposta la lingua, ad esempio "it_IT" (default: locale di sistema)</translation> </message> <message> <source>Start minimized</source> <translation>Avvia ridotto a icona</translation> </message> <message> <source>Set SSL root certificates for payment request (default: -system-)</source> <translation>Imposta un certificato SSL root per le richieste di pagamento (default: -system-)</translation> </message> <message> <source>Show splash screen on startup (default: %u)</source> <translation>Mostra schermata iniziale all'avvio (default: %u)</translation> </message> <message> <source>Reset all settings changes made over the GUI</source> <translation>Reset di tutte le modifiche alle impostazioni eseguite da interfaccia grafica</translation> </message> </context> <context> <name>Intro</name> <message> <source>Welcome</source> <translation>Benvenuto</translation> </message> <message> <source>Welcome to Bitcoin Core.</source> <translation>Benvenuti su Bitcoin Core.</translation> </message> <message> <source>As this is the first time the program is launched, you can choose where Bitcoin Core will store its data.</source> <translation>Visto che questa è la prima volta che il programma viene lanciato, puoi scegliere dove Bitcoin Core salverà i propri dati.</translation> </message> <message> <source>Bitcoin Core will download and store a copy of the Bitcoin block chain. At least %1GB of data will be stored in this directory, and it will grow over time. The wallet will also be stored in this directory.</source> <translation>Bitcoin Core scaricherà e salverà una copia della block chain di Bitcoin. Il portamonete ed almeno %1GB di dati saranno salvati in questa cartella. Si ricorda che lo spazio occupato andrà ad aumentare nel tempo.</translation> </message> <message> <source>Use the default data directory</source> <translation>Usa la cartella dati predefinita</translation> </message> <message> <source>Use a custom data directory:</source> <translation>Usa una cartella dati personalizzata:</translation> </message> <message> <source>Bitcoin Core</source> <translation>Bitcoin Core</translation> </message> <message> <<<<<<< HEAD <source>Error: Specified data directory "%1" cannot be created.</source> ======= <source>Error: Specified data directory "%1" can not be created.</source> >>>>>>> 5b9f78d69ccf189bebe894b1921e34417103a046 <translation>Errore: La cartella dati "%1" specificata non può essere creata.</translation> </message> <message> <source>Error</source> <translation>Errore</translation> </message> <message numerus="yes"> <source>(of %n GB needed)</source> <translation><numerusform>(di %nGB richiesti)</numerusform><numerusform>(%n GB richiesti)</numerusform></translation> </message> </context> <context> <name>OpenURIDialog</name> <message> <source>Open URI</source> <translation>Apri URI</translation> </message> <message> <source>Open payment request from URI or file</source> <translation>Apri richiesta di pagamento da URI o file</translation> </message> <message> <source>URI:</source> <translation>URI:</translation> </message> <message> <source>Select payment request file</source> <translation>Seleziona il file di richiesta di pagamento</translation> </message> <message> <source>Select payment request file to open</source> <translation>Seleziona il file di richiesta di pagamento da aprire</translation> </message> </context> <context> <name>OptionsDialog</name> <message> <source>Options</source> <translation>Opzioni</translation> </message> <message> <source>&amp;Main</source> <translation>&amp;Principale</translation> </message> <message> <source>Size of &amp;database cache</source> <translation>Dimensione della cache del &amp;database.</translation> </message> <message> <source>MB</source> <translation>MB</translation> </message> <message> <source>Number of script &amp;verification threads</source> <translation>Numero di thread di &amp;verifica degli script </translation> </message> <message> <source>Accept connections from outside</source> <translation>Accetta connessioni provenienti dall'esterno</translation> </message> <message> <source>Allow incoming connections</source> <translation>Permetti connessioni in ingresso</translation> </message> <message> <source>IP address of the proxy (e.g. IPv4: 127.0.0.1 / IPv6: ::1)</source> <translation>Indirizzo IP del proxy (ad es. IPv4: 127.0.0.1 / IPv6: ::1)</translation> </message> <message> <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 Exit in the menu.</source> <translation>Riduci ad icona invece di uscire dall'applicazione quando la finestra viene chiusa. Attivando questa opzione l'applicazione terminerà solo dopo aver selezionato Esci dal menu File.</translation> </message> <message> <source>The user interface language can be set here. This setting will take effect after restarting Bitcoin Core.</source> <translation>La lingua dell'interfaccia utente può essere impostata qui. L'applicazione delle modifiche avrà effetto dopo il riavvio di Bitcoin Core.</translation> </message> <message> <source>Third party URLs (e.g. a block explorer) that appear in the transactions tab as context menu items. %s in the URL is replaced by transaction hash. Multiple URLs are separated by vertical bar |.</source> <translation>URL di terze parti (ad es. un block explorer) che appaiono nella tabella delle transazioni come voci nel menu contestuale. "%s" nell'URL è sostituito dall'hash della transazione. Per specificare più URL separarli con una barra verticale "|".</translation> </message> <message> <source>Third party transaction URLs</source> <translation>URL di transazione di terze parti</translation> </message> <message> <source>Active command-line options that override above options:</source> <translation>Opzioni della riga di comando attive che sostituiscono i settaggi sopra elencati:</translation> </message> <message> <source>Reset all client options to default.</source> <translation>Reimposta tutte le opzioni del client allo stato predefinito.</translation> </message> <message> <source>&amp;Reset Options</source> <translation>&amp;Ripristina Opzioni</translation> </message> <message> <source>&amp;Network</source> <translation>Rete</translation> </message> <message> <source>Automatically start Bitcoin Core after logging in to the system.</source> <translation>Avvia automaticamente Bitcoin Core una volta effettuato l'accesso al sistema.</translation> </message> <message> <source>&amp;Start Bitcoin Core on system login</source> <translation>&amp;Avvia Bitcoin Core all'accesso al sistema</translation> </message> <message> <source>(0 = auto, &lt;0 = leave that many cores free)</source> <translation>(0 = automatico, &lt;0 = lascia questo numero di core liberi)</translation> </message> <message> <source>W&amp;allet</source> <translation>Port&amp;amonete</translation> </message> <message> <source>Expert</source> <translation>Esperti</translation> </message> <message> <source>Enable coin &amp;control features</source> <translation>Abilita le funzionalità di coin &amp;control</translation> </message> <message> <source>If you disable the spending of unconfirmed change, the change from a transaction cannot be used until that transaction has at least one confirmation. This also affects how your balance is computed.</source> <<<<<<< HEAD <translation>Disabilitando l'uso di resti non confermati, il resto di una transazione non potrà essere speso fino a quando la transazione non avrà ottenuto almeno una conferma. Questa impostazione influisce inoltre sul calcolo saldo.</translation> <<<<<<< HEAD </message> <message> <source>&amp;Spend unconfirmed change</source> <translation>&amp;Spendere resti non confermati</translation> ======= >>>>>>> 5b9f78d69ccf189bebe894b1921e34417103a046 ======= <translation>Disabilitando l'uso di resti non confermati, il resto di una transazione non potrà essere speso fino a quando non avrà ottenuto almeno una conferma. Questa impostazione influisce inoltre sul calcolo del saldo.</translation> </message> <message> <source>&amp;Spend unconfirmed change</source> <translation>&amp;Spendi resti non confermati</translation> >>>>>>> 80d1f2e48364f05b2cdf44239b3a1faa0277e58e </message> <message> <source>Automatically open the Bitcoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation>Apri automaticamente la porta del client Bitcoin sul router. Il protocollo UPnP deve essere supportato da parte del router ed attivo.</translation> </message> <message> <source>Map port using &amp;UPnP</source> <translation>Mappa le porte tramite &amp;UPnP</translation> </message> <message> <source>Connect to the Bitcoin network through a SOCKS5 proxy.</source> <translation>Connessione alla rete Bitcoin attraverso un proxy SOCKS5.</translation> </message> <message> <source>&amp;Connect through SOCKS5 proxy (default proxy):</source> <translation>&amp;Connessione attraverso proxy SOCKS5 (proxy predefinito):</translation> </message> <message> <source>Proxy &amp;IP:</source> <translation>&amp;IP del proxy:</translation> </message> <message> <source>&amp;Port:</source> <translation>&amp;Porta:</translation> </message> <message> <source>Port of the proxy (e.g. 9050)</source> <translation>Porta del proxy (ad es. 9050)</translation> </message> <message> <source>Used for reaching peers via:</source> <translation>Utilizzata per connettersi attraverso:</translation> </message> <message> <source>Shows, if the supplied default SOCKS5 proxy is used to reach peers via this network type.</source> <translation>Mostra se la proxy SOCKS5 fornita viene utilizzata per raggiungere i peers attraverso questo tipo di rete.</translation> </message> <message> <source>IPv4</source> <translation>IPv4</translation> </message> <message> <source>IPv6</source> <translation>IPv6</translation> </message> <message> <source>Tor</source> <translation>Tor</translation> </message> <message> <source>Connect to the Bitcoin network through a separate SOCKS5 proxy for Tor hidden services.</source> <translation>Connette alla rete Bitcoin attraverso un proxy SOCKS5 separato per Tor.</translation> </message> <message> <source>Use separate SOCKS5 proxy to reach peers via Tor hidden services:</source> <translation>Usa un proxy SOCKS5 separato per connettersi ai peers attraverso Tor:</translation> </message> <message> <source>&amp;Window</source> <translation>&amp;Finestra</translation> </message> <message> <source>Show only a tray icon after minimizing the window.</source> <translation>Mostra solo nella tray bar quando si riduce ad icona.</translation> </message> <message> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>&amp;Minimizza nella tray bar invece che sulla barra delle applicazioni</translation> </message> <message> <source>M&amp;inimize on close</source> <translation>M&amp;inimizza alla chiusura</translation> </message> <message> <source>&amp;Display</source> <translation>&amp;Mostra</translation> </message> <message> <source>User Interface &amp;language:</source> <translation>&amp;Lingua Interfaccia Utente:</translation> </message> <message> <source>&amp;Unit to show amounts in:</source> <translation>&amp;Unità di misura con cui visualizzare gli importi:</translation> </message> <message> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <<<<<<< HEAD <translation>Scegli l'unità di suddivisione predefinita da utilizzare per l'interfaccia e per l'invio di monete.</translation> <<<<<<< HEAD ======= </message> <message> <source>Whether to show Bitcoin addresses in the transaction list or not.</source> <translation>Specifica se gli indirizzi saranno visualizzati nella lista delle transazioni.</translation> </message> <message> <source>&amp;Display addresses in transaction list</source> <translation>&amp;Mostra gli indirizzi nella lista delle transazioni</translation> >>>>>>> 5b9f78d69ccf189bebe894b1921e34417103a046 ======= <translation>Scegli l'unità di suddivisione predefinita da utilizzare per l'interfaccia e per l'invio di bitcoin.</translation> >>>>>>> 80d1f2e48364f05b2cdf44239b3a1faa0277e58e </message> <message> <source>Whether to show coin control features or not.</source> <translation>Specifica se le funzionalita di coin control saranno visualizzate.</translation> </message> <message> <source>&amp;OK</source> <translation>&amp;OK</translation> </message> <message> <source>&amp;Cancel</source> <translation>&amp;Cancella</translation> </message> <message> <source>default</source> <translation>predefinito</translation> </message> <message> <source>none</source> <translation>nessuno</translation> </message> <message> <source>Confirm options reset</source> <translation>Conferma ripristino opzioni</translation> </message> <message> <source>Client restart required to activate changes.</source> <translation>È necessario un riavvio del client per applicare le modifiche.</translation> </message> <message> <source>Client will be shut down. Do you want to proceed?</source> <translation>Il client sarà arrestato. Si desidera procedere?</translation> </message> <message> <source>This change would require a client restart.</source> <translation>Questa modifica richiede un riavvio del client.</translation> </message> <message> <source>The supplied proxy address is invalid.</source> <translation>L'indirizzo proxy che hai fornito non è valido.</translation> </message> </context> <context> <name>OverviewPage</name> <message> <source>Form</source> <translation>Modulo</translation> </message> <message> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the Bitcoin network after a connection is established, but this process has not completed yet.</source> <translation>Le informazioni visualizzate potrebbero non essere aggiornate. Il portamonete si sincronizza automaticamente con la rete Bitcoin una volta stabilita una connessione, ma questo processo non è ancora stato completato.</translation> </message> <message> <source>Watch-only:</source> <translation>Sola lettura:</translation> </message> <message> <source>Available:</source> <translation>Disponibile:</translation> </message> <message> <source>Your current spendable balance</source> <translation>Il tuo saldo spendibile attuale</translation> </message> <message> <source>Pending:</source> <translation>In attesa:</translation> </message> <message> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the spendable balance</source> <translation>Totale delle transazioni in corso di conferma e che non sono ancora conteggiate nel saldo spendibile</translation> </message> <message> <source>Immature:</source> <translation>Immaturo:</translation> </message> <message> <source>Mined balance that has not yet matured</source> <translation>Importo generato dal mining e non ancora maturato</translation> </message> <message> <source>Balances</source> <translation>Saldo</translation> </message> <message> <source>Total:</source> <translation>Totale:</translation> </message> <message> <source>Your current total balance</source> <translation>Il tuo saldo totale attuale</translation> </message> <message> <source>Your current balance in watch-only addresses</source> <translation>Il tuo saldo attuale negli indirizzi di sola lettura</translation> </message> <message> <source>Spendable:</source> <translation>Spendibile:</translation> </message> <message> <source>Recent transactions</source> <translation>Transazioni recenti</translation> </message> <message> <source>Unconfirmed transactions to watch-only addresses</source> <translation>Transazioni non confermate su indirizzi di sola lettura</translation> </message> <message> <source>Mined balance in watch-only addresses that has not yet matured</source> <translation>Importo generato dal mining su indirizzi di sola lettura e non ancora maturato</translation> </message> <message> <source>Current total balance in watch-only addresses</source> <translation>Saldo corrente totale negli indirizzi di sola lettura</translation> </message> </context> <context> <name>PaymentServer</name> <message> <source>URI handling</source> <translation>Gestione URI</translation> </message> <message> <<<<<<< HEAD <source>Invalid payment address %1</source> <translation>Indirizzo di pagamento non valido %1</translation> </message> <message> <source>Payment request rejected</source> <translation>Richiesta di pagamento respinta</translation> </message> <message> <source>Payment request network doesn't match client network.</source> <translation>La rete della richiesta di pagamento non corrisponde alla rete del client.</translation> </message> <message> <source>Payment request is not initialized.</source> <translation>La richiesta di pagamento non è stata inizializzata.</translation> ======= <source>URI can not be parsed! This can be caused by an invalid Bitcoin address or malformed URI parameters.</source> <translation>Impossibile interpretare l'URI! Ciò può essere provocato da un indirizzo Bitcoin non valido o da parametri URI non corretti.</translation> >>>>>>> 5b9f78d69ccf189bebe894b1921e34417103a046 </message> <message> <source>Requested payment amount of %1 is too small (considered dust).</source> <translation>L'importo di pagamento di %1 richiesto è troppo basso (considerato come trascurabile).</translation> </message> <message> <source>Payment request error</source> <translation>Errore di richiesta di pagamento</translation> </message> <message> <source>Cannot start bitcoin: click-to-pay handler</source> <translation>Impossibile avviare bitcoin: gestore click-to-pay</translation> </message> <message> <<<<<<< HEAD ======= <source>Net manager warning</source> <translation>Avviso Net manager</translation> </message> <message> <source>Your active proxy doesn't support SOCKS5, which is required for payment requests via proxy.</source> <translation>Il proxy attualmente attivo non supporta SOCKS5, il quale è necessario per richieste di pagamento via proxy.</translation> </message> <message> >>>>>>> 5b9f78d69ccf189bebe894b1921e34417103a046 <source>Payment request fetch URL is invalid: %1</source> <translation>URL di recupero della Richiesta di pagamento non valido: %1</translation> </message> <message> <source>URI cannot be parsed! This can be caused by an invalid Bitcoin address or malformed URI parameters.</source> <translation>Impossibile interpretare l'URI! I parametri URI o l'indirizzo Bitcoin potrebbero non essere corretti.</translation> </message> <message> <source>Payment request file handling</source> <translation>Gestione del file di richiesta del pagamento</translation> </message> <message> <source>Payment request file cannot be read! This can be caused by an invalid payment request file.</source> <translation>Impossibile leggere il file della richiesta di pagamento! Il file della richiesta di pagamento potrebbe non essere valido.</translation> </message> <message> <source>Payment request expired.</source> <translation>Richiesta di pagamento scaduta.</translation> </message> <message> <source>Unverified payment requests to custom payment scripts are unsupported.</source> <translation>Le richieste di pagamento non verificate verso script di pagamento personalizzati non sono supportate.</translation> </message> <message> <source>Invalid payment request.</source> <translation>Richiesta di pagamento non valida.</translation> </message> <message> <source>Refund from %1</source> <translation>Rimborso da %1</translation> </message> <message> <source>Payment request %1 is too large (%2 bytes, allowed %3 bytes).</source> <translation>La richiesta di pagamento %1 (%2 byte) supera la dimensione massima di %3 byte.</translation> </message> <message> <source>Error communicating with %1: %2</source> <translation>Errore di comunicazione con %1: %2</translation> </message> <message> <source>Payment request cannot be parsed!</source> <translation>La richiesta di pagamento non può essere analizzata!</translation> </message> <message> <source>Bad response from server %1</source> <translation>Risposta errata da parte del server %1</translation> </message> <message> <source>Payment acknowledged</source> <translation>Pagamento riconosciuto</translation> </message> <message> <source>Network request error</source> <translation>Errore di richiesta di rete</translation> </message> </context> <context> <name>PeerTableModel</name> <message> <source>User Agent</source> <translation>User Agent</translation> </message> <message> <source>Node/Service</source> <translation>Nodo/Servizio</translation> </message> <message> <source>Ping Time</source> <translation>Tempo di ping</translation> </message> </context> <context> <name>QObject</name> <message> <source>Amount</source> <translation>Importo</translation> </message> <message> <source>Enter a Bitcoin address (e.g. %1)</source> <translation>Inserisci un indirizzo Bitcoin (ad es. %1)</translation> </message> <message> <source>%1 d</source> <translation>%1 d</translation> </message> <message> <<<<<<< HEAD <source>%1 h</source> <translation>%1 h</translation> </message> <message> <source>%1 m</source> <translation>%1 m</translation> ======= <source>Error: Specified data directory "%1" does not exist.</source> <translation>Errore: La cartella dati "%1" specificata non esiste.</translation> >>>>>>> 5b9f78d69ccf189bebe894b1921e34417103a046 </message> <message> <source>%1 s</source> <translation>%1 s</translation> </message> <message> <<<<<<< HEAD <source>NETWORK</source> <translation>RETE</translation> </message> <message> <<<<<<< HEAD <source>UNKNOWN</source> <translation>SCONOSCIUTO</translation> ======= <source>Bitcoin Core didn't yet exit safely...</source> <translation>Bitcoin Core non si è ancora chiuso con sicurezza...</translation> >>>>>>> 5b9f78d69ccf189bebe894b1921e34417103a046 </message> <message> ======= >>>>>>> 80d1f2e48364f05b2cdf44239b3a1faa0277e58e <source>None</source> <translation>Nessuno</translation> </message> <message> <source>N/A</source> <translation>N/D</translation> </message> <message> <source>%1 ms</source> <translation>%1 ms</translation> </message> </context> <context> <name>QRImageWidget</name> <message> <source>&amp;Save Image...</source> <translation>&amp;Salva Immagine...</translation> </message> <message> <source>&amp;Copy Image</source> <translation>&amp;Copia Immagine</translation> </message> <message> <source>Save QR Code</source> <translation>Salva codice QR</translation> </message> <message> <source>PNG Image (*.png)</source> <translation>Immagine PNG (*.png)</translation> </message> </context> <context> <name>RPCConsole</name> <message> <source>Client name</source> <translation>Nome del client</translation> </message> <message> <source>N/A</source> <translation>N/D</translation> </message> <message> <source>Client version</source> <translation>Versione client</translation> </message> <message> <source>&amp;Information</source> <translation>&amp;Informazioni</translation> </message> <message> <source>Debug window</source> <translation>Finestra di debug</translation> </message> <message> <source>General</source> <translation>Generale</translation> </message> <message> <source>Using OpenSSL version</source> <translation>Versione OpenSSL in uso</translation> </message> <message> <source>Using BerkeleyDB version</source> <translation>Versione BerkeleyDB in uso</translation> </message> <message> <source>Startup time</source> <translation>Ora di avvio</translation> </message> <message> <source>Network</source> <translation>Rete</translation> </message> <message> <source>Name</source> <translation>Nome</translation> </message> <message> <source>Number of connections</source> <translation>Numero di connessioni</translation> </message> <message> <source>Block chain</source> <translation>Block chain</translation> </message> <message> <source>Current number of blocks</source> <translation>Numero attuale di blocchi</translation> </message> <message> <source>Memory Pool</source> <translation>Memory Pool</translation> </message> <message> <source>Current number of transactions</source> <translation>Numero attuale di transazioni</translation> </message> <message> <source>Memory usage</source> <translation>Utilizzo memoria</translation> </message> <message> <source>Open the Bitcoin Core debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation>Apre il file log di debug di Bitcoin Core dalla cartella dati attuale. Questa azione può richiedere alcuni secondi per file log di grandi dimensioni.</translation> </message> <message> <source>Received</source> <translation>Ricevuto</translation> </message> <message> <source>Sent</source> <translation>Inviato</translation> </message> <message> <source>&amp;Peers</source> <translation>&amp;Peer</translation> </message> <message> <source>Banned peers</source> <translation>Peers bannati</translation> </message> <message> <source>Select a peer to view detailed information.</source> <translation>Seleziona un peer per visualizzare informazioni più dettagliate.</translation> </message> <message> <source>Whitelisted</source> <translation>Whitelisted/sicuri</translation> </message> <message> <source>Direction</source> <translation>Direzione</translation> </message> <message> <source>Version</source> <translation>Versione</translation> </message> <message> <source>Starting Block</source> <translation>Blocco di partenza</translation> </message> <message> <source>Synced Headers</source> <translation>Headers sincronizzati</translation> </message> <message> <source>Synced Blocks</source> <translation>Blocchi sincronizzati</translation> </message> <message> <source>User Agent</source> <translation>User Agent</translation> </message> <message> <source>Services</source> <translation>Servizi</translation> </message> <message> <source>Ban Score</source> <translation>Punteggio di Ban</translation> </message> <message> <source>Connection Time</source> <translation>Tempo di Connessione</translation> </message> <message> <source>Last Send</source> <translation>Ultimo Invio</translation> </message> <message> <source>Last Receive</source> <translation>Ultima Ricezione</translation> </message> <message> <source>Ping Time</source> <translation>Tempo di Ping</translation> </message> <message> <source>The duration of a currently outstanding ping.</source> <translation>La durata di un ping attualmente in corso.</translation> </message> <message> <source>Ping Wait</source> <translation>Attesa ping</translation> </message> <message> <source>Time Offset</source> <translation>Scarto Temporale</translation> </message> <message> <source>Last block time</source> <translation>Ora del blocco più recente</translation> </message> <message> <source>&amp;Open</source> <translation>&amp;Apri</translation> </message> <message> <source>&amp;Console</source> <translation>&amp;Console</translation> </message> <message> <source>&amp;Network Traffic</source> <translation>&amp;Traffico di Rete</translation> </message> <message> <source>&amp;Clear</source> <translation>&amp;Cancella</translation> </message> <message> <source>Totals</source> <translation>Totali</translation> </message> <message> <source>In:</source> <translation>Entrata:</translation> </message> <message> <source>Out:</source> <translation>Uscita:</translation> </message> <message> <source>Build date</source> <translation>Data di creazione</translation> </message> <message> <source>Debug log file</source> <translation>File log del Debug</translation> </message> <message> <source>Clear console</source> <translation>Cancella console</translation> </message> <message> <source>&amp;Disconnect Node</source> <translation>&amp;Nodo Disconnesso</translation> </message> <message> <source>Ban Node for</source> <translation>Nodo Bannato perché</translation> </message> <message> <source>1 &amp;hour</source> <translation>1 &amp;ora</translation> </message> <message> <source>1 &amp;day</source> <translation>1 &amp;giorno</translation> </message> <message> <source>1 &amp;week</source> <translation>1 &amp;settimana</translation> </message> <message> <source>1 &amp;year</source> <translation>1 &amp;anno</translation> </message> <message> <source>&amp;Unban Node</source> <translation>&amp;Elimina Ban Nodo</translation> </message> <message> <source>Welcome to the Bitcoin Core RPC console.</source> <translation>Benvenuto nella console RPC di Bitcoin Core.</translation> </message> <message> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation>Usa le frecce direzionali per scorrere la cronologia, e &lt;b&gt;Ctrl-L&lt;/b&gt; per cancellarla.</translation> </message> <message> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation>Scrivi &lt;b&gt;help&lt;/b&gt; per un riassunto dei comandi disponibili.</translation> </message> <message> <source>%1 B</source> <translation>%1 B</translation> </message> <message> <source>%1 KB</source> <translation>%1 KB</translation> </message> <message> <source>%1 MB</source> <translation>%1 MB</translation> </message> <message> <source>%1 GB</source> <translation>%1 GB</translation> </message> <message> <source>(node id: %1)</source> <translation>(id nodo: %1)</translation> </message> <message> <source>via %1</source> <translation>via %1</translation> </message> <message> <source>never</source> <translation>mai</translation> </message> <message> <source>Inbound</source> <translation>In entrata</translation> </message> <message> <source>Outbound</source> <translation>In uscita</translation> </message> <message> <source>Yes</source> <translation>Si</translation> </message> <message> <source>No</source> <translation>No</translation> </message> <message> <source>Unknown</source> <translation>Sconosciuto</translation> </message> </context> <context> <name>ReceiveCoinsDialog</name> <message> <source>&amp;Amount:</source> <translation>&amp;Importo:</translation> </message> <message> <source>&amp;Label:</source> <translation>&amp;Etichetta:</translation> </message> <message> <source>&amp;Message:</source> <translation>&amp;Messaggio:</translation> </message> <message> <source>Reuse one of the previously used receiving addresses. Reusing addresses has security and privacy issues. Do not use this unless re-generating a payment request made before.</source> <translation>Riutilizza uno degli indirizzi di ricezione generati in precedenza. Riutilizzare un indirizzo comporta problemi di sicurezza e privacy. Non selezionare questa opzione a meno che non si stia rigenerando una richiesta di pagamento creata in precedenza.</translation> </message> <message> <source>R&amp;euse an existing receiving address (not recommended)</source> <translation>R&amp;iusa un indirizzo di ricezione (non raccomandato)</translation> </message> <message> <source>An optional message to attach to the payment request, which will be displayed when the request is opened. Note: The message will not be sent with the payment over the Bitcoin network.</source> <translation>Un messaggio opzionale da allegare e mostrare all'apertura della richiesta di pagamento. Nota: Il messaggio non sarà inviato con il pagamento sulla rete Bitcoin.</translation> </message> <message> <source>An optional label to associate with the new receiving address.</source> <translation>Un'etichetta opzionale da associare al nuovo indirizzo di ricezione.</translation> </message> <message> <source>Use this form to request payments. All fields are &lt;b&gt;optional&lt;/b&gt;.</source> <translation>Usa questo modulo per richiedere pagamenti. Tutti i campi sono &lt;b&gt;opzionali&lt;/b&gt;.</translation> </message> <message> <source>An optional amount to request. Leave this empty or zero to not request a specific amount.</source> <translation>Un importo opzionale da associare alla richiesta. Lasciare vuoto o a zero per non richiedere un importo specifico.</translation> </message> <message> <source>Clear all fields of the form.</source> <translation>Cancellare tutti i campi del modulo.</translation> </message> <message> <source>Clear</source> <translation>Cancella</translation> </message> <message> <source>Requested payments history</source> <translation>Cronologia pagamenti richiesti</translation> </message> <message> <source>&amp;Request payment</source> <translation>&amp;Richiedi pagamento</translation> </message> <message> <source>Show the selected request (does the same as double clicking an entry)</source> <translation>Mostra la richiesta selezionata (produce lo stesso effetto di un doppio click su una voce)</translation> </message> <message> <source>Show</source> <translation>Mostra</translation> </message> <message> <source>Remove the selected entries from the list</source> <translation>Rimuovi le voci selezionate dalla lista</translation> </message> <message> <source>Remove</source> <translation>Rimuovi</translation> </message> <message> <source>Copy label</source> <translation>Copia l'etichetta</translation> </message> <message> <source>Copy message</source> <translation>Copia il messaggio</translation> </message> <message> <source>Copy amount</source> <translation>Copia l'importo</translation> </message> </context> <context> <name>ReceiveRequestDialog</name> <message> <source>QR Code</source> <translation>Codice QR</translation> </message> <message> <source>Copy &amp;URI</source> <translation>Copia &amp;URI</translation> </message> <message> <source>Copy &amp;Address</source> <translation>Copia &amp;Indirizzo</translation> </message> <message> <source>&amp;Save Image...</source> <translation>&amp;Salva Immagine...</translation> </message> <message> <source>Request payment to %1</source> <translation>Richiesta di pagamento a %1</translation> </message> <message> <source>Payment information</source> <translation>Informazioni pagamento</translation> </message> <message> <source>URI</source> <translation>URI</translation> </message> <message> <source>Address</source> <translation>Indirizzo</translation> </message> <message> <source>Amount</source> <translation>Importo</translation> </message> <message> <source>Label</source> <translation>Etichetta</translation> </message> <message> <source>Message</source> <translation>Messaggio</translation> </message> <message> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation>L'URI risultante è troppo lungo, prova a ridurre il testo nell'etichetta / messaggio.</translation> </message> <message> <source>Error encoding URI into QR Code.</source> <translation>Errore nella codifica dell'URI nel codice QR.</translation> </message> </context> <context> <name>RecentRequestsTableModel</name> <message> <source>Date</source> <translation>Data</translation> </message> <message> <source>Label</source> <translation>Etichetta</translation> </message> <message> <source>Message</source> <translation>Messaggio</translation> </message> <message> <source>Amount</source> <translation>Importo</translation> </message> <message> <source>(no label)</source> <translation>(nessuna etichetta)</translation> </message> <message> <source>(no message)</source> <translation>(nessun messaggio)</translation> </message> <message> <source>(no amount)</source> <translation>(nessun importo)</translation> </message> </context> <context> <name>SendCoinsDialog</name> <message> <source>Send Coins</source> <translation>Invia Bitcoin</translation> </message> <message> <source>Coin Control Features</source> <translation>Funzionalità di Coin Control</translation> </message> <message> <source>Inputs...</source> <translation>Input...</translation> </message> <message> <source>automatically selected</source> <translation>selezionato automaticamente</translation> </message> <message> <source>Insufficient funds!</source> <translation>Fondi insufficienti!</translation> </message> <message> <source>Quantity:</source> <translation>Quantità:</translation> </message> <message> <source>Bytes:</source> <translation>Byte:</translation> </message> <message> <source>Amount:</source> <translation>Importo:</translation> </message> <message> <source>Priority:</source> <translation>Priorità:</translation> </message> <message> <source>Fee:</source> <translation>Commissione:</translation> </message> <message> <source>After Fee:</source> <translation>Dopo Commissione:</translation> </message> <message> <source>Change:</source> <translation>Resto:</translation> </message> <message> <source>If this is activated, but the change address is empty or invalid, change will be sent to a newly generated address.</source> <translation>In caso di abilitazione con indirizzo vuoto o non valido, il resto sarà inviato ad un nuovo indirizzo generato appositamente.</translation> </message> <message> <source>Custom change address</source> <translation>Personalizza indirizzo di resto</translation> </message> <message> <source>Transaction Fee:</source> <translation>Commissione di Transazione:</translation> </message> <message> <source>Choose...</source> <translation>Scegli...</translation> </message> <message> <source>collapse fee-settings</source> <translation>minimizza le impostazioni di commissione</translation> </message> <message> <source>per kilobyte</source> <translation>per kilobyte</translation> </message> <message> <source>If the custom fee is set to 1000 satoshis and the transaction is only 250 bytes, then "per kilobyte" only pays 250 satoshis in fee, while "total at least" pays 1000 satoshis. For transactions bigger than a kilobyte both pay by kilobyte.</source> <translation>Se la commissione personalizzata è impostata su 1000 satoshi e la transazione è di soli 250 byte, allora "per kilobyte" paga solo 250 satoshi di commissione, mentre "somma almeno" paga 1000 satoshi. Per transazioni più grandi di un kilobyte, entrambe le opzioni pagano al kilobyte.</translation> </message> <message> <source>Hide</source> <translation>Nascondi</translation> </message> <message> <source>total at least</source> <translation>somma almeno</translation> </message> <message> <source>Paying only the minimum fee is just fine as long as there is less transaction volume than space in the blocks. But be aware that this can end up in a never confirming transaction once there is more demand for bitcoin transactions than the network can process.</source> <translation>Non vi è alcuna controindicazione a pagare la commissione minima, a patto che il volume delle transazioni sia inferiore allo spazio disponibile nei blocchi. Occorre comunque essere consapevoli che ciò potrebbe impedire la conferma delle transazioni nel caso in cui la rete risultasse satura.</translation> </message> <message> <source>(read the tooltip)</source> <translation>(leggi il suggerimento)</translation> </message> <message> <source>Recommended:</source> <translation>Raccomandata:</translation> </message> <message> <source>Custom:</source> <translation>Personalizzata:</translation> </message> <message> <source>(Smart fee not initialized yet. This usually takes a few blocks...)</source> <translation>(Commissione intelligente non ancora inizializzata. Normalmente richiede un'attesa di alcuni blocchi...)</translation> </message> <message> <source>Confirmation time:</source> <translation>Tempo di conferma:</translation> </message> <message> <source>normal</source> <translation>normale</translation> </message> <message> <source>fast</source> <translation>veloce</translation> </message> <message> <source>Send as zero-fee transaction if possible</source> <translation>Invia come transazione a zero commissioni se possibile</translation> </message> <message> <source>(confirmation may take longer)</source> <translation>(la conferma potrebbe richiedere più tempo)</translation> </message> <message> <source>Send to multiple recipients at once</source> <translation>Invia simultaneamente a più beneficiari</translation> </message> <message> <source>Add &amp;Recipient</source> <translation>&amp;Aggiungi beneficiario</translation> </message> <message> <source>Clear all fields of the form.</source> <translation>Cancellare tutti i campi del modulo.</translation> </message> <message> <source>Dust:</source> <translation>Trascurabile:</translation> </message> <message> <source>Clear &amp;All</source> <translation>Cancella &amp;tutto</translation> </message> <message> <source>Balance:</source> <translation>Saldo:</translation> </message> <message> <source>Confirm the send action</source> <translation>Conferma l'azione di invio</translation> </message> <message> <source>S&amp;end</source> <translation>&amp;Invia</translation> </message> <message> <source>Confirm send coins</source> <translation>Conferma l'invio di bitcoin</translation> </message> <message> <source>%1 to %2</source> <translation>%1 a %2</translation> </message> <message> <source>Copy quantity</source> <translation>Copia quantità</translation> </message> <message> <source>Copy amount</source> <translation>Copia importo</translation> </message> <message> <source>Copy fee</source> <translation>Copia commissione</translation> </message> <message> <source>Copy after fee</source> <translation>Copia dopo commissione</translation> </message> <message> <source>Copy bytes</source> <translation>Copia byte</translation> </message> <message> <source>Copy priority</source> <translation>Copia priorità</translation> </message> <message> <source>Copy change</source> <translation>Copia resto</translation> </message> <message> <source>Total Amount %1</source> <translation>Ammontare Totale %1</translation> </message> <message> <source>or</source> <translation>o</translation> </message> <message> <source>The amount to pay must be larger than 0.</source> <translation>L'importo da pagare deve essere maggiore di 0.</translation> </message> <message> <source>The amount exceeds your balance.</source> <translation>L'importo è superiore al tuo saldo attuale.</translation> </message> <message> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>Il totale è superiore al tuo saldo attuale includendo la commissione di %1.</translation> </message> <message> <source>Transaction creation failed!</source> <translation>Creazione transazione fallita!</translation> </message> <message> <source>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>La transazione è stata respinta! Questo può accadere se alcuni bitcoin nel tuo portamonete sono già stati spesi, come nel caso in cui tu avessi utilizzato una copia del file wallet.dat per spendere bitcoin e questi non fossero stati considerati come spesi dal portamonete corrente.</translation> </message> <message> <source>A fee higher than %1 is considered an absurdly high fee.</source> <translation>Una commissione maggiore di %1 è considerata irragionevolmente elevata.</translation> </message> <message> <source>Payment request expired.</source> <translation>Richiesta di pagamento scaduta.</translation> </message> <message> <source>Pay only the required fee of %1</source> <translation>Paga solamente la commissione richiesta di %1</translation> </message> <message numerus="yes"> <source>Estimated to begin confirmation within %n block(s).</source> <translation><numerusform>Inizio delle conferme stimato entro %n blocco.</numerusform><numerusform>Inizio delle conferme stimato entro %n blocchi.</numerusform></translation> </message> <message> <source>The recipient address is not valid. Please recheck.</source> <translation>L'indirizzo del beneficiario non è valido. Si prega di ricontrollare.</translation> </message> <message> <source>Duplicate address found: addresses should only be used once each.</source> <translation>Rilevato un indirizzo duplicato Ciascun indirizzo dovrebbe essere utilizzato una sola volta.</translation> </message> <message> <source>Warning: Invalid Bitcoin address</source> <translation>Attenzione: Indirizzo Bitcoin non valido</translation> </message> <message> <source>(no label)</source> <translation>(nessuna etichetta)</translation> </message> <message> <source>Warning: Unknown change address</source> <translation>Attenzione: Indirizzo per il resto sconosciuto</translation> </message> <message> <source>Copy dust</source> <translation>Copia trascurabile</translation> </message> <message> <source>Are you sure you want to send?</source> <translation>Sei sicuro di voler inviare?</translation> </message> <message> <source>added as transaction fee</source> <translation>aggiunto come tassa di transazione</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <source>A&amp;mount:</source> <translation>&amp;Importo:</translation> </message> <message> <source>Pay &amp;To:</source> <translation>Paga &amp;a:</translation> </message> <message> <<<<<<< HEAD ======= <source>The address to send the payment to (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>L'indirizzo del beneficiario a cui inviare il pagamento (ad esempio 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> <message> >>>>>>> 5b9f78d69ccf189bebe894b1921e34417103a046 <source>Enter a label for this address to add it to your address book</source> <translation>Inserisci un'etichetta per questo indirizzo, per aggiungerlo alla rubrica</translation> </message> <message> <source>&amp;Label:</source> <translation>&amp;Etichetta:</translation> </message> <message> <source>Choose previously used address</source> <translation>Scegli un indirizzo usato precedentemente</translation> </message> <message> <source>This is a normal payment.</source> <translation>Questo è un normale pagamento.</translation> </message> <message> <source>The Bitcoin address to send the payment to</source> <translation>L'indirizzo Bitcoin a cui vuoi inviare il pagamento</translation> </message> <message> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <source>Paste address from clipboard</source> <translation>Incollare l'indirizzo dagli appunti</translation> </message> <message> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <source>Remove this entry</source> <translation>Rimuovi questa voce</translation> </message> <message> <source>The fee will be deducted from the amount being sent. The recipient will receive less bitcoins than you enter in the amount field. If multiple recipients are selected, the fee is split equally.</source> <translation>La commissione sarà sottratta dall'importo che si sta inviando. Il beneficiario riceverà un totale di bitcoin inferiore al valore digitato. Nel caso in cui siano stati selezionati più beneficiari la commissione sarà suddivisa in parti uguali.</translation> </message> <message> <source>S&amp;ubtract fee from amount</source> <translation>S&amp;ottrae la commissione dall'importo</translation> </message> <message> <source>Message:</source> <translation>Messaggio:</translation> </message> <message> <source>This is an unauthenticated payment request.</source> <translation>Questa è una richiesta di pagamento non autenticata.</translation> </message> <message> <source>This is an authenticated payment request.</source> <translation>Questa è una richiesta di pagamento autenticata.</translation> </message> <message> <source>Enter a label for this address to add it to the list of used addresses</source> <translation>Inserisci un'etichetta per questo indirizzo per aggiungerlo alla lista degli indirizzi utilizzati</translation> </message> <message> <source>A message that was attached to the bitcoin: URI which will be stored with the transaction for your reference. Note: This message will not be sent over the Bitcoin network.</source> <translation>Messaggio incluso nel bitcoin URI e che sarà memorizzato con la transazione per vostro riferimento. Nota: Questo messaggio non sarà inviato attraverso la rete Bitcoin.</translation> </message> <message> <source>Pay To:</source> <translation>Pagare a:</translation> </message> <message> <source>Memo:</source> <translation>Memo:</translation> </message> </context> <context> <name>ShutdownWindow</name> <message> <source>Bitcoin Core is shutting down...</source> <translation>Arresto di Bitcoin Core in corso...</translation> </message> <message> <source>Do not shut down the computer until this window disappears.</source> <translation>Non spegnere il computer fino a quando questa finestra non si sarà chiusa.</translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <source>Signatures - Sign / Verify a Message</source> <translation>Firme - Firma / Verifica un messaggio</translation> </message> <message> <source>&amp;Sign Message</source> <translation>&amp;Firma Messaggio</translation> </message> <message> <source>You can sign messages/agreements with your addresses to prove you can receive bitcoins sent to them. Be careful not to sign anything vague or random, 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>È possibile firmare messaggi/accordi con i propri indirizzi in modo da dimostrare di poter ricevere bitcoin attraverso di essi. Si consiglia di prestare attenzione a non firmare dichiarazioni vaghe o casuali, attacchi di phishing potrebbero cercare di indurre ad apporre la firma su di esse. Si raccomanda di firmare esclusivamente dichiarazioni completamente dettagliate e delle quali si condivide in pieno il contenuto.</translation> </message> <message> <<<<<<< HEAD <source>The Bitcoin address to sign the message with</source> <<<<<<< HEAD <translation>L'indirizzo Bitcoin con cui vuoi contrassegnare il messaggio</translation> ======= <source>The address to sign the message with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>L'indirizzo con cui firmare il messaggio (ad esempio 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> >>>>>>> 5b9f78d69ccf189bebe894b1921e34417103a046 ======= <translation>L'indirizzo Bitcoin da utilizzare per firmare il messaggio</translation> >>>>>>> 80d1f2e48364f05b2cdf44239b3a1faa0277e58e </message> <message> <source>Choose previously used address</source> <translation>Scegli un indirizzo usato precedentemente</translation> </message> <message> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <source>Paste address from clipboard</source> <translation>Incolla l'indirizzo dagli appunti</translation> </message> <message> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <source>Enter the message you want to sign here</source> <translation>Inserisci qui il messaggio che vuoi firmare</translation> </message> <message> <source>Signature</source> <translation>Firma</translation> </message> <message> <source>Copy the current signature to the system clipboard</source> <translation>Copia la firma corrente nella clipboard</translation> </message> <message> <source>Sign the message to prove you own this Bitcoin address</source> <translation>Firma un messaggio per dimostrare di possedere questo indirizzo Bitcoin</translation> </message> <message> <source>Sign &amp;Message</source> <translation>Firma &amp;Messaggio</translation> </message> <message> <source>Reset all sign message fields</source> <translation>Reimposta tutti i campi della firma messaggio</translation> </message> <message> <source>Clear &amp;All</source> <translation>Cancella &amp;Tutto</translation> </message> <message> <source>&amp;Verify Message</source> <translation>&amp;Verifica Messaggio</translation> </message> <message> <source>Enter the receiver's 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. Note that this only proves the signing party receives with the address, it cannot prove sendership of any transaction!</source> <translation>Per verificare il messaggio inserire l'indirizzo del firmatario, il messaggio e la firma nei campi sottostanti, assicurandosi di copiare esattamente anche ritorni a capo, spazi, tabulazioni, etc.. Si raccomanda di non lasciarsi fuorviare dalla firma a leggere più di quanto non sia riportato nel testo del messaggio stesso, in modo da evitare di cadere vittima di attacchi di tipo man-in-the-middle. Si ricorda che la verifica della firma dimostra soltanto che il firmatario può ricevere pagamenti con l'indirizzo corrispondente, non prova l'invio di alcuna transazione.</translation> </message> <message> <<<<<<< HEAD <source>The Bitcoin address the message was signed with</source> <translation>L'indirizzo Bitcoin con cui è stato contrassegnato il messaggio</translation> ======= <source>The address the message was signed with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>L'indirizzo con cui è stato firmato il messaggio (ad esempio 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> >>>>>>> 5b9f78d69ccf189bebe894b1921e34417103a046 </message> <message> <source>Verify the message to ensure it was signed with the specified Bitcoin address</source> <translation>Verifica il messaggio per accertare che sia stato firmato con l'indirizzo specificato</translation> </message> <message> <source>Verify &amp;Message</source> <translation>Verifica &amp;Messaggio</translation> </message> <message> <source>Reset all verify message fields</source> <translation>Reimposta tutti i campi della verifica messaggio</translation> </message> <message> <<<<<<< HEAD ======= <source>Enter a Bitcoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>Inserisci un indirizzo Bitcoin (ad esempio 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> <message> >>>>>>> 5b9f78d69ccf189bebe894b1921e34417103a046 <source>Click "Sign Message" to generate signature</source> <translation>Clicca "Firma il messaggio" per ottenere la firma</translation> </message> <message> <source>The entered address is invalid.</source> <translation>L'indirizzo inserito non è valido.</translation> </message> <message> <source>Please check the address and try again.</source> <translation>Per favore controlla l'indirizzo e prova di nuovo.</translation> </message> <message> <source>The entered address does not refer to a key.</source> <translation>L'indirizzo bitcoin inserito non è associato a nessuna chiave.</translation> </message> <message> <source>Wallet unlock was cancelled.</source> <translation>Sblocco del portamonete annullato.</translation> </message> <message> <source>Private key for the entered address is not available.</source> <translation>La chiave privata per l'indirizzo inserito non è disponibile.</translation> </message> <message> <source>Message signing failed.</source> <translation>Firma messaggio fallita.</translation> </message> <message> <source>Message signed.</source> <translation>Messaggio firmato.</translation> </message> <message> <source>The signature could not be decoded.</source> <translation>Non è stato possibile decodificare la firma.</translation> </message> <message> <source>Please check the signature and try again.</source> <translation>Per favore controlla la firma e prova di nuovo.</translation> </message> <message> <source>The signature did not match the message digest.</source> <translation>La firma non corrisponde al digest del messaggio.</translation> </message> <message> <source>Message verification failed.</source> <translation>Verifica messaggio fallita.</translation> </message> <message> <source>Message verified.</source> <translation>Messaggio verificato.</translation> </message> </context> <context> <name>SplashScreen</name> <message> <source>Bitcoin Core</source> <translation>Bitcoin Core</translation> </message> <message> <source>The Bitcoin Core developers</source> <translation>Gli sviluppatori di Bitcoin Core</translation> </message> <message> <source>[testnet]</source> <translation>[testnet]</translation> </message> </context> <context> <name>TrafficGraphWidget</name> <message> <source>KB/s</source> <translation>KB/s</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <source>Open until %1</source> <translation>Aperto fino a %1</translation> </message> <message> <source>conflicted</source> <translation>in conflitto</translation> </message> <message> <source>%1/offline</source> <translation>%1/offline</translation> </message> <message> <source>%1/unconfirmed</source> <translation>%1/non confermata</translation> </message> <message> <source>%1 confirmations</source> <translation>%1 conferme</translation> </message> <message> <source>Status</source> <translation>Stato</translation> </message> <message numerus="yes"> <source>, broadcast through %n node(s)</source> <translation><numerusform>, trasmesso attraverso %n nodo</numerusform><numerusform>, trasmessa attraverso %n nodi</numerusform></translation> </message> <message> <source>Date</source> <translation>Data</translation> </message> <message> <source>Source</source> <translation>Sorgente</translation> </message> <message> <source>Generated</source> <translation>Generato</translation> </message> <message> <source>From</source> <translation>Da</translation> </message> <message> <source>To</source> <translation>A</translation> </message> <message> <source>own address</source> <translation>proprio indirizzo</translation> </message> <message> <source>watch-only</source> <translation>sola lettura</translation> </message> <message> <source>label</source> <translation>etichetta</translation> </message> <message> <source>Credit</source> <translation>Credito</translation> </message> <message numerus="yes"> <source>matures in %n more block(s)</source> <translation><numerusform>matura tra %n blocco</numerusform><numerusform>matura tra %n blocchi</numerusform></translation> </message> <message> <source>not accepted</source> <translation>non accettate</translation> </message> <message> <source>Debit</source> <translation>Debito</translation> </message> <message> <source>Total debit</source> <translation>Debito totale</translation> </message> <message> <source>Total credit</source> <translation>Credito totale</translation> </message> <message> <source>Transaction fee</source> <translation>Commissione transazione</translation> </message> <message> <source>Net amount</source> <translation>Importo netto</translation> </message> <message> <source>Message</source> <translation>Messaggio</translation> </message> <message> <source>Comment</source> <translation>Commento</translation> </message> <message> <source>Transaction ID</source> <translation>ID della transazione</translation> </message> <message> <source>Merchant</source> <translation>Commerciante</translation> </message> <message> <source>Generated coins must mature %1 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>È necessario attendere %1 blocchi prima che i bitcoin generati possano essere spesi. Al momento della generazione questo blocco è stato trasmesso alla rete in modo da poter essere aggiunto alla block chain. Se l'inserimento avrà esito negativo lo stato del blocco sarà modificato in "non accettato" ed esso risulterà non spendibile. Ciò può verificarsi occasionalmente nel caso in cui un altro blocco sia stato generato entro pochi secondi dal tuo.</translation> </message> <message> <source>Debug information</source> <translation>Informazione di debug</translation> </message> <message> <source>Transaction</source> <translation>Transazione</translation> </message> <message> <source>Inputs</source> <translation>Input</translation> </message> <message> <source>Amount</source> <translation>Importo</translation> </message> <message> <source>true</source> <translation>vero</translation> </message> <message> <source>false</source> <translation>falso</translation> </message> <message> <source>, has not been successfully broadcast yet</source> <translation>, non è ancora stata trasmessa con successo</translation> </message> <message numerus="yes"> <source>Open for %n more block(s)</source> <translation><numerusform>Aperto per %n altro blocco</numerusform><numerusform>Aperto per altri %n blocchi</numerusform></translation> </message> <message> <source>unknown</source> <translation>sconosciuto</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <source>Transaction details</source> <translation>Dettagli sulla transazione</translation> </message> <message> <source>This pane shows a detailed description of the transaction</source> <translation>Questo pannello mostra una descrizione dettagliata della transazione</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <source>Date</source> <translation>Data</translation> </message> <message> <source>Type</source> <translation>Tipo</translation> </message> <message> <source>Immature (%1 confirmations, will be available after %2)</source> <translation>Immaturo (%1 conferme, sarà disponibile fra %2)</translation> </message> <message numerus="yes"> <source>Open for %n more block(s)</source> <translation><numerusform>Aperto per %n altro blocco</numerusform><numerusform>Aperto per altri %n blocchi</numerusform></translation> </message> <message> <source>Open until %1</source> <translation>Aperto fino a %1</translation> </message> <message> <source>Confirmed (%1 confirmations)</source> <translation>Confermata (%1 conferme)</translation> </message> <message> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>Questo blocco non è stato ricevuto da alcun altro nodo e probabilmente non sarà accettato!</translation> </message> <message> <source>Generated but not accepted</source> <translation>Generati, ma non accettati</translation> </message> <message> <source>Offline</source> <translation>Offline</translation> </message> <message> <source>Label</source> <translation>Etichetta</translation> </message> <message> <source>Unconfirmed</source> <translation>Non confermata</translation> </message> <message> <source>Confirming (%1 of %2 recommended confirmations)</source> <translation>In conferma (%1 di %2 conferme raccomandate)</translation> </message> <message> <source>Conflicted</source> <translation>In conflitto</translation> </message> <message> <source>Received with</source> <translation>Ricevuto tramite</translation> </message> <message> <source>Received from</source> <translation>Ricevuto da</translation> </message> <message> <source>Sent to</source> <translation>Inviato a</translation> </message> <message> <source>Payment to yourself</source> <translation>Pagamento a te stesso</translation> </message> <message> <source>Mined</source> <translation>Ottenuto dal mining</translation> </message> <message> <source>watch-only</source> <translation>sola lettura</translation> </message> <message> <source>(n/a)</source> <translation>(n/d)</translation> </message> <message> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Stato della transazione. Passare con il mouse su questo campo per visualizzare il numero di conferme.</translation> </message> <message> <source>Date and time that the transaction was received.</source> <translation>Data e ora in cui la transazione è stata ricevuta.</translation> </message> <message> <source>Type of transaction.</source> <translation>Tipo di transazione.</translation> </message> <message> <source>Whether or not a watch-only address is involved in this transaction.</source> <translation>Indica se un indirizzo di sola lettura sia o meno coinvolto in questa transazione.</translation> </message> <message> <source>User-defined intent/purpose of the transaction.</source> <translation>Intento/scopo della transazione definito dall'utente.</translation> </message> <message> <source>Amount removed from or added to balance.</source> <translation>Importo rimosso o aggiunto al saldo.</translation> </message> </context> <context> <name>TransactionView</name> <message> <source>All</source> <translation>Tutti</translation> </message> <message> <source>Today</source> <translation>Oggi</translation> </message> <message> <source>This week</source> <translation>Questa settimana</translation> </message> <message> <source>This month</source> <translation>Questo mese</translation> </message> <message> <source>Last month</source> <translation>Il mese scorso</translation> </message> <message> <source>This year</source> <translation>Quest'anno</translation> </message> <message> <source>Range...</source> <translation>Intervallo...</translation> </message> <message> <source>Received with</source> <translation>Ricevuto tramite</translation> </message> <message> <source>Sent to</source> <translation>Inviato a</translation> </message> <message> <source>To yourself</source> <translation>A te stesso</translation> </message> <message> <source>Mined</source> <translation>Ottenuto dal mining</translation> </message> <message> <source>Other</source> <translation>Altro</translation> </message> <message> <source>Enter address or label to search</source> <translation>Inserisci un indirizzo o un'etichetta da cercare</translation> </message> <message> <source>Min amount</source> <translation>Importo minimo</translation> </message> <message> <source>Copy address</source> <translation>Copia l'indirizzo</translation> </message> <message> <source>Copy label</source> <translation>Copia l'etichetta</translation> </message> <message> <source>Copy amount</source> <translation>Copia l'importo</translation> </message> <message> <source>Copy transaction ID</source> <translation>Copia l'ID transazione</translation> </message> <message> <source>Copy raw transaction</source> <translation>Copia la transazione raw</translation> </message> <message> <source>Edit label</source> <translation>Modifica l'etichetta</translation> </message> <message> <source>Show transaction details</source> <translation>Mostra i dettagli della transazione</translation> </message> <message> <source>Export Transaction History</source> <translation>Esporta lo storico delle transazioni</translation> </message> <message> <source>Watch-only</source> <translation>Sola lettura</translation> </message> <message> <source>Exporting Failed</source> <translation>Esportazione Fallita.</translation> </message> <message> <source>There was an error trying to save the transaction history to %1.</source> <translation>Si è verificato un errore durante il salvataggio dello storico delle transazioni in %1.</translation> </message> <message> <source>Exporting Successful</source> <translation>Esportazione Riuscita</translation> </message> <message> <source>The transaction history was successfully saved to %1.</source> <translation>Lo storico delle transazioni e' stato salvato con successo in %1.</translation> </message> <message> <source>Comma separated file (*.csv)</source> <translation>Testo CSV (*.csv)</translation> </message> <message> <source>Confirmed</source> <translation>Confermato</translation> </message> <message> <source>Date</source> <translation>Data</translation> </message> <message> <source>Type</source> <translation>Tipo</translation> </message> <message> <source>Label</source> <translation>Etichetta</translation> </message> <message> <source>Address</source> <translation>Indirizzo</translation> </message> <message> <source>ID</source> <translation>ID</translation> </message> <message> <source>Range:</source> <translation>Intervallo:</translation> </message> <message> <source>to</source> <translation>a</translation> </message> </context> <context> <name>UnitDisplayStatusBarControl</name> <message> <source>Unit to show amounts in. Click to select another unit.</source> <translation>Unità con cui visualizzare gli importi. Clicca per selezionare un altra unità.</translation> </message> </context> <context> <name>WalletFrame</name> <message> <source>No wallet has been loaded.</source> <translation>Non è stato caricato alcun portamonete.</translation> </message> </context> <context> <name>WalletModel</name> <message> <source>Send Coins</source> <translation>Invia Bitcoin</translation> </message> </context> <context> <name>WalletView</name> <message> <source>&amp;Export</source> <translation>&amp;Esporta</translation> </message> <message> <source>Export the data in the current tab to a file</source> <translation>Esporta su file i dati contenuti nella tabella corrente</translation> </message> <message> <source>Backup Wallet</source> <translation>Backup Portamonete</translation> </message> <message> <source>Wallet Data (*.dat)</source> <translation>Dati Portamonete (*.dat)</translation> </message> <message> <source>Backup Failed</source> <translation>Backup Fallito</translation> </message> <message> <source>There was an error trying to save the wallet data to %1.</source> <translation>Si è verificato un errore durante il salvataggio dei dati del portamonete in %1.</translation> </message> <message> <source>The wallet data was successfully saved to %1.</source> <translation>Il portamonete è stato correttamente salvato in %1.</translation> </message> <message> <source>Backup Successful</source> <translation>Backup eseguito con successo</translation> </message> </context> <context> <name>bitcoin-core</name> <message> <source>Options:</source> <translation>Opzioni:</translation> </message> <message> <source>Specify data directory</source> <translation>Specifica la cartella dati</translation> </message> <message> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation>Connessione ad un nodo e successiva disconnessione per recuperare gli indirizzi dei peer</translation> </message> <message> <source>Specify your own public address</source> <translation>Specifica il tuo indirizzo pubblico</translation> </message> <message> <<<<<<< HEAD ======= <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>Soglia di disconnessione dei peer di cattiva qualità (predefinita: 100)</translation> </message> <message> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>Numero di secondi di sospensione che i peer di cattiva qualità devono attendere prima di potersi riconnettere (predefiniti: 86400)</translation> </message> <message> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation>Errore riscontrato durante l'impostazione della porta RPC %u per l'ascolto su IPv4: %s</translation> </message> <message> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 8332 or testnet: 18332)</source> <translation>Attendi le connessioni JSON-RPC su &lt;porta&gt; (predefinita: 8332 or testnet: 18332)</translation> </message> <message> >>>>>>> 5b9f78d69ccf189bebe894b1921e34417103a046 <source>Accept command line and JSON-RPC commands</source> <translation>Accetta comandi da riga di comando e JSON-RPC</translation> </message> <message> <source>If &lt;category&gt; is not supplied or if &lt;category&gt; = 1, output all debugging information.</source> <translation>Se &lt;category&gt; non è specificato oppure se &lt;category&gt; = 1, mostra tutte le informazioni di debug.</translation> </message> <message> <source>Maximum total fees (in %s) to use in a single wallet transaction; setting this too low may abort large transactions (default: %s)</source> <translation>Totale massimo di commissioni (in %s) da usare in una singola transazione del wallet; valori troppo bassi possono abortire grandi transazioni (default: %s)</translation> </message> <message> <source>Please check that your computer's date and time are correct! If your clock is wrong Bitcoin Core will not work properly.</source> <translation>Per favore controllate che la data del computer e l'ora siano corrette. Se il vostro orologio è sbagliato Bitcoin non funzionerà correttamente.</translation> </message> <message> <<<<<<< HEAD <<<<<<< HEAD <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation>Associa all'indirizzo indicato e resta permanentemente in ascolto su questo. Usa la notazione [host]:porta per l'IPv6</translation> ======= <source>Acceptable ciphers (default: TLSv1.2+HIGH:TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH)</source> <translation>Cifrature accettabili (predefinito: TLSv1.2+HIGH:TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH)</translation> </message> <message> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation>Errore riscontrato durante l'impostazione della porta RPC %u per l'ascolto su IPv6, tornando su IPv4: %s</translation> </message> <message> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation>Associa all'indirizzo indicato e resta permanentemente in ascolto su questo. Usa la notazione [host]:porta per l'IPv6</translation> </message> <message> <source>Continuously rate-limit free transactions to &lt;n&gt;*1000 bytes per minute (default:15)</source> <translation>Limita la quantità di transazioni gratuite ad &lt;n&gt;*1000 byte al minuto (predefinito: 15)</translation> >>>>>>> 5b9f78d69ccf189bebe894b1921e34417103a046 ======= <source>Prune configured below the minimum of %d MiB. Please use a higher number.</source> <translation>La modalità prune è configurata al di sotto del minimo di %d MB. Si prega di utilizzare un valore più elevato.</translation> >>>>>>> 80d1f2e48364f05b2cdf44239b3a1faa0277e58e </message> <message> <source>Prune: last wallet synchronisation goes beyond pruned data. You need to -reindex (download the whole blockchain again in case of pruned node)</source> <translation>Prune: l'ultima sincronizzazione del wallet risulta essere oltre la riduzione dei dati. È necessario eseguire un -reindex (scaricare nuovamente la blockchain in caso di nodo pruned)</translation> </message> <message> <source>Reduce storage requirements by pruning (deleting) old blocks. This mode is incompatible with -txindex and -rescan. Warning: Reverting this setting requires re-downloading the entire blockchain. (default: 0 = disable pruning blocks, &gt;%u = target size in MiB to use for block files)</source> <translation>Riduce i requisiti di spazio di archiviazione attraverso la rimozione dei vecchi blocchi (pruning). Questa modalità è incompatibile con l'opzione -txindex e -rescan. Attenzione: ripristinando questa opzione l'intera blockchain dovrà essere riscaricata. (default: 0 = disabilita il pruning, &gt;%u = dimensione desiderata in MiB per i file dei blocchi)</translation> </message> <message> <<<<<<< HEAD <<<<<<< HEAD ======= <source>Error: Listening for incoming connections failed (listen returned error %d)</source> <translation>Errore: l'ascolto per le connessioni in ingresso non è riuscito (errore riportato %d) </translation> </message> <message> >>>>>>> 5b9f78d69ccf189bebe894b1921e34417103a046 <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>Errore: la transazione è stata rifiutata! Questo può accadere se alcuni bitcoin nel tuo portamonete sono già stati spesi, ad esempio se hai utilizzato una copia del file wallet.dat per spendere bitcoin e questi non sono stati considerati spesi dal portamonete corrente.</translation> ======= <source>Rescans are not possible in pruned mode. You will need to use -reindex which will download the whole blockchain again.</source> <translation>Non è possibile un Rescan in modalità pruned. Sarà necessario utilizzare -reindex che farà scaricare nuovamente tutta la blockchain.</translation> >>>>>>> 80d1f2e48364f05b2cdf44239b3a1faa0277e58e </message> <message> <source>Error: A fatal internal error occurred, see debug.log for details</source> <translation>Errore: si è presentato un errore interno fatale, consulta il file debug.log per maggiori dettagli</translation> </message> <message> <source>Fee (in %s/kB) to add to transactions you send (default: %s)</source> <translation>Commissione (in %s/kB) da aggiungere alle transazioni inviate (default: %s)</translation> </message> <message> <<<<<<< HEAD <<<<<<< HEAD ======= <source>Fees smaller than this are considered zero fee (for transaction creation) (default:</source> <translation>Le commissioni inferiori a questo valore saranno considerate nulle (per la creazione della transazione) (prefedinito:</translation> </message> <message> <source>Flush database activity from memory pool to disk log every &lt;n&gt; megabytes (default: 100)</source> <translation>Scarica l'attività del database dalla memoria al log su disco ogni &lt;n&gt; megabytes (predefinito: 100)</translation> </message> <message> <source>How thorough the block verification of -checkblocks is (0-4, default: 3)</source> <translation>Determina quanto sarà approfondita la verifica da parte di -checkblocks (0-4, predefinito: 3)</translation> </message> <message> >>>>>>> 5b9f78d69ccf189bebe894b1921e34417103a046 <source>In this mode -genproclimit controls how many blocks are generated immediately.</source> <translation>In questa modalità -genproclimit determina quanti blocchi saranno generati immediatamente.</translation> ======= <source>Pruning blockstore...</source> <translation>Pruning del blockstore...</translation> </message> <message> <source>Run in the background as a daemon and accept commands</source> <translation>Esegui in background come demone ed accetta i comandi</translation> </message> <message> <source>Unable to start HTTP server. See debug log for details.</source> <translation>Impossibile avviare il server HTTP. Dettagli nel log di debug.</translation> </message> <message> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation>Accetta connessioni dall'esterno (predefinito: 1 se -proxy o -connect non sono utilizzati)</translation> </message> <message> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation>Associa all'indirizzo indicato e resta permanentemente in ascolto su di esso. Usa la notazione [host]:porta per l'IPv6</translation> </message> <message> <source>Delete all wallet transactions and only recover those parts of the blockchain through -rescan on startup</source> <translation>Elimina tutte le transazioni dal portamonete e recupera solo quelle che fanno parte della blockchain attraverso il comando -rescan all'avvio.</translation> </message> <message> <source>Distributed under the MIT software license, see the accompanying file COPYING or &lt;http://www.opensource.org/licenses/mit-license.php&gt;.</source> <translation>Distribuito secondo la licenza software MIT, vedi il file COPYING incluso oppure &lt;http://www.opensource.org/licenses/mit-license.php&gt;.</translation> </message> <message> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation>Esegue un comando quando lo stato di una transazione del portamonete cambia (%s in cmd è sostituito da TxID)</translation> >>>>>>> 80d1f2e48364f05b2cdf44239b3a1faa0277e58e </message> <message> <source>Set the number of script verification threads (%u to %d, 0 = auto, &lt;0 = leave that many cores free, default: %d)</source> <translation>Imposta il numero di thread per la verifica degli script (da %u a %d, 0 = automatico, &lt;0 = lascia questo numero di core liberi, predefinito: %d)</translation> </message> <message> <source>The block database contains a block which appears to be from the future. This may be due to your computer's date and time being set incorrectly. Only rebuild the block database if you are sure that your computer's date and time are correct</source> <translation>Il database dei blocchi contiene un blocco che sembra provenire dal futuro. Questo può essere dovuto alla data e ora del tuo computer impostate in modo scorretto. Ricostruisci il database dei blocchi se sei certo che la data e l'ora sul tuo computer siano corrette</translation> </message> <message> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation>Questa versione è una compilazione pre-rilascio - usala a tuo rischio - non utilizzarla per la generazione o per applicazioni di commercio</translation> </message> <message> <source>Unable to bind to %s on this computer. Bitcoin Core is probably already running.</source> <translation>Impossibile associarsi a %s su questo computer. Probabilmente Bitcoin Core è già in esecuzione.</translation> </message> <message> <source>Use UPnP to map the listening port (default: 1 when listening and no -proxy)</source> <translation>Utilizza UPnP per mappare la porta in ascolto (default: 1 quando in ascolto e -proxy non è specificato)</translation> </message> <message> <<<<<<< HEAD <<<<<<< HEAD ======= <source>Warning: Please check that your computer's date and time are correct! If your clock is wrong Bitcoin will not work properly.</source> <translation>Attenzione: si prega di controllare che la data e l'ora del computer siano corrette. Se l'ora di sistema è errata Bitcoin non funzionerà correttamente.</translation> </message> <message> >>>>>>> 5b9f78d69ccf189bebe894b1921e34417103a046 <source>Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.</source> <translation>Attenzione: La rete non sembra essere d'accordo pienamente! Alcuni minatori sembrano riscontrare problemi.</translation> ======= <source>WARNING: abnormally high number of blocks generated, %d blocks received in the last %d hours (%d expected)</source> <translation>ATTENZIONE, il numero di blocchi generati è insolitamente elevato: %d blocchi ricevuti nelle ultime %d ore (%d previsti)</translation> >>>>>>> 80d1f2e48364f05b2cdf44239b3a1faa0277e58e </message> <message> <source>WARNING: check your network connection, %d blocks received in the last %d hours (%d expected)</source> <translation>ATTENZIONE, si consiglia di verificare la connessione di rete: %d blocchi ricevuti nelle ultime %d ore (%d previsti)</translation> </message> <message> <source>Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.</source> <translation>Attenzione: La rete non sembra trovarsi in pieno consenso! Alcuni minatori sembrano riscontrare problemi.</translation> </message> <message> <source>Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade.</source> <translation>Attenzione: Sembra che non vi sia pieno consenso con i nostri peer! Un aggiornamento da parte tua o degli altri nodi potrebbe essere necessario.</translation> </message> <message> <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>Attenzione: wallet.dat corrotto, dati recuperati! Il wallet.dat originale è stato salvato come wallet.{timestamp}.bak in %s. Se i dati relativi a saldo o transazioni non dovessero risultare corretti si consiglia di procedere al ripristino da un backup.</translation> </message> <message> <source>Whitelist peers connecting from the given netmask or IP address. Can be specified multiple times.</source> <translation>Inserisce in whitelist i peer che si connettono da un dato indirizzo IP o netmask. Può essere specificato più volte.</translation> </message> <message> <source>-maxmempool must be at least %d MB</source> <translation>-maxmempool deve essere almeno %d MB</translation> </message> <message> <source>&lt;category&gt; can be:</source> <translation>Valori possibili per &lt;category&gt;:</translation> </message> <message> <source>Block creation options:</source> <translation>Opzioni creazione blocco:</translation> </message> <message> <source>Connect only to the specified node(s)</source> <translation>Connessione ai soli nodi specificati</translation> </message> <message> <source>Connection options:</source> <translation>Opzioni di connessione:</translation> </message> <message> <source>Corrupted block database detected</source> <translation>Rilevato database blocchi corrotto</translation> </message> <message> <source>Debugging/Testing options:</source> <translation>Opzioni di Debug/Test:</translation> </message> <message> <source>Do not load the wallet and disable wallet RPC calls</source> <translation>Disabilita il portamonete e le relative chiamate RPC</translation> </message> <message> <source>Do you want to rebuild the block database now?</source> <translation>Vuoi ricostruire ora il database dei blocchi?</translation> </message> <message> <source>Enable publish hash block in &lt;address&gt;</source> <translation>Abilita pubblicazione hash blocco in &lt;address&gt;</translation> </message> <message> <source>Enable publish hash transaction in &lt;address&gt;</source> <translation>Abilità pubblicazione hash transazione in &lt;address&gt;</translation> </message> <message> <source>Enable publish raw block in &lt;address&gt;</source> <translation>Abilita pubblicazione blocchi raw in &lt;address&gt;</translation> </message> <message> <source>Enable publish raw transaction in &lt;address&gt;</source> <translation>Abilita pubblicazione transazione raw in &lt;address&gt;</translation> </message> <message> <source>Error initializing block database</source> <translation>Errore durante l'inizializzazione del database dei blocchi</translation> </message> <message> <source>Error initializing wallet database environment %s!</source> <translation>Errore durante l'inizializzazione dell'ambiente del database del portamonete %s!</translation> </message> <message> <source>Error loading block database</source> <translation>Errore durante il caricamento del database blocchi</translation> </message> <message> <source>Error opening block database</source> <translation>Errore durante l'apertura del database blocchi</translation> </message> <message> <source>Error: Disk space is low!</source> <translation>Errore: la spazio libero sul disco è insufficiente!</translation> </message> <message> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation>Nessuna porta disponibile per l'ascolto. Usa -listen=0 se vuoi procedere comunque.</translation> <<<<<<< HEAD ======= </message> <message> <source>Failed to read block info</source> <translation>Lettura informazioni blocco fallita</translation> </message> <message> <source>Failed to read block</source> <translation>Lettura blocco fallita</translation> </message> <message> <source>Failed to sync block index</source> <translation>Sincronizzazione dell'indice del blocco fallita</translation> </message> <message> <source>Failed to write block index</source> <translation>Scrittura dell'indice del blocco fallita</translation> </message> <message> <source>Failed to write block info</source> <translation>Scrittura informazioni blocco fallita</translation> </message> <message> <source>Failed to write block</source> <translation>Scrittura blocco fallita</translation> </message> <message> <source>Failed to write file info</source> <translation>Scrittura informazioni file fallita</translation> </message> <message> <source>Failed to write to coin database</source> <translation>Scrittura nel database dei bitcoin fallita</translation> </message> <message> <source>Failed to write transaction index</source> <translation>Scrittura dell'indice di transazione fallita</translation> </message> <message> <source>Failed to write undo data</source> <translation>Scrittura dei dati di ripristino fallita</translation> </message> <message> <source>Fee per kB to add to transactions you send</source> <translation>Commissione per kB da aggiungere alle transazioni in uscita</translation> </message> <message> <source>Fees smaller than this are considered zero fee (for relaying) (default:</source> <translation>Le commissioni inferiori a questo valore saranno considerate nulle (per la trasmissione) (prefedinito:</translation> </message> <message> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation>Trova peer utilizzando la ricerca DNS (predefinito: 1 a meno che non si usi -connect)</translation> </message> <message> <source>Force safe mode (default: 0)</source> <translation>Forza modalità provvisoria (predefinito: 0)</translation> </message> <message> <source>Generate coins (default: 0)</source> <translation>Genera Bitcoin (predefinito: 0)</translation> </message> <message> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation>Numero di blocchi da controllare all'avvio (predefinito: 288, 0 = tutti)</translation> >>>>>>> 5b9f78d69ccf189bebe894b1921e34417103a046 </message> <message> <source>Importing...</source> <translation>Importazione...</translation> </message> <message> <source>Incorrect or no genesis block found. Wrong datadir for network?</source> <translation>Blocco genesi non corretto o non trovato. È possibile che la cartella dati appartenga ad un'altra rete.</translation> </message> <message> <source>Invalid -onion address: '%s'</source> <translation>Indirizzo -onion non valido: '%s'</translation> </message> <message> <source>Keep the transaction memory pool below &lt;n&gt; megabytes (default: %u)</source> <translation>Mantieni la memory pool delle transazioni al di sotto di &lt;n&gt; megabytes (default: %u)</translation> </message> <message> <source>Not enough file descriptors available.</source> <translation>Non ci sono abbastanza descrittori di file disponibili.</translation> </message> <message> <<<<<<< HEAD <source>Only connect to nodes in network &lt;net&gt; (ipv4, ipv6 or onion)</source> <<<<<<< HEAD <translation>Connetti solo ai nodi nella rete &lt;net&gt; (ipv4, ipv6 o Tor)</translation> ======= <source>Prepend debug output with timestamp (default: 1)</source> <translation>Preponi timestamp all'output di debug (predefinito: 1)</translation> </message> <message> <source>RPC client options:</source> <translation>Opzioni client RPC:</translation> >>>>>>> 5b9f78d69ccf189bebe894b1921e34417103a046 </message> <message> <source>Rebuild block chain index from current blk000??.dat files</source> <translation>Ricreare l'indice della catena di blocchi dai file blk000??.dat correnti</translation> <<<<<<< HEAD ======= </message> <message> <source>Select SOCKS version for -proxy (4 or 5, default: 5)</source> <translation>Selezionare la versione SOCKS per -proxy (4 o 5, predefinito: 5)</translation> >>>>>>> 5b9f78d69ccf189bebe894b1921e34417103a046 ======= <translation>Connessione ai soli nodi appartenenti alla rete &lt;net&gt; (ipv4, ipv6 o Tor)</translation> </message> <message> <source>Prune cannot be configured with a negative value.</source> <translation>La modalità prune non può essere configurata con un valore negativo.</translation> </message> <message> <source>Prune mode is incompatible with -txindex.</source> <translation>La modalità prune è incompatibile con l'opzione -txindex.</translation> >>>>>>> 80d1f2e48364f05b2cdf44239b3a1faa0277e58e </message> <message> <source>Set database cache size in megabytes (%d to %d, default: %d)</source> <translation>Imposta la dimensione della cache del database in megabyte (%d a %d, predefinito: %d)</translation> </message> <message> <source>Set maximum block size in bytes (default: %d)</source> <translation>Imposta la dimensione massima del blocco in byte (predefinito: %d)</translation> </message> <message> <source>Specify wallet file (within data directory)</source> <<<<<<< HEAD <translation>Specifica il file portamonete (all'interno della cartella dati)</translation> <<<<<<< HEAD ======= </message> <message> <source>Spend unconfirmed change when sending transactions (default: 1)</source> <translation>Spendi il resto non confermato quando si inviano transazioni (predefinito: 1)</translation> >>>>>>> 5b9f78d69ccf189bebe894b1921e34417103a046 </message> <message> <source>This is intended for regression testing tools and app development.</source> <translation>Questo è previsto per l'uso con test di regressione e per lo sviluppo di applicazioni.</translation> <<<<<<< HEAD ======= </message> <message> <source>Usage (deprecated, use bitcoin-cli):</source> <translation>Usage (deprecato, usare bitcoin-cli):</translation> >>>>>>> 5b9f78d69ccf189bebe894b1921e34417103a046 ======= <translation>Specifica il file del portamonete (all'interno della cartella dati)</translation> </message> <message> <source>Unsupported argument -benchmark ignored, use -debug=bench.</source> <translation>Ignorata opzione -benchmark non supportata, utilizzare -debug=bench.</translation> </message> <message> <source>Unsupported argument -debugnet ignored, use -debug=net.</source> <translation>Argomento -debugnet ignorato in quanto non supportato, usare -debug=net.</translation> </message> <message> <source>Unsupported argument -tor found, use -onion.</source> <translation>Rilevato argomento -tor non supportato, utilizzare -onion.</translation> </message> <message> <source>Use UPnP to map the listening port (default: %u)</source> <translation>Usa UPnP per mappare la porta di ascolto (predefinito: %u)</translation> </message> <message> <source>User Agent comment (%s) contains unsafe characters.</source> <translation>Il commento del User Agent (%s) contiene caratteri non sicuri.</translation> >>>>>>> 80d1f2e48364f05b2cdf44239b3a1faa0277e58e </message> <message> <source>Verifying blocks...</source> <translation>Verifica blocchi...</translation> </message> <message> <source>Verifying wallet...</source> <translation>Verifica portamonete...</translation> </message> <message> <<<<<<< HEAD ======= <source>Wait for RPC server to start</source> <translation>Attendere l'avvio dell'RPC server</translation> </message> <message> >>>>>>> 5b9f78d69ccf189bebe894b1921e34417103a046 <source>Wallet %s resides outside data directory %s</source> <translation>Il portamonete %s si trova al di fuori dalla cartella dati %s</translation> </message> <message> <source>Wallet options:</source> <translation>Opzioni portamonete:</translation> </message> <message> <source>Warning: This version is obsolete; upgrade required!</source> <translation>Attenzione: questa versione è obsoleta. Aggiornamento necessario!</translation> </message> <message> <source>You need to rebuild the database using -reindex to change -txindex</source> <translation>È necessario ricostruire il database usando -reindex per cambiare -txindex</translation> </message> <message> <source>Allow JSON-RPC connections from specified source. Valid for &lt;ip&gt; are a single IP (e.g. 1.2.3.4), a network/netmask (e.g. 1.2.3.4/255.255.255.0) or a network/CIDR (e.g. 1.2.3.4/24). This option can be specified multiple times</source> <translation>Permette connessioni JSON-RPC dall'origine specificata. I valori validi per &lt;ip&gt; sono un singolo IP (ad es. 1.2.3.4), una network/netmask (ad es. 1.2.3.4/255.255.255.0) oppure una network/CIDR (ad es. 1.2.3.4/24). Questa opzione può essere specificata più volte.</translation> </message> <message> <source>Bind to given address and whitelist peers connecting to it. Use [host]:port notation for IPv6</source> <translation>Resta in ascolto sull'indirizzo indicato ed inserisce in whitelist i peer che vi si collegano. Usa la notazione [host]:porta per l'IPv6</translation> </message> <message> <source>Bind to given address to listen for JSON-RPC connections. Use [host]:port notation for IPv6. This option can be specified multiple times (default: bind to all interfaces)</source> <translation>Resta in attesa di connessioni JSON-RPC sull'indirizzo indicato. Usa la notazione [host]:porta per IPv6. Questa opzione può essere specificata più volte (predefinito: associa a tutte le interfacce) </translation> </message> <message> <source>Cannot obtain a lock on data directory %s. Bitcoin Core is probably already running.</source> <translation>Non è possibile ottenere un lock sulla cartella %s. Probabilmente Bitcoin Core è già in esecuzione.</translation> </message> <message> <source>Create new files with system default permissions, instead of umask 077 (only effective with disabled wallet functionality)</source> <translation>Crea nuovi file con i permessi di default del sistema, invece che con umask 077 (ha effetto solo con funzionalità di portamonete disabilitate)</translation> </message> <message> <source>Discover own IP addresses (default: 1 when listening and no -externalip or -proxy)</source> <translation>Scopre i propri indirizzi IP (predefinito: 1 se in ascolto ed -externalip o -proxy non sono specificati)</translation> </message> <message> <source>Error: Listening for incoming connections failed (listen returned error %s)</source> <translation>Errore: attesa per connessioni in arrivo fallita (errore riportato %s)</translation> </message> <message> <source>Execute command when a relevant alert is received or we see a really long fork (%s in cmd is replaced by message)</source> <translation>Esegue un comando in caso di ricezione di un allarme pertinente o se si rileva un fork molto lungo (%s in cmd è sostituito dal messaggio)</translation> </message> <message> <source>Fees (in %s/kB) smaller than this are considered zero fee for relaying, mining and transaction creation (default: %s)</source> <translation>Le commissioni (in %s/kB) inferiori a questo valore sono considerate pari a zero per trasmissione, mining e creazione della transazione (default: %s)</translation> </message> <message> <source>If paytxfee is not set, include enough fee so transactions begin confirmation on average within n blocks (default: %u)</source> <translation>Nel caso in cui paytxfee non sia impostato, include una commissione tale da ottenere un avvio delle conferme entro una media di n blocchi (predefinito: %u)</translation> </message> <message> <source>Invalid amount for -maxtxfee=&lt;amount&gt;: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)</source> <translation>Importo non valido per -maxtxfee=&lt;amount&gt;: '%s' (deve essere almeno pari alla commissione 'minrelay fee' di %s per prevenire transazioni bloccate)</translation> </message> <message> <source>Maximum size of data in data carrier transactions we relay and mine (default: %u)</source> <translation>Dimensione massima dei dati in transazioni di trasporto dati che saranno trasmesse ed incluse nei blocchi (predefinito: %u)</translation> </message> <message> <source>Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect)</source> <translation>Ottiene gli indirizzi dei peer attraverso interrogazioni DNS, in caso di scarsa disponibilità (predefinito: 1 a meno che -connect non sia specificato)</translation> </message> <message> <source>Randomize credentials for every proxy connection. This enables Tor stream isolation (default: %u)</source> <translation>Randomizza le credenziali per ogni connessione proxy. Permette la Tor stream isolation (predefinito: %u)</translation> </message> <message> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: %d)</source> <translation>Imposta la dimensione massima in byte delle transazioni ad alta-priorità/basse-commissioni (predefinito: %d)</translation> </message> <message> <source>Set the number of threads for coin generation if enabled (-1 = all cores, default: %d)</source> <translation>Specifica il numero di thread per la generazione di bitcoin, se abilitata (-1 = tutti i core, predefinito: %d)</translation> </message> <message> <source>The transaction amount is too small to send after the fee has been deducted</source> <translation>L'importo della transazione risulta troppo basso per l'invio una volta dedotte le commissioni.</translation> </message> <message> <source>This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit &lt;https://www.openssl.org/&gt; and cryptographic software written by Eric Young and UPnP software written by Thomas Bernard.</source> <translation>Questo prodotto include software sviluppato dal progetto OpenSSL per l'uso del Toolkit OpenSSL &lt;https://www.openssl.org/&gt;, software crittografico scritto da Eric Young e software UPnP scritto da Thomas Bernard.</translation> </message> <message> <source>Whitelisted peers cannot be DoS banned and their transactions are always relayed, even if they are already in the mempool, useful e.g. for a gateway</source> <translation>I peer inclusi in whitelist non possono subire ban per DoS e le loro transazioni saranno sempre trasmesse, anche nel caso in cui si trovino già nel mempool. Ciò è utile ad es. per i gateway</translation> </message> <message> <source>You need to rebuild the database using -reindex to go back to unpruned mode. This will redownload the entire blockchain</source> <translation>Per ritornare alla modalità unpruned sarà necessario ricostruire il database utilizzando l'opzione -reindex. L'intera blockchain sarà riscaricata.</translation> </message> <message> <source>(default: %u)</source> <translation>(default: %u)</translation> </message> <message> <source>Accept public REST requests (default: %u)</source> <translation>Accetta richieste REST pubbliche (predefinito: %u)</translation> </message> <message> <source>Activating best chain...</source> <translation>Attivazione della blockchain migliore...</translation> </message> <message> <source>Always relay transactions received from whitelisted peers (default: %d)</source> <translation>Trasmetti sempre le transazioni ricevute da peers whitelisted (default: %d)</translation> </message> <message> <source>Attempt to recover private keys from a corrupt wallet.dat on startup</source> <translation>Prova a recuperare le chiavi private da un wallet corrotto all'avvio</translation> </message> <message> <source>Automatically create Tor hidden service (default: %d)</source> <translation>Crea automaticamente il servizio Tor (default: %d)</translation> </message> <message> <source>Cannot resolve -whitebind address: '%s'</source> <translation>Impossibile risolvere indirizzo -whitebind: '%s'</translation> </message> <message> <source>Connect through SOCKS5 proxy</source> <translation>Connessione attraverso un proxy SOCKS5</translation> </message> <message> <source>Copyright (C) 2009-%i The Bitcoin Core Developers</source> <translation>Copyright (C) 2009-%i Gli sviluppatori di Bitcoin Core</translation> </message> <message> <source>Error loading wallet.dat: Wallet requires newer version of Bitcoin Core</source> <translation>Errore durante il caricamento del file wallet.dat: il portamonete richiede una versione di Bitcoin Core più recente</translation> </message> <message> <source>Error reading from database, shutting down.</source> <translation>Errore durante lalettura del database. Arresto in corso.</translation> </message> <message> <source>Imports blocks from external blk000??.dat file on startup</source> <translation>Importa blocchi da un file blk000??.dat esterno all'avvio</translation> </message> <message> <source>Information</source> <translation>Informazioni</translation> </message> <message> <source>Initialization sanity check failed. Bitcoin Core is shutting down.</source> <translation>Test di integrità iniziale fallito. Bitcoin Core si arresterà.</translation> </message> <message> <source>Invalid amount for -maxtxfee=&lt;amount&gt;: '%s'</source> <translation>Importo non valido per -maxtxfee=&lt;amount&gt;: '%s'</translation> </message> <message> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: '%s'</source> <translation>Importo non valido per -minrelaytxfee=&lt;amount&gt;: '%s'</translation> <<<<<<< HEAD ======= </message> <message> <source>Invalid amount for -mintxfee=&lt;amount&gt;: '%s'</source> <translation>Importo non valido per -mintxfee=&lt;amount&gt;: '%s'</translation> </message> <message> <source>Limit size of signature cache to &lt;n&gt; entries (default: 50000)</source> <translation>Limita la dimensione della cache delle firme a &lt;n&gt; voci (predefinito: 50000)</translation> </message> <message> <source>Log transaction priority and fee per kB when mining blocks (default: 0)</source> <translation>Abilita il log della priorità di transazione e della commissione per kB quando si generano blocchi (default: 0)</translation> </message> <message> <source>Maintain a full transaction index (default: 0)</source> <translation>Mantieni un indice di transazione completo (predefinito: 0)</translation> </message> <message> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation>Buffer di ricezione massimo per connessione, &lt;n&gt;*1000 byte (predefinito: 5000)</translation> </message> <message> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation>Buffer di invio massimo per connessione, &lt;n&gt;*1000 byte (predefinito: 1000)</translation> >>>>>>> 5b9f78d69ccf189bebe894b1921e34417103a046 </message> <message> <source>Invalid amount for -mintxfee=&lt;amount&gt;: '%s'</source> <translation>Importo non valido per -mintxfee=&lt;amount&gt;: '%s'</translation> </message> <message> <source>Invalid amount for -paytxfee=&lt;amount&gt;: '%s' (must be at least %s)</source> <translation>Importo non valido per -paytxfee=&lt;amount&gt;: '%s' (deve essere almeno %s)</translation> </message> <message> <<<<<<< HEAD <source>Print block on startup, if found in block index</source> <translation>Stampa il blocco all'avvio, se presente nell'indice dei blocchi</translation> <<<<<<< HEAD ======= </message> <message> <source>Print block tree on startup (default: 0)</source> <translation>Stampa l'albero dei blocchi all'avvio (default: 0)</translation> >>>>>>> 5b9f78d69ccf189bebe894b1921e34417103a046 ======= <source>Invalid netmask specified in -whitelist: '%s'</source> <translation>Netmask non valida specificata in -whitelist: '%s'</translation> >>>>>>> 80d1f2e48364f05b2cdf44239b3a1faa0277e58e </message> <message> <source>Keep at most &lt;n&gt; unconnectable transactions in memory (default: %u)</source> <translation>Mantiene in memoria al massimo &lt;n&gt; transazioni non collegabili (predefinito: %u)</translation> </message> <message> <source>Need to specify a port with -whitebind: '%s'</source> <translation>È necessario specificare una porta con -whitebind: '%s'</translation> </message> <message> <source>Node relay options:</source> <translation>Opzioni trasmissione nodo:</translation> </message> <message> <source>RPC server options:</source> <translation>Opzioni server RPC:</translation> </message> <message> <source>Rebuild block chain index from current blk000??.dat files on startup</source> <translation>Ricostruzione dell'indice della block chain dai file blk000??.dat correnti all'avvio</translation> </message> <message> <source>Receive and display P2P network alerts (default: %u)</source> <translation>Ricevi e visualizza gli alerts della rete P2P (default: %u)</translation> </message> <message> <source>Reducing -maxconnections from %d to %d, because of system limitations.</source> <translation>Riduzione -maxconnections da %d a %d a causa di limitazioni di sistema.</translation> </message> <message> <source>Rescan the block chain for missing wallet transactions on startup</source> <translation>Ripete la scansione della block chain per individuare le transazioni che mancano dal wallet all'avvio</translation> </message> <message> <source>Send trace/debug info to console instead of debug.log file</source> <translation>Invia le informazioni di trace/debug alla console invece che al file debug.log</translation> </message> <message> <<<<<<< HEAD <<<<<<< HEAD ======= <source>Set minimum block size in bytes (default: 0)</source> <translation>Imposta dimensione minima del blocco in bytes (predefinita: 0)</translation> </message> <message> <source>Sets the DB_PRIVATE flag in the wallet db environment (default: 1)</source> <translation>Imposta il flag DB_PRIVATE nell'ambiente di database del portamonete (predefinito: 1)</translation> </message> <message> >>>>>>> 5b9f78d69ccf189bebe894b1921e34417103a046 ======= <source>Send transactions as zero-fee transactions if possible (default: %u)</source> <translation>Invia transazioni a zero commissioni se possibile (predefinito: %u)</translation> </message> <message> >>>>>>> 9bd8c9b13132d45db4240b2dec256ee1500ce133 <source>Show all debugging options (usage: --help -help-debug)</source> <translation>Mostra tutte le opzioni di debug (utilizzo: --help -help-debug)</translation> </message> <message> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation>Riduce il file debug.log all'avvio del client (predefinito: 1 se -debug non è impostato)</translation> </message> <message> <source>Signing transaction failed</source> <translation>Firma transazione fallita</translation> </message> <message> <source>The transaction amount is too small to pay the fee</source> <translation>L'importo della transazione è troppo basso per pagare la commissione</translation> </message> <message> <source>This is experimental software.</source> <translation>Questo è un software sperimentale.</translation> </message> <message> <source>Tor control port password (default: empty)</source> <translation>Password porta controllo Tor (default: empty)</translation> </message> <message> <source>Tor control port to use if onion listening enabled (default: %s)</source> <translation>Porta di controllo Tor da usare se in ascolto su onion (default: %s)</translation> </message> <message> <source>Transaction amount too small</source> <translation>Importo transazione troppo piccolo</translation> </message> <message> <source>Transaction amounts must be positive</source> <translation>Gli importi della transazione devono essere positivi</translation> </message> <message> <source>Transaction too large for fee policy</source> <translation>Transazione troppo grande in base alla policy sulle commissioni</translation> </message> <message> <source>Transaction too large</source> <translation>Transazione troppo grande</translation> </message> <message> <source>Unable to bind to %s on this computer (bind returned error %s)</source> <translation>Impossibile associarsi a %s su questo computer (l'associazione ha restituito l'errore %s)</translation> </message> <message> <source>Upgrade wallet to latest format on startup</source> <translation>Aggiorna il wallet all'ultimo formato all'avvio</translation> </message> <message> <source>Username for JSON-RPC connections</source> <translation>Nome utente per connessioni JSON-RPC</translation> </message> <message> <source>Wallet needed to be rewritten: restart Bitcoin Core to complete</source> <translation>Il portamonete necessitava di essere riscritto: riavviare Bitcoin Core per completare l'operazione</translation> </message> <message> <source>Warning</source> <translation>Attenzione</translation> </message> <message> <source>Whether to operate in a blocks only mode (default: %u)</source> <translation>Imposta se operare in modalità solo blocchi (default: %u)</translation> </message> <message> <source>Zapping all transactions from wallet...</source> <translation>Eliminazione dal portamonete di tutte le transazioni...</translation> </message> <message> <<<<<<< HEAD <source>on startup</source> <translation>all'avvio</translation> <<<<<<< HEAD ======= </message> <message> <source>version</source> <translation>versione</translation> >>>>>>> 5b9f78d69ccf189bebe894b1921e34417103a046 ======= <source>ZeroMQ notification options:</source> <translation>Opzioni di notifica ZeroMQ</translation> >>>>>>> 80d1f2e48364f05b2cdf44239b3a1faa0277e58e </message> <message> <source>wallet.dat corrupt, salvage failed</source> <translation>wallet.dat corrotto, recupero fallito</translation> </message> <message> <source>Password for JSON-RPC connections</source> <translation>Password per connessioni JSON-RPC</translation> </message> <message> <<<<<<< HEAD ======= <source>Allow JSON-RPC connections from specified IP address</source> <translation>Consenti connessioni JSON-RPC dall'indirizzo IP specificato </translation> </message> <message> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>Inviare comandi al nodo in esecuzione su &lt;ip&gt; (predefinito: 127.0.0.1)</translation> </message> <message> >>>>>>> 5b9f78d69ccf189bebe894b1921e34417103a046 <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <<<<<<< HEAD <translation>Esegui il comando quando il migliore blocco cambia(%s nel cmd è sostituito dall'hash del blocco)</translation> </message> <message> <source>Upgrade wallet to latest format</source> <translation>Aggiorna il wallet all'ultimo formato</translation> <<<<<<< HEAD ======= </message> <message> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>Impostare la quantità di chiavi nel key pool a &lt;n&gt; (predefinita: 100)</translation> >>>>>>> 5b9f78d69ccf189bebe894b1921e34417103a046 </message> <message> <source>Rescan the block chain for missing wallet transactions</source> <translation>Ripeti analisi della catena dei blocchi per cercare le transazioni mancanti dal portamonete </translation> </message> <message> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>Utilizzare OpenSSL (https) per le connessioni JSON-RPC </translation> ======= <translation>Esegue un comando quando il miglior blocco cambia (%s nel cmd è sostituito dall'hash del blocco)</translation> >>>>>>> 80d1f2e48364f05b2cdf44239b3a1faa0277e58e </message> <message> <source>This help message</source> <translation>Questo messaggio di aiuto</translation> </message> <message> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>Consente interrogazioni DNS per -addnode, -seednode e -connect</translation> </message> <message> <source>Loading addresses...</source> <translation>Caricamento indirizzi...</translation> </message> <message> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>Errore caricamento wallet.dat: Portamonete corrotto</translation> </message> <message> <source>(1 = keep tx meta data e.g. account owner and payment request information, 2 = drop tx meta data)</source> <translation>(1 = mantiene metadati tx, ad es. proprietario account ed informazioni di richiesta di pagamento, 2 = scarta metadati tx)</translation> </message> <message> <source>-maxtxfee is set very high! Fees this large could be paid on a single transaction.</source> <translation>-maxtxfee è impostato molto alto! Commissioni così alte possono venir pagate anche su una singola transazione.</translation> </message> <message> <source>-paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation>-paytxfee è impostato su un valore molto elevato. Questa è la commissione che si paga quando si invia una transazione.</translation> </message> <message> <source>Do not keep transactions in the mempool longer than &lt;n&gt; hours (default: %u)</source> <translation>Non mantenere le transazioni nella mempool più a lungo di &lt;n&gt; ore (default: %u)</translation> </message> <message> <source>Error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation>Errore di lettura di wallet.dat! Tutte le chiavi sono state lette correttamente, ma i dati delle transazioni o della rubrica potrebbero essere mancanti o non corretti.</translation> </message> <message> <source>Fees (in %s/kB) smaller than this are considered zero fee for transaction creation (default: %s)</source> <translation>Le commissioni (in %s/kB) inferiori a questo valore sono considerate pari a zero per la creazione della transazione (default: %s)</translation> </message> <message> <source>How thorough the block verification of -checkblocks is (0-4, default: %u)</source> <translation>Determina quanto sarà approfondita la verifica da parte di -checkblocks (0-4, predefinito: %u)</translation> </message> <message> <source>Maintain a full transaction index, used by the getrawtransaction rpc call (default: %u)</source> <translation>Mantiene l'indice completo delle transazioni usato dalla chiamata rpc getrawtransaction (predefinito: %u)</translation> </message> <message> <source>Number of seconds to keep misbehaving peers from reconnecting (default: %u)</source> <translation>Numero di secondi di sospensione prima della riconnessione per i peer che mostrano un comportamento anomalo (predefinito: %u)</translation> </message> <message> <source>Output debugging information (default: %u, supplying &lt;category&gt; is optional)</source> <translation>Emette informazioni di debug (predefinito: %u, fornire &lt;category&gt; è opzionale)</translation> </message> <message> <source>Support filtering of blocks and transaction with bloom filters (default: %u)</source> <translation>Supporta filtraggio di blocchi e transazioni con filtri bloom (default: %u)</translation> </message> <message> <source>Total length of network version string (%i) exceeds maximum length (%i). Reduce the number or size of uacomments.</source> <translation>La lunghezza totale della stringa di network version (%i) eccede la lunghezza massima (%i). Ridurre il numero o la dimensione di uacomments.</translation> </message> <message> <source>Tries to keep outbound traffic under the given target (in MiB per 24h), 0 = no limit (default: %d)</source> <translation>Cerca di mantenere il traffico in uscita al di sotto della soglia scelta (in MiB ogni 24h), 0 = nessun limite (default: %d)</translation> </message> <message> <source>Unsupported argument -socks found. Setting SOCKS version isn't possible anymore, only SOCKS5 proxies are supported.</source> <translation>Argomento -socks non supportato. Non è più possibile impostare la versione SOCKS, solamente i proxy SOCKS5 sono supportati.</translation> </message> <message> <source>Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: %s)</source> <translation>Usa un proxy SOCKS5 a parte per raggiungere i peer attraverso gli hidden services di Tor (predefinito: %s)</translation> </message> <message> <source>Username and hashed password for JSON-RPC connections. The field &lt;userpw&gt; comes in the format: &lt;USERNAME&gt;:&lt;SALT&gt;$&lt;HASH&gt;. A canonical python script is included in share/rpcuser. This option can be specified multiple times</source> <translation>Username e hash password per connessioni JSON-RPC. Il campo &lt;userpw&gt; utilizza il formato: &lt;USERNAME&gt;:&lt;SALT&gt;$&lt;HASH&gt;. Uno script python standard è incluso in share/rpcuser. Questa opzione può essere specificata più volte</translation> </message> <message> <source>(default: %s)</source> <translation>(predefinito: %s)</translation> </message> <message> <source>Always query for peer addresses via DNS lookup (default: %u)</source> <translation>Interroga sempre i DNS per ottenere gli indirizzi dei peer (predefinito: %u)</translation> </message> <message> <source>Error loading wallet.dat</source> <translation>Errore caricamento wallet.dat</translation> </message> <message> <source>Generate coins (default: %u)</source> <translation>Genera bitcoin (predefinito: %u)</translation> </message> <message> <source>How many blocks to check at startup (default: %u, 0 = all)</source> <translation>Numero di blocchi da controllare all'avvio (predefinito: %u, 0 = tutti)</translation> </message> <message> <source>Include IP addresses in debug output (default: %u)</source> <translation>Include gli indirizzi IP nell'output del debug (predefinito: %u)</translation> </message> <message> <source>Invalid -proxy address: '%s'</source> <translation>Indirizzo -proxy non valido: '%s'</translation> </message> <message> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: %u or testnet: %u)</source> <translation>Resta in attesa di connessioni JSON-RPC su &lt;port&gt; (predefinito: %u o testnet: %u)</translation> </message> <message> <source>Listen for connections on &lt;port&gt; (default: %u or testnet: %u)</source> <translation>Resta in attesa di connessioni su &lt;port&gt; (predefinito: %u o testnet: %u)</translation> </message> <message> <source>Maintain at most &lt;n&gt; connections to peers (default: %u)</source> <translation>Mantiene al massimo &lt;n&gt; connessioni verso i peer (predefinito: %u)</translation> </message> <message> <source>Make the wallet broadcast transactions</source> <translation>Configura il portamonete per la trasmissione di transazioni</translation> </message> <message> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: %u)</source> <translation>Buffer di ricezione massimo per connessione, &lt;n&gt;*1000 byte (predefinito: %u)</translation> </message> <message> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: %u)</source> <translation>Buffer di invio massimo per connessione, &lt;n&gt;*1000 byte (predefinito: %u)</translation> </message> <message> <source>Prepend debug output with timestamp (default: %u)</source> <translation>Antepone un timestamp all'output del debug (predefinito: %u)</translation> </message> <message> <source>Relay and mine data carrier transactions (default: %u)</source> <translation>Trasmette ed include nei blocchi transazioni di trasporto dati (predefinito: %u)</translation> </message> <message> <source>Relay non-P2SH multisig (default: %u)</source> <translation>Trasmette transazioni non-P2SH multisig (predefinito: %u)</translation> </message> <message> <source>Set key pool size to &lt;n&gt; (default: %u)</source> <translation>Imposta la dimensione del pool di chiavi a &lt;n&gt; (predefinito: %u)</translation> </message> <message> <source>Set minimum block size in bytes (default: %u)</source> <translation>Imposta la dimensione minima del blocco in byte (predefinito: %u)</translation> </message> <message> <source>Set the number of threads to service RPC calls (default: %d)</source> <translation>Imposta il numero di thread destinati a rispondere alle chiamate RPC (predefinito %d)</translation> </message> <message> <source>Specify configuration file (default: %s)</source> <translation>Specifica il file di configurazione (predefinito: %s)</translation> </message> <message> <source>Specify connection timeout in milliseconds (minimum: 1, default: %d)</source> <translation>Specifica il timeout di connessione in millisecondi (minimo:1, predefinito: %d)</translation> </message> <message> <source>Specify pid file (default: %s)</source> <translation>Specifica il file pid (predefinito: %s)</translation> </message> <message> <source>Spend unconfirmed change when sending transactions (default: %u)</source> <translation>Abilita la spesa di resto non confermato quando si inviano transazioni (predefinito: %u)</translation> </message> <message> <source>Threshold for disconnecting misbehaving peers (default: %u)</source> <translation>Soglia di disconnessione per i peer che si comportano in maniera anomala (predefinito: %u)</translation> </message> <message> <source>Unknown network specified in -onlynet: '%s'</source> <translation>Rete sconosciuta specificata in -onlynet: '%s'</translation> </message> <message> <source>Cannot resolve -bind address: '%s'</source> <translation>Impossibile risolvere indirizzo -bind: '%s'</translation> </message> <message> <<<<<<< HEAD <source>Cannot resolve -externalip address: '%s'</source> <translation>Impossibile risolvere indirizzo -externalip: '%s'</translation> </message> <message> ======= <source>Cannot resolve -bind address: '%s'</source> <translation>Impossibile risolvere -bind address: '%s'</translation> </message> <message> <source>Cannot resolve -externalip address: '%s'</source> <translation>Impossibile risolvere indirizzo -externalip: '%s'</translation> </message> <message> >>>>>>> 5b9f78d69ccf189bebe894b1921e34417103a046 <source>Invalid amount for -paytxfee=&lt;amount&gt;: '%s'</source> <translation>Importo non valido per -paytxfee=&lt;amount&gt;: '%s'</translation> </message> <message> <source>Insufficient funds</source> <translation>Fondi insufficienti</translation> </message> <message> <source>Loading block index...</source> <translation>Caricamento dell'indice dei blocchi...</translation> </message> <message> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>Aggiunge un nodo a cui connettersi e tenta di mantenere aperta la connessione</translation> </message> <message> <source>Loading wallet...</source> <translation>Caricamento portamonete...</translation> </message> <message> <source>Cannot downgrade wallet</source> <translation>Non è possibile effettuare il downgrade del portamonete</translation> </message> <message> <source>Cannot write default address</source> <translation>Non è possibile scrivere l'indirizzo predefinito</translation> </message> <message> <source>Rescanning...</source> <translation>Ripetizione scansione...</translation> </message> <message> <source>Done loading</source> <translation>Caricamento completato</translation> </message> <message> <source>Error</source> <translation>Errore</translation> </message> </context> </TS>
mit
EricShiGit/personalblog
djangoblog/urls.py
723
from django.conf.urls import patterns, include, url from django.conf.urls.static import static from django.conf import settings from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'djangoblog.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), # Blog URLs url(r'', include('blogengine.urls')), # Flat pages url(r'', include('django.contrib.flatpages.urls')), # Comments url(r'', include('django.contrib.comments.urls')), ) if settings.DEBUG: import debug_toolbar urlpatterns += patterns('', url(r'^__debug__/', include(debug_toolbar.urls)), )
mit
Yordanov101/OperatorsAndExpressionsHW
16.BitExchangeTwo/BitExchangeTwo.cs
2027
using System; class BitExchangeTwo { // Program that exchanges bits {p, p+1, …, p+k-1} with bits {q, q+1, …, q+k-1} of a given 32-bit // unsigned integer.The first and the second sequence of bits may not overlap. static void Main() { uint number = uint.Parse(Console.ReadLine()); int pBits = int.Parse(Console.ReadLine()); int qBits = int.Parse(Console.ReadLine()); int kBits = int.Parse(Console.ReadLine()); if (pBits > qBits) { int oldValue = pBits; pBits = qBits; qBits = oldValue; } if (pBits + kBits >= qBits) { kBits += pBits - qBits - 1; qBits += pBits + kBits + 1; } number = ModifyNumber(number, pBits, qBits, kBits); Console.WriteLine(number); } private static uint ModifyNumber(uint number, int p, int q, int k) { int[] pBits = new int[k]; int[] qBits = new int[k]; for (int position = p, i = 0; i < pBits.Length; position++, i++) { pBits[i] = PthBit(number, position); } for (int position = q, i = 0; i < qBits.Length; position++, i++) { qBits[i] = PthBit(number, position); } for (int position = p, i = 0; i < qBits.Length; position++, i++) { number = ModifiedNumber(number, position, qBits[i]); } for (int position = q, i = 0; i < pBits.Length; position++, i++) { number = ModifiedNumber(number, position, pBits[i]); } return number; } private static int PthBit(uint number, int position) { uint pthBit = (number >> position) & 1; return (int)pthBit; } private static uint ModifiedNumber(uint number,int position,int bitValue) { uint actualP = (uint)bitValue << position; number = number & (~((uint)1 << position)); uint result = number | actualP; return result; } }
mit
dinosaurwithakatana/Google-I-O-Bingo
app/src/androidTest/java/io/dwak/googleiobingo/ApplicationTest.java
352
package io.dwak.googleiobingo; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
mit
plastic-karma/junit-flakey-detector
testrunner/src/main/java/de/plastickarma/flakeyunit/PrintStreamListener.java
1079
package de.plastickarma.flakeyunit; import org.junit.runner.Description; import java.io.PrintStream; import java.util.List; /** * Example listener, that prints a message to the given PrintStream, if a flakey test was discovered. */ public final class PrintStreamListener implements FlakeyTestcaseListener { private final PrintStream output; /** * Creates a PrintStreamListener with the given PrintStream. */ public PrintStreamListener(final PrintStream output) { this.output = output; } /** * Prints a message to this listener's PrintStream, that a flakey test was discovered. */ @Override public void handlePotentialFlakeyness( final Description description, final Throwable originalException, final int rerunCount, final List<Throwable> rerunExceptions) { this.output.printf( "%s failed %d times after %d reruns. Testcase is potentially flakey.\n", description.getDisplayName(), rerunExceptions.size(), rerunCount); } }
mit
redaktor/exiftool.js
src/exiftool/filetypes/435.js
2877
exports.info = { FormatID: '1222', FormatName: 'Drawing Interchange File Format (ASCII)', FormatVersion: '2010/2011/2012', FormatAliases: '', FormatFamilies: '', FormatTypes: 'Image (Vector)', FormatDisclosure: '', FormatDescription: 'This is an outline record only, and requires further details, research or authentication to provide information that will enable users to further understand the format and to assess digital preservation risks associated with it if appropriate. If you are able to help by supplying any additional information concerning this entry, please return to the main PRONOM page and select ‘Add an Entry’.', BinaryFileFormat: '', ByteOrders: '', ReleaseDate: '', WithdrawnDate: '', ProvenanceSourceID: '1', ProvenanceName: 'Digital Preservation Department / The National Archives', ProvenanceSourceDate: '11 Jun 2012', ProvenanceDescription: '', LastUpdatedDate: '18 Dec 2012', FormatNote: '', FormatRisk: '', TechnicalEnvironment: '', FileFormatIdentifier: [ { Identifier: 'fmt/435', IdentifierType: 'PUID' }, { Identifier: 'image/vnd.dxf', IdentifierType: 'MIME' } ], Developers: { DeveloperID: '18', DeveloperName: '', OrganisationName: 'Autodesk Corporation', DeveloperCompoundName: 'Autodesk Corporation' }, Support: { SupportID: '18', SupportName: '', OrganisationName: 'Autodesk Corporation', SupportCompoundName: 'Autodesk Corporation' }, ExternalSignature: { ExternalSignatureID: '1223', Signature: 'dxf', SignatureType: 'File extension' }, InternalSignature: { SignatureID: '652', SignatureName: 'Drawing Interchange File Format 2010/2011/2012', SignatureNote: 'Header section with $ACADVER group code (AC1024), EOF marker', ByteSequence: [ { ByteSequenceID: '797', PositionType: 'Variable', Offset: '', MaxOffset: '', IndirectOffsetLocation: '', IndirectOffsetLength: '', Endianness: '', ByteSequenceValue: '30{1-2}53454354494F4E{1-2}202032{1-2}484541444552{1-2}*39{1-2}2441434144564552{1-2}202031{1-2}414331303234{1-2}*30{1-2}454E44534543{1-2}' }, { ByteSequenceID: '798', PositionType: 'Absolute from EOF', Offset: '1', MaxOffset: '2', IndirectOffsetLocation: '', IndirectOffsetLength: '', Endianness: '', ByteSequenceValue: '30{1-2}454F46' } ] }, RelatedFormat: [ { RelationshipType: 'Has priority over', RelatedFormatID: '766', RelatedFormatName: 'Drawing Interchange File Format (ASCII)', RelatedFormatVersion: 'Generic' }, { RelationshipType: 'Is previous version of', RelatedFormatID: '1319', RelatedFormatName: 'Drawing Interchange File Format (ASCII)', RelatedFormatVersion: '2013/2014' } ] }
mit
DataFire/Integrations
integrations/generated/google_servicecontrol/index.js
175
"use strict"; let datafire = require('datafire'); let openapi = require('./openapi.json'); module.exports = datafire.Integration.fromOpenAPI(openapi, "google_servicecontrol");
mit
brocaar/loraserver
internal/downlink/downlink.go
1097
package downlink import ( "time" "github.com/pkg/errors" "github.com/brocaar/chirpstack-network-server/internal/config" "github.com/brocaar/chirpstack-network-server/internal/downlink/data" "github.com/brocaar/chirpstack-network-server/internal/downlink/join" "github.com/brocaar/chirpstack-network-server/internal/downlink/multicast" "github.com/brocaar/chirpstack-network-server/internal/downlink/proprietary" ) var ( schedulerBatchSize = 100 schedulerInterval time.Duration ) // Setup sets up the downlink. func Setup(conf config.Config) error { nsConfig := conf.NetworkServer schedulerInterval = nsConfig.Scheduler.SchedulerInterval if err := data.Setup(conf); err != nil { return errors.Wrap(err, "setup downlink/data error") } if err := join.Setup(conf); err != nil { return errors.Wrap(err, "setup downlink/join error") } if err := multicast.Setup(conf); err != nil { return errors.Wrap(err, "setup downlink/multicast error") } if err := proprietary.Setup(conf); err != nil { return errors.Wrap(err, "setup downlink/proprietary error") } return nil }
mit
kyokley/MediaViewer
mediaviewer/models/path.py
6522
import time from django.db import models from django.core.urlresolvers import reverse from mediaviewer.models.file import File from mediaviewer.models.posterfile import PosterFile from mediaviewer.models.usercomment import UserComment from mediaviewer.models.genre import Genre from datetime import datetime as dateObj from datetime import timedelta from django.utils.timezone import utc class Path(models.Model): localpathstr = models.TextField(blank=True) remotepathstr = models.TextField(blank=True) skip = models.BooleanField(blank=True) is_movie = models.BooleanField(blank=False, null=False, db_column='ismovie') defaultScraper = models.ForeignKey( 'mediaviewer.FilenameScrapeFormat', null=True, blank=True, db_column='defaultscraperid') tvdb_id = models.TextField(null=True, blank=True) server = models.TextField(blank=False, null=False) defaultsearchstr = models.TextField(null=True, blank=True) imdb_id = models.TextField(null=True, blank=True) override_display_name = models.TextField( null=True, blank=True, db_column='display_name') lastCreatedFileDate = models.DateTimeField( null=True, blank=True, db_column='lastcreatedfiledate') class Meta: app_label = 'mediaviewer' db_table = 'path' @classmethod def new(cls, localpathstr, remotepathstr, is_movie, skip=True, server='127.0.0.1' ): obj = cls() obj.localpathstr = localpathstr obj.remotepathstr = remotepathstr obj.is_movie = is_movie obj.skip = skip obj.server = server obj.save() return obj @property def isFile(self): return False @property def isPath(self): return True def files(self): return File.objects.filter( path__localpathstr=self.localpathstr).filter(hide=False) @property def shortName(self): return self.localPath.rpartition('/')[-1] @property def localPath(self): return self.localpathstr localpath = localPath @property def remotePath(self): return self.remotepathstr remotepath = remotePath def displayName(self): return (self.override_display_name or self.shortName.replace('.', ' ').title()) def __unicode__(self): return 'id: %s r: %s l: %s' % (self.id, self.remotePath, self.localPath) def lastCreatedFileDateForSpan(self): last_date = self.lastCreatedFileDate return last_date and last_date.date().isoformat() def url(self): return '<a href="{}">{}</a>'.format( reverse('mediaviewer:tvshows', args=(self.id,)), self.displayName()) @classmethod def distinctShowFolders(cls): refFiles = File.objects.filter( path__is_movie=False).order_by( 'path').distinct('path').select_related('path') paths = set([file.path for file in refFiles]) return cls._buildDistinctShowFoldersFromPaths(paths) @classmethod def _buildDistinctShowFoldersFromPaths(cls, paths): pathDict = dict() for path in paths: lastDate = path.lastCreatedFileDate if path.shortName in pathDict: if (lastDate and pathDict[ path.shortName].lastCreatedFileDate < lastDate): pathDict[path.shortName] = path else: pathDict[path.shortName] = path return pathDict @classmethod def distinctShowFoldersByGenre(cls, genre): paths = cls.objects.filter(_posterfile__genres=genre) return cls._buildDistinctShowFoldersFromPaths(paths) def isMovie(self): return self.is_movie def isTVShow(self): return not self.isMovie() def _posterfileget(self): posterfile = PosterFile.new(path=self) return posterfile def _posterfileset(self, val): val.path = self val.save() posterfile = property(fset=_posterfileset, fget=_posterfileget) def destroy(self): files = File.objects.filter(path=self) for file in files: file.delete() self.delete() def unwatched_tv_shows_since_date(self, user, daysBack=30): if self.isMovie(): raise Exception('This function does not apply to movies') if daysBack > 0: refDate = (dateObj.utcnow().replace(tzinfo=utc) - timedelta(days=daysBack)) files = (File.objects.filter(path__localpathstr=self.localpathstr) .filter(datecreated__gt=refDate) .filter(hide=False) .all()) else: files = (File.objects.filter(path__localpathstr=self.localpathstr) .filter(hide=False) .all()) unwatched_files = set() for file in files: comment = file.usercomment(user) if not comment or not comment.viewed: unwatched_files.add(file) return unwatched_files def number_of_unwatched_shows_since_date(self, user, daysBack=30): return len(self.unwatched_tv_shows_since_date(user, daysBack=daysBack)) def number_of_unwatched_shows(self, user): if not user: return 0 files = (File.objects.filter(path__localpathstr=self.localpathstr) .filter(hide=False)) file_count = files.count() usercomments_count = (UserComment.objects.filter(user=user) .filter(file__in=files) .filter(viewed=True) .count()) return file_count - usercomments_count @classmethod def populate_all_posterfiles(cls): all_paths = cls.objects.filter(is_movie=False).all() for path in all_paths: path.posterfile time.sleep(.5) @classmethod def get_tv_genres(cls): return Genre.get_tv_genres()
mit
raadhuis/modx-basic
core/components/formit/model/formit/formit.class.php
11235
<?php /** * FormIt * * Copyright 2009-2012 by Shaun McCormick <[email protected]> * * FormIt 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. * * FormIt is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * FormIt; if not, write to the Free Software Foundation, Inc., 59 Temple Place, * Suite 330, Boston, MA 02111-1307 USA * * @package formit */ /** * Base class for FormIt. Used for initializing the form processing engine, handling templating and running snippets. * * @package formit */ class FormIt { /** * A reference to the modX instance * @var modX $modx */ public $modx; /** * A configuration array * @var array $config */ public $config; /** * In debug mode, will monitor execution time. * @var int $debugTimer * @access public */ public $debugTimer = 0; /** * True if the class has been initialized or not. * @var boolean $_initialized */ private $_initialized = false; /** * The fiHooks instance for processing preHooks * @var fiHooks $preHooks */ public $preHooks; /** * The fiHooks instance for processing postHooks * @var fiHooks $postHooks */ public $postHooks; /** * The request handling class * @var fiRequest $request */ public $request; /** * An array of cached chunk tpls for processing * @var array $chunks */ public $chunks; /** * Used when running unit tests to prevent emails/headers from being sent * @var boolean $inTestMode */ public $inTestMode = false; /** * FormIt constructor * * @param modX &$modx A reference to the modX instance. * @param array $config An array of configuration options. Optional. */ function __construct(modX &$modx,array $config = array()) { $this->modx =& $modx; /* allows you to set paths in different environments * this allows for easier SVN management of files */ $corePath = $this->modx->getOption('formit.core_path',null,MODX_CORE_PATH.'components/formit/'); $assetsPath = $this->modx->getOption('formit.assets_path',null,MODX_ASSETS_PATH.'components/formit/'); $assetsUrl = $this->modx->getOption('formit.assets_url',null,MODX_ASSETS_URL.'components/formit/'); $connectorUrl = $assetsUrl.'connector.php'; /* loads some default paths for easier management */ $this->config = array_merge(array( 'corePath' => $corePath, 'modelPath' => $corePath.'model/', 'chunksPath' => $corePath.'elements/chunks/', 'snippetsPath' => $corePath.'elements/snippets/', 'controllersPath' => $corePath.'controllers/', 'includesPath' => $corePath.'includes/', 'testsPath' => $corePath.'test/', 'templatesPath' => $corePath.'templates/', 'assetsPath' => $assetsPath, 'assetsUrl' => $assetsUrl, 'cssUrl' => $assetsUrl.'css/', 'jsUrl' => $assetsUrl.'js/', 'connectorUrl' => $connectorUrl, 'debug' => $this->modx->getOption('formit.debug',null,false), 'use_multibyte' => (boolean)$this->modx->getOption('use_multibyte',null,false), 'encoding' => $this->modx->getOption('modx_charset',null,'UTF-8'), ),$config); if ($this->modx->getOption('formit.debug',$this->config,true)) { $this->startDebugTimer(); } $this->modx->addPackage('formit',$this->config['modelPath']); } /** * Initialize the component into a context and provide context-specific * handling actions. * * @access public * @param string $context The context to initialize FormIt into * @return mixed */ public function initialize($context = 'web') { switch ($context) { case 'mgr': break; case 'web': default: $language = isset($this->config['language']) ? $this->config['language'] . ':' : ''; $this->modx->lexicon->load($language.'formit:default'); $this->_initialized = true; break; } return $this->_initialized; } /** * Sees if the FormIt class has been initialized already * @return boolean */ public function isInitialized() { return $this->_initialized; } /** * Load the fiRequest class * @return fiRequest */ public function loadRequest() { $className = $this->modx->getOption('request_class',$this->config,'fiRequest'); $classPath = $this->modx->getOption('request_class_path',$this->config,''); if (empty($classPath)) $classPath = $this->config['modelPath'].'formit/'; if ($this->modx->loadClass($className,$classPath,true,true)) { $this->request = new fiRequest($this,$this->config); } else { $this->modx->log(modX::LOG_LEVEL_ERROR,'[FormIt] Could not load fiRequest class.'); } return $this->request; } /** * @param string $className * @param string $serviceName * @param array $config * @return fiModule */ public function loadModule($className,$serviceName,array $config = array()) { if (empty($this->$serviceName)) { $classPath = $this->modx->getOption('formit.modules_path',null,$this->config['modelPath'].'formit/module/'); if ($this->modx->loadClass($className,$classPath,true,true)) { $this->$serviceName = new $className($this,$config); } else { $this->modx->log(modX::LOG_LEVEL_ERROR,'[FormIt] Could not load module: '.$className.' from '.$classPath); } } return $this->$serviceName; } /** * Loads the Hooks class. * * @access public * @param $type string The type of hook to load. * @param $config array An array of configuration parameters for the * hooks class * @return fiHooks An instance of the fiHooks class. */ public function loadHooks($type = 'post',$config = array()) { if (!$this->modx->loadClass('formit.fiHooks',$this->config['modelPath'],true,true)) { $this->modx->log(modX::LOG_LEVEL_ERROR,'[FormIt] Could not load Hooks class.'); return false; } $typeVar = $type.'Hooks'; $this->$typeVar = new fiHooks($this,$config,$type); return $this->$typeVar; } /** * Gets a unique session-based store key for storing form submissions. * * @return string */ public function getStoreKey() { return $this->modx->context->get('key').'/elements/formit/submission/'.md5(session_id()); } /** * Gets a Chunk and caches it; also falls back to file-based templates * for easier debugging. * * Will always use the file-based chunk if $debug is set to true. * * @access public * @param string $name The name of the Chunk * @param array $properties The properties for the Chunk * @return string The processed content of the Chunk */ public function getChunk($name,$properties = array()) { $chunk = null; if(substr($name, 0, 6) == "@CODE:"){ $content = substr($name, 6); $chunk = $this->modx->newObject('modChunk'); $chunk->setContent($content); } elseif (!isset($this->chunks[$name])) { if (!$this->config['debug']) { $chunk = $this->modx->getObject('modChunk',array('name' => $name),true); } if (empty($chunk)) { $chunk = $this->_getTplChunk($name); if ($chunk == false) return false; } $this->chunks[$name] = $chunk->getContent(); } else { $o = $this->chunks[$name]; $chunk = $this->modx->newObject('modChunk'); $chunk->setContent($o); } $chunk->setCacheable(false); return $chunk->process($properties); } /** * Returns a modChunk object from a template file. * * @access private * @param string $name The name of the Chunk. Will parse to name.chunk.tpl * @return modChunk/boolean Returns the modChunk object if found, otherwise * false. */ private function _getTplChunk($name) { $chunk = false; if (file_exists($name)) { $f = $name; } else { $lowerCaseName = $this->config['use_multibyte'] ? mb_strtolower($name,$this->config['encoding']) : strtolower($name); $f = $this->config['chunksPath'].$lowerCaseName.'.chunk.tpl'; } if (file_exists($f)) { $o = file_get_contents($f); /** @var modChunk $chunk */ $chunk = $this->modx->newObject('modChunk'); $chunk->set('name',$name); $chunk->setContent($o); } return $chunk; } /** * Output the final output and wrap in the wrapper chunk. Optional, but * recommended for debugging as it outputs the execution time to the output. * * Also, it is good to output your snippet code with wrappers for easier * CSS isolation and styling. * * @access public * @param string $output The output to process * @return string The final wrapped output */ public function output($output) { if ($this->debugTimer !== false) { $output .= "<br />\nExecution time: ".$this->endDebugTimer()."\n"; } return $output; } /** * Starts the debug timer. * * @access protected * @return int The start time. */ protected function startDebugTimer() { $mtime = microtime(); $mtime = explode(' ', $mtime); $mtime = $mtime[1] + $mtime[0]; $tstart = $mtime; $this->debugTimer = $tstart; return $this->debugTimer; } /** * Ends the debug timer and returns the total number of seconds script took * to run. * * @access protected * @return int The end total time to execute the script. */ protected function endDebugTimer() { $mtime= microtime(); $mtime= explode(" ", $mtime); $mtime= $mtime[1] + $mtime[0]; $tend= $mtime; $totalTime= ($tend - $this->debugTimer); $totalTime= sprintf("%2.4f s", $totalTime); $this->debugTimer = false; return $totalTime; } public function setOption($key,$value) { $this->config[$key] = $value; } public function setOptions($array) { foreach ($array as $k => $v) { $this->setOption($k,$v); } } }
mit
tableau/TabPy
tabpy/tabpy_server/app/util.py
2635
import csv from datetime import datetime import logging from OpenSSL import crypto import os logger = logging.getLogger(__name__) def validate_cert(cert_file_path): with open(cert_file_path, "r") as f: cert_buf = f.read() cert = crypto.load_certificate(crypto.FILETYPE_PEM, cert_buf) date_format, encoding = "%Y%m%d%H%M%SZ", "ascii" not_before = datetime.strptime(cert.get_notBefore().decode(encoding), date_format) not_after = datetime.strptime(cert.get_notAfter().decode(encoding), date_format) now = datetime.now() https_error = "Error using HTTPS: " if now < not_before: msg = https_error + f"The certificate provided is not valid until {not_before}." logger.critical(msg) raise RuntimeError(msg) if now > not_after: msg = https_error + f"The certificate provided expired on {not_after}." logger.critical(msg) raise RuntimeError(msg) def parse_pwd_file(pwd_file_name): """ Parses passwords file and returns set of credentials. Parameters ---------- pwd_file_name : str Passwords file name. Returns ------- succeeded : bool True if specified file was parsed successfully. False if there were any issues with parsing specified file. credentials : dict Credentials from the file. Empty if succeeded is False. """ logger.info(f"Parsing passwords file {pwd_file_name}...") if not os.path.isfile(pwd_file_name): logger.critical(f"Passwords file {pwd_file_name} not found") return False, {} credentials = {} with open(pwd_file_name) as pwd_file: pwd_file_reader = csv.reader(pwd_file, delimiter=" ") for row in pwd_file_reader: # skip empty lines if len(row) == 0: continue # skip commented lines if row[0][0] == "#": continue if len(row) != 2: logger.error(f'Incorrect entry "{row}" in password file') return False, {} login = row[0].lower() if login in credentials: logger.error( f"Multiple entries for username {login} in password file" ) return False, {} if len(row[1]) > 0: credentials[login] = row[1] logger.debug(f"Found username {login}") else: logger.warning(f"Found username {row[0]} but no password") return False, {} logger.info("Authentication is enabled") return True, credentials
mit
mcqueary/jnats
src/test/java/io/nats/client/impl/HeadersTests.java
33640
package io.nats.client.impl; import io.nats.client.support.IncomingHeadersProcessor; import io.nats.client.support.Status; import io.nats.client.support.Token; import io.nats.client.support.TokenType; import org.junit.jupiter.api.Test; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.function.Consumer; import static org.junit.jupiter.api.Assertions.*; public class HeadersTests { private static final String KEY1 = "Key1"; private static final String KEY2 = "Key2"; private static final String KEY3 = "Key3"; private static final String KEY1_ALT = "KEY1"; private static final String KEY1_OTHER = "kEy1"; private static final String KEY2_OTHER = "kEy2"; private static final String VAL1 = "val1"; private static final String VAL2 = "val2"; private static final String VAL3 = "val3"; private static final String VAL4 = "val4"; private static final String VAL5 = "val5"; private static final String VAL6 = "val6"; private static final String EMPTY = ""; @Test public void add_key_strings_works() { add( headers -> headers.add(KEY1, VAL1), headers -> headers.add(KEY1, VAL2), headers -> headers.add(KEY2, VAL3), headers -> { headers.add(KEY1_ALT, VAL4); headers.add(KEY1_ALT, VAL5); } ); } @Test public void add_key_collection_works() { add( headers -> headers.add(KEY1, Collections.singletonList(VAL1)), headers -> headers.add(KEY1, Collections.singletonList(VAL2)), headers -> headers.add(KEY2, Collections.singletonList(VAL3)), headers -> headers.add(KEY1_ALT, Arrays.asList(VAL4, VAL5)) ); } private void add( Consumer<Headers> stepKey1Val1, Consumer<Headers> step2Key1Val2, Consumer<Headers> step3Key2Val3, Consumer<Headers> step4Key1AVal4Val5 ) { Headers headers = new Headers(); stepKey1Val1.accept(headers); assertContainsKeysIgnoreCase(headers, Arrays.asList(KEY1, KEY1_ALT, KEY1_OTHER)); assertNotContainsKeysIgnoreCase(headers, Arrays.asList(KEY2, KEY2_OTHER, KEY3)); assertContainsKeys(headers, 1, Collections.singletonList(KEY1)); assertKeyIgnoreCaseContainsValues(headers, Arrays.asList(KEY1, KEY1_ALT, KEY1_OTHER), Collections.singletonList(VAL1)); assertKeyContainsValues(headers, Collections.singletonList(KEY1), Collections.singletonList(VAL1)); validateDirtyAndLength(headers); step2Key1Val2.accept(headers); assertContainsKeysIgnoreCase(headers, Arrays.asList(KEY1, KEY1_ALT, KEY1_OTHER)); assertNotContainsKeysIgnoreCase(headers, Arrays.asList(KEY2, KEY2_OTHER, KEY3)); assertContainsKeys(headers, 1, Collections.singletonList(KEY1)); assertKeyIgnoreCaseContainsValues(headers, Arrays.asList(KEY1, KEY1_ALT, KEY1_OTHER), Arrays.asList(VAL1, VAL2)); assertKeyContainsValues(headers, Collections.singletonList(KEY1), Arrays.asList(VAL1, VAL2)); validateDirtyAndLength(headers); step3Key2Val3.accept(headers); assertContainsKeysIgnoreCase(headers, Arrays.asList(KEY1, KEY1_ALT, KEY1_OTHER, KEY2, KEY2_OTHER)); assertNotContainsKeysIgnoreCase(headers, Collections.singletonList(KEY3)); assertContainsKeys(headers, 2, Arrays.asList(KEY1, KEY2)); assertKeyIgnoreCaseContainsValues(headers, Arrays.asList(KEY2, KEY2_OTHER), Collections.singletonList(VAL3)); assertKeyContainsValues(headers, Collections.singletonList(KEY2), Collections.singletonList(VAL3)); validateDirtyAndLength(headers); step4Key1AVal4Val5.accept(headers); assertContainsKeysIgnoreCase(headers, Arrays.asList(KEY1, KEY1_ALT, KEY1_OTHER, KEY2, KEY2_OTHER)); assertContainsKeys(headers, 3, Arrays.asList(KEY1, KEY2, KEY1_ALT)); assertKeyIgnoreCaseContainsValues(headers, Arrays.asList(KEY1, KEY1_ALT, KEY1_OTHER), Arrays.asList(VAL1, VAL2, VAL4, VAL5)); assertKeyContainsValues(headers, Collections.singletonList(KEY1), Arrays.asList(VAL1, VAL2)); assertKeyContainsValues(headers, Collections.singletonList(KEY1_ALT), Arrays.asList(VAL4, VAL5)); validateDirtyAndLength(headers); } @Test public void put_key_strings_works() { put( headers -> headers.put(KEY1, VAL1), headers -> headers.put(KEY1, VAL2), headers -> headers.put(KEY2, VAL3), headers -> headers.put(KEY1_ALT, VAL4), headers -> headers.put(KEY1_OTHER, VAL5) ); } @Test public void put_key_collection_works() { put( headers -> headers.put(KEY1, Collections.singletonList(VAL1)), headers -> headers.put(KEY1, Collections.singletonList(VAL2)), headers -> headers.put(KEY2, Collections.singletonList(VAL3)), headers -> headers.put(KEY1_ALT, Collections.singletonList(VAL4)), headers -> headers.put(KEY1_OTHER, Collections.singletonList(VAL5)) ); } private void put( Consumer<Headers> step1PutKey1Val1, Consumer<Headers> step2PutKey1Val2, Consumer<Headers> step3PutKey2Val3, Consumer<Headers> step4PutKey1AVal4, Consumer<Headers> step6PutKey1HVal5) { Headers headers = new Headers(); assertTrue(headers.isEmpty()); step1PutKey1Val1.accept(headers); assertContainsKeys(headers, 1, Collections.singletonList(KEY1)); assertContainsKeysIgnoreCase(headers, Arrays.asList(KEY1, KEY1_ALT, KEY1_OTHER)); assertNotContainsKeysIgnoreCase(headers, Arrays.asList(KEY2, KEY2_OTHER, KEY3)); assertKeyContainsValues(headers, Collections.singletonList(KEY1), Collections.singletonList(VAL1)); assertKeyIgnoreCaseContainsValues(headers, Arrays.asList(KEY1, KEY1_ALT, KEY1_OTHER), Collections.singletonList(VAL1)); validateDirtyAndLength(headers); step2PutKey1Val2.accept(headers); assertContainsKeys(headers, 1, Collections.singletonList(KEY1)); assertContainsKeysIgnoreCase(headers, Arrays.asList(KEY1, KEY1_ALT, KEY1_OTHER)); assertNotContainsKeysIgnoreCase(headers, Arrays.asList(KEY2, KEY2_OTHER, KEY3)); assertKeyContainsValues(headers, Collections.singletonList(KEY1), Collections.singletonList(VAL2)); assertKeyIgnoreCaseContainsValues(headers, Arrays.asList(KEY1, KEY1_ALT, KEY1_OTHER), Collections.singletonList(VAL2)); validateDirtyAndLength(headers); step3PutKey2Val3.accept(headers); assertContainsKeys(headers, 2, Arrays.asList(KEY1, KEY2)); assertContainsKeysIgnoreCase(headers, Arrays.asList(KEY1, KEY1_ALT, KEY1_OTHER, KEY2, KEY2_OTHER)); assertNotContainsKeysIgnoreCase(headers, Collections.singletonList(KEY3)); assertKeyContainsValues(headers, Collections.singletonList(KEY2), Collections.singletonList(VAL3)); assertKeyIgnoreCaseContainsValues(headers, Arrays.asList(KEY2, KEY2_OTHER), Collections.singletonList(VAL3)); validateDirtyAndLength(headers); step4PutKey1AVal4.accept(headers); assertContainsKeys(headers, 3, Arrays.asList(KEY1, KEY1_ALT, KEY2)); assertContainsKeysIgnoreCase(headers, Arrays.asList(KEY1, KEY1_ALT, KEY1_OTHER, KEY2, KEY2_OTHER)); assertNotContainsKeysIgnoreCase(headers, Collections.singletonList(KEY3)); assertKeyContainsValues(headers, Collections.singletonList(KEY1_ALT), Collections.singletonList(VAL4)); assertKeyIgnoreCaseContainsValues(headers, Arrays.asList(KEY1, KEY1_ALT, KEY1_OTHER), Arrays.asList(VAL2, VAL4)); validateDirtyAndLength(headers); step6PutKey1HVal5.accept(headers); assertContainsKeys(headers, 4, Arrays.asList(KEY1, KEY1_ALT, KEY1_OTHER, KEY2)); assertNotContainsKeysIgnoreCase(headers, Collections.singletonList(KEY3)); assertContainsKeysIgnoreCase(headers, Arrays.asList(KEY1, KEY1_ALT, KEY1_OTHER, KEY2, KEY2_OTHER)); assertKeyContainsValues(headers, Collections.singletonList(KEY1_OTHER), Collections.singletonList(VAL5)); assertKeyIgnoreCaseContainsValues(headers, Arrays.asList(KEY1, KEY1_ALT, KEY1_OTHER), Arrays.asList(VAL2, VAL4, VAL5)); } private void assertKeyIgnoreCaseContainsValues(Headers headers, List<String> keys, List<String> values) { for (String k : keys) { List<String> hVals = headers.getIgnoreCase(k); assertEquals(values.size(), hVals.size()); for (String v : values) { assertTrue(hVals.contains(v)); } } } private void assertKeyContainsValues(Headers headers, List<String> keys, List<String> values) { for (String k : keys) { List<String> hVals = headers.get(k); assertEquals(values.size(), hVals.size()); for (String v : values) { assertTrue(hVals.contains(v)); } } } private void assertContainsKeysIgnoreCase(Headers headers, List<String> keys) { Set<String> keySet = headers.keySetIgnoreCase(); assertNotNull(keySet); for (String k : keys) { assertTrue(keySet.contains(k.toLowerCase())); assertTrue(headers.containsKeyIgnoreCase(k)); } } private void assertNotContainsKeysIgnoreCase(Headers headers, List<String> keys) { Set<String> keySet = headers.keySetIgnoreCase(); for (String k : keys) { assertFalse(keySet.contains(k.toLowerCase())); assertFalse(headers.containsKeyIgnoreCase(k)); assertNull(headers.getIgnoreCase(k)); } } private void assertContainsKeys(Headers headers, int countUniqueKeys, List<String> keys) { Set<String> keySet = headers.keySet(); assertNotNull(keySet); assertEquals(countUniqueKeys, headers.size()); for (String k : keys) { assertTrue(keySet.contains(k)); assertTrue(headers.containsKey(k)); } } @Test public void keyCannotBeNullOrEmpty() { Headers headers = new Headers(); assertThrows(IllegalArgumentException.class, () -> headers.put(null, VAL1)); assertThrows(IllegalArgumentException.class, () -> headers.put(null, VAL1, VAL2)); assertThrows(IllegalArgumentException.class, () -> headers.put(null, Collections.singletonList(VAL1))); assertThrows(IllegalArgumentException.class, () -> headers.put(EMPTY, VAL1)); assertThrows(IllegalArgumentException.class, () -> headers.put(EMPTY, VAL1, VAL2)); assertThrows(IllegalArgumentException.class, () -> headers.put(EMPTY, Collections.singletonList(VAL1))); assertThrows(IllegalArgumentException.class, () -> headers.add(null, VAL1)); assertThrows(IllegalArgumentException.class, () -> headers.add(null, VAL1, VAL2)); assertThrows(IllegalArgumentException.class, () -> headers.add(null, Collections.singletonList(VAL1))); assertThrows(IllegalArgumentException.class, () -> headers.add(EMPTY, VAL1)); assertThrows(IllegalArgumentException.class, () -> headers.add(EMPTY, VAL1, VAL2)); assertThrows(IllegalArgumentException.class, () -> headers.add(EMPTY, Collections.singletonList(VAL1))); } @Test public void valuesThatAreEmptyButAreAllowed() { Headers headers = new Headers(); assertEquals(0, headers.size()); validateDirtyAndLength(headers); headers.add(KEY1, ""); assertEquals(1, headers.get(KEY1).size()); validateDirtyAndLength(headers); headers.put(KEY1, ""); assertEquals(1, headers.get(KEY1).size()); validateDirtyAndLength(headers); headers = new Headers(); headers.add(KEY1, VAL1, "", VAL2); assertEquals(3, headers.get(KEY1).size()); validateDirtyAndLength(headers); headers.put(KEY1, VAL1, "", VAL2); assertEquals(3, headers.get(KEY1).size()); validateDirtyAndLength(headers); } @Test public void valuesThatAreNullButAreIgnored() { Headers headers = new Headers(); assertEquals(0, headers.size()); validateDirtyAndLength(headers); headers.add(KEY1, VAL1, null, VAL2); assertEquals(2, headers.get(KEY1).size()); validateDirtyAndLength(headers); headers.put(KEY1, VAL1, null, VAL2); assertEquals(2, headers.get(KEY1).size()); validateDirtyAndLength(headers); headers.clear(); assertEquals(0, headers.size()); validateDirtyAndLength(headers); headers.add(KEY1); assertEquals(0, headers.size()); validateNotDirtyAndLength(headers); headers.put(KEY1); assertEquals(0, headers.size()); validateNotDirtyAndLength(headers); headers.add(KEY1, (String)null); assertEquals(0, headers.size()); validateNotDirtyAndLength(headers); headers.put(KEY1, (String)null); assertEquals(0, headers.size()); validateNotDirtyAndLength(headers); headers.add(KEY1, (Collection<String>)null); assertEquals(0, headers.size()); validateNotDirtyAndLength(headers); headers.put(KEY1, (Collection<String> )null); assertEquals(0, headers.size()); validateNotDirtyAndLength(headers); } @Test public void keyCharactersMustBePrintableExceptForColon() { Headers headers = new Headers(); // ctrl characters, space and colon are not allowed for (char c = 0; c < 33; c++) { final String key = "key" + c; assertThrows(IllegalArgumentException.class, () -> headers.put(key, VAL1)); } assertThrows(IllegalArgumentException.class, () -> headers.put("key:", VAL1)); assertThrows(IllegalArgumentException.class, () -> headers.put("key" + (char)127, VAL1)); // all other characters are good for (char c = 33; c < ':'; c++) { headers.put("key" + c, VAL1); } for (char c = ':' + 1; c < 127; c++) { headers.put("key" + c, VAL1); } } @Test public void valueCharactersMustBePrintableOrTab() { Headers headers = new Headers(); // ctrl characters, except for tab not allowed for (char c = 0; c < 9; c++) { final String val = "val" + c; assertThrows(IllegalArgumentException.class, () -> headers.put(KEY1, val)); } for (char c = 10; c < 32; c++) { final String val = "val" + c; assertThrows(IllegalArgumentException.class, () -> headers.put(KEY1, val)); } assertThrows(IllegalArgumentException.class, () -> headers.put(KEY1, "val" + (char)127)); // printable and tab are allowed for (char c = 32; c < 127; c++) { headers.put(KEY1, "" + c); } headers.put(KEY1, "val" + (char)9); } @Test public void remove_string_work() { remove( headers -> headers.remove(KEY1), headers -> headers.remove(KEY1_ALT), headers -> headers.remove(KEY1_OTHER), headers -> headers.remove(KEY2, KEY3) ); } @Test public void remove_collection_work() { remove( headers -> headers.remove(Collections.singletonList(KEY1)), headers -> headers.remove(Collections.singletonList(KEY1_ALT)), headers -> headers.remove(Collections.singletonList(KEY1_OTHER)), headers -> headers.remove(Arrays.asList(KEY2, KEY3)) ); } @Test public void getFirsts() { Headers headers = new Headers(); assertNull(headers.getFirst(KEY1)); headers.add(KEY1, VAL1); assertEquals(VAL1, headers.getFirst(KEY1)); headers.add(KEY1, VAL2); assertEquals(VAL1, headers.getFirst(KEY1)); headers.put(KEY1, VAL3); assertEquals(VAL3, headers.getFirst(KEY1)); } private void remove( Consumer<Headers> step1RemoveKey1, Consumer<Headers> step2RemoveKey1A, Consumer<Headers> step3RemoveKey1H, Consumer<Headers> step4RemoveKey2Key3) { Headers headers = testHeaders(); step1RemoveKey1.accept(headers); assertContainsKeysIgnoreCase(headers, Arrays.asList(KEY2, KEY2_OTHER, KEY3)); assertNotContainsKeysIgnoreCase(headers, Arrays.asList(KEY1, KEY1_ALT, KEY1_OTHER)); assertContainsKeys(headers, 2, Arrays.asList(KEY2, KEY3)); assertKeyIgnoreCaseContainsValues(headers, Arrays.asList(KEY2, KEY2_OTHER), Collections.singletonList(VAL2)); assertKeyIgnoreCaseContainsValues(headers, Collections.singletonList(KEY3), Collections.singletonList(VAL3)); assertKeyContainsValues(headers, Collections.singletonList(KEY2), Collections.singletonList(VAL2)); assertKeyContainsValues(headers, Collections.singletonList(KEY3), Collections.singletonList(VAL3)); validateDirtyAndLength(headers); headers = testHeaders(); step2RemoveKey1A.accept(headers); assertContainsKeys(headers, 3, Arrays.asList(KEY1, KEY2, KEY3)); headers = testHeaders(); step3RemoveKey1H.accept(headers); assertContainsKeys(headers, 3, Arrays.asList(KEY1, KEY2, KEY3)); headers = testHeaders(); step4RemoveKey2Key3.accept(headers); assertContainsKeysIgnoreCase(headers, Arrays.asList(KEY1, KEY1_ALT, KEY1_OTHER)); assertNotContainsKeysIgnoreCase(headers, Arrays.asList(KEY2, KEY2_OTHER, KEY3)); assertContainsKeys(headers, 1, Collections.singletonList(KEY1)); assertKeyIgnoreCaseContainsValues(headers, Arrays.asList(KEY1, KEY1_ALT, KEY1_OTHER), Collections.singletonList(VAL1)); assertKeyContainsValues(headers, Collections.singletonList(KEY1), Collections.singletonList(VAL1)); validateDirtyAndLength(headers); } private byte[] validateDirtyAndLength(Headers headers) { assertTrue(headers.isDirty()); byte[] serialized = headers.getSerialized(); assertFalse(headers.isDirty()); assertEquals(serialized.length, headers.serializedLength()); return serialized; } private void validateNotDirtyAndLength(Headers headers) { assertFalse(headers.isDirty()); byte[] serialized = headers.getSerialized(); assertFalse(headers.isDirty()); assertEquals(serialized.length, headers.serializedLength()); } @Test public void equalsHashcodeClearSizeEmpty_work() { assertEquals(testHeaders(), testHeaders()); assertEquals(testHeaders().hashCode(), testHeaders().hashCode()); Headers headers1 = new Headers(); headers1.put(KEY1, VAL1); Headers headers2 = new Headers(); headers2.put(KEY2, VAL2); assertNotEquals(headers1, headers2); assertEquals(1, headers1.size()); assertFalse(headers1.isEmpty()); headers1.clear(); assertEquals(0, headers1.size()); assertTrue(headers1.isEmpty()); } @Test public void serialize_deserialize() { Headers headers1 = new Headers(); headers1.add(KEY1, VAL1); headers1.add(KEY1, VAL3); headers1.add(KEY2, VAL2); headers1.add(KEY3, EMPTY); byte[] serialized = validateDirtyAndLength(headers1); IncomingHeadersProcessor incomingHeadersProcessor = new IncomingHeadersProcessor(serialized); Headers headers2 = incomingHeadersProcessor.getHeaders(); assertNotNull(headers2); validateDirtyAndLength(headers2); assertEquals(headers1.size(), headers2.size()); assertTrue(headers2.containsKey(KEY1)); assertTrue(headers2.containsKey(KEY2)); assertEquals(2, headers2.get(KEY1).size()); assertEquals(1, headers2.get(KEY2).size()); assertEquals(1, headers2.get(KEY3).size()); assertTrue(headers2.get(KEY1).contains(VAL1)); assertTrue(headers2.get(KEY1).contains(VAL3)); assertTrue(headers2.get(KEY2).contains(VAL2)); assertTrue(headers2.get(KEY3).contains(EMPTY)); } @Test public void constructHeadersWithInvalidBytes() { assertThrows(IllegalArgumentException.class, () -> new IncomingHeadersProcessor(null)); assertThrows(IllegalArgumentException.class, () -> new IncomingHeadersProcessor("".getBytes())); assertThrows(IllegalArgumentException.class, () -> new IncomingHeadersProcessor("NATS/0.0".getBytes())); assertThrows(IllegalArgumentException.class, () -> new IncomingHeadersProcessor("NATS/1.0".getBytes())); assertThrows(IllegalArgumentException.class, () -> new IncomingHeadersProcessor("NATS/1.0 \r\n".getBytes())); assertThrows(IllegalArgumentException.class, () -> new IncomingHeadersProcessor("NATS/1.0X\r\n".getBytes())); assertThrows(IllegalArgumentException.class, () -> new IncomingHeadersProcessor("NATS/1.0 \r\n\r\n".getBytes())); assertThrows(IllegalArgumentException.class, () -> new IncomingHeadersProcessor("NATS/1.0\r\n\r\n".getBytes())); assertThrows(IllegalArgumentException.class, () -> new IncomingHeadersProcessor("NATS/1.0\r\n".getBytes())); assertThrows(IllegalArgumentException.class, () -> new IncomingHeadersProcessor("NATS/1.0 503\r".getBytes())); assertThrows(IllegalArgumentException.class, () -> new IncomingHeadersProcessor("NATS/1.0 503\n".getBytes())); assertThrows(IllegalArgumentException.class, () -> new IncomingHeadersProcessor("NATS/1.0 FiveOhThree\r\n".getBytes())); assertThrows(IllegalArgumentException.class, () -> new IncomingHeadersProcessor("NATS/1.0\r\n".getBytes())); assertThrows(IllegalArgumentException.class, () -> new IncomingHeadersProcessor("NATS/1.0\r\n\r\n".getBytes())); assertThrows(IllegalArgumentException.class, () -> new IncomingHeadersProcessor("NATS/1.0\r\n\r\n\r\n".getBytes())); assertThrows(IllegalArgumentException.class, () -> new IncomingHeadersProcessor("NATS/1.0\r\nk1:v1".getBytes())); assertThrows(IllegalArgumentException.class, () -> new IncomingHeadersProcessor("NATS/1.0\r\nk1:v1\r\n".getBytes())); assertThrows(IllegalArgumentException.class, () -> new IncomingHeadersProcessor("NATS/1.0\r\nk1:v1\r\r\n".getBytes())); } @Test public void constructHeadersWithValidBytes() { assertValidHeader("NATS/1.0\r\nk1:v1\r\n\r\n", "k1", "v1"); assertValidHeader("NATS/1.0\r\nks1: v1\r\n\r\n", "ks1", "v1"); assertValidHeader("NATS/1.0\r\nk1:\r\n\r\n", "k1", EMPTY); assertValidHeader("NATS/1.0\r\nks1: \r\n\r\n", "ks1", EMPTY); assertValidHeader("NATS/1.0\r\ncolons::::\r\n\r\n", "colons", ":::"); } @Test public void constructStatusWithValidBytes() { assertValidStatus("NATS/1.0 503\r\n", 503, "No Responders Available For Request"); // status made message assertValidStatus("NATS/1.0 404\r\n", 404, "Server Status Message: 404"); // status made message assertValidStatus("NATS/1.0 503 No Responders\r\n", 503, "No Responders"); // from data assertValidStatus("NATS/1.0 503 No Responders\r\n", 503, "No Responders"); } @Test public void verifyStatusBooleans() { Status status = new Status(Status.FLOW_OR_HEARTBEAT_STATUS_CODE, Status.FLOW_CONTROL_TEXT); assertTrue(status.isFlowControl()); assertFalse(status.isHeartbeat()); assertFalse(status.isNoResponders()); status = new Status(Status.FLOW_OR_HEARTBEAT_STATUS_CODE, Status.HEARTBEAT_TEXT); assertFalse(status.isFlowControl()); assertTrue(status.isHeartbeat()); assertFalse(status.isNoResponders()); status = new Status(Status.NO_RESPONDERS_CODE, Status.NO_RESPONDERS_TEXT); assertFalse(status.isFlowControl()); assertFalse(status.isHeartbeat()); assertTrue(status.isNoResponders()); // path coverage status = new Status(Status.NO_RESPONDERS_CODE, "not no responders text"); assertFalse(status.isNoResponders()); } @Test public void constructHasStatusAndHeaders() { IncomingHeadersProcessor ihp = assertValidStatus("NATS/1.0 503\r\nfoo:bar\r\n\r\n", 503, "No Responders Available For Request"); // status made message assertValidHeader(ihp, "foo", "bar"); ihp = assertValidStatus("NATS/1.0 503 No Responders\r\nfoo:bar\r\n\r\n", 503, "No Responders"); // from data assertValidHeader(ihp, "foo", "bar"); } private IncomingHeadersProcessor assertValidHeader(String test, String key, String val) { IncomingHeadersProcessor ihp = new IncomingHeadersProcessor(test.getBytes()); assertValidHeader(ihp, key, val); return ihp; } private IncomingHeadersProcessor assertValidHeader(IncomingHeadersProcessor ihp, String key, String val) { Headers headers = ihp.getHeaders(); assertNotNull(headers); assertEquals(1, headers.size()); assertTrue(headers.containsKey(key)); assertEquals(1, headers.get(key).size()); assertEquals(val, headers.get(key).get(0)); return ihp; } private IncomingHeadersProcessor assertValidStatus(String test, int code, String msg) { IncomingHeadersProcessor ihp = new IncomingHeadersProcessor(test.getBytes()); assertValidStatus(ihp, code, msg); return ihp; } private IncomingHeadersProcessor assertValidStatus(IncomingHeadersProcessor ihp, int code, String msg) { Status status = ihp.getStatus(); assertNotNull(status); assertEquals(code, status.getCode()); if (msg != null) { assertEquals(msg, status.getMessage()); } NatsMessage.InternalMessageFactory imf = new NatsMessage.InternalMessageFactory("sid", "sub", "rt", 0, false); imf.setHeaders(ihp); assertTrue(imf.getMessage().isStatusMessage()); return ihp; } static class IteratorTestHelper { int manualCount = 0; int forEachCount = 0; int entrySetCount = 0; StringBuilder manualCompareString = new StringBuilder(); StringBuilder forEachCompareString = new StringBuilder(); StringBuilder entrySetCompareString = new StringBuilder(); } @Test public void iteratorsTest() { Headers headers = testHeaders(); headers.add(KEY1_ALT, VAL6); IteratorTestHelper helper = new IteratorTestHelper(); for (String key : headers.keySet()) { helper.manualCount++; helper.manualCompareString.append(key); headers.get(key).forEach(v -> helper.manualCompareString.append(v)); } assertEquals(4, helper.manualCount); headers.forEach((key, values) -> { helper.forEachCount++; helper.forEachCompareString.append(key); values.forEach(v -> helper.forEachCompareString.append(v)); }); assertEquals(4, helper.forEachCount); headers.entrySet().forEach(entry -> { helper.entrySetCount++; helper.entrySetCompareString.append(entry.getKey()); entry.getValue().forEach(v -> helper.entrySetCompareString.append(v)); }); assertEquals(4, helper.entrySetCount); assertEquals(helper.manualCompareString.toString(), helper.forEachCompareString.toString()); assertEquals(helper.manualCompareString.toString(), helper.entrySetCompareString.toString()); assertEquals(3, headers.keySetIgnoreCase().size()); } private Headers testHeaders() { Headers headers = new Headers(); validateDirtyAndLength(headers); headers.put(KEY1, VAL1); validateDirtyAndLength(headers); headers.put(KEY2, VAL2); validateDirtyAndLength(headers); headers.put(KEY3, VAL3); validateDirtyAndLength(headers); assertContainsKeysIgnoreCase(headers, Arrays.asList(KEY1, KEY1_ALT, KEY1_OTHER, KEY2, KEY2_OTHER, KEY3)); assertContainsKeys(headers, 3, Arrays.asList(KEY1, KEY2, KEY3)); assertKeyIgnoreCaseContainsValues(headers, Arrays.asList(KEY1, KEY1_ALT, KEY1_OTHER), Collections.singletonList(VAL1)); assertKeyIgnoreCaseContainsValues(headers, Arrays.asList(KEY2, KEY2_OTHER), Collections.singletonList(VAL2)); assertKeyIgnoreCaseContainsValues(headers, Collections.singletonList(KEY3), Collections.singletonList(VAL3)); assertKeyContainsValues(headers, Collections.singletonList(KEY1), Collections.singletonList(VAL1)); assertKeyContainsValues(headers, Collections.singletonList(KEY2), Collections.singletonList(VAL2)); assertKeyContainsValues(headers, Collections.singletonList(KEY3), Collections.singletonList(VAL3)); return headers; } private void assertContainsExactly(Collection<String> actual, String... expected) { assertNotNull(actual); assertEquals(actual.size(), expected.length); for (String v : expected) { assertTrue(actual.contains(v)); } } @Test public void nullPathways() { Headers h = new Headers(); assertTrue(h.isEmpty()); assertNull(h.get(KEY1)); h = new Headers(h); assertTrue(h.isEmpty()); h = new Headers(null); assertTrue(h.isEmpty()); h.add(KEY1, (String[])null); assertTrue(h.isEmpty()); h.put(KEY1, (Collection<String>)null); assertTrue(h.isEmpty()); h.put(KEY1, (String[])null); assertTrue(h.isEmpty()); } @Test public void equalsHash() { Headers h1 = new Headers(); Headers h2 = new Headers(); assertNotEquals(h1, null); assertEquals(h1, h1); assertEquals(h1, h2); assertEquals(h1.hashCode(), h1.hashCode()); assertEquals(h1.hashCode(), h2.hashCode()); h1.add(KEY1, VAL1); h2.add(KEY1, VAL1); assertEquals(h1, h2); assertEquals(h1.hashCode(), h2.hashCode()); h1.add(KEY2, VAL2); assertNotEquals(h1, h2); assertNotEquals(h1.hashCode(), h2.hashCode()); assertNotEquals(h1, new Object()); } @Test public void constructorWithHeaders() { Headers h = new Headers(); h.add(KEY1, VAL1); h.add(KEY2, VAL2, VAL3); validateDirtyAndLength(h); Headers h2 = new Headers(h); assertEquals(2, h2.size()); assertTrue(h2.containsKey(KEY1)); assertTrue(h2.containsKey(KEY2)); assertEquals(1, h2.get(KEY1).size()); assertEquals(2, h2.get(KEY2).size()); assertTrue(h2.get(KEY1).contains(VAL1)); assertTrue(h2.get(KEY2).contains(VAL2)); assertTrue(h2.get(KEY2).contains(VAL3)); validateDirtyAndLength(h2); } @Test public void testToken() { byte[] serialized1 = "notspaceorcrlf".getBytes(StandardCharsets.US_ASCII); assertThrows(IllegalArgumentException.class, () -> new Token(serialized1, serialized1.length, 0, TokenType.WORD)); assertThrows(IllegalArgumentException.class, () -> new Token(serialized1, serialized1.length, 0, TokenType.KEY)); assertThrows(IllegalArgumentException.class, () -> new Token(serialized1, serialized1.length, 0, TokenType.SPACE)); assertThrows(IllegalArgumentException.class, () -> new Token(serialized1, serialized1.length, 0, TokenType.CRLF)); byte[] serialized2 = "\r".getBytes(StandardCharsets.US_ASCII); assertThrows(IllegalArgumentException.class, () -> new Token(serialized2, serialized2.length, 0, TokenType.CRLF)); byte[] serialized3 = "\rnotlf".getBytes(StandardCharsets.US_ASCII); assertThrows(IllegalArgumentException.class, () -> new Token(serialized3, serialized3.length, 0, TokenType.CRLF)); Token t = new Token("k1:v1\r\n\r\n".getBytes(StandardCharsets.US_ASCII), 9, 0, TokenType.KEY); t.mustBe(TokenType.KEY); assertThrows(IllegalArgumentException.class, () -> t.mustBe(TokenType.CRLF)); } @Test public void testTokenSamePoint() { byte[] serialized1 = " \r\n".getBytes(StandardCharsets.US_ASCII); Token t1 = new Token(serialized1, serialized1.length, 0, TokenType.SPACE); // equals Token t1Same = new Token(serialized1, serialized1.length, 0, TokenType.SPACE); assertTrue(t1.samePoint(t1Same)); // same start, same end, different type byte[] notSame = "x\r\n".getBytes(StandardCharsets.US_ASCII); Token tNotSame = new Token(notSame, notSame.length, 0, TokenType.TEXT); assertFalse(t1.samePoint(tNotSame)); // same start, different end, same type notSame = " \r\n".getBytes(StandardCharsets.US_ASCII); tNotSame = new Token(notSame, notSame.length, 0, TokenType.SPACE); assertFalse(t1.samePoint(tNotSame)); // different start notSame = "x \r\n".getBytes(StandardCharsets.US_ASCII); tNotSame = new Token(notSame, notSame.length, 1, TokenType.SPACE); assertFalse(t1.samePoint(tNotSame)); } @Test public void testToString() { assertNotNull(new Status(1, "msg").toString()); // COVERAGE } }
mit
kanonirov/lanb-client
src/main/java/ru/lanbilling/webservice/wsdl/GetSharedPostsCategories.java
1917
package ru.lanbilling.webservice.wsdl; import javax.annotation.Generated; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element name="flt" type="{urn:api3}soapFilter" minOccurs="0"/&gt; * &lt;/sequence&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "flt" }) @XmlRootElement(name = "getSharedPostsCategories") @Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11") public class GetSharedPostsCategories { @Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11") protected SoapFilter flt; /** * Gets the value of the flt property. * * @return * possible object is * {@link SoapFilter } * */ @Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11") public SoapFilter getFlt() { return flt; } /** * Sets the value of the flt property. * * @param value * allowed object is * {@link SoapFilter } * */ @Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11") public void setFlt(SoapFilter value) { this.flt = value; } }
mit
staafl/dotnet-bclext
to-integrate/libcs_staaflutil/Business/Controls/Text_Boxes/Our_MaskedTextBox.cs
1084
using System; using System.Windows.Forms; namespace Common.Controls { #if NO_CALCULATOR public class Our_MaskedTextBox : MaskedTextBox #else public partial class Our_MaskedTextBox : MaskedTextBox, ICalculatorTextBox #endif { public Our_MaskedTextBox() { (this).AutoSize = false; } public bool Auto_Highlight { get; set; } protected override void OnEnter(EventArgs e) { if (Auto_Highlight) this.SelectAll(); base.OnEnter(e); } } #if !NO_CALCULATOR public partial class Our_MaskedTextBox : MaskedTextBox, ICalculatorTextBox { void ICalculatorTextBox.AcceptChar(char ch) { Our_StaticTextBoxBase.Accept_Char(this, ch); } Control ICalculatorTextBox.Control { get { return this; } } void ICalculatorTextBox.NotifyChanged() { } bool ICalculatorTextBox.IsCalculable { get { return false; } } } #endif }
mit
danielholgate/marklogic-kinesis-connector
src/main/java/com/marklogic/kinesis/implementations/MarkLogicEmitter.java
1741
package com.marklogic.kinesis.implementations; import com.amazonaws.services.kinesis.connectors.KinesisConnectorConfiguration; import com.amazonaws.services.kinesis.connectors.UnmodifiableBuffer; import com.amazonaws.services.kinesis.connectors.interfaces.IEmitter; import com.marklogic.kinesis.MarkLogicSender; import com.marklogic.kinesis.config.KinesisConnectorForMarkLogicConfiguration; import com.marklogic.kinesis.model.MarkLogicMessageModel; import java.io.IOException; import java.util.List; import org.apache.log4j.Logger; public class MarkLogicEmitter implements IEmitter<MarkLogicMessageModel> { private static final Logger LOG = Logger.getLogger(MarkLogicEmitter.class.getName()); private MarkLogicSender sender; private KinesisConnectorForMarkLogicConfiguration config; private static final boolean SEND_RECORDS_IN_BATCHES = true; private long batchSize = 1000L; public MarkLogicEmitter(KinesisConnectorConfiguration configuration) { this.config = ((KinesisConnectorForMarkLogicConfiguration)configuration); this.sender = new MarkLogicSender(this.config); this.batchSize = this.config.BUFFER_RECORD_COUNT_LIMIT; } public List<MarkLogicMessageModel> emit(UnmodifiableBuffer<MarkLogicMessageModel> buffer) throws IOException { List<MarkLogicMessageModel> records = buffer.getRecords(); return sendRecords(records); } private List<MarkLogicMessageModel> sendRecords(List<MarkLogicMessageModel> records) { return this.sender.sendToMarkLogic(records); } public void fail(List<MarkLogicMessageModel> records) { for (MarkLogicMessageModel record : records) { LOG.error("Could not emit record: " + record); } } public void shutdown() {} }
mit
NiklasFauth/33c3-hot-wire
software/main.cpp
17591
#include <RFM12B.h> #include <SPI.h> #include "bma2XX_regs.h" #include <CounterLib_t.h> #include "Energia.h" Counter<> freqCounter; // create counter that counts pulses on pin P1.0 #define NODEID 42 //network ID used for this unit #define NETWORKID 137 //the network ID we are on #define GATEWAYID 1 //the node ID we're sending to #define LED //disbable modules by uncommenting #define RADIO #define BUZZER #define ACC //#define DEBUG #define WINFREQ 500 #define STARTFREQ 100 /* * Gamemode 1: green. Only reacts on wire contact. * Gamemode 2: blue. Triggers on wire contact, and too slow motion. * Gamemode 3: red. Triggers on wire contact, too slow motion and change of oriantation. */ /* VBAT = ADC * 0,00244V * 614 = 1,5V * 574 = 1,4V * 533 = 1,3V * 492 = 1,2V */ #define FILTER //prefilter for some Frequencies (100, 200, 300, 400, 500, 600kHz) #define FREQDELAY 2 //tune this for better frequency readout #define AQUISITION 50 //how lonh to wait for frequency measurement #define MINFREQ 90 //lowest used frequency #define START digitalWrite(CS_BMA, 0) #define STOP digitalWrite(CS_BMA, 1) #define READ 0x80 #define LED_G P2_4 #define LED_R P2_2 #define LED_B P2_1 #define BUZZ P2_5 #define BUTTON P2_3 #define CS_RFM12 P3_0 #define CS_BMA P3_1 #define ADC P1_4 #define WIRE P1_0 #define INT_BMA P1_3 #define ACK_TIME 1500 // # of ms to wait for an ack #define SERIAL_BAUD 9600 // serial debug baud rate #define requestACK 0 //request ack #define RED 2 #define GREEN 0 #define BLUE 1 RFM12B radio; byte sendSize = 0; char payload[28] = ""; // max. 127 bytes uint16_t history[3] = {0, 0, 0}; byte data[3]; boolean buttonInterrupt = false, wireInterrupt = false, accInterrupt = false; uint16_t batVoltage = 0; byte gameMode = 0; void setup() { // initialize the digital pin as an output. pinMode(LED_R, OUTPUT); pinMode(LED_G, OUTPUT); pinMode(LED_B, OUTPUT); digitalWrite(LED_R, LOW); digitalWrite(LED_G, LOW); digitalWrite(LED_B, LOW); pinMode(BUZZ, OUTPUT); digitalWrite(BUZZ, LOW); pinMode(ADC, INPUT); analogReference(INTERNAL2V5); pinMode(CS_RFM12, OUTPUT); digitalWrite(CS_RFM12, HIGH); pinMode(CS_BMA, OUTPUT); digitalWrite(CS_BMA, HIGH); #ifdef DEBUG Serial.begin(SERIAL_BAUD); Serial.print("start..."); #endif SPI.begin(); SPI.setClockDivider(2); //8MHz SPI clock #ifdef RADIO radio.Initialize(NODEID, RF12_433MHZ, NETWORKID); radio.Sleep(); //sleep right away to save power #endif pinMode(BUTTON, INPUT_PULLUP); attachInterrupt(BUTTON, buttonFunction, FALLING); //interrupt for button #ifdef ACC bma2XXclearInterrupts(); //clear existing interrupts delay(100); bma2XXsetProfile(); //initialize Accelerometer //attachInterrupt(INT_BMA, accFunction, FALLING); //interrupt for BMA280 #endif //pinMode(WIRE, INPUT); attachInterrupt(WIRE, wireFunction, CHANGE); //interrupt for button //enableComparator(); //_BIS_SR(LPM4_bits + GIE); //sleep, wait for interrupts //interrupts(); suspend(); } void loop() { if (buttonInterrupt) { buttonInterrupt = false; for (byte i = 0; i < 255; i++) { //wait ~5s if (digitalRead(BUTTON) != LOW) { delay(1000); if (digitalRead(BUTTON) == LOW) { gameMode++; if (gameMode > 2) gameMode = 0; if (gameMode == 0) detachInterrupt(INT_BMA); else attachInterrupt(INT_BMA, accFunction, FALLING); //noInterrupts();*/ fail(gameMode); } return; } delay(20); } for (byte i = 0; i < 2; i++) { //indicator flashing digitalWrite(LED_B, HIGH); delay(100); digitalWrite(LED_B, LOW); delay(100); } delay(1000); if (digitalRead(BUTTON) != LOW) { //button still pressed? deepSleep(); //...then go to deep sleep #ifdef ACC //This is the point we wake up again later bma2XXclearInterrupts(); delay(100); bma2XXsetProfile(); attachInterrupt(INT_BMA, accFunction, FALLING); #endif digitalWrite(LED_G, HIGH); delay(200); digitalWrite(LED_G, LOW); #ifdef BUZZER bootMelody(); //Windows XP boot melody ;) #endif attachInterrupt(WIRE, wireFunction, FALLING); return; } delay(1000); //not pressed? selfTest(); //then do a self test } if (wireInterrupt) { wireInterrupt = false; //CACTL1 = 0; //disable comparator //CACTL2 = 0; //reuse interrupt Pin from frequency measurement long currentTime = millis(); boolean freqValid = false, freqStart = false, freqWin = false;; freqCounter.start(CL_Div8); //start Timer with 8x divider while (millis() - currentTime < AQUISITION) { freqCounter.reset(); delay(FREQDELAY); history[0] = ((freqCounter.read()) / FREQDELAY * 8) / 1.28; if ((history[1] < history[2] + 1 || history[1] > history[2] - 1) && (history[0] < history[1] + 1 || history[0] > history[1] - 1) && history[0] > 90) { //compare three measurements #ifdef FILTER if (history[0] < 110 && history[0] > 90) { freqValid = true; #if STARTFREQ == 100 freqStart = true; #endif #if WINFREQ == 100 freqWin = true; #endif break; } if (history[0] < 210 && history[0] > 190) { freqValid = true; #if STARTFREQ == 200 freqStart = true; #endif #if WINFREQ == 200 freqWin = true; #endif break; } if (history[0] < 310 && history[0] > 290) { freqValid = true; #if STARTFREQ == 300 freqStart = true; #endif #if WINFREQ == 300 freqWin = true; #endif break; } if (history[0] < 410 && history[0] > 390) { freqValid = true; #if STARTFREQ == 400 freqStart = true; #endif #if WINFREQ == 400 freqWin = true; #endif break; } if (history[0] < 510 && history[0] > 490) { freqValid = true; #if STARTFREQ == 500 freqStart = true; #endif #if WINFREQ == 500 freqWin = true; #endif break; } if (history[0] < 610 && history[0] > 590) { freqValid = true; #if STARTFREQ == 600 freqStart = true; #endif #if WINFREQ == 600 freqWin = true; #endif break; } #endif #ifndef FILTER freqValid = true; break; #endif } history[2] = history[1]; history[1] = history[0]; delay(FREQDELAY); } freqCounter.stop(); //stop Timer if (!freqValid) { history[0] = 999; } sendPackage(2, history[0]); initTimers(); //restore system Timers if (freqStart) { startMelody(); } else if (freqWin) { for (byte i = 0; i < 2; i++) { //indicator flashing digitalWrite(LED_B, HIGH); digitalWrite(LED_R, HIGH); delay(100); digitalWrite(LED_B, LOW); digitalWrite(LED_R, LOW); delay(100); } winMelody(); } else { fail(gameMode); } pinMode(WIRE, INPUT); attachInterrupt(WIRE, wireFunction, CHANGE); } if (accInterrupt) { accInterrupt = false; char intType = readBMA2XX(BMAREG_INTSTAT0); //Read the Interrupt Reason if (bitRead(intType, INTSTAT0_FLATINT) && gameMode == 2) { //Oriantation changed sendPackage(11, 0); fail(gameMode); } else if (bitRead(intType, INTSTAT0_SLOPEINT)) { //Fast motion Interrupt sendPackage(12, 0); //fail(); } else if (bitRead(intType, INTSTAT0_SLO_NO_MOT_INT) && gameMode > 0) { //Slow Motion interrupt sendPackage(13, 0); fail(gameMode); } } //enableComparator(); interrupts();//reenable interrupts //go back to sleep suspend(); } void selfTest() { uint16_t batVoltage = readBat(); #ifdef LED analogWrite(LED_R, constrain(map(batVoltage, 490, 615, 255, 0), 0, 255)); //display the Battery voltage (1,1V - 1,5V ^= Red - Green) analogWrite(LED_G, constrain(map(batVoltage, 490, 615, 0, 255), 0, 255)); delay(1000); digitalWrite(LED_R, LOW); digitalWrite(LED_G, LOW); for(int j=0; j<512; j++) { //test LED's if (j % 512 < 256) analogWrite(LED_R, j % 256); else analogWrite(LED_R, 256 - j % 256); delay(1); } digitalWrite(LED_R, LOW); for(int j=0; j<512; j++) { if (j % 512 < 256) analogWrite(LED_G, j % 256); else analogWrite(LED_G, 256 - j % 256); delay(1); digitalWrite(LED_G, LOW); } for(int j=0; j<512; j++) { if (j % 512 < 256) analogWrite(LED_B, j % 256); else analogWrite(LED_B, 256 - j % 256); delay(1); } digitalWrite(LED_B, LOW); delay(500); #endif #ifdef BUZZER //test Buzzer tone(BUZZ, 2200); delay(100); tone(BUZZ, 2700); delay(100); tone(BUZZ, 3200); delay(100); noTone(BUZZ); delay(500); #endif delay(500); sendPackage(1, 0); //test Radio digitalWrite(LED_G, HIGH); delay(200); digitalWrite(LED_G, LOW); } void deepSleep() { detachInterrupt(WIRE); detachInterrupt(INT_BMA); #ifdef BUZZER shutdownMelody(); //Windows XP shutdown melody ;) #endif #ifdef RADIO radio.Sleep(); #endif #ifdef ACC writeBMA2XX(BMAREG_SLEEP_DURATION, 0b10 << BMA_LOWPOWER_ENA); //go to suspend mode (~2µA) #endif interrupts(); //enable interrupts to capture button press //_BIS_SR(LPM4_bits + GIE); //low power mode suspend(); } /* void Wheel(byte WheelPos, byte pdata[]) { //HSV color table thingy if(WheelPos < 85) { pdata[0] = WheelPos * 3; pdata[1] = 255 - WheelPos * 3; pdata[2] = 0; return; } else if(WheelPos < 170) { WheelPos -= 85; pdata[0] = 255 - WheelPos * 3; pdata[1] = 0; pdata[2] = WheelPos * 3; return; } else { WheelPos -= 170; pdata[0] = 0; pdata[1] = WheelPos * 3; pdata[2] = 255 - WheelPos * 3; return; } }*/ void fail(byte color) { //fail sound... #ifdef ACC //detachInterrupt(INT_BMA); delay(5); #endif for (byte i = 0; i < 5; i++) { if (color == RED) digitalWrite(LED_R, HIGH); else if (color == GREEN) digitalWrite(LED_G, HIGH); else if (color == BLUE) digitalWrite(LED_B, HIGH); #ifdef BUZZER tone(BUZZ, 3200); #endif delay(100); if (color == RED) digitalWrite(LED_R, LOW); if (color == GREEN) digitalWrite(LED_G, LOW); if (color == BLUE) digitalWrite(LED_B, LOW); noTone(BUZZ); delay(100); } #ifdef ACC delay(5); //attachInterrupt(INT_BMA, accFunction, FALLING); #endif } void wireFunction() //ISR { detachInterrupt(WIRE); wakeup(); noInterrupts(); wireInterrupt = true; } void buttonFunction() //ISR { wakeup(); noInterrupts(); buttonInterrupt = true; } void accFunction() //ISR { wakeup(); noInterrupts(); accInterrupt = true; } void startMelody() {} #define WINSLEEP 600 void winMelody() { tone(BUZZ, 196); delay(WINSLEEP/4); tone(BUZZ, 262); delay(WINSLEEP/4); tone(BUZZ, 330); delay(WINSLEEP/4); tone(BUZZ, 392); delay(WINSLEEP/4); tone(BUZZ, 523); delay(WINSLEEP/4); tone(BUZZ, 784); delay(WINSLEEP/2); tone(BUZZ, 659); delay(WINSLEEP/2); // put your setup code here, to run once: tone(BUZZ, 207); delay(WINSLEEP/4); tone(BUZZ, 261); delay(WINSLEEP/4); tone(BUZZ, 311); delay(WINSLEEP/4); tone(BUZZ, 415); delay(WINSLEEP/4); tone(BUZZ, 523); delay(WINSLEEP/4); tone(BUZZ, 622); delay(WINSLEEP/4); tone(BUZZ, 830); delay(WINSLEEP/2); tone(BUZZ, 659); delay(WINSLEEP/2); // put your setup code here, to run once: tone(BUZZ, 233); delay(WINSLEEP/4); tone(BUZZ, 293); delay(WINSLEEP/4); tone(BUZZ, 349); delay(WINSLEEP/4); tone(BUZZ, 466); delay(WINSLEEP/4); tone(BUZZ, 587); delay(WINSLEEP/4); tone(BUZZ, 698); delay(WINSLEEP/4); tone(BUZZ, 932); delay(WINSLEEP/2); noTone(BUZZ); delay(WINSLEEP/32); tone(BUZZ, 988); delay(WINSLEEP/4); noTone(BUZZ); delay(WINSLEEP/32); tone(BUZZ, 988); delay(WINSLEEP/4); noTone(BUZZ); delay(WINSLEEP/32); tone(BUZZ, 988); delay(WINSLEEP/4); noTone(BUZZ); delay(WINSLEEP/32); tone(BUZZ, 1046); delay(WINSLEEP); noTone(BUZZ); } /* __attribute__((interrupt(COMPARATORA_VECTOR))) //ISR void ComparatorISR(void) { wakeup(); noInterrupts(); wireInterrupt = true; } void enableComparator() { //TODO //WDTCTL = WDTPW + WDTHOLD; CACTL2 = CAF + P2CA0; //no short, CA0 on -, digital Filter CACTL1 = CAON + CAREF_3 + CAIE + CAIES; //comparator enabled, internal diode reference, comparator interrupt enabled, rising edge interrupt } */ uint16_t readBat() { for (byte i = 0; i < 3; i++) { //read multiple times for better Accuracy, espacially after deep sleep batVoltage = analogRead(ADC); delay(5); } if (batVoltage < 490) { errorBlink(4); deepSleep(); } return batVoltage; } void sendPackage(byte reason, uint16_t freq) { //package handler uint8_t bat = constrain(map(readBat(), 490, 615, 0, 99), 0, 99); #ifdef RADIO snprintf(payload, 28, "ID:%02d;INT:%02d;BAT:%02d;F:%03d;", NODEID, reason, bat, freq); radio.Wakeup(); radio.Send(GATEWAYID, payload, strlen(payload) + 1, requestACK); memset(payload, 0, sizeof(payload)); #if requestACK if (waitForAck()) Serial.print("ok!"); else { errorBlink(3); } #endif #endif } void errorBlink(byte code) { //error blink sequence for (byte i = 0; i < code; i++) { digitalWrite(LED_R, HIGH); #ifdef BUZZER tone(BUZZ, 3200); #endif delay(100); digitalWrite(LED_R, LOW); noTone(BUZZ); delay(100); } } void shutdownMelody() { tone(BUZZ, 1661); delay(300); tone(BUZZ, 1244); delay(300); tone(BUZZ, 830); delay(300); tone(BUZZ, 932); delay(300); noTone(BUZZ); } void bootMelody() { tone(BUZZ, 1661); delay(225); tone(BUZZ, 622); delay(150); tone(BUZZ, 932); delay(300); tone(BUZZ, 830); delay(450); tone(BUZZ, 1661); delay(300); tone(BUZZ, 932); delay(600); noTone(BUZZ); } #if requestACK // wait a few milliseconds for proper ACK, return true if received static bool waitForAck() { long now = millis(); while (millis() - now <= ACK_TIME) if (radio.ACKReceived(GATEWAYID)) return true; return false; } #endif void bma2XXclearInterrupts() { // clear interrupt enable flags writeBMA2XX(BMAREG_DETECT_OPTS1, 0x00); writeBMA2XX(BMAREG_DETECT_OPTS2, 0x00); // clear mapping writeBMA2XX(BMAREG_INT_MAP1, 0x00); writeBMA2XX(BMAREG_INT_MAP2, 0x00); writeBMA2XX(BMAREG_INT_MAP3, 0x00); // set pins tri-state writeBMA2XX(BMAREG_INTPIN_OPTS, (INTPIN_ACTIVE_LO<<INTPIN_INT1_ACTLVL) | (INTPIN_OPENDRIVE<<INTPIN_INT1_DRV) | // make pins active low and open-collector ~ tri-state (INTPIN_ACTIVE_LO<<INTPIN_INT2_ACTLVL) | (INTPIN_OPENDRIVE<<INTPIN_INT2_DRV) ); writeBMA2XX(BMAREG_INT_CTRL_LATCH, 1 << BMA_RESET_INT); // setting this clears any latched interrupts } void bma2XXsetProfile() { writeBMA2XX(BMAREG_SLEEP_DURATION, 0x00);// deactivate sleep mode delayMicroseconds(500); //SUSPEND/LPM1: a > 450us delay is required between writeBMA2XX transactions bma2XXclearInterrupts(); //perform a soft reset, wait >30ms writeBMA2XX(BMAREG_SOFTRESET, BMA_SOFTRESET_MAGICNUMBER); delay(50); //wait for soft reset to complete writeBMA2XX(BMAREG_BANDWIDTH, BW_500Hz); //500 Hz BW, 1000 samples per second writeBMA2XX(BMAREG_ACC_RANGE, ACC_2g); writeBMA2XX(BMAREG_INT_CTRL_LATCH, 0b1011); //set interrupt resetting behavior: temporary 1ms (active low) writeBMA2XX(BMAREG_DETECT_OPTS1, (1<<DO_FLAT_EN));//(1<<DO_SLOPE_Z_EN) | (1<<DO_SLOPE_Y_EN) | (1<<DO_SLOPE_X_EN) | (1<<DO_FLAT_EN)); //enable Slope and Flat Interrupt writeBMA2XX(BMAREG_SLOPE_THRESHOLD, (char)(15)); //configure slope detection: ds 4.8.5 writeBMA2XX(BMAREG_SLOW_THRESHOLD, (char)(10)); //configure slow motion detection writeBMA2XX(BMAREG_SLOPE_DURATION, 0b00001011); //configure slope detection: ds 4.8.5 writeBMA2XX(BMAREG_DETECT_OPTS3, (1<<DO_SLO_NO_MOT_SEL) | (1<<DO_SLO_NO_MOT_Z_EN)|(1<<DO_SLO_NO_MOT_X_EN)|(1<<DO_SLO_NO_MOT_Y_EN)); //no motion on all axis writeBMA2XX(BMAREG_INT_MAP1, 1<<MAP_INT1_FLAT | 1<<MAP_INT1_NO_MOTION | 1<<MAP_INT1_SLOPE); // ap FLAT and No motion interrupt to INT1 pin writeBMA2XX(BMAREG_INTPIN_OPTS, (INTPIN_ACTIVE_LO<<INTPIN_INT1_ACTLVL) | (INTPIN_PUSHPULL<<INTPIN_INT1_DRV) | (INTPIN_ACTIVE_LO<<INTPIN_INT2_ACTLVL) | (INTPIN_PUSHPULL<<INTPIN_INT2_DRV) ); //pins are active low and push-pull mode writeBMA2XX(BMAREG_SLEEP_DURATION, 1 << BMA_LOWPOWER_ENA); //go to low power Mode } char readBMA2XX(uint8_t address) { //returns the contents of any 1 byte register from any address char buf; START; SPI.transfer(address|READ); buf = SPI.transfer(0xFF); STOP; return buf; } void writeBMA2XX(uint8_t address, char data) { //write any data byte to any single address START; SPI.transfer(address); SPI.transfer(data); STOP; delayMicroseconds(2); }
mit
bitzesty/trade-tariff-frontend
spec/models/heading_spec.rb
660
require 'spec_helper' describe Heading do describe '#to_param' do let(:heading) { Heading.new(attributes_for(:heading).stringify_keys) } it 'returns heading code as param' do expect(heading.to_param).to eq heading.short_code end end describe '#commodity_code' do let(:heading) { Heading.new(attributes_for(:heading).stringify_keys) } it 'returns first ten symbols of code' do expect(heading.commodity_code).to eq heading.code.to_s.first(10) end end describe '#consigned?' do it 'returns false (there are no consigned declarable headings)' do expect(subject.consigned?).to be false end end end
mit
guigrpa/storyboard
packages/storyboard-examples/src/clientWithUpload.js
1634
/* eslint-env browser */ import { mainStory, chalk, addListener } from 'storyboard'; import browserExtensionListener from 'storyboard-listener-browser-extension'; import wsClientListener from 'storyboard-listener-ws-client'; require('babel-polyfill'); /* from root packages */ // eslint-disable-line require('isomorphic-fetch'); // for IE addListener(browserExtensionListener); addListener(wsClientListener, { uploadClientStories: true }); mainStory.info('client', 'Running client...'); const nodeButton = document.getElementById('refresh'); const nodeItems = document.getElementById('items'); nodeButton.addEventListener('click', () => refresh('Click on Refresh')); const refresh = async (storyTitle) => { const seq = Math.floor(Math.random() * 100); const story = mainStory.child({ src: 'client', title: `${storyTitle} (seq=${seq})` }); story.info('serverInterface', 'Fetching animals from server...'); nodeItems.innerHTML = 'Fetching...'; try { const response = await fetch(`/animals?seq=${seq}`, { method: 'post', headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ storyId: story.storyId }), }); const items = await response.json(); if (Array.isArray(items)) { story.info('serverInterface', `Fetched animals from server: ${chalk.cyan.bold(items.length)}`, { attach: items }); nodeItems.innerHTML = items.map((o) => `<li>${o}</li>`).join(''); } } finally { story.close(); } }; refresh('Initial fetch'); setInterval(() => mainStory.debug('Repeated message'), 5000);
mit
VitorCBSB/DinoReborn
src/systems/InputSystem.cpp
625
/* * InputSystem.cpp * * Created on: 15/07/2014 * Author: vitor */ #include "InputSystem.h" void InputSystem::process(double dt) { SDL_Event event; while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_QUIT: world_ptr.lock()->get_event_manager().broadcast<Quit>(); break; case SDL_KEYDOWN: if (!event.key.repeat) { world_ptr.lock()->get_event_manager().broadcast<KeyboardDown>( event.key.keysym.scancode); } break; case SDL_KEYUP: world_ptr.lock()->get_event_manager().broadcast<KeyboardUp>( event.key.keysym.scancode); break; default: break; } } }
mit
gibbok/dojo-keyboard-shortcuts
keysJs.js
2953
// module: // keysJs // summary: // Set of keycodes based on English keyboard. // description: // Common set of keycodes based on English keyboard. // Non-English keyboards are not mapped. // Any additional keys can be added in this module. define({ 3: "break", 8: "backspace / delete", 9: "tab", 12: 'clear', 13: "enter", 16: "shift", 17: "ctrl ", 18: "alt", 19: "pause/break", 20: "caps lock", 27: "escape", 32: "spacebar", 33: "page up", 34: "page down", 35: "end", 36: "home ", 37: "left arrow ", 38: "up arrow ", 39: "right arrow", 40: "down arrow ", 41: "select", 42: "print", 43: "execute", 44: "Print Screen", 45: "insert ", 46: "delete", 48: "0", 49: "1", 50: "2", 51: "3", 52: "4", 53: "5", 54: "6", 55: "7", 56: "8", 57: "9", 59: "semicolon (firefox), equals", 60: "<", 61: "equals (firefox)", 63: "ß", 65: "a", 66: "b", 67: "c", 68: "d", 69: "e", 70: "f", 71: "g", 72: "h", 73: "i", 74: "j", 75: "k", 76: "l", 77: "m", 78: "n", 79: "o", 80: "p", 81: "q", 82: "r", 83: "s", 84: "t", 85: "u", 86: "v", 87: "w", 88: "x", 89: "y", 90: "z", 91: "Windows Key / Left ⌘", 92: "right window key ", 93: "Windows Menu / Right ⌘", 96: "numpad 0 ", 97: "numpad 1 ", 98: "numpad 2 ", 99: "numpad 3 ", 100: "numpad 4 ", 101: "numpad 5 ", 102: "numpad 6 ", 103: "numpad 7 ", 104: "numpad 8 ", 105: "numpad 9 ", 106: "multiply ", 107: "add", 108: "numpad period (firefox)", 109: "subtract ", 110: "decimal point", 111: "divide ", 112: "f1 ", 113: "f2 ", 114: "f3 ", 115: "f4 ", 116: "f5 ", 117: "f6 ", 118: "f7 ", 119: "f8 ", 120: "f9 ", 121: "f10", 122: "f11", 123: "f12", 124: "f13", 125: "f14", 126: "f15", 127: "f16", 128: "f17", 129: "f18", 130: "f19", 144: "num lock ", 145: "scroll lock", 160: "^", 163: "#", 173: "minus (firefox), mute/unmute", 174: "decrease volume level", 175: "increase volume level", 176: "next", 177: "previous", 178: "stop", 179: "play/pause", 180: "e-mail", 181: "mute/unmute (firefox)", 182: "decrease volume level (firefox)", 183: "increase volume level (firefox)", 186: "semi-colon / ñ", 187: "equal sign ", 188: "comma", 189: "dash ", 190: "period ", 191: "forward slash", 192: "grave accent ", 194: "numpad period (chrome)", 219: "open bracket ", 220: "back slash ", 221: "close bracket ", 222: "single quote ", 223: "`", 224: "left or right ⌘ key (firefox)", 225: "altgr", 226: "< /git >", 230: "GNOME Compose Key", 255: "toggle touchpad" });
mit
pocky/user
src/User/Application/DTO/DisableUserDTO.php
367
<?php namespace Black\User\Application\DTO; /** * Class DisableUserDTO */ final class DisableUserDTO { /** * @var */ private $id; /** * @param $id */ public function __construct($id) { $this->id = $id; } /** * @return mixed */ public function getId() { return $this->id; } }
mit
YuChenTech/yilai
vendor/amranidev/scaffold-interface/src/Http/Controllers/GuiController.php
8717
<?php namespace Amranidev\ScaffoldInterface\Http\Controllers; use Amranidev\Ajaxis\Ajaxis; use Amranidev\ScaffoldInterface\Attribute; use Amranidev\ScaffoldInterface\Datasystem\Database\DatabaseManager; use Amranidev\ScaffoldInterface\Models\Relation; use Amranidev\ScaffoldInterface\Models\Scaffoldinterface; use AppController; use Illuminate\Http\Request; use Illuminate\Support\Facades\Artisan; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Schema; use Session; use URL; /** * Class GuiController. * * @author Amrani Houssain <[email protected]> */ class GuiController extends AppController { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $scaffold = Scaffoldinterface::paginate(6); $scaffoldList = DatabaseManager::tableNames(); return view('scaffold-interface::scaffoldApp', compact('scaffold', 'scaffoldList')); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * * @return \Illuminate\Http\Response */ public function store(Request $request) { app()->make('Request')->setRequest($request->toArray()); $scaffold = app()->make('Scaffold'); $relations = app()->make('Datasystem'); $scaffold->model()->views()->controller()->migration()->route(); $paths = app()->make('Path'); $names = app()->make('Parser'); $scaffoldInterface = new Scaffoldinterface(); $scaffoldInterface->migration = $paths->migrationPath; $scaffoldInterface->model = $paths->modelPath(); $scaffoldInterface->controller = $paths->controllerPath(); $scaffoldInterface->views = $paths->dirPath(); $scaffoldInterface->tablename = $names->plural(); $scaffoldInterface->package = config('amranidev.config.package'); $scaffoldInterface->save(); if ($relations->getForeignKeys()) { foreach ($relations->getForeignKeys() as $foreignKey) { $record = DB::table('scaffoldinterfaces')->where('tablename', $foreignKey)->first(); $relation = new Relation(); $relation->scaffoldinterface_id = $scaffoldInterface->id; $relation->to = $record->id; $relation->having = 'OneToMany'; $relation->save(); } } Session::flash('status', 'Created Successfully '.$names->singular()); return redirect('scaffold'); } /** * Remove the specified resource from storage. * * @param int $id * * @return \Illuminate\Http\Response */ public function destroy($id) { $scaffoldInterface = Scaffoldinterface::FindOrFail($id); unlink($scaffoldInterface->migration); unlink($scaffoldInterface->model); unlink($scaffoldInterface->controller); unlink($scaffoldInterface->views.'/index.blade.php'); unlink($scaffoldInterface->views.'/create.blade.php'); unlink($scaffoldInterface->views.'/show.blade.php'); unlink($scaffoldInterface->views.'/edit.blade.php'); rmdir($scaffoldInterface->views); //Clear Routes Resources $this->clearRoutes(lcfirst(str_singular($scaffoldInterface->tablename))); $scaffoldInterface->delete(); Session::flash('status', 'Deleted Successfully'); return URL::to('scaffold'); } /** * Delete confirmation message by ajaxis. * * @link https://github.com/amranidev/ajaxis * * @return \Illuminate\Http\Response */ public function deleteMsg($id) { $scaffold = Scaffoldinterface::FindOrFail($id); if (Schema::hasTable($scaffold->tablename)) { $table = $scaffold->tablename; return view('scaffold-interface::template.DeleteMessage.delete', compact('table'))->render(); } $msg = Ajaxis::Mtdeleting('Warning!!', "Would you like to delete {$scaffold->tablename} MVC files ??", '/scaffold/guirollback/'.$id); return $msg; } /** * Get attributes. * * @param string $table * * @return \Illuminate\Http\Response */ public function getResult($table, Request $request) { $attributes = new Attribute($table); if ($request->ajax()) { return $attributes->getAttributes(); } } /** * Migrate schema. * * @return \Illuminate\Http\Response */ public function migrate() { try { Artisan::call('migrate', ['--path' => config('amranidev.config.database')]); exec('cd '.base_path().' && composer dump-autoload'); } catch (\Exception $e) { return $e->getMessage(); } $Msg = str_replace("\n", '', Artisan::output()); Session::flash('status', $Msg); return redirect('scaffold'); } /** * Rollback schema. * * @throws Exception * * @return \Illuminate\Http\Response */ public function rollback() { try { if (!Scaffoldinterface::all()->count()) { throw new \Exception('Nothing to rollback'); } Artisan::call('migrate:rollback'); } catch (\Exception $e) { return $e->getMessage(); } $Msg = str_replace("\n", '', Artisan::output()); Session::flash('status', $Msg); return redirect('scaffold'); } /** * Clear routes. * * @param string $remove * * @return mixed */ private function clearRoutes($remove) { $path = config('amranidev.config.routes'); $lines = file($path, FILE_IGNORE_NEW_LINES); foreach ($lines as $key => $line) { if (strstr($line, $remove)) { unset($lines[$key]); } } $data = implode("\n", array_values($lines)); return file_put_contents($path, $data); } /** * ManyToMany form. * * @param \Illuminate\Http\Request * * @return \Illuminate\Http\Response */ public function manyToManyForm(Request $request) { $dummyData = DatabaseManager::tableNames(); $elements = Ajaxis::MtcreateFormModal([ ['type' => 'select', 'name' => 'table1', 'key' => 'table1', 'value' => $dummyData], ['type' => 'select', 'name' => 'table2', 'key' => 'table2', 'value' => $dummyData], ], '/scaffold/manyToMany', 'Many To Many'); return $elements; } /** * ManyToMany generate. * * @param \Illuminate\Http\Request * * @return \Illuminate\Http\Response */ public function manyToMany(Request $request) { if ($this->check($request->toArray())) { Session::flash('status', 'Error! could not be related'); return redirect('scaffold'); } $table1 = DB::table('scaffoldinterfaces')->where('tablename', $request->toArray()['table1'])->first(); $table2 = DB::table('scaffoldinterfaces')->where('tablename', $request->toArray()['table2'])->first(); $manytomany = new \Amranidev\ScaffoldInterface\ManyToMany\ManyToMany($request->except('_token')); $manytomany->burn(); // save the relationship $relation = new Relation(); $relation->scaffoldinterface_id = $table1->id; $relation->to = $table2->id; $relation->having = 'ManyToMany'; $relation->save(); Session::flash('status', 'ManyToMany generated successfully'); return redirect('/scaffold'); } /** * Check ManyToMany request which is it available to use. * * @param array $request * * @return mixed */ private function check(array $request) { return $request['table1'] == $request['table2'] ? true : false; } /** * Transform entities to a grahp. * * @return \Illuminate\Http\Response */ public function graph() { $entities = Scaffoldinterface::all(); $relations = Relation::all(); $nodes = collect([]); $edges = collect([]); foreach ($entities as $entity) { $nodes->push(['id' => $entity->id, 'label' => $entity->tablename]); } foreach ($relations as $relation) { $edges->push(['from' => $relation->scaffoldinterface_id, 'to' => $relation->to, 'label' => $relation->having]); } $nodes = $nodes->toJson(); $edges = $edges->toJson(); return view('scaffold-interface::graph', compact('nodes', 'edges')); } }
mit
cloudcmd/gritty
test/client/get-el.js
574
'use strict'; const test = require('supertape'); const stub = require('@cloudcmd/stub'); const getEl = require('../../client/get-el'); test('gritty: get-el: object', (t) => { const el = {}; t.equal(getEl(el), el, 'should return el'); t.end(); }); test('gritty: get-el: string', (t) => { const el = 'hello'; const querySelector = stub(); global.document = { querySelector, }; getEl(el); t.calledWith(querySelector, [el], 'should call querySelector'); delete global.document; t.end(); });
mit
aleacoin/aleacoin-release
src/qt/locale/bitcoin_fi.ts
130862
<?xml version="1.0" ?><!DOCTYPE TS><TS language="fi" version="2.1"> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About Aleacoin</source> <translation>Tietoa Aleacoinista</translation> </message> <message> <location line="+39"/> <source>&lt;b&gt;Aleacoin&lt;/b&gt; version</source> <translation>&lt;b&gt;Aleacoin&lt;/b&gt; versio</translation> </message> <message> <location line="+41"/> <source>Copyright © 2009-2014 The Bitcoin developers Copyright © 2012-2014 The NovaCoin developers Copyright © 2014 The Aleacoin developers</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <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 kokeellista ohjelmistoa. 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ä tuote sisältää OpenSSL-projektin kehittämää ohjelmistoa OpenSSL-työkalupakettia varten (http://www.openssl.org/), Eric Youngin ([email protected]) kehittämän salausohjelmiston sekä Thomas Bernardin UPnP-ohjelmiston. </translation> </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="+22"/> <source>Double-click to edit address or label</source> <translation>Kaksoisnapauta muokataksesi osoitetta tai nimikettä</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 järjestelmän leikepöydälle</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation>&amp;Uusi osoite</translation> </message> <message> <location line="-46"/> <source>These are your Aleacoin 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 Aleacoin-osoitteesi rahansiirtojen vastaanottoa varten. Jos haluat, voit antaa jokaiselle lähettäjälle oman osoitteen jotta voit pitää kirjaa sinulle rahaa siirtäneistä henkilöistä.</translation> </message> <message> <location line="+60"/> <source>&amp;Copy Address</source> <translation>&amp;Kopioi osoite</translation> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation>Näytä &amp;QR-koodi</translation> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a Aleacoin address</source> <translation>Allekirjoita viesti osoittaaksesi Aleacoin-osoitteesi omistajuus</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>Allekirjoita &amp;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="-14"/> <source>Verify a message to ensure it was signed with a specified Aleacoin address</source> <translation>Vahvista viesti varmistaaksesi että kyseinen Aleacoin-osoitteesi on allekirjoittanut sen</translation> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation>&amp;Varmista viesti</translation> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>&amp;Poista</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+65"/> <source>Copy &amp;Label</source> <translation>Kopioi &amp;nimi</translation> </message> <message> <location line="+2"/> <source>&amp;Edit</source> <translation>&amp;Muokkaa</translation> </message> <message> <location line="+250"/> <source>Export Address Book Data</source> <translation>Vie osoitekirjasta tietoja</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Pilkuilla eroteltu tiedosto (*.csv)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation>Virhe vietäessä</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>Syötä 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>Toista uusi tunnuslause uudelleen</translation> </message> <message> <location line="+33"/> <source>Serves to disable the trivial sendmoney when OS account compromised. Provides no real security.</source> <translation>Sallii estettäväksi yksinkertaiset rahansiirrot kun käyttöjärjestelmän käyttäjätunnuksen turvallisuutta on rikottu. Tämä ei takaa oikeasti turvallisuutta.</translation> </message> <message> <location line="+3"/> <source>For staking only</source> <translation>Vain osakkuutta varten</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+35"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>Anna lompakolle uusi tunnuslause.&lt;br/&gt;Käytä tunnuslausetta, jossa on ainakin &lt;b&gt;10 satunnaista merkkiä&lt;/b&gt; tai &lt;b&gt;kahdeksan sanaa&lt;/b&gt;.</translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>Salaa lompakko</translation> </message> <message> <location line="+7"/> <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 lukituksestaan</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 &lt;b&gt;LOSE ALL OF YOUR COINS&lt;/b&gt;!</source> <translation>Varoitus: Jos salaat lompakkosi ja hukkaat salasanasi, &lt;b&gt;MENETÄT KAIKKI KOLIKKOSI&lt;/b&gt;!</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 tulisi korvata uusilla suojatuilla varmuuskopioilla. Turvallisuussyistä edelliset varmuuskopiot muuttuvat käyttökelvottomiksi, kun aloitat uuden salatun lompakon käytön.</translation> </message> <message> <location line="+103"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation>Varoitus: Caps Lock-näppäin on käytössä!</translation> </message> <message> <location line="-133"/> <location line="+60"/> <source>Wallet encrypted</source> <translation>Lompakko salattu</translation> </message> <message> <location line="-58"/> <source>Aleacoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your coins from being stolen by malware infecting your computer.</source> <translation>Aleacoin-ohjelma sulkee itsensä päättääkseen salauksen luonnin. Muista, että lompakon salaaminen ei täysin turvaa kolikoitasi haittaohjelmien aiheuttamien varkauksien uhalta.</translation> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+44"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>Lompakon salaus epäonnistui</translation> </message> <message> <location line="-56"/> <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="+50"/> <source>The supplied passphrases do not match.</source> <translation>Annetut tunnuslauseet eivät täsmää.</translation> </message> <message> <location line="-38"/> <source>Wallet unlock failed</source> <translation>Lompakon avaaminen epäonnistui.</translation> </message> <message> <location line="+1"/> <location line="+12"/> <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="+282"/> <source>Sign &amp;message...</source> <translation>Allekirjoita &amp;viesti...</translation> </message> <message> <location line="+251"/> <source>Synchronizing with network...</source> <translation>Synkronoidaan verkon kanssa...</translation> </message> <message> <location line="-319"/> <source>&amp;Overview</source> <translation>&amp;Yleisnäkymä</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation>Lompakon tilanteen yleiskatsaus</translation> </message> <message> <location line="+17"/> <source>&amp;Transactions</source> <translation>&amp;Rahansiirrot</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>Selaa rahansiirtohistoriaa</translation> </message> <message> <location line="+5"/> <source>&amp;Address Book</source> <translation>%Osoitekirja</translation> </message> <message> <location line="+1"/> <source>Edit the list of stored addresses and labels</source> <translation>Muokkaa tallennettujen osoitteiden ja nimien listaa</translation> </message> <message> <location line="-13"/> <source>&amp;Receive coins</source> <translation>&amp;Vastaanota kolikoita</translation> </message> <message> <location line="+1"/> <source>Show the list of addresses for receiving payments</source> <translation>Näytä osoitelista vastaanottaaksesi maksuja</translation> </message> <message> <location line="-7"/> <source>&amp;Send coins</source> <translation>&amp;Lähetä kolikoita</translation> </message> <message> <location line="+35"/> <source>E&amp;xit</source> <translation>L&amp;opeta</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>Sulje ohjelma</translation> </message> <message> <location line="+6"/> <source>Show information about Aleacoin</source> <translation>Näytä tietoja Aleacoinista</translation> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>Tietoja &amp;Qt</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>Näytä tietoja Qt:sta</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>&amp;Asetukset...</translation> </message> <message> <location line="+4"/> <source>&amp;Encrypt Wallet...</source> <translation>&amp;Salaa lompakko...</translation> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation>&amp;Varmuuskopioi lompakko...</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>&amp;Vaihda tunnuslause...</translation> </message> <message numerus="yes"> <location line="+259"/> <source>~%n block(s) remaining</source> <translation><numerusform>~%n lohko jäljellä</numerusform><numerusform>~%n lohkoa jäljellä</numerusform></translation> </message> <message> <location line="+6"/> <source>Downloaded %1 of %2 blocks of transaction history (%3% done).</source> <translation>Ladattu %1 lohkoa %2 lohkosta rahansiirtohistoriassa (%3% ladattu).</translation> </message> <message> <location line="-256"/> <source>&amp;Export...</source> <translation>Vie...</translation> </message> <message> <location line="-64"/> <source>Send coins to a Aleacoin address</source> <translation>Lähetä kolikkoja Aleacoin osoitteeseen</translation> </message> <message> <location line="+47"/> <source>Modify configuration options for Aleacoin</source> <translation>Mukauta Aleacoinin konfigurointiasetuksia</translation> </message> <message> <location line="+18"/> <source>Export the data in the current tab to a file</source> <translation>Vie data tämänhetkisestä välilehdestä tiedostoon</translation> </message> <message> <location line="-14"/> <source>Encrypt or decrypt wallet</source> <translation>Salaa tai pura salaus lompakosta</translation> </message> <message> <location line="+3"/> <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="+10"/> <source>&amp;Debug window</source> <translation>&amp;Testausikkuna</translation> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation>Avaa debuggaus- ja diagnostiikkakonsoli</translation> </message> <message> <location line="-5"/> <source>&amp;Verify message...</source> <translation>&amp;Vahvista viesti...</translation> </message> <message> <location line="-202"/> <source>Aleacoin</source> <translation>Aleacoin</translation> </message> <message> <location line="+0"/> <source>Wallet</source> <translation>Lompakko</translation> </message> <message> <location line="+180"/> <source>&amp;About Aleacoin</source> <translation>&amp;Tietoa Aleacoinista</translation> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation>&amp;Näytä / Piilota</translation> </message> <message> <location line="+9"/> <source>Unlock wallet</source> <translation>Avaa Lompakko</translation> </message> <message> <location line="+1"/> <source>&amp;Lock Wallet</source> <translation>&amp;Lukitse Lompakko</translation> </message> <message> <location line="+1"/> <source>Lock wallet</source> <translation>Lukitse lompakko</translation> </message> <message> <location line="+35"/> <source>&amp;File</source> <translation>&amp;Tiedosto</translation> </message> <message> <location line="+8"/> <source>&amp;Settings</source> <translation>&amp;Asetukset</translation> </message> <message> <location line="+8"/> <source>&amp;Help</source> <translation>&amp;Apua</translation> </message> <message> <location line="+12"/> <source>Tabs toolbar</source> <translation>Välilehtipalkki</translation> </message> <message> <location line="+8"/> <source>Actions toolbar</source> <translation>Toimintopalkki</translation> </message> <message> <location line="+13"/> <location line="+9"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> <message> <location line="+0"/> <location line="+60"/> <source>Aleacoin client</source> <translation>Aleacoin-asiakas</translation> </message> <message numerus="yes"> <location line="+75"/> <source>%n active connection(s) to Aleacoin network</source> <translation><numerusform>%n aktiivinen yhteys Aleacoin-verkkoon</numerusform><numerusform>%n aktiivista yhteyttä Aleacoin-verkkoon</numerusform></translation> </message> <message> <location line="+40"/> <source>Downloaded %1 blocks of transaction history.</source> <translation>Ladattu %1 lohkoa rahansiirtohistoriasta.</translation> </message> <message> <location line="+413"/> <source>Staking.&lt;br&gt;Your weight is %1&lt;br&gt;Network weight is %2&lt;br&gt;Expected time to earn reward is %3</source> <translation>Osakkaana.&lt;br&gt;Osuutesi on %1&lt;br&gt;Verkon osuus on %2&lt;br&gt;Odotettu aika palkkion ansaitsemiselle on %3</translation> </message> <message> <location line="+6"/> <source>Not staking because wallet is locked</source> <translation>Ei osakkaana koska lompakko on lukittu</translation> </message> <message> <location line="+2"/> <source>Not staking because wallet is offline</source> <translation>Ei osakkaana koska lompakko on offline-tilassa</translation> </message> <message> <location line="+2"/> <source>Not staking because wallet is syncing</source> <translation>Ei osakkaana koska lompakko synkronoituu</translation> </message> <message> <location line="+2"/> <source>Not staking because you don&apos;t have mature coins</source> <translation>Ei osakkaana koska sinulle ei ole erääntynyt kolikoita</translation> </message> <message numerus="yes"> <location line="-403"/> <source>%n second(s) ago</source> <translation><numerusform>%n sekunti sitten</numerusform><numerusform>%n sekuntia sitten</numerusform></translation> </message> <message> <location line="-312"/> <source>About Aleacoin card</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show information about Aleacoin card</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>&amp;Unlock Wallet...</source> <translation>&amp;Aukaise lompakko</translation> </message> <message numerus="yes"> <location line="+297"/> <source>%n minute(s) ago</source> <translation><numerusform>%n minuutti sitten</numerusform><numerusform>%n minuuttia sitten</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n hour(s) ago</source> <translation><numerusform>%n tunti sitten</numerusform><numerusform>%n tuntia sitten</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s) ago</source> <translation><numerusform>%n päivä sitten</numerusform><numerusform>%n päivää sitten</numerusform></translation> </message> <message> <location line="+6"/> <source>Up to date</source> <translation>Rahansiirtohistoria on ajan tasalla</translation> </message> <message> <location line="+7"/> <source>Catching up...</source> <translation>Saavutetaan verkkoa...</translation> </message> <message> <location line="+10"/> <source>Last received block was generated %1.</source> <translation>Viimeinen vastaanotettu lohko generoitu %1.</translation> </message> <message> <location line="+59"/> <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>Tämä rahansiirto ylittää siirtorajan. Voit silti lähettää sen %1 rahansiirtopalkkiota vastaan, joka siirretään rahansiirtoasi käsitteleville solmuille jotta se auttaisi ja tukisi verkkoa. Haluatko maksaa rahansiirtopalkkion?</translation> </message> <message> <location line="+5"/> <source>Confirm transaction fee</source> <translation>Hyväksy rahansiirtopalkkio</translation> </message> <message> <location line="+27"/> <source>Sent transaction</source> <translation>Lähetetyt rahansiirrot</translation> </message> <message> <location line="+1"/> <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="+100"/> <location line="+15"/> <source>URI handling</source> <translation>URI-merkkijonojen käsittely</translation> </message> <message> <location line="-15"/> <location line="+15"/> <source>URI can not be parsed! This can be caused by an invalid Aleacoin address or malformed URI parameters.</source> <translation>URI-merkkijonoa ei voida jäsentää! Tämä voi johtua väärästä Aleacoin-osoitteesta tai väärässä muodossa olevista URI-parametreistä.</translation> </message> <message> <location line="+18"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>Lompakko on &lt;b&gt;salattu&lt;/b&gt; ja tällä hetkellä &lt;b&gt;avoinna&lt;/b&gt;</translation> </message> <message> <location line="+10"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>Lompakko on &lt;b&gt;salattu&lt;/b&gt; ja tällä hetkellä &lt;b&gt;lukittuna&lt;/b&gt;</translation> </message> <message> <location line="+25"/> <source>Backup Wallet</source> <translation>Varmuuskopioi lompakkosi</translation> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation>Lompakkodata (*.dat)</translation> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation>Varmuuskopion luonti epäonnistui</translation> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation>Virhe tallentaessa lompakkotiedostoa uuteen sijaintiinsa.</translation> </message> <message numerus="yes"> <location line="+76"/> <source>%n second(s)</source> <translation><numerusform>%n sekunti</numerusform><numerusform>%n sekuntia</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n minute(s)</source> <translation><numerusform>%n minuutti</numerusform><numerusform>%n minuuttia</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <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><numerusform>%n päivä</numerusform><numerusform>%n päivää</numerusform></translation> </message> <message> <location line="+18"/> <source>Not staking</source> <translation>Ei osakkaana</translation> </message> <message> <location filename="../bitcoin.cpp" line="+109"/> <source>A fatal error occurred. Aleacoin can no longer continue safely and will quit.</source> <translation>Vakava virhe kohdattu. Aleacoin-ohjelma ei voi enää jatkaa turvallisesti ja sulkee itsensä.</translation> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+90"/> <source>Network Alert</source> <translation>Verkkohälytys</translation> </message> </context> <context> <name>CoinControlDialog</name> <message> <location filename="../forms/coincontroldialog.ui" line="+14"/> <source>Coin Control</source> <translation>Rahan hallinta</translation> </message> <message> <location line="+31"/> <source>Quantity:</source> <translation>Määrä:</translation> </message> <message> <location line="+32"/> <source>Bytes:</source> <translation>Tavua:</translation> </message> <message> <location line="+48"/> <source>Amount:</source> <translation>Määrä:</translation> </message> <message> <location line="+32"/> <source>Priority:</source> <translation>Prioriteetti:</translation> </message> <message> <location line="+48"/> <source>Fee:</source> <translation>Kulu:</translation> </message> <message> <location line="+35"/> <source>Low Output:</source> <translation>Heikko ulosanti:</translation> </message> <message> <location filename="../coincontroldialog.cpp" line="+551"/> <source>no</source> <translation>ei</translation> </message> <message> <location filename="../forms/coincontroldialog.ui" line="+51"/> <source>After Fee:</source> <translation>Kulujen jälkeen:</translation> </message> <message> <location line="+35"/> <source>Change:</source> <translation>Vaihdos:</translation> </message> <message> <location line="+69"/> <source>(un)select all</source> <translation>(tai ei)Valitse kaikki</translation> </message> <message> <location line="+13"/> <source>Tree mode</source> <translation>Puunäkymä</translation> </message> <message> <location line="+16"/> <source>List mode</source> <translation>Listanäkymä</translation> </message> <message> <location line="+45"/> <source>Amount</source> <translation>Määrä</translation> </message> <message> <location line="+5"/> <source>Label</source> <translation>Nimike</translation> </message> <message> <location line="+5"/> <source>Address</source> <translation>Osoite</translation> </message> <message> <location line="+5"/> <source>Date</source> <translation>Päivämäärä</translation> </message> <message> <location line="+5"/> <source>Confirmations</source> <translation>Vahvistukset</translation> </message> <message> <location line="+3"/> <source>Confirmed</source> <translation>Vahvistettu</translation> </message> <message> <location line="+5"/> <source>Priority</source> <translation>Prioriteetti</translation> </message> <message> <location filename="../coincontroldialog.cpp" line="-515"/> <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"/> <location line="+26"/> <source>Copy amount</source> <translation>Kopioi määrä</translation> </message> <message> <location line="-25"/> <source>Copy transaction ID</source> <translation>Kopioi siirtotunnus</translation> </message> <message> <location line="+24"/> <source>Copy quantity</source> <translation>Kopioi määrä</translation> </message> <message> <location line="+2"/> <source>Copy fee</source> <translation>Kopioi kulu</translation> </message> <message> <location line="+1"/> <source>Copy after fee</source> <translation>Kopioi kulun jälkeen</translation> </message> <message> <location line="+1"/> <source>Copy bytes</source> <translation>Kopioi tavuja</translation> </message> <message> <location line="+1"/> <source>Copy priority</source> <translation>Kopioi prioriteetti</translation> </message> <message> <location line="+1"/> <source>Copy low output</source> <translation>Kopioi heikko ulosanti</translation> </message> <message> <location line="+1"/> <source>Copy change</source> <translation>Kopioi vaihdos</translation> </message> <message> <location line="+317"/> <source>highest</source> <translation>korkein</translation> </message> <message> <location line="+1"/> <source>high</source> <translation>korkea</translation> </message> <message> <location line="+1"/> <source>medium-high</source> <translation>keskikorkea</translation> </message> <message> <location line="+1"/> <source>medium</source> <translation>keski</translation> </message> <message> <location line="+4"/> <source>low-medium</source> <translation>keskimatala</translation> </message> <message> <location line="+1"/> <source>low</source> <translation>matala</translation> </message> <message> <location line="+1"/> <source>lowest</source> <translation>matalin</translation> </message> <message> <location line="+155"/> <source>DUST</source> <translation>pölyä</translation> </message> <message> <location line="+0"/> <source>yes</source> <translation>kyllä</translation> </message> <message> <location line="+10"/> <source>This label turns red, if the transaction size is bigger than 10000 bytes. This means a fee of at least %1 per kb is required. Can vary +/- 1 Byte per input.</source> <translation>Tämä nimike muuttuu punaiseksi, jos rahansiirron koko on suurempi kuin 10000 tavua. Tämä tarkoittaa, että ainakin %1 rahansiirtopalkkio per kilotavu tarvitaan. Voi vaihdella välillä +/- 1 Tavu per syöte.</translation> </message> <message> <location line="+1"/> <source>Transactions with higher priority get more likely into a block. This label turns red, if the priority is smaller than &quot;medium&quot;. This means a fee of at least %1 per kb is required.</source> <translation>Suuremman prioriteetin rahansiirrot pääsevät suuremmalla todennäköisyydellä lohkoketjuun. Tämä nimike muuttuu punaiseksi, jos prioriteetti on pienempi kuin &quot;keskikokoinen&quot;. Tämä tarkoittaa, että ainakin %1 rahansiirtopalkkio per kilotavu tarvitaan.</translation> </message> <message> <location line="+1"/> <source>This label turns red, if any recipient receives an amount smaller than %1. This means a fee of at least %2 is required. Amounts below 0.546 times the minimum relay fee are shown as DUST.</source> <translation>Tämä nimike muuttuu punaiseksi, jos jokin asiakas saa pienemmän määrän kuin %1. Tämä tarkoittaa, että ainakin %2 rahansiirtopalkkio tarvitaan. Määrät alle 0.546 kertaa pienimmän rahansiirtokulun verran näytetään pölynä.</translation> </message> <message> <location line="+1"/> <source>This label turns red, if the change is smaller than %1. This means a fee of at least %2 is required.</source> <translation>Tämä nimike muuttuu punaiseksi, jos vaihdos on pienempi kuin %1. Tämä tarkoittaa, että ainakin %2 rahansiirtopalkkio tarvitaan.</translation> </message> <message> <location line="+37"/> <location line="+66"/> <source>(no label)</source> <translation>(ei nimeä)</translation> </message> <message> <location line="-9"/> <source>change from %1 (%2)</source> <translation>vaihdos %1 (%2)</translation> </message> <message> <location line="+1"/> <source>(change)</source> <translation>(vaihdos)</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>&amp;Label</source> <translation>&amp;Nimi</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation>Tämän syötteen nimike osoitekirjassa</translation> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>&amp;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>Tämän syötteen nimike osoitekirjassa. Nimikettä voidaan muuttaa vain lähetysosoitteille.</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="+20"/> <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 &quot;%1&quot; is already in the address book.</source> <translation>Osoite &quot;%1&quot; on jo osoitekirjassa.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid Aleacoin address.</source> <translation>Syöttämäsi osoite &quot;%1&quot; ei ole hyväksytty Aleacoin-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="+420"/> <location line="+12"/> <source>Aleacoin-Qt</source> <translation>Aleacoin-Qt</translation> </message> <message> <location line="-12"/> <source>version</source> <translation>versio</translation> </message> <message> <location line="+2"/> <source>Usage:</source> <translation>Kulutus:</translation> </message> <message> <location line="+1"/> <source>command-line options</source> <translation>komentokehotteen asetukset</translation> </message> <message> <location line="+4"/> <source>UI options</source> <translation>Käyttäjärajapinnan asetukset</translation> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation>Aseta kieli, esimerkiksi &quot;fi_FI&quot; (oletus: järjestelmän oma)</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ä logo 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>&amp;Main</source> <translation>&amp;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. Fee 0.01 recommended.</source> <translation>Vapaavalintainen rahansiirtopalkkio kilotavua kohden auttaa varmistamaan että rahansiirtosi käsitellään nopeasti. Suurin osa rahansiirroista on alle yhden kilotavun. Palkkiota 0.01 suositellaan.</translation> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation>Maksa rahansiirtopalkkio</translation> </message> <message> <location line="+31"/> <source>Reserved amount does not participate in staking and is therefore spendable at any time.</source> <translation>Varattu määrä ei vaadi osakkuutta jonka vuoksi se on mahdollista käyttää milloin tahansa.</translation> </message> <message> <location line="+15"/> <source>Reserve</source> <translation>Varattuna</translation> </message> <message> <location line="+31"/> <source>Automatically start Aleacoin after logging in to the system.</source> <translation>Käynnistä Aleacoin-asiakasohjelma automaattisesti kun olet kirjautunut järjestelmään.</translation> </message> <message> <location line="+3"/> <source>&amp;Start Aleacoin on system login</source> <translation>%Käynnistä Aleacoin-asiakasohjelma kirjautuessasi</translation> </message> <message> <location line="+7"/> <source>Detach block and address databases at shutdown. This means they can be moved to another data directory, but it slows down shutdown. The wallet is always detached.</source> <translation>Irroita lohko- ja osoitetietokannat lopetettaessa. Tämä tarkoittaa, että tietokannat voidaan siirtää eri hakemistoon mutta se hidastaa ohjelman sammumista. Lompakko on aina irroitettuna.</translation> </message> <message> <location line="+3"/> <source>&amp;Detach databases at shutdown</source> <translation>%Irroita tietokannat lopetettaessa</translation> </message> <message> <location line="+21"/> <source>&amp;Network</source> <translation>&amp;Verkko</translation> </message> <message> <location line="+6"/> <source>Automatically open the Aleacoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation>Avaa Aleacoin-asiakkaalle automaattisesti portti reitittimestä. Tämä toimii vain, kun reitittimesi tukee UPnP:tä ja se on aktivoituna.</translation> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation>Portin uudelleenohjaus &amp;UPnP:llä</translation> </message> <message> <location line="+7"/> <source>Connect to the Aleacoin network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation>Yhdistä Aleacoin-verkkoon SOCKS-välityspalvelimen lävitse. (esim. yhdistettäessä Tor:n läpi).</translation> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation>%Yhdistä SOCKS-välityspalvelimen läpi:</translation> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation>Proxyn &amp;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>&amp;Port:</source> <translation>&amp;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 &amp;Version:</source> <translation>SOCKS &amp;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>&amp;Window</source> <translation>&amp;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>&amp;Minimize to the tray instead of the taskbar</source> <translation>&amp;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ää Bitcoin-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&amp;inimize on close</source> <translation>P&amp;ienennä suljettaessa</translation> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation>&amp;Käyttöliittymä</translation> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation>&amp;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 Aleacoin.</source> <translation>Käyttöliittymän kieli voidaan valita tästä. Tämä asetus tulee voimaan vasta Aleacoin-asiakasohjelman uudelleenkäynnistyksen jälkeen.</translation> </message> <message> <location line="+11"/> <source>&amp;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 Aleacoin addresses in the transaction list or not.</source> <translation>Näytä tai piilota Aleacoin-osoitteet rahansiirtolistassa.</translation> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation>&amp;Näytä osoitteet rahansiirrot listassa</translation> </message> <message> <location line="+7"/> <source>Whether to show coin control features or not.</source> <translation>Näytä tai piilota rahanhallintaominaisuudet.</translation> </message> <message> <location line="+3"/> <source>Display coin &amp;control features (experts only!)</source> <translation>Näytä rahan&amp;hallinnan ominaisuudet (vain kokeneille käyttäjille!)</translation> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation>&amp;OK</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>&amp;Peruuta</translation> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation>%Käytä</translation> </message> <message> <location filename="../optionsdialog.cpp" line="+55"/> <source>default</source> <translation>oletus</translation> </message> <message> <location line="+149"/> <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 Aleacoin.</source> <translation>Tämä asetus tulee voimaan vasta Aleacoin-asiakasohjelman uudelleenkäynnistyksen jälkeen.</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="+33"/> <location line="+231"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the Aleacoin network after a connection is established, but this process has not completed yet.</source> <translation>Näytettävät tiedot voivat olla vanhentuneet. Lompakkosi synkronoituu automaattisesti Aleacoin-verkon kanssa kun yhteys on muodostettu, mutta tätä prosessia ei ole viety vielä päätökseen.</translation> </message> <message> <location line="-160"/> <source>Stake:</source> <translation>Vaihdos:</translation> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation>Hyväksymätöntä:</translation> </message> <message> <location line="-107"/> <source>Wallet</source> <translation>Lompakko</translation> </message> <message> <location line="+49"/> <source>Spendable:</source> <translation>Käytettävissä:</translation> </message> <message> <location line="+16"/> <source>Your current spendable balance</source> <translation>Käytettävissä olevat varat:</translation> </message> <message> <location line="+71"/> <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="+20"/> <source>Total:</source> <translation>Yhteensä:</translation> </message> <message> <location line="+16"/> <source>Your current total balance</source> <translation>Tililläsi tällä hetkellä olevien Bitcoinien määrä</translation> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Viimeisimmät rahansiirrot&lt;/b&gt;</translation> </message> <message> <location line="-108"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation>Kaikki vahvistamattomat rahansiirrot yhteensä, joita ei vielä lasketa saldoosi.</translation> </message> <message> <location line="-29"/> <source>Total of coins that was staked, and do not yet count toward the current balance</source> <translation>Kolikoiden kokoinaismäärä, jotka eivät vielä ole laskettu tämänhetkiseen saldoon.</translation> </message> <message> <location filename="../overviewpage.cpp" line="+113"/> <location line="+1"/> <source>out of sync</source> <translation>Ei ajan tasalla</translation> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation>QR-koodidialogi</translation> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation>Pyydä rahansiirtoa</translation> </message> <message> <location line="+56"/> <source>Amount:</source> <translation>Määrä:</translation> </message> <message> <location line="-44"/> <source>Label:</source> <translation>Nimike:</translation> </message> <message> <location line="+19"/> <source>Message:</source> <translation>Viesti:</translation> </message> <message> <location line="+71"/> <source>&amp;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 koodatessa linkkiä QR-koodiin.</translation> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation>Syötetty määrä on epäkelpoinen; tarkista.</translation> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation>Tuloksena liian pitkä URI, yritä lyhentää nimikkeen tai viestin pituutta.</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="+348"/> <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>&amp;Information</source> <translation>T&amp;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>Testiverkossa</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>&amp;Open</source> <translation>&amp;Avaa</translation> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation>Komentokehotteen ominaisuudet</translation> </message> <message> <location line="+7"/> <source>Show the Aleacoin-Qt help message to get a list with possible Aleacoin command-line options.</source> <translation>Näytä Aleacoin-Qt:n avustusohje saadaksesi listan käytettävistä Aleacoinin komentokehotteen määritteistä.</translation> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation>%Näytä</translation> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation>&amp;Konsoli</translation> </message> <message> <location line="-260"/> <source>Build date</source> <translation>Kääntöpäiväys</translation> </message> <message> <location line="-104"/> <source>Aleacoin - Debug window</source> <translation>Aleacoin - Debug-ikkuna</translation> </message> <message> <location line="+25"/> <source>Aleacoin Core</source> <translation>Aleacoinin ydin</translation> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation>Debug lokitiedosto</translation> </message> <message> <location line="+7"/> <source>Open the Aleacoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation>Avaa Aleacoin-asiakasohjelman debug-lokitiedosto nykyisestä hakemistostaan. Tämä voi kestää muutaman sekunnin avattaessa suuria lokitiedostoja.</translation> </message> <message> <location line="+102"/> <source>Clear console</source> <translation>Tyhjennä konsoli</translation> </message> <message> <location filename="../rpcconsole.cpp" line="-33"/> <source>Welcome to the Aleacoin RPC console.</source> <translation>Tervetuloa Aleacoinin RPC-konsoliin.</translation> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation>Ylös- ja alas-nuolet selaavat historiaa ja &lt;b&gt;Ctrl-L&lt;/b&gt; tyhjentää ruudun.</translation> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation>Kirjoita &lt;b&gt;help&lt;/b&gt; 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="+182"/> <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="+76"/> <source>Coin Control Features</source> <translation>Kolikoidenhallinnan ominaisuudet</translation> </message> <message> <location line="+20"/> <source>Inputs...</source> <translation>Syötteet...</translation> </message> <message> <location line="+7"/> <source>automatically selected</source> <translation>automaattisesti valittu</translation> </message> <message> <location line="+19"/> <source>Insufficient funds!</source> <translation>Ei tarpeeksi varoja!</translation> </message> <message> <location line="+77"/> <source>Quantity:</source> <translation>Määrä:</translation> </message> <message> <location line="+22"/> <location line="+35"/> <source>0</source> <translation>0</translation> </message> <message> <location line="-19"/> <source>Bytes:</source> <translation>Tavua:</translation> </message> <message> <location line="+51"/> <source>Amount:</source> <translation>Määrä:</translation> </message> <message> <location line="+22"/> <location line="+86"/> <location line="+86"/> <location line="+32"/> <source>0.00 ALEA</source> <translation>123.456 ALEA {0.00 ?}</translation> </message> <message> <location line="-191"/> <source>Priority:</source> <translation>Prioriteetti:</translation> </message> <message> <location line="+19"/> <source>medium</source> <translation>keskikokoinen</translation> </message> <message> <location line="+32"/> <source>Fee:</source> <translation>Kulu:</translation> </message> <message> <location line="+35"/> <source>Low Output:</source> <translation>Heikko ulosanti:</translation> </message> <message> <location line="+19"/> <source>no</source> <translation>ei</translation> </message> <message> <location line="+32"/> <source>After Fee:</source> <translation>Kulujen jälkeen:</translation> </message> <message> <location line="+35"/> <source>Change</source> <translation>Vaihtoraha</translation> </message> <message> <location line="+50"/> <source>custom change address</source> <translation>erikseen määritetty vaihtorahaosoite</translation> </message> <message> <location line="+106"/> <source>Send to multiple recipients at once</source> <translation>Lähetä monelle vastaanottajalle</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation>Lisää &amp;Vastaanottaja</translation> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation>Tyhjennä kaikki rahansiirtokentät</translation> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation>&amp;Tyhjennnä Kaikki</translation> </message> <message> <location line="+28"/> <source>Balance:</source> <translation>Saldo:</translation> </message> <message> <location line="+16"/> <source>123.456 ALEA</source> <translation>123.456 ALEA</translation> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation>Vahvista lähetys</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>&amp;Lähetä</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-173"/> <source>Enter a Aleacoin address (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source> <translation>Syötä Aleacoin-osoite (esim. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</translation> </message> <message> <location line="+15"/> <source>Copy quantity</source> <translation>Kopioi määrä</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Kopioi määrä</translation> </message> <message> <location line="+1"/> <source>Copy fee</source> <translation>Kopioi rahansiirtokulu</translation> </message> <message> <location line="+1"/> <source>Copy after fee</source> <translation>Kopioi rahansiirtokulun jälkeen</translation> </message> <message> <location line="+1"/> <source>Copy bytes</source> <translation>Kopioi tavuja</translation> </message> <message> <location line="+1"/> <source>Copy priority</source> <translation>Kopioi prioriteetti</translation> </message> <message> <location line="+1"/> <source>Copy low output</source> <translation>Kopioi heikko ulosanti</translation> </message> <message> <location line="+1"/> <source>Copy change</source> <translation>Kopioi vaihtoraha</translation> </message> <message> <location line="+86"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation>&lt;b&gt;%1&lt;/b&gt;:sta %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>Oletko varma että haluat lähettää %1?</translation> </message> <message> <location line="+0"/> <source> and </source> <translation>ja</translation> </message> <message> <location line="+29"/> <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>Virhe: Rahansiirron luonti epäonnistui.</translation> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation>Virhe: Rahansiirto evätty. Tämä voi tapahtua kun jotkut kolikot lompakossasi ovat jo käytetty, kuten myös tilanteessa jos käytit wallet.dat-tiedoston kopiota ja rahat olivat käytetty kopiossa, mutta eivät ole merkitty käytetyiksi tässä.</translation> </message> <message> <location line="+251"/> <source>WARNING: Invalid Aleacoin address</source> <translation>VAROITUS: Epäkelpo Aleacoin-osoite</translation> </message> <message> <location line="+13"/> <source>(no label)</source> <translation>(ei nimeä)</translation> </message> <message> <location line="+4"/> <source>WARNING: unknown change address</source> <translation>VAROITUS: Tuntematon vaihtorahaosoite</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation>Kaavake</translation> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>M&amp;äärä:</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>Maksun saaja:</translation> </message> <message> <location line="+24"/> <location filename="../sendcoinsentry.cpp" line="+25"/> <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="+9"/> <source>&amp;Label:</source> <translation>&amp;Nimi:</translation> </message> <message> <location line="+18"/> <source>The address to send the payment to (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source> <translation>Osoite, johon maksu lähetetään (esim. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</translation> </message> <message> <location line="+10"/> <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 tämä vastaanottaja</translation> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a Aleacoin address (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source> <translation>Syötä Aleacoin-osoite (esim. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</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"/> <location line="+124"/> <source>&amp;Sign Message</source> <translation>&amp;Allekirjoita viesti</translation> </message> <message> <location line="-118"/> <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, ettet allekirjoita mitään epämääräistä, sillä phishing-hyökkääjät voivat yrittää huijata sinua allekirjoittamaan henkilöllisyytesi heidän hyväksi. Allekirjoita vain se, mihin olet sitoutunut.</translation> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source> <translation>Osoite, jolle viesti kirjataan (esim. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</translation> </message> <message> <location line="+10"/> <location line="+203"/> <source>Choose an address from the address book</source> <translation>Valitse osoite osoitekirjasta</translation> </message> <message> <location line="-193"/> <location line="+203"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="-193"/> <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 viesti, jonka haluat allekirjoittaa tähän</translation> </message> <message> <location line="+24"/> <source>Copy the current signature to the system clipboard</source> <translation>Kopioi tämänhetkinen allekirjoitus järjestelmän leikepöydälle</translation> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this Aleacoin address</source> <translation>Allekirjoita viesti vahvistaaksesi, että omistat tämän Aleacoin-osoitteen</translation> </message> <message> <location line="+17"/> <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 &amp;All</source> <translation>&amp;Tyhjennä Kaikki</translation> </message> <message> <location line="-87"/> <location line="+70"/> <source>&amp;Verify Message</source> <translation>&amp;Varmista viesti</translation> </message> <message> <location line="-64"/> <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. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source> <translation>Osoite, jolla viesti on allekirjoitettu (esim. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX) </translation> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified Aleacoin address</source> <translation>Vahvista viesti varmistaaksesi että se on allekirjoitettu kyseisellä Aleacoin-osoitteella</translation> </message> <message> <location line="+17"/> <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 Aleacoin address (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source> <translation>Syötä Aleacoin-osoite (esim. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</translation> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation>Klikkaa &quot;Allekirjoita Viesti luodaksesi allekirjoituksen </translation> </message> <message> <location line="+3"/> <source>Enter Aleacoin signature</source> <translation>Syötä Aleacoin-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>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+19"/> <source>Open until %1</source> <translation>Avoinna %1 asti</translation> </message> <message numerus="yes"> <location line="-2"/> <source>Open for %n block(s)</source> <translation><numerusform>Avoinna %n:lle lohkolle</numerusform><numerusform>Avoinna %n lohkolle</numerusform></translation> </message> <message> <location line="+8"/> <source>conflicted</source> <translation>törmännyt</translation> </message> <message> <location line="+2"/> <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 110 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation>Luotujen kolikoiden on eräännyttävä 510 lohkon ajan ennenkuin niitä voidaan käyttää. Kun loit tämän lohkon, se oli lähetetty verkkoon lohkoketjuun lisättäväksi. Jos lohkon siirtyminen ketjuun epäonnistuu, tilaksi muuttuu &quot;ei hyväksytty&quot; ja sillon sitä ei voida käyttää. Tämä voi tapahtua joskus jos toinen verkon noodi luo lohkon muutaman sekunnin sisällä luodusta lohkostasi.</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="+5"/> <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="-211"/> <source>, has not been successfully broadcast yet</source> <translation>, ei ole vielä onnistuneesti lähetetty</translation> </message> <message> <location line="+35"/> <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="+226"/> <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> <location line="+60"/> <source>Open until %1</source> <translation>Avoinna %1 asti</translation> </message> <message> <location line="+12"/> <source>Confirmed (%1 confirmations)</source> <translation>Vahvistettu (%1 vahvistusta)</translation> </message> <message numerus="yes"> <location line="-15"/> <source>Open for %n more block(s)</source> <translation><numerusform>Avoinna %n lohkolle</numerusform><numerusform>Avoinna %n lohkolle</numerusform></translation> </message> <message> <location line="+6"/> <source>Offline</source> <translation>Offline-tila</translation> </message> <message> <location line="+3"/> <source>Unconfirmed</source> <translation>Vahvistamaton</translation> </message> <message> <location line="+3"/> <source>Confirming (%1 of %2 recommended confirmations)</source> <translation>Vahvistetaan (%1 %2:sta suositellusta vahvistuksesta)</translation> </message> <message> <location line="+6"/> <source>Conflicted</source> <translation>Törmännyt</translation> </message> <message> <location line="+3"/> <source>Immature (%1 confirmations, will be available after %2)</source> <translation>Ei vahvistettu (%1 vahvistusta, on saatavilla %2:n jälkeen)</translation> </message> <message> <location line="+3"/> <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="+42"/> <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="+190"/> <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 Bitcoin-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="+55"/> <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>Kopioi rahansiirron ID</translation> </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="+144"/> <source>Export Transaction Data</source> <translation>Vie tiedot rahansiirrosta</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 vietäessä</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="+206"/> <source>Sending...</source> <translation>Lähetetään...</translation> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+33"/> <source>Aleacoin version</source> <translation>Aleacoinin versio</translation> </message> <message> <location line="+1"/> <source>Usage:</source> <translation>Käyttö:</translation> </message> <message> <location line="+1"/> <source>Send command to -server or aleacoind</source> <translation>Syötä komento kohteeseen -server tai aleacoind</translation> </message> <message> <location line="+1"/> <source>List commands</source> <translation>Lista komennoista</translation> </message> <message> <location line="+1"/> <source>Get help for a command</source> <translation>Hanki apua käskyyn</translation> </message> <message> <location line="+2"/> <source>Options:</source> <translation>Asetukset:</translation> </message> <message> <location line="+2"/> <source>Specify configuration file (default: aleacoin.conf)</source> <translation>Määritä asetustiedosto (oletus: aleacoin.conf)</translation> </message> <message> <location line="+1"/> <source>Specify pid file (default: aleacoind.pid)</source> <translation>Määritä prosessitiedosto (oletus: aleacoin.pid)</translation> </message> <message> <location line="+2"/> <source>Specify wallet file (within data directory)</source> <translation>Määritä lompakkotiedosto (datahakemiston sisällä)</translation> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>Määritä data-hakemisto</translation> </message> <message> <location line="+2"/> <source>Set database cache size in megabytes (default: 25)</source> <translation>Aseta tietokannan välimuistin koko megatavuina (oletus: 25)</translation> </message> <message> <location line="+1"/> <source>Set database disk log size in megabytes (default: 100)</source> <translation>Aseta tietokannan lokien maksimikoko megatavuissa (oletus: 100)</translation> </message> <message> <location line="+6"/> <source>Listen for connections on &lt;port&gt; (default: 15714 or testnet: 25714)</source> <translation>Kuuntele yhteyksiä portissa &lt;port&gt; (oletus: 15714 tai testiverkko: 25714)</translation> </message> <message> <location line="+1"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>Pidä enintään &lt;n&gt; yhteyttä verkkoihin (oletus: 125)</translation> </message> <message> <location line="+3"/> <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="+1"/> <source>Specify your own public address</source> <translation>Määritä julkinen osoitteesi</translation> </message> <message> <location line="+5"/> <source>Bind to given address. Use [host]:port notation for IPv6</source> <translation>Liitä annettuun osoitteeseen. Käytä [host]:port merkintää IPv6:lle</translation> </message> <message> <location line="+2"/> <source>Stake your coins to support network and gain reward (default: 1)</source> <translation>Panosta rahasi tukeaksi verkkoa ja saadaksesi palkkiota (oletus: 1)</translation> </message> <message> <location line="+5"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>Kynnysarvo aikakatkaisulle heikosti toimiville verkoille (oletus: 100)</translation> </message> <message> <location line="+1"/> <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="-44"/> <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="+51"/> <source>Detach block and address databases. Increases shutdown time (default: 0)</source> <translation>Irroita lohko- ja osoitetietokannat lopetuksessa. Nostaa ohjelman lopetusaikaa (oletus: 0)</translation> </message> <message> <location line="+109"/> <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 on evätty. Tämä voi tapahtua jos joitakin kolikoistasi lompakossasi on jo käytetty, tai jos olet käyttänyt wallet.dat-tiedoston kopiota ja rahat olivat käytetyt kopiossa, mutta ei merkitty käytetyksi tässä.</translation> </message> <message> <location line="-5"/> <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>Virhe: Tämä rahansiirto tarvitsee rahansiirtopalkkion, kooltaan %s, kokonsa, monimutkaisuutensa tai aikaisemmin saatujen varojen käytön takia.</translation> </message> <message> <location line="-87"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 15715 or testnet: 25715)</source> <translation>Kuuntele JSON-RPC-yhteyksiä portissa &lt;port&gt; (oletus: 15715 tai testiverkko: 25715)</translation> </message> <message> <location line="-11"/> <source>Accept command line and JSON-RPC commands</source> <translation>Hyväksy merkkipohjaiset- ja JSON-RPC-käskyt</translation> </message> <message> <location line="+101"/> <source>Error: Transaction creation failed </source> <translation>Virhe: Rahansiirron luonti epäonnistui</translation> </message> <message> <location line="-5"/> <source>Error: Wallet locked, unable to create transaction </source> <translation>Virhe: Lompakko lukittu, rahansiirtoa ei voida luoda</translation> </message> <message> <location line="-8"/> <source>Importing blockchain data file.</source> <translation>Tuodaan lohkoketjun datatiedostoa.</translation> </message> <message> <location line="+1"/> <source>Importing bootstrap blockchain data file.</source> <translation>Tuodaan esilatausohjelma lohkoketjun datatiedostolle.</translation> </message> <message> <location line="-88"/> <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="+1"/> <source>Use the test network</source> <translation>Käytä test -verkkoa</translation> </message> <message> <location line="-24"/> <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="-38"/> <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="+117"/> <source>Error initializing database environment %s! To recover, BACKUP THAT DIRECTORY, then remove everything from it except for wallet.dat.</source> <translation>Virhe alustettaessa tietokantaympäristöä %s! Palauttaaksesi sen, TEE VARMUUSKOPIO HAKEMISTOSTA ja poista tämän jälkeen kaikki hakemiston tiedostot paitsi wallet.dat-tiedosto.</translation> </message> <message> <location line="-20"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation>Aseta maksimikoko korkean prioriteetin/pienen siirtokulun maksutapahtumille tavuina (oletus: 27000)</translation> </message> <message> <location line="+11"/> <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="+61"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong Aleacoin will not work properly.</source> <translation>Varoitus: Tarkista, että tietokoneesi aika ja päivämäärä ovat oikeassa! Jos kellosi on väärässä, Aleacoin ei toimi oikein.</translation> </message> <message> <location line="-31"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation>Varoitus: Virhe luettaessa wallet.dat-tiedostoa! Kaikki avaimet luettiin oikein, mutta rahansiirtodata tai osoitekirjan kentät voivat olla puuttuvat tai väärät.</translation> </message> <message> <location line="-18"/> <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>Varoitus: wallet.dat-tiedosto on korruptoitunut, data pelastettu! Alkuperäinen wallet.dat on tallennettu nimellä wallet.{aikaleima}.bak kohteeseen %s; Jos saldosi tai rahansiirrot ovat väärät, sinun tulee palauttaa lompakko varmuuskopiosta.</translation> </message> <message> <location line="-30"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation>Yritetään palauttaa yksityisiä salausavaimia korruptoituneesta wallet.dat-tiedostosta</translation> </message> <message> <location line="+4"/> <source>Block creation options:</source> <translation>Lohkon luonnin asetukset:</translation> </message> <message> <location line="-62"/> <source>Connect only to the specified node(s)</source> <translation>Yhidstä ainoastaan määrättyihin noodeihin</translation> </message> <message> <location line="+4"/> <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="+94"/> <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="-90"/> <source>Find peers using DNS lookup (default: 1)</source> <translation>Etsi vertaisiasi käyttäen DNS-nimihakua (oletus: 1)</translation> </message> <message> <location line="+5"/> <source>Sync checkpoints policy (default: strict)</source> <translation>Synkronoi tallennuspisteiden käytännöt (oletus: strict)</translation> </message> <message> <location line="+83"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation>Epäkelpo -tor-osoite: &apos;%s&apos;</translation> </message> <message> <location line="+4"/> <source>Invalid amount for -reservebalance=&lt;amount&gt;</source> <translation>Epäkelpo määrä -reservebalance=&lt;amount&gt;</translation> </message> <message> <location line="-82"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation>Suurin vastaanottopuskuri yksittäiselle yhteydelle, &lt;n&gt;*1000 tavua (vakioasetus: 5000)</translation> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation>Suurin lähetyspuskuri yksittäiselle yhteydelle, &lt;n&gt;*1000 tavua (vakioasetus: 1000)</translation> </message> <message> <location line="-16"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation>Yhdistä vain noodeihin verkossa &lt;net&gt; (IPv4, IPv6 tai Tor)</translation> </message> <message> <location line="+28"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation>Tulosta lisäksi debug-tietoa, seuraa kaikkia muita -debug*-asetuksia</translation> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation>Tulosta lisäksi verkon debug-tietoa</translation> </message> <message> <location line="+1"/> <source>Prepend debug output with timestamp</source> <translation>Lisää debug-tulosteiden alkuun aikaleimat</translation> </message> <message> <location line="+35"/> <source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source> <translation>SSL asetukset (katso Bitcoin Wikistä tarkemmat SSL ohjeet)</translation> </message> <message> <location line="-74"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation>Valitse SOCKS-välityspalvelimen versio (4-5, oletus 5)</translation> </message> <message> <location line="+41"/> <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ä debug-tuloste kehittäjille</translation> </message> <message> <location line="+28"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation>Aseta lohkon maksimikoko tavuissa (oletus: 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="-29"/> <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="-42"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation>Määritä yhteyden aikakataisu millisekunneissa (vakioasetus: 5000)</translation> </message> <message> <location line="+109"/> <source>Unable to sign checkpoint, wrong checkpointkey? </source> <translation>Ei voitu kirjata tallennuspistettä, väärä checkpointkey? </translation> </message> <message> <location line="-80"/> <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="-25"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation>Käytä välityspalvelinta saavuttaaksesi tor:n piilotetut palvelut (oletus: sama kuin -proxy)</translation> </message> <message> <location line="+42"/> <source>Username for JSON-RPC connections</source> <translation>Käyttäjätunnus JSON-RPC-yhteyksille</translation> </message> <message> <location line="+47"/> <source>Verifying database integrity...</source> <translation>Tarkistetaan tietokannan eheyttä...</translation> </message> <message> <location line="+57"/> <source>WARNING: syncronized checkpoint violation detected, but skipped!</source> <translation>VAROITUS: synkronoidun tallennuspisteen rikkomista havaittu, mutta ohitettu!</translation> </message> <message> <location line="+1"/> <source>Warning: Disk space is low!</source> <translation>Varoitus: Kiintolevytila on vähissä!</translation> </message> <message> <location line="-2"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation>Varoitus: Tämä versio on vanhentunut, päivitys tarpeen!</translation> </message> <message> <location line="-48"/> <source>wallet.dat corrupt, salvage failed</source> <translation>wallet.dat on korruptoitunut, pelastusyritys epäonnistui</translation> </message> <message> <location line="-54"/> <source>Password for JSON-RPC connections</source> <translation>Salasana JSON-RPC-yhteyksille</translation> </message> <message> <location line="-84"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=aleacoinrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;Aleacoin Alert&quot; [email protected] </source> <translation>%s, sinun on asetettava rpcpassword asetustiedostoon: %s On suositeltavaa, että käytät seuraavaa arvottua salasanaa: rpcuser=aleacoinrpc rpcpassword=%s (Sinun ei tarvitse muistaa tätä salasanaa) Käyttäjänimen ja salasanan EI TULE OLLA SAMOJA. Jos tiedostoa ei ole olemassa, luo se asettaen samalla omistajan lukuoikeudet. On myös suositeltavaa asettaa alertnotify jolloin olet tiedotettu ongelmista; esimerkiksi: alertnotify=echo %%s | mail -s &quot;Aleacoin Alert&quot; [email protected] </translation> </message> <message> <location line="+51"/> <source>Find peers using internet relay chat (default: 0)</source> <translation>Etsi vertaisiasi käyttäen Internet Relay Chatia (oletus: 1) {0)?}</translation> </message> <message> <location line="+5"/> <source>Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)</source> <translation>Synkronoi kello muiden noodien kanssa. Poista käytöstä, jos järjestelmäsi aika on tarkka esim. päivittää itsensä NTP-palvelimelta. (oletus: 1)</translation> </message> <message> <location line="+15"/> <source>When creating transactions, ignore inputs with value less than this (default: 0.01)</source> <translation>Rahansiirtoja luodessa jätä huomioimatta syötteet joiden arvo on vähemmän kuin tämä (oletus: 0.01)</translation> </message> <message> <location line="+16"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>Salli JSON-RPC yhteydet tietystä ip-osoitteesta</translation> </message> <message> <location line="+1"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>Lähetä käskyjä solmuun osoitteessa &lt;ip&gt; (oletus: 127.0.0.1)</translation> </message> <message> <location line="+1"/> <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="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation>Suorita komento kun lompakon rahansiirrossa muutoksia (%s komennossa on korvattu TxID:llä)</translation> </message> <message> <location line="+3"/> <source>Require a confirmations for change (default: 0)</source> <translation>Vaadi vaihtorahalle vahvistus (oletus: 0)</translation> </message> <message> <location line="+1"/> <source>Enforce transaction scripts to use canonical PUSH operators (default: 1)</source> <translation>Vahvista, että rahansiirtoskriptit käyttävät sääntöjen mukaisia PUSH-toimijoita (oletus: 1)</translation> </message> <message> <location line="+2"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation>Suorita komento kun olennainen varoitus on saatu (%s komennossa korvattu viestillä)</translation> </message> <message> <location line="+3"/> <source>Upgrade wallet to latest format</source> <translation>Päivitä lompakko uusimpaan formaattiin</translation> </message> <message> <location line="+1"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>Aseta avainpoolin koko arvoon &lt;n&gt; (oletus: 100)</translation> </message> <message> <location line="+1"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>Skannaa uudelleen lohkoketju lompakon puuttuvien rahasiirtojen vuoksi</translation> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 2500, 0 = all)</source> <translation>Kuinka monta lohkoa tarkistetaan käynnistyksen yhteydessä (oletus: 2500, 0 = kaikki)</translation> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-6, default: 1)</source> <translation>Kuinka perusteellisesti lohko vahvistetaan (0-6, oletus: 1)</translation> </message> <message> <location line="+1"/> <source>Imports blocks from external blk000?.dat file</source> <translation>Tuo lohkoja erillisestä blk000?.dat-tiedostosta</translation> </message> <message> <location line="+8"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>Käytä OpenSSL:ää (https) JSON-RPC-yhteyksille</translation> </message> <message> <location line="+1"/> <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="+1"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation>Hyväksytyt salaustyypit (oletus: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation> </message> <message> <location line="+53"/> <source>Error: Wallet unlocked for staking only, unable to create transaction.</source> <translation>Virhe: Lompakko avattu vain osakkuutta varten, rahansiirtoja ei voida luoda.</translation> </message> <message> <location line="+18"/> <source>WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.</source> <translation>VAROITUS: Epäkelpo tarkistuspiste löydetty! Ilmoitetut rahansiirrot eivät välttämättä pidä paikkaansa! Sinun täytyy päivittää asiakasohjelma, tai ilmoittaa kehittäjille ongelmasta.</translation> </message> <message> <location line="-158"/> <source>This help message</source> <translation>Tämä ohjeviesti</translation> </message> <message> <location line="+95"/> <source>Wallet %s resides outside data directory %s.</source> <translation>Lompakko %s on datahakemiston %s ulkopuolella.</translation> </message> <message> <location line="+1"/> <source>Cannot obtain a lock on data directory %s. Aleacoin is probably already running.</source> <translation>Ei voida saavuttaa lukkoa datatiedostossa %s. Aleacoin-asiakasohjelma on ehkä jo käynnissä.</translation> </message> <message> <location line="-98"/> <source>Aleacoin</source> <translation>Aleacoin</translation> </message> <message> <location line="+140"/> <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="-130"/> <source>Connect through socks proxy</source> <translation>Yhdistä SOCKS-välityspalvelimen lävitse</translation> </message> <message> <location line="+3"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>Salli DNS kyselyt -addnode, -seednode ja -connect yhteydessä</translation> </message> <message> <location line="+122"/> <source>Loading addresses...</source> <translation>Ladataan osoitteita...</translation> </message> <message> <location line="-15"/> <source>Error loading blkindex.dat</source> <translation>Virhe ladattaessa blkindex.dat-tiedostoa</translation> </message> <message> <location line="+2"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>Virhe ladattaessa wallet.dat-tiedostoa: Lompakko vioittunut</translation> </message> <message> <location line="+4"/> <source>Error loading wallet.dat: Wallet requires newer version of Aleacoin</source> <translation>Virhe ladattaessa wallet.dat-tiedostoa: Lompakko tarvitsee uudemman version Aleacoin-asiakasohjelmasta</translation> </message> <message> <location line="+1"/> <source>Wallet needed to be rewritten: restart Aleacoin to complete</source> <translation>Lompakko on kirjoitettava uudelleen: käynnistä Aleacoin-asiakasohjelma uudelleen päättääksesi toiminnon</translation> </message> <message> <location line="+1"/> <source>Error loading wallet.dat</source> <translation>Virhe ladattaessa wallet.dat-tiedostoa</translation> </message> <message> <location line="-16"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation>Virheellinen proxy-osoite &apos;%s&apos;</translation> </message> <message> <location line="-1"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation>Tuntematon verkko -onlynet parametrina: &apos;%s&apos;</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="+4"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation>-bind osoitteen &apos;%s&apos; selvittäminen epäonnistui</translation> </message> <message> <location line="+2"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation>-externalip osoitteen &apos;%s&apos; selvittäminen epäonnistui</translation> </message> <message> <location line="-24"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>-paytxfee=&lt;amount&gt;: &apos;%s&apos; on virheellinen</translation> </message> <message> <location line="+44"/> <source>Error: could not start node</source> <translation>Virhe: Ei voitu käynnistää noodia</translation> </message> <message> <location line="+11"/> <source>Sending...</source> <translation>Lähetetään...</translation> </message> <message> <location line="+5"/> <source>Invalid amount</source> <translation>Virheellinen määrä</translation> </message> <message> <location line="+1"/> <source>Insufficient funds</source> <translation>Lompakon saldo ei riitä</translation> </message> <message> <location line="-34"/> <source>Loading block index...</source> <translation>Ladataan lohkoindeksiä...</translation> </message> <message> <location line="-103"/> <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="+122"/> <source>Unable to bind to %s on this computer. Aleacoin is probably already running.</source> <translation>Ei voitu liittää %s tällä tietokoneella. Aleacoin-asiakasohjelma on jo ehkä päällä.</translation> </message> <message> <location line="-97"/> <source>Fee per KB to add to transactions you send</source> <translation>Rahansiirtopalkkio kilotavua kohden lähetettäviin rahansiirtoihisi</translation> </message> <message> <location line="+55"/> <source>Invalid amount for -mininput=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Epäkelpo määrä parametrille -mininput=&lt;amount&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+25"/> <source>Loading wallet...</source> <translation>Ladataan lompakkoa...</translation> </message> <message> <location line="+8"/> <source>Cannot downgrade wallet</source> <translation>Et voi päivittää lompakkoasi vanhempaan versioon</translation> </message> <message> <location line="+1"/> <source>Cannot initialize keypool</source> <translation>Ei voida alustaa avainallasta</translation> </message> <message> <location line="+1"/> <source>Cannot write default address</source> <translation>Oletusosoitetta ei voi kirjoittaa</translation> </message> <message> <location line="+1"/> <source>Rescanning...</source> <translation>Skannataan uudelleen...</translation> </message> <message> <location line="+5"/> <source>Done loading</source> <translation>Lataus on valmis</translation> </message> <message> <location line="-167"/> <source>To use the %s option</source> <translation>Käytä %s optiota</translation> </message> <message> <location line="+14"/> <source>Error</source> <translation>Virhe</translation> </message> <message> <location line="+6"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation>Sinun täytyy asettaa rpcpassword=&lt;password&gt; asetustiedostoon: %s Jos tiedostoa ei ole, niin luo se ainoastaan omistajan kirjoitusoikeuksin.</translation> </message> </context> </TS>
mit
heisedebaise/ranch
ranch-paypal/src/main/java/org/lpw/ranch/paypal/NotExistsValidatorImpl.java
768
package org.lpw.ranch.paypal; import org.lpw.tephra.ctrl.validate.ValidateWrapper; import org.lpw.tephra.ctrl.validate.ValidatorSupport; import org.springframework.stereotype.Controller; import javax.inject.Inject; /** * @author lpw */ @Controller(PaypalService.VALIDATOR_NOT_EXISTS) public class NotExistsValidatorImpl extends ValidatorSupport { @Inject private PaypalService paypalService; @Override public boolean validate(ValidateWrapper validate, String[] parameters) { PaypalModel paypal = paypalService.findByAppId(parameters[1]); return paypal == null || paypal.getKey().equals(parameters[0]); } @Override protected String getDefaultFailureMessageKey() { return PaypalModel.NAME + ".exists"; } }
mit
teco-kit/jActivity
node/features/audiolevel.destroy.js
42
meter.stopListening(); meter.disconnect();
mit
alex-ta/Chat-Server
server/config.js
344
module.exports = { jwtSecret: 'somesecretkeyforjsonwebtoken', databaseUrl: 'mongodb://localhost/chatdb', serverPort: 3000, chatLimit: 5, url: { logout: '/logout', login: '/login', exists: '/exists', success: '/', failure: '/login', signup: '/signup', authenticated: '/auth', avatarUrl: '/avatar' } }
mit
J-Y/RubyQuiz
ruby_quiz/quiz49_sols/solutions/Brian Schroeder/adventure-refaktored.rb
12065
#!/usr/bin/ruby # # This is a refaktored version of the lisp tutorial at # # http://www.lisperati.com/casting.html # # into the ruby programming language. # # This code is under the ruby licence. # # The code can be found at http://ruby.brian-schroeder.de/quiz/adventure/ # A Thing in the adventure world. Parallel to an object in the lisp version. Thing = Struct.new(:name, :description, :portable) # Maps objects that have a key to the object using the key converted by a # block. If no block is given the key is converted using to_s.downcase # # This is a method that generates a FuzzyIndexedList class specialized for one # index and a transformation proc def FuzzyIndexedList(key, &key_transform_proc) key = key.to_sym key_transform_proc = key_transform_proc || lambda { | x | x.to_s.downcase } result = Class.new result.module_eval do include Enumerable def initialize @data = {} end define_method(:<<) do | object | @data[key_transform_proc[object.send(key)]] = object self end define_method(:[]) do | name | @data[key_transform_proc[name]] end define_method(:delete) do | key_or_object | key_or_object = key_or_object.send(key) if key_or_object.respond_to?key @data.delete(key_transform_proc[key_or_object]) end def each @data.each do | _, object | yield object end end end result end ThingList = FuzzyIndexedList(:name) Connection = Struct.new(:direction, :passage, :next_room) ConnectionList = FuzzyIndexedList(:direction) class Room attr_reader :name, :description, :connections, :things def initialize(name, description = "") @name = name @description = description @connections = ConnectionList.new @things = ThingList.new yield self if block_given? end end Map = FuzzyIndexedList(:name) # We can inherit adventures from this class. WizardsHouse is the adventure from # the lisp tutorial. A game action can be defined by a triplet of functions # named # action_name # action_name_help # action_name_complete # where the first defines the action, the second returns a description of the # action and a usage string and the third is used for auto completion. # # To see this in action take a look at the #action_look_at, # #action_look_at_help and #action_look_at_complete functions. # # The adventure is interpreted by the Interpreter class using a readline # interface. class Adventure attr_reader :map, :location, :held_things def commands methods.select{ | method | /^action_/ =~ method and not /action_(.*)(_complete|_help)/ =~ method }.map{ | method | method.sub(/^action_/, '') }.sort end def location=(location) location = location.name if location.respond_to?:name raise "Location not in map" unless @map[location] @location = @map[location] end # Create the adventure world def initialize @map = Map.new @held_things = ThingList.new end def describe_location @location.description end def describe_paths @location.connections.map { | connection | "There is a #{connection.passage} going #{connection.direction} from here." } end def describe_floor @location.things.map { | object | "You see #{object.description}." } end def have(object) @held_things[object] end def action_help descriptions = commands.map { | cmd | respond_to?("action_#{cmd}_help") ? send("action_#{cmd}_help") : ["Description missing for #{cmd}", ""] } max_usage_width = descriptions.map { | _, usage | usage.length }.max max_description_width = descriptions.map { | description, _ | description.length }.max [ 'You can do the following things', "", " Usage ".ljust(max_usage_width+4) + "Description", "-" * (max_usage_width + 4 + max_description_width) ] + descriptions.map { | description, usage | " #{usage}".ljust(max_usage_width+4) + description } end def action_help_help ["Show this help", "help"] end # Helper function to create actions that are applied to two objects and are # dependent on a specific place. # # Defines all three helper functions for the action, though the help # description is a bit ugly. def self.def_combine_action(command, subject, object, place, &block) #define_method("__action_#{command}", &block) #private "__action_#{command}" define_method("action_#{command}") do | subject_, object_ | if have(subject) and self.location.name == place and subject_.to_s.downcase == subject.to_s.downcase and object_.to_s.downcase == object.to_s.downcase instance_eval(&block) else "I can't #{command} like that." end end define_method("action_#{command}_help") do ["#{command} subject with object", "#{command} subject object"] end define_method("action_#{command}_complete") do | *args | return false if args.length > 2 (self.location.things.to_a + self.held_things.to_a).map { | object | object.name }.select { | object | /^#{args[-1]}/i =~ object } end end end class WizardsHouse < Adventure def initialize super # Define Rooms and things map << Room.new(:living_room, "You are in the living-room of a wizards house. There is a wizard snoring loudly on the couch.") do | room | room.things << Thing.new("Bucket", "a wooden bucket with a metal handle", true) << Thing.new("Bottle", "an empty whiskey bottle", true) << Thing.new("Wizard", "a completely drunken wizard snoring loudly on the couch", false) << Thing.new("Couch", "a couch whereon a drunken wizard lies", false) end << Room.new(:garden, "You are in a beautiful garden. There is a well in front of you.") do | room | room.things << Thing.new("Chain", "a rusty old chain", true) << Thing.new("Frog", "a vivid colored magic frog singing a happy frog-song", true) << Thing.new("Well", "an old well with a wooden hut above", false) end << Room.new(:attic, "You are in the attic of the wizards house. There is a giant welding torch in the corner.") do | room | room.things << Thing.new("Window", "a window showing that nothingness surrounds the wizards house", false) << Thing.new("Torch", "a giant welding torch built into the corner of the attic. This may come handy", false) end # Define Connections map[:living_room].connections << Connection.new(:west, :door, map[:garden]) << Connection.new(:upstairs, :stairway, map[:attic]) map[:garden].connections << Connection.new(:east, :door, map[:living_room]) map[:attic].connections << Connection.new(:downstairs, :stairway, :living_room) self.location = :living_room @chain_welded = false @bucket_filled = false end # Define actions def action_look [ describe_location, "", describe_floor, "", describe_paths ] end def action_look_help ["Take a look at the surroundings", "look"] end def action_look_at(object) object = (held_things[object] || location.things[object]) if object "You look at the #{object.name} and see #{object.description}." else "I do not know where to look" end end def action_look_at_help ["Take a look at something in the room or in your inventory", "look_at object"] end def action_look_at_complete(*args) return false if args.length > 1 (held_things.to_a + location.things.to_a).map { | thing | thing.name.to_s }.select { | thing | /^#{args[0]}/i =~ thing } end def action_walk(direction) connection = self.location.connections[direction] if connection self.location = connection.next_room action_look else "You can't go that way." end end def action_walk_help ["Walk into the room adjoining in the given direction", "walk direction"] end def action_walk_complete(*args) return false if args.length > 1 self.location.connections.map { | connection | connection.direction.to_s }.select { | direction | /^#{args[0]}/i =~ direction } end def action_pickup(object) object = self.location.things[object] if object and object.portable self.held_things << self.location.things.delete(object) "You are now carrying the #{object.name}" else "You cannot get that." end end def action_pickup_help ["Take an object from the world", "pickup object"] end def action_pickup_complete(*args) return false if args.length > 1 self.location.things.map { | object | object.name.to_s }.select { | object | /^#{args[0]}/i =~ object } end def action_drop(object) object = self.held_things[object] if object self.location.things << self.held_things.delete(object) "You have dropped the #{object.name}" else "You do not have that." end end def action_drop_help ["Litter the world with things you carry", "drop object"] end def action_drop_complete(*args) return false if args.length > 1 self.held_things.map { | object | object.name.to_s }.select { | object | /^#{args[0]}/i =~ object } end def action_inventory result = self.held_things.map{ | object | "#{object.name} - #{object.description}" } "You carry nothing." if result.empty? end def action_inventory_help ["Take a look at your inventory", "inventory"] end def_combine_action(:weld, "Chain", "Bucket", :attic) do if have("Bucket") @chain_welded = true held_things[:bucket].description = "An empty bucket with a long chain" held_things.delete(:chain) "The chain is now securely welded to the bucket." else "You do not have a bucket." end end def_combine_action(:dunk, "Bucket", "Well", :garden) do if @chain_welded @bucket_filled = true held_things[:bucket].description = "A bucket full of water" "The bucket is now full of water" else "The water level is too low to reach." end end def_combine_action(:splash, "Bucket", "Wizard", :living_room) do if not @bucket_filled "Splashing an empty bucket on the wizard has no effekt." elsif have("Frog") ["The wizard awakens and sees that you stole his frog.", "He is so upset he banishes you to the netherworlds -- you lose!", " === The End ==="] else ["The wizard awakens from his slumber and greets you warmly.", "He hands you the magic low-carb donut --- you win!", " === The End ==="] end end end # Readline interface for the Adventure class. class Interpreter def initialize(adventure) @adventure = adventure end # Readline interface with autocompletion. (Has some quirks but helps) def play require "readline" Readline.completer_word_break_characters = '' Readline.completion_proc = lambda do | line | line.gsub!(/^\s+/, '') args = line.downcase.split(/\s+/, -1) if args.length <= 1 (['exit'] + @adventure.commands).select { | cmd | /^#{args[0]}/i =~ cmd } else cmd = args.shift if @adventure.respond_to?("action_#{cmd}_complete") completes = @adventure.send("action_#{cmd}_complete", *args) if completes completes.map { | complete | [line.split(/\s+/, -1)[0..-2], complete].join(" ") } end end end end puts @adventure.action_look while line = Readline.readline("\nWhat do you want to do? ", true) break if /^exit/ =~ line next if /^\s*$/ =~ line begin args = line.split(/\s+/) cmd = args.shift puts @adventure.send("action_#{cmd}", *args) rescue => e puts "I could not understand your command. Try help for a list of applicable commands." p e if $DEBUG end end end end if __FILE__ == $0 Interpreter.new(WizardsHouse.new).play end
mit
spiral/orm
source/Spiral/ORM/Entities/Nodes/ArrayInterface.php
187
<?php /** * Spiral, Core Components * * @author Wolfy-J */ namespace Spiral\ORM\Entities\Nodes; /** * Indicates that node represent array sub-set. */ interface ArrayInterface { }
mit
D4rk4/talks-on-map
model/Info.js
492
'use strict'; let mongoose = require('mongoose'); let itemSchema = new mongoose.Schema({ city: { type: Number, index: true }, date: { type: Date, index: true }, accident: { type: Number }, level: { type: Number }, weather: { code: { type: String }, wind: { type: Number }, temperature: { type: String }, dampness: { type: Number } } }); module.exports = mongoose.model('Info', itemSchema);
mit
shimengyv/js-study
object.js
321
/** * 2017-09-14 Shi Mengyv */ var person = { hascar : true, age : 20, info : function () { console.log(this.hascar); console.log(this.age); console.log(this.info); console.log(`hascar => ${ this.hascar} age => ${ this.age} info => ${ this.info}`) } }; person.info();
mit
wusuopu/web.rb
lib/webrb.rb
279
require "webrb/version" require "webrb/routing" require "webrb/util" require "webrb/dependencies" require "webrb/controller" require "webrb/file_model" module Webrb class Application def call env rack_app = get_rack_app env rack_app.call env end end end
mit
vdt/matching-engine
test/update_precision.py
539
# a simple script to update the precision for the tests import json, sys, os def update(file): with open(file) as f: o = json.load(f); for x in o: p = x.get('payload') if not p: continue size = p.get('size') if not size: continue p['size'] = int(round(p['size'] * 1e8)) p['price'] = int(round(p['price'] * 1e8)) with open(file, 'w') as f: json.dump(o, f, indent=4) dirs = os.listdir('unit') for d in dirs: update(os.path.join('unit', d, "send.json"))
mit
BaderLab/openPIP
src/AppBundle/Controller/AutoCompleteController.php
3596
<?php namespace AppBundle\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use AppBundle\Entity\Identifier; use AppBundle\Form\IdentifierType; use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Component\Form\Extension\Core\Type\ChoiceType; use Symfony\Component\Form\Extension\Core\Type\CheckboxType; use AppBundle\Entity\Protein; use AppBundle\Entity\Interaction; //use AppBundle\Entity\Interaction_Network; use Symfony\Component\HttpFoundation\JsonResponse; use AppBundle\Form\ChoiceList\ArrayChoiceList; use AppBundle\Entity\Dataset_Request; use AppBundle\Utils\Node; use AppBundle\Utils\Edge; use AppBundle\Utils\QueryParameters; use AppBundle\Utils\PublicationStatus; use AppBundle\Utils\Functions; use AppBundle\Entity\Interaction_Category; use AppBundle\Entity\Interaction_Network; use AppBundle\Entity\Experiment; /** * Autocomplete controller. */ class AutoCompleteController extends Controller { /** * Autocomplete * * @Route("/autocomplete/{search_term}", name="autocomplete_search") * @Method({"GET", "POST"}) */ public function autocompleteAction($search_term) { $return = array(); $return['invalid_terms'] = array(); $pattern = '/[;,\s\t\n]/'; $search_query_array = preg_split( $pattern, $search_term); $search_query_array = array_filter($search_query_array, function($value) { return $value !== ''; }); foreach($search_query_array as $search_query){ if(self::assertIdentifierExists($search_query) == false){ $return['invalid_terms'][] = $search_query; } } $query = array_pop($search_query_array); $return_string = join(",", $search_query_array); $em = $this->getDoctrine()->getManager(); $identifier_repository = $em->getRepository('AppBundle:Identifier'); $query_builder = $identifier_repository->createQueryBuilder('i') ->where('i.identifier LIKE :identifier_keyword'); $query_builder->setParameter('identifier_keyword', "%$query%"); $query = $query_builder->getQuery(); $identifier_results = $query->getResult(); $identifier_array = array(); foreach($identifier_results as $identifier_result){ $return_2 = array(); $name = $identifier_result->getIdentifier(); $proteins = $identifier_result->getProteins(); $protein = $proteins[0]; $num_interactions = $protein->getNumberOfInteractionsInDatabase(); if(!in_array($name, $identifier_array)){ $identifier_array[] = $name; $return_string_2 = $return_string . "," . $name; $return_string_2 = preg_replace("/^[;,\s\t\n]/", '', $return_string_2); $return_2['value'] = $return_string_2; $return_2['label'] = $name; $return_2['num_interactions'] = $num_interactions; $return['autocomplete'][] = $return_2; } } $response = new JsonResponse(); $response->setData($return); return $response; } public function assertIdentifierExists($search_term){ $em = $this->getDoctrine()->getManager(); $query = $em->createQuery("SELECT i FROM AppBundle:Identifier i WHERE i.identifier = :identifier"); $query->setParameter('identifier', $search_term); $results = $query->getResult(); $return = false; if($results){$return = true;} return $return; } } ?>
mit
cuckata23/wurfl-data
data/sagem_myx_6_ver2_sub6224105_20.php
175
<?php return array ( 'id' => 'sagem_myx_6_ver2_sub6224105_20', 'fallback' => 'sagem_myx_6_ver1_subr2', 'capabilities' => array ( 'max_data_rate' => '40', ), );
mit
fpgentil/gitlabhq
app/models/note.rb
8749
# == Schema Information # # Table name: notes # # id :integer not null, primary key # note :text # noteable_type :string(255) # author_id :integer # created_at :datetime # updated_at :datetime # project_id :integer # attachment :string(255) # line_code :string(255) # commit_id :string(255) # noteable_id :integer # system :boolean default(FALSE), not null # st_diff :text # updated_by_id :integer # require 'carrierwave/orm/activerecord' require 'file_size_validator' class Note < ActiveRecord::Base include Mentionable include Gitlab::CurrentSettings include Participable default_value_for :system, false attr_mentionable :note participant :author, :mentioned_users belongs_to :project belongs_to :noteable, polymorphic: true belongs_to :author, class_name: "User" belongs_to :updated_by, class_name: "User" delegate :name, to: :project, prefix: true delegate :name, :email, to: :author, prefix: true validates :note, :project, presence: true validates :line_code, format: { with: /\A[a-z0-9]+_\d+_\d+\Z/ }, allow_blank: true # Attachments are deprecated and are handled by Markdown uploader validates :attachment, file_size: { maximum: :max_attachment_size } validates :noteable_id, presence: true, if: ->(n) { n.noteable_type.present? && n.noteable_type != 'Commit' } validates :commit_id, presence: true, if: ->(n) { n.noteable_type == 'Commit' } mount_uploader :attachment, AttachmentUploader # Scopes scope :for_commit_id, ->(commit_id) { where(noteable_type: "Commit", commit_id: commit_id) } scope :inline, ->{ where("line_code IS NOT NULL") } scope :not_inline, ->{ where(line_code: [nil, '']) } scope :system, ->{ where(system: true) } scope :user, ->{ where(system: false) } scope :common, ->{ where(noteable_type: ["", nil]) } scope :fresh, ->{ order(created_at: :asc, id: :asc) } scope :inc_author_project, ->{ includes(:project, :author) } scope :inc_author, ->{ includes(:author) } scope :with_associations, -> do includes(:author, :noteable, :updated_by, project: [:project_members, { group: [:group_members] }]) end serialize :st_diff before_create :set_diff, if: ->(n) { n.line_code.present? } class << self def discussions_from_notes(notes) discussion_ids = [] discussions = [] notes.each do |note| next if discussion_ids.include?(note.discussion_id) # don't group notes for the main target if !note.for_diff_line? && note.noteable_type == "MergeRequest" discussions << [note] else discussions << notes.select do |other_note| note.discussion_id == other_note.discussion_id end discussion_ids << note.discussion_id end end discussions end def build_discussion_id(type, id, line_code) [:discussion, type.try(:underscore), id, line_code].join("-").to_sym end def search(query) where("LOWER(note) like :query", query: "%#{query.downcase}%") end end def cross_reference? system && SystemNoteService.cross_reference?(note) end def max_attachment_size current_application_settings.max_attachment_size.megabytes.to_i end def find_diff return nil unless noteable && noteable.diffs.present? @diff ||= noteable.diffs.find do |d| Digest::SHA1.hexdigest(d.new_path) == diff_file_index if d.new_path end end def hook_attrs attributes end def set_diff # First lets find notes with same diff # before iterating over all mr diffs diff = diff_for_line_code unless for_merge_request? diff ||= find_diff self.st_diff = diff.to_hash if diff end def diff @diff ||= Gitlab::Git::Diff.new(st_diff) if st_diff.respond_to?(:map) end def diff_for_line_code Note.where(noteable_id: noteable_id, noteable_type: noteable_type, line_code: line_code).last.try(:diff) end # Check if such line of code exists in merge request diff # If exists - its active discussion # If not - its outdated diff def active? return true unless self.diff return false unless noteable noteable.diffs.each do |mr_diff| next unless mr_diff.new_path == self.diff.new_path lines = Gitlab::Diff::Parser.new.parse(mr_diff.diff.lines.to_a) lines.each do |line| if line.text == diff_line return true end end end false end def outdated? !active? end def diff_file_index line_code.split('_')[0] if line_code end def diff_file_name diff.new_path if diff end def file_path if diff.new_path.present? diff.new_path elsif diff.old_path.present? diff.old_path end end def diff_old_line line_code.split('_')[1].to_i if line_code end def diff_new_line line_code.split('_')[2].to_i if line_code end def generate_line_code(line) Gitlab::Diff::LineCode.generate(file_path, line.new_pos, line.old_pos) end def diff_line return @diff_line if @diff_line if diff diff_lines.each do |line| if generate_line_code(line) == self.line_code @diff_line = line.text end end end @diff_line end def diff_line_type return @diff_line_type if @diff_line_type if diff diff_lines.each do |line| if generate_line_code(line) == self.line_code @diff_line_type = line.type end end end @diff_line_type end def truncated_diff_lines max_number_of_lines = 16 prev_match_line = nil prev_lines = [] diff_lines.each do |line| if line.type == "match" prev_lines.clear prev_match_line = line else prev_lines << line break if generate_line_code(line) == self.line_code prev_lines.shift if prev_lines.length >= max_number_of_lines end end prev_lines end def diff_lines @diff_lines ||= Gitlab::Diff::Parser.new.parse(diff.diff.lines.to_a) end def discussion_id @discussion_id ||= Note.build_discussion_id(noteable_type, noteable_id || commit_id, line_code) end def for_commit? noteable_type == "Commit" end def for_commit_diff_line? for_commit? && for_diff_line? end def for_diff_line? line_code.present? end def for_issue? noteable_type == "Issue" end def for_merge_request? noteable_type == "MergeRequest" end def for_merge_request_diff_line? for_merge_request? && for_diff_line? end def for_project_snippet? noteable_type == "Snippet" end # override to return commits, which are not active record def noteable if for_commit? project.commit(commit_id) else super end # Temp fix to prevent app crash # if note commit id doesn't exist rescue nil end DOWNVOTES = %w(-1 :-1: :thumbsdown: :thumbs_down_sign:) # Check if the note is a downvote def downvote? votable? && note.start_with?(*DOWNVOTES) end UPVOTES = %w(+1 :+1: :thumbsup: :thumbs_up_sign:) # Check if the note is an upvote def upvote? votable? && note.start_with?(*UPVOTES) end def superceded?(notes) return false unless vote? notes.each do |note| next if note == self if note.vote? && self[:author_id] == note[:author_id] && self[:created_at] <= note[:created_at] return true end end false end def vote? upvote? || downvote? end def votable? for_issue? || (for_merge_request? && !for_diff_line?) end # Mentionable override. def gfm_reference(from_project = nil) noteable.gfm_reference(from_project) end # Mentionable override. def local_reference noteable end def noteable_type_name noteable_type.downcase if noteable_type.present? end # FIXME: Hack for polymorphic associations with STI # For more information visit http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#label-Polymorphic+Associations def noteable_type=(noteable_type) super(noteable_type.to_s.classify.constantize.base_class.to_s) end # Reset notes events cache # # Since we do cache @event we need to reset cache in special cases: # * when a note is updated # * when a note is removed # Events cache stored like events/23-20130109142513. # The cache key includes updated_at timestamp. # Thus it will automatically generate a new fragment # when the event is updated because the key changes. def reset_events_cache Event.reset_event_cache_for(self) end def system? read_attribute(:system) end def editable? !system? end end
mit
arnau/ISO8601
lib/iso8601/errors.rb
1225
# frozen_string_literal: true module ISO8601 ## # Contains all ISO8601-specific errors. module Errors ## # Catch-all exception. class StandardError < ::StandardError end ## # Raised when the given pattern doesn't fit as ISO 8601 parser. class UnknownPattern < StandardError def initialize(pattern) super("Unknown pattern #{pattern}") end end ## # Raised when the given pattern contains an invalid fraction. class InvalidFractions < StandardError def initialize super("Fractions are only allowed in the last component") end end ## # Raised when the given date is valid but out of range. class RangeError < StandardError def initialize(pattern) super("#{pattern} is out of range") end end ## # Raised when the type is unexpected class TypeError < ::ArgumentError end ## # Raised when the interval is unexpected class IntervalError < StandardError end ## # Raise when the base is not suitable. class DurationBaseError < StandardError def initialize(duration) super("Wrong base for #{duration} duration.") end end end end
mit
thisishugo/thisishugo.github.com
src/images/index.d.ts
78
declare module "*.jpg" { const content: string; export default content; }
mit
Connor-R/nba_shot_charts
charting/TODO_temp_helper.py
23829
import urllib import os import shutil import sys import glob import math import pandas as pd import argparse from datetime import date, datetime from time import time import matplotlib as mpb import matplotlib.pyplot as plt from matplotlib import offsetbox as osb from matplotlib.patches import RegularPolygon from datetime import date, datetime, timedelta from time import time from py_data_getter import data_getter from py_db import db import helper_charting import helper_data db = db('nba_shots') # setting the color map we want to use mymap = mpb.cm.YlOrRd whitelist_pngs = ['charts_description.png', 'nba_logo.png', '0.png', 'chart_icon.png'] base_path = os.getcwd()+"/shot_charts_custom_charts/" def initiate(_type, _names, season_type, start_date, end_date, custom_title=None, custom_text=None, custom_img=None, custom_file=None): start_time = time() print '\n\ncharting.....' if _type == 'Player': print '\n\tplayers:\t', else: print '\n\tteams:\t\t', for n in _names: print n.replace(' ',''), print '\n\tseason type:\t' + str(season_type) print '\tstart date: \t' + str(start_date) print '\tend date: \t' + str(end_date) if custom_title is not None: print '\ttitle: \t\t' + str(custom_title) if custom_text is not None: print '\ttext: \t\t' + str(custom_text) if custom_file is None: path_add = str(date.today())+'_'+str(datetime.now().hour)+'_'+str(datetime.now().minute)+'_'+str(datetime.now().second)+'.png' else: path_add = str(custom_file).replace(' ', '').replace(',','-') + '.png' print '\tfilename: \t' + str(custom_file).replace(' ', '_').replace(',','-') + '.png' path = base_path + path_add id_list = [] print '\n\t\tgetting ids.....' if _type.lower() == 'player': for _name in _names: idq = """SELECT player_id FROM players WHERE CONCAT(fname, " ", lname) = '%s'""" % (_name) _id = int(db.query(idq)[0][0]) id_list.append(_id) elif _type.lower() == 'team': for _name in _names: idq = """SELECT team_id FROM teams WHERE CONCAT(city, " ", tname) = '%s'""" % (_name) _id = int(db.query(idq)[0][0]) id_list.append(_id) print '\t\t\tDONE' ids = tuple(id_list) if len(ids) == 1: ids = '('+ str(ids[0]) + ')' # path_ids = zip(_names, id_list) # print len(path_ids) # raw_input(path_ids) if custom_title is None: custom_title = '' for n in _names[:-1]: custom_title += n custom_title += _names[-1] start2, end2 = get_dates(_type, ids, start_date, end_date, season_type) print '\t\tacquiring shooting data.....' shot_df = acquire_shootingData(ids, start_date, end_date, _type, season_type) print '\t\t\tDONE' if shot_df is not None and len(shot_df.index) != 0: shooting_plot(path, _type, shot_df, ids, _names, season_type, start_date, end_date, custom_title, custom_text, custom_img, start2, end2) end_time = time() elapsed_time = float(end_time - start_time) print "time elapsed (in seconds): \t" + str(elapsed_time) print "time elapsed (in minutes): \t" + str(elapsed_time/60.0) print "\n\n ==================================================================================" def acquire_shootingData(ids, start_date, end_date, _type='Player', season_type='Reg'): shot_query = """SELECT season_id, game_id, team_id, game_date, event_type, shot_type, shot_zone_basic, shot_zone_area, LOC_X, LOC_Y, IF(event_type='Made Shot', 1, 0) AS SHOT_MADE_FLAG, zone_pct_plus, efg_plus FROM shots JOIN shots_%s_Relative_Year USING (season_id, %s_id, season_type, shot_zone_basic, shot_zone_area) WHERE %s_id IN %s AND game_date >= '%s' AND game_date <= '%s' AND season_type = '%s'; """ shot_q = shot_query % (_type, _type, _type, ids, start_date, end_date, season_type) # raw_input(shot_q) shots = db.query(shot_q) shot_data = {'season_id':[], 'game_id':[], 'team_id':[], 'game_date':[], 'event_type':[], 'shot_type':[], 'shot_zone_basic':[], 'shot_zone_area':[], 'LOC_X':[], 'LOC_Y':[], 'SHOT_MADE_FLAG':[], 'zone_pct_plus':[], 'efg_plus':[]} for row in shots: season_id, game_id, team_id, game_date, event_type, shot_type, shot_zone_basic, shot_zone_area, LOC_X, LOC_Y, SHOT_MADE_FLAG, zone_pct_plus, efg_plus = row shot_data['season_id'].append(season_id) shot_data['game_id'].append(game_id) shot_data['team_id'].append(team_id) shot_data['game_date'].append(game_date) shot_data['event_type'].append(event_type) shot_data['shot_type'].append(shot_type) shot_data['shot_zone_basic'].append(shot_zone_basic) shot_data['shot_zone_area'].append(shot_zone_area) shot_data['LOC_X'].append(LOC_X) shot_data['LOC_Y'].append(LOC_Y) shot_data['SHOT_MADE_FLAG'].append(SHOT_MADE_FLAG) shot_data['zone_pct_plus'].append(zone_pct_plus) shot_data['efg_plus'].append(efg_plus) shot_df = pd.DataFrame(shot_data, columns=shot_data.keys()) return shot_df def shooting_plot(path, _type, shot_df, ids, _names, season_type, start_date, end_date, custom_title, custom_text, custom_img, start2, end2, plot_size=(12,12), gridNum=30): print '\t\tgetting shooting percentages in each zone.....' (ShootingPctLocs, shotNumber), shot_count_all = helper_charting.find_shootingPcts(shot_df, gridNum) print '\t\t\tDONE' print '\t\tcalculating metrics.....' metrics = calculate_metrics(_type, ids, start_date, end_date, season_type) #TODO print '\t\t\tDONE' all_efg_plus = float(get_metrics(metrics, 'all', 'efg_plus')) paa = float(get_metrics(metrics, 'all', 'paa')) color_efg = max(min(((all_efg_plus/100)-0.5),1.0),0.0) fig = plt.figure(figsize=(12,12)) cmap = mymap ax = plt.axes([0.05, 0.15, 0.81, 0.775]) ax.set_axis_bgcolor('#0C232E') helper_charting.draw_court(outer_lines=False) plt.xlim(-250,250) plt.ylim(370, -30) print '\t\tgetting icon.....' img = acquire_custom_pic(custom_img) #TODO ax.add_artist(img) print '\t\t\tDONE' max_radius_perc = 1.0 max_rad_multiplier = 100.0/max_radius_perc area_multiplier = (3./4.) lg_efg = float(get_lg_metrics(start_date, end_date, season_type, 'all', 'efg')) print '\t\tplotting each hex bin.....' # i is the bin#, and shots is the shooting% for that bin for i, shots in enumerate(ShootingPctLocs): x,y = shotNumber.get_offsets()[i] # we check the distance from the hoop the bin is. If it in 3pt territory, we add a multiplier of 1.5 to the shooting% to properly encapsulate eFG% dist = math.sqrt(x**2 + y**2) mult = 1.0 if abs(x) >= 220: mult = 1.5 elif dist/10 >= 23.75: mult = 1.5 else: mult = 1.0 # Setting the eFG% for a bin, making sure it's never over 1 (our maximum color value) color_pct = ((shots*mult)/lg_efg)-0.5 bin_pct = max(min(color_pct, 1.0), 0.0) hexes = RegularPolygon( shotNumber.get_offsets()[i], #x/y coords numVertices=6, radius=(295/gridNum)*((max_rad_multiplier*((shotNumber.get_array()[i]))/shot_count_all)**(area_multiplier)), color=cmap(bin_pct), alpha=0.95, fill=True) # setting a maximum radius for our bins at 295 (personal preference) if hexes.radius > 295/gridNum: hexes.radius = 295/gridNum ax.add_patch(hexes) print '\t\t\tDONE' print '\t\tcreating the frequency legend.....' # we want to have 4 ticks in this legend so we iterate through 4 items for i in range(0,4): base_rad = max_radius_perc/4 # the x,y coords for our patch (the first coordinate is (-205,415), and then we move up and left for each addition coordinate) patch_x = -205-(10*i) patch_y = 365-(14*i) # specifying the size of our hexagon in the frequency legend patch_rad = (299.9/gridNum)*((base_rad+(base_rad*i))**(area_multiplier)) patch_perc = base_rad+(i*base_rad) # the x,y coords for our text text_x = patch_x + patch_rad + 2 text_y = patch_y patch_axes = (patch_x, patch_y) # the text will be slightly different for our maximum sized hexagon, if i < 3: text_text = ' %s%% of Attempted Shots' % ('%.2f' % patch_perc) else: text_text = '$\geq$%s%% of Attempted Shots' %(str(patch_perc)) # draw the hexagon. the color=map(eff_fg_all_float/100) makes the hexagons in the legend the same color as the player's overall eFG% patch = RegularPolygon(patch_axes, numVertices=6, radius=patch_rad, color=cmap(color_efg), alpha=0.95, fill=True) ax.add_patch(patch) # add the text for the hexagon ax.text(text_x, text_y, text_text, fontsize=12, horizontalalignment='left', verticalalignment='center', family='DejaVu Sans', color='white', fontweight='bold') print '\t\t\tDONE' # Add a title to our frequency legend (the x/y coords are hardcoded). # Again, the color=map(eff_fg_all_float/100) makes the hexagons in the legend the same color as the player's overall eFG% ax.text(-235, 310, 'Zone Frequencies', fontsize = 15, horizontalalignment='left', verticalalignment='bottom', family='DejaVu Sans', color=cmap(color_efg), fontweight='bold') print '\t\tadding text.....' # Add a title to our chart (just the player's name) chart_title = "%s" % (custom_title) ax.text(31.25,-40, chart_title, fontsize=29, horizontalalignment='center', verticalalignment='bottom', family='DejaVu Sans', color=cmap(color_efg), fontweight='bold') # Add user text ax.text(-250,-31,'CHARTS BY CONNOR REED (@NBAChartBot)', fontsize=10, horizontalalignment='left', verticalalignment = 'bottom', family='DejaVu Sans', color='white', fontweight='bold') # Add data source text ax.text(31.25,-31,'DATA FROM STATS.NBA.COM', fontsize=10, horizontalalignment='center', verticalalignment = 'bottom', family='DejaVu Sans', color='white', fontweight='bold') # Add date text _date = date.today() ax.text(250,-31,'AS OF %s' % (str(_date)), fontsize=10, horizontalalignment='right', verticalalignment = 'bottom', family='DejaVu Sans', color='white', fontweight='bold') key_text = get_key_text(_type, ids, start_date, end_date, metrics) #TODO # adding breakdown of eFG% by shot zone at the bottom of the chart ax.text(307,380, key_text, fontsize=12, horizontalalignment='right', verticalalignment = 'top', family='DejaVu Sans', color='white', linespacing=1.5) if _type == 'Player': teams_text, team_len = get_teams_text(ids, start_date, end_date, custom_text, season_type) elif _type == 'Team': team_len = len(_names) if custom_text is None: teams_text = '' if len(_names) == 1: teams_text = str(_names[0]) else: i = 0 for team in _names[0:-1]: if i%2 == 0 and i > 0: teams_text += '\n' text_add = '%s, ' % str(team) teams_text += text_add i += 1 if i%2 == 0: teams_text += '\n' teams_text += str(_names[-1]) else: teams_text = custom_text if custom_text is None: if season_type == 'Reg': season_type_text = 'Regular Season Shots:\n' elif season_type == 'AS': season_type_text = 'All Star Shots:\n' elif season_type == 'Pre': season_type_text = 'Pre Season Shots:\n' elif season_type == 'Post': season_type_text = 'Post Season Shots:\n' else: season_type_text = 'All Shots:\n' else: season_type_text = '' if team_len > 6: ax.text(-250,380, str(start2) + ' to ' + str(end2) + '\n'+ season_type_text + teams_text, fontsize=8, horizontalalignment='left', verticalalignment = 'top', family='DejaVu Sans', color='white', linespacing=1.4) else: ax.text(-250,380,str(start2) + ' to ' + str(end2) + '\n'+ season_type_text + teams_text, fontsize=11, horizontalalignment='left', verticalalignment = 'top', family='DejaVu Sans', color='white', linespacing=1.5) print '\t\t\tDONE' # adding a color bar for reference ax2 = fig.add_axes([0.875, 0.15, 0.04, 0.775]) cb = mpb.colorbar.ColorbarBase(ax2,cmap=cmap, orientation='vertical') cbytick_obj = plt.getp(cb.ax.axes, 'yticklabels') plt.setp(cbytick_obj, color='white', fontweight='bold') cb.set_label('EFG+ (100 is League Average)', family='DejaVu Sans', color='white', fontweight='bold', labelpad=-4, fontsize=14) cb.set_ticks([0.0, 0.25, 0.5, 0.75, 1.0]) cb.set_ticklabels(['$\mathbf{\leq}$50','75', '100','125', '$\mathbf{\geq}$150']) print 'ALL DONE\n\n' figtit = path plt.savefig(figtit, facecolor='#26373F', edgecolor='black') plt.clf() def calculate_metrics(_type, ids, start_date, end_date, season_type): print '\t\t\tgetting breakdown.....' breakdown_q = """SELECT * FROM( SELECT shot_zone_basic, COUNT(*) AS attempts, SUM(CASE WHEN event_type = "Made Shot" THEN 1 ELSE 0 END) AS makes, SUM(CASE WHEN event_type = "Made Shot" AND shot_type = '2PT Field Goal' THEN 2 WHEN event_type = "Made Shot" AND shot_type = '3PT Field Goal' THEN 3 ELSE 0 END) AS points FROM shots WHERE %s_id IN %s AND game_date >= '%s' AND game_date <= '%s' AND season_type = '%s' GROUP BY shot_zone_basic UNION SELECT 'all' AS shot_zone_basic, COUNT(*) AS attempts, SUM(CASE WHEN event_type = "Made Shot" THEN 1 ELSE 0 END) AS makes, SUM(CASE WHEN event_type = "Made Shot" AND shot_type = '2PT Field Goal' THEN 2 WHEN event_type = "Made Shot" AND shot_type = '3PT Field Goal' THEN 3 ELSE 0 END) AS points FROM shots WHERE %s_id IN %s AND game_date >= '%s' AND game_date <= '%s' AND season_type = '%s' ) a JOIN(SELECT COUNT(DISTINCT game_id) as games FROM shots WHERE %s_id IN %s AND game_date >= '%s' AND game_date <= '%s' AND season_type = '%s' ) b """ breakdown_qry = breakdown_q % (_type, ids, start_date, end_date, season_type, _type, ids, start_date, end_date, season_type, _type, ids, start_date, end_date, season_type) # raw_input(breakdown_qry) breakdown = db.query(breakdown_qry) zone_data = [] allatts = 0 for row in breakdown: _z, att, mak, pts, gms = row efg = (float(pts)/float(att))/2.0 entry = {'zone':_z, 'attempts':float(att), 'makes':float(mak), 'points':float(pts), 'games':float(gms), 'efg':efg} zone_data.append(entry) if _z == 'all': allatts = att print '\t\t\tgetting all league metrics.....' final_data = [] lgALL_zone = float(get_lg_metrics(start_date, end_date, season_type, 'all', 'zone_pct')) lgALL_efg = float(get_lg_metrics(start_date, end_date, season_type, 'all', 'efg')) print '\t\t\tgetting zone league metrics.....' for entry in zone_data: z_pct = float(entry.get('attempts'))/float(allatts) entry['z_pct'] = z_pct lg_zone = float(get_lg_metrics(start_date, end_date, season_type, entry.get('zone'), 'zone_pct')) lg_efg = float(get_lg_metrics(start_date, end_date, season_type, entry.get('zone'), 'efg')) if lg_zone == 0: entry['zone_pct_plus'] = 0 else: entry['zone_pct_plus'] = 100*(entry.get('z_pct')/lg_zone) if lg_efg == 0: entry['ZONE_efg_plus'] = 0 else: entry['ZONE_efg_plus'] = 100*(entry.get('efg')/lg_efg) if lgALL_efg == 0: entry['efg_plus'] = 0 else: entry['efg_plus'] = 100*(entry.get('efg')/lgALL_efg) zone_paa = entry.get('attempts')*(entry.get('efg')-lg_efg)*2 entry['ZONE_paa'] = zone_paa entry['ZONE_paa_per_game'] = zone_paa/(entry.get('games')) paa = entry.get('attempts')*(entry.get('efg')-lgALL_efg)*2 entry['paa'] = paa entry['paa_per_game'] = paa/(entry.get('games')) final_data.append(entry) return final_data def get_lg_metrics(start_date, end_date, season_type, shot_zone_basic, metric): q = """SELECT SUM(%s*attempts)/SUM(attempts) FROM shots_League_Distribution_Year WHERE season_id IN (SELECT DISTINCT season_id FROM shots s WHERE game_date >= '%s' AND game_date <= '%s') AND shot_zone_basic = '%s' AND shot_zone_area = 'all' AND season_type = '%s' """ qry = q % (metric, start_date, end_date, shot_zone_basic, season_type) # raw_input(qry) lg_val = db.query(qry)[0][0] if lg_val is None: return 0 else: return lg_val def get_metrics(metrics, zone, target): for row in metrics: if row.get('zone').lower() == zone.lower(): return row.get(target) return 0 def get_teams_text(ids, start_date, end_date, custom_text, season_type): if custom_text is None: team_q = """SELECT DISTINCT CONCAT(city, ' ', tname) FROM shots s JOIN teams t USING (team_id) WHERE Player_id IN %s AND game_date >= '%s' AND game_date <= '%s' AND LEFT(season_id, 4) >= t.start_year AND LEFT(season_id, 4) < t.end_year AND season_type = '%s'; """ team_qry = team_q % (ids, start_date, end_date, season_type) teams = db.query(team_qry) team_list = [] for team in teams: team_list.append(team[0]) team_text = "" if len(team_list) == 1: team_text = str(team_list[0]) else: i = 0 for team in team_list[0:-1]: if i%2 == 0 and i > 0: team_text += '\n' text_add = '%s, ' % str(team) team_text += text_add i += 1 if i%2 == 0: team_text += '\n' team_text += str(team_list[-1]) return team_text, len(team_list) else: return custom_text, 0 def get_key_text(_type, ids, start_date, end_date, metrics): text = '' for zone in ('All', 'Above The Break 3', 'Corner 3', 'Mid-Range', 'In The Paint (Non-RA)', 'Restricted Area'): if zone == 'All': text += 'All Shots | ' elif zone == 'Above The Break 3': text += '\n' + 'Arc 3 | ' elif zone == 'In The Paint (Non-RA)': text += '\n' + 'Paint(Non-RA) | ' elif zone == 'Restricted Area': text += '\n' + 'Restricted | ' else: text += '\n' + zone + ' | ' atts = ("%.0f" % get_metrics(metrics, zone, 'attempts')) makes = ("%.0f" % get_metrics(metrics, zone, 'makes')) zone_pct = ("%.1f" % (float(100)*get_metrics(metrics, zone, 'z_pct'))) zone_pct_plus = ("%.1f" % get_metrics(metrics, zone, 'zone_pct_plus')) efg = ("%.1f" % (float(100)*get_metrics(metrics, zone, 'efg'))) efg_plus = ("%.1f" % get_metrics(metrics, zone, 'efg_plus')) zone_efg_plus = ("%.1f" % get_metrics(metrics, zone, 'ZONE_efg_plus')) paa = ("%.1f" % get_metrics(metrics, zone, 'paa')) paa_game = ("%.1f" % get_metrics(metrics, zone, 'paa_per_game')) if zone == 'All': text += str(makes) + ' for ' + str(atts) + ' | ' text += str(efg) + ' EFG% (' text += str(efg_plus) + ' EFG+ | ' text += str(paa) + ' PAA) | ' text += str(paa_game) + ' PAA/G' else: text += str(makes) + '/' + str(atts) + ' | ' text += str(zone_pct) + '% z% (' + str(zone_pct_plus) + ' z%+) | ' text += str(zone_efg_plus) + ' zEFG+ (' text += str(efg_plus) + ' EFG+ | ' text += str(paa) + ' PAA)' return text def get_dates(_type, ids, start_date, end_date, season_type): q = """SELECT MIN(game_date), MAX(game_date) FROM shots WHERE %s_id IN %s AND game_date >= '%s' AND game_date <= '%s' AND season_type = '%s';""" qry = q % (_type, ids, start_date, end_date, season_type) dates = db.query(qry)[0] start_date, end_date = dates return dates def acquire_custom_pic(custom_img, offset=(250,370)): if custom_img is not None: try: img_path = os.getcwd()+'/'+custom_img+'.png' player_pic = plt.imread(img_path) except IOError: img_path = os.getcwd()+'/chart_icon.png' player_pic = plt.imread(img_path) else: img_path = os.getcwd()+'/chart_icon.png' player_pic = plt.imread(img_path) img = osb.OffsetImage(player_pic) img = osb.AnnotationBbox(img, offset,xycoords='data',pad=0.0, box_alignment=(1,0), frameon=False) return img if __name__ == "__main__": parser = argparse.ArgumentParser() # parser.add_argument('--_type', default = 'Player') # parser.add_argument('--_names', default = ["Paul Pierce"]) # parser.add_argument('--season_type', default = 'Post') # parser.add_argument('--start_date', default = '1996-04-01') # parser.add_argument('--end_date', default = '2017-10-01') # parser.add_argument('--custom_title', default = 'Paul Pierce - Career Playoffs') # parser.add_argument('--custom_text', default = None) # parser.add_argument('--custom_img', default = None) # parser.add_argument('--custom_file', default = 'PaulPierce_Playoffs') # parser.add_argument('--_type', default = 'Player') # parser.add_argument('--_names', default = ['John Wall', 'DeMar DeRozan', 'Jimmy Butler', 'Draymond Green', 'DeAndre Jordan']) # parser.add_argument('--season_type', default = 'Reg') # parser.add_argument('--start_date', default = '2016-06-14') # parser.add_argument('--end_date', default = date.today()) # parser.add_argument('--custom_title', default = '2016-17 All NBA 3rd Team') # parser.add_argument('--custom_text', default = 'John Wall\nDeMar DeRozan\nJimmy Butler\nDraymond Green\nDeAndre Jordan') # parser.add_argument('--custom_img', default = None) # parser.add_argument('--custom_file', default = 'AllNBA_3_201617') parser.add_argument('--_type', default = 'Player') parser.add_argument('--_names', default = ["Stephen Curry"]) parser.add_argument('--season_type', default = 'Reg') parser.add_argument('--start_date', default = '2017-06-01') parser.add_argument('--end_date', default = '2018-06-01') parser.add_argument('--custom_title', default = 'Stephen Curry - 2017/18') parser.add_argument('--custom_text', default = None) parser.add_argument('--custom_img', default = None) parser.add_argument('--custom_file', default = 'Stephen Curry_201718') args = parser.parse_args() initiate(args._type, args._names, args.season_type, args.start_date, args.end_date, args.custom_title, args.custom_text, args.custom_img, args.custom_file)
mit
baguss42/autoshop
assets/plugins/filemanager/config/config.php
19654
<?php if (session_id() == '') session_start(); mb_internal_encoding('UTF-8'); date_default_timezone_set('Asia/Jakarta'); /* |-------------------------------------------------------------------------- | Optional security |-------------------------------------------------------------------------- | | if set to true only those will access RF whose url contains the access key(akey) like: | <input type="button" href="../filemanager/dialog.php?field_id=imgField&lang=en_EN&akey=myPrivateKey" value="Files"> | in tinymce a new parameter added: filemanager_access_key:"myPrivateKey" | example tinymce config: | | tiny init ... | external_filemanager_path:"../filemanager/", | filemanager_title:"Filemanager" , | filemanager_access_key:"myPrivateKey" , | ... | */ define('USE_ACCESS_KEYS', false); // TRUE or FALSE /* |-------------------------------------------------------------------------- | DON'T COPY THIS VARIABLES IN FOLDERS config.php FILES |-------------------------------------------------------------------------- */ define('DEBUG_ERROR_MESSAGE', true); // TRUE or FALSE /* |-------------------------------------------------------------------------- | Path configuration |-------------------------------------------------------------------------- | In this configuration the folder tree is | root | |- source <- upload folder | |- thumbs <- thumbnail folder [must have write permission (755)] | |- filemanager | |- js | | |- tinymce | | | |- plugins | | | | |- responsivefilemanager | | | | | |- plugin.min.js */ $config = array( /* |-------------------------------------------------------------------------- | DON'T TOUCH (base url (only domain) of site). |-------------------------------------------------------------------------- | | without final / (DON'T TOUCH) | */ 'base_url' => ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] && ! in_array(strtolower($_SERVER['HTTPS']), array( 'off', 'no' ))) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'], /* |-------------------------------------------------------------------------- | path from base_url to base of upload folder |-------------------------------------------------------------------------- | | with start and final / | */ 'upload_dir' => '/media_library/uploads/', /* |-------------------------------------------------------------------------- | relative path from filemanager folder to upload folder |-------------------------------------------------------------------------- | | with final / | */ 'current_path' => '../../../media_library/uploads/', /* |-------------------------------------------------------------------------- | relative path from filemanager folder to thumbs folder |-------------------------------------------------------------------------- | | with final / | DO NOT put inside upload folder | */ 'thumbs_base_path' => '../../../media_library/thumbs/', /* |-------------------------------------------------------------------------- | FTP configuration BETA VERSION |-------------------------------------------------------------------------- | | If you want enable ftp use write these parametres otherwise leave empty | Remember to set base_url properly to point in the ftp server domain and | upload dir will be ftp_base_folder + upload_dir so without final / | */ 'ftp_host' => false, 'ftp_user' => "user", 'ftp_pass' => "pass", 'ftp_base_folder' => "base_folder", 'ftp_base_url' => "http://site to ftp root", /* -------------------------------------------------------------------------- | path from ftp_base_folder to base of thumbs folder with start and final | |--------------------------------------------------------------------------*/ 'ftp_thumbs_dir' => '/thumbs/', 'ftp_ssl' => false, 'ftp_port' => 21, // 'ftp_host' => "s108707.gridserver.com", // 'ftp_user' => "[email protected]", // 'ftp_pass' => "Test.1234", // 'ftp_base_folder' => "/domains/responsivefilemanager.com/html", /* |-------------------------------------------------------------------------- | Access keys |-------------------------------------------------------------------------- | | add access keys eg: array('myPrivateKey', 'someoneElseKey'); | keys should only containt (a-z A-Z 0-9 \ . _ -) characters | if you are integrating lets say to a cms for admins, i recommend making keys randomized something like this: | $username = 'Admin'; | $salt = 'dsflFWR9u2xQa' (a hard coded string) | $akey = md5($username.$salt); | DO NOT use 'key' as access key! | Keys are CASE SENSITIVE! | */ 'access_keys' => array(), //-------------------------------------------------------------------------------------------------------- // YOU CAN COPY AND CHANGE THESE VARIABLES INTO FOLDERS config.php FILES TO CUSTOMIZE EACH FOLDER OPTIONS //-------------------------------------------------------------------------------------------------------- /* |-------------------------------------------------------------------------- | Maximum size of all files in source folder |-------------------------------------------------------------------------- | | in Megabytes | */ 'MaxSizeTotal' => false, /* |-------------------------------------------------------------------------- | Maximum upload size |-------------------------------------------------------------------------- | | in Megabytes | */ 'MaxSizeUpload' => 100, /* |-------------------------------------------------------------------------- | File and Folder permission |-------------------------------------------------------------------------- | */ 'fileFolderPermission' => 0755, /* |-------------------------------------------------------------------------- | default language file name |-------------------------------------------------------------------------- */ 'default_language' => "en_EN", /* |-------------------------------------------------------------------------- | Icon theme |-------------------------------------------------------------------------- | | Default available: ico and ico_dark | Can be set to custom icon inside filemanager/img | */ 'icon_theme' => "ico", //Show or not total size in filemanager (is possible to greatly increase the calculations) 'show_total_size' => true, //Show or not show folder size in list view feature in filemanager (is possible, if there is a large folder, to greatly increase the calculations) 'show_folder_size' => true, //Show or not show sorting feature in filemanager 'show_sorting_bar' => true, //Show or not show filters button in filemanager 'show_filter_buttons' => true, //Show or not language selection feature in filemanager 'show_language_selection' => true, //active or deactive the transliteration (mean convert all strange characters in A..Za..z0..9 characters) 'transliteration' => false, //convert all spaces on files name and folders name with $replace_with variable 'convert_spaces' => false, //convert all spaces on files name and folders name this value 'replace_with' => "_", //convert to lowercase the files and folders name 'lower_case' => false, //Add ?484899493349 (time value) to returned images to prevent cache 'add_time_to_img' => false, // -1: There is no lazy loading at all, 0: Always lazy-load images, 0+: The minimum number of the files in a directory // when lazy loading should be turned on. 'lazy_loading_file_number_threshold' => 0, //******************************************* //Images limit and resizing configuration //******************************************* // set maximum pixel width and/or maximum pixel height for all images // If you set a maximum width or height, oversized images are converted to those limits. Images smaller than the limit(s) are unaffected // if you don't need a limit set both to 0 'image_max_width' => 0, 'image_max_height' => 0, 'image_max_mode' => 'auto', /* # $option: 0 / exact = defined size; # 1 / portrait = keep aspect set height; # 2 / landscape = keep aspect set width; # 3 / auto = auto; # 4 / crop= resize and crop; */ //Automatic resizing // // If you set $image_resizing to TRUE the script converts all uploaded images exactly to image_resizing_width x image_resizing_height dimension // If you set width or height to 0 the script automatically calculates the other dimension // Is possible that if you upload very big images the script not work to overcome this increase the php configuration of memory and time limit 'image_resizing' => false, 'image_resizing_width' => 0, 'image_resizing_height' => 0, 'image_resizing_mode' => 'auto', // same as $image_max_mode 'image_resizing_override' => false, // If set to TRUE then you can specify bigger images than $image_max_width & height otherwise if image_resizing is // bigger than $image_max_width or height then it will be converted to those values //****************** // // WATERMARK IMAGE // //Watermark url or false 'image_watermark' => false, # Could be a pre-determined position such as: # tl = top left, # t = top (middle), # tr = top right, # l = left, # m = middle, # r = right, # bl = bottom left, # b = bottom (middle), # br = bottom right # Or, it could be a co-ordinate position such as: 50x100 'image_watermark_position' => 'br', # padding: If using a pre-determined position you can # adjust the padding from the edges by passing an amount # in pixels. If using co-ordinates, this value is ignored. 'image_watermark_padding' => 0, //****************** // Default layout setting // // 0 => boxes // 1 => detailed list (1 column) // 2 => columns list (multiple columns depending on the width of the page) // YOU CAN ALSO PASS THIS PARAMETERS USING SESSION VAR => $_SESSION['RF']["VIEW"]= // //****************** 'default_view' => 0, //set if the filename is truncated when overflow first row 'ellipsis_title_after_first_row' => true, //************************* //Permissions configuration //****************** 'delete_files' => true, 'create_folders' => false, 'delete_folders' => false, 'upload_files' => true, 'rename_files' => false, 'rename_folders' => false, 'duplicate_files' => true, 'copy_cut_files' => true, // for copy/cut files 'copy_cut_dirs' => true, // for copy/cut directories 'chmod_files' => false, // change file permissions 'chmod_dirs' => false, // change folder permissions 'preview_text_files' => false, // eg.: txt, log etc. 'edit_text_files' => false, // eg.: txt, log etc. 'create_text_files' => false, // only create files with exts. defined in $editable_text_file_exts // you can preview these type of files if $preview_text_files is true 'previewable_text_file_exts' => array( 'txt', 'log', 'xml', 'html', 'css', 'htm', 'js' ), 'previewable_text_file_exts_no_prettify' => array( 'txt', 'log' ), // you can edit these type of files if $edit_text_files is true (only text based files) // you can create these type of files if $create_text_files is true (only text based files) // if you want you can add html,css etc. // but for security reasons it's NOT RECOMMENDED! 'editable_text_file_exts' => array( 'txt', 'log', 'xml', 'html', 'css', 'htm', 'js' ), // Preview with Google Documents 'googledoc_enabled' => true, 'googledoc_file_exts' => array( 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx' ), // Preview with Viewer.js 'viewerjs_enabled' => true, 'viewerjs_file_exts' => array( 'pdf', 'odt', 'odp', 'ods' ), // defines size limit for paste in MB / operation // set 'FALSE' for no limit 'copy_cut_max_size' => 100, // defines file count limit for paste / operation // set 'FALSE' for no limit 'copy_cut_max_count' => 200, //IF any of these limits reached, operation won't start and generate warning //********************** //Allowed extensions (lowercase insert) //********************** 'ext_img' => array( 'jpg', 'jpeg', 'png', 'gif', 'bmp', 'tiff', 'svg' ), //Images 'ext_file' => array( 'doc', 'docx', 'rtf', 'pdf', 'xls', 'xlsx', 'txt', 'csv', 'html', 'xhtml', 'psd', 'sql', 'log', 'fla', 'xml', 'ade', 'adp', 'mdb', 'accdb', 'ppt', 'pptx', 'odt', 'ots', 'ott', 'odb', 'odg', 'otp', 'otg', 'odf', 'ods', 'odp', 'css', 'ai', 'kmz' ), //Files 'ext_video' => array( 'mov', 'mpeg', 'm4v', 'mp4', 'avi', 'mpg', 'wma', "flv", "webm" ), //Video 'ext_music' => array( 'mp3', 'mpga', 'm4a', 'ac3', 'aiff', 'mid', 'ogg', 'wav' ), //Audio 'ext_misc' => array( 'zip', 'rar', 'gz', 'tar', 'iso', 'dmg' ), //Archives /****************** * AVIARY config *******************/ 'aviary_active' => true, 'aviary_apiKey' => "2444282ef4344e3dacdedc7a78f8877d", 'aviary_language' => "en", 'aviary_theme' => "light", 'aviary_tools' => "all", 'aviary_maxSize' => "1400", // Add or modify the Aviary options below as needed - they will be json encoded when added to the configuration so arrays can be utilized as needed //The filter and sorter are managed through both javascript and php scripts because if you have a lot of //file in a folder the javascript script can't sort all or filter all, so the filemanager switch to php script. //The plugin automatic swich javascript to php when the current folder exceeds the below limit of files number 'file_number_limit_js' => 500, //********************** // Hidden files and folders //********************** // set the names of any folders you want hidden (eg "hidden_folder1", "hidden_folder2" ) Remember all folders with these names will be hidden (you can set any exceptions in config.php files on folders) 'hidden_folders' => array(), // set the names of any files you want hidden. Remember these names will be hidden in all folders (eg "this_document.pdf", "that_image.jpg" ) 'hidden_files' => array( 'config.php' ), /******************* * JAVA upload *******************/ 'java_upload' => true, 'JAVAMaxSizeUpload' => 200, //Gb //************************************ //Thumbnail for external use creation //************************************ // New image resized creation with fixed path from filemanager folder after uploading (thumbnails in fixed mode) // If you want create images resized out of upload folder for use with external script you can choose this method, // You can create also more than one image at a time just simply add a value in the array // Remember than the image creation respect the folder hierarchy so if you are inside source/test/test1/ the new image will create at // path_from_filemanager/test/test1/ // PS if there isn't write permission in your destination folder you must set it // 'fixed_image_creation' => false, //activate or not the creation of one or more image resized with fixed path from filemanager folder 'fixed_path_from_filemanager' => array( '../test/', '../test1/' ), //fixed path of the image folder from the current position on upload folder 'fixed_image_creation_name_to_prepend' => array( '', 'test_' ), //name to prepend on filename 'fixed_image_creation_to_append' => array( '_test', '' ), //name to appendon filename 'fixed_image_creation_width' => array( 300, 400 ), //width of image (you can leave empty if you set height) 'fixed_image_creation_height' => array( 200, '' ), //height of image (you can leave empty if you set width) /* # $option: 0 / exact = defined size; # 1 / portrait = keep aspect set height; # 2 / landscape = keep aspect set width; # 3 / auto = auto; # 4 / crop= resize and crop; */ 'fixed_image_creation_option' => array( 'crop', 'auto' ), //set the type of the crop // New image resized creation with relative path inside to upload folder after uploading (thumbnails in relative mode) // With Responsive filemanager you can create automatically resized image inside the upload folder, also more than one at a time // just simply add a value in the array // The image creation path is always relative so if i'm inside source/test/test1 and I upload an image, the path start from here // 'relative_image_creation' => false, //activate or not the creation of one or more image resized with relative path from upload folder 'relative_path_from_current_pos' => array( './', './' ), //relative path of the image folder from the current position on upload folder 'relative_image_creation_name_to_prepend' => array( '', '' ), //name to prepend on filename 'relative_image_creation_name_to_append' => array( '_thumb', '_thumb1' ), //name to append on filename 'relative_image_creation_width' => array( 300, 400 ), //width of image (you can leave empty if you set height) 'relative_image_creation_height' => array( 200, '' ), //height of image (you can leave empty if you set width) /* # $option: 0 / exact = defined size; # 1 / portrait = keep aspect set height; # 2 / landscape = keep aspect set width; # 3 / auto = auto; # 4 / crop= resize and crop; */ 'relative_image_creation_option' => array( 'crop', 'crop' ), //set the type of the crop // Remember text filter after close filemanager for future session 'remember_text_filter' => false, ); return array_merge( $config, array( 'MaxSizeUpload' => ((int)(ini_get('post_max_size')) < $config['MaxSizeUpload']) ? (int)(ini_get('post_max_size')) : $config['MaxSizeUpload'], 'ext'=> array_merge( $config['ext_img'], $config['ext_file'], $config['ext_misc'], $config['ext_video'], $config['ext_music'] ), // For a list of options see: https://developers.aviary.com/docs/web/setup-guide#constructor-config 'aviary_defaults_config' => array( 'apiKey' => $config['aviary_apiKey'], 'language' => $config['aviary_language'], 'theme' => $config['aviary_theme'], 'tools' => $config['aviary_tools'], 'maxSize' => $config['aviary_maxSize'] ), ) ); ?>
mit
secondrotation/dump_truck
lib/dump_truck.rb
1365
require 'dump_truck/version' require 'colorize' require 'dump_truck/configuration' require 'dump_truck/database_configuration' require 'dump_truck/schema_configuration' require 'dump_truck/table_configuration' require 'dump_truck/target' require 'dump_truck/truck' require 'dump_truck/loggable_truck' require 'dump_truck/mysql' class DumpTruck attr_reader :config def initialize(&block) @config = Configuration.new(&block) end def dump config.each_database do |db_config| dump_database(db_config) end end private def dump_database(db_config) db_config.each_schema.map do |schema_config| truck(db_config, schema_config) end.map do |truck| Thread.new(truck){|t| t.dump} end.each do |thread| thread.join end end def truck(db_config, schema_config) translator = translator_for(db_config.type) client = client_for(db_config.type, db_config, schema_config) LoggableTruck.new(schema_config, client, translator, config.logger) end def translator_for(type) case type.to_sym when :mysql Mysql::Translator.new else raise "Unknown type #{type}" end end def client_for(type, db_config, schema_config) case type.to_sym when :mysql Mysql::Client.new(db_config, schema_config) else raise "Unknown type #{type}" end end end
mit
atonse/mobiledoc-kit
tests/unit/parsers/mobiledoc/0-3-test.js
5216
import MobiledocParser from 'mobiledoc-kit/parsers/mobiledoc/0-3'; import { MOBILEDOC_VERSION } from 'mobiledoc-kit/renderers/mobiledoc/0-3'; import PostNodeBuilder from 'mobiledoc-kit/models/post-node-builder'; const DATA_URL = "data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACwAAAAAAQABAAACAkQBADs="; const { module, test } = window.QUnit; let parser, builder, post; module('Unit: Parsers: Mobiledoc 0.3', { beforeEach() { builder = new PostNodeBuilder(); parser = new MobiledocParser(builder); post = builder.createPost(); }, afterEach() { parser = null; builder = null; post = null; } }); test('#parse empty doc returns an empty post', (assert) => { const mobiledoc = { version: MOBILEDOC_VERSION, atoms: [], cards: [], markups: [], sections: [] }; const parsed = parser.parse(mobiledoc); assert.equal(parsed.sections.length, 0, '0 sections'); }); test('#parse empty markup section returns an empty post', (assert) => { const mobiledoc = { version: MOBILEDOC_VERSION, atoms: [], cards: [], markups: [], sections: [ [1, 'p', []] ] }; const section = builder.createMarkupSection('p'); post.sections.append(section); assert.deepEqual(parser.parse(mobiledoc), post); }); test('#parse doc without marker types', (assert) => { const mobiledoc = { version: MOBILEDOC_VERSION, atoms: [], cards: [], markups: [], sections: [ [ 1,'P', [[0, [], 0, 'hello world']] ] ] }; const parsed = parser.parse(mobiledoc); let section = builder.createMarkupSection('P', [], false); let marker = builder.createMarker('hello world'); section.markers.append(marker); post.sections.append(section); assert.deepEqual( parsed, post ); }); test('#parse doc with blank marker', (assert) => { const mobiledoc = { version: MOBILEDOC_VERSION, atoms: [], cards: [], markups: [], sections: [ [ 1,'P', [[0, [], 0, '']] ] ] }; const parsed = parser.parse(mobiledoc); let section = builder.createMarkupSection('P', [], false); post.sections.append(section); assert.deepEqual( parsed, post ); }); test('#parse doc with marker type', (assert) => { const mobiledoc = { version: MOBILEDOC_VERSION, atoms: [], cards: [], markups: [ ['B'], ['A', ['href', 'google.com']] ], sections: [ [ 1,'P', [ [0, [1], 0, 'hello'], // a tag open [0, [0], 1, 'brave new'], // b tag open/close [0, [], 1, 'world'] // a tag close ] ] ] }; const parsed = parser.parse(mobiledoc); let section = builder.createMarkupSection('P', [], false); let aMarkerType = builder.createMarkup('A', {href:'google.com'}); let bMarkerType = builder.createMarkup('B'); let markers = [ builder.createMarker('hello', [aMarkerType]), builder.createMarker('brave new', [aMarkerType, bMarkerType]), builder.createMarker('world', [aMarkerType]) ]; markers.forEach(marker => section.markers.append(marker)); post.sections.append(section); assert.deepEqual( parsed, post ); }); test('#parse doc with image section', (assert) => { const mobiledoc = { version: MOBILEDOC_VERSION, atoms: [], cards: [], markups: [], sections: [ [2, DATA_URL] ] }; const parsed = parser.parse(mobiledoc); let section = builder.createImageSection(DATA_URL); post.sections.append(section); assert.deepEqual( parsed, post ); }); test('#parse doc with custom card type', (assert) => { const mobiledoc = { version: MOBILEDOC_VERSION, atoms: [], cards: [ ['custom-card', {}] ], markups: [], sections: [ [10, 0] ] }; const parsed = parser.parse(mobiledoc); let section = builder.createCardSection('custom-card'); post.sections.append(section); assert.deepEqual( parsed, post ); }); test('#parse doc with custom atom type', (assert) => { const mobiledoc = { version: MOBILEDOC_VERSION, atoms: [ ['mention', '@bob', { id: 42 }] ], cards: [], markups: [], sections: [ [ 1,'P', [ [1, [], 0, 0] ] ] ] }; const parsed = parser.parse(mobiledoc); let section = builder.createMarkupSection('P', [], false); let atom = builder.createAtom('mention', '@bob', { id: 42 }); section.markers.append(atom); post.sections.append(section); assert.deepEqual( parsed, post ); }); test('#parse a mobile doc with list-section and list-item', (assert) => { const mobiledoc = { version: MOBILEDOC_VERSION, atoms: [], cards: [], markups: [], sections: [ [3, 'ul', [ [[0, [], 0, "first item"]], [[0, [], 0, "second item"]] ]] ] }; const parsed = parser.parse(mobiledoc); const items = [ builder.createListItem([builder.createMarker('first item')]), builder.createListItem([builder.createMarker('second item')]) ]; const section = builder.createListSection('ul', items); post.sections.append(section); assert.deepEqual( parsed, post ); });
mit
FARIDMESCAM/Manufacture
config.php
5884
<?php if (!isset($_SERVER['HTTP_HOST'])) { exit('This script cannot be run from the CLI. Run it from a browser.'); } //if (!in_array(@$_SERVER['REMOTE_ADDR'], array( // '127.0.0.1', // '::1', //))) { // header('HTTP/1.0 403 Forbidden'); // exit('This script is only accessible from localhost.'); //} require_once dirname(__FILE__).'/../app/SymfonyRequirements.php'; $symfonyRequirements = new SymfonyRequirements(); $majorProblems = $symfonyRequirements->getFailedRequirements(); $minorProblems = $symfonyRequirements->getFailedRecommendations(); ?> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <meta name="robots" content="noindex,nofollow" /> <title>Symfony Configuration</title> <link rel="stylesheet" href="bundles/framework/css/structure.css" media="all" /> <link rel="stylesheet" href="bundles/framework/css/body.css" media="all" /> <link rel="stylesheet" href="bundles/sensiodistribution/webconfigurator/css/install.css" media="all" /> </head> <body> <div id="content"> <div class="header clear-fix"> <div class="header-logo"> <img src="bundles/framework/images/logo_symfony.png" alt="Symfony" /> </div> <div class="search"> <form method="get" action="http://symfony.com/search"> <div class="form-row"> <label for="search-id"> <img src="bundles/framework/images/grey_magnifier.png" alt="Search on Symfony website" /> </label> <input name="q" id="search-id" type="search" placeholder="Search on Symfony website" /> <button type="submit" class="sf-button"> <span class="border-l"> <span class="border-r"> <span class="btn-bg">OK</span> </span> </span> </button> </div> </form> </div> </div> <div class="sf-reset"> <div class="block"> <div class="symfony-block-content"> <h1 class="title">Welcome!</h1> <p>Welcome to your new Symfony project.</p> <p> This script will guide you through the basic configuration of your project. You can also do the same by editing the ‘<strong>app/config/parameters.yml</strong>’ file directly. </p> <?php if (count($majorProblems)): ?> <h2 class="ko">Major problems</h2> <p>Major problems have been detected and <strong>must</strong> be fixed before continuing:</p> <ol> <?php foreach ($majorProblems as $problem): ?> <li><?php echo $problem->getHelpHtml() ?></li> <?php endforeach; ?> </ol> <?php endif; ?> <?php if (count($minorProblems)): ?> <h2>Recommendations</h2> <p> <?php if (count($majorProblems)): ?>Additionally, to<?php else: ?>To<?php endif; ?> enhance your Symfony experience, it’s recommended that you fix the following: </p> <ol> <?php foreach ($minorProblems as $problem): ?> <li><?php echo $problem->getHelpHtml() ?></li> <?php endforeach; ?> </ol> <?php endif; ?> <?php if ($symfonyRequirements->hasPhpIniConfigIssue()): ?> <p id="phpini">* <?php if ($symfonyRequirements->getPhpIniConfigPath()): ?> Changes to the <strong>php.ini</strong> file must be done in "<strong><?php echo $symfonyRequirements->getPhpIniConfigPath() ?></strong>". <?php else: ?> To change settings, create a "<strong>php.ini</strong>". <?php endif; ?> </p> <?php endif; ?> <?php if (!count($majorProblems) && !count($minorProblems)): ?> <p class="ok">Your configuration looks good to run Symfony.</p> <?php endif; ?> <ul class="symfony-install-continue"> <?php if (!count($majorProblems)): ?> <li><a href="app_dev.php/_configurator/">Configure your Symfony Application online</a></li> <li><a href="app_dev.php/">Bypass configuration and go to the Welcome page</a></li> <?php endif; ?> <?php if (count($majorProblems) || count($minorProblems)): ?> <li><a href="config.php">Re-check configuration</a></li> <?php endif; ?> </ul> </div> </div> </div> <div class="version">Symfony Standard Edition</div> </div> </body> </html>
mit
eidias/Training
BestPractices/BestPractices.Shell/Patterns/Visitor.cs
149
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VisitorPattern { }
mit
akashnautiyal013/ImpactRun01
components/ImpactLeague/ImpactLeagueHome.js
9198
'use strict'; import React, { Component } from 'react'; import{ StyleSheet, View, Image, ScrollView, Dimensions, TouchableOpacity, Text, ListView, AlertIOS, NetInfo, AsyncStorage, RefreshControl, } from 'react-native'; import apis from '../apis'; import commonStyles from '../styles'; import Icon from 'react-native-vector-icons/Ionicons'; import GiftedListView from 'react-native-gifted-listview'; import LodingScreen from '../LodingScreen'; import TimerMixin from 'react-timer-mixin'; import styleConfig from '../styleConfig' var deviceWidth = Dimensions.get('window').width; var deviceHeight = Dimensions.get('window').height; class ImpactLeague extends Component { constructor(props) { super(props); this.fetchDataLocally(); var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); this.state = { LeaderBoardData: ds.cloneWithRows([]), loaded: false, refreshing: false, downrefresh:true, }; this.renderRow = this.renderRow.bind(this); this.NavigateToDetail = this.NavigateToDetail.bind(this); } mixins: [TimerMixin] componentDidMount() { this.getUserData(); setTimeout(() => {this.setState({downrefresh: false})}, 1000) } componentWillMount() { } fetchDataLocally(){ AsyncStorage.multiGet(['UID234'], (err, stores) => { stores.map((result, i, store) => { let key = store[i][0]; let val = store[i][1]; let user = JSON.parse(val); this.setState({ user:user, }) AsyncStorage.getItem('teamleaderBoardData', (err, result) => { var boardData = JSON.parse(result); if (result != null || undefined) { this.setState({ LeaderBoardData: this.state.LeaderBoardData.cloneWithRows(boardData.results), BannerData:boardData.results[0].impactleague_banner, leaguename:boardData.results[0].impactleague, loaded: true, }) }else{ this.getUserData(); this.setState({ leaguename:'Impact League' }) } }); }); }); } getUserData(){ AsyncStorage.multiGet(['UID234'], (err, stores) => { stores.map((result, i, store) => { let key = store[i][0]; let val = store[i][1]; let user = JSON.parse(val); this.setState({ user:user, }) NetInfo.isConnected.fetch().done( (isConnected) => { this.setState({isConnected}); if (isConnected) { this.fetchLeaderBoardData(); }; } ); }) }) } fetchLeaderBoardData() { var token = this.state.user.auth_token; var url = apis.ImpactLeagueTeamLeaderBoardApi; fetch(url,{ method: "GET", headers: { 'Authorization':"Bearer "+ token, 'Content-Type':'application/x-www-form-urlencoded', } }) .then( response => response.json() ) .then( jsonData => { this.setState({ LeaderBoardData: this.state.LeaderBoardData.cloneWithRows(jsonData.results), loaded: true, refreshing:false, BannerData:jsonData.results[0].impactleague_banner, }); AsyncStorage.removeItem('teamleaderBoardData',(err) => { }); let teamleaderBoardData = jsonData; AsyncStorage.setItem('teamleaderBoardData',JSON.stringify(teamleaderBoardData)); }) .catch( error => console.log('Error fetching: ' + error) ); } NavigateToleagueend(){ this.props.navigator.push({ title: 'leaderboard', id:'leaderboard', }) } NavigateToDetail(rowData){ this.props.navigator.push({ title: 'impactleaguehome', id:'impactleagueleaderboard', passProps:{user:this.props.user, Team_id:rowData.id} }) } goBack(){ if (this.props.data == 'fromshare') { this.props.navigator.push({ id:'tab', }) }else{ this.props.navigator.pop({}) } } _onRefresh() { this.setState({refreshing: true}); this.fetchLeaderBoardData(); } renderRow(rowData,index,rowID){ rowID++ var me = this; var backgroundColor =(me.state.user.team_code === rowData.id)?'#ffcd4d':'#fff'; return ( <View style={{justifyContent: 'center',alignItems: 'center',}}> <TouchableOpacity onPress={()=>this.NavigateToDetail(rowData)} style={[styles.cardLeaderBoard,{backgroundColor:backgroundColor}]}> <Text style={{fontFamily: 'Montserrat-Regular',fontWeight:'400',fontSize:17,color:'#4a4a4a',}}>{rowID}</Text> <Text numberOfLines={1} style={styles.txt}>{rowData.team_name}</Text> <View style={{width:deviceWidth/2-20, alignItems:'flex-end'}}> <Text style={styles.txtSec}>{parseFloat(rowData.total_distance.total_distance).toFixed(2)} Km</Text> </View> </TouchableOpacity> </View> ); } renderLoadingView() { return ( <View style={{height:deviceHeight}}> <View style={commonStyles.Navbar}> <TouchableOpacity style={{left:0,position:'absolute',height:60,width:60,backgroundColor:'transparent',justifyContent: 'center',alignItems: 'center',}} onPress={()=>this.goBack()} > <Icon style={{color:'white',fontSize:30,fontWeight:'bold'}}name={(this.props.data === 'fromshare')?'md-home':'ios-arrow-back'}></Icon> </TouchableOpacity> <Text numberOfLines={1} style={commonStyles.menuTitle}>{this.state.leaguename}</Text> </View> <LodingScreen style={{height:deviceHeight-50}}/> </View> ); } swwipeDowntoRefress(){ if (this.state.downrefresh === true) { return( <View style={styles.swipedown}><Text style={styles.txt3}>Pull down to refresh</Text></View> ) }else{ return; } } render(rowData,jsonData) { if (!this.state.loaded) { return this.renderLoadingView(); } return ( <View> <View style={commonStyles.Navbar}> <TouchableOpacity style={{left:0,position:'absolute',height:60,width:60,backgroundColor:'transparent',justifyContent: 'center',alignItems: 'center',}} onPress={()=>this.goBack()} > <Icon style={{color:'white',fontSize:30,fontWeight:'bold'}}name={(this.props.data === 'fromshare')?'md-home':'ios-arrow-back'}></Icon> </TouchableOpacity> <Text numberOfLines={1} style={commonStyles.menuTitle}>{this.state.leaguename}</Text> </View> <View> <Image source={{uri:this.state.BannerData}} style={styles.bannerimage}> </Image> {this.swwipeDowntoRefress()} <ListView refreshControl={ <RefreshControl refreshing={this.state.refreshing} onRefresh={this._onRefresh.bind(this)} />} navigator={this.props.navigator} dataSource={this.state.LeaderBoardData} renderRow={this.renderRow} style={styles.container}> <View style={{width:deviceWidth,height:20,backgroundColor:'red'}}></View> </ListView> </View> </View> ); } } const styles = StyleSheet.create({ container: { backgroundColor:'white', height:deviceHeight-(deviceHeight/2-100)-75, }, cardLeaderBoard:{ alignItems: 'center', flexDirection:'row', padding:20, margin:5, width:deviceWidth-10, borderRadius:5, shadowColor: '#000000', shadowOpacity: 0.2, shadowRadius: 4, shadowOffset: { height: 3, }, }, swipedown:{ height:30, width:deviceWidth, backgroundColor:styleConfig.bright_blue, justifyContent: 'center', alignItems: 'center', }, bannerimage:{ height:deviceHeight/2-100, }, txt: { width:deviceWidth-200, color:'#4a4a4a', fontSize: 15, fontWeight:'400', textAlign: 'left', marginLeft:10, fontFamily: 'Montserrat-Regular', }, txt3: { color:'white', fontSize: 13, fontWeight:'400', fontFamily: 'Montserrat-Regular', }, txtSec:{ color:'#4a4a4a', fontSize:17, fontWeight:'400', right:deviceWidth/4-50, textAlign:'right', alignItems:'flex-end', fontFamily: 'Montserrat-Regular', }, }); export default ImpactLeague;
mit