code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
module SynapseClient
class Merchant
attr_accessor :client_id
attr_accessor :client_secret
attr_accessor :oauth_merchant_key
attr_accessor :merchant_email
attr_accessor :device_id
def initialize(options ={})
options = Map.new(options)
@client_id = options[:client_id] || ENV["SYNAPSE_CLIENT_ID"]
@client_secret = options[:client_secret] || ENV["SYNAPSE_CLIENT_SECRET"]
@oauth_merchant_key = options[:oauth_merchant_key] || ENV["SYNAPSE_OAUTH_MERCHANT_KEY"]
@merchant_email = options[:merchant_email] || ENV["SYNAPSE_MERCHANT_EMAIL"]
@device_id = options[:device_id] || ENV["SYNAPSE_DEVICE_ID"]
end
end
end
| milesmatthias/synapse_client | lib/synapse_client/merchant.rb | Ruby | mit | 734 |
import qor
from scripts import ctf
class Mod(qor.Mod):
def __init__(self):
# set up specific things that engine needs to know about the mod
# possibly setting up customized gui, background music, theming, etc.
# include possible selections of things, and which customizations to
# enable
pass
def validate():
# make sure the game can be run with the current players/settings
self.map_info = qor.MapInfo(qor.get("map","church"))
if qor.is_map(self.map_info):
raise qor.Error
# checks with ctf script if the given map is okay
if not ctf.valid_map(self.map_info):
raise qor.Error
def preload():
# set up FOV and all that good stuff (possibly read from player config)
qor.ortho(False)
# set up any mod-specific stuff
# load a specific (or user selected) map
self.level = qor.Map(self.map_fn)
self.mode_logic = ctf.logic
def update(t):
# possibly distinguish between client and server somewhere here
# do player logic (do different classes and characters have diff logic)?
self.mode_logic(t)
# update the game, call any modes logic or policies here
def event(ev):
# called upon specific game events
# also called if something changes in config that must affect game
pass
#def stats():
# pass
| flipcoder/qor | bin/mods/example/__init__.py | Python | mit | 1,487 |
<?php
namespace Imp\AppBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* This is the class that validates and merges configuration from your app/config files
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritDoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('imp_app');
// Here you should define the parameters that are allowed to
// configure your bundle. See the documentation linked above for
// more information on that topic.
return $treeBuilder;
}
}
| AlexanderPok/Football | src/Imp/AppBundle/DependencyInjection/Configuration.php | PHP | mit | 869 |
import { Injector, Pipe, PipeTransform } from '@angular/core';
import { AppComponentBase } from '@shared/app-component-base';
@Pipe({
name: 'localize'
})
export class LocalizePipe extends AppComponentBase implements PipeTransform {
constructor(injector: Injector) {
super(injector);
}
transform(key: string, ...args: any[]): string {
return this.l(key, ...args);
}
}
| aspnetboilerplate/module-zero-core-template | angular/src/shared/pipes/localize.pipe.ts | TypeScript | mit | 406 |
"use strict";
var Client_1 = require('./src/helpers/Client');
exports.Client = Client_1.Client;
//# sourceMappingURL=index.js.map | alormil/put.io-node | js/ts/index.js | JavaScript | mit | 129 |
(function() {
angular.module('signup', [ 'userServiceMod' ])
.controller('SignupCtrl', ['$location', 'userService', 'validator', function($location, userService, validator) {
var signup = this;
signup.buttonEnabled = true;
signup.err = {
username: "",
email: "",
password: "",
server: ""
};
signup.data = {
username: "",
email: "",
password: ""
};
signup.submit = function() {
if (!signup.buttonEnabled) {
return;
}
var errors = null;
// reset err messages
signup.err.username = "";
signup.err.email = "";
signup.err.password = "";
signup.err.server = "";
// check validity of data
errors = validator('user', signup.data, ['username', 'email', 'password']);
if (errors) {
signup.err = errors;
return;
}
// disable submit button
signup.buttonEnabled = false;
userService.signup(signup.data, function(err, data) {
if (err) {
// enable submit button
signup.buttonEnabled = true;
if (err.status === 400) {
// email or username already in use
signup.err.server = err.data.error;
} else {
signup.err.server = "There was a problem with the server. Please try again.";
}
return;
}
// redirect to user's page
$location.path('/' + userService.getUser().username);
});
};
}]);
})(); | BYossarian/focus | public/js/controllers/signup.js | JavaScript | mit | 2,063 |
from __future__ import absolute_import, print_function, division
import operator
from petl.compat import text_type
from petl.util.base import Table, asindices, itervalues
from petl.transform.sorts import sort
def duplicates(table, key=None, presorted=False, buffersize=None, tempdir=None,
cache=True):
"""
Select rows with duplicate values under a given key (or duplicate
rows where no key is given). E.g.::
>>> import petl as etl
>>> table1 = [['foo', 'bar', 'baz'],
... ['A', 1, 2.0],
... ['B', 2, 3.4],
... ['D', 6, 9.3],
... ['B', 3, 7.8],
... ['B', 2, 12.3],
... ['E', None, 1.3],
... ['D', 4, 14.5]]
>>> table2 = etl.duplicates(table1, 'foo')
>>> table2
+-----+-----+------+
| foo | bar | baz |
+=====+=====+======+
| 'B' | 2 | 3.4 |
+-----+-----+------+
| 'B' | 3 | 7.8 |
+-----+-----+------+
| 'B' | 2 | 12.3 |
+-----+-----+------+
| 'D' | 6 | 9.3 |
+-----+-----+------+
| 'D' | 4 | 14.5 |
+-----+-----+------+
>>> # compound keys are supported
... table3 = etl.duplicates(table1, key=['foo', 'bar'])
>>> table3
+-----+-----+------+
| foo | bar | baz |
+=====+=====+======+
| 'B' | 2 | 3.4 |
+-----+-----+------+
| 'B' | 2 | 12.3 |
+-----+-----+------+
If `presorted` is True, it is assumed that the data are already sorted by
the given key, and the `buffersize`, `tempdir` and `cache` arguments are
ignored. Otherwise, the data are sorted, see also the discussion of the
`buffersize`, `tempdir` and `cache` arguments under the
:func:`petl.transform.sorts.sort` function.
See also :func:`petl.transform.dedup.unique` and
:func:`petl.transform.dedup.distinct`.
"""
return DuplicatesView(table, key=key, presorted=presorted,
buffersize=buffersize, tempdir=tempdir, cache=cache)
Table.duplicates = duplicates
class DuplicatesView(Table):
def __init__(self, source, key=None, presorted=False, buffersize=None,
tempdir=None, cache=True):
if presorted:
self.source = source
else:
self.source = sort(source, key, buffersize=buffersize,
tempdir=tempdir, cache=cache)
self.key = key
def __iter__(self):
return iterduplicates(self.source, self.key)
def iterduplicates(source, key):
# assume source is sorted
# first need to sort the data
it = iter(source)
hdr = next(it)
yield tuple(hdr)
# convert field selection into field indices
if key is None:
indices = range(len(hdr))
else:
indices = asindices(hdr, key)
# now use field indices to construct a _getkey function
# N.B., this may raise an exception on short rows, depending on
# the field selection
getkey = operator.itemgetter(*indices)
previous = None
previous_yielded = False
for row in it:
if previous is None:
previous = row
else:
kprev = getkey(previous)
kcurr = getkey(row)
if kprev == kcurr:
if not previous_yielded:
yield tuple(previous)
previous_yielded = True
yield tuple(row)
else:
# reset
previous_yielded = False
previous = row
def unique(table, key=None, presorted=False, buffersize=None, tempdir=None,
cache=True):
"""
Select rows with unique values under a given key (or unique rows
if no key is given). E.g.::
>>> import petl as etl
>>> table1 = [['foo', 'bar', 'baz'],
... ['A', 1, 2],
... ['B', '2', '3.4'],
... ['D', 'xyz', 9.0],
... ['B', u'3', u'7.8'],
... ['B', '2', 42],
... ['E', None, None],
... ['D', 4, 12.3],
... ['F', 7, 2.3]]
>>> table2 = etl.unique(table1, 'foo')
>>> table2
+-----+------+------+
| foo | bar | baz |
+=====+======+======+
| 'A' | 1 | 2 |
+-----+------+------+
| 'E' | None | None |
+-----+------+------+
| 'F' | 7 | 2.3 |
+-----+------+------+
If `presorted` is True, it is assumed that the data are already sorted by
the given key, and the `buffersize`, `tempdir` and `cache` arguments are
ignored. Otherwise, the data are sorted, see also the discussion of the
`buffersize`, `tempdir` and `cache` arguments under the
:func:`petl.transform.sorts.sort` function.
See also :func:`petl.transform.dedup.duplicates` and
:func:`petl.transform.dedup.distinct`.
"""
return UniqueView(table, key=key, presorted=presorted,
buffersize=buffersize, tempdir=tempdir, cache=cache)
Table.unique = unique
class UniqueView(Table):
def __init__(self, source, key=None, presorted=False, buffersize=None,
tempdir=None, cache=True):
if presorted:
self.source = source
else:
self.source = sort(source, key, buffersize=buffersize,
tempdir=tempdir, cache=cache)
self.key = key
def __iter__(self):
return iterunique(self.source, self.key)
def iterunique(source, key):
# assume source is sorted
# first need to sort the data
it = iter(source)
hdr = next(it)
yield tuple(hdr)
# convert field selection into field indices
if key is None:
indices = range(len(hdr))
else:
indices = asindices(hdr, key)
# now use field indices to construct a _getkey function
# N.B., this may raise an exception on short rows, depending on
# the field selection
getkey = operator.itemgetter(*indices)
try:
prev = next(it)
except StopIteration:
return
prev_key = getkey(prev)
prev_comp_ne = True
for curr in it:
curr_key = getkey(curr)
curr_comp_ne = (curr_key != prev_key)
if prev_comp_ne and curr_comp_ne:
yield tuple(prev)
prev = curr
prev_key = curr_key
prev_comp_ne = curr_comp_ne
# last one?
if prev_comp_ne:
yield prev
def conflicts(table, key, missing=None, include=None, exclude=None,
presorted=False, buffersize=None, tempdir=None, cache=True):
"""
Select rows with the same key value but differing in some other field.
E.g.::
>>> import petl as etl
>>> table1 = [['foo', 'bar', 'baz'],
... ['A', 1, 2.7],
... ['B', 2, None],
... ['D', 3, 9.4],
... ['B', None, 7.8],
... ['E', None],
... ['D', 3, 12.3],
... ['A', 2, None]]
>>> table2 = etl.conflicts(table1, 'foo')
>>> table2
+-----+-----+------+
| foo | bar | baz |
+=====+=====+======+
| 'A' | 1 | 2.7 |
+-----+-----+------+
| 'A' | 2 | None |
+-----+-----+------+
| 'D' | 3 | 9.4 |
+-----+-----+------+
| 'D' | 3 | 12.3 |
+-----+-----+------+
Missing values are not considered conflicts. By default, `None` is treated
as the missing value, this can be changed via the `missing` keyword
argument.
One or more fields can be ignored when determining conflicts by providing
the `exclude` keyword argument. Alternatively, fields to use when
determining conflicts can be specified explicitly with the `include`
keyword argument. This provides a simple mechanism for analysing the
source of conflicting rows from multiple tables, e.g.::
>>> table1 = [['foo', 'bar'], [1, 'a'], [2, 'b']]
>>> table2 = [['foo', 'bar'], [1, 'a'], [2, 'c']]
>>> table3 = etl.cat(etl.addfield(table1, 'source', 1),
... etl.addfield(table2, 'source', 2))
>>> table4 = etl.conflicts(table3, key='foo', exclude='source')
>>> table4
+-----+-----+--------+
| foo | bar | source |
+=====+=====+========+
| 2 | 'b' | 1 |
+-----+-----+--------+
| 2 | 'c' | 2 |
+-----+-----+--------+
If `presorted` is True, it is assumed that the data are already sorted by
the given key, and the `buffersize`, `tempdir` and `cache` arguments are
ignored. Otherwise, the data are sorted, see also the discussion of the
`buffersize`, `tempdir` and `cache` arguments under the
:func:`petl.transform.sorts.sort` function.
"""
return ConflictsView(table, key, missing=missing, exclude=exclude,
include=include, presorted=presorted,
buffersize=buffersize, tempdir=tempdir, cache=cache)
Table.conflicts = conflicts
class ConflictsView(Table):
def __init__(self, source, key, missing=None, exclude=None, include=None,
presorted=False, buffersize=None, tempdir=None, cache=True):
if presorted:
self.source = source
else:
self.source = sort(source, key, buffersize=buffersize,
tempdir=tempdir, cache=cache)
self.key = key
self.missing = missing
self.exclude = exclude
self.include = include
def __iter__(self):
return iterconflicts(self.source, self.key, self.missing, self.exclude,
self.include)
def iterconflicts(source, key, missing, exclude, include):
# normalise arguments
if exclude and not isinstance(exclude, (list, tuple)):
exclude = (exclude,)
if include and not isinstance(include, (list, tuple)):
include = (include,)
# exclude overrides include
if include and exclude:
include = None
it = iter(source)
hdr = next(it)
flds = list(map(text_type, hdr))
yield tuple(hdr)
# convert field selection into field indices
indices = asindices(hdr, key)
# now use field indices to construct a _getkey function
# N.B., this may raise an exception on short rows, depending on
# the field selection
getkey = operator.itemgetter(*indices)
previous = None
previous_yielded = False
for row in it:
if previous is None:
previous = row
else:
kprev = getkey(previous)
kcurr = getkey(row)
if kprev == kcurr:
# is there a conflict?
conflict = False
for x, y, f in zip(previous, row, flds):
if (exclude and f not in exclude) \
or (include and f in include) \
or (not exclude and not include):
if missing not in (x, y) and x != y:
conflict = True
break
if conflict:
if not previous_yielded:
yield tuple(previous)
previous_yielded = True
yield tuple(row)
else:
# reset
previous_yielded = False
previous = row
def distinct(table, key=None, count=None, presorted=False, buffersize=None,
tempdir=None, cache=True):
"""
Return only distinct rows in the table.
If the `count` argument is not None, it will be used as the name for an
additional field, and the values of the field will be the number of
duplicate rows.
If the `key` keyword argument is passed, the comparison is done on the
given key instead of the full row.
See also :func:`petl.transform.dedup.duplicates`,
:func:`petl.transform.dedup.unique`,
:func:`petl.transform.reductions.groupselectfirst`,
:func:`petl.transform.reductions.groupselectlast`.
"""
return DistinctView(table, key=key, count=count, presorted=presorted,
buffersize=buffersize, tempdir=tempdir, cache=cache)
Table.distinct = distinct
class DistinctView(Table):
def __init__(self, table, key=None, count=None, presorted=False,
buffersize=None, tempdir=None, cache=True):
if presorted:
self.table = table
else:
self.table = sort(table, key=key, buffersize=buffersize,
tempdir=tempdir, cache=cache)
self.key = key
self.count = count
def __iter__(self):
it = iter(self.table)
hdr = next(it)
# convert field selection into field indices
if self.key is None:
indices = range(len(hdr))
else:
indices = asindices(hdr, self.key)
# now use field indices to construct a _getkey function
# N.B., this may raise an exception on short rows, depending on
# the field selection
getkey = operator.itemgetter(*indices)
INIT = object()
if self.count:
hdr = tuple(hdr) + (self.count,)
yield hdr
previous = INIT
n_dup = 1
for row in it:
if previous is INIT:
previous = row
else:
kprev = getkey(previous)
kcurr = getkey(row)
if kprev == kcurr:
n_dup += 1
else:
yield tuple(previous) + (n_dup,)
n_dup = 1
previous = row
# deal with last row
yield tuple(previous) + (n_dup,)
else:
yield tuple(hdr)
previous_keys = INIT
for row in it:
keys = getkey(row)
if keys != previous_keys:
yield tuple(row)
previous_keys = keys
def isunique(table, field):
"""
Return True if there are no duplicate values for the given field(s),
otherwise False. E.g.::
>>> import petl as etl
>>> table1 = [['foo', 'bar'],
... ['a', 1],
... ['b'],
... ['b', 2],
... ['c', 3, True]]
>>> etl.isunique(table1, 'foo')
False
>>> etl.isunique(table1, 'bar')
True
The `field` argument can be a single field name or index (starting from
zero) or a tuple of field names and/or indexes.
"""
vals = set()
for v in itervalues(table, field):
if v in vals:
return False
else:
vals.add(v)
return True
Table.isunique = isunique
| alimanfoo/petl | petl/transform/dedup.py | Python | mit | 15,217 |
from composite import *
from ensemble import *
from metrics import *
# from parametrization import *
from pdf import *
from utils import *
| aimalz/qp | qp/__init__.py | Python | mit | 145 |
'use strict';
angular.module('spc')
.factory('Auth', function Auth($location, $rootScope, $http, User, CremaAuth, spcServerUrl, apiKey, $cookieStore, $q) {
var currentMetaData = {};
if ($cookieStore.get('access_token')) {
currentMetaData = CremaAuth.get();
}
return {
/**
* Authenticate user and save token
*
* @param {Object} user - login info
* @param {Function} callback - optional
* @return {Promise}
*/
login: function (user) {
var deferred = $q.defer();
$http.post(spcServerUrl + '/api/auth/login', {
apikey: apiKey,
email: user.email,
password: user.password
}).
success(function (data) {
if (data.secondFactor) {
currentMetaData = data;
deferred.resolve(data);
} else {
$cookieStore.put('access_token', data.access_token);
currentMetaData = CremaAuth.get(null, function () {
deferred.resolve(data);
}, function (error) {
deferred.reject(error.data);
});
}
}).
error(function (err) {
this.logout();
deferred.reject(err);
}.bind(this));
return deferred.promise;
},
loginLdap: function (user) {
var deferred = $q.defer();
$http.post(spcServerUrl + '/api/auth/ldap', {
email: user.email,
password: user.password
}).
success(function (data) {
if (data.secondFactor) {
currentMetaData = data;
deferred.resolve(data);
} else {
$cookieStore.put('access_token', data.access_token);
currentMetaData = CremaAuth.get(null, function () {
deferred.resolve(data);
}, function (error) {
deferred.reject(error.data);
});
}
}).
error(function (err) {
this.logout();
deferred.reject(err);
}.bind(this));
return deferred.promise;
},
loginGoogle: function (accessToken, user) {
var deferred = $q.defer();
if (user.secondFactor) {
currentMetaData = user;
currentMetaData.$promise = '&promise';
deferred.resolve(currentMetaData);
} else {
$cookieStore.put('access_token', accessToken);
currentMetaData = CremaAuth.get(null, function() {
deferred.resolve();
}, function (error) {
deferred.reject(error.data);
});
}
return deferred.promise;
},
/**
* Delete access token and user info
*
* @param {Function}
*/
logout: function () {
$cookieStore.remove('access_token');
currentMetaData = {};
},
/**
* Create a new user
*
* @param {Object} user - user info
* @param {Function} callback - optional
* @return {Promise}
*/
createUser: function (user) {
var deferred = $q.defer();
console.debug("client auth.service.js createUser", "userData", user);
User.save(user).$promise.then(function (data) {
console.debug("client auth.service.js.createUser", "success", data);
$cookieStore.put('access_token', data.access_token);
return CremaAuth.get({id: currentMetaData._id}).$promise;
}).then(function (cremaUser) {
currentMetaData = cremaUser;
deferred.resolve(cremaUser)
}).catch(function (err) {
console.debug("client auth.service.js createUser", "failed", err);
deferred.reject(err);
}
);
return deferred.promise;
},
/**
* Change password
*
* @param {String} oldPassword
* @param {String} newPassword
* @param {Function} callback - optional
* @return {Promise}
*/
changePassword: function (oldPassword, newPassword, callback) {
var cb = callback || angular.noop;
return User.changePassword({id: currentMetaData._id}, {
oldPassword: oldPassword,
newPassword: newPassword
}, function (user) {
return cb(user);
}, function (err) {
return cb(err);
}).$promise;
},
/**
* Gets all available info on authenticated user / entity
*
* @return {Object} user
*/
getCurrentMetaData: function () {
return currentMetaData;
},
setCurrentMetaData: function (metaData) {
currentMetaData = metaData;
},
/**
* Check if a user is logged in
*
* @return {Boolean}
*/
isLoggedIn: function () {
return $cookieStore.get('access_token');
},
/**
* Waits for currentMetaData to resolve before checking if user is logged in
*/
isLoggedInAsync: function (cb) {
if (currentMetaData.hasOwnProperty('$promise')) {
currentMetaData.$promise.then(function () {
cb(true);
}).catch(function () {
cb(false);
});
}
else if (currentMetaData.hasOwnProperty('secondFactor')) {
cb(true);
} else {
cb(false);
}
},
/**
* Check if a user is an admin
*
* @return {Boolean}
*/
isAdmin: function () {
var isAdmin = false;
if (currentMetaData && currentMetaData.entity !== undefined) {
var roles = currentMetaData.entity.roles;
roles.forEach(function(role, index, roles) {
if (role === 'admin') {
isAdmin = true;
}
});
}
return isAdmin;
},
/**
* Check if user needs two-factor auth
*/
isTwoFactor: function() {
return currentMetaData.secondFactor;
},
/**
* Get auth token
*/
getToken: function () {
return $cookieStore.get('access_token');
}
};
});
| tobistw/spc-web-client | client/components/auth/auth.service.js | JavaScript | mit | 6,192 |
const WEEKDAYS_LONG = {
ru: [
'Воскресенье',
'Понедельник',
'Вторник',
'Среда',
'Четверг',
'Пятница',
'Суббота',
],
it: [
'Domenica',
'Lunedì',
'Martedì',
'Mercoledì',
'Giovedì',
'Venerdì',
'Sabato',
],
};
const WEEKDAYS_SHORT = {
ru: ['Вс', 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб'],
it: ['Do', 'Lu', 'Ma', 'Me', 'Gi', 'Ve', 'Sa'],
};
const MONTHS = {
ru: [
'Январь',
'Февраль',
'Март',
'Апрель',
'Май',
'Июнь',
'Июль',
'Август',
'Сентябрь',
'Октябрь',
'Ноябрь',
'Декабрь',
],
it: [
'Gennaio',
'Febbraio',
'Marzo',
'Aprile',
'Maggio',
'Giugno',
'Luglio',
'Agosto',
'Settembre',
'Ottobre',
'Novembre',
'Dicembre',
],
};
const FIRST_DAY_OF_WEEK = {
ru: 1,
it: 1,
};
// Translate aria-labels
const LABELS = {
ru: { nextMonth: 'следующий месяц', previousMonth: 'предыдущий месяц' },
it: { nextMonth: 'Prossimo mese', previousMonth: 'Mese precedente' },
};
export default class Example extends React.Component {
state = {
locale: 'en',
};
switchLocale = e => {
const locale = e.target.value || 'en';
this.setState({ locale });
};
render() {
const { locale } = this.state;
return (
<div>
<p>
<select value={locale} onChange={this.switchLocale}>
<option value="en">English</option>
<option value="ru">Русский (Russian)</option>
<option value="it">Italian</option>
</select>
</p>
<DayPicker
locale={locale}
months={MONTHS[locale]}
weekdaysLong={WEEKDAYS_LONG[locale]}
weekdaysShort={WEEKDAYS_SHORT[locale]}
firstDayOfWeek={FIRST_DAY_OF_WEEK[locale]}
labels={LABELS[locale]}
/>
</div>
);
}
}
| saenglert/react-day-picker | docs/examples/src/localization.js | JavaScript | mit | 2,036 |
{
TITLE : 'HiddenColony',
API : 'API',
USED_BY : 'Used by',
LAS_MOD : 'Last update',
EXPIRES : 'Next update',
SER_TIM : 'Server time',
LOC_TIM : 'Local time',
REM_TIM : 'Remaining time'
}
| EliasGrande/OGameHiddenColony | dist/locale/en_GB.js | JavaScript | mit | 202 |
#!/usr/bin/env python
import sys
import os
import argparse
import h5py
import numpy
import shutil
import logging
import json
from skimage import morphology as skmorph
from scipy.ndimage import label
import traceback
from . import imio, agglo, morpho, classify, evaluate, app_logger, \
session_manager, pixel, features
try:
from ray import stack_np
except ImportError:
np_installed = False
else:
np_installed = True
try:
import syngeo
except ImportError:
logging.warning('Could not import syngeo. ' +
'Synapse-aware mode not available.')
def grab_boundary(prediction, channels, master_logger):
boundary = None
master_logger.debug("Grabbing boundary labels: " + str(channels))
for channel_id in channels:
if boundary is None:
boundary = prediction[...,channel_id]
else:
boundary += prediction[...,channel_id]
return boundary
def gen_supervoxels(session_location, options, prediction_file, master_logger):
master_logger.debug("Generating supervoxels")
if not os.path.isfile(prediction_file):
raise Exception("Training file not found: " + prediction_file)
prediction = imio.read_image_stack(prediction_file, group='/volume/prediction', single_channel=False)
if options.extract_ilp_prediction:
prediction = prediction.transpose((2, 1, 0))
boundary = grab_boundary(prediction, options.bound_channels, master_logger)
master_logger.debug("watershed seed value threshold: " + str(options.seed_val))
seeds = label(boundary<=options.seed_val)[0]
if options.seed_size > 0:
master_logger.debug("Removing small seeds")
seeds = morpho.remove_small_connected_components(seeds, options.seed_size)
master_logger.debug("Finished removing small seeds")
master_logger.info("Starting watershed")
boundary_cropped = boundary
seeds_cropped = seeds
if options.border_size > 0:
boundary_cropped = boundary[options.border_size:(-1*options.border_size), options.border_size:(-1*options.border_size),options.border_size:(-1*options.border_size)]
seeds_cropped = seeds[options.border_size:(-1*options.border_size), options.border_size:(-1*options.border_size),options.border_size:(-1*options.border_size)]
supervoxels_cropped = skmorph.watershed(boundary_cropped, seeds_cropped)
supervoxels = supervoxels_cropped
if options.border_size > 0:
supervoxels = seeds.copy()
supervoxels.dtype = supervoxels_cropped.dtype
supervoxels[:,:,:] = 0
supervoxels[options.border_size:(-1*options.border_size), options.border_size:(-1*options.border_size),options.border_size:(-1*options.border_size)] = supervoxels_cropped
master_logger.info("Finished watershed")
if options.synapse_file is not None:
master_logger.info("Processing synapses")
pre_post_pairs = syngeo.io.raveler_synapse_annotations_to_coords(
options.synapse_file)
synapse_volume = syngeo.io.volume_synapse_view(pre_post_pairs, boundary.shape)
if options.border_size > 0:
synvol_cropped = synapse_volume[options.border_size:(-1*options.border_size), options.border_size:(-1*options.border_size),options.border_size:(-1*options.border_size)]
synvol_cropped = synvol_cropped.copy()
synapse_volume[:,:,:] = 0
synapse_volume[options.border_size:(-1*options.border_size), options.border_size:(-1*options.border_size),options.border_size:(-1*options.border_size)] = synvol_cropped
supervoxels = morpho.split_exclusions(boundary, supervoxels, synapse_volume,
options.synapse_dilation)
master_logger.info("Finished processing synapses")
return supervoxels, prediction
def agglomeration(options, agglom_stack, supervoxels, prediction,
image_stack, session_location, sp_outs, master_logger):
seg_thresholds = sorted(options.segmentation_thresholds)
for threshold in seg_thresholds:
if threshold != 0 or not options.use_neuroproof:
master_logger.info("Starting agglomeration to threshold " + str(threshold)
+ " with " + str(agglom_stack.number_of_nodes()))
agglom_stack.agglomerate(threshold)
master_logger.info("Finished agglomeration to threshold " + str(threshold)
+ " with " + str(agglom_stack.number_of_nodes()))
if options.inclusion_removal:
inclusion_removal(agglom_stack, master_logger)
segmentation = agglom_stack.get_segmentation()
if options.h5_output:
imio.write_image_stack(segmentation,
session_location+"/agglom-"+str(threshold)+".lzf.h5", compression='lzf')
if options.raveler_output:
sps_outs = output_raveler(segmentation, supervoxels, image_stack, "agglom-" + str(threshold),
session_location, master_logger)
master_logger.info("Writing graph.json")
agglom_stack.write_plaza_json(session_location+"/raveler-export/agglom-"+str(threshold)+"/graph.json",
options.synapse_file)
if options.synapse_file is not None:
shutil.copyfile(options.synapse_file,
session_location + "/raveler-export/agglom-"+str(threshold)+"/annotations-synapse.json")
master_logger.info("Finished writing graph.json")
def inclusion_removal(agglom_stack, master_logger):
master_logger.info("Starting inclusion removal with " + str(agglom_stack.number_of_nodes()) + " nodes")
agglom_stack.remove_inclusions()
master_logger.info("Finished inclusion removal with " + str(agglom_stack.number_of_nodes()) + " nodes")
def output_raveler(segmentation, supervoxels, image_stack, name, session_location, master_logger, sps_out=None):
outdir = session_location + "/raveler-export/" + name + "/"
master_logger.info("Exporting Raveler directory: " + outdir)
rav = imio.segs_to_raveler(supervoxels, segmentation, 0, do_conn_comp=False, sps_out=sps_out)
sps_out, dummy1, dummy2 = rav
if os.path.exists(outdir):
master_logger.warning("Overwriting Raveler diretory: " + outdir)
shutil.rmtree(outdir)
imio.write_to_raveler(*rav, directory=outdir, gray=image_stack)
return sps_out
def flow_perform_agglomeration(options, supervoxels, prediction, image_stack,
session_location, sps_out, master_logger):
# make synapse constraints
synapse_volume = numpy.array([])
if not options.use_neuroproof and options.synapse_file is not None:
pre_post_pairs = syngeo.io.raveler_synapse_annotations_to_coords(
options.synapse_file)
synapse_volume = \
syngeo.io.volume_synapse_view(pre_post_pairs, supervoxels.shape)
# ?! build RAG (automatically load features if classifier file is available, default to median
# if no classifier, check if np mode or not, automatically load features in NP as well)
if options.classifier is not None:
cl = classify.load_classifier(options.classifier)
fm_info = json.loads(str(cl.feature_description))
master_logger.info("Building RAG")
if fm_info is None or fm_info["neuroproof_features"] is None:
raise Exception("agglomeration classifier to old to be used")
if options.use_neuroproof:
if not fm_info["neuroproof_features"]:
raise Exception("random forest created not using neuroproof")
agglom_stack = stack_np.Stack(supervoxels, prediction,
single_channel=False, classifier=cl, feature_info=fm_info, synapse_file=options.synapse_file,
master_logger=master_logger)
else:
if fm_info["neuroproof_features"]:
master_logger.warning("random forest created using neuroproof features -- should still work")
fm = features.io.create_fm(fm_info)
if options.expected_vi:
mpf = agglo.expected_change_vi(fm, cl, beta=options.vi_beta)
else:
mpf = agglo.classifier_probability(fm, cl)
agglom_stack = agglo.Rag(supervoxels, prediction, mpf,
feature_manager=fm, show_progress=True, nozeros=True,
exclusions=synapse_volume)
master_logger.info("Finished building RAG")
else:
master_logger.info("Building RAG")
boundary = grab_boundary(prediction, options.bound_channels, master_logger)
if options.use_neuroproof:
agglom_stack = stack_np.Stack(supervoxels, boundary, synapse_file=options.synapse_file,
master_logger=master_logger)
else:
agglom_stack = agglo.Rag(supervoxels, boundary, merge_priority_function=agglo.boundary_median,
show_progress=True, nozeros=True, exclusions=synapse_volume)
master_logger.info("Finished building RAG")
# remove inclusions
if options.inclusion_removal:
inclusion_removal(agglom_stack, master_logger)
# actually perform the agglomeration
agglomeration(options, agglom_stack, supervoxels, prediction, image_stack,
session_location, sps_out, master_logger)
def run_segmentation_pipeline(session_location, options, master_logger):
# read grayscale
image_stack = None
if options.image_stack is not None:
image_stack = imio.read_image_stack(options.image_stack)
prediction_file = None
# run boundary prediction -- produces a prediction file
if options.gen_pixel:
pixel.gen_pixel_probabilities(session_location, options, master_logger, image_stack)
prediction_file = session_location + "/" + options.pixelprob_name
else:
prediction_file = options.pixelprob_file
# generate supervoxels -- produces supervoxels and output as appropriate
supervoxels = None
prediction = None
if options.gen_supervoxels:
supervoxels, prediction = gen_supervoxels(session_location, options, prediction_file, master_logger)
elif options.supervoxels_file:
master_logger.info("Reading supervoxels: " + options.supervoxels_file)
supervoxels = imio.read_image_stack(options.supervoxels_file)
master_logger.info("Finished reading supervoxels")
sps_out = None
if supervoxels is not None:
if options.h5_output:
imio.write_image_stack(supervoxels,
session_location + "/" + options.supervoxels_name, compression='lzf')
if options.raveler_output:
sps_out = output_raveler(supervoxels, supervoxels, image_stack, "supervoxels", session_location, master_logger)
if options.synapse_file is not None:
shutil.copyfile(options.synapse_file,
session_location + "/raveler-export/supervoxels/annotations-synapse.json")
# agglomerate and generate output
if options.gen_agglomeration:
if prediction is None and options.pixelprob_file is not None:
master_logger.info("Reading pixel prediction: " + options.pixelprob_file)
prediction = imio.read_image_stack(options.pixelprob_file, group='/volume/prediction', single_channel=False)
master_logger.info("Finished reading pixel prediction")
elif prediction is None:
raise Exception("No pixel probs available for agglomeration")
flow_perform_agglomeration(options, supervoxels, prediction, image_stack,
session_location, sps_out, master_logger)
def np_verify(options_parser, options, master_logger):
if options.use_neuroproof and not np_installed:
raise Exception("NeuroProof not properly installed on your machine. Install or disable neuroproof")
def synapse_file_verify(options_parser, options, master_logger):
if options.synapse_file:
if not os.path.exists(options.synapse_file):
raise Exception("Synapse file " + options.synapse_file + " not found")
if not options.synapse_file.endswith('.json'):
raise Exception("Synapse file " + options.synapse_file + " does not end with .json")
def classifier_verify(options_parser, options, master_logger):
if options.classifier is not None:
if not os.path.exists(options.classifier):
raise Exception("Classifier " + options.classifier + " not found")
if not options.classifier.endswith('.h5'):
raise Exception("Classifier " + options.classifier + " does not end with .h5")
def gen_supervoxels_verify(options_parser, options, master_logger):
if options.gen_supervoxels and not options.gen_pixel and options.pixelprob_file is None:
raise Exception("Must have a pixel prediction to generate supervoxels")
def supervoxels_file_verify(options_parser, options, master_logger):
if options.supervoxels_file is not None:
if not os.path.exists(options.supervoxels_file):
raise Exception("Supervoxel file " + options.supervoxels_file + " does not exist")
def gen_agglomeration_verify(options_parser, options, master_logger):
if options.gen_agglomeration:
if not options.gen_supervoxels and options.supervoxels_file is None:
raise Exception("No supervoxels available for agglomeration")
if not options.gen_pixel and options.pixelprob_file is None:
raise Exception("No prediction available for agglomeration")
def create_segmentation_pipeline_options(options_parser):
pixel.create_pixel_options(options_parser, False)
options_parser.create_option("use-neuroproof", "Use NeuroProof",
default_val=False, required=False, dtype=bool, verify_fn=np_verify, num_args=None,
shortcut='NP', warning=False, hidden=(not np_installed))
options_parser.create_option("supervoxels-name", "Name for the supervoxel segmentation",
default_val="supervoxels.lzf.h5", required=False, dtype=str, verify_fn=None, num_args=None,
shortcut=None, warning=False, hidden=True)
options_parser.create_option("supervoxels-file", "Supervoxel segmentation file or directory stack",
default_val=None, required=False, dtype=str, verify_fn=supervoxels_file_verify, num_args=None,
shortcut=None, warning=False, hidden=True)
options_parser.create_option("gen-supervoxels", "Enable supervoxel generation",
default_val=False, required=False, dtype=bool, verify_fn=gen_supervoxels_verify, num_args=None,
shortcut='GS', warning=True, hidden=False)
options_parser.create_option("inclusion-removal", "Disable inclusion removal",
default_val=True, required=False, dtype=bool, verify_fn=None, num_args=None,
shortcut='IR', warning=False, hidden=False)
options_parser.create_option("seed-val", "Threshold for choosing seeds",
default_val=0, required=False, dtype=int, verify_fn=None, num_args=None,
shortcut=None, warning=False, hidden=True)
options_parser.create_option("seed-size", "Threshold for seed size",
default_val=0, required=False, dtype=int, verify_fn=None, num_args=None,
shortcut='SS', warning=False, hidden=False)
options_parser.create_option("synapse-file", "Json file containing synapse information",
default_val=None, required=False, dtype=str, verify_fn=synapse_file_verify, num_args=None,
shortcut='SJ', warning=False, hidden=False)
options_parser.create_option("segmentation-thresholds", "Segmentation thresholds",
default_val=[], required=False, dtype=float, verify_fn=None, num_args='+',
shortcut='ST', warning=True, hidden=False)
options_parser.create_option("gen-agglomeration", "Enable agglomeration",
default_val=False, required=False, dtype=bool, verify_fn=gen_agglomeration_verify, num_args=None,
shortcut='GA', warning=True, hidden=False)
options_parser.create_option("raveler-output", "Disable Raveler output",
default_val=True, required=False, dtype=bool, verify_fn=None, num_args=None,
shortcut=None, warning=False, hidden=True)
options_parser.create_option("h5-output", "Enable h5 output",
default_val=False, required=False, dtype=bool, verify_fn=None, num_args=None,
shortcut=None, warning=False, hidden=True)
options_parser.create_option("classifier", "H5 file containing RF",
default_val=None, required=False, dtype=str, verify_fn=classifier_verify, num_args=None,
shortcut='k', warning=False, hidden=False)
options_parser.create_option("bound-channels", "Channel numbers designated as boundary",
default_val=[0], required=False, dtype=int, verify_fn=None, num_args='+',
shortcut=None, warning=False, hidden=True)
options_parser.create_option("expected-vi", "Enable expected VI during agglomeration",
default_val=False, required=False, dtype=bool, verify_fn=None, num_args=None,
shortcut=None, warning=False, hidden=True)
options_parser.create_option("vi-beta", "Relative penalty for false merges in weighted expected VI",
default_val=1.0, required=False, dtype=float, verify_fn=None, num_args=None,
shortcut=None, warning=False, hidden=True)
options_parser.create_option("synapse-dilation", "Dilate synapse points by this amount",
default_val=1, required=False, dtype=int, verify_fn=None, num_args=None,
shortcut=None, warning=False, hidden=True)
options_parser.create_option("border-size", "Size of the border in pixels",
default_val=0, required=False, dtype=int, verify_fn=None, num_args=None,
shortcut=None, warning=False, hidden=True)
def entrypoint(argv):
applogger = app_logger.AppLogger(False, 'seg-pipeline')
master_logger = applogger.get_logger()
try:
session = session_manager.Session("seg-pipeline", "Segmentation pipeline (featuring boundary prediction, median agglomeration or trained agglomeration, inclusion removal, and raveler exports)",
master_logger, applogger, create_segmentation_pipeline_options)
run_segmentation_pipeline(session.session_location, session.options, master_logger)
except Exception, e:
master_logger.error(str(traceback.format_exc()))
except KeyboardInterrupt, err:
master_logger.error(str(traceback.format_exc()))
if __name__ == "__main__":
sys.exit(main(sys.argv))
| jni/ray | ray/segmentation_pipeline.py | Python | mit | 18,742 |
<?php
class Movie_model extends CI_Model{
public function __construct() {
parent::__construct();
$this->load->database();
}
public function get_movies() {
$query = $this->db->query("select time, movie_name, movie_play_times from `movie-times`");
return $query->result_array();
}
} | pepfi/tripserver | application/models/Movie_model.php | PHP | mit | 342 |
'''
Created on Oct 31, 2011
@author: robertsj
'''
import abc
class Bundle(object):
'''
An abstract base class for representing bundles.
'''
__metaclass__ = abs.ABCMeta
def __init__(self):
'''
Constructor
'''
| robertsj/poropy | poropy/bundletools/bundle.py | Python | mit | 264 |
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'tweakphoeus'
| basestylo/Tweakphoeus | spec/spec_helper.rb | Ruby | mit | 81 |
<?php
namespace Oro\Bundle\LocaleBundle\Migrations\Schema\v1_3;
use Doctrine\DBAL\Types\Type;
use Oro\Bundle\MigrationBundle\Migration\ArrayLogger;
use Oro\Bundle\MigrationBundle\Migration\ParametrizedMigrationQuery;
use Oro\Bundle\UserBundle\Entity\User;
use Psr\Log\LoggerInterface;
class CreateRelatedLanguagesQuery extends ParametrizedMigrationQuery
{
/**
* {@inheritdoc}
*/
public function getDescription()
{
$logger = new ArrayLogger();
$logger->info("Creates all required Languages that were used for Localizations");
$this->doExecute($logger, true);
return $logger->getMessages();
}
/**
* {@inheritDoc}
*/
public function execute(LoggerInterface $logger)
{
$this->doExecute($logger);
}
/**
* @param LoggerInterface $logger
* @param bool $dryRun
*/
public function doExecute(LoggerInterface $logger, $dryRun = false)
{
list($userId, $organizationId) = $this->getAdminUserAndOrganization($logger);
$createdAt = date('Y-m-d H:i:s');
$langsToProcess = array_map(
function ($item) use ($userId, $organizationId, $createdAt) {
return [
'code' => sprintf("'%s'", $item['language_code']),
'organization_id' => sprintf("'%s'", $organizationId),
'user_owner_id' => sprintf("'%s'", $userId),
'enabled' => sprintf("'%s'", 1),
'created_at' => sprintf("'%s'", $createdAt),
'updated_at' => sprintf("'%s'", $createdAt),
];
},
$this->getRelatedLanguages($logger)
);
foreach ($langsToProcess as $values) {
$query = $this->connection->createQueryBuilder()->insert('oro_language')->values($values)->getSQL();
$this->logQuery($logger, $query);
if (!$dryRun) {
$this->connection->executeQuery($query);
}
}
}
/**
* @param LoggerInterface $logger
*
* @return array
*/
protected function getRelatedLanguages(LoggerInterface $logger)
{
$sql = 'SELECT DISTINCT language_code FROM oro_localization ' .
'WHERE language_code NOT IN (SELECT code FROM oro_language)';
$this->logQuery($logger, $sql);
return $this->connection->fetchAll($sql);
}
/**
* @param LoggerInterface $logger
*
* @return array
*/
protected function getAdminUserAndOrganization(LoggerInterface $logger)
{
$sql = $this->connection->createQueryBuilder()
->select(['u.id AS user_owner_id', 'u.organization_id'])
->from('oro_user', 'u')
->innerJoin('u', 'oro_user_access_role', 'rel', 'rel.user_id = u.id')
->innerJoin('rel', 'oro_access_role', 'r', 'r.id = rel.role_id')
->where('r.role = :role')
->setMaxResults(1)
->getSQL();
$params = ['role' => User::ROLE_ADMINISTRATOR];
$types = ['role' => Type::STRING];
$this->logQuery($logger, $sql, $params, $types);
$data = $this->connection->fetchAssoc($sql, $params, $types);
return [$data['user_owner_id'], $data['organization_id']];
}
}
| orocrm/platform | src/Oro/Bundle/LocaleBundle/Migrations/Schema/v1_3/CreateRelatedLanguagesQuery.php | PHP | mit | 3,307 |
<?php
/*
* This file is part of the Studio Fact package.
*
* (c) Kulichkin Denis (onEXHovia) <onexhovia@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
$MESS['ID'] = 'ID HL блока или обычного инфоблока';
$MESS['TYPE'] = 'Тип генератора';
$MESS['TYPE_IBLOCK'] = 'Инфоблок';
$MESS['TYPE_HLBLOCK'] = 'Highload инфоблок';
$MESS['TYPE_CUSTOM'] = 'Расширенный режим';
$MESS['EVENT_NAME'] = 'Название почтового события';
$MESS['EVENT_TEMPLATE'] = 'Идентификатор почтового шаблона';
$MESS['EVENT_TYPE'] = 'Тип почтового события';
$MESS['BUILDER'] = 'Класс отвечающий за генерацию данных о форме';
$MESS['STORAGE'] = 'Класс отвечающий за сохраниение данных из формы';
$MESS['VALIDATOR'] = 'Класс отвечающий за валидацию данных из формы';
$MESS['AJAX'] = 'Включить AJAX режим';
$MESS['USE_CAPTCHA'] = 'Использовать каптчу';
$MESS['USE_CSRF'] = 'Использовать CSRF';
$MESS['CACHE_GROUPS'] = 'Учитывать права доступа';
$MESS['REDIRECT_PATH'] = 'УРЛ адрес для перенаправления после успешного оформления';
$MESS['ALIAS_FIELDS'] = 'Словарь для замены стандартных наименований полей';
$MESS['DISPLAY_FIELDS'] = 'Словарь со списком полей которые нужно отобразить, если пустой отображаются все';
$MESS['ATTACH_FIELDS'] = 'Список полей типа файл, которые в дальнейшем будут прикреплены к почтовому событию';
| studiofact/citfact.form | install/components/citfact/form/lang/ru/.parameters.php | PHP | mit | 1,946 |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _utils = require('./utils');
var metaFactory = function metaFactory(_ref) {
var name = _ref.name;
var checker = _ref.checker;
var types = _ref.types;
var meta = { name: name, checker: checker, types: types, isGeneric: false };
meta.map = (0, _utils.functor)(function () {
return [{ 'name': name }, { 'checker': checker }, { 'types': types }, { 'isGeneric': !!types }];
});
return meta;
};
var extend = function extend(checker) {
return function (name, newChecker) {
return typeFactory(name, function () {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return checker.apply(null, args) && newChecker.apply(null, args);
}, [checker, newChecker]);
};
};
var typeFactory = function typeFactory(name, checker, types) {
checker.map = (0, _utils.functor)(function () {
return metaFactory({ name: name, checker: checker, types: types });
});
checker.extend = extend(checker);
return checker;
};
exports.default = typeFactory; | Gwash3189/stronganator | dist/type.js | JavaScript | mit | 1,152 |
/*
* The MIT License (MIT)
*
* Copyright (c) 2014 The VoxelBox
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.thevoxelbox.vsl.api.variables;
import com.google.common.base.Optional;
/**
* A VariableScope is a recursive {@link VariableHolder}.
*/
public interface VariableScope extends VariableHolder
{
/**
* Sets the parent {@link VariableScope}.
*
* @param scope the new parent, cannot be null
*/
void setParent(VariableHolder scope);
/**
* Returns the parent of this VariableScope or null if this VariableScope
* has no parent.
*
* @return the parent, may be null
*/
Optional<VariableHolder> getParent();
/**
* Returns the highest parent VariableScope. That is the farthest parent
* VariableScope by recursively calling {@link #getParent()} until a
* VariableScope with no parent is reached. Returns null if this
* VariableScope has no parent.
*
* @return the highest parent, may be null
*/
Optional<VariableHolder> getHighestParent();
}
| Deamon5550/VisualScripting | src/main/java/com/thevoxelbox/vsl/api/variables/VariableScope.java | Java | mit | 2,100 |
module Sequel::Reporter
class Cell
attr_reader :title, :value, :style
attr_accessor :text, :align
def initialize(title, value)
@title = title
@value = value
@style = {}
@text = value
@align = 'left'
end
end
class Report
attr_accessor :error, :fields, :rows
@@params = {}
def self.params=(params)
@@params = params
end
def self.params
@@params
end
def self.from_query(db, query)
new_params = {}
@@params.each do |key, val|
new_params[key.to_sym] = val
end
ds = db.fetch(query, new_params)
report = self.new
begin
row = ds.first
if row.nil?
raise "No data"
end
ds.columns.each do |col|
report.add_field col.to_s
end
ds.each do |row|
vals = []
ds.columns.each do |col|
vals << Cell.new(col.to_s, row[col])
end
report.add_row(vals)
end
rescue Exception => e
report.error = e
end
return report
end
def initialize
@fields = []
@rows = []
end
def add_field(field)
@fields << field
end
def add_row(row)
if row.length != @fields.length
raise "row length not equal to fields length"
end
@rows << row
end
def each
@rows.each do |row|
yield row
end
end
def pivot(column, sort_order)
new_report = self.class.new
bucket_column_index = 0
self.fields.each_with_index do |f, i|
if f == column
bucket_column_index = i
break
else
new_report.add_field(f)
end
end
buckets = {}
new_rows = {}
self.each do |row|
key = row[0, bucket_column_index].map { |r| r.value }
bucket_name = row[bucket_column_index].value
bucket_value = row[bucket_column_index + 1].value
if not buckets.has_key? bucket_name
buckets[bucket_name] = bucket_name
end
new_rows[key] ||= {}
new_rows[key][bucket_name] = bucket_value
end
bucket_keys = buckets.keys.sort
if sort_order && sort_order == 'desc'
bucket_keys = bucket_keys.reverse
end
bucket_keys.each do |bucket|
new_report.add_field(buckets[bucket])
end
new_rows.each do |key, value|
row = key
bucket_keys.each do |b|
row << value[b]
end
new_report.add_row(row)
end
return new_report
end
end
end
| peterkeen/sequel-reporter | lib/sequel-reporter/report.rb | Ruby | mit | 2,604 |
"""
Support for installing and building the "wheel" binary package format.
"""
from __future__ import absolute_import
import compileall
import csv
import errno
import functools
import hashlib
import logging
import os
import os.path
import re
import shutil
import stat
import sys
import tempfile
import warnings
from base64 import urlsafe_b64encode
from email.parser import Parser
from pip._vendor.six import StringIO
import pip
from pip.compat import expanduser
from pip.download import path_to_url, unpack_url
from pip.exceptions import (
InstallationError, InvalidWheelFilename, UnsupportedWheel)
from pip.locations import distutils_scheme, PIP_DELETE_MARKER_FILENAME
from pip import pep425tags
from pip.utils import (
call_subprocess, ensure_dir, captured_stdout, rmtree, canonicalize_name)
from pip.utils.logging import indent_log
from pip._vendor.distlib.scripts import ScriptMaker
from pip._vendor import pkg_resources
from pip._vendor.six.moves import configparser
wheel_ext = '.whl'
VERSION_COMPATIBLE = (1, 0)
logger = logging.getLogger(__name__)
class WheelCache(object):
"""A cache of wheels for future installs."""
def __init__(self, cache_dir, format_control):
"""Create a wheel cache.
:param cache_dir: The root of the cache.
:param format_control: A pip.index.FormatControl object to limit
binaries being read from the cache.
"""
self._cache_dir = expanduser(cache_dir) if cache_dir else None
self._format_control = format_control
def cached_wheel(self, link, package_name):
return cached_wheel(
self._cache_dir, link, self._format_control, package_name)
def _cache_for_link(cache_dir, link):
"""
Return a directory to store cached wheels in for link.
Because there are M wheels for any one sdist, we provide a directory
to cache them in, and then consult that directory when looking up
cache hits.
We only insert things into the cache if they have plausible version
numbers, so that we don't contaminate the cache with things that were not
unique. E.g. ./package might have dozens of installs done for it and build
a version of 0.0...and if we built and cached a wheel, we'd end up using
the same wheel even if the source has been edited.
:param cache_dir: The cache_dir being used by pip.
:param link: The link of the sdist for which this will cache wheels.
"""
# We want to generate an url to use as our cache key, we don't want to just
# re-use the URL because it might have other items in the fragment and we
# don't care about those.
key_parts = [link.url_without_fragment]
if link.hash_name is not None and link.hash is not None:
key_parts.append("=".join([link.hash_name, link.hash]))
key_url = "#".join(key_parts)
# Encode our key url with sha224, we'll use this because it has similar
# security properties to sha256, but with a shorter total output (and thus
# less secure). However the differences don't make a lot of difference for
# our use case here.
hashed = hashlib.sha224(key_url.encode()).hexdigest()
# We want to nest the directories some to prevent having a ton of top level
# directories where we might run out of sub directories on some FS.
parts = [hashed[:2], hashed[2:4], hashed[4:6], hashed[6:]]
# Inside of the base location for cached wheels, expand our parts and join
# them all together.
return os.path.join(cache_dir, "wheels", *parts)
def cached_wheel(cache_dir, link, format_control, package_name):
if not cache_dir:
return link
if not link:
return link
if link.is_wheel:
return link
if not link.is_artifact:
return link
if not package_name:
return link
canonical_name = canonicalize_name(package_name)
formats = pip.index.fmt_ctl_formats(format_control, canonical_name)
if "binary" not in formats:
return link
root = _cache_for_link(cache_dir, link)
try:
wheel_names = os.listdir(root)
except OSError as e:
if e.errno in (errno.ENOENT, errno.ENOTDIR):
return link
raise
candidates = []
for wheel_name in wheel_names:
try:
wheel = Wheel(wheel_name)
except InvalidWheelFilename:
continue
if not wheel.supported():
# Built for a different python/arch/etc
continue
candidates.append((wheel.support_index_min(), wheel_name))
if not candidates:
return link
candidates.sort()
path = os.path.join(root, candidates[0][1])
return pip.index.Link(path_to_url(path))
def rehash(path, algo='sha256', blocksize=1 << 20):
"""Return (hash, length) for path using hashlib.new(algo)"""
h = hashlib.new(algo)
length = 0
with open(path, 'rb') as f:
block = f.read(blocksize)
while block:
length += len(block)
h.update(block)
block = f.read(blocksize)
digest = 'sha256=' + urlsafe_b64encode(
h.digest()
).decode('latin1').rstrip('=')
return (digest, length)
def open_for_csv(name, mode):
if sys.version_info[0] < 3:
nl = {}
bin = 'b'
else:
nl = {'newline': ''}
bin = ''
return open(name, mode + bin, **nl)
def fix_script(path):
"""Replace #!python with #!/path/to/python
Return True if file was changed."""
# XXX RECORD hashes will need to be updated
if os.path.isfile(path):
with open(path, 'rb') as script:
firstline = script.readline()
if not firstline.startswith(b'#!python'):
return False
exename = sys.executable.encode(sys.getfilesystemencoding())
firstline = b'#!' + exename + os.linesep.encode("ascii")
rest = script.read()
with open(path, 'wb') as script:
script.write(firstline)
script.write(rest)
return True
dist_info_re = re.compile(r"""^(?P<namever>(?P<name>.+?)(-(?P<ver>\d.+?))?)
\.dist-info$""", re.VERBOSE)
def root_is_purelib(name, wheeldir):
"""
Return True if the extracted wheel in wheeldir should go into purelib.
"""
name_folded = name.replace("-", "_")
for item in os.listdir(wheeldir):
match = dist_info_re.match(item)
if match and match.group('name') == name_folded:
with open(os.path.join(wheeldir, item, 'WHEEL')) as wheel:
for line in wheel:
line = line.lower().rstrip()
if line == "root-is-purelib: true":
return True
return False
def get_entrypoints(filename):
if not os.path.exists(filename):
return {}, {}
# This is done because you can pass a string to entry_points wrappers which
# means that they may or may not be valid INI files. The attempt here is to
# strip leading and trailing whitespace in order to make them valid INI
# files.
with open(filename) as fp:
data = StringIO()
for line in fp:
data.write(line.strip())
data.write("\n")
data.seek(0)
cp = configparser.RawConfigParser()
cp.readfp(data)
console = {}
gui = {}
if cp.has_section('console_scripts'):
console = dict(cp.items('console_scripts'))
if cp.has_section('gui_scripts'):
gui = dict(cp.items('gui_scripts'))
return console, gui
def move_wheel_files(name, req, wheeldir, user=False, home=None, root=None,
pycompile=True, scheme=None, isolated=False):
"""Install a wheel"""
if not scheme:
scheme = distutils_scheme(
name, user=user, home=home, root=root, isolated=isolated
)
if root_is_purelib(name, wheeldir):
lib_dir = scheme['purelib']
else:
lib_dir = scheme['platlib']
info_dir = []
data_dirs = []
source = wheeldir.rstrip(os.path.sep) + os.path.sep
# Record details of the files moved
# installed = files copied from the wheel to the destination
# changed = files changed while installing (scripts #! line typically)
# generated = files newly generated during the install (script wrappers)
installed = {}
changed = set()
generated = []
# Compile all of the pyc files that we're going to be installing
if pycompile:
with captured_stdout() as stdout:
with warnings.catch_warnings():
warnings.filterwarnings('ignore')
compileall.compile_dir(source, force=True, quiet=True)
logger.debug(stdout.getvalue())
def normpath(src, p):
return os.path.relpath(src, p).replace(os.path.sep, '/')
def record_installed(srcfile, destfile, modified=False):
"""Map archive RECORD paths to installation RECORD paths."""
oldpath = normpath(srcfile, wheeldir)
newpath = normpath(destfile, lib_dir)
installed[oldpath] = newpath
if modified:
changed.add(destfile)
def clobber(source, dest, is_base, fixer=None, filter=None):
ensure_dir(dest) # common for the 'include' path
for dir, subdirs, files in os.walk(source):
basedir = dir[len(source):].lstrip(os.path.sep)
destdir = os.path.join(dest, basedir)
if is_base and basedir.split(os.path.sep, 1)[0].endswith('.data'):
continue
for s in subdirs:
destsubdir = os.path.join(dest, basedir, s)
if is_base and basedir == '' and destsubdir.endswith('.data'):
data_dirs.append(s)
continue
elif (is_base and
s.endswith('.dist-info') and
# is self.req.project_name case preserving?
s.lower().startswith(
req.project_name.replace('-', '_').lower())):
assert not info_dir, 'Multiple .dist-info directories'
info_dir.append(destsubdir)
for f in files:
# Skip unwanted files
if filter and filter(f):
continue
srcfile = os.path.join(dir, f)
destfile = os.path.join(dest, basedir, f)
# directory creation is lazy and after the file filtering above
# to ensure we don't install empty dirs; empty dirs can't be
# uninstalled.
ensure_dir(destdir)
# We use copyfile (not move, copy, or copy2) to be extra sure
# that we are not moving directories over (copyfile fails for
# directories) as well as to ensure that we are not copying
# over any metadata because we want more control over what
# metadata we actually copy over.
shutil.copyfile(srcfile, destfile)
# Copy over the metadata for the file, currently this only
# includes the atime and mtime.
st = os.stat(srcfile)
if hasattr(os, "utime"):
os.utime(destfile, (st.st_atime, st.st_mtime))
# If our file is executable, then make our destination file
# executable.
if os.access(srcfile, os.X_OK):
st = os.stat(srcfile)
permissions = (
st.st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH
)
os.chmod(destfile, permissions)
changed = False
if fixer:
changed = fixer(destfile)
record_installed(srcfile, destfile, changed)
clobber(source, lib_dir, True)
assert info_dir, "%s .dist-info directory not found" % req
# Get the defined entry points
ep_file = os.path.join(info_dir[0], 'entry_points.txt')
console, gui = get_entrypoints(ep_file)
def is_entrypoint_wrapper(name):
# EP, EP.exe and EP-script.py are scripts generated for
# entry point EP by setuptools
if name.lower().endswith('.exe'):
matchname = name[:-4]
elif name.lower().endswith('-script.py'):
matchname = name[:-10]
elif name.lower().endswith(".pya"):
matchname = name[:-4]
else:
matchname = name
# Ignore setuptools-generated scripts
return (matchname in console or matchname in gui)
for datadir in data_dirs:
fixer = None
filter = None
for subdir in os.listdir(os.path.join(wheeldir, datadir)):
fixer = None
if subdir == 'scripts':
fixer = fix_script
filter = is_entrypoint_wrapper
source = os.path.join(wheeldir, datadir, subdir)
dest = scheme[subdir]
clobber(source, dest, False, fixer=fixer, filter=filter)
maker = ScriptMaker(None, scheme['scripts'])
# Ensure old scripts are overwritten.
# See https://github.com/pypa/pip/issues/1800
maker.clobber = True
# Ensure we don't generate any variants for scripts because this is almost
# never what somebody wants.
# See https://bitbucket.org/pypa/distlib/issue/35/
maker.variants = set(('', ))
# This is required because otherwise distlib creates scripts that are not
# executable.
# See https://bitbucket.org/pypa/distlib/issue/32/
maker.set_mode = True
# Simplify the script and fix the fact that the default script swallows
# every single stack trace.
# See https://bitbucket.org/pypa/distlib/issue/34/
# See https://bitbucket.org/pypa/distlib/issue/33/
def _get_script_text(entry):
if entry.suffix is None:
raise InstallationError(
"Invalid script entry point: %s for req: %s - A callable "
"suffix is required. Cf https://packaging.python.org/en/"
"latest/distributing.html#console-scripts for more "
"information." % (entry, req)
)
return maker.script_template % {
"module": entry.prefix,
"import_name": entry.suffix.split(".")[0],
"func": entry.suffix,
}
maker._get_script_text = _get_script_text
maker.script_template = """# -*- coding: utf-8 -*-
import re
import sys
from %(module)s import %(import_name)s
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
sys.exit(%(func)s())
"""
# Special case pip and setuptools to generate versioned wrappers
#
# The issue is that some projects (specifically, pip and setuptools) use
# code in setup.py to create "versioned" entry points - pip2.7 on Python
# 2.7, pip3.3 on Python 3.3, etc. But these entry points are baked into
# the wheel metadata at build time, and so if the wheel is installed with
# a *different* version of Python the entry points will be wrong. The
# correct fix for this is to enhance the metadata to be able to describe
# such versioned entry points, but that won't happen till Metadata 2.0 is
# available.
# In the meantime, projects using versioned entry points will either have
# incorrect versioned entry points, or they will not be able to distribute
# "universal" wheels (i.e., they will need a wheel per Python version).
#
# Because setuptools and pip are bundled with _ensurepip and virtualenv,
# we need to use universal wheels. So, as a stopgap until Metadata 2.0, we
# override the versioned entry points in the wheel and generate the
# correct ones. This code is purely a short-term measure until Metadat 2.0
# is available.
#
# To add the level of hack in this section of code, in order to support
# ensurepip this code will look for an ``ENSUREPIP_OPTIONS`` environment
# variable which will control which version scripts get installed.
#
# ENSUREPIP_OPTIONS=altinstall
# - Only pipX.Y and easy_install-X.Y will be generated and installed
# ENSUREPIP_OPTIONS=install
# - pipX.Y, pipX, easy_install-X.Y will be generated and installed. Note
# that this option is technically if ENSUREPIP_OPTIONS is set and is
# not altinstall
# DEFAULT
# - The default behavior is to install pip, pipX, pipX.Y, easy_install
# and easy_install-X.Y.
pip_script = console.pop('pip', None)
if pip_script:
if "ENSUREPIP_OPTIONS" not in os.environ:
spec = 'pip = ' + pip_script
generated.extend(maker.make(spec))
if os.environ.get("ENSUREPIP_OPTIONS", "") != "altinstall":
spec = 'pip%s = %s' % (sys.version[:1], pip_script)
generated.extend(maker.make(spec))
spec = 'pip%s = %s' % (sys.version[:3], pip_script)
generated.extend(maker.make(spec))
# Delete any other versioned pip entry points
pip_ep = [k for k in console if re.match(r'pip(\d(\.\d)?)?$', k)]
for k in pip_ep:
del console[k]
easy_install_script = console.pop('easy_install', None)
if easy_install_script:
if "ENSUREPIP_OPTIONS" not in os.environ:
spec = 'easy_install = ' + easy_install_script
generated.extend(maker.make(spec))
spec = 'easy_install-%s = %s' % (sys.version[:3], easy_install_script)
generated.extend(maker.make(spec))
# Delete any other versioned easy_install entry points
easy_install_ep = [
k for k in console if re.match(r'easy_install(-\d\.\d)?$', k)
]
for k in easy_install_ep:
del console[k]
# Generate the console and GUI entry points specified in the wheel
if len(console) > 0:
generated.extend(
maker.make_multiple(['%s = %s' % kv for kv in console.items()])
)
if len(gui) > 0:
generated.extend(
maker.make_multiple(
['%s = %s' % kv for kv in gui.items()],
{'gui': True}
)
)
record = os.path.join(info_dir[0], 'RECORD')
temp_record = os.path.join(info_dir[0], 'RECORD.pip')
with open_for_csv(record, 'r') as record_in:
with open_for_csv(temp_record, 'w+') as record_out:
reader = csv.reader(record_in)
writer = csv.writer(record_out)
for row in reader:
row[0] = installed.pop(row[0], row[0])
if row[0] in changed:
row[1], row[2] = rehash(row[0])
writer.writerow(row)
for f in generated:
h, l = rehash(f)
writer.writerow((f, h, l))
for f in installed:
writer.writerow((installed[f], '', ''))
shutil.move(temp_record, record)
def _unique(fn):
@functools.wraps(fn)
def unique(*args, **kw):
seen = set()
for item in fn(*args, **kw):
if item not in seen:
seen.add(item)
yield item
return unique
# TODO: this goes somewhere besides the wheel module
@_unique
def uninstallation_paths(dist):
"""
Yield all the uninstallation paths for dist based on RECORD-without-.pyc
Yield paths to all the files in RECORD. For each .py file in RECORD, add
the .pyc in the same directory.
UninstallPathSet.add() takes care of the __pycache__ .pyc.
"""
from pip.utils import FakeFile # circular import
r = csv.reader(FakeFile(dist.get_metadata_lines('RECORD')))
for row in r:
path = os.path.join(dist.location, row[0])
yield path
if path.endswith('.py'):
dn, fn = os.path.split(path)
base = fn[:-3]
path = os.path.join(dn, base + '.pyc')
yield path
def wheel_version(source_dir):
"""
Return the Wheel-Version of an extracted wheel, if possible.
Otherwise, return False if we couldn't parse / extract it.
"""
try:
dist = [d for d in pkg_resources.find_on_path(None, source_dir)][0]
wheel_data = dist.get_metadata('WHEEL')
wheel_data = Parser().parsestr(wheel_data)
version = wheel_data['Wheel-Version'].strip()
version = tuple(map(int, version.split('.')))
return version
except:
return False
def check_compatibility(version, name):
"""
Raises errors or warns if called with an incompatible Wheel-Version.
Pip should refuse to install a Wheel-Version that's a major series
ahead of what it's compatible with (e.g 2.0 > 1.1); and warn when
installing a version only minor version ahead (e.g 1.2 > 1.1).
version: a 2-tuple representing a Wheel-Version (Major, Minor)
name: name of wheel or package to raise exception about
:raises UnsupportedWheel: when an incompatible Wheel-Version is given
"""
if not version:
raise UnsupportedWheel(
"%s is in an unsupported or invalid wheel" % name
)
if version[0] > VERSION_COMPATIBLE[0]:
raise UnsupportedWheel(
"%s's Wheel-Version (%s) is not compatible with this version "
"of pip" % (name, '.'.join(map(str, version)))
)
elif version > VERSION_COMPATIBLE:
logger.warning(
'Installing from a newer Wheel-Version (%s)',
'.'.join(map(str, version)),
)
class Wheel(object):
"""A wheel file"""
# TODO: maybe move the install code into this class
wheel_file_re = re.compile(
r"""^(?P<namever>(?P<name>.+?)-(?P<ver>\d.*?))
((-(?P<build>\d.*?))?-(?P<pyver>.+?)-(?P<abi>.+?)-(?P<plat>.+?)
\.whl|\.dist-info)$""",
re.VERBOSE
)
def __init__(self, filename):
"""
:raises InvalidWheelFilename: when the filename is invalid for a wheel
"""
wheel_info = self.wheel_file_re.match(filename)
if not wheel_info:
raise InvalidWheelFilename(
"%s is not a valid wheel filename." % filename
)
self.filename = filename
self.name = wheel_info.group('name').replace('_', '-')
# we'll assume "_" means "-" due to wheel naming scheme
# (https://github.com/pypa/pip/issues/1150)
self.version = wheel_info.group('ver').replace('_', '-')
self.pyversions = wheel_info.group('pyver').split('.')
self.abis = wheel_info.group('abi').split('.')
self.plats = wheel_info.group('plat').split('.')
# All the tag combinations from this file
self.file_tags = set(
(x, y, z) for x in self.pyversions
for y in self.abis for z in self.plats
)
def support_index_min(self, tags=None):
"""
Return the lowest index that one of the wheel's file_tag combinations
achieves in the supported_tags list e.g. if there are 8 supported tags,
and one of the file tags is first in the list, then return 0. Returns
None is the wheel is not supported.
"""
if tags is None: # for mock
tags = pep425tags.supported_tags
indexes = [tags.index(c) for c in self.file_tags if c in tags]
return min(indexes) if indexes else None
def supported(self, tags=None):
"""Is this wheel supported on this system?"""
if tags is None: # for mock
tags = pep425tags.supported_tags
return bool(set(tags).intersection(self.file_tags))
class WheelBuilder(object):
"""Build wheels from a RequirementSet."""
def __init__(self, requirement_set, finder, build_options=None,
global_options=None):
self.requirement_set = requirement_set
self.finder = finder
self._cache_root = requirement_set._wheel_cache._cache_dir
self._wheel_dir = requirement_set.wheel_download_dir
self.build_options = build_options or []
self.global_options = global_options or []
def _build_one(self, req, output_dir):
"""Build one wheel.
:return: The filename of the built wheel, or None if the build failed.
"""
tempd = tempfile.mkdtemp('pip-wheel-')
try:
if self.__build_one(req, tempd):
try:
wheel_name = os.listdir(tempd)[0]
wheel_path = os.path.join(output_dir, wheel_name)
shutil.move(os.path.join(tempd, wheel_name), wheel_path)
logger.info('Stored in directory: %s', output_dir)
return wheel_path
except:
pass
# Ignore return, we can't do anything else useful.
self._clean_one(req)
return None
finally:
rmtree(tempd)
def _base_setup_args(self, req):
return [
sys.executable, '-c',
"import setuptools;__file__=%r;"
"exec(compile(open(__file__).read().replace('\\r\\n', '\\n'), "
"__file__, 'exec'))" % req.setup_py
] + list(self.global_options)
def __build_one(self, req, tempd):
base_args = self._base_setup_args(req)
logger.info('Running setup.py bdist_wheel for %s', req.name)
logger.debug('Destination directory: %s', tempd)
wheel_args = base_args + ['bdist_wheel', '-d', tempd] \
+ self.build_options
try:
call_subprocess(wheel_args, cwd=req.source_dir, show_stdout=False)
return True
except:
logger.error('Failed building wheel for %s', req.name)
return False
def _clean_one(self, req):
base_args = self._base_setup_args(req)
logger.info('Running setup.py clean for %s', req.name)
clean_args = base_args + ['clean', '--all']
try:
call_subprocess(clean_args, cwd=req.source_dir, show_stdout=False)
return True
except:
logger.error('Failed cleaning build dir for %s', req.name)
return False
def build(self, autobuilding=False):
"""Build wheels.
:param unpack: If True, replace the sdist we built from the with the
newly built wheel, in preparation for installation.
:return: True if all the wheels built correctly.
"""
assert self._wheel_dir or (autobuilding and self._cache_root)
# unpack sdists and constructs req set
self.requirement_set.prepare_files(self.finder)
reqset = self.requirement_set.requirements.values()
buildset = []
for req in reqset:
if req.constraint:
continue
if req.is_wheel:
if not autobuilding:
logger.info(
'Skipping %s, due to already being wheel.', req.name)
elif req.editable:
if not autobuilding:
logger.info(
'Skipping bdist_wheel for %s, due to being editable',
req.name)
elif autobuilding and req.link and not req.link.is_artifact:
pass
elif autobuilding and not req.source_dir:
pass
else:
if autobuilding:
link = req.link
base, ext = link.splitext()
if pip.index.egg_info_matches(base, None, link) is None:
# Doesn't look like a package - don't autobuild a wheel
# because we'll have no way to lookup the result sanely
continue
if "binary" not in pip.index.fmt_ctl_formats(
self.finder.format_control,
canonicalize_name(req.name)):
logger.info(
"Skipping bdist_wheel for %s, due to binaries "
"being disabled for it.", req.name)
continue
buildset.append(req)
if not buildset:
return True
# Build the wheels.
logger.info(
'Building wheels for collected packages: %s',
', '.join([req.name for req in buildset]),
)
with indent_log():
build_success, build_failure = [], []
for req in buildset:
if autobuilding:
output_dir = _cache_for_link(self._cache_root, req.link)
try:
ensure_dir(output_dir)
except OSError as e:
logger.warn("Building wheel for %s failed: %s",
req.name, e)
build_failure.append(req)
continue
else:
output_dir = self._wheel_dir
wheel_file = self._build_one(req, output_dir)
if wheel_file:
build_success.append(req)
if autobuilding:
# XXX: This is mildly duplicative with prepare_files,
# but not close enough to pull out to a single common
# method.
# The code below assumes temporary source dirs -
# prevent it doing bad things.
if req.source_dir and not os.path.exists(os.path.join(
req.source_dir, PIP_DELETE_MARKER_FILENAME)):
raise AssertionError(
"bad source dir - missing marker")
# Delete the source we built the wheel from
req.remove_temporary_source()
# set the build directory again - name is known from
# the work prepare_files did.
req.source_dir = req.build_location(
self.requirement_set.build_dir)
# Update the link for this.
req.link = pip.index.Link(
path_to_url(wheel_file))
assert req.link.is_wheel
# extract the wheel into the dir
unpack_url(
req.link, req.source_dir, None, False,
session=self.requirement_set.session)
else:
build_failure.append(req)
# notify success/failure
if build_success:
logger.info(
'Successfully built %s',
' '.join([req.name for req in build_success]),
)
if build_failure:
logger.info(
'Failed to build %s',
' '.join([req.name for req in build_failure]),
)
# Return True if all builds were successful
return len(build_failure) == 0
| James-Firth/pip | pip/wheel.py | Python | mit | 31,114 |
<?php
namespace MairieVoreppe\DemandeTravauxBundle\Entity;
/**
* ArreteModelRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class ArreteModelRepository extends \Doctrine\ORM\EntityRepository
{
}
| chadyred/demandeTravaux | src/MairieVoreppe/DemandeTravauxBundle/Entity/ArreteModelRepository.php | PHP | mit | 266 |
<?php
namespace perf\PresetString;
/**
* This class allows to handle and validate strings representing a standardized time (HH:MM:SS).
*
*/
class Time extends PresetStringBase
{
const REGEX = '/^([01]\d|2[0-3]):([0-5]\d):([0-5]\d)$/D';
/**
* Validates specified time string (HH:MM:SS).
*
* @param string $string
* @param {string:mixed} $parameters
* @return bool true if specified time string is valid, false otherwise.
*/
public static function validate($string, array $parameters = array())
{
return (1 === preg_match(self::REGEX, $string));
}
}
| jmfeurprier/perf-preset-string | lib/perf/PresetString/Time.php | PHP | mit | 613 |
<?php
/**
* @package Moar\Log\Monolog
*/
namespace Moar\Log\Monolog;
use Moar\Log\Helpers\HierarchicalLoggerFactory;
use Monolog\Logger;
use Psr\Log\LoggerInterface;
/**
* Logger factory for Monolog instances.
*
* @package Moar\Log\Monolog
* @copyright 2013 Bryan Davis and contributors. All Rights Reserved.
*/
class LoggerFactory extends HierarchicalLoggerFactory {
/**
* @var Logger
*/
protected $root;
/**
* Get the default logger.
*
* Must return the same logger instance on each call.
*
* @return LoggerInterface
*/
public function getDafaultLogger () {
if (null === $this->root) {
$this->root = new HierarchialLogger(null);
}
return $this->root;
} //end getDafaultLogger
/**
* Create a new LoggerInterface instance.
*
* @param string $name Name of new logger
* @param LoggerInterface $parent Closest known ancestor logger
* @return LoggerInterface Logger
*/
protected function newLogger ($name, LoggerInterface $parent) {
$logger = $parent;
if ($parent instanceof HierarchialLogger) {
$logger = new HierarchialLogger($name);
$logger->setParent($parent);
}
return $logger;
} //end newLogger
} //end MonologLoggerFactory
| bd808/moar-log | src/Moar/Log/Monolog/LoggerFactory.php | PHP | mit | 1,244 |
module.exports = {
"level": [
{
"level": "1",
"name": "trick"
},
{
"level": "1",
"name": "destiny-bond"
},
{
"level": "1",
"name": "ally-switch"
},
{
"level": "1",
"name": "hyperspace-hole"
},
{
"level": "1",
"name": "confusion"
},
{
"level": "6",
"name": "astonish"
},
{
"level": "10",
"name": "magic-coat"
},
{
"level": "15",
"name": "psybeam"
},
{
"level": "19",
"name": "light-screen"
},
{
"level": "25",
"name": "skill-swap"
},
{
"level": "29",
"name": "power-split"
},
{
"level": "35",
"name": "guard-split"
},
{
"level": "46",
"name": "phantom-force"
},
{
"level": "50",
"name": "wonder-room"
},
{
"level": "55",
"name": "trick-room"
},
{
"level": "68",
"name": "shadow-ball"
},
{
"level": "75",
"name": "psychic"
},
{
"level": "85",
"name": "hyperspace-hole"
}
],
"tutor": [],
"machine": [
"psyshock",
"calm-mind",
"toxic",
"hidden-power",
"sunny-day",
"taunt",
"hyper-beam",
"light-screen",
"protect",
"rain-dance",
"safeguard",
"frustration",
"thunderbolt",
"return",
"psychic",
"shadow-ball",
"brick-break",
"double-team",
"reflect",
"torment",
"facade",
"rest",
"thief",
"round",
"focus-blast",
"energy-ball",
"fling",
"charge-beam",
"quash",
"embargo",
"giga-impact",
"flash",
"thunder-wave",
"psych-up",
"dream-eater",
"grass-knot",
"swagger",
"sleep-talk",
"substitute",
"trick-room",
"power-up-punch",
"confide"
],
"egg": []
}; | leader22/simple-pokedex-v2 | _scraping/XYmoves/720.js | JavaScript | mit | 2,423 |
import Vue from "vue";
import Router from "vue-router";
Vue.use(Router);
import Home from "@/pages/home.vue";
import CategoryIndex from "@/pages/categoryIndex.vue";
import ExpenditureIndex from "@/pages/expenditureIndex.vue";
export default new Router({
routes: [
{
path: '/',
name: 'home',
component: Home,
},
{
path: '/categories',
name: 'categories',
component: CategoryIndex,
},
{
path: '/expenditure-index/:type',
name: 'expenditure-index',
component: ExpenditureIndex,
},
],
});
| trtstm/budgetr | web/src/router/index.ts | TypeScript | mit | 572 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TournamentsMVC.Data.Contracts;
using TournamentsMVC.Models;
using TournamentsMVC.Services.Contracts;
namespace TournamentsMVC.Services
{
public class RatingService : IRatingService
{
private readonly ITournamentSystemData data;
public RatingService(ITournamentSystemData data)
{
if (data == null)
{
throw new ArgumentNullException("data");
}
this.data = data;
}
public double GetRating(int playerId)
{
var player = this.data.Players.All.FirstOrDefault(x => x.Id == playerId);
if (player != null && player.Rating!=null)
{
return (double) player.Rating;
}
else
{
return 0;
}
}
public Player RatePlayer(int playerId, int currentRating)
{
// TODO: check rating range
var player = this.data.Players.All.Where(x => x.Id == playerId).FirstOrDefault();
if (player != null)
{
player.Rating = (player.Rating*player.Votes+currentRating)/(player.Votes+1);
player.Votes++;
this.data.SaveChanges();
return player;
}
else
{
return null;// throw new ArgumentException("No player with id {playerId} found in database");
}
}
}
}
| Krassimir-ILLIEV/TournamentsMVC | TournamentsMVC.Services/RatingService.cs | C# | mit | 1,629 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
Roles in this namespace are meant to provide `Nginx <http://wiki.nginx.org/Main>`_ web server utility methods for Debian distributions.
'''
from provy.core import Role
from provy.more.debian.package.aptitude import AptitudeRole
class NginxRole(Role):
'''
This role provides `Nginx <http://wiki.nginx.org/Main>`_ web server management utilities for Debian distributions.
Example:
::
from provy.core import Role
from provy.more.debian import NginxRole
class MySampleRole(Role):
def provision(self):
with self.using(NginxRole) as role:
role.ensure_conf(conf_template='nginx.conf')
role.ensure_site_disabled('default')
role.create_site(site='my-site', template='my-site')
role.ensure_site_enabled('my-site')
'''
def __available_site_for(self, name):
return '/etc/nginx/sites-available/%s' % name
def __enabled_site_for(self, name):
return '/etc/nginx/sites-enabled/%s' % name
def provision(self):
'''
Installs `Nginx <http://wiki.nginx.org/Main>`_ dependencies.
This method should be called upon if overriden in base classes, or `Nginx <http://wiki.nginx.org/Main>`_ won't work properly in the remote server.
Example:
::
from provy.core import Role
from provy.more.debian import NginxRole
class MySampleRole(Role):
def provision(self):
self.provision_role(NginxRole) # does not need to be called if using with block.
'''
with self.using(AptitudeRole) as role:
role.ensure_up_to_date()
role.ensure_package_installed('nginx')
def cleanup(self):
'''
Restarts nginx if any changes have been made.
There's no need to call this method manually.
'''
super(NginxRole, self).cleanup()
if 'must-restart-nginx' in self.context and self.context['must-restart-nginx']:
self.restart()
def ensure_conf(self, conf_template, options={}, nginx_conf_path='/etc/nginx/nginx.conf'):
'''
Ensures that nginx configuration is up-to-date with the specified template.
:param conf_template: Name of the template for nginx.conf.
:type conf_template: :class:`str`
:param options: Dictionary of options passed to template. Extends context.
:type options: :class:`dict`
:param nginx_conf_path: Path of the nginx configuration file. Defaults to /etc/nginx/nginx.conf.
:type nginx_conf_path: :class:`str`
Example:
::
from provy.core import Role
from provy.more.debian import NginxRole
class MySampleRole(Role):
def provision(self):
with self.using(NginxRole) as role:
role.ensure_conf(conf_template='nginx.conf')
'''
result = self.update_file(conf_template,
nginx_conf_path,
options=options,
sudo=True)
if result:
self.log('nginx conf updated!')
self.ensure_restart()
def ensure_site_disabled(self, site):
'''
Ensures that the specified site is removed from nginx list of enabled sites.
:param site: Name of the site to disable.
:type site: :class:`str`
Example:
::
from provy.core import Role
from provy.more.debian import NginxRole
class MySampleRole(Role):
def provision(self):
with self.using(NginxRole) as role:
role.ensure_site_disabled('default')
'''
result = self.remove_file(self.__enabled_site_for(site), sudo=True)
if result:
self.log('%s nginx site is disabled!' % site)
self.ensure_restart()
def ensure_site_enabled(self, site):
'''
Ensures that a symlink is created for the specified site at nginx list of enabled sites from the list of available sites.
:param site: Name of the site to enable.
:type site: :class:`str`
Example:
::
from provy.core import Role
from provy.more.debian import NginxRole
class MySampleRole(Role):
def provision(self):
with self.using(NginxRole) as role:
role.ensure_site_enabled('my-site')
'''
result = self.remote_symlink(self.__available_site_for(site),
self.__enabled_site_for(site),
sudo=True)
if result:
self.log('%s nginx site is enabled!' % site)
self.ensure_restart()
def create_site(self, site, template, options={}):
'''
Adds a website with the specified template to Nginx list of available sites.
Warning: Do not forget to call :meth:`ensure_site_enabled` after a call to `create_site`, or your site won't be enabled.
:param site: Name of the site to enable.
:type site: :class:`str`
:param template: Site configuration template.
:type template: :class:`str`
:param options: Options to pass to the template.
:type options: :class:`str`
Example:
::
from provy.core import Role
from provy.more.debian import NginxRole
class MySampleRole(Role):
def provision(self):
with self.using(NginxRole) as role:
role.create_site(site='my-site', template='my-site', options={
"user": "me"
})
'''
result = self.update_file(template,
self.__available_site_for(site),
options=options, sudo=True)
if result:
self.log('%s nginx site created!' % site)
self.ensure_restart()
def ensure_restart(self):
'''
Ensures that nginx gets restarted on cleanup. There's no need to call this method as any changes to Nginx will trigger it.
Example:
::
from provy.core import Role
from provy.more.debian import NginxRole
class MySampleRole(Role):
def provision(self):
with self.using(NginxRole) as role:
role.ensure_restart()
'''
self.context['must-restart-nginx'] = True
def restart(self):
'''
Forcefully restarts Nginx.
Example:
::
from provy.core import Role
from provy.more.debian import NginxRole
class MySampleRole(Role):
def provision(self):
with self.using(NginxRole) as role:
role.restart()
'''
command = '/etc/init.d/nginx restart'
self.execute(command, sudo=True)
| python-provy/provy | provy/more/debian/web/nginx.py | Python | mit | 7,202 |
// SPDX-License-Identifier: MIT
package mealplaner.plugins.utensil;
import static bundletests.BundleCommons.allMessageTests;
import java.io.File;
import org.junit.jupiter.api.Test;
class ObligatoryUtensilBundleTest {
@Test
void testBundle() {
allMessageTests("ObligatoryUtensilMessagesBundle", "plugins" + File.separator + "utensil");
}
}
| Martin-Idel/mealplaner | mealplaner-plugins/utensil/src/test/java/mealplaner/plugins/utensil/ObligatoryUtensilBundleTest.java | Java | mit | 354 |
from django.core.exceptions import ValidationError
from django.forms import UUIDField
import six
from django.utils.module_loading import import_string
from django.utils.translation import ugettext_lazy as _
from django_smalluuid import settings
class ShortUUIDField(UUIDField):
default_error_messages = {
'invalid': _('Enter a valid short-form UUID.'),
}
def __init__(self, uuid_class=settings.DEFAULT_CLASS, *args, **kwargs):
self.uuid_class = uuid_class
if isinstance(self.uuid_class, six.string_types):
self.uuid_class = import_string(uuid_class)
super(ShortUUIDField, self).__init__(*args, **kwargs)
def prepare_value(self, value):
if isinstance(value, self.uuid_class):
return six.text_type(value)
return value
def to_python(self, value):
if value in self.empty_values:
return None
if not isinstance(value, self.uuid_class):
try:
value = self.uuid_class(value)
except ValueError:
raise ValidationError(self.error_messages['invalid'], code='invalid')
return value
| adamcharnock/django-smalluuid | django_smalluuid/forms.py | Python | mit | 1,158 |
const ROOT_PATH = process.cwd()
module.exports = {
bail: false,
cache: false,
devtool: 'eval',
devServer: {
compress: true,
contentBase: `${ROOT_PATH}/public/`,
historyApiFallback: true,
hot: true,
port: 8000,
stats: {
colors: true
}
},
entry: require('./__entry'),
output: {
path: `${ROOT_PATH}/public/scripts`,
filename: '[name].js',
publicPath: 'scripts/'
},
module: require('./__module'),
plugins: require('./plugins'),
resolve: require('./__resolve')
}
| jbarinas/cake-hub | _configs/webpack.config.dev.js | JavaScript | mit | 600 |
(function( $, SocialCount ) {
SocialCount.selectors.facebook = '.facebook';
SocialCount.getFacebookAction = function( $el ) {
return ( $el.attr('data-facebook-action' ) || 'like' ).toLowerCase();
};
SocialCount.plugins.init.push(function() {
var $el = this;
$el.addClass( SocialCount.getFacebookAction( $el ) );
});
SocialCount.plugins.bind.push(function(bind, url) {
var $el = this,
facebookAction = SocialCount.getFacebookAction( $el );
bind( $el.find( SocialCount.selectors.facebook + ' a' ),
'<div class="fb-like" data-href="' + url + '" data-layout="button"' +
' data-action="' + facebookAction + '" data-show-faces="false"' +
' data-share="false"></div>',
'//connect.facebook.net/' + ( SocialCount.locale || 'en_US' ) + '/sdk.js#xfbml=1&version=v2.0',
function( el ) {
FB.XFBML.parse( el );
});
});
})( jQuery, window.SocialCount );
| filamentgroup/SocialCount | src/networks/facebook.js | JavaScript | mit | 937 |
/**
* Copyright (c) 2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import Flax from '../../../../';
import TodoActions from '../actions/TodoActions';
const TodoStore = Flax.createStore({
displayName: 'TodoStore',
getInitialState: function () {
return {
todos: {},
id: 0
}
},
getActionBinds() {
return [
[TodoActions.create, this._handleCreate],
[TodoActions.updateText, this._handleUpdateText],
[TodoActions.destroy, this._handleDestroy],
[TodoActions.toggleComplete, this._handleToggleComplete],
[TodoActions.toggleCompleteAll, this._handleToggleCompleteAll]
];
},
events: {
CHANGE_EVENT: null
},
getters: {
areAllComplete() {
var todos = this.state.todos;
for (var id in todos) {
if (!todos[id].complete) {
return false;
}
}
return true;
},
getAll() {
return this.state.todos;
}
},
// Helpers
_update(id, update) {
if (this.state.todos.hasOwnProperty(id)) this.state.todos[id] = Object.assign({}, this.state.todos[id], update);
},
_destroy(id) {
delete this.state.todos[id];
},
// Handlers
_handleCreate(payload) {
var text = payload.text.trim();
if (text !== '') {
// var id = (+new Date() + Math.floor(Math.random() * 999999)).toString(36);
var id = this.state.id++;
this.state.todos[id] = {
id: id,
complete: false,
text: text
};
this.emitChange(this.CHANGE_EVENT);
}
},
_handleToggleComplete(payload) {
this._update(payload.id, {complete: payload.complete});
this.emitChange(this.CHANGE_EVENT);
},
_handleUpdateText(payload) {
var id = payload.id;
var text = payload.text.trim();
if (text !== '') {
this._update(id, {text: text});
this.emitChange(this.CHANGE_EVENT);
}
},
_handleToggleCompleteAll() {
var updates;
if (this.areAllComplete()) {
updates = {complete: false};
} else {
updates = {complete: true};
}
for (var id in this.state.todos) {
this._update(id, updates);
}
this.emitChange(this.CHANGE_EVENT);
},
_handleDestroy(payload) {
var id = payload.id;
this._destroy(id);
this.emitChange(this.CHANGE_EVENT);
},
_handleDestroyCompleted() {
var todos = this.state.todos;
for (var id in todos) {
if (todos[id].complete) {
this._destroy(id);
}
}
this.emitChange(this.CHANGE_EVENT);
}
});
export default TodoStore;
| osmanpontes/flax | examples/todos/src/stores/TodoStore.js | JavaScript | mit | 2,773 |
require_relative "../spec_helper"
require_relative "../../lib/daily_affirmation/validators/presence_validator"
describe "PresenceValidator" do
subject { DailyAffirmation::Validators::PresenceValidator }
it "passes validation if the attribute is present" do
obj = double(:name => :foo)
validator = subject.new(obj, :name)
expect(validator).to be_valid
end
it "fails validation if the attribute is empty" do
obj = double(:name => " ")
validator = subject.new(obj, :name)
expect(validator).to_not be_valid
end
it "fails validation if the attribute is nil" do
obj = double(:name => nil)
validator = subject.new(obj, :name)
expect(validator).to_not be_valid
end
it "has the correct error message" do
obj = double(:name => nil)
validator = subject.new(obj, :name)
expect(validator.error_message).to eq(
"name can't be blank"
)
end
end
| teamsnap/daily_affirmation | spec/validators/presence_validator_spec.rb | Ruby | mit | 914 |
package net.cassite.daf4j.types;
import net.cassite.daf4j.DataIterable;
import java.util.ArrayList;
import java.util.List;
/**
* 针对List在实体中的简化
*/
public class XList<E> extends DataIterable<E, List<E>> {
/**
* 使用ArrayList初始化该数据项
*
* @param entity 该数据项所在的实体,使用(this)填入该参数
*/
public XList(Object entity) {
this(new ArrayList<E>(), entity);
}
/**
* 将该数据项初始化为指定值
*
* @param it 指定的初始化值
* @param entity 该数据线所在的实体,使用(this)填入该参数
*/
public XList(List<E> it, Object entity) {
super(it, entity);
}
}
| wkgcass/common | Data/src/main/java/net/cassite/daf4j/types/XList.java | Java | mit | 797 |
module.exports = {
update: function(data) {
var _ = this;
_.dom.update(data || _._data);
},
dispose: function dispose() {
var _ = this;
_.$element.innerHTML = '';
},
render: function render() {
var _ = this;
_.dispose();
_.dom = _.bars.compile(_.template);
_.dom.update(_._data);
_.dom.appendTo(_.$element);
_.emit('render');
}
};
| Mike96Angelo/Custom-Element | lib/events.js | JavaScript | mit | 438 |
import { createStore, applyMiddleware, compose } from 'redux'
import { autoRehydrate } from 'redux-persist'
import createLogger from 'redux-logger'
import rootReducer from '../reducers/'
import Config from '../../config/debug_settings'
import createSagaMiddleware from 'redux-saga'
import sagas from '../sagas'
import R from 'ramda'
import devTools from 'remote-redux-devtools'
import ReduxPersist from '../../config/redux_persist'
import RehydrationServices from '../services/rehydration_services'
import Types from '@actions/types'
var Fabric = require('react-native-fabric');
var { Answers } = Fabric;
// the logger master switch
const USE_LOGGING = Config.reduxLogging
// silence these saga-based messages
const SAGA_LOGGING_BLACKLIST = ['EFFECT_TRIGGERED', 'EFFECT_RESOLVED', 'EFFECT_REJECTED', 'persist/REHYDRATE']
const actionTransformer = action => {
console.log('log action')
// All log functions take an optional array of custom attributes as the last parameter
Answers.logCustom('User action', { action });
return action
}
// create the logger
const logger = createLogger({
predicate: ( getState, { type } ) => USE_LOGGING && R.not(R.contains(type, SAGA_LOGGING_BLACKLIST)),
actionTransformer
})
let middleware = []
const sagaMiddleware = createSagaMiddleware()
const answersLogger = store => next => action => {
switch(action.type){
case Types.LOGIN_SUCCESS:
Answers.logLogin('Login Success', true)
break
case Types.LOGIN_FAILURE:
Answers.logLogin('Login Success', false)
break
case Types.REGISTER_SUCCESS:
Answers.logSignUp('SignUp Success', false)
break
}
return next(action)
}
const crashLogger = store => next => action => {
try {
return next(action)
} catch (err) {
console.error('Caught an exception!', err)
Answers.logCustom('Redux error', {
extra: {
action,
state: store.getState()
}
});
throw err
}
}
middleware.push(sagaMiddleware)
middleware.push(answersLogger)
middleware.push(crashLogger)
// Don't ship these
if (__DEV__) {
middleware.push(logger)
}
// a function which can create our store and auto-persist the data
export default () => {
let store = {}
// Add rehydrate enhancer if ReduxPersist is active
if (ReduxPersist.active) {
const enhancers = compose(
applyMiddleware(...middleware),
autoRehydrate(),
devTools()
)
store = createStore(
rootReducer,
enhancers
)
// configure persistStore and check reducer version number
RehydrationServices.updateReducers(store)
} else {
const enhancers = compose(
applyMiddleware(...middleware),
)
store = createStore(
rootReducer,
enhancers
)
}
// run sagas
sagaMiddleware.run(sagas)
devTools.updateStore(store)
return store
}
| igorlimansky/react-native-redux-boilerplate | src/core/store/store.js | JavaScript | mit | 2,872 |
/*
* 根据贝塞尔曲线获取两个经纬度之间的曲线
*/
'use strict';
var PI = Math.PI;
/*
* 初始贝塞尔曲线值
* params:
* start: {lat:112,lng:22} 起点
* end: {lat:112,lng:22} 终点
* isClockWise: bool 是否顺时针
*/
var BezierPath = function(start,end,isClockWise){
this.geometries = [];
this.start = start;
this.end = end;
this.clockWise = isClockWise;
}
/*
* 绘制曲线
*
* params:
* angle: 绘制角度 范围:0~90
*/
BezierPath.prototype.MakePath = function(angle) {
this.angle = angle;
var auxiliaryPoint = this.AuxiliaryPoint();
var bezier1x;
var bezier1y;
var bezier2x;
var bezier2y;
var bezier_x;
var bezier_y;
var t = 0;
while ( this.geometries.length <= 100 ) {
bezier1x = this.start.lng + ( auxiliaryPoint.lng - this.start.lng ) * t;
bezier1y = this.start.lat + ( auxiliaryPoint.lat - this.start.lat ) * t;
bezier2x = auxiliaryPoint.lng + ( this.end.lng - auxiliaryPoint.lng ) * t;
bezier2y = auxiliaryPoint.lat + ( this.end.lat - auxiliaryPoint.lat ) * t;
bezier_x = bezier1x + ( bezier2x - bezier1x ) * t;
bezier_y = bezier1y + ( bezier2y - bezier1y ) * t;
this.geometries.push({lat:bezier_y,lng:bezier_x});
t += 0.01;
}
}
/*
* 获取辅助点
*
*/
BezierPath.prototype.AuxiliaryPoint = function() {
if (this.angle < 0) {
this.angle = 0;
}else if(this.angle > 90){
this.angle = 90;
}
var target = {lat:0,lng:0};
// 两点之间的角度
var btpAngle = Math.atan2(this.start.lat-this.end.lat,this.start.lng-this.end.lng)*180/PI;
// 中间点
var center = {lat:(this.start.lat+this.end.lat)/2,lng:(this.start.lng+this.end.lng)/2};
// 距离
var distance = Math.sqrt((this.start.lat-this.end.lat)*(this.start.lat-this.end.lat)+(this.start.lng-this.end.lng)*(this.start.lng-this.end.lng))
// 中间点到辅助点的距离
var adis = (distance/2.0)*Math.tan(this.angle*PI/180.0);
// 辅助点的经纬度
var auxAngle = Math.abs(btpAngle) > 90 ? 180 - Math.abs(btpAngle):Math.abs(btpAngle);
var lat = adis*Math.sin((90 - auxAngle)*PI/180);
var lng = adis*Math.cos((90 - auxAngle)*PI/180);
if (this.start.lat>this.end.lat) {
this.isClockWise = !this.isClockWise;
}
if (btpAngle >= 90) {
target.lat = center.lat + (this.isClockWise?lat:-1*lat);
target.lng = center.lng + (this.isClockWise?lng:-1*lng);
}else{
target.lat = center.lat + (this.isClockWise?lat:-1*lat);
target.lng = center.lng - (this.isClockWise?lng:-1*lng);
}
if (target.lat > 90) {
target.lat = 90.0;
}else if (target.lat <- 90){
target.lat = -90.0;
}
if (target.lng > 180) {
target.lng = target.lng-360.0;
}else if (target.lng <- 180){
target.lng = 360.0 + target.lng;
}
return target;
}
/*
* 转化 mapbox feature data
*/
BezierPath.prototype.toMapBoxFeature = function(properties) {
properties = properties || {};
if (this.geometries.length <= 0) {
return {'geometry': { 'type': 'LineString', 'coordinates': null },
'type': 'Feature', 'properties': properties
};
} else {
var multiline = [];
for (var i = 0; i < this.geometries.length ; i++) {
multiline.push([this.geometries[i].lng,this.geometries[i].lat]);
}
return {'geometry': { 'type': 'LineString', 'coordinates': multiline },
'type': 'Feature', 'properties': properties};
}
};
| ZacksTsang/BezierPath | bezierpath.js | JavaScript | mit | 3,579 |
/** @jsx jsx */
import { jsx } from 'slate-hyperscript'
export const input = (
<element>
<text>word</text>
</element>
)
export const output = {
children: [
{
text: 'word',
},
],
}
| ianstormtaylor/slate | packages/slate-hyperscript/test/fixtures/element-text-string.tsx | TypeScript | mit | 207 |
// Plugin.cs
// (c) Copyright Cirrious Ltd. http://www.cirrious.com
// MvvmCross is licensed using Microsoft Public License (Ms-PL)
// Contributions and inspirations noted in readme.md and license.txt
//
// Project Lead - Stuart Lodge, @slodge, me@slodge.com
using Cirrious.CrossCore;
using Cirrious.CrossCore.Plugins;
namespace MvvmCross.Plugins.File.Touch
{
public class Plugin
: IMvxPlugin
{
public void Load()
{
Mvx.RegisterType<IMvxFileStore, MvxTouchFileStore>();
Mvx.RegisterType<IMvxFileStoreAsync, MvxTouchFileStore>();
}
}
} | MatthewSannes/MvvmCross-Plugins | File/MvvmCross.Plugins.File.Touch/Plugin.cs | C# | mit | 615 |
<?xml version="1.0" ?><!DOCTYPE TS><TS language="ur_PK" version="2.1">
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About Nanite</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+39"/>
<source><b>Nanite</b> version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+41"/>
<source>Copyright © 2009-2014 The Bitcoin developers
Copyright © 2012-2014 The NovaCoin developers
Copyright © 2014 The Nanite 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 (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>Double-click to edit address or label</source>
<translation>ایڈریس یا لیبل میں ترمیم کرنے پر ڈبل کلک کریں</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>نیا ایڈریس بنائیں</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-46"/>
<source>These are your Nanite 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 type="unfinished"/>
</message>
<message>
<location line="+60"/>
<source>&Copy Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a Nanite address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-14"/>
<source>Verify a message to ensure it was signed with a specified Nanite address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+65"/>
<source>Copy &Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>&Edit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+250"/>
<source>Export Address Book Data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>چٹ</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation> پتہ</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>چٹ کے بغیر</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>پاس فریز داخل کریں</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>نیا پاس فریز</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>نیا پاس فریز دہرائیں</translation>
</message>
<message>
<location line="+33"/>
<source>Serves to disable the trivial sendmoney when OS account compromised. Provides no real security.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>For staking only</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+35"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>بٹوا ان لاک</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>خفیہ کشائی کر یںبٹوے کے</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>پاس فریز تبدیل کریں</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR COINS</b>!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+103"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-133"/>
<location line="+60"/>
<source>Wallet encrypted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-58"/>
<source>Nanite 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 type="unfinished"/>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+44"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-56"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<location line="+50"/>
<source>The supplied passphrases do not match.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-38"/>
<source>Wallet unlock failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<location line="+12"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+280"/>
<source>Sign &message...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+242"/>
<source>Synchronizing with network...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-308"/>
<source>&Overview</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>&Transactions</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>&Address Book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Edit the list of stored addresses and labels</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-13"/>
<source>&Receive coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show the list of addresses for receiving payments</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-7"/>
<source>&Send coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>E&xit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Show information about Nanite</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>&Encrypt Wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+250"/>
<source>~%n block(s) remaining</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Downloaded %1 of %2 blocks of transaction history (%3% done).</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-247"/>
<source>&Export...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-62"/>
<source>Send coins to a Nanite address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+45"/>
<source>Modify configuration options for Nanite</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>Export the data in the current tab to a file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-14"/>
<source>Encrypt or decrypt wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Backup wallet to another location</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>&Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-5"/>
<source>&Verify message...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-200"/>
<source>Nanite</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+178"/>
<source>&About Nanite</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Unlock wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>&Lock Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Lock wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+34"/>
<source>&File</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>&Settings</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>&Help</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Tabs toolbar</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Actions toolbar</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<location line="+9"/>
<source>[testnet]</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<location line="+60"/>
<source>Nanite client</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+70"/>
<source>%n active connection(s) to Nanite network</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+40"/>
<source>Downloaded %1 blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+413"/>
<source>Staking.<br>Your weight is %1<br>Network weight is %2<br>Expected time to earn reward is %3</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Not staking because wallet is locked</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Not staking because wallet is offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Not staking because wallet is syncing</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Not staking because you don't have mature coins</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="-403"/>
<source>%n second(s) ago</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="-284"/>
<source>&Unlock Wallet...</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+288"/>
<source>%n minute(s) ago</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n hour(s) ago</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s) ago</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Up to date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Catching up...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Last received block was generated %1.</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Confirm transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Sent transaction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Incoming transaction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+100"/>
<location line="+15"/>
<source>URI handling</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-15"/>
<location line="+15"/>
<source>URI can not be parsed! This can be caused by an invalid Nanite address or malformed URI parameters.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Backup Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+76"/>
<source>%n second(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n minute(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n hour(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+18"/>
<source>Not staking</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoin.cpp" line="+109"/>
<source>A fatal error occurred. Nanite can no longer continue safely and will quit.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+90"/>
<source>Network Alert</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<location filename="../forms/coincontroldialog.ui" line="+14"/>
<source>Coin Control</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Quantity:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>Bytes:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+48"/>
<source>Amount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>Priority:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+48"/>
<source>Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="+551"/>
<source>no</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="+51"/>
<source>After Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Change:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+69"/>
<source>(un)select all</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Tree mode</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>List mode</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+45"/>
<source>Amount</source>
<translation>رقم</translation>
</message>
<message>
<location line="+5"/>
<source>Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Address</source>
<translation> پتہ</translation>
</message>
<message>
<location line="+5"/>
<source>Date</source>
<translation>تاریخ</translation>
</message>
<message>
<location line="+5"/>
<source>Confirmations</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Confirmed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Priority</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="-515"/>
<source>Copy address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<location line="+26"/>
<source>Copy amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-25"/>
<source>Copy transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>Copy quantity</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Copy fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+317"/>
<source>highest</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>high</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>medium-high</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>medium</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>low-medium</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>low</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>lowest</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+155"/>
<source>DUST</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>yes</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</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 "medium".
This means a fee of at least %1 per kb is required.</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="+37"/>
<location line="+66"/>
<source>(no label)</source>
<translation>چٹ کے بغیر</translation>
</message>
<message>
<location line="-9"/>
<source>change from %1 (%2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>(change)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+20"/>
<source>New receiving address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid Nanite address.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+420"/>
<location line="+12"/>
<source>Nanite-Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Reserved amount does not participate in staking and is therefore spendable at any time.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Reserve</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Automatically start Nanite after logging in to the system.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Start Nanite on system login</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Detach databases at shutdown</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>&Network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Automatically open the Nanite client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Connect to the Nanite network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting Nanite.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Whether to show Nanite addresses in the transaction list or not.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Whether to show coin control features or not.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Display coin &control features (experts only!)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+55"/>
<source>default</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+149"/>
<location line="+9"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting Nanite.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+33"/>
<location line="+231"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the Nanite network after a connection is established, but this process has not completed yet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-160"/>
<source>Stake:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-107"/>
<source>Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>Spendable:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Your current spendable balance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>Immature:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>Total:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Your current total balance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="-29"/>
<source>Total of coins that was staked, and do not yet count toward the current balance</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../overviewpage.cpp" line="+113"/>
<location line="+1"/>
<source>out of sync</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Show the Nanite-Qt help message to get a list with possible Nanite command-line options.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-104"/>
<source>Nanite - Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Nanite Core</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Open the Nanite debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-33"/>
<source>Welcome to the Nanite RPC console.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+182"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+76"/>
<source>Coin Control Features</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>Inputs...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>automatically selected</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Insufficient funds!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+77"/>
<source>Quantity:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<location line="+35"/>
<source>0</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-19"/>
<source>Bytes:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+51"/>
<source>Amount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<location line="+86"/>
<location line="+86"/>
<location line="+32"/>
<source>0.00 SC</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-191"/>
<source>Priority:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>medium</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>no</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>After Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Change</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+50"/>
<source>custom change address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+106"/>
<source>Send to multiple recipients at once</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Balance:</source>
<translation>بیلنس:</translation>
</message>
<message>
<location line="+16"/>
<source>123.456 SC</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-173"/>
<source>Enter a Nanite address (e.g. S23Frty4r2RoEdqYk3QsAqFckyf9pRHN6i)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Copy quantity</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+86"/>
<source><b>%1</b> to %2 (%3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>The recipient address is not valid, please recheck.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+251"/>
<source>WARNING: Invalid Nanite address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>(no label)</source>
<translation>چٹ کے بغیر</translation>
</message>
<message>
<location line="+4"/>
<source>WARNING: unknown change address</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>&Label:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>The address to send the payment to (e.g. S23Frty4r2RoEdqYk3QsAqFckyf9pRHN6i)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Choose address from address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a Nanite address (e.g. S23Frty4r2RoEdqYk3QsAqFckyf9pRHN6i)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<location line="+124"/>
<source>&Sign Message</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. S23Frty4r2RoEdqYk3QsAqFckyf9pRHN6i)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<location line="+203"/>
<source>Choose an address from the address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-193"/>
<location line="+203"/>
<source>Alt+A</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-193"/>
<source>Paste address from clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>Copy the current signature to the system clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this Nanite address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Reset all sign message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-87"/>
<location line="+70"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. S23Frty4r2RoEdqYk3QsAqFckyf9pRHN6i)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified Nanite address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Reset all verify message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a Nanite address (e.g. S23Frty4r2RoEdqYk3QsAqFckyf9pRHN6i)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Enter Nanite signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+19"/>
<source>Open until %1</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="-2"/>
<source>Open for %n block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+8"/>
<source>conflicted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1/offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>تاریخ</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 510 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 type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Inputs</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation>رقم</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-211"/>
<source>, has not been successfully broadcast yet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>unknown</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+226"/>
<source>Date</source>
<translation>تاریخ</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>ٹائپ</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation> پتہ</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>رقم</translation>
</message>
<message>
<location line="+60"/>
<source>Open until %1</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Confirmed (%1 confirmations)</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="-15"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Confirming (%1 of %2 recommended confirmations)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Conflicted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Immature (%1 confirmations, will be available after %2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+42"/>
<source>Received with</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>کو بھیجا</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>(N / A)</translation>
</message>
<message>
<location line="+190"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+55"/>
<location line="+16"/>
<source>All</source>
<translation>تمام</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>آج</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>اس ہفتے</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>اس مہینے</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>پچھلے مہینے</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>اس سال</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>دیگر</translation>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>کو بھیجا</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+144"/>
<source>Export Transaction Data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>تاریخ</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>ٹائپ</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>چٹ</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation> پتہ</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>رقم</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+206"/>
<source>Sending...</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+33"/>
<source>Nanite version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Usage:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Send command to -server or Nanited</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>List commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Get help for a command</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Options:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Specify configuration file (default: Nanite.conf)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Specify pid file (default: Nanited.pid)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Specify wallet file (within data directory)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set database disk log size in megabytes (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Listen for connections on <port> (default: 15714 or testnet: 25714)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Specify your own public address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Bind to given address. Use [host]:port notation for IPv6</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Stake your coins to support network and gain reward (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-44"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+51"/>
<source>Detach block and address databases. Increases shutdown time (default: 0)</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="-87"/>
<source>Listen for JSON-RPC connections on <port> (default: 15715 or testnet: 25715)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-11"/>
<source>Accept command line and JSON-RPC commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+101"/>
<source>Error: Transaction creation failed </source>
<translation type="unfinished"/>
</message>
<message>
<location line="-5"/>
<source>Error: Wallet locked, unable to create transaction </source>
<translation type="unfinished"/>
</message>
<message>
<location line="-8"/>
<source>Importing blockchain data file.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Importing bootstrap blockchain data file.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-88"/>
<source>Run in the background as a daemon and accept commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use the test network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-24"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="-20"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="+61"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong Nanite will not work properly.</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="-30"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Block creation options:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-62"/>
<source>Connect only to the specified node(s)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+94"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-90"/>
<source>Find peers using DNS lookup (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Sync checkpoints policy (default: strict)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+83"/>
<source>Invalid -tor address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Invalid amount for -reservebalance=<amount></source>
<translation type="unfinished"/>
</message>
<message>
<location line="-82"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-16"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Prepend debug output with timestamp</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-74"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+41"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-29"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-42"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+109"/>
<source>Unable to sign checkpoint, wrong checkpointkey?
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-80"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-25"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+42"/>
<source>Username for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+47"/>
<source>Verifying database integrity...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+57"/>
<source>WARNING: syncronized checkpoint violation detected, but skipped!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Warning: Disk space is low!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-48"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-54"/>
<source>Password for JSON-RPC connections</source>
<translation type="unfinished"/>
</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=Naniterpc
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 "Nanite Alert" admin@foo.com
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+51"/>
<source>Find peers using internet relay chat (default: 0)</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>When creating transactions, ignore inputs with value less than this (default: 0.01)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Require a confirmations for change (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enforce transaction scripts to use canonical PUSH operators (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Upgrade wallet to latest format</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 2500, 0 = all)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-6, default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Imports blocks from external blk000?.dat file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Server certificate file (default: server.cert)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+53"/>
<source>Error: Wallet unlocked for staking only, unable to create transaction.</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="-158"/>
<source>This help message</source>
<translation>یہ مدد کا پیغام</translation>
</message>
<message>
<location line="+95"/>
<source>Wallet %s resides outside data directory %s.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot obtain a lock on data directory %s. Nanite is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-98"/>
<source>Nanite</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+140"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-130"/>
<source>Connect through socks proxy</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+122"/>
<source>Loading addresses...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-15"/>
<source>Error loading blkindex.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error loading wallet.dat: Wallet requires newer version of Nanite</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Wallet needed to be rewritten: restart Nanite to complete</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-16"/>
<source>Invalid -proxy address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-24"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+44"/>
<source>Error: could not start node</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Sending...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Invalid amount</source>
<translation>غلط رقم</translation>
</message>
<message>
<location line="+1"/>
<source>Insufficient funds</source>
<translation>ناکافی فنڈز</translation>
</message>
<message>
<location line="-34"/>
<source>Loading block index...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-103"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+122"/>
<source>Unable to bind to %s on this computer. Nanite is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-97"/>
<source>Fee per KB to add to transactions you send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+55"/>
<source>Invalid amount for -mininput=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Loading wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Cannot downgrade wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot initialize keypool</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot write default address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Rescanning...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Done loading</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-167"/>
<source>To use the %s option</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Error</source>
<translation>نقص</translation>
</message>
<message>
<location line="+6"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation type="unfinished"/>
</message>
</context>
</TS> | xNanite/Nanite | src/qt/locale/bitcoin_ur_PK.ts | TypeScript | mit | 107,598 |
namespace StockportWebapp.Emails.Models
{
public class GroupPublish
{
public string Name { get; set; }
public string Slug { get; set; }
}
}
| smbc-digital/iag-webapp | src/StockportWebapp/Emails/Models/GroupPublish.cs | C# | mit | 171 |
import './adventure_status_bar.html';
import { Template } from 'meteor/templating';
/**
* Template Helpers
*/
Template.AdventureStatusBar.helpers({
getHeaderMargin(){
return Template.instance().headerMargin.get();
},
adventureStatus(){
return this.adventure.get().status
}
});
/**
* Template Event Handlers
*/
Template.AdventureStatusBar.events({});
/**
* Template Created
*/
Template.AdventureStatusBar.onCreated(() => {
let instance = Template.instance();
instance.headerMargin = new ReactiveVar();
});
/**
* Template Rendered
*/
Template.AdventureStatusBar.onRendered(() => {
let instance = Template.instance();
instance.autorun(() => {
let viewport = instance.data.viewport.get(),
header = instance.$(".adventure-status-header"),
offset = $(".roba-accordion-content").first().offset(),
currentMargin = parseInt(header.css("margin-top"));
if(currentMargin >= 0 && viewport && viewport.offset){
instance.headerMargin.set(currentMargin + viewport.offset.top - offset.top);
}
})
});
/**
* Template Destroyed
*/
Template.AdventureStatusBar.onDestroyed(() => {
});
| austinsand/doc-roba | meteor/client/ui/pages/adventure_console/adventure_status_bar.js | JavaScript | mit | 1,164 |
/*
* ofxBox2dWeldJoint.cpp
* Taken from ofxBox2dJoint by Nick Hardeman
*
*
* Created by Joel Gethin Lewis on 20/2/2011
*
*/
#include "ofxBox2dWeldJoint.h"
//----------------------------------------
ofxBox2dWeldJoint::ofxBox2dWeldJoint() {
world = NULL;
alive = false;
}
ofxBox2dWeldJoint::ofxBox2dWeldJoint(b2World* b2world, b2Body* body1, b2Body* body2, bool bCollideConnected) {
ofxBox2dWeldJoint();
setup(b2world, body1, body2, bCollideConnected);
}
//----------------------------------------
ofxBox2dWeldJoint::ofxBox2dWeldJoint(b2World* b2world, b2Body* body1, b2Body* body2, b2Vec2 anchor, bool bCollideConnected) {
ofxBox2dWeldJoint();
setup(b2world, body1, body2, anchor, bCollideConnected);
}
//----------------------------------------
void ofxBox2dWeldJoint::setup(b2World* b2world, b2Body* body1, b2Body* body2, bool bCollideConnected) {
b2Vec2 a1, a2;
a1 = body1->GetWorldCenter();
a2 = body2->GetWorldCenter();
b2Vec2 anchor = a2 - a1;
anchor *= 0.5f;
anchor += a1;
setup(b2world, body1, body2, anchor, bCollideConnected);
}
//----------------------------------------
void ofxBox2dWeldJoint::setup(b2World* b2world, b2Body* body1, b2Body* body2, b2Vec2 anchor, bool bCollideConnected) {
setWorld(b2world);
b2WeldJointDef jointDef;
jointDef.Initialize(body1, body2, anchor);
jointDef.collideConnected = bCollideConnected;
joint = (b2WeldJoint*)world->CreateJoint(&jointDef);
alive = true;
}
//----------------------------------------
void ofxBox2dWeldJoint::setWorld(b2World* w) {
if(w == NULL) {
ofLog(OF_LOG_NOTICE, "ofxBox2dWeldJoint :: setWorld : - box2d world needed -");
return;
}
world = w;
}
//----------------------------------------
bool ofxBox2dWeldJoint::isSetup() {
if (world == NULL) {
ofLog(OF_LOG_NOTICE, "ofxBox2dWeldJoint :: world must be set!");
return false;
}
if (joint == NULL) {
ofLog(OF_LOG_NOTICE, "ofxBox2dWeldJoint :: setup function must be called!");
return false;
}
return true;
}
//----------------------------------------
void ofxBox2dWeldJoint::draw() {
if(!alive) return;
b2Vec2 p1 = joint->GetAnchorA();
b2Vec2 p2 = joint->GetAnchorB();
p1 *= OFX_BOX2D_SCALE;
p2 *= OFX_BOX2D_SCALE;
ofLine(p1.x, p1.y, p2.x, p2.y);
}
//----------------------------------------
void ofxBox2dWeldJoint::destroy() {
if (!isSetup()) return;
world->DestroyJoint(joint);
joint = NULL;
alive = false;
}
//----------------------------------------
ofxVec2f ofxBox2dWeldJoint::getReactionForce(float inv_dt) const {
b2Vec2 vec = getReactionForceB2D(inv_dt);
return ofxVec2f(vec.x, vec.y);
}
b2Vec2 ofxBox2dWeldJoint::getReactionForceB2D(float inv_dt) const {
return joint->GetReactionForce(inv_dt);
}
float ofxBox2dWeldJoint::getReactionTorque(float inv_dt) const {
return (float)joint->GetReactionTorque(inv_dt);
}
| HellicarAndLewis/NorwegianWood | addons/ofxBox2d/src/ofxBox2dWeldJoint.cpp | C++ | mit | 2,839 |
<?xml version="1.0" ?><!DOCTYPE TS><TS language="es_CL" version="2.0">
<defaultcodec>UTF-8</defaultcodec>
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About Okcoin</source>
<translation>Sobre Okcoin</translation>
</message>
<message>
<location line="+39"/>
<source><b>Okcoin</b> version</source>
<translation><b>Okcoin</b> - versión </translation>
</message>
<message>
<location line="+57"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source>
<translation>
Este es un software experimental.
Distribuido bajo la licencia MIT/X11, vea el archivo adjunto
COPYING o http://www.opensource.org/licenses/mit-license.php.
Este producto incluye software desarrollado por OpenSSL Project para su uso en
el OpenSSL Toolkit (http://www.openssl.org/), software criptográfico escrito por
Eric Young (eay@cryptsoft.com) y UPnP software escrito por Thomas Bernard.</translation>
</message>
<message>
<location filename="../aboutdialog.cpp" line="+14"/>
<source>Copyright</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The Okcoin developers</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>Guia de direcciones</translation>
</message>
<message>
<location line="+19"/>
<source>Double-click to edit address or label</source>
<translation>Haz doble clic para editar una dirección o etiqueta</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>Crea una nueva dirección</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Copia la dirección seleccionada al portapapeles</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation>&Nueva dirección</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+63"/>
<source>These are your Okcoin 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>Estas son tus direcciones Okcoin para recibir pagos. Puedes utilizar una diferente por cada persona emisora para saber quien te está pagando.</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>&Copy Address</source>
<translation>&Copia dirección</translation>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation>Mostrar Código &QR </translation>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a Okcoin address</source>
<translation>Firmar un mensaje para provar que usted es dueño de esta dirección</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>Firmar Mensaje</translation>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Export the data in the current tab to a file</source>
<translation>Exportar los datos de la pestaña actual a un archivo</translation>
</message>
<message>
<location line="+3"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-44"/>
<source>Verify a message to ensure it was signed with a specified Okcoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>&Borrar</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="-5"/>
<source>These are your Okcoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Copy &Label</source>
<translation>Copia &etiqueta</translation>
</message>
<message>
<location line="+1"/>
<source>&Edit</source>
<translation>&Editar</translation>
</message>
<message>
<location line="+1"/>
<source>Send &Coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+260"/>
<source>Export Address Book Data</source>
<translation>Exporta datos de la guia de direcciones</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Archivos separados por coma (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>Exportar errores</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>No se pudo escribir al archivo %1.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>Etiqueta</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Dirección</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(sin etiqueta)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>Introduce contraseña actual </translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>Nueva contraseña</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>Repite nueva contraseña:</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+33"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation>Introduce la nueva contraseña para la billetera.<br/>Por favor utiliza un contraseña <b>de 10 o mas caracteres aleatorios</b>, u <b>ocho o mas palabras</b>.</translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>Codificar billetera</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Esta operación necesita la contraseña para desbloquear la billetera.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>Desbloquea billetera</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Esta operación necesita la contraseña para decodificar la billetara.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>Decodificar cartera</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>Cambia contraseña</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Introduce la contraseña anterior y la nueva de cartera</translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>Confirma la codificación de cartera</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR OkcoinS</b>!</source>
<translation>Atención: ¡Si codificas tu billetera y pierdes la contraseña perderás <b>TODOS TUS OkcoinS</b>!</translation>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>¿Seguro que quieres seguir codificando la billetera?</translation>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+100"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation>Precaucion: Mayúsculas Activadas</translation>
</message>
<message>
<location line="-130"/>
<location line="+58"/>
<source>Wallet encrypted</source>
<translation>Billetera codificada</translation>
</message>
<message>
<location line="-56"/>
<source>Okcoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your Okcoins from being stolen by malware infecting your computer.</source>
<translation>Okcoin se cerrará para finalizar el proceso de encriptación. Recuerde que encriptar su billetera no protegera completatamente sus Okcoins de ser robados por malware que infecte su computador</translation>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+42"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>Falló la codificación de la billetera</translation>
</message>
<message>
<location line="-54"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>La codificación de la billetera falló debido a un error interno. Tu billetera no ha sido codificada.</translation>
</message>
<message>
<location line="+7"/>
<location line="+48"/>
<source>The supplied passphrases do not match.</source>
<translation>Las contraseñas no coinciden.</translation>
</message>
<message>
<location line="-37"/>
<source>Wallet unlock failed</source>
<translation>Ha fallado el desbloqueo de la billetera</translation>
</message>
<message>
<location line="+1"/>
<location line="+11"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>La contraseña introducida para decodificar la billetera es incorrecta.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>Ha fallado la decodificación de la billetera</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>La contraseña de billetera ha sido cambiada con éxito.</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+233"/>
<source>Sign &message...</source>
<translation>Firmar &Mensaje...</translation>
</message>
<message>
<location line="+280"/>
<source>Synchronizing with network...</source>
<translation>Sincronizando con la red...</translation>
</message>
<message>
<location line="-349"/>
<source>&Overview</source>
<translation>&Vista general</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation>Muestra una vista general de la billetera</translation>
</message>
<message>
<location line="+20"/>
<source>&Transactions</source>
<translation>&Transacciónes</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>Explora el historial de transacciónes</translation>
</message>
<message>
<location line="+7"/>
<source>Edit the list of stored addresses and labels</source>
<translation>Edita la lista de direcciones y etiquetas almacenadas</translation>
</message>
<message>
<location line="-14"/>
<source>Show the list of addresses for receiving payments</source>
<translation>Muestra la lista de direcciónes utilizadas para recibir pagos</translation>
</message>
<message>
<location line="+31"/>
<source>E&xit</source>
<translation>&Salir</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>Salir del programa</translation>
</message>
<message>
<location line="+4"/>
<source>Show information about Okcoin</source>
<translation>Muestra información acerca de Okcoin</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>Acerca de</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>Mostrar Información sobre QT</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>&Opciones</translation>
</message>
<message>
<location line="+6"/>
<source>&Encrypt Wallet...</source>
<translation>&Codificar la billetera...</translation>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation>&Respaldar billetera...</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>&Cambiar la contraseña...</translation>
</message>
<message>
<location line="+285"/>
<source>Importing blocks from disk...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Reindexing blocks on disk...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-347"/>
<source>Send coins to a Okcoin address</source>
<translation>Enviar monedas a una dirección Okcoin</translation>
</message>
<message>
<location line="+49"/>
<source>Modify configuration options for Okcoin</source>
<translation>Modifica las opciones de configuración de Okcoin</translation>
</message>
<message>
<location line="+9"/>
<source>Backup wallet to another location</source>
<translation>Respaldar billetera en otra ubicación</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Cambiar la contraseña utilizada para la codificación de la billetera</translation>
</message>
<message>
<location line="+6"/>
<source>&Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-4"/>
<source>&Verify message...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-165"/>
<location line="+530"/>
<source>Okcoin</source>
<translation>Okcoin</translation>
</message>
<message>
<location line="-530"/>
<source>Wallet</source>
<translation>Cartera</translation>
</message>
<message>
<location line="+101"/>
<source>&Send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Receive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>&Addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>&About Okcoin</source>
<translation>&Sobre Okcoin</translation>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation>&Mostrar/Ocultar</translation>
</message>
<message>
<location line="+1"/>
<source>Show or hide the main Window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Encrypt the private keys that belong to your wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Sign messages with your Okcoin addresses to prove you own them</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Verify messages to ensure they were signed with specified Okcoin addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>&File</source>
<translation>&Archivo</translation>
</message>
<message>
<location line="+7"/>
<source>&Settings</source>
<translation>&Configuración</translation>
</message>
<message>
<location line="+6"/>
<source>&Help</source>
<translation>&Ayuda</translation>
</message>
<message>
<location line="+9"/>
<source>Tabs toolbar</source>
<translation>Barra de pestañas</translation>
</message>
<message>
<location line="+17"/>
<location line="+10"/>
<source>[testnet]</source>
<translation>[red-de-pruebas]</translation>
</message>
<message>
<location line="+47"/>
<source>Okcoin client</source>
<translation>Cliente Okcoin</translation>
</message>
<message numerus="yes">
<location line="+141"/>
<source>%n active connection(s) to Okcoin network</source>
<translation><numerusform>%n conexión activa hacia la red Okcoin</numerusform><numerusform>%n conexiones activas hacia la red Okcoin</numerusform></translation>
</message>
<message>
<location line="+22"/>
<source>No block source available...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Processed %1 of %2 (estimated) blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Processed %1 blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+20"/>
<source>%n hour(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n week(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>%1 behind</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Last received block was generated %1 ago.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Transactions after this will not yet be visible.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>Error</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+70"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-140"/>
<source>Up to date</source>
<translation>Actualizado</translation>
</message>
<message>
<location line="+31"/>
<source>Catching up...</source>
<translation>Recuperando...</translation>
</message>
<message>
<location line="+113"/>
<source>Confirm transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Sent transaction</source>
<translation>Transacción enviada</translation>
</message>
<message>
<location line="+0"/>
<source>Incoming transaction</source>
<translation>Transacción entrante</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Fecha: %1
Cantidad: %2
Tipo: %3
Dirección: %4</translation>
</message>
<message>
<location line="+33"/>
<location line="+23"/>
<source>URI handling</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-23"/>
<location line="+23"/>
<source>URI can not be parsed! This can be caused by an invalid Okcoin address or malformed URI parameters.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>La billetera esta <b>codificada</b> y actualmente <b>desbloqueda</b></translation>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>La billetera esta <b>codificada</b> y actualmente <b>bloqueda</b></translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="+111"/>
<source>A fatal error occurred. Okcoin can no longer continue safely and will quit.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+104"/>
<source>Network Alert</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Editar dirección</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>&Etiqueta</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation>La etiqueta asociada con esta entrada de la libreta de direcciones</translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>&Dirección</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>La dirección asociada con esta entrada en la libreta de direcciones. Solo puede ser modificada para direcciónes de envío.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+21"/>
<source>New receiving address</source>
<translation>Nueva dirección para recibir</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>Nueva dirección para enviar</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>Editar dirección de recepción</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>Editar dirección de envio</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>La dirección introducida "%1" ya esta guardada en la libreta de direcciones.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid Okcoin address.</source>
<translation>La dirección introducida "%1" no es una dirección Okcoin valida.</translation>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>No se pudo desbloquear la billetera.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>La generación de nueva clave falló.</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+424"/>
<location line="+12"/>
<source>Okcoin-Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation>versión</translation>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation>Uso:</translation>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation>UI opciones</translation>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation>Arranca minimizado
</translation>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>Opciones</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>&Principal</translation>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation>Comisión de &transacciónes</translation>
</message>
<message>
<location line="+31"/>
<source>Automatically start Okcoin after logging in to the system.</source>
<translation>Inicia Okcoin automáticamente despues de encender el computador</translation>
</message>
<message>
<location line="+3"/>
<source>&Start Okcoin on system login</source>
<translation>&Inicia Okcoin al iniciar el sistema</translation>
</message>
<message>
<location line="+35"/>
<source>Reset all client options to default.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Reset Options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>&Network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Automatically open the Okcoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>Abre automáticamente el puerto del cliente Okcoin en el router. Esto funciona solo cuando tu router es compatible con UPnP y está habilitado.</translation>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation>Direcciona el puerto usando &UPnP</translation>
</message>
<message>
<location line="+7"/>
<source>Connect to the Okcoin network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation>Conecta a la red Okcoin a través de un proxy SOCKS (ej. cuando te conectas por la red Tor)</translation>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation>&Conecta a traves de un proxy SOCKS:</translation>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation>&IP Proxy:</translation>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation>Dirección IP del servidor proxy (ej. 127.0.0.1)</translation>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation>&Puerto:</translation>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation>Puerto del servidor proxy (ej. 9050)</translation>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation>Muestra solo un ícono en la bandeja después de minimizar la ventana</translation>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&Minimiza a la bandeja en vez de la barra de tareas</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>Minimiza la ventana en lugar de salir del programa cuando la ventana se cierra. Cuando esta opción esta activa el programa solo se puede cerrar seleccionando Salir desde el menu.</translation>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation>M&inimiza a la bandeja al cerrar</translation>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation>&Mostrado</translation>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting Okcoin.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation>&Unidad en la que mostrar cantitades:</translation>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>Elige la subdivisión por defecto para mostrar cantidaded en la interfaz cuando se envien monedas</translation>
</message>
<message>
<location line="+9"/>
<source>Whether to show Okcoin addresses in the transaction list or not.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation>&Muestra direcciones en el listado de transaccioines</translation>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+53"/>
<source>default</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+130"/>
<source>Confirm options reset</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Some settings may require a client restart to take effect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Do you want to proceed?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+42"/>
<location line="+9"/>
<source>Warning</source>
<translation>Atención</translation>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting Okcoin.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>Formulario</translation>
</message>
<message>
<location line="+50"/>
<location line="+166"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the Okcoin network after a connection is established, but this process has not completed yet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-124"/>
<source>Balance:</source>
<translation>Saldo:</translation>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation>No confirmados:</translation>
</message>
<message>
<location line="-78"/>
<source>Wallet</source>
<translation>Cartera</translation>
</message>
<message>
<location line="+107"/>
<source>Immature:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation><b>Transacciones recientes</b></translation>
</message>
<message>
<location line="-101"/>
<source>Your current balance</source>
<translation>Tu saldo actual</translation>
</message>
<message>
<location line="+29"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation>Total de transacciones que no han sido confirmadas aun, y que no cuentan para el saldo actual.</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="+116"/>
<location line="+1"/>
<source>out of sync</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+107"/>
<source>Cannot start Okcoin: click-to-pay handler</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation>Solicitar Pago</translation>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation>Cantidad:</translation>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation>Etiqueta</translation>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation>Mensaje:</translation>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation>&Guardar Como...</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation>Imágenes PNG (*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<location line="+23"/>
<location filename="../rpcconsole.cpp" line="+339"/>
<source>N/A</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Show the Okcoin-Qt help message to get a list with possible Okcoin command-line options.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-104"/>
<source>Okcoin - Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Okcoin Core</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Open the Okcoin debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-30"/>
<source>Welcome to the Okcoin RPC console.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+124"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>Enviar monedas</translation>
</message>
<message>
<location line="+50"/>
<source>Send to multiple recipients at once</source>
<translation>Enviar a múltiples destinatarios</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation>&Agrega destinatario</translation>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation>Remover todos los campos de la transacción</translation>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>&Borra todos</translation>
</message>
<message>
<location line="+22"/>
<source>Balance:</source>
<translation>Balance:</translation>
</message>
<message>
<location line="+10"/>
<source>123.456 BTC</source>
<translation>123.456 BTC</translation>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation>Confirma el envio</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation>&Envía</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-59"/>
<source><b>%1</b> to %2 (%3)</source>
<translation><b>%1</b> to %2 (%3)</translation>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>Confirmar el envio de monedas</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation>Estas seguro que quieres enviar %1?</translation>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation>y</translation>
</message>
<message>
<location line="+23"/>
<source>The recipient address is not valid, please recheck.</source>
<translation>La dirección de destinatarion no es valida, comprueba otra vez.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>La cantidad por pagar tiene que ser mayor 0.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation>La cantidad sobrepasa tu saldo.</translation>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>El total sobrepasa tu saldo cuando se incluyen %1 como tasa de envio.</translation>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>Tienes una dirección duplicada, solo puedes enviar a direcciónes individuales de una sola vez.</translation>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation>Error: La transacción fue rechazada. Esto puede haber ocurrido si alguna de las monedas ya estaba gastada o si ha usado una copia de wallet.dat y las monedas se gastaron en la copia pero no se han marcado como gastadas aqui.</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation>Envio</translation>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation>Cantidad:</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>&Pagar a:</translation>
</message>
<message>
<location line="+34"/>
<source>The address to send the payment to (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+60"/>
<location filename="../sendcoinsentry.cpp" line="+26"/>
<source>Enter a label for this address to add it to your address book</source>
<translation>Introduce una etiqueta a esta dirección para añadirla a tu guia</translation>
</message>
<message>
<location line="-78"/>
<source>&Label:</source>
<translation>&Etiqueta:</translation>
</message>
<message>
<location line="+28"/>
<source>Choose address from address book</source>
<translation>Elije dirección de la guia</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>Pega dirección desde portapapeles</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>Elimina destinatario</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a Okcoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Introduce una dirección Okcoin (ej. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>&Sign Message</source>
<translation>&Firmar Mensaje</translation>
</message>
<message>
<location line="+6"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Introduce una dirección Okcoin (ej. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="+10"/>
<location line="+213"/>
<source>Choose an address from the address book</source>
<translation>Elije dirección de la guia</translation>
</message>
<message>
<location line="-203"/>
<location line="+213"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="-203"/>
<source>Paste address from clipboard</source>
<translation>Pega dirección desde portapapeles</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>Escriba el mensaje que desea firmar</translation>
</message>
<message>
<location line="+7"/>
<source>Signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Copy the current signature to the system clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this Okcoin address</source>
<translation>Firmar un mensjage para probar que usted es dueño de esta dirección</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Reset all sign message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>&Borra todos</translation>
</message>
<message>
<location line="-87"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Introduce una dirección Okcoin (ej. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified Okcoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Verify &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Reset all verify message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a Okcoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Introduce una dirección Okcoin (ej. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation>Click en "Firmar Mensage" para conseguir firma</translation>
</message>
<message>
<location line="+3"/>
<source>Enter Okcoin signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<location filename="../splashscreen.cpp" line="+22"/>
<source>The Okcoin developers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>[testnet]</source>
<translation>[red-de-pruebas]</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+20"/>
<source>Open until %1</source>
<translation>Abierto hasta %1</translation>
</message>
<message>
<location line="+6"/>
<source>%1/offline</source>
<translation>%1/fuera de linea</translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/no confirmado</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 confirmaciónes</translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation>Estado</translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>Fecha</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation>Generado</translation>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation>De</translation>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation>etiqueta</translation>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation>Credito</translation>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation>no aceptada</translation>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation>Debito</translation>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation>Comisión transacción</translation>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation>Cantidad total</translation>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>Mensaje</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation>Comentario</translation>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation>ID de Transacción</translation>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation>Las monedas generadas deben esperar 120 bloques antes de ser gastadas. Cuando has generado este bloque se emitió a la red para ser agregado en la cadena de bloques. Si falla al incluirse en la cadena, cambiará a "no aceptado" y las monedas no se podrán gastar. Esto puede ocurrir ocasionalmente si otro nodo genera un bloque casi al mismo tiempo que el tuyo.</translation>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>Transacción</translation>
</message>
<message>
<location line="+3"/>
<source>Inputs</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation>Cantidad</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-209"/>
<source>, has not been successfully broadcast yet</source>
<translation>, no ha sido emitido satisfactoriamente todavía</translation>
</message>
<message numerus="yes">
<location line="-35"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+70"/>
<source>unknown</source>
<translation>desconocido</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>Detalles de transacción</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>Esta ventana muestra información detallada sobre la transacción</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+225"/>
<source>Date</source>
<translation>Fecha</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>Tipo</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Dirección</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>Cantidad</translation>
</message>
<message numerus="yes">
<location line="+57"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+3"/>
<source>Open until %1</source>
<translation>Abierto hasta %1</translation>
</message>
<message>
<location line="+3"/>
<source>Offline (%1 confirmations)</source>
<translation>Fuera de linea (%1 confirmaciónes)</translation>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation>No confirmado (%1 de %2 confirmaciónes)</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Confirmado (%1 confirmaciones)</translation>
</message>
<message numerus="yes">
<location line="+8"/>
<source>Mined balance will be available when it matures in %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+5"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>Este bloque no ha sido recibido por otros nodos y probablemente no sea aceptado !</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>Generado pero no acceptado</translation>
</message>
<message>
<location line="+43"/>
<source>Received with</source>
<translation>Recibido con</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>Recibido de</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>Enviado a</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>Pagar a usted mismo</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>Minado</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>(n/a)</translation>
</message>
<message>
<location line="+199"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Estado de transacción. Pasa el raton sobre este campo para ver el numero de confirmaciónes.</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>Fecha y hora cuando se recibió la transaccion</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>Tipo de transacción.</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>Dirección de destino para la transacción</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>Cantidad restada o añadida al balance</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+52"/>
<location line="+16"/>
<source>All</source>
<translation>Todo</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>Hoy</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>Esta semana</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>Esta mes</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>Mes pasado</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>Este año</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>Rango...</translation>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation>Recibido con</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>Enviado a</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>A ti mismo</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>Minado</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>Otra</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>Introduce una dirección o etiqueta para buscar</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>Cantidad minima</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>Copia dirección</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Copia etiqueta</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Copiar Cantidad</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>Edita etiqueta</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+139"/>
<source>Export Transaction Data</source>
<translation>Exportar datos de transacción</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Archivos separados por coma (*.csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>Confirmado</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>Fecha</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>Tipo</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>Etiqueta</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Dirección</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>Cantidad</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>Error exportando</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>No se pudo escribir en el archivo %1.</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>Rango:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>para</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+193"/>
<source>Send Coins</source>
<translation>Enviar monedas</translation>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<location filename="../walletview.cpp" line="+42"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Export the data in the current tab to a file</source>
<translation>Exportar los datos de la pestaña actual a un archivo</translation>
</message>
<message>
<location line="+193"/>
<source>Backup Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Backup Successful</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The wallet data was successfully saved to the new location.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+94"/>
<source>Okcoin version</source>
<translation>Versión Okcoin</translation>
</message>
<message>
<location line="+102"/>
<source>Usage:</source>
<translation>Uso:</translation>
</message>
<message>
<location line="-29"/>
<source>Send command to -server or Okcoind</source>
<translation>Envia comando a Okcoin lanzado con -server u Okcoind
</translation>
</message>
<message>
<location line="-23"/>
<source>List commands</source>
<translation>Muestra comandos
</translation>
</message>
<message>
<location line="-12"/>
<source>Get help for a command</source>
<translation>Recibir ayuda para un comando
</translation>
</message>
<message>
<location line="+24"/>
<source>Options:</source>
<translation>Opciones:
</translation>
</message>
<message>
<location line="+24"/>
<source>Specify configuration file (default: Okcoin.conf)</source>
<translation>Especifica archivo de configuración (predeterminado: Okcoin.conf)
</translation>
</message>
<message>
<location line="+3"/>
<source>Specify pid file (default: Okcoind.pid)</source>
<translation>Especifica archivo pid (predeterminado: Okcoin.pid)
</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>Especifica directorio para los datos
</translation>
</message>
<message>
<location line="-9"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-28"/>
<source>Listen for connections on <port> (default: 9333 or testnet: 19333)</source>
<translation>Escuchar por conecciones en <puerto> (Por defecto: 9333 o red de prueba: 19333)</translation>
</message>
<message>
<location line="+5"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Mantener al menos <n> conecciones por cliente (por defecto: 125) </translation>
</message>
<message>
<location line="-48"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<source>Specify your own public address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>Umbral de desconección de clientes con mal comportamiento (por defecto: 100)</translation>
</message>
<message>
<location line="-134"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-29"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Listen for JSON-RPC connections on <port> (default: 9332 or testnet: 19332)</source>
<translation>Escucha conexiones JSON-RPC en el puerto <port> (predeterminado: 9332 or testnet: 19332)</translation>
</message>
<message>
<location line="+37"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Aceptar comandos consola y JSON-RPC
</translation>
</message>
<message>
<location line="+76"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Correr como demonio y acepta comandos
</translation>
</message>
<message>
<location line="+37"/>
<source>Use the test network</source>
<translation>Usa la red de pruebas
</translation>
</message>
<message>
<location line="-112"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-80"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=Okcoinrpc
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 "Okcoin Alert" admin@foo.com
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. Okcoin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation>Precaución: -paytxfee es muy alta. Esta es la comisión que pagarás si envias una transacción.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong Okcoin will not work properly.</source>
<translation>Precaución: Por favor revise que la fecha y hora de tu ordenador son correctas. Si tu reloj está mal configurado Okcoin no funcionará correctamente.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Block creation options:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Connect only to the specified node(s)</source>
<translation>Conecta solo al nodo especificado
</translation>
</message>
<message>
<location line="+3"/>
<source>Corrupted block database detected</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Do you want to rebuild the block database now?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error initializing block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error initializing wallet database environment %s!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error loading block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error opening block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error: Disk space is low!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: Wallet locked, unable to create transaction!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: system error: </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to read block info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to read block</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to sync block index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write file info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write to coin database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write transaction index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write undo data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Find peers using DNS lookup (default: 1 unless -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Generate coins (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 288, 0 = all)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-4, default: 3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Not enough file descriptors available.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Rebuild block chain index from current blk000??.dat files</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+26"/>
<source>Verifying blocks...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Verifying wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-69"/>
<source>Imports blocks from external blk000??.dat file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-76"/>
<source>Set the number of script verification threads (up to 16, 0 = auto, <0 = leave that many cores free, default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+77"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Invalid -tor address: '%s'</source>
<translation>Dirección -tor invalida: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -minrelaytxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -mintxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Maintain a full transaction index (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Only accept block chain matching built-in checkpoints (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation>Adjuntar informacion extra de depuracion. Implies all other -debug* options</translation>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Prepend debug output with timestamp</source>
<translation>Anteponer salida de depuracion con marca de tiempo</translation>
</message>
<message>
<location line="+5"/>
<source>SSL options: (see the Okcoin Wiki for SSL setup instructions)</source>
<translation>Opciones SSL: (ver la Okcoin Wiki para instrucciones de configuración SSL)</translation>
</message>
<message>
<location line="+1"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Enviar informacion de seguimiento a la consola en vez del archivo debug.log</translation>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation>Enviar informacion de seguimiento al depurador</translation>
</message>
<message>
<location line="+5"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Signing transaction failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation>Especifica tiempo de espera para conexion en milisegundos (predeterminado: 5000)</translation>
</message>
<message>
<location line="+4"/>
<source>System error: </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Transaction amount too small</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction amounts must be positive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction too large</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation>Intenta usar UPnP para mapear el puerto de escucha (default: 0)</translation>
</message>
<message>
<location line="+1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation>Intenta usar UPnP para mapear el puerto de escucha (default: 1 when listening)</translation>
</message>
<message>
<location line="+1"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Username for JSON-RPC connections</source>
<translation>Usuario para las conexiones JSON-RPC
</translation>
</message>
<message>
<location line="+4"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>You need to rebuild the databases using -reindex to change -txindex</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-50"/>
<source>Password for JSON-RPC connections</source>
<translation>Contraseña para las conexiones JSON-RPC
</translation>
</message>
<message>
<location line="-67"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Permite conexiones JSON-RPC desde la dirección IP especificada
</translation>
</message>
<message>
<location line="+76"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Envia comando al nodo situado en <ip> (predeterminado: 127.0.0.1)
</translation>
</message>
<message>
<location line="-120"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+147"/>
<source>Upgrade wallet to latest format</source>
<translation>Actualizar billetera al formato actual</translation>
</message>
<message>
<location line="-21"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Ajusta el numero de claves en reserva <n> (predeterminado: 100)
</translation>
</message>
<message>
<location line="-12"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Rescanea la cadena de bloques para transacciones perdidas de la cartera
</translation>
</message>
<message>
<location line="+35"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>Usa OpenSSL (https) para las conexiones JSON-RPC
</translation>
</message>
<message>
<location line="-26"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Certificado del servidor (Predeterminado: server.cert)
</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>Clave privada del servidor (Predeterminado: server.pem)
</translation>
</message>
<message>
<location line="-151"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation>Cifrados aceptados (Predeterminado: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)
</translation>
</message>
<message>
<location line="+165"/>
<source>This help message</source>
<translation>Este mensaje de ayuda
</translation>
</message>
<message>
<location line="+6"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>No es posible escuchar en el %s en este ordenador (bind returned error %d, %s)</translation>
</message>
<message>
<location line="-91"/>
<source>Connect through socks proxy</source>
<translation>Conecta mediante proxy socks</translation>
</message>
<message>
<location line="-10"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>Permite búsqueda DNS para addnode y connect
</translation>
</message>
<message>
<location line="+55"/>
<source>Loading addresses...</source>
<translation>Cargando direcciónes...</translation>
</message>
<message>
<location line="-35"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>Error cargando wallet.dat: Billetera corrupta</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat: Wallet requires newer version of Okcoin</source>
<translation>Error cargando wallet.dat: Billetera necesita una vercion reciente de Okcoin</translation>
</message>
<message>
<location line="+93"/>
<source>Wallet needed to be rewritten: restart Okcoin to complete</source>
<translation>La billetera necesita ser reescrita: reinicie Okcoin para completar</translation>
</message>
<message>
<location line="-95"/>
<source>Error loading wallet.dat</source>
<translation>Error cargando wallet.dat</translation>
</message>
<message>
<location line="+28"/>
<source>Invalid -proxy address: '%s'</source>
<translation>Dirección -proxy invalida: '%s'</translation>
</message>
<message>
<location line="+56"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-96"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+44"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>Cantidad inválida para -paytxfee=<amount>: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount</source>
<translation>Cantidad inválida</translation>
</message>
<message>
<location line="-6"/>
<source>Insufficient funds</source>
<translation>Fondos insuficientes</translation>
</message>
<message>
<location line="+10"/>
<source>Loading block index...</source>
<translation>Cargando el index de bloques...</translation>
</message>
<message>
<location line="-57"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Agrega un nodo para conectarse and attempt to keep the connection open</translation>
</message>
<message>
<location line="-25"/>
<source>Unable to bind to %s on this computer. Okcoin is probably already running.</source>
<translation>No es posible escuchar en el %s en este ordenador. Probablemente Okcoin ya se está ejecutando.</translation>
</message>
<message>
<location line="+64"/>
<source>Fee per KB to add to transactions you send</source>
<translation>Comisión por kB para adicionarla a las transacciones enviadas</translation>
</message>
<message>
<location line="+19"/>
<source>Loading wallet...</source>
<translation>Cargando cartera...</translation>
</message>
<message>
<location line="-52"/>
<source>Cannot downgrade wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Cannot write default address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+64"/>
<source>Rescanning...</source>
<translation>Rescaneando...</translation>
</message>
<message>
<location line="-57"/>
<source>Done loading</source>
<translation>Carga completa</translation>
</message>
<message>
<location line="+82"/>
<source>To use the %s option</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-74"/>
<source>Error</source>
<translation>Error</translation>
</message>
<message>
<location line="-31"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation type="unfinished"/>
</message>
</context>
</TS> | stamhe/okcoin | src/qt/locale/bitcoin_es_CL.ts | TypeScript | mit | 106,839 |
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Http\Requests;
use App\User;
use App\Models\Role;
use App\Models\Permission;
class DashboardController extends Controller
{
/**
* Instantiate a new DashboardController instance.
*/
public function __construct()
{
$this->middleware(['auth']);
// $this->middleware('log', ['only' => ['fooAction', 'barAction']]);
// $this->middleware('subscribed', ['except' => ['fooAction', 'barAction']]);
}
public function painel()
{
return view('dashboard.painel');
}
}
| ricardoaugusto/starter | app/Http/Controllers/DashboardController.php | PHP | mit | 576 |
import {Component, Injectable} from '@angular/core';
import {Injectable} from '@angular/core';
import {Http, Response} from "@angular/http";
import {Observable} from "rxjs/Rx";
@Injectable()
export class GameService {
constructor(private http:Http) {
}
stopGame(gameId:string) {
console.log('in stopGame');
return this.http.post("http://192.168.1.74:5135/games/abort/" + gameId, "")
.map(this.extractData)
.catch(this.handleError);
}
getScore(gameId:string) {
console.log('in updateScore');
return this.http.get("http://192.168.1.74:5135/games/" + gameId)
.map(this.extractData)
.catch(this.handleError);
}
revertScore(gameId: any){
return this.http.delete("http://192.168.1.74:5135/scores/last/" + gameId)
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res:Response) {
let body = res.json();
return body || {};
}
private handleError(error:any) {
// In a real world app, we might use a remote logging infrastructure
// We'd also dig deeper into the error to get a better message
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg); // log to console instead
return Observable.throw(errMsg);
}
}
| Ehofas/rocketPuncherFrontEnd | src/app/Games/game.service.ts | TypeScript | mit | 1,329 |
import DOMExporter from './DOMExporter'
import DefaultDOMElement from '../ui/DefaultDOMElement'
import { isBoolean } from 'lodash-es'
import forEach from '../util/forEach'
import isNumber from '../util/isNumber'
import isString from '../util/isString'
var defaultAnnotationConverter = {
tagName: 'span',
export: function(node, el) {
el.tagName = 'span'
el.attr('data-type', node.type)
var properties = node.toJSON()
forEach(properties, function(value, name) {
if (name === 'id' || name === 'type') return
if (isString(value) || isNumber(value) || isBoolean(value)) {
el.attr('data-'+name, value)
}
})
}
}
var defaultBlockConverter = {
export: function(node, el, converter) {
el.attr('data-type', node.type)
var properties = node.toJSON()
forEach(properties, function(value, name) {
if (name === 'id' || name === 'type') {
return
}
var prop = converter.$$('div').attr('property', name)
if (node.getPropertyType(name) === 'string' && value) {
prop.append(converter.annotatedText([node.id, name]))
} else {
prop.text(value)
}
el.append(prop)
})
}
}
/*
@class
@abstract
Base class for custom HTML exporters. If you want to use XML as your
exchange format see {@link model/XMLExporter}.
*/
class HTMLExporter extends DOMExporter {
constructor(config) {
super(Object.assign({ idAttribute: 'data-id' }, config))
// used internally for creating elements
this._el = DefaultDOMElement.parseHTML('<html></html>')
}
exportDocument(doc) {
var htmlEl = DefaultDOMElement.parseHTML('<html><head></head><body></body></html>')
return this.convertDocument(doc, htmlEl)
}
getDefaultBlockConverter() {
return defaultBlockConverter
}
getDefaultPropertyAnnotationConverter() {
return defaultAnnotationConverter
}
}
export default HTMLExporter
| stencila/substance | model/HTMLExporter.js | JavaScript | mit | 1,923 |
package net.buycraft.plugin;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import net.buycraft.plugin.data.Coupon;
import net.buycraft.plugin.data.GiftCard;
import net.buycraft.plugin.data.RecentPayment;
import net.buycraft.plugin.data.ServerEvent;
import net.buycraft.plugin.data.responses.*;
import okhttp3.*;
import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.*;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Objects;
@SuppressWarnings("UnnecessaryInterfaceModifier")
public interface BuyCraftAPI {
static final String API_URL = "https://plugin.buycraft.net";
static final String API_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ssX";
static final Gson gson = new GsonBuilder()
.setDateFormat(API_DATE_FORMAT)
.create();
public static BuyCraftAPI create(final String secret) {
return BuyCraftAPI.create(secret, null);
}
public static BuyCraftAPI create(final String secret, OkHttpClient client) {
OkHttpClient.Builder clientBuilder = client != null ? client.newBuilder() : new OkHttpClient.Builder();
//noinspection Convert2Lambda
return new Retrofit.Builder()
.baseUrl(API_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.client(clientBuilder
.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();
Request request = original.newBuilder()
.header("X-Buycraft-Secret", secret)
.header("Accept", "application/json")
.header("User-Agent", "BuycraftX")
.method(original.method(), original.body())
.build();
return chain.proceed(request);
}
})
.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Response response = chain.proceed(chain.request());
if (!response.isSuccessful()) {
ResponseBody body = response.body();
if (body == null) {
throw new BuyCraftAPIException("Unknown error occurred whilst deserializing error object.", response.request(), response, "");
}
String in = body.string();
if (!Objects.equals(response.header("Content-Type"), "application/json")) {
throw new BuyCraftAPIException("Unexpected content-type " + response.header("Content-Type"), response.request(), response, in);
}
BuycraftError error = gson.fromJson(in, BuycraftError.class);
if (error != null) {
throw new BuyCraftAPIException(error.getErrorMessage(), response.request(), response, in);
} else {
throw new BuyCraftAPIException("Unknown error occurred whilst deserializing error object.", response.request(), response, in);
}
}
return response;
}
}).build())
.build().create(BuyCraftAPI.class);
}
@GET("/information")
public Call<ServerInformation> getServerInformation();
@GET("/listing")
public Call<Listing> retrieveListing();
@GET("/queue")
public Call<DueQueueInformation> retrieveDueQueue();
@GET("/queue/offline-commands")
public Call<QueueInformation> retrieveOfflineQueue();
@GET("/queue/online-commands/{id}")
public Call<QueueInformation> getPlayerQueue(@Path("id") int id);
@FormUrlEncoded
@HTTP(method = "DELETE", path = "/queue", hasBody = true)
public Call<Void> deleteCommands(@Field("ids[]") List<Integer> ids);
@FormUrlEncoded
@POST("/checkout")
public Call<CheckoutUrlResponse> getCheckoutUri(@Field("username") String username, @Field("package_id") int packageId);
@FormUrlEncoded
@POST("/checkout")
public Call<CheckoutUrlResponse> getCategoryUri(@Field("username") String username, @Field("category_id") int categoryId); //TODO Figure out category=true
@GET("/payments")
public Call<List<RecentPayment>> getRecentPayments(@Query("limit") int limit);
@GET("/coupons")
public Call<CouponListing> getAllCoupons();
@GET("/coupons/{id}")
public Call<Coupon> getCoupon(@Path("id") int id);
@DELETE("/coupons/{id}")
public Call<Void> deleteCoupon(@Path("id") int id);
@DELETE("/coupons/{id}/code")
public Call<Void> deleteCoupon(@Path("id") String id);
public default Call<CouponSingleListing> createCoupon(Coupon coupon) {
FormBody.Builder build = new FormBody.Builder()
.add("code", coupon.getCode())
.add("effective_on", coupon.getEffective().getType());
switch (coupon.getEffective().getType()) {
case "packages":
for (Integer id1 : coupon.getEffective().getPackages()) {
build.add("packages[]", Integer.toString(id1));
}
break;
case "categories":
for (Integer id2 : coupon.getEffective().getCategories()) {
build.add("categories[]", Integer.toString(id2));
}
break;
}
RequestBody body = build.add("discount_type", coupon.getDiscount().getType())
.add("discount_amount", coupon.getDiscount().getValue().toPlainString())
.add("discount_percentage", coupon.getDiscount().getPercentage().toPlainString())
.add("expire_type", coupon.getExpire().getType())
.add("expire_limit", Integer.toString(coupon.getExpire().getLimit()))
.add("expire_date", new SimpleDateFormat(API_DATE_FORMAT).format(coupon.getExpire().getDate()))
.add("start_date", new SimpleDateFormat(API_DATE_FORMAT).format(coupon.getStartDate()))
.add("basket_type", coupon.getBasketType())
.add("minimum", coupon.getMinimum().toPlainString())
.add("redeem_limit", Integer.toString(coupon.getUserLimit()))
.add("discount_application_method", Integer.toString(coupon.getDiscountMethod()))
.add("redeem_unlimited", coupon.getRedeemUnlimited()+"")
.add("expire_never", coupon.getExpireNever()+"")
.add("username", coupon.getUsername() == null ? "" : coupon.getUsername())
.add("note", coupon.getNote() == null ? "" : coupon.getNote())
.build();
return createCoupon(body);
}
@POST("/coupons")
public Call<CouponSingleListing> createCoupon(@Body RequestBody body);
@GET("/gift-cards")
public Call<GiftCardListing> getAllGiftCards();
@GET("/gift-cards/{id}")
public Call<GiftCardSingleListing> getGiftCard(@Path("id") int id);
@DELETE("/gift-cards/{id}")
public Call<GiftCardSingleListing> voidGiftCard(@Path("id") int id);
public default Call<GiftCardSingleListing> topUpGiftCard(int id, BigDecimal amount) {
return topUpGiftCard(id, new FormBody.Builder().add("amount", amount.toPlainString()).build());
}
@PUT("/gift-cards/{id}")
public Call<GiftCardSingleListing> topUpGiftCard(@Path("id") int id, @Body RequestBody body);
public default Call<GiftCardSingleListing> createGiftCard(BigDecimal amount, String note) {
return createGiftCard(new FormBody.Builder()
.add("amount", amount.toPlainString())
.add("note", note)
.build());
}
public default Call<GiftCardSingleListing> createGiftCard(GiftCard giftCard) {
return createGiftCard(new FormBody.Builder()
.add("amount", giftCard.getBalance().getStarting().toPlainString())
.add("note", giftCard.getNote())
.build());
}
@POST("/gift-cards")
public Call<GiftCardSingleListing> createGiftCard(@Body RequestBody body);
@POST("/events")
public Call<Void> sendEvents(@Body List<ServerEvent> events);
}
| BuycraftPlugin/BuycraftX | common/src/main/java/net/buycraft/plugin/BuyCraftAPI.java | Java | mit | 9,014 |
'use strict';
var tomasi = require('..');
var fs = require('fs');
var path = require('path');
var join = path.join;
var test = require('tape');
var RELATIVE_PATH = path.relative(process.cwd(), __dirname);
var FIXTURES_DIR = join(RELATIVE_PATH, 'fixtures');
var FIXTURES_ABS_DIR = join(__dirname, 'fixtures');
test('without `$preProcess` or `$views` pipelines', function(t) {
var inPath = join(FIXTURES_DIR, '*.txt');
var config = {
blog: {
$inPath: inPath
}
};
tomasi(config).build(function(err, dataTypes) {
t.false(err);
t.looseEquals(dataTypes.blog, [
{ $inPath: join(FIXTURES_DIR, '1-foo.txt'), $content: 'foo' },
{ $inPath: join(FIXTURES_DIR, '2-bar.txt'), $content: 'bar' },
{ $inPath: join(FIXTURES_DIR, '3-baz.txt'), $content: 'baz' }
]);
t.end();
});
});
test('calls the build `cb` with an `err` if no files match an `$inPath`', function(t) {
var calls = [];
var x = function(cb) {
calls.push(1);
cb();
};
var y = function(cb) {
calls.push(2);
cb();
};
var inPath = join('invalid', '*.txt');
var config = {
blog: {
$inPath: inPath,
$preProcess: [ x ],
$views: {
single: [
[ y ]
]
}
}
};
t.false(fs.existsSync('invalid'));
tomasi(config).build(function(err) {
t.true(err);
t.looseEqual(calls, []);
t.end();
});
});
test('calls plugins in a single `$preProcess` pipeline in series', function(t) {
var calls = [];
var x = function(cb, files, dataTypeName, viewName, dataTypes) {
calls.push(1);
t.equal(arguments.length, 6);
var expectedFiles = [
{ $inPath: join(FIXTURES_DIR, '1-foo.txt'), $content: 'foo' },
{ $inPath: join(FIXTURES_DIR, '2-bar.txt'), $content: 'bar' },
{ $inPath: join(FIXTURES_DIR, '3-baz.txt'), $content: 'baz' }
];
t.deepEqual(files, expectedFiles);
t.equal(dataTypeName, 'blog');
t.equal(viewName, null);
t.deepEqual(dataTypes, {
blog: expectedFiles
});
t.true(files === dataTypes.blog);
cb(null, ['tomasi']);
};
var y = function(cb, files, dataTypeName, viewName, dataTypes) {
calls.push(2);
t.equal(arguments.length, 6);
t.deepEqual(files, ['tomasi']);
t.equal(dataTypeName, 'blog');
t.equal(viewName, null);
t.deepEqual(dataTypes.blog, ['tomasi']);
t.true(files === dataTypes.blog);
cb();
};
var inPath = join(FIXTURES_DIR, '*.txt');
var config = {
blog: {
$inPath: inPath,
$preProcess: [ x, y ]
}
};
tomasi(config).build(function(err) {
t.false(err);
t.looseEquals(calls, [ 1, 2 ]);
t.end();
});
});
test('calls the build `cb` with the `err` if a plugin in a `$preProcess` pipeline has an error', function(t) {
var calls = [];
var x = function(cb) {
calls.push(1);
cb();
};
var y = function(cb) {
calls.push(2);
cb('error');
};
var z = function(cb) {
calls.push(3);
cb();
};
var inPath = join(FIXTURES_DIR, '*.txt');
var config = {
blog: {
$inPath: inPath,
$preProcess: [ x, y, z ]
}
};
tomasi(config).build(function(err) {
t.equal(err, 'error');
t.looseEquals(calls, [ 1, 2 ]);
t.end();
});
});
test('runs parallel `$preProcess` pipelines in parallel', function(t) {
var calls = [];
var x = function(cb) {
calls.push(1);
setTimeout(function() {
calls.push(4);
cb();
}, 10);
};
var y = function(cb) {
calls.push(2);
setTimeout(function() {
calls.push(3);
cb();
}, 0);
};
var inPath = join(FIXTURES_DIR, '*.txt');
var config = {
blog: {
$inPath: inPath,
$preProcess: [ x ]
},
news: {
$inPath: inPath,
$preProcess: [ y ]
}
};
tomasi(config).build(function(err) {
t.false(err);
t.looseEquals(calls, [ 1, 2, 3, 4 ]);
t.end();
});
});
test('calls plugins in a single `$view` pipeline in series', function(t) {
var calls = [];
var x = function(cb, files, dataTypeName, viewName, dataTypes) {
calls.push(1);
t.equal(arguments.length, 6);
var expectedFiles = [
{ $inPath: join(FIXTURES_DIR, '1-foo.txt'), $content: 'foo' },
{ $inPath: join(FIXTURES_DIR, '2-bar.txt'), $content: 'bar' },
{ $inPath: join(FIXTURES_DIR, '3-baz.txt'), $content: 'baz' }
];
t.deepEqual(files, expectedFiles);
t.equal(dataTypeName, 'blog');
t.equal(viewName, 'single');
t.deepEqual(dataTypes, {
blog: {
single: expectedFiles
}
});
t.true(files === dataTypes.blog.single);
cb(null, ['tomasi']);
};
var y = function(cb, files, dataTypeName, viewName, dataTypes) {
calls.push(2);
t.equal(arguments.length, 6);
var expectedFiles = ['tomasi'];
t.deepEquals(files, expectedFiles);
t.equal(dataTypeName, 'blog');
t.equal(viewName, 'single');
t.deepEqual(dataTypes, {
blog: {
single: expectedFiles
}
});
t.true(files === dataTypes.blog.single);
cb();
};
var config = {
blog: {
$inPath: join(FIXTURES_DIR, '*.txt'),
$views: {
single: [
[ x, y ]
]
}
}
};
tomasi(config).build(function(err) {
t.false(err);
t.looseEquals(calls, [ 1, 2 ]);
t.end();
});
});
test('calls the build `cb` with the `err` if a plugin in a `$preProcess` pipeline has an error', function(t) {
var calls = [];
var x = function(cb) {
calls.push(1);
cb();
};
var y = function(cb) {
calls.push(2);
cb('error');
};
var z = function(cb) {
calls.push(3);
cb();
};
var inPath = join(FIXTURES_DIR, '*.txt');
var config = {
blog: {
$inPath: inPath,
$views: {
single: [
[ x, y, z ]
]
}
}
};
tomasi(config).build(function(err) {
t.equal(err, 'error');
t.looseEquals(calls, [ 1, 2 ]);
t.end();
});
});
test('runs consecutive `$view` pipelines in series', function(t) {
var calls = [];
var x = function(cb) {
calls.push(1);
cb(null, ['tomasi']);
};
var y = function(cb, files, dataTypeName, viewName, dataTypes) {
calls.push(2);
t.deepEquals(files, ['tomasi']);
t.deepEquals(dataTypes.blog.single, ['tomasi']);
cb();
};
var inPath = join(FIXTURES_DIR, '*.txt');
var config = {
blog: {
$inPath: inPath,
$views: {
single: [
[ x ],
[ y ]
]
}
}
};
tomasi(config).build(function(err) {
t.false(err);
t.looseEquals(calls, [ 1, 2 ]);
t.end();
});
});
test('runs parallel `$view` pipelines in parallel', function(t) {
t.test('same data type', function() {
var calls = [];
var x = function(cb) {
calls.push(1);
setTimeout(function() {
calls.push(3);
cb();
}, 10);
};
var y = function(cb) {
calls.push(5);
setTimeout(function() {
calls.push(6);
cb();
}, 0);
};
var z = function(cb) {
calls.push(2);
setTimeout(function() {
calls.push(4);
cb();
}, 20);
};
var inPath = join(FIXTURES_DIR, '*.txt');
var config = {
blog: {
$inPath: inPath,
$views: {
single: [
[ x ],
[ y ]
],
archive: [
[ z ]
]
}
}
};
tomasi(config).build(function(err) {
t.false(err);
t.looseEquals(calls, [ 1, 2, 3, 4, 5, 6 ]);
t.end();
});
});
t.test('different data types', function(t) {
var calls = [];
var x = function(cb) {
calls.push(1);
setTimeout(function() {
calls.push(3);
cb();
}, 10);
};
var y = function(cb) {
calls.push(5);
setTimeout(function() {
calls.push(6);
cb();
}, 0);
};
var z = function(cb) {
calls.push(2);
setTimeout(function() {
calls.push(4);
cb();
}, 20);
};
var inPath = join(FIXTURES_DIR, '*.txt');
var config = {
blog: {
$inPath: inPath,
$views: {
single: [
[ x ],
[ y ]
]
}
},
news: {
$inPath: inPath,
$views: {
single: [
[ z ]
]
}
}
};
tomasi(config).build(function(err) {
t.false(err);
t.looseEquals(calls, [ 1, 2, 3, 4, 5, 6 ]);
t.end();
});
});
});
test('uses settings in the specified `config` file', function(t) {
var config = join(FIXTURES_ABS_DIR, 'tomasi.js');
t.true(fs.existsSync(config));
tomasi(config).build(function(err, dataTypes) {
t.false(err);
t.looseEquals(dataTypes.blog, [
{ $inPath: join(FIXTURES_ABS_DIR, '1-foo.txt'), $content: 'foo' },
{ $inPath: join(FIXTURES_ABS_DIR, '2-bar.txt'), $content: 'bar' },
{ $inPath: join(FIXTURES_ABS_DIR, '3-baz.txt'), $content: 'baz' }
]);
t.end();
});
});
test('throws if the specified `config` file does not exist', function(t) {
t.throws(function() {
var config = 'invalid';
t.false(fs.existsSync(config));
tomasi(config);
});
t.end();
});
test('prepends `$dirs.$inDir` to each `$inPath`', function(t) {
var config = {
$dirs: {
$inDir: FIXTURES_ABS_DIR
},
$dataTypes: {
blog: {
$inPath: '*.txt'
}
}
};
tomasi(config).build(function(err, dataTypes) {
t.false(err);
t.looseEquals(dataTypes.blog, [
{ $inPath: join(FIXTURES_ABS_DIR, '1-foo.txt'), $content: 'foo' },
{ $inPath: join(FIXTURES_ABS_DIR, '2-bar.txt'), $content: 'bar' },
{ $inPath: join(FIXTURES_ABS_DIR, '3-baz.txt'), $content: 'baz' }
]);
t.end();
});
});
test('can handle non-utf8 files', function(t) {
var calls = [];
var inPath = join(FIXTURES_DIR, 'heart.png');
var content = fs.readFileSync(inPath);
var expectedFiles = [
{ $inPath: inPath, $content: content }
];
var x = function(cb, files, dataTypeName, viewName, dataTypes) {
calls.push(1);
t.equal(arguments.length, 6);
t.deepEqual(files, expectedFiles);
t.equal(dataTypeName, 'images');
t.equal(viewName, null);
t.deepEqual(dataTypes, {
images: expectedFiles
});
t.equal(files, dataTypes.images);
cb();
};
var y = function(cb, files, dataTypeName, viewName, dataTypes) {
calls.push(2);
t.equal(arguments.length, 6);
t.deepEqual(files, expectedFiles);
t.equal(dataTypeName, 'images');
t.equal(viewName, 'single');
t.deepEqual(dataTypes, {
images: {
single: expectedFiles
}
});
t.equal(files, dataTypes.images.single);
cb();
};
var config = {
images: {
$inPath: join(FIXTURES_DIR, '*.png'),
$preProcess: [ x ],
$views: {
single: [
[ y ]
]
}
}
};
tomasi(config).build(function(err) {
t.false(err);
t.looseEquals(calls, [ 1, 2 ]);
t.end();
});
});
| yuanqing/tomasi | test/build.js | JavaScript | mit | 11,000 |
<?php
namespace spec\IonAuth\IonAuth\Lang;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class LangSpec extends ObjectBehavior
{
function let()
{
$this->beConstructedWith('English');
}
function it_is_initializable()
{
$this->shouldHaveType('IonAuth\IonAuth\Lang\Lang');
}
function it_cannot_read_an_unsupported_language()
{
$this->shouldThrow('\Exception')->during('__construct', array('fakity_fake_fake'));
}
function it_can_register_a_new_language()
{
$this->registerLanguage('BeepBeepBoopBoop', 'path/to/file');
$this->getSupportedLanguages()->shouldContain('Beepbeepboopboop');
}
function it_can_extend_a_language()
{
$this->registerLanguage('Dutch', 'path/to/file');
$languages = $this->getRegisteredLangFiles();
$languages['DUTCH']->shouldBeArray();
$languages['DUTCH']->shouldContain('path/to/file');
}
function it_can_get_a_language_value()
{
$this->get('activateSuccessful')->shouldReturn('Account activated');
}
function it_can_return_active_language()
{
$this->getActiveLanguage()->shouldReturn('English');
}
public function getMatchers()
{
return [
'contain' => function($subject, $key) {
return in_array($key, $subject);
},
];
}
}
| IonAuth/IonAuth | spec/Lang/LangSpec.php | PHP | mit | 1,400 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _15.Neighbour_Wars
{
class NeighbourWars
{
static void Main(string[] args)
{
int peshoDamage = int.Parse(Console.ReadLine());
int goshoDamage = int.Parse(Console.ReadLine());
int peshoHealt = 100;
int goshoHealt = 100;
int count = 0;
do
{
count++;
if (count % 2 == 1)
{
goshoHealt -= peshoDamage;
if (goshoHealt <= 0)
{
break;
}
Console.WriteLine($"Pesho used Roundhouse kick and reduced Gosho to {goshoHealt} health.");
}
else
{
peshoHealt -= goshoDamage;
if (peshoHealt <= 0)
{
break;
}
Console.WriteLine($"Gosho used Thunderous fist and reduced Pesho to {peshoHealt} health.");
}
if (count % 3 == 0)
{
peshoHealt += 10;
goshoHealt += 10;
}
} while (true);
if (peshoHealt > 0)
{
Console.WriteLine($"Pesho won in {count}th round.");
}
else
{
Console.WriteLine($"Gosho won in {count}th round.");
}
}
}
}
| plamenrusanov/Programming-Fundamentals | Conditional Statements and Loops - Exercises/15. Neighbour Wars/NeighbourWars.cs | C# | mit | 1,621 |
from collections import OrderedDict
from conans.paths import SimplePaths
from conans.client.output import Color
from conans.model.ref import ConanFileReference
from conans.model.ref import PackageReference
from conans.client.installer import build_id
import fnmatch
class Printer(object):
""" Print some specific information """
INDENT_COLOR = {0: Color.BRIGHT_CYAN,
1: Color.BRIGHT_RED,
2: Color.BRIGHT_GREEN,
3: Color.BRIGHT_YELLOW,
4: Color.BRIGHT_MAGENTA}
INDENT_SPACES = 4
def __init__(self, out):
self._out = out
def print_graph(self, deps_graph, registry):
""" Simple pretty printing of a deps graph, can be improved
with options, info like licenses, etc
"""
self._out.writeln("Requirements", Color.BRIGHT_YELLOW)
for node in sorted(deps_graph.nodes):
ref, _ = node
if not ref:
continue
remote = registry.get_ref(ref)
from_text = "from local" if not remote else "from %s" % remote.name
self._out.writeln(" %s %s" % (repr(ref), from_text), Color.BRIGHT_CYAN)
self._out.writeln("Packages", Color.BRIGHT_YELLOW)
for node in sorted(deps_graph.nodes):
ref, conanfile = node
if not ref:
continue
ref = PackageReference(ref, conanfile.info.package_id())
self._out.writeln(" %s" % repr(ref), Color.BRIGHT_CYAN)
self._out.writeln("")
def _print_paths(self, ref, conan, path_resolver, show):
if isinstance(ref, ConanFileReference):
if show("export_folder"):
path = path_resolver.export(ref)
self._out.writeln(" export_folder: %s" % path, Color.BRIGHT_GREEN)
if show("source_folder"):
path = path_resolver.source(ref, conan.short_paths)
self._out.writeln(" source_folder: %s" % path, Color.BRIGHT_GREEN)
if show("build_folder") and isinstance(path_resolver, SimplePaths):
# @todo: check if this is correct or if it must always be package_id()
bid = build_id(conan)
if not bid:
bid = conan.info.package_id()
path = path_resolver.build(PackageReference(ref, bid), conan.short_paths)
self._out.writeln(" build_folder: %s" % path, Color.BRIGHT_GREEN)
if show("package_folder") and isinstance(path_resolver, SimplePaths):
id_ = conan.info.package_id()
path = path_resolver.package(PackageReference(ref, id_), conan.short_paths)
self._out.writeln(" package_folder: %s" % path, Color.BRIGHT_GREEN)
def print_info(self, deps_graph, project_reference, _info, registry, graph_updates_info=None,
remote=None, node_times=None, path_resolver=None, package_filter=None,
show_paths=False):
""" Print the dependency information for a conan file
Attributes:
deps_graph: the dependency graph of conan file references to print
placeholder_reference: the conan file reference that represents the conan
file for a project on the path. This may be None,
in which case the project itself will not be part
of the printed dependencies.
remote: Remote specified in install command.
Could be different from the registry one.
"""
if _info is None: # No filter
def show(_):
return True
else:
_info_lower = [s.lower() for s in _info.split(",")]
def show(field):
return field in _info_lower
graph_updates_info = graph_updates_info or {}
for node in sorted(deps_graph.nodes):
ref, conan = node
if not ref:
# ref is only None iff info is being printed for a project directory, and
# not a passed in reference
if project_reference is None:
continue
else:
ref = project_reference
if package_filter and not fnmatch.fnmatch(str(ref), package_filter):
continue
self._out.writeln("%s" % str(ref), Color.BRIGHT_CYAN)
reg_remote = registry.get_ref(ref)
# Excludes PROJECT fake reference
remote_name = remote
if reg_remote and not remote:
remote_name = reg_remote.name
if show("id"):
id_ = conan.info.package_id()
self._out.writeln(" ID: %s" % id_, Color.BRIGHT_GREEN)
if show("build_id"):
bid = build_id(conan)
self._out.writeln(" BuildID: %s" % bid, Color.BRIGHT_GREEN)
if show_paths:
self._print_paths(ref, conan, path_resolver, show)
if isinstance(ref, ConanFileReference) and show("remote"):
if reg_remote:
self._out.writeln(" Remote: %s=%s" % (reg_remote.name, reg_remote.url),
Color.BRIGHT_GREEN)
else:
self._out.writeln(" Remote: None", Color.BRIGHT_GREEN)
url = getattr(conan, "url", None)
license_ = getattr(conan, "license", None)
author = getattr(conan, "author", None)
if url and show("url"):
self._out.writeln(" URL: %s" % url, Color.BRIGHT_GREEN)
if license_ and show("license"):
if isinstance(license_, (list, tuple, set)):
self._out.writeln(" Licenses: %s" % ", ".join(license_), Color.BRIGHT_GREEN)
else:
self._out.writeln(" License: %s" % license_, Color.BRIGHT_GREEN)
if author and show("author"):
self._out.writeln(" Author: %s" % author, Color.BRIGHT_GREEN)
if isinstance(ref, ConanFileReference) and show("update"): # Excludes PROJECT
update = graph_updates_info.get(ref)
update_messages = {
None: ("Version not checked", Color.WHITE),
0: ("You have the latest version (%s)" % remote_name, Color.BRIGHT_GREEN),
1: ("There is a newer version (%s)" % remote_name, Color.BRIGHT_YELLOW),
-1: ("The local file is newer than remote's one (%s)" % remote_name,
Color.BRIGHT_RED)
}
self._out.writeln(" Updates: %s" % update_messages[update][0],
update_messages[update][1])
if node_times and node_times.get(ref, None) and show("date"):
self._out.writeln(" Creation date: %s" % node_times.get(ref, None),
Color.BRIGHT_GREEN)
dependants = deps_graph.inverse_neighbors(node)
if isinstance(ref, ConanFileReference) and show("required"): # Excludes
self._out.writeln(" Required by:", Color.BRIGHT_GREEN)
for d in dependants:
ref = repr(d.conan_ref) if d.conan_ref else project_reference
self._out.writeln(" %s" % ref, Color.BRIGHT_YELLOW)
if show("requires"):
depends = deps_graph.neighbors(node)
if depends:
self._out.writeln(" Requires:", Color.BRIGHT_GREEN)
for d in depends:
self._out.writeln(" %s" % repr(d.conan_ref), Color.BRIGHT_YELLOW)
def print_search_recipes(self, references, pattern):
""" Print all the exported conans information
param pattern: wildcards, e.g., "opencv/*"
"""
if not references:
warn_msg = "There are no packages"
pattern_msg = " matching the %s pattern" % pattern
self._out.info(warn_msg + pattern_msg if pattern else warn_msg)
return
self._out.info("Existing package recipes:\n")
for conan_ref in sorted(references):
self._print_colored_line(str(conan_ref), indent=0)
def print_search_packages(self, packages_props, reference, recipe_hash, packages_query):
if not packages_props:
if packages_query:
warn_msg = "There are no packages for reference '%s' matching the query '%s'" % (str(reference),
packages_query)
else:
warn_msg = "There are no packages for pattern '%s'" % str(reference)
self._out.info(warn_msg)
return
self._out.info("Existing packages for recipe %s:\n" % str(reference))
# Each package
for package_id, properties in sorted(packages_props.items()):
self._print_colored_line("Package_ID", package_id, 1)
for section in ("options", "settings", "full_requires"):
attrs = properties.get(section, [])
if attrs:
section_name = {"full_requires": "requires"}.get(section, section)
self._print_colored_line("[%s]" % section_name, indent=2)
if isinstance(attrs, dict): # options, settings
attrs = OrderedDict(sorted(attrs.items()))
for key, value in attrs.items():
self._print_colored_line(key, value=value, indent=3)
elif isinstance(attrs, list): # full requires
for key in sorted(attrs):
self._print_colored_line(key, indent=3)
package_recipe_hash = properties.get("recipe_hash", None)
# Always compare outdated with local recipe, simplification,
# if a remote check is needed install recipe first
if recipe_hash:
self._print_colored_line("outdated from recipe: %s" % (recipe_hash != package_recipe_hash), indent=2)
self._out.writeln("")
def print_profile(self, name, profile):
self._out.info("Configuration for profile %s:\n" % name)
self._print_profile_section("settings", profile.settings.items())
envs = []
for package, env_vars in profile.env_values.data.items():
for name, value in env_vars.items():
key = "%s:%s" % (package, name) if package else name
envs.append((key, value))
self._print_profile_section("env", envs, separator='=')
scopes = profile.scopes.dumps().splitlines()
self._print_colored_line("[scopes]")
for scope in scopes:
self._print_colored_line(scope, indent=1)
def _print_profile_section(self, name, items, indent=0, separator=": "):
self._print_colored_line("[%s]" % name, indent=indent)
for key, value in items:
self._print_colored_line(key, value=str(value), indent=indent+1, separator=separator)
def _print_colored_line(self, text, value=None, indent=0, separator=": "):
""" Print a colored line depending on its indentation level
Attributes:
text: string line
split_symbol: if you want an output with different in-line colors
indent_plus: integer to add a plus indentation
"""
text = text.strip()
if not text:
return
text_color = Printer.INDENT_COLOR.get(indent, Color.BRIGHT_WHITE)
indent_text = ' ' * Printer.INDENT_SPACES * indent
if value is not None:
value_color = Color.BRIGHT_WHITE
self._out.write('%s%s%s' % (indent_text, text, separator), text_color)
self._out.writeln(value, value_color)
else:
self._out.writeln('%s%s' % (indent_text, text), text_color)
| mropert/conan | conans/client/printer.py | Python | mit | 12,165 |
<?php
/**
* @author Boris Guéry <guery.b@gmail.com>
*/
namespace Bgy\EventStore\Transport;
interface Transport {}
| fedir/EventStoreForPHP | src/Bgy/EventStore/Transport/Transport.php | PHP | mit | 119 |
/*
This script generates mock data for local development.
This way you don't have to point to an actual API,
but you can enjoy realistic, but randomized data,
and rapid page loads due to local, static data.
*/
/* eslint-disable no-console */
import jsf from 'json-schema-faker';
import {schema} from './mockDataSchema';
import fs from 'fs';
import chalk from 'chalk';
const json = JSON.stringify(jsf.resolve(schema));
fs.writeFile("./src/api/db.json", json, function(err) {
if (err) {
console.log(chalk.red(err));
} else {
console.log(chalk.green("Mock data generated."));
}
});
| davefud/js-dev-env | buildScripts/generateMockData.js | JavaScript | mit | 604 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MathML
{
public abstract class MathMLElement : IMathMLNode
{
[MathMLAttributeName("id")]
[MathMLAttributeOrderIndex(1)]
[DefaultValue("")]
public string Id { get; set; }
[MathMLAttributeName("class")]
[MathMLAttributeOrderIndex(2)]
[DefaultValue("")]
public string StyleClass { get; set; }
[MathMLAttributeName("style")]
[MathMLAttributeOrderIndex(3)]
[DefaultValue("")]
public string Style { get; set; }
[MathMLAttributeName("href")]
[MathMLAttributeOrderIndex(4)]
[DefaultValue("")]
public string HRef { get; set; }
[MathMLAttributeName("mathbackground")]
[MathMLAttributeOrderIndex(5)]
public MathMLColor MathBackgroundColor { get; set; }
[MathMLAttributeName("mathcolor")]
[MathMLAttributeOrderIndex(6)]
public MathMLColor MathColor { get; set; }
public IMathMLNode Parent { get; set; }
public IList<IMathMLNode> Children { get; set; }
public MathMLElement()
{
Id = "";
StyleClass = "";
Style = "";
HRef = "";
Parent = null;
Children = new List<IMathMLNode>();
}
}
}
| BenjaminTMilnes/MathML | MathML/MathMLElement.cs | C# | mit | 1,408 |
import { NgModule } from '@angular/core';
import { SharedModule } from '../shared/shared.module';
import { NgBusyModule } from 'ng-busy';
import { SurvivalRoutingModule } from './survival-routing.module';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';
import { HotkeyModule } from 'angular2-hotkeys';
import { NgxDatatableModule } from '@swimlane/ngx-datatable';
import { SurvivalFormComponent } from './survival-form.component';
import { SurvivalSummaryComponent } from './survival-summary.component';
import { SurvivalSummaryTableComponent } from './survival-summary-table.component';
import { SurvivalReportComponent } from './survival-report.component';
import { SurvivalProbabilityComponent } from './survival-probability.component';
import { SurvivalChanceComponent } from './survival-chance.component';
import { LifeTableService } from '../shared/life-table/life-table.service';
import { SurvivalService } from './survival.service';
import { ApiService } from '../shared/services/api.service';
@NgModule({
imports: [
CommonModule,
HotkeyModule,
FormsModule,
ReactiveFormsModule,
NgxDatatableModule,
SharedModule,
NgBusyModule,
SurvivalRoutingModule
],
declarations: [
SurvivalFormComponent,
SurvivalSummaryComponent,
SurvivalSummaryTableComponent,
SurvivalReportComponent,
SurvivalProbabilityComponent,
SurvivalChanceComponent,
],
providers: [
LifeTableService,
SurvivalService,
ApiService
]
})
export class SurvivalModule { }
| brevinL/longevity-visualizer-front-end | src/app/survival/survival.module.ts | TypeScript | mit | 1,553 |
package fi.csc.chipster.sessionworker;
public class SupportRequest {
private String message;
private String mail;
private String session;
private String app;
private String log;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getMail() {
return mail;
}
public void setMail(String email) {
this.mail = email;
}
public String getSession() {
return session;
}
public void setSession(String session) {
this.session = session;
}
public String getApp() {
return app;
}
public void setApp(String app) {
this.app = app;
}
public String getLog() {
return log;
}
public void setLog(String log) {
this.log = log;
}
}
| chipster/chipster-web-server | src/main/java/fi/csc/chipster/sessionworker/SupportRequest.java | Java | mit | 748 |
using System;
namespace RecurringInterval
{
public abstract class Interval
{
protected Interval(Period period)
{
Period = period;
}
public int TotalDays => (int)EndDate.Subtract(StartDate).TotalDays + 1;
public DateTime StartDate { get; protected set; }
public DateTime EndDate { get; protected set; }
public Period Period { get; }
static readonly IntervalFactory factory = new IntervalFactory();
public static Interval Create(Period period, DateTime startDate, DateTime? firstStartDate = null)
{
return factory.CreateFromStartDate(period, startDate, firstStartDate);
}
public abstract Interval Next();
}
} | ribbles/RecurringInterval | RecurringInterval/Interval.cs | C# | mit | 786 |
/* global describe,it */
var getSlug = require('../lib/speakingurl');
describe('getSlug symbols', function () {
'use strict';
it('should convert symbols', function (done) {
getSlug('Foo & Bar | Baz')
.should.eql('foo-and-bar-or-baz');
getSlug('Foo & Bar | Baz', {
lang: 'cs'
})
.should.eql('foo-a-bar-nebo-baz');
getSlug('Foo & Bar | Baz', {
lang: 'en'
})
.should.eql('foo-and-bar-or-baz');
getSlug('Foo & Bar | Baz', {
lang: 'de'
})
.should.eql('foo-und-bar-oder-baz');
getSlug('Foo & Bar | Baz', {
lang: 'fr'
})
.should.eql('foo-et-bar-ou-baz');
getSlug('Foo & Bar | Baz', {
lang: 'es'
})
.should.eql('foo-y-bar-u-baz');
getSlug('Foo & Bar | Baz', {
lang: 'ru'
})
.should.eql('foo-i-bar-ili-baz');
getSlug('Foo & Bar | Baz', {
lang: 'ro'
})
.should.eql('foo-si-bar-sau-baz');
getSlug('Foo & Bar | Baz', {
lang: 'sk'
})
.should.eql('foo-a-bar-alebo-baz');
done();
});
it('shouldn\'t convert symbols', function (done) {
getSlug('Foo & Bar | Baz', {
symbols: false
})
.should.eql('foo-bar-baz');
getSlug('Foo & Bar | Baz', {
lang: 'en',
symbols: false
})
.should.eql('foo-bar-baz');
getSlug('Foo & Bar | Baz', {
lang: 'de',
symbols: false
})
.should.eql('foo-bar-baz');
getSlug('Foo & Bar | Baz', {
lang: 'fr',
symbols: false
})
.should.eql('foo-bar-baz');
getSlug('Foo & Bar | Baz', {
lang: 'es',
symbols: false
})
.should.eql('foo-bar-baz');
getSlug('Foo & Bar | Baz', {
lang: 'ru',
symbols: false
})
.should.eql('foo-bar-baz');
getSlug('Foo & Bar | Baz', {
lang: 'cs',
symbols: false
})
.should.eql('foo-bar-baz');
getSlug('Foo & Bar | Baz', {
lang: 'sk',
symbols: false
})
.should.eql('foo-bar-baz');
done();
});
it('should not convert symbols with uric flag true', function (done) {
getSlug('Foo & Bar | Baz', {
uric: true
})
.should.eql('foo-&-bar-or-baz');
getSlug('Foo & Bar | Baz', {
lang: 'en',
uric: true
})
.should.eql('foo-&-bar-or-baz');
getSlug('Foo & Bar | Baz', {
lang: 'de',
uric: true
})
.should.eql('foo-&-bar-oder-baz');
getSlug('Foo & Bar | Baz', {
lang: 'fr',
uric: true
})
.should.eql('foo-&-bar-ou-baz');
getSlug('Foo & Bar | Baz', {
lang: 'es',
uric: true
})
.should.eql('foo-&-bar-u-baz');
getSlug('Foo & Bar | Baz', {
lang: 'ru',
uric: true
})
.should.eql('foo-&-bar-ili-baz');
getSlug('Foo & Bar | Baz', {
lang: 'cs',
uric: true
})
.should.eql('foo-&-bar-nebo-baz');
getSlug('Foo & Bar | Baz', {
lang: 'sk',
uric: true
})
.should.eql('foo-&-bar-alebo-baz');
done();
});
it('should not convert symbols with uricNoSlash flag true', function (done) {
getSlug('Foo & Bar | Baz', {
uricNoSlash: true
})
.should.eql('foo-&-bar-or-baz');
getSlug('Foo & Bar | Baz', {
lang: 'en',
uricNoSlash: true
})
.should.eql('foo-&-bar-or-baz');
getSlug('Foo & Bar | Baz', {
lang: 'de',
uricNoSlash: true
})
.should.eql('foo-&-bar-oder-baz');
getSlug('Foo & Bar | Baz', {
lang: 'fr',
uricNoSlash: true
})
.should.eql('foo-&-bar-ou-baz');
getSlug('Foo & Bar | Baz', {
lang: 'es',
uricNoSlash: true
})
.should.eql('foo-&-bar-u-baz');
getSlug('Foo & Bar | Baz', {
lang: 'ru',
uricNoSlash: true
})
.should.eql('foo-&-bar-ili-baz');
getSlug('Foo & Bar | Baz', {
lang: 'cs',
uricNoSlash: true
})
.should.eql('foo-&-bar-nebo-baz');
getSlug('Foo & Bar | Baz', {
lang: 'sk',
uricNoSlash: true
})
.should.eql('foo-&-bar-alebo-baz');
done();
});
it('should not convert symbols with mark flag true', function (done) {
getSlug('Foo (Bar) . Baz', {
mark: true
})
.should.eql('foo-(bar)-.-baz');
getSlug('Foo (Bar) . Baz', {
lang: 'en',
mark: true
})
.should.eql('foo-(bar)-.-baz');
getSlug('Foo (Bar) . Baz', {
lang: 'de',
mark: true
})
.should.eql('foo-(bar)-.-baz');
getSlug('Foo (Bar) . Baz', {
lang: 'fr',
mark: true
})
.should.eql('foo-(bar)-.-baz');
getSlug('Foo (Bar) . Baz', {
lang: 'es',
mark: true
})
.should.eql('foo-(bar)-.-baz');
getSlug('Foo (Bar) . Baz', {
lang: 'ru',
mark: true
})
.should.eql('foo-(bar)-.-baz');
getSlug('Foo (Bar) . Baz', {
lang: 'cs',
mark: true
})
.should.eql('foo-(bar)-.-baz');
getSlug('Foo (Bar) . Baz', {
lang: 'sk',
mark: true
})
.should.eql('foo-(bar)-.-baz');
done();
});
it('should convert symbols with flags true', function (done) {
getSlug('Foo (♥) ; Baz=Bar', {
lang: 'en',
uric: true,
uricNoSlash: true,
mark: true
})
.should.eql('foo-(love)-;-baz=bar');
getSlug('Foo (♥) ; Baz=Bar', {
lang: 'de',
uric: true,
uricNoSlash: true,
mark: true
})
.should.eql('foo-(liebe)-;-baz=bar');
getSlug('Foo (♥) ; Baz=Bar', {
lang: 'fr',
uric: true,
uricNoSlash: true,
mark: true
})
.should.eql('foo-(amour)-;-baz=bar');
getSlug('Foo (♥) ; Baz=Bar', {
lang: 'es',
uric: true,
uricNoSlash: true,
mark: true
})
.should.eql('foo-(amor)-;-baz=bar');
getSlug('Foo (♥) ; Baz=Bar', {
lang: 'ru',
uric: true,
uricNoSlash: true,
mark: true
})
.should.eql('foo-(lubov)-;-baz=bar');
getSlug('Foo (♥) ; Baz=Bar', {
lang: 'cs',
uric: true,
uricNoSlash: true,
mark: true
})
.should.eql('foo-(laska)-;-baz=bar');
getSlug('Foo (♥) ; Baz=Bar', {
lang: 'sk',
uric: true,
uricNoSlash: true,
mark: true
})
.should.eql('foo-(laska)-;-baz=bar');
getSlug(' Sch(* )ner (♥)Ti♥tel ♥läßt grüßen!? Bel♥♥ été !', {
lang: 'en',
uric: true,
uricNoSlash: true,
mark: true,
maintainCase: true
})
.should.eql(
'Sch(*-)ner-(love)Ti-love-tel-love-laesst-gruessen!?-Bel-love-love-ete-!'
);
done();
});
it('should replace symbols (de)', function (done) {
getSlug('Äpfel & Birnen', {
lang: 'de'
})
.should.eql('aepfel-und-birnen');
getSlug('ÄÖÜäöüß', {
lang: 'de',
maintainCase: true
})
.should.eql('AeOeUeaeoeuess');
done();
});
it('should replace chars by cs language standards', function (done) {
getSlug(
'AaÁáBbCcČčDdĎďEeÉéĚěFfGgHhChchIiÍíJjKkLlMmNnŇňOoÓóPpQqRrŘřSsŠšTtŤťUuÚúŮůVvWwXxYyÝýZzŽž', {
lang: 'cs'
})
.should.eql(
'aaaabbccccddddeeeeeeffgghhchchiiiijjkkllmmnnnnooooppqqrrrrssssttttuuuuuuvvwwxxyyyyzzzz'
);
getSlug(
'AaÁáBbCcČčDdĎďEeÉéĚěFfGgHhChchIiÍíJjKkLlMmNnŇňOoÓóPpQqRrŘřSsŠšTtŤťUuÚúŮůVvWwXxYyÝýZzŽž', {
lang: 'cs',
maintainCase: true
})
.should.eql(
'AaAaBbCcCcDdDdEeEeEeFfGgHhChchIiIiJjKkLlMmNnNnOoOoPpQqRrRrSsSsTtTtUuUuUuVvWwXxYyYyZzZz'
);
done();
});
it('should replace chars by fi language standards', function (done) {
getSlug(
'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZzÅåÄäÖö', {
lang: 'fi',
maintainCase: true
})
.should.eql(
'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZzAaAaOo'
);
done();
});
it('should replace chars by sk language standards', function (done) {
getSlug(
'AaÁaÄäBbCcČčDdĎďDzdzDždžEeÉéFfGgHhChchIiÍíJjKkLlĹ弾MmNnŇňOoÓóÔôPpQqRrŔŕSsŠšTtŤťUuÚúVvWwXxYyÝýZzŽž', {
lang: 'sk'
})
.should.eql(
'aaaaaabbccccdddddzdzdzdzeeeeffgghhchchiiiijjkkllllllmmnnnnooooooppqqrrrrssssttttuuuuvvwwxxyyyyzzzz'
);
getSlug(
'AaÁaÄäBbCcČčDdĎďDzdzDždžEeÉéFfGgHhChchIiÍíJjKkLlĹ弾MmNnŇňOoÓóÔôPpQqRrŔŕSsŠšTtŤťUuÚúVvWwXxYyÝýZzŽž', {
lang: 'sk',
maintainCase: true
})
.should.eql(
'AaAaAaBbCcCcDdDdDzdzDzdzEeEeFfGgHhChchIiIiJjKkLlLlLlMmNnNnOoOoOoPpQqRrRrSsSsTtTtUuUuVvWwXxYyYyZzZz'
);
done();
});
it('should ignore not available language param', function (done) {
getSlug('Äpfel & Birnen', {
lang: 'xx'
})
.should.eql('aepfel-and-birnen');
done();
});
it('should convert currency symbols to lowercase', function (done) {
getSlug('NEXUS4 only €199!', {
maintainCase: false
})
.should.eql('nexus4-only-eur199');
getSlug('NEXUS4 only €299.93', {
maintainCase: false
})
.should.eql('nexus4-only-eur299-93');
getSlug('NEXUS4 only 円399.73', {
maintainCase: false
})
.should.eql('nexus4-only-yen399-73');
done();
});
it('should convert currency symbols to uppercase', function (done) {
getSlug('NEXUS4 only €199!', {
maintainCase: true
})
.should.eql('NEXUS4-only-EUR199');
getSlug('NEXUS4 only €299.93', {
maintainCase: true
})
.should.eql('NEXUS4-only-EUR299-93');
getSlug('NEXUS4 only 円399.73', {
maintainCase: true
})
.should.eql('NEXUS4-only-YEN399-73');
done();
});
}); | jotamaggi/react-calendar-app | node_modules/speakingurl/test/test-lang.js | JavaScript | mit | 12,387 |
#include "SoundSource.hpp"
#include "../Entity/Entity.hpp"
#include "../Hymn.hpp"
#include "../Audio/SoundFile.hpp"
#include "../Audio/SoundBuffer.hpp"
#include "../Manager/Managers.hpp"
#include "../Manager/ResourceManager.hpp"
using namespace Component;
SoundSource::SoundSource() {
alGenSources(1, &source);
soundBuffer = new Audio::SoundBuffer();
}
SoundSource::~SoundSource() {
alDeleteSources(1, &source);
Audio::SoundFile* soundFile = soundBuffer->GetSoundFile();
if (soundFile)
Managers().resourceManager->FreeSound(soundFile);
delete soundBuffer;
}
Json::Value SoundSource::Save() const {
Json::Value component;
Audio::SoundFile* soundFile = soundBuffer->GetSoundFile();
if (soundFile)
component["sound"] = soundFile->path + soundFile->name;
component["pitch"] = pitch;
component["gain"] = gain;
component["loop"] = loop;
return component;
}
void SoundSource::Play() {
shouldPlay = true;
}
void SoundSource::Pause() {
shouldPause = true;
}
void SoundSource::Stop() {
shouldStop = true;
}
| Chainsawkitten/HymnToBeauty | src/Engine/Component/SoundSource.cpp | C++ | mit | 1,089 |
/*global module:false*/
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
// Metadata.
pkg: grunt.file.readJSON('package.json'),
banner: '/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - ' +
'<%= grunt.template.today("yyyy-mm-dd") %>\n' +
'<%= pkg.homepage ? "* " + pkg.homepage + "\\n" : "" %>' +
'* Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>;' +
' Licensed <%= _.pluck(pkg.licenses, "type").join(", ") %> */\n',
// Task configuration.
watch: {
compass: {
files: ['app/styles/{,*/}*.{scss,sass}'],
tasks: ['compass:server']
}
},
open: {
server: {
path: 'http://localhost:<%= connect.options.port %>'
}
},
clean: {
dist: {
files: [{
dot: true,
src: [
'.tmp',
'dist/*',
'!dist/.git*'
]
}]
},
server: '.tmp'
},
compass: {
options: {
sassDir: 'app/styles',
cssDir: 'app/styles',
generatedImagesDir: '.tmp/images/generated',
imagesDir: 'app/images',
javascriptsDir: 'app/scripts',
fontsDir: 'app/styles/fonts',
importPath: 'app/bower_components',
httpImagesPath: '/images',
httpGeneratedImagesPath: '/images/generated',
httpFontsPath: '/styles/fonts',
relativeAssets: false
},
dist: {},
server: {
options: {
debugInfo: false
}
}
},
});
// These plugins provide necessary tasks.
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-compass');
grunt.registerTask('server', function (target) {
if (target === 'dist') {
return grunt.task.run(['build', 'open', 'connect:dist:keepalive']);
}
grunt.task.run([
'clean:server',
'concurrent:server',
'connect:livereload',
'open',
'watch'
]);
});
// Default task.
grunt.registerTask('default', ['watch']);
};
| jussiip/wamefork | Gruntfile.js | JavaScript | mit | 2,290 |
/**
* Using Rails-like standard naming convention for endpoints.
* GET /things -> index
* POST /things -> create
* GET /things/:id -> show
* PUT /things/:id -> update
* DELETE /things/:id -> destroy
*/
import {notFound, invalidData} from './errors';
import awaitify from 'awaitify';
import _ from 'lodash';
import {loadGroupUsers} from './api-utils';
import UserGroup from './models/user-group.model';
import User from './models/user.model';
export const index = awaitify(function *(req, res, next) {
try {
const userGroups = yield UserGroup.find({}).exec();
res.status(200).json(userGroups);
} catch (err) {
return next(err);
}
});
export const show = awaitify(function *(req, res, next) {
try {
const {params:{id}} = req;
const userGroup = yield UserGroup.findById(id).exec();
if (!userGroup) {
return notFound(req, res);
}
res.status(200).json(userGroup);
} catch (err) {
return next(err);
}
});
export const create = awaitify(function *(req, res, next) {
try {
const {body:{name}} = req;
if (!name) {
return invalidData(req, res);
}
let userGroup = new UserGroup();
userGroup.name = name;
userGroup.users = [];
const result = yield userGroup.save();
res.status(200).json(result);
} catch (err) {
return next(err);
}
});
export const update = awaitify(function *(req, res, next) {
try {
const {body:{name}, params:{id}} = req;
if (!name || !id) {
return invalidData(req, res);
}
const userGroup = yield UserGroup.findById(id).exec();
if (!userGroup) {
return notFound(req, res);
}
userGroup.name = name;
const result = yield userGroup.save().exec();
res.status(200).json(result);
} catch (err) {
return next(err);
}
});
export const users = awaitify(function *(req, res, next) {
try {
const {params:{name}} = req;
if (!name) {
return invalidData(req, res);
}
const result = yield loadGroupUsers(name);
if (!result) {
return notFound(req, res);
}
res.status(200).json(result);
} catch (err) {
return next(err);
}
});
export const assignUsersToGroup = awaitify(function *(req, res, next) {
try {
const {body, params:{name}} = req;
if (!name || !_.isArray(body)) {
return invalidData(req, res);
}
const userGroup = yield UserGroup.findOne({name}).exec();
if (!userGroup) {
return notFound(req, res);
}
userGroup.users = _.uniq(userGroup.users.concat(body));
userGroup.markModified('users');
const result = yield userGroup.save();
res.status(200).json(result);
} catch (err) {
return next(err);
}
});
export const unassignUsersFromGroup = awaitify(function *(req, res, next) {
try {
const {body, params:{name}} = req;
if (!name || !_.isArray(body)) {
return invalidData(req, res);
}
const userGroup = yield UserGroup.findOne({name}).exec();
if (!userGroup) {
return notFound(req, res);
}
_.remove(userGroup.users, id => _.includes(body, String(id)));
userGroup.markModified('users');
const result = yield userGroup.save();
res.status(200).json(result);
} catch (err) {
return next(err);
}
});
export const destroy = awaitify(function *(req, res, next) {
try {
const userGroup = yield UserGroup.findById(req.params.id).exec();
if (!userGroup || userGroup.users.length) {
return invalidData(req, res);
}
const result = yield UserGroup.findByIdAndRemove(req.params.id).exec();
res.status(200).json(result);
} catch (err) {
return next(err);
}
});
| fixjs/user-management-app | src/apis/user-group.api.js | JavaScript | mit | 3,703 |
<?php
namespace Korsmakolnikov\InternalBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Class DependencyFactory
* @package Korsmakolnikov\InternalBundle\DependencyInjection
*/
class DependencyFactory implements ContainerAwareInterface
{
/**
* @var ContainerInterface
*/
protected $container;
/**
* DependencyFactory constructor.
* @param ContainerInterface $container
*/
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
/**
* Sets the container.
*
* @param ContainerInterface|null $container
*/
public function setContainer(ContainerInterface $container = null)
{
$this->container = $container;
}
/**
* @param array|string $serviceName
* @return DependencyMasterDecorator
*/
public function create($serviceName)
{
if(is_array($serviceName)) {
$dependencyDecorator = $wrap = null;
foreach ($serviceName as $s) {
$dependencyDecorator = $this->decorate($dependencyDecorator, $s);
}
return $dependencyDecorator;
}
$dependencyDecorator = $this->createDecorator($serviceName);
return $dependencyDecorator;
}
/**
* @param DependencyMasterDecorator|null $host
* @param $service
* @return DependencyMasterDecorator
*/
private function decorate(DependencyMasterDecorator $host = null, $service)
{
if($service && $host) {
$tmp = $host;
$host = $this->createDecorator($service);
$host->wrap($tmp);
return $host;
}
return $this->createDecorator($service);
}
/**
* @param $serviceName
* @return DependencyMasterDecorator
*/
private function createDecorator($serviceName)
{
$dependencyDecorator = new DependencyMasterDecorator($serviceName);
$dependencyDecorator->setService($this->container->get($serviceName));
return $dependencyDecorator;
}
} | korsmakolnikov/InternalBundle | DependencyInjection/DependencyFactory.php | PHP | mit | 2,196 |
var express = require('express');
var app = express();
var uid = require('uid');
var databaseUrl = 'mongodb://dev:angular@ds047107.mongolab.com:47107/getitrightdev';
var collections = ['active_users'];
var db = require('mongojs').connect(databaseUrl, collections);
app.use(express.static('public'));
app.use(express.json());
//Getting Data
app.get('/api/active-users', function(req, res) {
var now = new Date().valueOf(),
criteria = new Date(now - 5 * 60 * 60000);
db.active_users.find({'last_updated': {'$gte': criteria}}).toArray(function(err, results) {
res.send(results.map(function(item, i) {
return {long: item.coords.long, lat: item.coords.lat};
}));
});
});
//Storing DATA
app.post('/api/heartbeat', function(req, res) {
var data = {
id: req.body.id,
coords: {
long: req.query.long,
lat: req.query.lat
},
last_updated: new Date()
};
console.log(data.id);
if (data.id) {
db.active_users.update({id: data.id}, data, callback);
} else {
data.id = uid();
db.active_users.save(data, callback);
}
function callback(err, saved) {
if (err || !saved) {
res.send('Couldnt proceed');
} else {
res.send(data.id);
}
}
});
var server = app.listen(3030, function() {
console.log('Listening on port %d', server.address().port);
});
| getitrightio/getitright-server | app/server.js | JavaScript | mit | 1,356 |
<?php
namespace Veta\HomeworkBundle\Controller;
use RedCode\TreeBundle\Controller\TreeAdminController;
class CategoryAdminController extends TreeAdminController
{
}
| eltrubetskaya/blog | src/Veta/HomeworkBundle/Controller/CategoryAdminController.php | PHP | mit | 168 |
// 74: String - `endsWith()`
// To do: make all tests pass, leave the assert lines unchanged!
var assert = require("assert");
describe('`str.endsWith(searchString)` determines whether `str` ends with `searchString`.', function() {
const s = 'el fin';
describe('1st parameter, the string to search for', function() {
it('works with just a character', function() {
const doesEndWith = s.endsWith('n');
assert.equal(doesEndWith, true);
});
it('works with a string', function() {
const expected = true;
assert.equal(s.endsWith('fin'), expected);
});
it('works with unicode characters', function() {
const nuclear = '☢';
assert.equal(nuclear.endsWith('☢'), true);
});
it('a regular expression throws a TypeError', function() {
const aRegExp = /the/;
assert.throws(() => {''.endsWith(aRegExp)}, TypeError);
});
});
describe('2nd parameter, searches within this string as if this string were only this long', function() {
it('find "el" at a substring of the length 2', function() {
const endPos = 2;
assert.equal(s.endsWith('el', endPos), true);
});
it('`undefined` uses the entire string', function() {
const _undefined_ = undefined;
assert.equal(s.endsWith('fin', _undefined_), true);
});
it('the parameter gets coerced to an int', function() {
const position = '5';
assert.equal(s.endsWith('fi', position), true);
});
describe('value less than 0', function() {
it('returns `true`, when searching for an empty string', function() {
const emptyString = '';
assert.equal('1'.endsWith(emptyString, -1), true);
});
it('return `false`, when searching for a non-empty string', function() {
const notEmpty = '??';
assert.equal('1'.endsWith(notEmpty, -1), false);
});
});
});
describe('transfer the functionality to other objects', function() {
const endsWith = (...args) => String.prototype.endsWith.call(...args);
it('e.g. a boolean', function() {
let aBool = true;
assert.equal(endsWith(!aBool, 'lse'), true);
});
it('e.g. a number', function() {
let aNumber = 84;
assert.equal(endsWith(aNumber + 1900, 84), true);
});
it('also using the position works', function() {
const position = 3;
assert.equal(endsWith(1994, '99', position), true);
});
});
});
| jostw/es6-katas | tests/74-string-ends-with.js | JavaScript | mit | 2,438 |
# frozen_string_literal: true
require 'spec_helper'
module Steam
module Networking
describe Packet do
it 'requies a tcp body' do
expect do
Packet.new(nil)
end.to raise_error(RuntimeError)
expect do
Packet.new('')
end.to raise_error(RuntimeError)
end
it 'has a TCP identifier' do
expect(Packet::TCP_MAGIC).to eq('VT01')
end
describe 'valid packet object' do
before do
# size and random junk of size
identifier = 123
tcp = [identifier].pack('l')
@packet = Packet.new(tcp)
end
it 'can encode to a valve packet' do
expect(@packet.encode).to eq("\x04\x00\x00\x00VT01{\x00\x00\x00")
end
it 'encapsulates a raw tcp body' do
expect(@packet.body).to eq("{\x00\x00\x00")
end
it 'has a message type' do
expect(@packet.msg_type).to eq(123)
expect(@packet.emsg).to eq(@packet.msg_type)
end
it 'is not multi' do
expect(@packet.multi?).to eq(false)
end
it 'can decodes protobuf client messages' do
msg = ProtobufMessage.new(MsgHdrProtoBuf.new,
Steamclient::CMsgClientLoggedOff.new,
EMsg::CLIENT_LOG_OFF)
tcp = msg.encode
@packet = Packet.new(tcp)
msg = @packet.as_message(Steamclient::CMsgClientLogOff.new)
expect(msg.header).to be_a(MsgHdrProtoBuf)
expect(msg.body).to be_a(Steamclient::CMsgClientLogOff)
end
it 'can decodes client messages' do
msg = ClientMessage.new(MsgHdr.new,
MsgChannelEncryptResponse.new,
EMsg::CHANNEL_ENCRYPT_RESPONSE)
tcp = msg.encode
@packet = Packet.new(tcp)
msg = @packet.as_message(MsgChannelEncryptResponse.new)
expect(msg.header).to be_a(MsgHdr)
expect(msg.body).to be_a(MsgChannelEncryptResponse)
expect(msg.emsg).to eq(EMsg::CHANNEL_ENCRYPT_RESPONSE)
end
end
describe 'a multi packet object' do
before do
# size and random junk of size
identifier = EMsg::MULTI
tcp = [identifier].pack('l')
@packet = Packet.new(tcp)
end
it 'has a truthy multi? flag' do
expect(@packet.multi?).to eq(true)
end
end
end
end
end
| fastpeek/steam | spec/steam/networking/packet_spec.rb | Ruby | mit | 2,516 |
require 'spec_helper'
describe AridCache do
describe 'results' do
before :each do
Company.destroy_all
@company1 = Company.make(:name => 'a')
@company2 = Company.make(:name => 'b')
Company.class_caches do
ordered_by_name { Company.all(:order => 'name ASC') }
end
Company.clear_caches
end
it "order should match the original order" do
3.times do |t|
results = Company.cached_ordered_by_name
results.size.should == 2
results[0].name.should == @company1.name
results[1].name.should == @company2.name
end
end
it "order should match the order option" do
3.times do |t|
results = Company.cached_ordered_by_name(:order => 'name DESC')
results.size.should == 2
results[0].name.should == @company2.name
results[1].name.should == @company1.name
end
end
it "with order option should go to the database to order" do
lambda {
Company.cached_ordered_by_name(:order => 'name DESC').inspect
}.should query(2)
end
it "should apply limit *before* going to the database when the result is cached and no order is specified" do
Company.cached_ordered_by_name
id = @company1.id
lambda {
Company.cached_ordered_by_name(:limit => 1).inspect
}.should query("SELECT \"companies\".* FROM \"companies\" WHERE (\"companies\".id in (#{id})) ORDER BY CASE WHEN \"companies\".id=#{id} THEN 1 END LIMIT 1")
end
it "should apply limit after going to the database when an order is specified" do
Company.cached_ordered_by_name
lambda {
Company.cached_ordered_by_name(:limit => 1, :order => 'name DESC').inspect
}.should query("SELECT \"companies\".* FROM \"companies\" WHERE (\"companies\".id in (#{@company1.id},#{@company2.id})) ORDER BY name DESC LIMIT 1")
end
it "should order in memory when enabled" do
Company.cached_ordered_by_name
with_order_in_memory do
lambda {
Company.cached_ordered_by_name(:limit => 1).inspect
}.should query("SELECT \"companies\".* FROM \"companies\" WHERE (\"companies\".id in (#{@company1.id}))")
end
end
end
it "should set the special raw flag" do
AridCache.raw_with_options.should be_false
AridCache.raw_with_options = true
AridCache.raw_with_options.should be_true
end
describe "pagination" do
before :each do
@user = User.make
@user.companies << Company.make
end
it "should not fail if the page is nil" do
lambda {
@user.cached_companies(:page => nil)
@user.cached_companies(:page => nil) # works when seeding, so call again to load from cache
}.should_not raise_error(WillPaginate::InvalidPage)
end
end
end
| kjvarga/arid_cache | spec/arid_cache/arid_cache_spec.rb | Ruby | mit | 2,815 |
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,n) FOR(i,0,n)
#define dump(x) cerr << #x << " = " << (x) << endl;
int n=16;
int a[16] = {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15};
int dp[100];
int search(int a[], int cur, int edge) {
if (cur > n) return edge;
int cv = a[cur];
if (dp[cv] != 0) {
dp[cv]+=1;
int i=cv+1;
while(dp[i]!=0 && dp[i]<dp[cv]) {
dp[i]=dp[cv];
i+=1;
}
return search(a, cur+1, edge);
}
int v = dp[edge];
FOR(i,edge+1,cv) {
dp[i]=v;
}
dp[cv] = v+1;
return search(a, cur+1, cv);
}
void solve() {
memset(dp, 0, sizeof(dp));
cout << dp[search(a, 0, 0)] << endl;
}
int main(int argc, char const *argv[]) {
solve();
}
| k-ori/algorithm-playground | src/dp/longest-increasing-subsequence/longest-increasing-subsequence-org.cpp | C++ | mit | 823 |
<?php
namespace Pandora\MainBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class PandoraMainBundle extends Bundle
{
}
| Kilo3/pandora | src/Pandora/MainBundle/PandoraMainBundle.php | PHP | mit | 130 |
package io.cucumber.core.backend;
/**
* Marks a glue class as being scenario scoped.
* <p>
* Instances of scenario scoped glue can not be used between scenarios and will
* be removed from the glue. This is useful when the glue holds a reference to a
* scenario scoped object (e.g. a method closure).
*/
public interface ScenarioScoped {
/**
* Disposes of the test execution context.
* <p>
* Scenario scoped step definition may be used in events. Thus retaining a
* potential reference to the test execution context. When many tests are
* used this may result in an over consumption of memory. Disposing of the
* execution context resolves this problem.
*/
default void dispose() {
}
}
| cucumber/cucumber-jvm | core/src/main/java/io/cucumber/core/backend/ScenarioScoped.java | Java | mit | 742 |
var merge = require('merge');
var clone = require('clone');
var Field = require('./field');
var maxCounter = require('../mixins/max-counter');
module.exports = function() {
return merge.recursive(Field(), {
props: {
placeholder: {
type:String,
required:false,
default:''
},
disabled: {
type: Boolean
},
tinymce:{
default: false
},
debounce:{
type:Number,
default:300
},
lazy:{
type:Boolean
},
toggler:{
type:Boolean
},
togglerButton:{
type:Object,
default:function() {
return {
expand:'Expand',
minimize:'Minimize'
}
}
}
},
data: function() {
return {
editor: null,
expanded:false,
fieldType:'textarea',
tagName:'textarea'
}
},
methods:{
toggle: function() {
this.expanded=!this.expanded;
var textarea = $(this.$el).find("textarea");
height = this.expanded?textarea.get(0).scrollHeight:"auto";
textarea.height(height);
this.$dispatch('vue-formular.textarea-was-toggled', {expanded:this.expanded});
}
},
computed:merge(maxCounter, {
togglerText: function() {
return this.expanded?this.togglerButton.minimize:this.togglerButton.expand;
}
}),
ready: function() {
if (this.tinymce===false) return;
var that = this;
var setup = that.tinymce && that.tinymce.hasOwnProperty('setup')?
that.tinymce.setup:
function() {};
var parentSetup = that.getForm().options.tinymceOptions.hasOwnProperty('setup')?
that.getForm().options.tinymceOptions.setup:
function(){};
var options = typeof this.tinymce=='object'?
merge.recursive(clone(this.getForm().options.tinymceOptions), this.tinymce):
this.getForm().options.tinymceOptions;
options = merge.recursive(options, {
selector:'textarea[name=' + this.name +']',
setup : function(ed) {
that.editor = ed;
parentSetup(ed);
setup(ed);
ed.on('change',function(e) {
that.value = ed.getContent();
}.bind(this));
}
});
tinymce.init(options);
this.$watch('value', function(val) {
if(val != tinymce.get("textarea_" + this.name).getContent()) {
tinymce.get("textarea_" + this.name).setContent(val);
}
});
}
});
}
| matfish2/vue-formular | lib/components/fields/textarea.js | JavaScript | mit | 2,395 |
package jnesulator.core.nes.audio;
public class TriangleTimer extends Timer {
private static int periodadd = 1;
private static int[] triangle = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 15, 14, 13, 12, 11, 10, 9,
8, 7, 6, 5, 4, 3, 2, 1, 0 };
private int divider = 0;
public TriangleTimer() {
period = 0;
position = 0;
}
@Override
public void clock() {
if (period == 0) {
return;
}
++divider;
// note: stay away from negative division to avoid rounding problems
int periods = (divider + period + periodadd) / (period + periodadd);
if (periods < 0) {
periods = 0; // can happen if period or periodadd were made smaller
}
position = (position + periods) & 0x1F;
divider -= (period + periodadd) * periods;
}
@Override
public void clock(int cycles) {
if (period == 0) {
return;
}
divider += cycles;
// note: stay away from negative division to avoid rounding problems
int periods = (divider + period + periodadd) / (period + periodadd);
if (periods < 0) {
periods = 0; // can happen if period or periodadd were made smaller
}
position = (position + periods) & 0x1F;
divider -= (period + periodadd) * periods;
}
@Override
public int getval() {
return (period == 0) ? 7 : triangle[position];
// needed to avoid screech when period is zero
}
@Override
public void reset() {
// no way to reset the triangle
}
@Override
public void setduty(int duty) {
throw new UnsupportedOperationException("Triangle counter has no duty setting.");
}
@Override
public void setduty(int[] duty) {
throw new UnsupportedOperationException("Triangle counter has no duty setting.");
}
@Override
public void setperiod(int newperiod) {
period = newperiod;
if (period == 0) {
position = 7;
}
}
} | thomas-kendall/jnesulator | jnesulator-core/src/main/java/jnesulator/core/nes/audio/TriangleTimer.java | Java | mit | 1,785 |
<?php
namespace Ghw\UserBundle\Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;
use FOS\UserBundle\Controller\RegistrationController as BaseController;
class LoginController extends BaseController
{
public function loginAction()
{
$request = $this->container->get('request');
/* @var $request \Symfony\Component\HttpFoundation\Request */
$session = $request->getSession();
/* @var $session \Symfony\Component\HttpFoundation\Session */
// get the error if any (works with forward and redirect -- see below)
if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) {
$error = $request->attributes->get(SecurityContext::AUTHENTICATION_ERROR);
} elseif (null !== $session && $session->has(SecurityContext::AUTHENTICATION_ERROR)) {
$error = $session->get(SecurityContext::AUTHENTICATION_ERROR);
$session->remove(SecurityContext::AUTHENTICATION_ERROR);
} else {
$error = '';
}
if ($error) {
// TODO: this is a potential security risk (see http://trac.symfony-project.org/ticket/9523)
$error = $error->getMessage();
}
// last username entered by the user
$lastUsername = (null === $session) ? '' : $session->get(SecurityContext::LAST_USERNAME);
$csrfToken = $this->container->get('form.csrf_provider')->generateCsrfToken('authenticate');
return $this->renderLogin(array(
'last_username' => $lastUsername,
'error' => $error,
'csrf_token' => $csrfToken,
));
}
} | deuxnids/Wiloma | src/Ghw/UserBundle/Controller/LoginController.php | PHP | mit | 1,652 |
import i18n from 'mi18n'
import Sortable from 'sortablejs'
import h, { indexOfNode } from '../common/helpers'
import dom from '../common/dom'
import { ANIMATION_SPEED_SLOW, ANIMATION_SPEED_FAST } from '../constants'
import { merge } from '../common/utils'
const defaults = Object.freeze({
type: 'field',
displayType: 'slider',
})
const getTransition = val => ({ transform: `translateX(${val ? `${val}px` : 0})` })
/**
* Edit and control sliding panels
*/
export default class Panels {
/**
* Panels initial setup
* @param {Object} options Panels config
* @return {Object} Panels
*/
constructor(options) {
this.opts = merge(defaults, options)
this.panelDisplay = this.opts.displayType
this.activePanelIndex = 0
this.panelNav = this.createPanelNav()
const panelsWrap = this.createPanelsWrap()
this.nav = this.navActions()
const resizeObserver = new window.ResizeObserver(([{ contentRect: { width } }]) => {
if (this.currentWidth !== width) {
this.toggleTabbedLayout()
this.currentWidth = width
this.nav.setTranslateX(this.activePanelIndex, false)
}
})
const observeTimeout = window.setTimeout(() => {
resizeObserver.observe(panelsWrap)
window.clearTimeout(observeTimeout)
}, ANIMATION_SPEED_SLOW)
}
getPanelDisplay() {
const column = this.panelsWrap
const width = parseInt(dom.getStyle(column, 'width'))
const autoDisplayType = width > 390 ? 'tabbed' : 'slider'
const isAuto = this.opts.displayType === 'auto'
this.panelDisplay = isAuto ? autoDisplayType : this.opts.displayType || defaults.displayType
return this.panelDisplay
}
toggleTabbedLayout = () => {
this.getPanelDisplay()
const isTabbed = this.isTabbed
this.panelsWrap.parentElement.classList.toggle('tabbed-panels', isTabbed)
if (isTabbed) {
this.panelNav.removeAttribute('style')
}
return isTabbed
}
/**
* Resize the panel after its contents change in height
* @return {String} panel's height in pixels
*/
resizePanels = () => {
this.toggleTabbedLayout()
const panelStyle = this.panelsWrap.style
const activePanelHeight = dom.getStyle(this.currentPanel, 'height')
panelStyle.height = activePanelHeight
return activePanelHeight
}
/**
* Wrap a panel and make properties sortable
* if the panel belongs to a field
* @return {Object} DOM element
*/
createPanelsWrap() {
const panelsWrap = dom.create({
className: 'panels',
content: this.opts.panels.map(({ config: { label }, ...panel }) => panel),
})
if (this.opts.type === 'field') {
this.sortableProperties(panelsWrap)
}
this.panelsWrap = panelsWrap
this.panels = panelsWrap.children
this.currentPanel = this.panels[this.activePanelIndex]
return panelsWrap
}
/**
* Sortable panel properties
* @param {Array} panels
* @return {Array} panel groups
*/
sortableProperties(panels) {
const _this = this
const groups = panels.getElementsByClassName('field-edit-group')
return h.forEach(groups, (group, index) => {
group.fieldId = _this.opts.id
if (group.isSortable) {
Sortable.create(group, {
animation: 150,
group: {
name: 'edit-' + group.editGroup,
pull: true,
put: ['properties'],
},
sort: true,
handle: '.prop-order',
onSort: evt => {
_this.propertySave(evt.to)
_this.resizePanels()
},
})
}
})
}
createPanelNavLabels() {
const labels = this.opts.panels.map(panel => ({
tag: 'h5',
action: {
click: evt => {
const index = indexOfNode(evt.target, evt.target.parentElement)
this.currentPanel = this.panels[index]
const labels = evt.target.parentElement.childNodes
this.nav.refresh(index)
dom.removeClasses(labels, 'active-tab')
evt.target.classList.add('active-tab')
},
},
content: panel.config.label,
}))
const panelLabels = {
className: 'panel-labels',
content: {
content: labels,
},
}
const [firstLabel] = labels
firstLabel.className = 'active-tab'
return dom.create(panelLabels)
}
/**
* Panel navigation, tabs and arrow buttons for slider
* @return {Object} DOM object for panel navigation wrapper
*/
createPanelNav() {
this.labels = this.createPanelNavLabels()
const next = {
tag: 'button',
attrs: {
className: 'next-group',
title: i18n.get('controlGroups.nextGroup'),
type: 'button',
},
dataset: {
toggle: 'tooltip',
placement: 'top',
},
action: {
click: e => this.nav.nextGroup(e),
},
content: dom.icon('triangle-right'),
}
const prev = {
tag: 'button',
attrs: {
className: 'prev-group',
title: i18n.get('controlGroups.prevGroup'),
type: 'button',
},
dataset: {
toggle: 'tooltip',
placement: 'top',
},
action: {
click: e => this.nav.prevGroup(e),
},
content: dom.icon('triangle-left'),
}
return dom.create({
tag: 'nav',
attrs: {
className: 'panel-nav',
},
content: [prev, this.labels, next],
})
}
get isTabbed() {
return this.panelDisplay === 'tabbed'
}
/**
* Handlers for navigating between panel groups
* @todo refactor to use requestAnimationFrame instead of css transitions
* @return {Object} actions that control panel groups
*/
navActions() {
const action = {}
const groupParent = this.currentPanel.parentElement
const labelWrap = this.labels.firstChild
const siblingGroups = this.currentPanel.parentElement.childNodes
this.activePanelIndex = indexOfNode(this.currentPanel, groupParent)
let offset = { nav: 0, panel: 0 }
let lastOffset = { ...offset }
const groupChange = newIndex => {
const labels = labelWrap.children
dom.removeClasses(siblingGroups, 'active-panel')
dom.removeClasses(labels, 'active-tab')
this.currentPanel = siblingGroups[newIndex]
this.currentPanel.classList.add('active-panel')
labels[newIndex].classList.add('active-tab')
return this.currentPanel
}
const getOffset = index => {
return {
nav: -labelWrap.offsetWidth * index,
panel: -groupParent.offsetWidth * index,
}
}
const translateX = ({ offset, reset, duration = ANIMATION_SPEED_FAST, animate = !this.isTabbed }) => {
const panelQueue = [getTransition(lastOffset.panel), getTransition(offset.panel)]
const navQueue = [getTransition(lastOffset.nav), getTransition(this.isTabbed ? 0 : offset.nav)]
if (reset) {
const [panelStart] = panelQueue
const [navStart] = navQueue
panelQueue.push(panelStart)
navQueue.push(navStart)
}
const animationOptions = {
easing: 'ease-in-out',
duration: animate ? duration : 0,
fill: 'forwards',
}
const panelTransition = groupParent.animate(panelQueue, animationOptions)
labelWrap.animate(navQueue, animationOptions)
const handleFinish = () => {
this.panelsWrap.style.height = dom.getStyle(this.currentPanel, 'height')
panelTransition.removeEventListener('finish', handleFinish)
if (!reset) {
lastOffset = offset
}
}
panelTransition.addEventListener('finish', handleFinish)
}
action.setTranslateX = (panelIndex, animate = true) => {
offset = getOffset(panelIndex || this.activePanelIndex)
translateX({ offset, animate })
}
action.refresh = newIndex => {
if (newIndex !== undefined) {
this.activePanelIndex = newIndex
groupChange(newIndex)
}
this.resizePanels()
action.setTranslateX(this.activePanelIndex, false)
}
/**
* Slides panel to the next group
* @return {Object} current group after navigation
*/
action.nextGroup = () => {
const newIndex = this.activePanelIndex + 1
if (newIndex !== siblingGroups.length) {
const curPanel = groupChange(newIndex)
offset = {
nav: -labelWrap.offsetWidth * newIndex,
panel: -curPanel.offsetLeft,
}
translateX({ offset })
this.activePanelIndex++
} else {
offset = {
nav: lastOffset.nav - 8,
panel: lastOffset.panel - 8,
}
translateX({ offset, reset: true })
}
return this.currentPanel
}
action.prevGroup = () => {
if (this.activePanelIndex !== 0) {
const newIndex = this.activePanelIndex - 1
const curPanel = groupChange(newIndex)
offset = {
nav: -labelWrap.offsetWidth * newIndex,
panel: -curPanel.offsetLeft,
}
translateX({ offset })
this.activePanelIndex--
} else {
offset = {
nav: 8,
panel: 8,
}
translateX({ offset, reset: true })
}
}
return action
}
}
| Draggable/formeo | src/js/components/panels.js | JavaScript | mit | 9,240 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DiscordSharp.Commands
{
public abstract class IModule
{
/// <summary>
/// The name of the module.
/// </summary>
public virtual string Name { get; set; } = "module";
/// <summary>
/// A description talking about what the module contains
/// </summary>
public virtual string Description { get; set; } = "Please set this in the constructor of your IModule derivative.";
/// <summary>
/// A list of the commands this module contains
/// </summary>
public virtual List<ICommand> Commands { get; internal set; } = new List<ICommand>();
/// <summary>
/// Installs the module's commands into the commands manager
/// </summary>
/// <param name="manager"></param>
public abstract void Install(CommandsManager manager);
/// <summary>
/// Uninstall's this modules's commands from the given module manager.
/// </summary>
/// <param name="manager"></param>
public void Uninstall(CommandsManager manager)
{
lock (manager.Commands)
{
foreach (var command in manager.Commands)
{
var thisModulesCommand = Commands.Find(x => x.ID == command.ID && x.Parent.Name == this.Name); //compare modules by name just in case
if (thisModulesCommand != null)
manager.Commands.Remove(command);
}
}
}
}
}
| Luigifan/DiscordSharp | DiscordSharp.Commands/IModule.cs | C# | mit | 1,662 |
/*
* Copyright (c) 2012 VMware, Inc. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
(function (buster, define) {
"use strict";
var assert, refute, undef;
assert = buster.assert;
refute = buster.refute;
define('probe/stats/mean-test', function (require) {
var mean, counter;
mean = require('probe/stats/mean');
counter = require('probe/stats/counter');
buster.testCase('probe/stats/mean', {
'update the mean for each new value': function () {
var m = mean();
assert.same(1, m(1));
assert.same(2, m(3));
assert.same(2, m(2));
assert.same(4, m(10));
assert.same(0, m(-16));
assert.same(1 / 6, m(1));
},
'allow counter to be injected': function () {
var m, c;
c = counter();
m = mean(c);
c.inc();
assert.same(1, m(1));
c.inc();
assert.same(2, m(3));
c.inc();
assert.same(2, m(2));
c.inc();
assert.same(4, m(10));
c.inc();
assert.same(0, m(-16));
c.inc();
assert.same(1 / 6, m(1));
},
'injected counters must be incremented manually': function () {
var m = mean(counter());
assert.same(Number.POSITIVE_INFINITY, m(1));
},
'not passing a value returns the most recent mean': function () {
var m = mean();
assert.same(1, m(1));
assert.same(1, m());
assert.same(1, m());
},
'should restart from NaN when reset': function () {
var m = mean();
assert.same(NaN, m());
assert.same(1, m(1));
assert.same(2, m(3));
m.reset();
assert.same(NaN, m());
assert.same(1, m(1));
assert.same(2, m(3));
},
'should not update the readOnly stat': function () {
var m, ro;
m = mean();
ro = m.readOnly();
assert.same(NaN, m());
assert.same(NaN, ro());
assert.same(1, m(1));
assert.same(1, ro(2));
ro.reset();
assert.same(1, m());
m.reset();
assert.same(NaN, m());
assert.same(NaN, ro());
assert.same(ro, ro.readOnly());
}
});
});
}(
this.buster || require('buster'),
typeof define === 'function' && define.amd ? define : function (id, factory) {
var packageName = id.split(/[\/\-]/)[0], pathToRoot = id.replace(/[^\/]+/g, '..');
pathToRoot = pathToRoot.length > 2 ? pathToRoot.substr(3) : pathToRoot;
factory(function (moduleId) {
return require(moduleId.indexOf(packageName) === 0 ? pathToRoot + moduleId.substr(packageName.length) : moduleId);
});
}
// Boilerplate for AMD and Node
));
| s2js/probes | test/stats/mean-test.js | JavaScript | mit | 3,493 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("01.PriorityQueueImplementation")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("01.PriorityQueueImplementation")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("7791088d-2137-46b3-bfa2-75a2e51f83ee")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| ni4ka7a/TelerikAcademyHomeworks | DataStructuresAndAlgorithms/05.AdvancedDataStructures/01.PriorityQueueImplementation/Properties/AssemblyInfo.cs | C# | mit | 1,436 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RevStack.Client.API.Membership
{
public interface IValidation
{
void Validate(Object obj);
bool IsValid { get; }
Exception Exception { get; }
ValidationType ValidationType { get; }
}
}
| MISInteractive/revstack-net | src/REVStack.Client/API/Membership/IValidation.cs | C# | mit | 359 |
/**
* Copyright (c) 2010 by Gabriel Birke
*
* 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.
*/
function Sanitize(){
var i, e, options;
options = arguments[0] || {}
this.config = {}
this.config.elements = options.elements ? options.elements : [];
this.config.attributes = options.attributes ? options.attributes : {};
this.config.attributes[Sanitize.ALL] = this.config.attributes[Sanitize.ALL] ? this.config.attributes[Sanitize.ALL] : [];
this.config.allow_comments = options.allow_comments ? options.allow_comments : false;
this.allowed_elements = {};
this.config.protocols = options.protocols ? options.protocols : {};
this.config.add_attributes = options.add_attributes ? options.add_attributes : {};
this.dom = options.dom ? options.dom : document;
for(i=0;i<this.config.elements.length;i++) {
this.allowed_elements[this.config.elements[i]] = true;
}
this.config.remove_element_contents = {};
this.config.remove_all_contents = false;
if(options.remove_contents) {
if(options.remove_contents instanceof Array) {
for(i=0;i<options.remove_contents.length;i++) {
this.config.remove_element_contents[options.remove_contents[i]] = true;
}
}
else {
this.config.remove_all_contents = true;
}
}
this.transformers = options.transformers ? options.transformers : [];
}
Sanitize.REGEX_PROTOCOL = /^([A-Za-z0-9\+\-\.\&\;\*\s]*?)(?:\:|&*0*58|&*x0*3a)/i
Sanitize.RELATIVE = '__relative__'; // emulate Ruby symbol with string constant
Sanitize.prototype.clean_node = function(container) {
var fragment = this.dom.createDocumentFragment();
this.current_element = fragment;
this.whitelist_nodes = [];
/**
* Utility function to check if an element exists in an array
*/
function _array_index(needle, haystack) {
var i;
for(i=0; i < haystack.length; i++) {
if(haystack[i] == needle)
return i;
}
return -1;
}
function _merge_arrays_uniq() {
var result = [];
var uniq_hash = {}
var i,j;
for(i=0;i<arguments.length;i++) {
if(!arguments[i] || !arguments[i].length)
continue;
for(j=0;j<arguments[i].length;j++) {
if(uniq_hash[arguments[i][j]])
continue;
uniq_hash[arguments[i][j]] = true;
result.push(arguments[i][j]);
}
}
return result;
}
/**
* Clean function that checks the different node types and cleans them up accordingly
* @param elem DOM Node to clean
*/
function _clean(elem) {
var clone;
switch(elem.nodeType) {
// Element
case 1:
_clean_element.call(this, elem)
break;
// Text
case 3:
var clone = elem.cloneNode(false);
this.current_element.appendChild(clone);
break;
// Entity-Reference (normally not used)
case 5:
var clone = elem.cloneNode(false);
this.current_element.appendChild(clone);
break;
// Comment
case 8:
if(this.config.allow_comments) {
var clone = elem.cloneNode(false);
this.current_element.appendChild(clone);
}
default:
//console.log("unknown node type", elem.nodeType)
}
}
function _clean_element(elem) {
var i, j, clone, parent_element, name, allowed_attributes, attr, attr_name, attr_node, protocols, del, attr_ok;
var transform = _transform_element.call(this, elem);
elem = transform.node;
name = elem.nodeName.toLowerCase();
// check if element itself is allowed
parent_element = this.current_element;
if(this.allowed_elements[name] || transform.whitelist) {
this.current_element = this.dom.createElement(elem.nodeName);
parent_element.appendChild(this.current_element);
// clean attributes
allowed_attributes = _merge_arrays_uniq(
this.config.attributes[name],
this.config.attributes['__ALL__'],
transform.attr_whitelist
);
for(i=0;i<allowed_attributes.length;i++) {
attr_name = allowed_attributes[i];
attr = elem.attributes[attr_name];
if(attr) {
attr_ok = true;
// Check protocol attributes for valid protocol
if(this.config.protocols[name] && this.config.protocols[name][attr_name]) {
protocols = this.config.protocols[name][attr_name];
del = attr.nodeValue.toLowerCase().match(Sanitize.REGEX_PROTOCOL);
if(del) {
attr_ok = (_array_index(del[1], protocols) != -1);
}
else {
attr_ok = (_array_index(Sanitize.RELATIVE, protocols) != -1);
}
}
if(attr_ok) {
attr_node = document.createAttribute(attr_name);
attr_node.value = attr.nodeValue;
this.current_element.setAttributeNode(attr_node);
}
}
}
// Add attributes
if(this.config.add_attributes[name]) {
for(attr_name in this.config.add_attributes[name]) {
attr_node = document.createAttribute(attr_name);
attr_node.value = this.config.add_attributes[name][attr_name];
this.current_element.setAttributeNode(attr_node);
}
}
} // End checking if element is allowed
// If this node is in the dynamic whitelist array (built at runtime by
// transformers), let it live with all of its attributes intact.
else if(_array_index(elem, this.whitelist_nodes) != -1) {
this.current_element = elem.cloneNode(true);
// Remove child nodes, they will be sanitiazied and added by other code
while(this.current_element.childNodes.length > 0) {
this.current_element.removeChild(this.current_element.firstChild);
}
parent_element.appendChild(this.current_element);
}
// iterate over child nodes
if(!this.config.remove_all_contents && !this.config.remove_element_contents[name]) {
for(i=0;i<elem.childNodes.length;i++) {
_clean.call(this, elem.childNodes[i]);
}
}
// some versions of IE don't support normalize.
if(this.current_element.normalize) {
this.current_element.normalize();
}
this.current_element = parent_element;
} // END clean_element function
function _transform_element(node) {
var output = {
attr_whitelist:[],
node: node,
whitelist: false
}
var i, j, transform;
for(i=0;i<this.transformers.length;i++) {
transform = this.transformers[i]({
allowed_elements: this.allowed_elements,
config: this.config,
node: node,
node_name: node.nodeName.toLowerCase(),
whitelist_nodes: this.whitelist_nodes,
dom: this.dom
});
if(transform == null)
continue;
else if(typeof transform == 'object') {
if(transform.whitelist_nodes && transform.whitelist_nodes instanceof Array) {
for(j=0;j<transform.whitelist_nodes.length;j++) {
if(_array_index(transform.whitelist_nodes[j], this.whitelist_nodes) == -1) {
this.whitelist_nodes.push(transform.whitelist_nodes[j]);
}
}
}
output.whitelist = transform.whitelist ? true : false;
if(transform.attr_whitelist) {
output.attr_whitelist = _merge_arrays_uniq(output.attr_whitelist, transform.attr_whitelist);
}
output.node = transform.node ? transform.node : output.node;
}
else {
throw new Error("transformer output must be an object or null");
}
}
return output;
}
for(i=0;i<container.childNodes.length;i++) {
_clean.call(this, container.childNodes[i]);
}
if(fragment.normalize) {
fragment.normalize();
}
return fragment;
}
if(!Sanitize.Config) {
Sanitize.Config = {};
}
Sanitize.Config.BASIC = {
elements: [
'a', 'b', 'blockquote', 'br', 'cite', 'code', 'dd', 'dl', 'dt', 'em',
'i', 'li', 'ol', 'p', 'pre', 'q', 'small', 'strike', 'strong', 'sub',
'sup', 'u', 'ul'],
attributes: {
'a' : ['href'],
'blockquote': ['cite'],
'q' : ['cite']
},
add_attributes: {
'a': {'rel': 'nofollow'}
},
protocols: {
'a' : {'href': ['ftp', 'http', 'https', 'mailto',
Sanitize.RELATIVE]},
'blockquote': {'cite': ['http', 'https', Sanitize.RELATIVE]},
'q' : {'cite': ['http', 'https', Sanitize.RELATIVE]}
}
}; | kurbmedia/transit-legacy | app/assets/javascripts/libs/sanitize.js | JavaScript | mit | 9,555 |
export default {
actions: {
edit: '編集',
save: 'セーブ',
cancel: 'キャンセル',
new: '新しい',
list: 'リスト',
},
}
| HospitalRun/hospitalrun-frontend | src/shared/locales/ja/translations/actions/index.ts | TypeScript | mit | 156 |
const router = require('express').Router()
const albumsQueries = require('../../db/albums')
const albumsRoutes = require('./albums')
const usersQueries = require('../../db/users')
const usersRoutes = require('./users')
const reviewsQueries = require('../../db/reviews')
const {getSimpleDate} = require('../utils')
router.use('/albums', albumsRoutes)
router.use('/users', usersRoutes)
router.get('/', (req, res) => {
if (req.session.user) {
const userSessionID = req.session.user[0].id
const userSession = req.session.user[0]
reviewsQueries.getReviews((error, reviews) => {
if (error) {
res.status(500).render('common/error', {
error,
})
}
albumsQueries.getAlbums((error, albums) => {
if (error) {
res.status(500).render('common/error', {
error,
})
}
res.render('index/index', {
albums,
reviews,
userSessionID,
userSession,
})
})
})
}
const userSessionID = null
const userSession = null
reviewsQueries.getReviews((error, reviews) => {
if (error) {
res.status(500).render('common/error', {
error,
})
}
albumsQueries.getAlbums((error, albums) => {
if (error) {
res.status(500).render('common/error', {
error,
})
}
res.render('index/index', {
albums,
reviews,
userSessionID,
userSession,
})
})
})
})
router.get('/signup', (req, res) => {
if (req.session.user) {
const userSessionID = req.session.user[0].id
const userSession = req.session.user[0]
res.render('index/signup', {
userSessionID,
userSession,
})
}
const userSessionID = null
const userSession = null
res.render('index/signup', {
userSessionID,
userSession,
})
})
router.post('/signup', (req, res) => {
const accountInfo = req.body
const dateToday = new Date()
const dateJoined = getSimpleDate(dateToday)
usersQueries.getUsersByEmail(accountInfo.email, (error, userEmailInfo) => {
if (error) {
return res.status(500).render('common/error', {
error,
})
} else if (userEmailInfo.length > 0) {
return res.status(401).render('common/error', {
error: {
message: 'Email address already exists',
},
})
}
usersQueries.createUser(accountInfo, dateJoined, (error, accountNew) => {
if (error) {
return res.status(500).render('common/error', {
error,
})
}
return res.redirect(`/users/${accountNew[0].id}`)
})
})
})
router.get('/signin', (req, res) => {
if (req.session.user) {
const userSessionID = req.session.user[0].id
const userSession = req.session.user[0]
res.render('index/signin', {
userSessionID,
userSession,
})
}
const userSessionID = null
const userSession = null
res.render('index/signin', {
userSessionID,
userSession,
})
})
router.post('/signin', (req, res) => {
const loginEmail = req.body.email
const loginPassword = req.body.password
usersQueries.getUsersByEmail(loginEmail, (error, userEmailInfo) => {
if (error) {
return res.status(500).render('common/error', {
error,
})
} else if (userEmailInfo[0] !== undefined) {
if (loginPassword !== userEmailInfo[0].password) {
return res.status(401).render('common/error', {
error: {
message: 'Username and password do not match',
},
})
}
console.log('Logged in')
req.session.user = userEmailInfo
req.session.save()
return res.redirect(`/users/${userEmailInfo[0].id}`)
}
return res.status(401).render('common/error', {
error: {
message: 'Username and password do not match',
},
})
})
})
router.get('/signout', (req, res) => {
req.session.destroy()
res.clearCookie('userInformation')
res.redirect('/')
})
module.exports = router
| hhhhhaaaa/phase-4-challenge | src/server/routes/index.js | JavaScript | mit | 4,027 |
# Abstract model
class Abstract < ActiveRecordShared
belongs_to :study_subject, :counter_cache => true
with_options :class_name => 'User', :primary_key => 'uid' do |u|
u.belongs_to :entry_1_by, :foreign_key => 'entry_1_by_uid'
u.belongs_to :entry_2_by, :foreign_key => 'entry_2_by_uid'
u.belongs_to :merged_by, :foreign_key => 'merged_by_uid'
end
include AbstractValidations
attr_protected :study_subject_id, :study_subject
attr_protected :entry_1_by_uid
attr_protected :entry_2_by_uid
attr_protected :merged_by_uid
attr_accessor :current_user
attr_accessor :weight_units, :height_units
attr_accessor :merging # flag to be used to skip 2 abstract limitation
# The :on => :create doesn't seem to work as described
# validate_on_create is technically deprecated, but still works
validate_on_create :subject_has_less_than_three_abstracts #, :on => :create
validate_on_create :subject_has_no_merged_abstract #, :on => :create
before_create :set_user
after_create :delete_unmerged
before_save :convert_height_to_cm
before_save :convert_weight_to_kg
before_save :set_days_since_fields
def self.fields
# db: db field name
# human: humanized field
@@fields ||= YAML::load( ERB.new( IO.read(
File.join(File.dirname(__FILE__),'../../config/abstract_fields.yml')
)).result)
end
def fields
Abstract.fields
end
def self.db_fields
# @db_fields ||= fields.collect{|f|f[:db]}
Abstract.fields.collect{|f|f[:db]}
end
def db_fields
Abstract.db_fields
end
def comparable_attributes
HashWithIndifferentAccess[attributes.select {|k,v| db_fields.include?(k)}]
end
def is_the_same_as?(another_abstract)
self.diff(another_abstract).blank?
end
def diff(another_abstract)
a1 = self.comparable_attributes
a2 = Abstract.find(another_abstract).comparable_attributes
HashWithIndifferentAccess[a1.select{|k,v| a2[k] != v unless( a2[k].blank? && v.blank? ) }]
end
# include AbstractSearch
def self.search(params={})
# TODO stop using this. Now that study subjects and abstracts are in
# the same database, this should be simplified. Particularly since
# the only searching is really on the study subject and not the abstract.
AbstractSearch.new(params).abstracts
end
def self.sections
# :label: Cytogenetics
# :controller: CytogeneticsController
# :edit: :edit_abstract_cytogenetic_path
# :show: :abstract_cytogenetic_path
@@sections ||= YAML::load(ERB.new( IO.read(
File.join(File.dirname(__FILE__),'../../config/abstract_sections.yml')
)).result)
end
def merged?
!merged_by_uid.blank?
end
protected
def set_days_since_fields
# must explicitly convert these DateTimes to Date so that the
# difference is in days and not seconds
# I really only need to do this if something changes,
# but for now, just do it and make sure that
# it is tested. Optimize and refactor later.
unless diagnosed_on.nil?
self.response_day_7_days_since_diagnosis = (
response_report_on_day_7.to_date - diagnosed_on.to_date
) unless response_report_on_day_7.nil?
self.response_day_14_days_since_diagnosis = (
response_report_on_day_14.to_date - diagnosed_on.to_date
) unless response_report_on_day_14.nil?
self.response_day_28_days_since_diagnosis = (
response_report_on_day_28.to_date - diagnosed_on.to_date
) unless response_report_on_day_28.nil?
end
unless treatment_began_on.nil?
self.response_day_7_days_since_treatment_began = (
response_report_on_day_7.to_date - treatment_began_on.to_date
) unless response_report_on_day_7.nil?
self.response_day_14_days_since_treatment_began = (
response_report_on_day_14.to_date - treatment_began_on.to_date
) unless response_report_on_day_14.nil?
self.response_day_28_days_since_treatment_began = (
response_report_on_day_28.to_date - treatment_began_on.to_date
) unless response_report_on_day_28.nil?
end
end
def convert_height_to_cm
if( !height_units.nil? && height_units.match(/in/i) )
self.height_units = nil
self.height_at_diagnosis *= 2.54
end
end
def convert_weight_to_kg
if( !weight_units.nil? && weight_units.match(/lb/i) )
self.weight_units = nil
self.weight_at_diagnosis /= 2.2046
end
end
# Set user if given
def set_user
if study_subject
# because it is possible to create the first, then the second
# and then delete the first, and create another, first and
# second kinda lose their meaning until the merge, so set them
# both as the same until the merge
case study_subject.abstracts_count
when 0
self.entry_1_by_uid = current_user.try(:uid)||0
self.entry_2_by_uid = current_user.try(:uid)||0
when 1
self.entry_1_by_uid = current_user.try(:uid)||0
self.entry_2_by_uid = current_user.try(:uid)||0
when 2
abs = study_subject.abstracts
# compact just in case a nil crept in
self.entry_1_by_uid = [abs[0].entry_1_by_uid,abs[0].entry_2_by_uid].compact.first
self.entry_2_by_uid = [abs[1].entry_1_by_uid,abs[1].entry_2_by_uid].compact.first
self.merged_by_uid = current_user.try(:uid)||0
end
end
end
def delete_unmerged
if study_subject and !merged_by_uid.blank?
# use delete and not destroy to preserve the abstracts_count
study_subject.unmerged_abstracts.each{|a|a.delete}
end
end
def subject_has_less_than_three_abstracts
# because this abstract hasn't been created yet, we're comparing to 2, not 3
if study_subject and study_subject.abstracts_count >= 2
errors.add(:study_subject_id,"Study Subject can only have 2 abstracts." ) unless merging
end
end
def subject_has_no_merged_abstract
if study_subject and study_subject.merged_abstract
errors.add(:study_subject_id,"Study Subject already has a merged abstract." )
end
end
end
| ccls/ccls_engine | app/models/abstract.rb | Ruby | mit | 5,798 |
package com.tehreh1uneh.cloudstorage.common.messages.files;
import com.tehreh1uneh.cloudstorage.common.messages.base.Message;
import com.tehreh1uneh.cloudstorage.common.messages.base.MessageType;
import java.io.File;
import java.util.ArrayList;
public class FilesListResponse extends Message {
private final ArrayList<File> filesList;
private final boolean root;
public FilesListResponse(ArrayList<File> filesList, boolean root) {
super(MessageType.FILES_LIST_RESPONSE);
this.filesList = filesList;
this.root = root;
}
public boolean isRoot() {
return root;
}
public ArrayList<File> getFilesList() {
return filesList;
}
}
| tehreh1uneh/CloudStorage | common/src/main/java/com/tehreh1uneh/cloudstorage/common/messages/files/FilesListResponse.java | Java | mit | 701 |
class PagesController < ApplicationController
def home
@emptyphoto = Photo.new
@top5 = Photo.popular
end
end | jannewaren/toukoaalto_generator | app/controllers/pages_controller.rb | Ruby | mit | 126 |
require "active_record"
require "authem/token"
module Authem
class Session < ::ActiveRecord::Base
self.table_name = :authem_sessions
belongs_to :subject, polymorphic: true
before_create do
self.token ||= Authem::Token.generate
self.ttl ||= 30.days
self.expires_at ||= ttl_from_now
end
class << self
def by_subject(record)
where(subject_type: record.class.name, subject_id: record.id)
end
def active
where(arel_table[:expires_at].gteq(Time.zone.now))
end
def expired
where(arel_table[:expires_at].lt(Time.zone.now))
end
end
def refresh
self.expires_at = ttl_from_now
save!
end
private
def ttl_from_now
ttl.to_i.from_now
end
end
end
| rwz/authem2 | lib/authem/session.rb | Ruby | mit | 784 |
require 'rails_helper'
include OmniauthHelpers
describe Users::SignIn do
describe '#call' do
it 'returns object with user_id and organisation_id' do
auth = create_auth
sign_in = Users::SignIn.new(auth: auth)
membership = sign_in.call
expect(membership.user_id).to eq(User.first.id)
expect(membership.organisation_id).to eq(Organisation.first.id)
end
it 'adds user to the organisation' do
auth = create_auth
sign_in = Users::SignIn.new(auth: auth)
sign_in.call
expect(Organisation.first.users).to include(User.first)
end
it "updates user's email when it's different from one in the database" do
new_email = 'different@email.com'
auth = create_auth(email: new_email)
user = create(:user,
email: 'some@email.com',
provider: auth['provider'], uid: auth['uid'])
sign_in = Users::SignIn.new(auth: auth)
sign_in.call
expect(user.reload.email).to eq(new_email)
end
it 'saves authenitcation token when organisation is created' do
token = 'some_token'
auth = create_auth(token: token)
sign_in = Users::SignIn.new(auth: auth)
sign_in.call
expect(Organisation.first.token).to eq(token)
end
it 'saves user as admin if is_admin is true' do
auth = create_auth(is_admin: true)
sign_in = Users::SignIn.new(auth: auth)
sign_in.call
expect(User.first.admin).to eq true
end
it 'does not save user as admin if is_admin is false' do
auth = create_auth(is_admin: false)
sign_in = Users::SignIn.new(auth: auth)
sign_in.call
expect(User.first.admin).to eq false
end
end
end
| netguru/props | spec/services/sign_in_spec.rb | Ruby | mit | 1,728 |
using System;
using System.IO;
using System.IO.Abstractions;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using NSubstitute;
using PactNet.Mocks.MockHttpService;
using PactNet.Mocks.MockHttpService.Models;
using PactNet.Mocks.MockHttpService.Validators;
using PactNet.Models;
using PactNet.Tests.Fakes;
using Xunit;
using Xunit.Sdk;
namespace PactNet.Tests
{
public class PactVerifierTests
{
private Tuple<bool, IHttpRequestSender> _providerServiceValidatorFactoryCallInfo;
private IFileSystem _mockFileSystem;
private IProviderServiceValidator _mockProviderServiceValidator;
private FakeHttpMessageHandler _fakeHttpMessageHandler;
private IPactVerifier GetSubject()
{
_providerServiceValidatorFactoryCallInfo = null;
_mockFileSystem = Substitute.For<IFileSystem>();
_mockProviderServiceValidator = Substitute.For<IProviderServiceValidator>();
_fakeHttpMessageHandler = new FakeHttpMessageHandler();
return new PactVerifier(() => {}, () => {}, _mockFileSystem, (httpRequestSender, reporter, config) =>
{
_providerServiceValidatorFactoryCallInfo = new Tuple<bool, IHttpRequestSender>(true, httpRequestSender);
return _mockProviderServiceValidator;
}, new HttpClient(_fakeHttpMessageHandler), null);
}
[Fact]
public void ProviderState_WhenCalledWithSetUpAndTearDown_SetsProviderStateWithSetUpAndTearDownActions()
{
const string providerState = "There is an event with id 1234 in the database";
Action providerStateSetUpAction = () => { };
Action providerStateTearDownAction = () => { };
var pactVerifier = (PactVerifier)GetSubject();
pactVerifier
.ProviderState(providerState, providerStateSetUpAction, providerStateTearDownAction);
var providerStateItem = pactVerifier.ProviderStates.Find(providerState);
Assert.Equal(providerStateSetUpAction, providerStateItem.SetUp);
Assert.Equal(providerStateTearDownAction, providerStateItem.TearDown);
}
[Fact]
public void ProviderState_WhenCalledWithNullProviderState_ThrowsArgumentException()
{
var pactVerifier = GetSubject();
Assert.Throws<ArgumentException>(() =>
pactVerifier
.ProviderState(null));
}
[Fact]
public void ProviderState_WhenCalledWithEmptyProviderState_ThrowsArgumentException()
{
var pactVerifier = GetSubject();
Assert.Throws<ArgumentException>(() =>
pactVerifier
.ProviderState(String.Empty));
}
[Fact]
public void ServiceProvider_WhenCalledWithNullProviderName_ThrowsArgumentException()
{
var pactVerifier = GetSubject();
Assert.Throws<ArgumentException>(() => pactVerifier.ServiceProvider(null, new HttpClient()));
}
[Fact]
public void ServiceProvider_WhenCalledWithEmptyProviderName_ThrowsArgumentException()
{
var pactVerifier = GetSubject();
Assert.Throws<ArgumentException>(() => pactVerifier.ServiceProvider(String.Empty, new HttpClient()));
}
[Fact]
public void ServiceProvider_WhenCalledWithAnAlreadySetProviderName_ThrowsArgumentException()
{
const string providerName = "My API";
var pactVerifier = GetSubject();
pactVerifier.ServiceProvider(providerName, new HttpClient());
Assert.Throws<ArgumentException>(() => pactVerifier.ServiceProvider(providerName, new HttpClient()));
}
[Fact]
public void ServiceProviderOverload_WhenCalledWithAnAlreadySetProviderName_ThrowsArgumentException()
{
const string providerName = "My API";
var pactVerifier = GetSubject();
pactVerifier.ServiceProvider(providerName, request => null);
Assert.Throws<ArgumentException>(() => pactVerifier.ServiceProvider(providerName, request => null));
}
[Fact]
public void ServiceProvider_WhenCalledWithNullHttpClient_ThrowsArgumentException()
{
var pactVerifier = GetSubject();
Assert.Throws<ArgumentException>(() => pactVerifier.ServiceProvider("Event API", httpClient: null));
}
[Fact]
public void ServiceProvider_WhenCalledWithProviderName_SetsProviderName()
{
const string providerName = "Event API";
var pactVerifier = GetSubject();
pactVerifier.ServiceProvider(providerName, new HttpClient());
Assert.Equal(providerName, ((PactVerifier)pactVerifier).ProviderName);
}
[Fact]
public void ServiceProvider_WhenCalledWithHttpClient_HttpClientRequestSenderIsPassedIntoProviderServiceValidatorFactoryWhenVerifyIsCalled()
{
var httpClient = new HttpClient();
var pactVerifier = GetSubject();
pactVerifier.ServiceProvider("Event API", httpClient);
pactVerifier
.HonoursPactWith("My client")
.PactUri("../../../Consumer.Tests/pacts/my_client-event_api.json")
.Verify();
Assert.True(_providerServiceValidatorFactoryCallInfo.Item1, "_providerServiceValidatorFactory was called");
Assert.IsType(typeof(HttpClientRequestSender), _providerServiceValidatorFactoryCallInfo.Item2); //was called with type
}
[Fact]
public void ServiceProvider_WhenCalledWithNullProviderNameAndCustomRequestSender_ThrowsArgumentException()
{
var pactVerifier = GetSubject();
Assert.Throws<ArgumentException>(() => pactVerifier.ServiceProvider(null, request => new ProviderServiceResponse()));
}
[Fact]
public void ServiceProvider_WhenCalledWithNullRequestSender_ThrowsArgumentException()
{
var pactVerifier = GetSubject();
Assert.Throws<ArgumentException>(() => pactVerifier.ServiceProvider("Event API", (Func<ProviderServiceRequest, ProviderServiceResponse>) null));
}
[Fact]
public void ServiceProvider_WhenCalledWithCustomRequestSender_CustomRequestSenderIsPassedIntoProviderServiceValidatorFactoryWhenVerifyIsCalled()
{
var pactVerifier = GetSubject();
pactVerifier.ServiceProvider("Event API", request => new ProviderServiceResponse());
pactVerifier
.HonoursPactWith("My client")
.PactUri("../../../Consumer.Tests/pacts/my_client-event_api.json")
.Verify();
Assert.True(_providerServiceValidatorFactoryCallInfo.Item1, "_providerServiceValidatorFactory was called");
Assert.IsType(typeof(CustomRequestSender), _providerServiceValidatorFactoryCallInfo.Item2); //was called with type
}
[Fact]
public void HonoursPactWith_WhenCalledWithNullConsumerName_ThrowsArgumentException()
{
var pactVerifier = GetSubject();
Assert.Throws<ArgumentException>(() => pactVerifier.HonoursPactWith(null));
}
[Fact]
public void HonoursPactWith_WhenCalledWithEmptyConsumerName_ThrowsArgumentException()
{
var pactVerifier = GetSubject();
Assert.Throws<ArgumentException>(() => pactVerifier.HonoursPactWith(String.Empty));
}
[Fact]
public void HonoursPactWith_WhenCalledWithAnAlreadySetConsumerName_ThrowsArgumentException()
{
const string consumerName = "My Consumer";
var pactVerifier = GetSubject();
pactVerifier.HonoursPactWith(consumerName);
Assert.Throws<ArgumentException>(() => pactVerifier.HonoursPactWith(consumerName));
}
[Fact]
public void HonoursPactWith_WhenCalledWithConsumerName_SetsConsumerName()
{
const string consumerName = "My Client";
var pactVerifier = GetSubject();
pactVerifier.HonoursPactWith(consumerName);
Assert.Equal(consumerName, ((PactVerifier)pactVerifier).ConsumerName);
}
[Fact]
public void PactUri_WhenCalledWithNullUri_ThrowsArgumentException()
{
var pactVerifier = GetSubject();
Assert.Throws<ArgumentException>(() => pactVerifier.PactUri(null));
}
[Fact]
public void PactUri_WhenCalledWithEmptyUri_ThrowsArgumentException()
{
var pactVerifier = GetSubject();
Assert.Throws<ArgumentException>(() => pactVerifier.PactUri(String.Empty));
}
[Fact]
public void PactUri_WhenCalledWithUri_SetsPactFileUri()
{
const string pactFileUri = "../../../Consumer.Tests/pacts/my_client-event_api.json";
var pactVerifier = GetSubject();
pactVerifier.PactUri(pactFileUri);
Assert.Equal(pactFileUri, ((PactVerifier)pactVerifier).PactFileUri);
}
[Fact]
public void Verify_WhenHttpRequestSenderIsNull_ThrowsInvalidOperationException()
{
var pactVerifier = GetSubject();
pactVerifier.PactUri("../../../Consumer.Tests/pacts/my_client-event_api.json");
Assert.Throws<InvalidOperationException>(() => pactVerifier.Verify());
}
[Fact]
public void Verify_WhenPactFileUriIsNull_ThrowsInvalidOperationException()
{
var pactVerifier = GetSubject();
pactVerifier.ServiceProvider("Event API", new HttpClient());
Assert.Throws<InvalidOperationException>(() => pactVerifier.Verify());
}
[Fact]
public void Verify_WithFileSystemPactFileUri_CallsFileReadAllText()
{
var serviceProvider = "Event API";
var serviceConsumer = "My client";
var pactUri = "../../../Consumer.Tests/pacts/my_client-event_api.json";
var pactFileJson = "{ \"provider\": { \"name\": \"Event API\" }, \"consumer\": { \"name\": \"My client\" }, \"interactions\": [{ \"description\": \"My Description\", \"provider_state\": \"My Provider State\" }, { \"description\": \"My Description 2\", \"provider_state\": \"My Provider State\" }, { \"description\": \"My Description\", \"provider_state\": \"My Provider State 2\" }], \"metadata\": { \"pactSpecificationVersion\": \"1.0.0\" } }";
var pactVerifier = GetSubject();
_mockFileSystem.File.ReadAllText(pactUri).Returns(pactFileJson);
pactVerifier
.ServiceProvider(serviceProvider, new HttpClient())
.HonoursPactWith(serviceConsumer)
.PactUri(pactUri);
pactVerifier.Verify();
_mockFileSystem.File.Received(1).ReadAllText(pactUri);
}
[Fact]
public void Verify_WithHttpPactFileUri_CallsHttpClientWithJsonGetRequest()
{
var serviceProvider = "Event API";
var serviceConsumer = "My client";
var pactUri = "http://yourpactserver.com/getlatestpactfile";
var pactFileJson = "{ \"provider\": { \"name\": \"Event API\" }, \"consumer\": { \"name\": \"My client\" }, \"interactions\": [{ \"description\": \"My Description\", \"provider_state\": \"My Provider State\" }, { \"description\": \"My Description 2\", \"provider_state\": \"My Provider State\" }, { \"description\": \"My Description\", \"provider_state\": \"My Provider State 2\" }], \"metadata\": { \"pactSpecificationVersion\": \"1.0.0\" } }";
var pactVerifier = GetSubject();
_fakeHttpMessageHandler.Response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(pactFileJson, Encoding.UTF8, "application/json")
};
pactVerifier
.ServiceProvider(serviceProvider, new HttpClient())
.HonoursPactWith(serviceConsumer)
.PactUri(pactUri);
pactVerifier.Verify();
Assert.Equal(HttpMethod.Get, _fakeHttpMessageHandler.RequestsRecieved.Single().Method);
Assert.Equal("application/json", _fakeHttpMessageHandler.RequestsRecieved.Single().Headers.Single(x => x.Key == "Accept").Value.Single());
}
[Fact]
public void Verify_WithHttpsPactFileUri_CallsHttpClientWithJsonGetRequest()
{
var serviceProvider = "Event API";
var serviceConsumer = "My client";
var pactUri = "https://yourpactserver.com/getlatestpactfile";
var pactFileJson = "{ \"provider\": { \"name\": \"Event API\" }, \"consumer\": { \"name\": \"My client\" }, \"interactions\": [{ \"description\": \"My Description\", \"provider_state\": \"My Provider State\" }, { \"description\": \"My Description 2\", \"provider_state\": \"My Provider State\" }, { \"description\": \"My Description\", \"provider_state\": \"My Provider State 2\" }], \"metadata\": { \"pactSpecificationVersion\": \"1.0.0\" } }";
var pactVerifier = GetSubject();
_fakeHttpMessageHandler.Response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(pactFileJson, Encoding.UTF8, "application/json")
};
pactVerifier
.ServiceProvider(serviceProvider, new HttpClient())
.HonoursPactWith(serviceConsumer)
.PactUri(pactUri);
pactVerifier.Verify();
Assert.Equal(HttpMethod.Get, _fakeHttpMessageHandler.RequestsRecieved.Single().Method);
Assert.Equal("application/json", _fakeHttpMessageHandler.RequestsRecieved.Single().Headers.Single(x => x.Key == "Accept").Value.Single());
}
[Fact]
public void Verify_WithHttpsPactFileUriAndBasicAuthUriOptions_CallsHttpClientWithJsonGetRequestAndBasicAuthorizationHeader()
{
var serviceProvider = "Event API";
var serviceConsumer = "My client";
var pactUri = "https://yourpactserver.com/getlatestpactfile";
var pactFileJson = "{ \"provider\": { \"name\": \"Event API\" }, \"consumer\": { \"name\": \"My client\" }, \"interactions\": [{ \"description\": \"My Description\", \"provider_state\": \"My Provider State\" }, { \"description\": \"My Description 2\", \"provider_state\": \"My Provider State\" }, { \"description\": \"My Description\", \"provider_state\": \"My Provider State 2\" }], \"metadata\": { \"pactSpecificationVersion\": \"1.0.0\" } }";
var options = new PactUriOptions("someuser", "somepassword");
var pactVerifier = GetSubject();
_fakeHttpMessageHandler.Response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(pactFileJson, Encoding.UTF8, "application/json")
};
pactVerifier
.ServiceProvider(serviceProvider, new HttpClient())
.HonoursPactWith(serviceConsumer)
.PactUri(pactUri, options);
pactVerifier.Verify();
Assert.Equal(HttpMethod.Get, _fakeHttpMessageHandler.RequestsRecieved.Single().Method);
Assert.Equal("application/json", _fakeHttpMessageHandler.RequestsRecieved.Single().Headers.Single(x => x.Key == "Accept").Value.Single());
Assert.Equal(_fakeHttpMessageHandler.RequestsRecieved.Single().Headers.Authorization.Scheme, options.AuthorizationScheme);
Assert.Equal(_fakeHttpMessageHandler.RequestsRecieved.Single().Headers.Authorization.Parameter, options.AuthorizationValue);
}
[Fact]
public void Verify_WithFileUriAndWhenFileDoesNotExistOnFileSystem_ThrowsInvalidOperationException()
{
var serviceProvider = "Event API";
var serviceConsumer = "My client";
var pactUri = "../../../Consumer.Tests/pacts/my_client-event_api.json";
var pactVerifier = GetSubject();
_mockFileSystem.File.ReadAllText(pactUri).Returns(x => { throw new FileNotFoundException(); });
pactVerifier
.ServiceProvider(serviceProvider, new HttpClient())
.HonoursPactWith(serviceConsumer)
.PactUri(pactUri);
Assert.Throws<InvalidOperationException>(() => pactVerifier.Verify());
_mockFileSystem.File.Received(1).ReadAllText(pactUri);
}
[Fact]
public void Verify_WithHttpUriAndNonSuccessfulStatusCodeIsReturned_ThrowsInvalidOperationException()
{
var serviceProvider = "Event API";
var serviceConsumer = "My client";
var pactUri = "http://yourpactserver.com/getlatestpactfile";
var pactVerifier = GetSubject();
_fakeHttpMessageHandler.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
pactVerifier
.ServiceProvider(serviceProvider, new HttpClient())
.HonoursPactWith(serviceConsumer)
.PactUri(pactUri);
Assert.Throws<InvalidOperationException>(() => pactVerifier.Verify());
Assert.Equal(HttpMethod.Get, _fakeHttpMessageHandler.RequestsRecieved.Single().Method);
}
[Fact]
public void Verify_WhenPactFileWithNoInteractionsExistOnFileSystem_CallsPactProviderValidator()
{
var serviceProvider = "Event API";
var serviceConsumer = "My client";
var pactUri = "../../../Consumer.Tests/pacts/my_client-event_api.json";
var pactFileJson = "{ \"provider\": { \"name\": \"" + serviceProvider + "\" }, \"consumer\": { \"name\": \"" + serviceConsumer + "\" }, \"metadata\": { \"pactSpecificationVersion\": \"1.0.0\" } }";
var httpClient = new HttpClient();
var pactVerifier = GetSubject();
_mockFileSystem.File.ReadAllText(pactUri).Returns(pactFileJson);
pactVerifier
.ServiceProvider(serviceProvider, httpClient)
.HonoursPactWith(serviceConsumer)
.PactUri(pactUri);
pactVerifier.Verify();
_mockFileSystem.File.Received(1).ReadAllText(pactUri);
_mockProviderServiceValidator.Received(1).Validate(Arg.Any<ProviderServicePactFile>(), Arg.Any<ProviderStates>());
}
[Fact]
public void Verify_WithNoProviderDescriptionOrProviderStateSupplied_CallsProviderServiceValidatorWithAll3Interactions()
{
var pactUri = "../../../Consumer.Tests/pacts/my_client-event_api.json";
var pactFileJson = "{ \"provider\": { \"name\": \"Event API\" }, \"consumer\": { \"name\": \"My client\" }, \"interactions\": [{ \"description\": \"My Description\", \"provider_state\": \"My Provider State\" }, { \"description\": \"My Description 2\", \"provider_state\": \"My Provider State\" }, { \"description\": \"My Description\", \"provider_state\": \"My Provider State 2\" }], \"metadata\": { \"pactSpecificationVersion\": \"1.0.0\" } }";
var httpClient = new HttpClient();
var pactVerifier = GetSubject();
_mockFileSystem.File.ReadAllText(pactUri).Returns(pactFileJson);
pactVerifier
.ProviderState("My Provider State")
.ProviderState("My Provider State 2");
pactVerifier.ServiceProvider("Event API", httpClient)
.HonoursPactWith("My client")
.PactUri(pactUri);
pactVerifier.Verify();
_mockProviderServiceValidator.Received(1).Validate(
Arg.Is<ProviderServicePactFile>(x => x.Interactions.Count() == 3),
Arg.Any<ProviderStates>());
}
[Fact]
public void Verify_WithDescription_CallsProviderServiceValidatorWith2FilteredInteractions()
{
var description = "My Description";
var pactUri = "../../../Consumer.Tests/pacts/my_client-event_api.json";
var pactFileJson = "{ \"provider\": { \"name\": \"Event API\" }, \"consumer\": { \"name\": \"My client\" }, \"interactions\": [{ \"description\": \"My Description\", \"provider_state\": \"My Provider State\" }, { \"description\": \"My Description 2\", \"provider_state\": \"My Provider State\" }, { \"description\": \"My Description\", \"provider_state\": \"My Provider State 2\" }], \"metadata\": { \"pactSpecificationVersion\": \"1.0.0\" } }";
var httpClient = new HttpClient();
var pactVerifier = GetSubject();
_mockFileSystem.File.ReadAllText(pactUri).Returns(pactFileJson);
pactVerifier
.ProviderState("My Provider State")
.ProviderState("My Provider State 2");
pactVerifier.ServiceProvider("Event API", httpClient)
.HonoursPactWith("My client")
.PactUri(pactUri);
pactVerifier.Verify(description: description);
_mockProviderServiceValidator.Received(1).Validate(
Arg.Is<ProviderServicePactFile>(x => x.Interactions.Count() == 2 && x.Interactions.All(i => i.Description.Equals(description))),
Arg.Any<ProviderStates>());
}
[Fact]
public void Verify_WithProviderState_CallsProviderServiceValidatorWith2FilteredInteractions()
{
var providerState = "My Provider State";
var pactUri = "../../../Consumer.Tests/pacts/my_client-event_api.json";
var pactFileJson = "{ \"provider\": { \"name\": \"Event API\" }, \"consumer\": { \"name\": \"My client\" }, \"interactions\": [{ \"description\": \"My Description\", \"provider_state\": \"My Provider State\" }, { \"description\": \"My Description 2\", \"provider_state\": \"My Provider State\" }, { \"description\": \"My Description\", \"provider_state\": \"My Provider State 2\" }], \"metadata\": { \"pactSpecificationVersion\": \"1.0.0\" } }";
var httpClient = new HttpClient();
var pactVerifier = GetSubject();
_mockFileSystem.File.ReadAllText(pactUri).Returns(pactFileJson);
pactVerifier
.ProviderState("My Provider State")
.ProviderState("My Provider State 2");
pactVerifier.ServiceProvider("Event API", httpClient)
.HonoursPactWith("My client")
.PactUri(pactUri);
pactVerifier.Verify(providerState: providerState);
_mockProviderServiceValidator.Received(1).Validate(
Arg.Is<ProviderServicePactFile>(x => x.Interactions.Count() == 2 && x.Interactions.All(i => i.ProviderState.Equals(providerState))),
Arg.Any<ProviderStates>());
}
[Fact]
public void Verify_WithDescriptionAndProviderState_CallsProviderServiceValidatorWith1FilteredInteractions()
{
var description = "My Description";
var providerState = "My Provider State";
var pactUri = "../../../Consumer.Tests/pacts/my_client-event_api.json";
var pactFileJson = "{ \"provider\": { \"name\": \"Event API\" }, \"consumer\": { \"name\": \"My client\" }, \"interactions\": [{ \"description\": \"My Description\", \"provider_state\": \"My Provider State\" }, { \"description\": \"My Description 2\", \"provider_state\": \"My Provider State\" }, { \"description\": \"My Description\", \"provider_state\": \"My Provider State 2\" }], \"metadata\": { \"pactSpecificationVersion\": \"1.0.0\" } }";
var httpClient = new HttpClient();
var pactVerifier = GetSubject();
_mockFileSystem.File.ReadAllText(pactUri).Returns(pactFileJson);
pactVerifier
.ProviderState("My Provider State")
.ProviderState("My Provider State 2");
pactVerifier.ServiceProvider("Event API", httpClient)
.HonoursPactWith("My client")
.PactUri(pactUri);
pactVerifier.Verify(description: description, providerState: providerState);
_mockProviderServiceValidator.Received(1).Validate(
Arg.Is<ProviderServicePactFile>(x => x.Interactions.Count() == 1 && x.Interactions.All(i => i.ProviderState.Equals(providerState) && i.Description.Equals(description))),
Arg.Any<ProviderStates>());
}
[Fact]
public void Verify_WithDescriptionThatYieldsNoInteractions_ThrowsArgumentException()
{
var description = "Description that does not match an interaction";
var pactUri = "../../../Consumer.Tests/pacts/my_client-event_api.json";
var pactFileJson = "{ \"provider\": { \"name\": \"Event API\" }, \"consumer\": { \"name\": \"My client\" }, \"interactions\": [{ \"description\": \"My Description\", \"provider_state\": \"My Provider State\" }, { \"description\": \"My Description 2\", \"provider_state\": \"My Provider State\" }, { \"description\": \"My Description\", \"provider_state\": \"My Provider State 2\" }], \"metadata\": { \"pactSpecificationVersion\": \"1.0.0\" } }";
var httpClient = new HttpClient();
var pactVerifier = GetSubject();
_mockFileSystem.File.ReadAllText(pactUri).Returns(pactFileJson);
pactVerifier
.ProviderState("My Provider State")
.ProviderState("My Provider State 2");
pactVerifier.ServiceProvider("Event API", httpClient)
.HonoursPactWith("My client")
.PactUri(pactUri);
Assert.Throws<ArgumentException>(() => pactVerifier.Verify(description: description));
_mockProviderServiceValidator.DidNotReceive().Validate(
Arg.Any<ProviderServicePactFile>(),
Arg.Any<ProviderStates>());
}
[Fact]
public void Verify_WithProviderStateSet_CallsProviderServiceValidatorWithProviderState()
{
var httpClient = new HttpClient();
var pactVerifier = GetSubject();
_mockFileSystem.File.ReadAllText(Arg.Any<string>()).Returns("{}");
pactVerifier
.ProviderState("My Provider State")
.ProviderState("My Provider State 2");
pactVerifier.ServiceProvider("Event API", httpClient)
.HonoursPactWith("My client")
.PactUri("/test.json");
pactVerifier.Verify();
_mockProviderServiceValidator.Received(1).Validate(
Arg.Any<ProviderServicePactFile>(),
(pactVerifier as PactVerifier).ProviderStates);
}
}
}
| mvdbuuse/pact-net | PactNet.Tests/PactVerifierTests.cs | C# | mit | 27,525 |
<?php
/*
* This file is part of the TraitorBundle, an RunOpenCode project.
*
* (c) 2017 RunOpenCode
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace RunOpenCode\Bundle\Traitor\Traits;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
/**
* Class EventDispatcherAwareTrait
*
* @package RunOpenCode\Bundle\Traitor\Traits
*
* @codeCoverageIgnore
*/
trait EventDispatcherAwareTrait
{
/**
* @var EventDispatcherInterface
*/
protected $eventDispatcher;
public function setEventDispatcher(EventDispatcherInterface $eventDispatcher)
{
$this->eventDispatcher = $eventDispatcher;
}
}
| RunOpenCode/traitor-bundle | src/RunOpenCode/Bundle/Traitor/Traits/EventDispatcherAwareTrait.php | PHP | mit | 734 |
let path = require('path');
let glob = require('glob');
let fs = require('fs');
let net = require('net');
let webpack = require('webpack');
let HtmlWebpackPlugin = require('html-webpack-plugin');
let ExtractTextPlugin = require('extract-text-webpack-plugin');
let slash = require('slash');
let autoprefixer = require("autoprefixer");
function getPath(projectPath, ...otherPath) {
return path.join(projectPath, ...otherPath);
}
function fixFileLoaderPath(path) {
return process.env.NODE_ENV === 'development' ? path : '/' + path;
}
function addEntry(directory, ext, entries, chunks, entryName) {
let entry = path.join(directory, `index.${ext}`);
if (fs.existsSync(entry)) {
entryName = slash(entryName).replace(/\//g, '_')
entries[entryName] = `${entry}?__webpack__`;
chunks.push(entryName)
}
}
function buildEntriesAndPlugins(projectPath, userConfig) {
let commonChunks = {};
let vendors = [];
let plugins = [];
(userConfig.vendors || []).forEach((vendor, key) => {
let row = vendor.dependencies;
if (row instanceof Array) {
row.forEach(function (value, key) {
row[key] = value.replace(/\[project\]/gi, projectPath);
});
} else if (row instanceof String) {
row = row.replace(/\[project\]/gi, projectPath);
}
commonChunks[vendor.name] = row;
vendors.push(vendor.name);
});
let entries = Object.assign({}, commonChunks);
//html webpack plugin
glob.sync(getPath(projectPath, 'src', 'app', '**', '*.html')).forEach(function (file) {
let fileParser = path.parse(file);
let entryName = path.relative(getPath(projectPath, 'src', 'app'), fileParser.dir);
let chunks = [...vendors];
addEntry(fileParser.dir, 'js', entries, chunks, entryName);
// addEntry(fileParser.dir, 'less', entries, chunks, entryName);
plugins.push(new HtmlWebpackPlugin({
template: file,
inject: true,
chunks: chunks,
filename: getPath(projectPath, 'dist', userConfig.pagePath || '', `${entryName}.html`),
favicon: path.join(projectPath, 'src', 'assets', 'images', 'favorite.ico')
}))
});
//common chunks plugin
plugins.push(new webpack.optimize.CommonsChunkPlugin({
names: vendors
}));
return {
entries,
plugins
}
}
function getStyleLoaders(ext, options, userConfig) {
const cssLoaders = {
loader: 'css-loader',
options: {
importLoaders: 1
}
};
const postCssLoader = {
loader: 'postcss-loader',
options: {
plugins: [
autoprefixer({
browsers: userConfig.postCss.browsers,
add: true,
remove: true
})
]
}
};
return [{
test: new RegExp(`\.${ext}$`),
include: [
path.join(options.projectPath, 'src')
],
exclude: [
path.join(options.projectPath, 'node_modules'),
path.join(options.cliPath, 'node_modules')
],
oneOf: [{
issuer: /\.js$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [cssLoaders, {
loader: 'sprite-loader'
}, postCssLoader].concat(ext === 'css' ? [] : [{
loader: `${ext}-loader`
}])
})
}, {
issuer: /\.(html|tpl)$/,
oneOf: [
{
resourceQuery: /inline/,
use: [{
loader: 'style-loader'
}, cssLoaders, {
loader: 'sprite-loader'
}, postCssLoader].concat(ext === 'css' ? [] : [{
loader: `${ext}-loader`
}])
},
{
use: [{
loader: 'file-loader',
options: {
name: fixFileLoaderPath(`styles/[name]_${ext}.[hash:8].css`)
}
}, {
loader: 'extract-loader'
}, cssLoaders, {
loader: 'sprite-loader'
}, postCssLoader].concat(ext === 'css' ? [] : [{
loader: `${ext}-loader`
}])
}
]
}]
}];
}
function getScriptLoaders(options) {
let babelLoaderConfig = {
loader: 'babel-loader',
options: {
presets: [
require('babel-preset-react')
]
}
};
return [{
test: /\.js/,
include: [path.join(options.projectPath, 'src')],
exclude: [path.join(options.projectPath, 'node_modules'), path.join(options.cliPath, 'node_modules')],
oneOf: [{
issuer: /\.(html|tpl)$/,
oneOf: [{
resourceQuery: /source/,
use: [{
loader: 'file-loader',
options: {
name: fixFileLoaderPath('scripts/[name].[hash:8].js')
}
}]
}, {
use: [{
loader: 'entry-loader',
options: {
name: fixFileLoaderPath('scripts/[name].[hash:8].js'),
projectPath: options.projectPath
}
}, babelLoaderConfig]
}]
}, {
use: [babelLoaderConfig]
}]
}, {
test: /\.jsx$/,
use: [babelLoaderConfig]
}];
}
function throttle(fn, interval = 300) {
let canRun = true;
return function () {
if (!canRun) return;
canRun = false;
setTimeout(() => {
fn.apply(this, arguments);
canRun = true;
}, interval);
};
}
module.exports = {
getPath,
buildEntriesAndPlugins,
getStyleLoaders,
getScriptLoaders,
fixFileLoaderPath,
throttle
}; | IveChen/saber-cli | build/util.js | JavaScript | mit | 6,228 |
<?php
/**
* UserFrosting (http://www.userfrosting.com)
*
* @link https://github.com/userfrosting/UserFrosting
* @license https://github.com/userfrosting/UserFrosting/blob/master/licenses/UserFrosting.md (MIT License)
*/
namespace UserFrosting\Sprinkle\Core\Throttle;
/**
* ThrottleRule Class
*
* Represents a request throttling rule.
* @author Alex Weissman (https://alexanderweissman.com)
*/
class ThrottleRule
{
/** @var string Set to 'ip' for ip-based throttling, 'data' for request-data-based throttling. */
protected $method;
/** @var int The amount of time, in seconds, to look back in determining attempts to consider. */
protected $interval;
/**
* @var int[] A mapping of minimum observation counts (x) to delays (y), in seconds.
* Any throttleable event that has occurred more than x times in this rule's interval,
* must wait y seconds after the last occurrence before another attempt is permitted.
*/
protected $delays;
/**
* Create a new ThrottleRule object.
*
* @param string $method Set to 'ip' for ip-based throttling, 'data' for request-data-based throttling.
* @param int $interval The amount of time, in seconds, to look back in determining attempts to consider.
* @param int[] $delays A mapping of minimum observation counts (x) to delays (y), in seconds.
*/
public function __construct($method, $interval, $delays)
{
$this->setMethod($method);
$this->setInterval($interval);
$this->setDelays($delays);
}
/**
* Get the current delay on this rule for a particular number of event counts.
*
* @param Carbon\Carbon $lastEventTime The timestamp for the last countable event.
* @param int $count The total number of events which have occurred in an interval.
*/
public function getDelay($lastEventTime, $count)
{
// Zero occurrences always maps to a delay of 0 seconds.
if ($count == 0) {
return 0;
}
foreach ($this->delays as $observations => $delay) {
// Skip any delay rules for which we haven't met the requisite number of observations
if ($count < $observations) {
continue;
}
// If this rule meets the observed number of events, and violates the required delay, then return the remaining time left
if ($lastEventTime->diffInSeconds() < $delay) {
return $lastEventTime->addSeconds($delay)->diffInSeconds();
}
}
return 0;
}
/**
* Gets the current mapping of attempts (int) to delays (seconds).
*
* @return int[]
*/
public function getDelays()
{
return $this->delays;
}
/**
* Gets the current throttling interval (seconds).
*
* @return int
*/
public function getInterval()
{
return $this->interval;
}
/**
* Gets the current throttling method ('ip' or 'data').
*
* @return string
*/
public function getMethod()
{
return $this->method;
}
/**
* Sets the current mapping of attempts (int) to delays (seconds).
*
* @param int[] A mapping of minimum observation counts (x) to delays (y), in seconds.
*/
public function setDelays($delays)
{
// Sort the array by key, from highest to lowest value
$this->delays = $delays;
krsort($this->delays);
return $this;
}
/**
* Sets the current throttling interval (seconds).
*
* @param int The amount of time, in seconds, to look back in determining attempts to consider.
*/
public function setInterval($interval)
{
$this->interval = $interval;
return $this;
}
/**
* Sets the current throttling method ('ip' or 'data').
*
* @param string Set to 'ip' for ip-based throttling, 'data' for request-data-based throttling.
*/
public function setMethod($method)
{
$this->method = $method;
return $this;
}
}
| splitt3r/UserFrosting | app/sprinkles/core/src/Throttle/ThrottleRule.php | PHP | mit | 4,106 |
import java.util.ArrayList;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.List;
/**
* Created by liuxz on 17-3-19.
*/
public class Leet54SpiralMatrix {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new ArrayList<>();
int n = matrix.length;
if (n == 0){
return res;
}
int m = matrix[0].length;
int left =0;
int right = m-1;
int up = 0;
int down = n-1;
while(true){
for(int i = left ; i <= right ; i ++){
res.add(matrix[up][i]);
}
if (res.size() == m*n){break;}
up ++;
for (int i = up; i <= down ; i ++){
res.add(matrix[i][right]);
}
if (res.size() == m*n){break;}
right --;
for (int i = right; i >= left; i --){
res.add(matrix[down][i]);
}
if (res.size() == m*n){break;}
down -- ;
for (int i = down; i >= up ; i --){
res.add(matrix[i][left]);
}
if (res.size() == m*n){break;}
left ++;
}
return res;
}
public static void main(String[] args){
Leet54SpiralMatrix xx = new Leet54SpiralMatrix();
int[][] input = new int[][]{
// new int[]{1,2,3},
// new int[]{4,5,6},
// new int[]{7,8,9},
// new int[]{10,11,12}
};
System.out.println(xx.spiralOrder(input));
}
}
| LiuXiaozeeee/OnlineJudge | src/Leet54SpiralMatrix.java | Java | mit | 1,600 |
<?php
require_once("support/config.php");
if(!isLoggedIn()){
toLogin();
die();
}
if(!AllowUser(array(1))){
redirect("index.php");
}
$to_do="";
// var_dump($_GET['id']);
// die;
if(!empty($_GET['id'])){
$to_do=$con->myQuery("SELECT ev.stat_id,ev.event_stat,ev.atype_id,ev.activity_type,ev.priority_id,ev.priority,ev.location,ev.event_place,ev.description,ev.subjects,DATE(ev.start_date) AS start_date,TIME(ev.start_date) AS start_time,DATE(ev.end_date) AS end_date,TIME(ev.start_date) AS end_time,ev.opp_name,ev.assigned_to,ev.due_date,ev.id FROM vw_calendar ev WHERE ev.is_deleted=0 AND ev.id=?",array($_GET['id']))->fetch(PDO::FETCH_ASSOC);
if(empty($to_do)){
redirect("calendar_list.php");
die();
}
}
$to_do_stat=$con->myQuery("SELECT id,name FROM event_status where type=1 or type=3")->fetchAll(PDO::FETCH_ASSOC);
$activity_type=$con->myQuery("SELECT id,name FROM act_types")->fetchAll(PDO::FETCH_ASSOC);
$org_name=$con->myQuery("SELECT id,org_name FROM organizations")->fetchAll(PDO::FETCH_ASSOC);
$prod=$con->myQuery("SELECT id,product_name,unit_price from products")->fetchAll(PDO::FETCH_ASSOC);
$prior=$con->myQuery("SELECT id,name FROM priorities")->fetchAll(PDO::FETCH_ASSOC);
$contact=$con->myQuery("SELECT id,CONCAT(fname,' ',lname) as name from contacts")->fetchAll(PDO::FETCH_ASSOC);
$user=$con->myQuery("SELECT id,CONCAT(last_name,' ',first_name,' ',middle_name) as name FROM users")->fetchAll(PDO::FETCH_ASSOC);
makeHead("Calendar");
?>
<?php
require_once("template/header.php");
require_once("template/sidebar.php");
?>
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Create New To Do
</h1>
</section>
<!-- Main content -->
<section class="content">
<!-- Main row -->
<div class="row">
<div class='col-md-10 col-md-offset-1'>
<?php
Alert();
?>
<div class="box box-primary">
<div class="box-body">
<div class="row">
<div class='col-sm-12 col-md-8 col-md-offset-1'>
<form class='form-horizontal' method='POST' action='save_to_do.php'>
<input type='hidden' name='id' value='<?php echo !empty($to_do)?$to_do['id']:""?>'>
<!-- <input type='hidden' name='to_do_id' value='<?php echo $to_do['id']?>'> -->
<div class='form-group'>
<label for="" class="col-sm-4 control-label"> Subject *</label>
<div class='col-sm-8'>
<input type='text' class='form-control' name='subject' placeholder='Enter Subject Name' value='<?php echo !empty($to_do)?$to_do['subjects']:"" ?>' required>
</div>
</div>
<div class="form-group">
<label for="" class="col-sm-4 control-label">Start Date*</label>
<div class="col-sm-8">
<?php
$start_date="";
if(!empty($to_do)){
$start_date=$to_do['start_date'];
if($start_date=="0000-00-00"){
$start_date="";
}
}
?>
<input type='date' class='form-control' name='start_date' value='<?php echo $start_date; ?>' required>
</div>
<label for="" class="col-sm-4 control-label">Time*</label>
<div class="col-sm-3">
<input type="time" class="form-control" value='<?php echo !empty($to_do)?$to_do['start_time']:"" ?>' id="until_t" name="start_time" required/>
</div>
</div>
<div class="form-group">
<label for="" class="col-sm-4 control-label">Due Date*</label>
<div class="col-sm-8">
<?php
$due_date="";
if(!empty($to_do)){
$due_date=$to_do['due_date'];
if($due_date=="0000-00-00"){
$due_date="";
}
}
?>
<input type='date' class='form-control' name='due_date' value='<?php echo $due_date; ?>' required>
</div>
</div>
<div class='form-group'>
<label for="" class="col-md-4 control-label">Status*</label>
<div class="col-sm-8">
<select class='form-control' name='status' data-placeholder="Select an option" <?php echo!(empty($to_do))?"data-selected='".$to_do['stat_id']."'":NULL ?> required>
<?php
echo makeOptions($to_do_stat,'Select Contact Name',NULL,'',!(empty($to_do))?$to_do['stat_id']:NULL)
?>
</select>
</div>
</div>
<!-- <div class='form-group'>
<label class='col-sm-4 control-label' > User *</label>
<div class='col-sm-6'>
<div class='row'>
<div class='col-sm-11'>
<select id="disabledSelect" class='form-control' name='assigned_to' data-placeholder="Select a user" <?php echo!(empty($opportunity))?"data-selected='".$opportunity['assigned_to']."'":"data-selected='".$_SESSION[WEBAPP]['user']['id']."'" ?> required>
<?php
echo makeOptions($user);
?>
</select>
</div>
<?php
if($_SESSION[WEBAPP]['user']['user_type']==1):
?>
<div class='col-ms-1'>
<a href='frm_users.php' class='btn btn-sm btn-success'><span class='fa fa-plus'></span></a>
</div>
<?php
endif;
?>
</div>
</div>
</div> -->
<div class='form-group'>
<label class='col-sm-4 control-label' > Priority</label>
<div class='col-sm-8'>
<select class='form-control' name='priority' data-placeholder="Select an option" <?php echo!(empty($to_do))?"data-selected='".$event['priority_id']."'":NULL ?>>
<?php
echo makeOptions($prior,'Select Contact Name',NULL,'',!(empty($to_do))?$to_do['priority_id']:NULL)
?>
</select>
</div>
</div>
<div class='form-group'>
<label for="" class="col-sm-4 control-label"> Location</label>
<div class='col-sm-8'>
<input type='text' class='form-control' name='event_place' placeholder='Enter Location' value='<?php echo !empty($to_do)?$to_do['event_place']:"" ?>'>
</div>
</div>
<div class='form-group'>
<label for="" class="col-sm-4 control-label"> Description</label>
<div class='col-sm-8'>
<textarea class='form-control' placeholder="Enter Description" name='description' value=''><?php echo !empty($to_do)?$to_do['description']:"" ?></textarea>
</div>
</div>
<div class='form-group'>
<div class='col-sm-12 col-md-9 col-md-offset-3 '>
<a href='calendar_list.php' class='btn btn-default'>Cancel</a>
<button type='submit' class='btn btn-brand'> <span class='fa fa-check'></span> Save</button>
</div>
</div>
</form>
</div>
</div><!-- /.row -->
</div><!-- /.box-body -->
</div><!-- /.box -->
</div>
</div><!-- /.row -->
</section><!-- /.content -->
</div>
<script type="text/javascript">
$(function () {
$('#ResultTable').DataTable();
});
</script>
<?php
makeFoot();
?> | sgtsi-jenny/crmv2 | frm_to_do.php | PHP | mit | 10,845 |
import React from 'react';
import { Image, Text, View } from 'react-native';
import Example from '../../shared/example';
const Spacer = () => <View style={{ height: '1rem' }} />;
const Heading = ({ children }) => (
<Text
accessibilityRole="heading"
children={children}
style={{ fontSize: '1rem', fontWeight: 'bold', marginBottom: '0.5rem' }}
/>
);
function Color() {
return (
<View>
<Heading>color</Heading>
<Text style={{ color: 'red' }}>Red color</Text>
<Text style={{ color: 'blue' }}>Blue color</Text>
</View>
);
}
function FontFamily() {
return (
<View>
<Heading>fontFamily</Heading>
<Text style={{ fontFamily: 'Cochin' }}>Cochin</Text>
<Text
style={{
fontFamily: 'Cochin',
fontWeight: 'bold'
}}
>
Cochin bold
</Text>
<Text style={{ fontFamily: 'Helvetica' }}>Helvetica</Text>
<Text style={{ fontFamily: 'Helvetica', fontWeight: 'bold' }}>Helvetica bold</Text>
<Text style={{ fontFamily: 'Verdana' }}>Verdana</Text>
<Text
style={{
fontFamily: 'Verdana',
fontWeight: 'bold'
}}
>
Verdana bold
</Text>
</View>
);
}
function FontSize() {
return (
<View>
<Heading>fontSize</Heading>
<Text style={{ fontSize: 23 }}>Size 23</Text>
<Text style={{ fontSize: 8 }}>Size 8</Text>
</View>
);
}
function FontStyle() {
return (
<View>
<Heading>fontStyle</Heading>
<Text style={{ fontStyle: 'normal' }}>Normal text</Text>
<Text style={{ fontStyle: 'italic' }}>Italic text</Text>
</View>
);
}
function FontVariant() {
return (
<View>
<Heading>fontVariant</Heading>
<Text style={{ fontVariant: ['small-caps'] }}>Small Caps{'\n'}</Text>
<Text
style={{
fontVariant: ['oldstyle-nums']
}}
>
Old Style nums 0123456789{'\n'}
</Text>
<Text
style={{
fontVariant: ['lining-nums']
}}
>
Lining nums 0123456789{'\n'}
</Text>
<Text style={{ fontVariant: ['tabular-nums'] }}>
Tabular nums{'\n'}
1111{'\n'}
2222{'\n'}
</Text>
<Text style={{ fontVariant: ['proportional-nums'] }}>
Proportional nums{'\n'}
1111{'\n'}
2222{'\n'}
</Text>
</View>
);
}
function FontWeight() {
return (
<View>
<Heading>fontWeight</Heading>
<Text style={{ fontSize: 20, fontWeight: '100' }}>Move fast and be ultralight</Text>
<Text style={{ fontSize: 20, fontWeight: '200' }}>Move fast and be light</Text>
<Text style={{ fontSize: 20, fontWeight: 'normal' }}>Move fast and be normal</Text>
<Text style={{ fontSize: 20, fontWeight: 'bold' }}>Move fast and be bold</Text>
<Text style={{ fontSize: 20, fontWeight: '900' }}>Move fast and be ultrabold</Text>
</View>
);
}
function LetterSpacing() {
return (
<View>
<Heading>letterSpacing</Heading>
<Text style={{ letterSpacing: 0 }}>letterSpacing = 0</Text>
<Text style={{ letterSpacing: 2, marginTop: 5 }}>letterSpacing = 2</Text>
<Text style={{ letterSpacing: 9, marginTop: 5 }}>letterSpacing = 9</Text>
<View style={{ flexDirection: 'row' }}>
<Text style={{ fontSize: 12, letterSpacing: 2, backgroundColor: 'fuchsia', marginTop: 5 }}>
With size and background color
</Text>
</View>
<Text style={{ letterSpacing: -1, marginTop: 5 }}>letterSpacing = -1</Text>
<Text style={{ letterSpacing: 3, backgroundColor: '#dddddd', marginTop: 5 }}>
[letterSpacing = 3]
<Text style={{ letterSpacing: 0, backgroundColor: '#bbbbbb' }}>
[Nested letterSpacing = 0]
</Text>
<Text style={{ letterSpacing: 6, backgroundColor: '#eeeeee' }}>
[Nested letterSpacing = 6]
</Text>
</Text>
</View>
);
}
function LineHeight() {
return (
<View>
<Heading>lineHeight</Heading>
<Text style={{ lineHeight: 35 }}>
A lot of space should display between the lines of this long passage as they wrap across
several lines. A lot of space should display between the lines of this long passage as they
wrap across several lines.
</Text>
</View>
);
}
function TextAlign() {
return (
<View>
<Heading>textAlign</Heading>
<Text>auto (default) - english LTR</Text>
<Text>
{'\u0623\u062D\u0628 \u0627\u0644\u0644\u063A\u0629 ' +
'\u0627\u0644\u0639\u0631\u0628\u064A\u0629 auto (default) - arabic ' +
'RTL'}
</Text>
<Text style={{ textAlign: 'left' }}>
left left left left left left left left left left left left left left left
</Text>
<Text style={{ textAlign: 'center' }}>
center center center center center center center center center center center
</Text>
<Text style={{ textAlign: 'right' }}>
right right right right right right right right right right right right right
</Text>
<Text style={{ textAlign: 'justify' }}>
justify: this text component{"'"}s contents are laid out with "textAlign: justify" and as
you can see all of the lines except the last one span the available width of the parent
container.
</Text>
</View>
);
}
function TextDecoration() {
return (
<View>
<Heading>textDecoration</Heading>
<Text
style={{
textDecorationLine: 'underline',
textDecorationStyle: 'solid'
}}
>
Solid underline
</Text>
<Text
style={{
textDecorationLine: 'underline',
textDecorationStyle: 'double',
textDecorationColor: '#ff0000'
}}
>
Double underline with custom color
</Text>
<Text
style={{
textDecorationLine: 'underline',
textDecorationStyle: 'dashed',
textDecorationColor: '#9CDC40'
}}
>
Dashed underline with custom color
</Text>
<Text
style={{
textDecorationLine: 'underline',
textDecorationStyle: 'dotted',
textDecorationColor: 'blue'
}}
>
Dotted underline with custom color
</Text>
<Text style={{ textDecorationLine: 'none' }}>None textDecoration</Text>
<Text
style={{
textDecorationLine: 'line-through',
textDecorationStyle: 'solid'
}}
>
Solid line-through
</Text>
<Text
style={{
textDecorationLine: 'line-through',
textDecorationStyle: 'double',
textDecorationColor: '#ff0000'
}}
>
Double line-through with custom color
</Text>
<Text
style={{
textDecorationLine: 'line-through',
textDecorationStyle: 'dashed',
textDecorationColor: '#9CDC40'
}}
>
Dashed line-through with custom color
</Text>
<Text
style={{
textDecorationLine: 'line-through',
textDecorationStyle: 'dotted',
textDecorationColor: 'blue'
}}
>
Dotted line-through with custom color
</Text>
<Text style={{ textDecorationLine: 'underline line-through' }}>
Both underline and line-through
</Text>
</View>
);
}
function TextShadow() {
return (
<View>
<Heading>textShadow*</Heading>
<Text
style={{
fontSize: 20,
textShadowOffset: { width: 2, height: 2 },
textShadowRadius: 1,
textShadowColor: '#00cccc'
}}
>
Text shadow example
</Text>
</View>
);
}
function LineExample({ description, children }) {
return (
<View style={{ marginTop: 20 }}>
<Text style={{ color: 'gray', marginBottom: 5 }}>{description}</Text>
<View
style={{
borderWidth: 2,
borderColor: 'black',
width: 200
}}
>
{children}
</View>
</View>
);
}
export default function TextPage() {
return (
<Example title="Text">
<View style={{ maxWidth: 500 }}>
<Text>
Text wraps across multiple lines by default. Text wraps across multiple lines by default.
Text wraps across multiple lines by default. Text wraps across multiple lines by default.
</Text>
<Spacer />
<Text>
(Text inherits styles from parent Text elements,
<Text style={{ fontWeight: 'bold' }}>
{'\n '}
(for example this text is bold
<Text style={{ fontSize: 11, color: '#527fe4' }}>
{'\n '}
(and this text inherits the bold while setting size and color)
</Text>
{'\n '})
</Text>
{'\n'})
</Text>
<Spacer />
<Text style={{ opacity: 0.7 }}>
(Text opacity
<Text>
{'\n '}
(is inherited
<Text style={{ opacity: 0.7 }}>
{'\n '}
(and accumulated
<Text style={{ backgroundColor: '#ffaaaa' }}>
{'\n '}
(and also applies to the background)
</Text>
{'\n '})
</Text>
{'\n '})
</Text>
{'\n'})
</Text>
<Spacer />
<Text>
This text contains an inline blue view{' '}
<View style={{ width: 25, height: 25, backgroundColor: 'steelblue' }} /> and an inline
image{' '}
<Image
source={{ uri: 'http://lorempixel.com/30/11' }}
style={{ width: 30, height: 11, resizeMode: 'cover' }}
/>
.
</Text>
<Spacer />
<Text>
This text contains a view{' '}
<View style={{ borderColor: 'red', borderWidth: 1 }}>
<Text style={{ borderColor: 'blue', borderWidth: 1 }}>which contains</Text>
<Text style={{ borderColor: 'green', borderWidth: 1 }}>another text.</Text>
<Text style={{ borderColor: 'yellow', borderWidth: 1 }}>
And contains another view
<View style={{ borderColor: 'red', borderWidth: 1 }}>
<Text style={{ borderColor: 'blue', borderWidth: 1 }}>
which contains another text!
</Text>
</View>
</Text>
</View>{' '}
And then continues as text.
</Text>
<Text selectable={true}>
This text is <Text style={{ fontWeight: 'bold' }}>selectable</Text> if you click-and-hold.
</Text>
<Text selectable={false}>
This text is <Text style={{ fontWeight: 'bold' }}>not selectable</Text> if you
click-and-hold.
</Text>
<View style={{ paddingVertical: 20 }}>
<LineExample description="With no line breaks, text is limited to 2 lines.">
<Text numberOfLines={2}>
{
'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'
}
</Text>
</LineExample>
<LineExample description="With line breaks, text is limited to 2 lines.">
<Text numberOfLines={2}>
{
'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\nUt enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.\nDuis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.\nExcepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'
}
</Text>
</LineExample>
<LineExample description="With no line breaks, text is limited to 1 line.">
<Text numberOfLines={1}>
{
'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'
}
</Text>
</LineExample>
<LineExample description="With line breaks, text is limited to 1 line.">
<Text numberOfLines={1}>
{
'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\nUt enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.\nDuis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.\nExcepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'
}
</Text>
</LineExample>
<LineExample description="With very long word, text is limited to 1 line and long word is truncated.">
<Text numberOfLines={1}>goal aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa</Text>
</LineExample>
<LineExample description="With space characters within adjacent truncated lines">
<View style={{ display: 'flex', flexDirection: 'row' }}>
<Text numberOfLines={1}>
<Text>Spaces </Text>
<Text>between</Text>
<Text> words</Text>
</Text>
</View>
<View style={{ display: 'flex', flexDirection: 'row' }}>
<Text>Spaces </Text>
<Text>between</Text>
<Text> words</Text>
</View>
</LineExample>
</View>
<View>
<Color />
<Spacer />
<FontFamily />
<Spacer />
<FontSize />
<Spacer />
<FontStyle />
<Spacer />
<FontVariant />
<Spacer />
<FontWeight />
<Spacer />
<LetterSpacing />
<Spacer />
<LineHeight />
<Spacer />
<TextAlign />
<Spacer />
<TextDecoration />
<Spacer />
<TextShadow />
</View>
</View>
</Example>
);
}
| necolas/react-native-web | packages/examples/pages/text/index.js | JavaScript | mit | 15,012 |
package org.wycliffeassociates.translationrecorder.project;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Created by sarabiaj on 4/17/2017.
*/
public class TakeInfo implements Parcelable {
ProjectSlugs mSlugs;
int mChapter;
int mStartVerse;
int mEndVerse;
int mTake;
public TakeInfo(ProjectSlugs slugs, int chapter, int startVerse, int endVerse, int take) {
mSlugs = slugs;
mChapter = chapter;
mStartVerse = startVerse;
mEndVerse = endVerse;
mTake = take;
}
public TakeInfo(ProjectSlugs slugs, String chapter, String startVerse, String endVerse, String take) {
mSlugs = slugs;
//If there is only one chapter in the book, set default the chapter to 1
if(chapter != null && !chapter.equals("")) {
mChapter = Integer.parseInt(chapter);
} else {
mChapter = 1;
}
mStartVerse = Integer.parseInt(startVerse);
if(endVerse != null) {
mEndVerse = Integer.parseInt(endVerse);
} else {
mEndVerse = -1;
}
if(take != null) {
mTake = Integer.parseInt(take);
} else {
mTake = 0;
}
}
public ProjectSlugs getProjectSlugs() {
return mSlugs;
}
public int getChapter() {
return mChapter;
}
public int getStartVerse() {
return mStartVerse;
}
public int getTake() {
return mTake;
}
public int getEndVerse() {
//if there is no end verse, there is no verse range, so the end verse is the start verse
if(mEndVerse == -1) {
return mStartVerse;
}
return mEndVerse;
}
// public String getNameWithoutTake() {
// if (mSlugs.anthology != null && mSlugs.anthology.compareTo("obs") == 0) {
// return mSlugs.language + "_obs_c" + String.format("%02d", mChapter) + "_v" + String.format("%02d", mStartVerse);
// } else {
// String name;
// String end = (mEndVerse != -1 && mStartVerse != mEndVerse) ? String.format("-%02d", mEndVerse) : "";
// if (mSlugs.book.compareTo("psa") == 0 && mChapter != 119) {
// name = mSlugs.language + "_" + mSlugs.version + "_b" + String.format("%02d", mSlugs.bookNumber) + "_" + mSlugs.book + "_c" + String.format("%03d", mChapter) + "_v" + String.format("%02d", mStartVerse) + end;
// } else if (mSlugs.book.compareTo("psa") == 0) {
// end = (mEndVerse != -1) ? String.format("-%03d", mEndVerse) : "";
// name = mSlugs.language + "_" + mSlugs.version + "_b" + String.format("%02d", mSlugs.bookNumber) + "_" + mSlugs.book + "_c" + ProjectFileUtils.chapterIntToString(mSlugs.book, mChapter) + "_v" + String.format("%03d", mStartVerse) + end;
// } else {
// name = mSlugs.language + "_" + mSlugs.version + "_b" + String.format("%02d", mSlugs.bookNumber) + "_" + mSlugs.book + "_c" + ProjectFileUtils.chapterIntToString(mSlugs.book, mChapter) + "_v" + String.format("%02d", mStartVerse) + end;
// }
// return name;
// }
// }
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeParcelable(mSlugs, flags);
dest.writeInt(mChapter);
dest.writeInt(mStartVerse);
dest.writeInt(mEndVerse);
dest.writeInt(mTake);
}
public static final Parcelable.Creator<TakeInfo> CREATOR = new Parcelable.Creator<TakeInfo>() {
public TakeInfo createFromParcel(Parcel in) {
return new TakeInfo(in);
}
public TakeInfo[] newArray(int size) {
return new TakeInfo[size];
}
};
public TakeInfo(Parcel in) {
mSlugs = in.readParcelable(ProjectSlugs.class.getClassLoader());
mChapter = in.readInt();
mStartVerse = in.readInt();
mEndVerse = in.readInt();
mTake = in.readInt();
}
// @Override
// public boolean equals(Object takeInfo){
// if(takeInfo == null) {
// return false;
// }
// if(!(takeInfo instanceof TakeInfo)) {
// return false;
// } else {
// return (getProjectSlugs().equals(((TakeInfo) takeInfo).getProjectSlugs())
// && getChapter() == ((TakeInfo) takeInfo).getChapter()
// && getStartVerse() == ((TakeInfo) takeInfo).getStartVerse()
// && getEndVerse() == ((TakeInfo) takeInfo).getEndVerse()
// && getTake() == ((TakeInfo) takeInfo).getTake());
// }
// }
public boolean equalBaseInfo(TakeInfo takeInfo) {
if(takeInfo == null) {
return false;
}
if(!(takeInfo instanceof TakeInfo)) {
return false;
} else {
return (getProjectSlugs().equals(takeInfo.getProjectSlugs())
&& getChapter() == takeInfo.getChapter()
&& getStartVerse() == takeInfo.getStartVerse()
&& getEndVerse() == takeInfo.getEndVerse());
}
}
}
| WycliffeAssociates/translationRecorder | translationRecorder/app/src/main/java/org/wycliffeassociates/translationrecorder/project/TakeInfo.java | Java | mit | 5,206 |
def ReadLines(filename):
content = []
with open(filename) as f:
content = [x.rstrip() for x in f.readlines()]
return content
| aawc/cryptopals | sets/1/challenges/common/read_lines.py | Python | mit | 136 |
const ACCOUNTS = [
'all',
'default',
'kai-tfsa',
'kai-rrsp',
'kai-spouse-rrsp',
'kai-non-registered',
'kai-charles-schwab',
'crystal-non-registered',
'crystal-tfsa',
'crystal-rrsp',
'crystal-spouse-rrsp'
];
export default ACCOUNTS; | kaiguogit/growfolio | client/src/constants/accounts.js | JavaScript | mit | 276 |
package charlotte.tools;
import java.util.Arrays;
import java.util.List;
public class QueueData<T> {
private LinkNode<T> _top;
private LinkNode<T> _last;
private int _count;
public QueueData(T[] entries) {
this(Arrays.asList(entries));
}
public QueueData(List<T> entries) {
this();
for(T entry : entries) {
add(entry);
}
}
public QueueData() {
_top = new LinkNode<T>();
_last = _top;
}
public void add(T element) {
_last.element = element;
_last.next = new LinkNode<T>();
_last = _last.next;
_count++;
}
public T poll() {
if(_count <= 0) {
return null;
}
T ret = _top.element;
_top = _top.next;
_count--;
return ret;
}
public int size() {
return _count;
}
private class LinkNode<U> {
public U element;
public LinkNode<U> next;
}
public void clear() {
_top = new LinkNode<T>();
_last = _top;
_count = 0;
}
public ValueStore<T> toValueStore() {
return new ValueStore<T>() {
@Override
public T get() {
return poll();
}
@Override
public void set(T element) {
add(element);
}
};
}
}
| stackprobe/Java | charlotte/tools/QueueData.java | Java | mit | 1,092 |
using Nucleus.Logs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Nucleus.Game
{
/// <summary>
/// Interface for components, status effects, items etc. that
/// modify critical hit chance
/// </summary>
public interface ICritChanceModifier
{
/// <summary>
/// Modify a critical success chance
/// </summary>
/// <param name="critChance"></param>
/// <returns></returns>
double ModifyCritChance(double critChance, IActionLog log, EffectContext context);
}
}
| pnjeffries/Nucleus | Nucleus/Nucleus.Game/Components/ICritChanceModifier.cs | C# | mit | 617 |