prompt large_stringlengths 70 991k | completion large_stringlengths 0 1.02k |
|---|---|
<|file_name|>utils.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
#
# Copyright 2016 Pinterest, Inc
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import socket
hostname = socket.gethostname()
<|fim▁hole|>def _escape_path_for_stats_name(path):
# Do some formatting the file path.
if path is None:
return None
if path.startswith("/"):
path = path[1:]
return path.replace("/", "_")
class DummyStatsdClient:
def __init__(self, *args, **kwargs):
pass
def increment(self, stats, sample_rate=1, tags={}):
pass
def gauge(self, stats, value, sample_rate=1, tags={}):
pass
dummy_statsd = DummyStatsdClient()<|fim▁end|> | |
<|file_name|>pydev_runfiles_pytest2.py<|end_file_name|><|fim▁begin|>from _pydev_runfiles import pydev_runfiles_xml_rpc
import pickle
import zlib
import base64
import os
from pydevd_file_utils import canonical_normalized_path
import pytest
import sys
import time
try:
from pathlib import Path
except:
Path = None
#=========================================================================
# Load filters with tests we should skip
#=========================================================================
py_test_accept_filter = None
def _load_filters():
global py_test_accept_filter
if py_test_accept_filter is None:
py_test_accept_filter = os.environ.get('PYDEV_PYTEST_SKIP')
if py_test_accept_filter:
py_test_accept_filter = pickle.loads(
zlib.decompress(base64.b64decode(py_test_accept_filter)))
if Path is not None:
# Newer versions of pytest resolve symlinks, so, we
# may need to filter with a resolved path too.
new_dct = {}
for filename, value in py_test_accept_filter.items():
new_dct[canonical_normalized_path(str(Path(filename).resolve()))] = value
py_test_accept_filter.update(new_dct)
else:
py_test_accept_filter = {}
def is_in_xdist_node():
main_pid = os.environ.get('PYDEV_MAIN_PID')
if main_pid and main_pid != str(os.getpid()):
return True
return False
connected = False
def connect_to_server_for_communication_to_xml_rpc_on_xdist():
global connected
if connected:
return
connected = True
if is_in_xdist_node():
port = os.environ.get('PYDEV_PYTEST_SERVER')
if not port:
sys.stderr.write(
'Error: no PYDEV_PYTEST_SERVER environment variable defined.\n')
else:
pydev_runfiles_xml_rpc.initialize_server(int(port), daemon=True)
PY2 = sys.version_info[0] <= 2
PY3 = not PY2
class State:
start_time = time.time()
buf_err = None
buf_out = None
def start_redirect():
if State.buf_out is not None:
return
from _pydevd_bundle import pydevd_io
State.buf_err = pydevd_io.start_redirect(keep_original_redirection=True, std='stderr')
State.buf_out = pydevd_io.start_redirect(keep_original_redirection=True, std='stdout')
def get_curr_output():
buf_out = State.buf_out
buf_err = State.buf_err
return buf_out.getvalue() if buf_out is not None else '', buf_err.getvalue() if buf_err is not None else ''
def pytest_unconfigure():
if is_in_xdist_node():
return
# Only report that it finished when on the main node (we don't want to report
# the finish on each separate node).
pydev_runfiles_xml_rpc.notifyTestRunFinished(
'Finished in: %.2f secs.' % (time.time() - State.start_time,))
def pytest_collection_modifyitems(session, config, items):
# A note: in xdist, this is not called on the main process, only in the
# secondary nodes, so, we'll actually make the filter and report it multiple
# times.
connect_to_server_for_communication_to_xml_rpc_on_xdist()
_load_filters()
if not py_test_accept_filter:
pydev_runfiles_xml_rpc.notifyTestsCollected(len(items))
return # Keep on going (nothing to filter)
new_items = []
for item in items:
f = canonical_normalized_path(str(item.parent.fspath))
name = item.name
if f not in py_test_accept_filter:
# print('Skip file: %s' % (f,))
continue # Skip the file
i = name.find('[')
name_without_parametrize = None
if i > 0:
name_without_parametrize = name[:i]
accept_tests = py_test_accept_filter[f]
if item.cls is not None:
class_name = item.cls.__name__
else:
class_name = None
for test in accept_tests:
if test == name:
# Direct match of the test (just go on with the default
# loading)
new_items.append(item)
break
if name_without_parametrize is not None and test == name_without_parametrize:
# This happens when parameterizing pytest tests on older versions
# of pytest where the test name doesn't include the fixture name
<|fim▁hole|> new_items.append(item)
break
if class_name is not None:
if test == class_name + '.' + name:
new_items.append(item)
break
if name_without_parametrize is not None and test == class_name + '.' + name_without_parametrize:
new_items.append(item)
break
if class_name == test:
new_items.append(item)
break
else:
pass
# print('Skip test: %s.%s. Accept: %s' % (class_name, name, accept_tests))
# Modify the original list
items[:] = new_items
pydev_runfiles_xml_rpc.notifyTestsCollected(len(items))
try:
"""
pytest > 5.4 uses own version of TerminalWriter based on py.io.TerminalWriter
and assumes there is a specific method TerminalWriter._write_source
so try load pytest version first or fallback to default one
"""
from _pytest._io import TerminalWriter
except ImportError:
from py.io import TerminalWriter
def _get_error_contents_from_report(report):
if report.longrepr is not None:
try:
tw = TerminalWriter(stringio=True)
stringio = tw.stringio
except TypeError:
import io
stringio = io.StringIO()
tw = TerminalWriter(file=stringio)
tw.hasmarkup = False
report.toterminal(tw)
exc = stringio.getvalue()
s = exc.strip()
if s:
return s
return ''
def pytest_collectreport(report):
error_contents = _get_error_contents_from_report(report)
if error_contents:
report_test('fail', '<collect errors>', '<collect errors>', '', error_contents, 0.0)
def append_strings(s1, s2):
if s1.__class__ == s2.__class__:
return s1 + s2
if sys.version_info[0] == 2:
if not isinstance(s1, basestring):
s1 = str(s1)
if not isinstance(s2, basestring):
s2 = str(s2)
# Prefer bytes
if isinstance(s1, unicode):
s1 = s1.encode('utf-8')
if isinstance(s2, unicode):
s2 = s2.encode('utf-8')
return s1 + s2
else:
# Prefer str
if isinstance(s1, bytes):
s1 = s1.decode('utf-8', 'replace')
if isinstance(s2, bytes):
s2 = s2.decode('utf-8', 'replace')
return s1 + s2
def pytest_runtest_logreport(report):
if is_in_xdist_node():
# When running with xdist, we don't want the report to be called from the node, only
# from the main process.
return
report_duration = report.duration
report_when = report.when
report_outcome = report.outcome
if hasattr(report, 'wasxfail'):
if report_outcome != 'skipped':
report_outcome = 'passed'
if report_outcome == 'passed':
# passed on setup/teardown: no need to report if in setup or teardown
# (only on the actual test if it passed).
if report_when in ('setup', 'teardown'):
return
status = 'ok'
elif report_outcome == 'skipped':
status = 'skip'
else:
# It has only passed, skipped and failed (no error), so, let's consider
# error if not on call.
if report_when in ('setup', 'teardown'):
status = 'error'
else:
# any error in the call (not in setup or teardown) is considered a
# regular failure.
status = 'fail'
# This will work if pytest is not capturing it, if it is, nothing will
# come from here...
captured_output, error_contents = getattr(report, 'pydev_captured_output', ''), getattr(report, 'pydev_error_contents', '')
for type_section, value in report.sections:
if value:
if type_section in ('err', 'stderr', 'Captured stderr call'):
error_contents = append_strings(error_contents, value)
else:
captured_output = append_strings(error_contents, value)
filename = getattr(report, 'pydev_fspath_strpath', '<unable to get>')
test = report.location[2]
if report_outcome != 'skipped':
# On skipped, we'll have a traceback for the skip, which is not what we
# want.
exc = _get_error_contents_from_report(report)
if exc:
if error_contents:
error_contents = append_strings(error_contents, '----------------------------- Exceptions -----------------------------\n')
error_contents = append_strings(error_contents, exc)
report_test(status, filename, test, captured_output, error_contents, report_duration)
def report_test(status, filename, test, captured_output, error_contents, duration):
'''
@param filename: 'D:\\src\\mod1\\hello.py'
@param test: 'TestCase.testMet1'
@param status: fail, error, ok
'''
time_str = '%.2f' % (duration,)
pydev_runfiles_xml_rpc.notifyTest(
status, captured_output, error_contents, filename, test, time_str)
if not hasattr(pytest, 'hookimpl'):
raise AssertionError('Please upgrade pytest (the current version of pytest: %s is unsupported)' % (pytest.__version__,))
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
outcome = yield
report = outcome.get_result()
report.pydev_fspath_strpath = item.fspath.strpath
report.pydev_captured_output, report.pydev_error_contents = get_curr_output()
@pytest.mark.tryfirst
def pytest_runtest_setup(item):
'''
Note: with xdist will be on a secondary process.
'''
# We have our own redirection: if xdist does its redirection, we'll have
# nothing in our contents (which is OK), but if it does, we'll get nothing
# from pytest but will get our own here.
start_redirect()
filename = item.fspath.strpath
test = item.location[2]
pydev_runfiles_xml_rpc.notifyStartTest(filename, test)<|fim▁end|> | # in it.
|
<|file_name|>class.spellEffects.junglecreatures.js<|end_file_name|><|fim▁begin|>spellEffects[ 'junglecreatures' ] = function( args )
{
var self = this,
_ccd = Component.bugcraft.currentCharacterObject.characterData,
_moveFrames = {},
_tc = args.targetCharacter,
_tcd = _tc.characterData,
_changeFrameFunctionPointer = null,
_currentIndex = 1,
_maxFrames = 1,
_backgroundSound = null;
this.ID = spellEffects.layer[0].push( this ) - 1;
this.characterSpellEffectID = _tc._internal.spellEffects.push( this ) - 1;
this.offsetX = 20;
this.offsetY = 20;
this.rotation = _tcd.character_rotation;
this.deleteRange = 40;
this.previousX = _tcd.character_zone_x - this.offsetX;
this.previousY = _tcd.character_zone_y - this.offsetY;
// initialize
var _soundLoop = function()
{
_backgroundSound = Application.sound.playExclusive({
url: '/components/bugcraft/resources/public/component.bugcraft.spellEffects/sounds/junglecreatures/junglecreatures.mp3',
volume: spellEffects.volumeByRangeVoice(
_ccd.character_zone_x,
_ccd.character_zone_y,
_tcd.character_zone_x,
_tcd.character_zone_y,
spellEffects.volumeRangeLong
),
onFinish: function()
{
_soundLoop();
<|fim▁hole|> }
// for(var i=1;i<=_maxFrames;i++)
// {
// _moveFrames[ i ] = { image: new Image(), alpha: 0 };
// _moveFrames[ i ].image.src = '/components/bugcraft/resources/public/component.bugcraft.spellEffects/images/junglecreatures/junglecreatures' + i + '.png';
// }
//draw the bombardierBeetleDeath spatter
this.draw = function()
{
// Map.ctx.save();
// Map.ctx.translate( self.previousX + self.offsetX + Map.viewPortX, self.previousY + self.offsetY + Map.viewPortY );
// Map.ctx.rotate( ( self.rotation - 90 ) * Math.PI / 180 );
// Map.ctx.shadowColor = 'rgba(0, 0, 0, 0.7)';
// Map.ctx.shadowOffsetX = 3;
// Map.ctx.shadowOffsetY = 3;
// Map.ctx.drawImage(
// _moveFrames[ _currentIndex ].image,
// - self.offsetX,
// - self.offsetY
// );
// Map.ctx.restore();
// Map.ctx.globalAlpha = 1;
}
//remove the deathDecay
this.remove = function()
{
clearTimeout( _changeFrameFunctionPointer );
if( _backgroundSound )
{
_backgroundSound.stop();
}
spellEffects.layerCleaner.push( this );
spellEffects.layer[0][ this.ID ] = null;
delete _tc._internal.spellEffects[ this.characterSpellEffectID ];
}
var _changeFrameFunction = function()
{
_currentIndex++;
if( _currentIndex > _maxFrames )
{
_currentIndex = 1;
setTimeout( _changeFrameFunction, 2000 + Math.random() * 5000 );
return;
}
_changeFrameFunctionPointer = setTimeout( _changeFrameFunction, 100 );
}
_soundLoop();
// _changeFrameFunction();
} //end bombardierBeetleDeath<|fim▁end|> | }
});
|
<|file_name|>routes.js<|end_file_name|><|fim▁begin|>var indexController = require('./controllers/cIndex');
var usuarioController = require('./controllers/cUsuario');
var clientesController = require('./controllers/cCliente');
var adminController = require('./controllers/cAdmin');
var umedController = require('./controllers/cUmed');
var matepController = require('./controllers/cMatep');
var empleController = require('./controllers/cEmple');
var accesosController = require('./controllers/cAccesos');
var cargoController = require('./controllers/cCargos');
var reactoController = require('./controllers/cReacto');
var lineasController = require('./controllers/cLineas');
var prodController = require('./controllers/cProd');
var envasesController = require('./controllers/cEnvases');
var tanquesController = require('./controllers/cTanques');
var ubicaController = require('./controllers/cUbica');
var recetaController = require('./controllers/cReceta');
var remitosController = require('./controllers/cRemitos');
var progController = require('./controllers/cProgramacion');
var FormEnReactorController = require('./controllers/cFormEnReactor');
var labController = require('./controllers/cLab');
var formController = require('./controllers/cFormulados');
var mEventos = require('./models/mEventos');
var consuController = require('./controllers/cConsumibles');
var produccionController = require('./controllers/cProduccion');
var fraccionadoController = require('./controllers/cFraccionado');
var aprobacionController = require('./controllers/cAprobacion');
var navesController = require('./controllers/cNaves');
var mapaController = require('./controllers/cMapa');
function logout (req, res) {
fecha = new Date();
day = fecha.getDate();
month = fecha.getMonth();
if (day<10)
day = "0" + day;
if (month<10)
month = "0" + month;
fecha = fecha.getFullYear() + "/"+month+"/"+day+" "+fecha.getHours()+":"+fecha.getMinutes()
mEventos.add(req.session.user.unica, fecha, "Logout", "", function(){
});
req.session = null;
return res.redirect('/');
}
// Verifica que este logueado
function auth (req, res, next) {
if (req.session.auth) {
return next();
} else {
console.log("dentro del else del auth ")
return res.redirect('/')
}
}
module.exports = function(app) {
app.get('/', adminController.getLogin);
app.get('/login', adminController.getLogin)
app.post('/login', adminController.postLogin);
app.get('/logout', logout);
app.get('/inicio', auth, indexController.getInicio);
app.get('/error', indexController.getError);
//ayuda
app.get('/ayuda', indexController.getAyuda);
app.get('/ayudaver/:id', indexController.AyudaVer);<|fim▁hole|> app.get('/usuariosalta', auth, usuarioController.getUsuariosAlta);
app.post('/usuariosalta', auth, usuarioController.putUsuario);
app.get('/usuariosmodificar/:id', auth, usuarioController.getUsuarioModificar);
app.post('/usuariosmodificar', auth, usuarioController.postUsuarioModificar);
app.get('/usuariosborrar/:id', auth, usuarioController.getDelUsuario);
//configurar accesos
app.get('/accesoslista/:id', auth, accesosController.getAccesos);
app.post('/accesoslista', auth, accesosController.postAccesos);
//clientes
app.get('/clienteslista', auth, clientesController.getClientes);
app.get('/clientesalta', auth, clientesController.getClientesAlta);
app.post('/clientesalta', auth, clientesController.putCliente);
app.get('/clientesmodificar/:id', auth, clientesController.getClienteModificar);
app.post('/clientesmodificar', auth, clientesController.postClienteModificar);
app.get('/clientesborrar/:id', auth, clientesController.getDelCliente);
app.get('/:cliente/materiasprimas', auth, clientesController.getMatep);
//unidades de medida "umed"
app.get('/umedlista', auth, umedController.getAllUmed);
app.get('/umedalta', auth, umedController.getAlta);
app.post('/umedalta', auth, umedController.postAlta);
app.get('/umedmodificar/:id', auth, umedController.getModificar);
app.post('/umedactualizar', auth, umedController.postModificar);
app.get('/umedborrar/:id', auth, umedController.getDelUmed);
//materias primas por cliente
app.get('/mateplista/:cdcliente', auth, matepController.getAllMatepPorCliente);
app.get('/matepalta/:cdcliente', auth, matepController.getAlta);
app.post('/matepalta', auth, matepController.postAlta);
app.get('/matepmodificar/:id', auth, matepController.getModificar);
app.post('/matepmodificar', auth, matepController.postModificar);
app.get('/matepborrar/:id', auth, matepController.getDelMatep);
//cantidad maxima en tanque por matep
app.get('/formenreactor/:id', auth, FormEnReactorController.getFormEnReactor);
app.get('/formenreactoralta/:idform', auth, FormEnReactorController.getAlta);
app.post('/formenreactoralta', auth, FormEnReactorController.postAlta);
app.get('/formenreactormodificar/:id', auth, FormEnReactorController.getModificar);
app.post('/formenreactormodificar', auth, FormEnReactorController.postModificar);
app.get('/formenreactorborrar/:id', auth, FormEnReactorController.del);
//producto por clientereactor
app.get('/prodlista/:cdcliente', auth, prodController.getAllProdPorCliente);
app.get('/prodalta/:cdcliente', auth, prodController.getAlta);
app.post('/prodalta', auth, prodController.postAlta);
app.get('/prodmodificar/:id', auth, prodController.getModificar);
app.post('/prodmodificar', auth, prodController.postModificar);
app.get('/prodborrar/:id', auth, prodController.getDelProd);
app.get('/:idprod/ablote', auth, prodController.getAbLote);
//empleados
app.get('/emplelista', auth, empleController.getEmpleados);
app.get('/emplealta', auth, empleController.getAlta);
app.post('/emplealta', auth, empleController.postAlta);
app.get('/emplemodificar/:codigo', auth, empleController.getModificar);
app.post('/emplemodificar', auth, empleController.postModificar);
app.get('/empleborrar/:codigo', auth, empleController.getDelEmple);
//cargos de empleados
app.get('/cargoslista', auth, cargoController.getAllCargos);
app.get('/cargosalta', auth, cargoController.getAlta);
app.post('/cargosalta', auth, cargoController.postAlta);
app.get('/cargosmodificar/:id', auth, cargoController.getModificar);
app.post('/cargosmodificar', auth, cargoController.postModificar);
app.get('/cargosborrar/:id', auth, cargoController.getDelCargo);
//reactores
app.get('/reactolista', auth, reactoController.getAll);
app.get('/reactoalta', auth, reactoController.getAlta);
app.post('/reactoalta', auth, reactoController.postAlta);
app.get('/reactomodificar/:id', auth, reactoController.getModificar);
app.post('/reactomodificar', auth, reactoController.postModificar);
app.get('/reactoborrar/:id', auth, reactoController.getDel);
//lineas
app.get('/lineaslista', auth, lineasController.getAll);
app.get('/lineasalta', auth, lineasController.getAlta);
app.post('/lineasalta', auth, lineasController.postAlta);
app.get('/lineasmodificar/:id', auth, lineasController.getModificar);
app.post('/lineasmodificar', auth, lineasController.postModificar);
app.get('/lineasborrar/:id', auth, lineasController.getDel);
//envases
app.get('/envaseslista', auth, envasesController.getAll);
app.get('/envasesalta', auth, envasesController.getAlta);
app.post('/envasesalta', auth, envasesController.postAlta);
app.get('/envasesmodificar/:id', auth, envasesController.getModificar);
app.post('/envasesmodificar', auth, envasesController.postModificar);
app.get('/envasesborrar/:id', auth, envasesController.getDel);
app.get('/capacidadenvase/:id', auth, envasesController.getCapacidad);
//tanques
app.get('/tanqueslista', auth, tanquesController.getAll);
app.get('/tanquesalta', auth, tanquesController.getAlta);
app.post('/tanquesalta', auth, tanquesController.postAlta);
app.get('/tanquesmodificar/:id', auth, tanquesController.getModificar);
app.post('/tanquesmodificar', auth, tanquesController.postModificar);
app.get('/tanquesborrar/:id', auth, tanquesController.getDel);
//ubicaciones "ubica"
app.get('/ubicalista', auth, ubicaController.getAll);
app.get('/ubicaalta', auth, ubicaController.getAlta);
app.post('/ubicaalta', auth, ubicaController.postAlta);
app.get('/ubicamodificar/:id', auth, ubicaController.getModificar);
app.post('/ubicamodificar', auth, ubicaController.postModificar);
app.get('/ubicaborrar/:id', auth, ubicaController.getDel);
//recetas
app.get('/recetalista/:id', auth, recetaController.getRecetaPorFormulado);
app.get('/recetaalta/:id', auth, recetaController.getAlta);
app.post('/recetaalta', auth, recetaController.postAlta);
app.get('/recetaborrar/:id', auth, recetaController.getDel);
app.get('/recetamodificar/:id', auth, recetaController.getModificar);
app.post('/recetamodificar', auth, recetaController.postModificar);
//remitos
app.get('/remitoslista', auth, remitosController.getAll);
app.get('/remitosalta', auth, remitosController.getAlta);
app.post('/remitosalta', auth, remitosController.postAlta);
app.get('/remitosmodificar/:id', auth, remitosController.getModificar);
app.post('/remitosmodificar', auth, remitosController.postModificar);
app.get('/remitosborrar/:id', auth, remitosController.getDel);
app.get('/buscarremito/:finicio/:ffin', auth, remitosController.getRemitos);
//programacion
app.get('/prog1lista', auth, progController.getAll);
app.get('/prog1alta', auth, progController.getAlta);
app.post('/prog1alta', auth, progController.postAlta);
app.get('/prog2lista', auth, progController.getLista);
app.get('/prog1alta2/:idprog', auth, progController.getAlta2);
app.post('/prog1alta2', auth, progController.postAlta2);
app.get('/prog1/:lote/:anio/:clienteid/:prodid', auth, progController.getCodigo);
app.get('/prog1borrar/:id', auth, progController.getDel);
app.get('/refrescaremito/:idcliente/:idmatep', auth, progController.getRemitos);
app.get('/traerpa/:idform', auth, progController.getPA);
app.get('/buscarprogramaciones/:fecha', auth, progController.getProgramaciones);
app.get('/produccionborrarprogram/:id', auth, progController.getDelProgram);
//laboratorio
app.get('/lab/:idremito', auth, labController.getLab);
app.post('/lab', auth, labController.postLab);
//formulados
app.get('/formuladoalta/:cdcliente', auth, formController.getAlta);
app.post('/formuladoalta', auth, formController.postAlta);
app.get('/formuladolista/:cdcliente', auth, formController.getAllFormuladoPorCliente);
app.get('/formuladomodificar/:id', auth, formController.getModificar);
app.post('/formuladomodificar', auth, formController.postModificar);
app.get('/formuladoborrar/:id', auth, formController.getDelFormulado);
app.get('/:id/formulados', auth, formController.getForms);
app.get('/:idform/ablotee', auth, formController.getAbLote);
//consumibles
app.get('/consumibleslista/:idprod', auth, consuController.getAll);
app.get('/consumiblesalta/:idprod', auth, consuController.getAlta);
app.post('/consumiblesalta', auth, consuController.postAlta);
app.get('/consumiblesborrar/:id', auth, consuController.getDel);
//produccion
app.get('/produccionlista', auth, produccionController.getLista);
app.get('/buscarprogramaciones2/:fi/:ff', auth, produccionController.getProgramaciones);
app.get('/produccionver/:id', auth, produccionController.getVerFormulado);
app.post('/produccionver', auth, produccionController.postDatosFormulado);
app.get('/produccionimprimir/:id', auth, produccionController.getImprimir);
//borrar
//fraccionado
app.get('/fraccionadolista', auth, fraccionadoController.getLista);
app.get('/fraccionadoalta/:id', auth, fraccionadoController.getAlta);
app.post('/fraccionadoalta', auth, fraccionadoController.postAlta);
app.get('/fraccionadomodificar/:id', auth, fraccionadoController.getModificar);
app.post('/fraccionadomodificar', auth, fraccionadoController.postModificar);
//borrar?
//aprobacion
app.get('/aprobacionlista', auth, aprobacionController.getLista);
app.get('/aprobacionver/:id', auth, aprobacionController.getVer);
app.post('/aprobacionver', auth, aprobacionController.postVer);
app.get('/aprobacionimprimir/:id', auth, aprobacionController.getImprimir);
//naves
app.get('/naveslista', auth, navesController.getLista);
//mapa
app.get('/mapaver', auth, mapaController.getMapa);
};<|fim▁end|> | //novedades
app.get('/listanovedades', indexController.getNovedades);
//usuarios
app.get('/usuarioslista', auth, usuarioController.getUsuarios); |
<|file_name|>setup.py<|end_file_name|><|fim▁begin|>from setuptools import setup<|fim▁hole|>def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name="martapy",
version=martapy.__version__,
author=martapy.__author__,
author_email="git@edward.sh",
description="Wrapper for MARTA realtime rail/bus APIs",
long_description=read('README.rst'),
keywords="MARTA API rail train Atlanta Georgia GA ATL itsmarta",
url="https://github.com/arcward/fbparser",
license="MIT",
packages=['martapy'],
install_requires=['requests'],
include_package_data=True
)<|fim▁end|> | import os
import martapy
|
<|file_name|>widget.js<|end_file_name|><|fim▁begin|>(function ($, _, Backbone, models) {
"use strict";
<|fim▁hole|> "update_interval": '10'
},
url: function() {
var tmp = "/api/dashboards/" + this.get("dashboard_id") + "/widgets";
if (this.isNew()) {
return tmp;
} else {
return tmp + "/" + this.get("id");
}
},
targetsString: function() {
return (this.get("targets") || "").split(';');
}
});
})($, _, Backbone, app.models);<|fim▁end|> | models.Widget = Backbone.Model.extend({
defaults: {
"name" : "Undefined name",
"range" : '30-minutes', |
<|file_name|>home.py<|end_file_name|><|fim▁begin|>import logging
import secrets
from typing import List, Optional, Tuple
from django.conf import settings
from django.http import HttpRequest, HttpResponse
from django.shortcuts import redirect, render
from django.utils.cache import patch_cache_control
from zerver.context_processors import get_valid_realm_from_request
from zerver.decorator import web_public_view, zulip_login_required
from zerver.forms import ToSForm
from zerver.lib.actions import do_change_tos_version, realm_user_count
from zerver.lib.compatibility import is_outdated_desktop_app, is_unsupported_browser
from zerver.lib.home import build_page_params_for_home_page_load, get_user_permission_info
from zerver.lib.request import RequestNotes
from zerver.lib.streams import access_stream_by_name
from zerver.lib.subdomains import get_subdomain
from zerver.lib.utils import statsd
from zerver.models import PreregistrationUser, Realm, Stream, UserProfile
from zerver.views.portico import hello_view
def need_accept_tos(user_profile: Optional[UserProfile]) -> bool:
if user_profile is None:
return False
if settings.TERMS_OF_SERVICE is None: # nocoverage
return False
if settings.TOS_VERSION is None:
return False
return int(settings.TOS_VERSION.split(".")[0]) > user_profile.major_tos_version()
@zulip_login_required
def accounts_accept_terms(request: HttpRequest) -> HttpResponse:
assert request.user.is_authenticated
if request.method == "POST":
form = ToSForm(request.POST)
if form.is_valid():
do_change_tos_version(request.user, settings.TOS_VERSION)
return redirect(home)
else:
form = ToSForm()
email = request.user.delivery_email
special_message_template = None
if request.user.tos_version is None and settings.FIRST_TIME_TOS_TEMPLATE is not None:
special_message_template = "zerver/" + settings.FIRST_TIME_TOS_TEMPLATE
return render(
request,
"zerver/accounts_accept_terms.html",
context={
"form": form,
"email": email,
"special_message_template": special_message_template,
},
)
def detect_narrowed_window(
request: HttpRequest, user_profile: Optional[UserProfile]
) -> Tuple[List[List[str]], Optional[Stream], Optional[str]]:
"""This function implements Zulip's support for a mini Zulip window
that just handles messages from a single narrow"""
if user_profile is None:
return [], None, None
narrow: List[List[str]] = []
narrow_stream = None
narrow_topic = request.GET.get("topic")
if request.GET.get("stream"):
try:
# TODO: We should support stream IDs and PMs here as well.
narrow_stream_name = request.GET.get("stream")
(narrow_stream, ignored_sub) = access_stream_by_name(user_profile, narrow_stream_name)
narrow = [["stream", narrow_stream.name]]
except Exception:
logging.warning("Invalid narrow requested, ignoring", extra=dict(request=request))
if narrow_stream is not None and narrow_topic is not None:
narrow.append(["topic", narrow_topic])
return narrow, narrow_stream, narrow_topic
def update_last_reminder(user_profile: Optional[UserProfile]) -> None:
"""Reset our don't-spam-users-with-email counter since the
user has since logged in
"""
if user_profile is None:
return
if user_profile.last_reminder is not None: # nocoverage
# TODO: Look into the history of last_reminder; we may have
# eliminated that as a useful concept for non-bot users.
user_profile.last_reminder = None
user_profile.save(update_fields=["last_reminder"])
def home(request: HttpRequest) -> HttpResponse:
if not settings.ROOT_DOMAIN_LANDING_PAGE:
return home_real(request)
# If settings.ROOT_DOMAIN_LANDING_PAGE, sends the user the landing
# page, not the login form, on the root domain
subdomain = get_subdomain(request)
if subdomain != Realm.SUBDOMAIN_FOR_ROOT_DOMAIN:
return home_real(request)
return hello_view(request)
@web_public_view
def home_real(request: HttpRequest) -> HttpResponse:
# Before we do any real work, check if the app is banned.
client_user_agent = request.META.get("HTTP_USER_AGENT", "")
(insecure_desktop_app, banned_desktop_app, auto_update_broken) = is_outdated_desktop_app(
client_user_agent
)
if banned_desktop_app:
return render(
request,
"zerver/insecure_desktop_app.html",
context={
"auto_update_broken": auto_update_broken,
},
)
(unsupported_browser, browser_name) = is_unsupported_browser(client_user_agent)
if unsupported_browser:
return render(
request,
"zerver/unsupported_browser.html",
context={
"browser_name": browser_name,
},
)
# We need to modify the session object every two weeks or it will expire.
# This line makes reloading the page a sufficient action to keep the
# session alive.
request.session.modified = True
if request.user.is_authenticated:
user_profile = request.user
realm = user_profile.realm
else:
# user_profile=None corresponds to the logged-out "web_public" visitor case.
user_profile = None
realm = get_valid_realm_from_request(request)
update_last_reminder(user_profile)
statsd.incr("views.home")
# If a user hasn't signed the current Terms of Service, send them there
if need_accept_tos(user_profile):
return accounts_accept_terms(request)
narrow, narrow_stream, narrow_topic = detect_narrowed_window(request, user_profile)
if user_profile is not None:
first_in_realm = realm_user_count(user_profile.realm) == 1
# If you are the only person in the realm and you didn't invite
# anyone, we'll continue to encourage you to do so on the frontend.
prompt_for_invites = (
first_in_realm
and not PreregistrationUser.objects.filter(referred_by=user_profile).count()<|fim▁hole|> first_in_realm = False
prompt_for_invites = False
# The current tutorial doesn't super make sense for logged-out users.
needs_tutorial = False
queue_id, page_params = build_page_params_for_home_page_load(
request=request,
user_profile=user_profile,
realm=realm,
insecure_desktop_app=insecure_desktop_app,
narrow=narrow,
narrow_stream=narrow_stream,
narrow_topic=narrow_topic,
first_in_realm=first_in_realm,
prompt_for_invites=prompt_for_invites,
needs_tutorial=needs_tutorial,
)
log_data = RequestNotes.get_notes(request).log_data
assert log_data is not None
log_data["extra"] = f"[{queue_id}]"
csp_nonce = secrets.token_hex(24)
user_permission_info = get_user_permission_info(user_profile)
response = render(
request,
"zerver/app/index.html",
context={
"user_profile": user_profile,
"page_params": page_params,
"csp_nonce": csp_nonce,
"color_scheme": user_permission_info.color_scheme,
},
)
patch_cache_control(response, no_cache=True, no_store=True, must_revalidate=True)
return response
@zulip_login_required
def desktop_home(request: HttpRequest) -> HttpResponse:
return redirect(home)<|fim▁end|> | )
needs_tutorial = user_profile.tutorial_status == UserProfile.TUTORIAL_WAITING
else: |
<|file_name|>bind.go<|end_file_name|><|fim▁begin|>package echo
import (
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"net/http"
"reflect"
"strconv"
"strings"
)
type (
// Binder is the interface that wraps the Bind method.
Binder interface {
Bind(i interface{}, c Context) error
}
// DefaultBinder is the default implementation of the Binder interface.
DefaultBinder struct{}
// BindUnmarshaler is the interface used to wrap the UnmarshalParam method.
BindUnmarshaler interface {
// UnmarshalParam decodes and assigns a value from an form or query param.
UnmarshalParam(param string) error
}
)
// Bind implements the `Binder#Bind` function.
func (b *DefaultBinder) Bind(i interface{}, c Context) (err error) {
req := c.Request()
if req.Method == GET {
if err = b.bindData(i, c.QueryParams(), "query"); err != nil {
return NewHTTPError(http.StatusBadRequest, err.Error())
}
return
}
ctype := req.Header.Get(HeaderContentType)
if req.ContentLength == 0 {
return NewHTTPError(http.StatusBadRequest, "Request body can't be empty")
}
switch {
case strings.HasPrefix(ctype, MIMEApplicationJSON):
if err = json.NewDecoder(req.Body).Decode(i); err != nil {
if ute, ok := err.(*json.UnmarshalTypeError); ok {
return NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Unmarshal type error: expected=%v, got=%v, offset=%v", ute.Type, ute.Value, ute.Offset))
} else if se, ok := err.(*json.SyntaxError); ok {
return NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Syntax error: offset=%v, error=%v", se.Offset, se.Error()))
} else {
return NewHTTPError(http.StatusBadRequest, err.Error())
}
}
case strings.HasPrefix(ctype, MIMEApplicationXML), strings.HasPrefix(ctype, MIMETextXML):
if err = xml.NewDecoder(req.Body).Decode(i); err != nil {
if ute, ok := err.(*xml.UnsupportedTypeError); ok {
return NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Unsupported type error: type=%v, error=%v", ute.Type, ute.Error()))
} else if se, ok := err.(*xml.SyntaxError); ok {
return NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Syntax error: line=%v, error=%v", se.Line, se.Error()))
} else {
return NewHTTPError(http.StatusBadRequest, err.Error())
}
}
case strings.HasPrefix(ctype, MIMEApplicationForm), strings.HasPrefix(ctype, MIMEMultipartForm):
params, err := c.FormParams()
if err != nil {
return NewHTTPError(http.StatusBadRequest, err.Error())
}
if err = b.bindData(i, params, "form"); err != nil {
return NewHTTPError(http.StatusBadRequest, err.Error())
}
default:
return ErrUnsupportedMediaType
}
return
}
func (b *DefaultBinder) bindData(ptr interface{}, data map[string][]string, tag string) error {
typ := reflect.TypeOf(ptr).Elem()
val := reflect.ValueOf(ptr).Elem()
if typ.Kind() != reflect.Struct {
return errors.New("Binding element must be a struct")
}
for i := 0; i < typ.NumField(); i++ {
typeField := typ.Field(i)
structField := val.Field(i)
if !structField.CanSet() {
continue
}
structFieldKind := structField.Kind()
inputFieldName := typeField.Tag.Get(tag)
if inputFieldName == "" {
inputFieldName = typeField.Name
// If tag is nil, we inspect if the field is a struct.
if _, ok := bindUnmarshaler(structField); !ok && structFieldKind == reflect.Struct {
err := b.bindData(structField.Addr().Interface(), data, tag)
if err != nil {
return err
}
continue
}
}
inputValue, exists := data[inputFieldName]
if !exists {
continue
}
// Call this first, in case we're dealing with an alias to an array type
if ok, err := unmarshalField(typeField.Type.Kind(), inputValue[0], structField); ok {
if err != nil {
return err
}
continue
}
numElems := len(inputValue)
if structFieldKind == reflect.Slice && numElems > 0 {
sliceOf := structField.Type().Elem().Kind()
slice := reflect.MakeSlice(structField.Type(), numElems, numElems)
for j := 0; j < numElems; j++ {
if err := setWithProperType(sliceOf, inputValue[j], slice.Index(j)); err != nil {
return err
}
}
val.Field(i).Set(slice)
} else {
if err := setWithProperType(typeField.Type.Kind(), inputValue[0], structField); err != nil {
return err
}
}
}
return nil
}
func setWithProperType(valueKind reflect.Kind, val string, structField reflect.Value) error {
// But also call it here, in case we're dealing with an array of BindUnmarshalers
if ok, err := unmarshalField(valueKind, val, structField); ok {
return err
}
switch valueKind {
case reflect.Int:
return setIntField(val, 0, structField)
case reflect.Int8:
return setIntField(val, 8, structField)
case reflect.Int16:
return setIntField(val, 16, structField)
case reflect.Int32:
return setIntField(val, 32, structField)
case reflect.Int64:
return setIntField(val, 64, structField)
case reflect.Uint:
return setUintField(val, 0, structField)
case reflect.Uint8:
return setUintField(val, 8, structField)
case reflect.Uint16:
return setUintField(val, 16, structField)
case reflect.Uint32:
return setUintField(val, 32, structField)
case reflect.Uint64:
return setUintField(val, 64, structField)
case reflect.Bool:
return setBoolField(val, structField)
case reflect.Float32:
return setFloatField(val, 32, structField)
case reflect.Float64:
return setFloatField(val, 64, structField)
case reflect.String:
structField.SetString(val)
default:
return errors.New("unknown type")
}
return nil
}
func unmarshalField(valueKind reflect.Kind, val string, field reflect.Value) (bool, error) {
switch valueKind {
case reflect.Ptr:
return unmarshalFieldPtr(val, field)
default:
return unmarshalFieldNonPtr(val, field)
}
}
// bindUnmarshaler attempts to unmarshal a reflect.Value into a BindUnmarshaler
func bindUnmarshaler(field reflect.Value) (BindUnmarshaler, bool) {
ptr := reflect.New(field.Type())
if ptr.CanInterface() {
iface := ptr.Interface()
if unmarshaler, ok := iface.(BindUnmarshaler); ok {
return unmarshaler, ok
}
}
return nil, false
}
func unmarshalFieldNonPtr(value string, field reflect.Value) (bool, error) {
if unmarshaler, ok := bindUnmarshaler(field); ok {
err := unmarshaler.UnmarshalParam(value)
field.Set(reflect.ValueOf(unmarshaler).Elem())
return true, err
}
return false, nil
}
func unmarshalFieldPtr(value string, field reflect.Value) (bool, error) {
if field.IsNil() {
// Initialize the pointer to a nil value<|fim▁hole|> field.Set(reflect.New(field.Type().Elem()))
}
return unmarshalFieldNonPtr(value, field.Elem())
}
func setIntField(value string, bitSize int, field reflect.Value) error {
if value == "" {
value = "0"
}
intVal, err := strconv.ParseInt(value, 10, bitSize)
if err == nil {
field.SetInt(intVal)
}
return err
}
func setUintField(value string, bitSize int, field reflect.Value) error {
if value == "" {
value = "0"
}
uintVal, err := strconv.ParseUint(value, 10, bitSize)
if err == nil {
field.SetUint(uintVal)
}
return err
}
func setBoolField(value string, field reflect.Value) error {
if value == "" {
value = "false"
}
boolVal, err := strconv.ParseBool(value)
if err == nil {
field.SetBool(boolVal)
}
return err
}
func setFloatField(value string, bitSize int, field reflect.Value) error {
if value == "" {
value = "0.0"
}
floatVal, err := strconv.ParseFloat(value, bitSize)
if err == nil {
field.SetFloat(floatVal)
}
return err
}<|fim▁end|> | |
<|file_name|>Chip.spec.js<|end_file_name|><|fim▁begin|>import Chip from '../../components/Chip'
import { vueTest } from '../utils'
describe('Chip', () => {
let vm
before((done) => {
vm = vueTest(Chip)
vm.$nextTick(done)
})
it('renders with text', () => {
const el = vm.$('#chip')
el.should.contain.text('Basic chip')
el.should.not.have.class('mdl-chip--contact')
el.should.not.have.class('mdl-chip--deletable')
})
it('renders with close button', () => {
const el = vm.$('#delete')
el.should.contain.text('Deletable chip')
el.should.not.have.class('mdl-chip--contact')
el.should.have.class('mdl-chip--deletable')
const action = vm.$('#delete .mdl-chip__action')
action.should.exist
action.should.have.text('cancel')
})
it('has custom icon', (done) => {
const action = vm.$('#delete .mdl-chip__action')
action.should.have.text('cancel')
vm.deleteIcon = 'star'
vm.nextTick()
.then(() => {
action.should.have.text('star')
})
.then(done, done)
})
it('emits close event', (done) => {
vm.deleted.should.be.false
const action = vm.$('#delete .mdl-chip__action')
action.click()
vm.nextTick()
.then(() => {
vm.deleted.should.be.true
vm.deleted = false
return vm.nextTick()
})
.then(done, done)
})
it('renders text inside circle', (done) => {
vm.$('#contact').should.have.class('mdl-chip--contact')
const el = vm.$('#contact .mdl-chip__contact')
el.should.contain.text(vm.contact)
el.should.not.have.class('mdl-chip--deletable')
vm.contact = 'A'
vm.nextTick()<|fim▁hole|> el.should.have.text('A')
})
.then(done, done)
})
it('renders image inside circle', () => {
vm.$('#image').should.have.class('mdl-chip--contact')
const el = vm.$('#image .mdl-chip__contact')
el.should.have.attr('src', 'https://getmdl.io/templates/dashboard/images/user.jpg')
el.should.not.have.class('mdl-chip--deletable')
})
})<|fim▁end|> | .then(() => { |
<|file_name|>bitcoin_fr.ts<|end_file_name|><|fim▁begin|><TS language="fr" version="2.1">
<context>
<name>AddressBookPage</name>
<message>
<source>Right-click to edit address or label</source>
<translation>Cliquer à droite pour modifier l'adresse ou l'étiquette</translation>
</message>
<message>
<source>Create a new address</source>
<translation>Créer une nouvelle adresse</translation>
</message>
<message>
<source>&New</source>
<translation>&Nouveau</translation>
</message>
<message>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Copier l'adresse sélectionnée actuellement dans le presse-papiers</translation>
</message>
<message>
<source>&Copy</source>
<translation>&Copier</translation>
</message>
<message>
<source>C&lose</source>
<translation>&Fermer</translation>
</message>
<message>
<source>Delete the currently selected address from the list</source>
<translation>Supprimer de la liste l'adresse sélectionnée actuellement</translation>
</message>
<message>
<source>Export the data in the current tab to a file</source>
<translation>Exporter les données de l'onglet actuel vers un fichier</translation>
</message>
<message>
<source>&Export</source>
<translation>&Exporter</translation>
</message>
<message>
<source>&Delete</source>
<translation>&Supprimer</translation>
</message>
<message>
<source>Choose the address to send coins to</source>
<translation>Choisir l'adresse à laquelle envoyer des pièces</translation>
</message>
<message>
<source>Choose the address to receive coins with</source>
<translation>Choisir l'adresse avec laquelle recevoir des pîèces</translation>
</message>
<message>
<source>C&hoose</source>
<translation>C&hoisir</translation>
</message>
<message>
<source>Such sending addresses</source>
<translation>Adresses d'envoi</translation>
</message>
<message>
<source>Much receiving addresses</source>
<translation>Adresses de réception</translation>
</message>
<message>
<source>These are your Smartcoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation>Voici vos adresses Smartcoin pour envoyer des paiements. Vérifiez toujours le montant et l'adresse du destinataire avant d'envoyer des pièces.</translation>
</message>
<message>
<source>These are your Smartcoin addresses for receiving payments. It is recommended to use a new receiving address for each transaction.</source>
<translation>Voici vos adresses Smartcoin pour recevoir des paiements. Il est recommandé d'utiliser une nouvelle adresse de réception pour chaque transaction.</translation>
</message>
<message>
<source>&Copy Address</source>
<translation>&Copier l'adresse</translation>
</message>
<message>
<source>Copy &Label</source>
<translation>Copier l'é&tiquette</translation>
</message>
<message>
<source>&Edit</source>
<translation>&Modifier</translation>
</message>
<message>
<source>Export Address List</source>
<translation>Exporter la liste d'adresses</translation>
</message>
<message>
<source>Comma separated file (*.csv)</source>
<translation>Valeurs séparées par des virgules (*.csv)</translation>
</message>
<message>
<source>Exporting Failed</source>
<translation>Échec d'exportation</translation>
</message>
<message>
<source>There was an error trying to save the address list to %1. Please try again.</source>
<translation>Une erreur est survenue lors de l'enregistrement de la liste d'adresses vers %1. Veuillez ressayer plus tard.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<source>Label</source>
<translation>Étiquette</translation>
</message>
<message>
<source>Address</source>
<translation>Adresse</translation>
</message>
<message>
<source>(no label)</source>
<translation>(aucune étiquette)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<source>Passphrase Dialog</source>
<translation>Fenêtre de dialogue de la phrase de passe</translation>
</message>
<message>
<source>Enter passphrase</source>
<translation>Saisir la phrase de passe</translation>
</message>
<message>
<source>New passphrase</source>
<translation>Nouvelle phrase de passe</translation>
</message>
<message>
<source>Repeat new passphrase</source>
<translation>Répéter la phrase de passe</translation>
</message>
<message>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>ten or more random characters</b>, or <b>eight or more words</b>.</source>
<translation>Saisissez la nouvelle phrase de passe du porte-monnaie.<br/>Veuillez utiliser une phrase de passe composée de <b>dix caractères aléatoires ou plus</b>, ou de <b>huit mots ou plus</b>.</translation>
</message>
<message>
<source>Encrypt wallet</source>
<translation>Chiffrer le porte-monnaie</translation>
</message>
<message>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Cette opération nécessite votre phrase de passe pour déverrouiller le porte-monnaie.</translation>
</message>
<message>
<source>Unlock wallet</source>
<translation>Déverrouiller le porte-monnaie</translation>
</message>
<message>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Cette opération nécessite votre phrase de passe pour déchiffrer le porte-monnaie.</translation>
</message>
<message>
<source>Decrypt wallet</source>
<translation>Déchiffrer le porte-monnaie</translation>
</message>
<message>
<source>Change passphrase</source>
<translation>Changer la phrase de passe</translation>
</message>
<message>
<source>Enter the old passphrase and new passphrase to the wallet.</source>
<translation>Saisir l'ancienne puis la nouvelle phrase de passe du porte-monnaie.</translation>
</message>
<message>
<source>Confirm wallet encryption</source>
<translation>Confirmer le chiffrement du porte-monnaie</translation>
</message>
<message>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR SMARTCOINS</b>!</source>
<translation>Avertissement : si vous chiffrez votre porte-monnaie et perdez votre phrase de passe, vous <b>PERDREZ TOUS VOS SMARTCOINS</b> !</translation>
</message>
<message>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>Voulez-vous vraiment chiffrer votre porte-monnaie ?</translation>
</message>
<message>
<source>Wallet encrypted</source>
<translation>Le porte-monnaie est chiffré</translation>
</message>
<message>
<source>%1 will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your smartcoins from being stolen by malware infecting your computer.</source>
<translation>%1 va maintenant se fermer pour terminer le processus de chiffrement. Souvenez-vous que le chiffrement de votre porte-monnaie ne peut pas protéger entièrement vos smartcoins contre le vol par des logiciels malveillants qui infecteraient votre ordinateur.</translation>
</message>
<message>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation>IMPORTANT : toutes les sauvegardes précédentes du fichier de votre porte-monnaie devraient être remplacées par le fichier du porte-monnaie chiffré nouvellement généré. Pour des raisons de sécurité, les sauvegardes précédentes de votre fichier de porte-monnaie non chiffré deviendront inutilisables dès que vous commencerez à utiliser le nouveau porte-monnaie chiffré.</translation>
</message>
<message>
<source>Wallet encryption failed</source>
<translation>Échec de chiffrement du porte-monnaie</translation>
</message>
<message>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Le chiffrement du porte-monnaie a échoué en raison d'une erreur interne. Votre porte-monnaie n'a pas été chiffré.</translation>
</message>
<message>
<source>The supplied passphrases do not match.</source>
<translation>Les phrases de passe saisies ne correspondent pas.</translation>
</message>
<message>
<source>Wallet unlock failed</source>
<translation>Échec de déverrouillage du porte-monnaie</translation>
</message>
<message>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>La phrase de passe saisie pour déchiffrer le porte-monnaie était erronée.</translation>
</message>
<message>
<source>Wallet decryption failed</source>
<translation>Échec de déchiffrement du porte-monnaie</translation>
</message>
<message>
<source>Wallet passphrase was successfully changed.</source>
<translation>La phrase de passe du porte-monnaie a été modifiée avec succès.</translation>
</message>
<message>
<source>Warning: The Caps Lock key is on!</source>
<translation>Avertissement : la touche Verr. Maj. est activée !</translation>
</message>
</context>
<context>
<name>BanTableModel</name>
<message>
<source>IP/Netmask</source>
<translation>IP/masque réseau</translation>
</message>
<message>
<source>Banned Until</source>
<translation>Banni jusqu'au</translation>
</message>
</context>
<context>
<name>SmartcoinGUI</name>
<message>
<source>Sign &message...</source>
<translation>Signer un &message...</translation>
</message>
<message>
<source>Synchronizing with network...</source>
<translation>Synchronisation avec le réseau…</translation>
</message>
<message>
<source>&Overview</source>
<translation>&Vue d'ensemble</translation>
</message>
<message>
<source>Node</source>
<translation>Nœud</translation>
</message>
<message>
<source>Show general overview of wallet</source>
<translation>Afficher une vue d’ensemble du porte-monnaie</translation>
</message>
<message>
<source>&Transactions</source>
<translation>&Transactions</translation>
</message>
<message>
<source>Browse transaction history</source>
<translation>Parcourir l'historique transactionnel</translation>
</message>
<message>
<source>E&xit</source>
<translation>Q&uitter</translation>
</message>
<message>
<source>Quit application</source>
<translation>Quitter l’application</translation>
</message>
<message>
<source>&About %1</source>
<translation>À &propos de %1</translation>
</message>
<message>
<source>Show information about %1</source>
<translation>Afficher des informations à propos de %1</translation>
</message>
<message>
<source>About &Qt</source>
<translation>À propos de &Qt</translation>
</message>
<message>
<source>Show information about Qt</source>
<translation>Afficher des informations sur Qt</translation>
</message>
<message>
<source>&Options...</source>
<translation>&Options…</translation>
</message>
<message>
<source>Modify configuration options for %1</source>
<translation>Modifier les options de configuration de %1</translation>
</message>
<message>
<source>&Encrypt Wallet...</source>
<translation>&Chiffrer le porte-monnaie...</translation>
</message>
<message>
<source>&Backup Wallet...</source>
<translation>Sauvegarder le &porte-monnaie...</translation>
</message>
<message>
<source>&Change Passphrase...</source>
<translation>&Changer la phrase de passe...</translation>
</message>
<message>
<source>Such &sending addresses...</source>
<translation>Adresses d'&envoi...</translation>
</message>
<message>
<source>Much &receiving addresses...</source>
<translation>Adresses de &réception...</translation>
</message>
<message>
<source>Open &URI...</source>
<translation>Ouvrir une &URI...</translation>
</message>
<message>
<source>Click to disable network activity.</source>
<translation>Cliquer pour désactiver l'activité réseau.</translation>
</message>
<message>
<source>Network activity disabled.</source>
<translation>L'activité réseau est désactivée.</translation>
</message>
<message>
<source>Click to enable network activity again.</source>
<translation>Cliquer pour réactiver l'activité réseau.</translation>
</message>
<message>
<source>Syncing Headers (%1%)...</source>
<translation>Synchronisation des en-têtes (%1)...</translation>
</message>
<message>
<source>Reindexing blocks on disk...</source>
<translation>Réindexation des blocs sur le disque...</translation>
</message>
<message>
<source>Send coins to a Smartcoin address</source>
<translation>Envoyer des pièces à une adresse Smartcoin</translation>
</message>
<message>
<source>Backup wallet to another location</source>
<translation>Sauvegarder le porte-monnaie vers un autre emplacement</translation>
</message>
<message>
<source>Change the passphrase used for wallet encryption</source>
<translation>Modifier la phrase de passe utilisée pour le chiffrement du porte-monnaie</translation>
</message>
<message>
<source>&Debug window</source>
<translation>Fenêtre de &débogage</translation>
</message>
<message>
<source>Open debugging and diagnostic console</source>
<translation>Ouvrir une console de débogage et de diagnostic</translation>
</message>
<message>
<source>&Verify message...</source>
<translation>&Vérifier un message...</translation>
</message>
<message>
<source>Smartcoin</source>
<translation>Smartcoin</translation>
</message>
<message>
<source>Wallet</source>
<translation>Porte-monnaie</translation>
</message>
<message>
<source>&Send</source>
<translation>&Envoyer</translation><|fim▁hole|> <message>
<source>&Receive</source>
<translation>&Recevoir</translation>
</message>
<message>
<source>&Show / Hide</source>
<translation>&Afficher / cacher</translation>
</message>
<message>
<source>Show or hide the main Window</source>
<translation>Afficher ou cacher la fenêtre principale</translation>
</message>
<message>
<source>Encrypt the private keys that belong to your wallet</source>
<translation>Chiffrer les clés privées qui appartiennent à votre porte-monnaie</translation>
</message>
<message>
<source>Sign messages with your Smartcoin addresses to prove you own them</source>
<translation>Signer les messages avec vos adresses Smartcoin pour prouver que vous les détenez</translation>
</message>
<message>
<source>Verify messages to ensure they were signed with specified Smartcoin addresses</source>
<translation>Vérifier les messages pour s'assurer qu'ils ont été signés avec les adresses Smartcoin spécifiées</translation>
</message>
<message>
<source>&File</source>
<translation>&Fichier</translation>
</message>
<message>
<source>&Settings</source>
<translation>&Paramètres</translation>
</message>
<message>
<source>&Help</source>
<translation>&Aide</translation>
</message>
<message>
<source>Tabs toolbar</source>
<translation>Barre d'outils des onglets</translation>
</message>
<message>
<source>Request payments (generates QR codes and smartcoin: URIs)</source>
<translation>Demander des paiements (génère des codes QR et des URI smartcoin:)</translation>
</message>
<message>
<source>Show the list of used sending addresses and labels</source>
<translation>Afficher la liste d'adresses d'envoi et d'étiquettes utilisées</translation>
</message>
<message>
<source>Show the list of used receiving addresses and labels</source>
<translation>Afficher la liste d'adresses de réception et d'étiquettes utilisées</translation>
</message>
<message>
<source>Open a smartcoin: URI or payment request</source>
<translation>Ouvrir une URI smartcoin: ou une demande de paiement</translation>
</message>
<message>
<source>&Command-line options</source>
<translation>Options de ligne de &commande</translation>
</message>
<message numerus="yes">
<source>%n active connection(s) to Smartcoin network</source>
<translation><numerusform>%n connexion active avec le réseau Smartcoin</numerusform><numerusform>%n connexions actives avec le réseau Smartcoin</numerusform></translation>
</message>
<message>
<source>Indexing blocks on disk...</source>
<translation>Indexation des blocs sur le disque...</translation>
</message>
<message>
<source>Processing blocks on disk...</source>
<translation>Traitement des blocs sur le disque...</translation>
</message>
<message numerus="yes">
<source>Processed %n block(s) of transaction history.</source>
<translation><numerusform>%n bloc d'historique transactionnel a été traité</numerusform><numerusform>%n blocs d'historique transactionnel ont été traités</numerusform></translation>
</message>
<message>
<source>%1 behind</source>
<translation>en retard de %1</translation>
</message>
<message>
<source>Last received block was generated %1 ago.</source>
<translation>Le dernier bloc reçu avait été généré il y a %1.</translation>
</message>
<message>
<source>Transactions after this will not yet be visible.</source>
<translation>Les transactions suivantes ne seront pas déjà visibles.</translation>
</message>
<message>
<source>Error</source>
<translation>Erreur</translation>
</message>
<message>
<source>Warning</source>
<translation>Avertissement</translation>
</message>
<message>
<source>Information</source>
<translation>Information</translation>
</message>
<message>
<source>Up to date</source>
<translation>À jour</translation>
</message>
<message>
<source>Show the %1 help message to get a list with possible Smartcoin command-line options</source>
<translation>Afficher le message d'aide de %1 pour obtenir la liste des options de ligne de commande Smartcoin possibles.</translation>
</message>
<message>
<source>%1 client</source>
<translation>Client %1</translation>
</message>
<message>
<source>Connecting to peers...</source>
<translation>Connexion aux pairs...</translation>
</message>
<message>
<source>Catching up...</source>
<translation>Rattrapage…</translation>
</message>
<message>
<source>Date: %1
</source>
<translation>Date : %1
</translation>
</message>
<message>
<source>Amount: %1
</source>
<translation>Montant : %1
</translation>
</message>
<message>
<source>Type: %1
</source>
<translation>Type : %1
</translation>
</message>
<message>
<source>Label: %1
</source>
<translation>Étiquette : %1
</translation>
</message>
<message>
<source>Address: %1
</source>
<translation>Adresse : %1
</translation>
</message>
<message>
<source>Sent transaction</source>
<translation>Transaction envoyée</translation>
</message>
<message>
<source>Incoming transaction</source>
<translation>Transaction entrante</translation>
</message>
<message>
<source>HD key generation is <b>enabled</b></source>
<translation>La génération de clé HD est <b>activée</b></translation>
</message>
<message>
<source>HD key generation is <b>disabled</b></source>
<translation>La génération de clé HD est <b>désactivée</b></translation>
</message>
<message>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Le porte-monnaie est <b>chiffré</b> et est actuellement <b>déverrouillé</b></translation>
</message>
<message>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Le porte-monnaie est <b>chiffré</b> et actuellement <b>verrouillé</b></translation>
</message>
<message>
<source>A fatal error occurred. Smartcoin can no longer continue safely and will quit.</source>
<translation>Une erreur fatale est survenue. Smartcoin ne peut plus continuer en toute sécurité et va s'arrêter.</translation>
</message>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<source>Coin Selection</source>
<translation>Sélection des pièces</translation>
</message>
<message>
<source>Quantity:</source>
<translation>Quantité :</translation>
</message>
<message>
<source>Bytes:</source>
<translation>Octets :</translation>
</message>
<message>
<source>Amount:</source>
<translation>Montant :</translation>
</message>
<message>
<source>Fee:</source>
<translation>Frais :</translation>
</message>
<message>
<source>Dust:</source>
<translation>Poussière :</translation>
</message>
<message>
<source>After Fee:</source>
<translation>Après les frais :</translation>
</message>
<message>
<source>Change:</source>
<translation>Monnaie :</translation>
</message>
<message>
<source>(un)select all</source>
<translation>Tout (des)sélectionner</translation>
</message>
<message>
<source>Tree mode</source>
<translation>Mode arborescence</translation>
</message>
<message>
<source>List mode</source>
<translation>Mode liste</translation>
</message>
<message>
<source>Amount</source>
<translation>Montant</translation>
</message>
<message>
<source>Received with label</source>
<translation>Reçu avec une étiquette</translation>
</message>
<message>
<source>Received with address</source>
<translation>Reçu avec une adresse</translation>
</message>
<message>
<source>Date</source>
<translation>Date</translation>
</message>
<message>
<source>Confirmations</source>
<translation>Confirmations</translation>
</message>
<message>
<source>Confirmed</source>
<translation>Confirmée</translation>
</message>
<message>
<source>Copy address</source>
<translation>Copier l’adresse</translation>
</message>
<message>
<source>Copy label</source>
<translation>Copier l’étiquette</translation>
</message>
<message>
<source>Copy amount</source>
<translation>Copier le montant</translation>
</message>
<message>
<source>Copy transaction ID</source>
<translation>Copier l'ID de la transaction</translation>
</message>
<message>
<source>Lock unspent</source>
<translation>Verrouiller les transactions non dépensées</translation>
</message>
<message>
<source>Unlock unspent</source>
<translation>Déverrouiller les transactions non dépensées</translation>
</message>
<message>
<source>Copy quantity</source>
<translation>Copier la quantité</translation>
</message>
<message>
<source>Copy fee</source>
<translation>Copier les frais</translation>
</message>
<message>
<source>Copy after fee</source>
<translation>Copier après les frais</translation>
</message>
<message>
<source>Copy bytes</source>
<translation>Copier les octets</translation>
</message>
<message>
<source>Copy dust</source>
<translation>Copier la poussière</translation>
</message>
<message>
<source>Copy change</source>
<translation>Copier la monnaie</translation>
</message>
<message>
<source>(%1 locked)</source>
<translation>(%1 verrouillée)</translation>
</message>
<message>
<source>yes</source>
<translation>oui</translation>
</message>
<message>
<source>no</source>
<translation>non</translation>
</message>
<message>
<source>This label turns red if any recipient receives an amount smaller than the current dust threshold.</source>
<translation>Cette étiquette devient rouge si un destinataire reçoit un montant inférieur au seuil actuel de poussière.</translation>
</message>
<message>
<source>Can vary +/- %1 koinu(s) per input.</source>
<translation>Peut varier +/- %1 koinu(s) par entrée.</translation>
</message>
<message>
<source>(no label)</source>
<translation>(aucune étiquette)</translation>
</message>
<message>
<source>change from %1 (%2)</source>
<translation>monnaie de %1 (%2)</translation>
</message>
<message>
<source>(change)</source>
<translation>(monnaie)</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<source>Edit Address</source>
<translation>Modifier l'adresse</translation>
</message>
<message>
<source>&Label</source>
<translation>É&tiquette</translation>
</message>
<message>
<source>The label associated with this address list entry</source>
<translation>L'étiquette associée à cette entrée de la liste d'adresses</translation>
</message>
<message>
<source>The address associated with this address list entry. This can only be modified for sending addresses.</source>
<translation>L'adresse associée à cette entrée de la liste d'adresses. Cela ne peut être modifié que pour les adresses d'envoi.</translation>
</message>
<message>
<source>&Address</source>
<translation>&Adresse</translation>
</message>
<message>
<source>New receiving address</source>
<translation>Nouvelle adresse de réception</translation>
</message>
<message>
<source>New sending address</source>
<translation>Nouvelle adresse d’envoi</translation>
</message>
<message>
<source>Edit receiving address</source>
<translation>Modifier l’adresse de réception</translation>
</message>
<message>
<source>Edit sending address</source>
<translation>Modifier l’adresse d'envoi</translation>
</message>
<message>
<source>The entered address "%1" is not a valid Smartcoin address.</source>
<translation>L'adresse saisie « %1 » n'est pas une adresse Smartcoin valide.</translation>
</message>
<message>
<source>The entered address "%1" is already in the address book.</source>
<translation>L’adresse saisie « %1 » est déjà présente dans le carnet d'adresses.</translation>
</message>
<message>
<source>Could not unlock wallet.</source>
<translation>Impossible de déverrouiller le porte-monnaie.</translation>
</message>
<message>
<source>New key generation failed.</source>
<translation>Échec de génération de la nouvelle clé.</translation>
</message>
</context>
<context>
<name>FreespaceChecker</name>
<message>
<source>A new data directory will be created.</source>
<translation>Un nouveau répertoire de données sera créé.</translation>
</message>
<message>
<source>name</source>
<translation>nom</translation>
</message>
<message>
<source>Directory already exists. Add %1 if you intend to create a new directory here.</source>
<translation>Le répertoire existe déjà. Ajouter %1 si vous comptez créer un nouveau répertoire ici.</translation>
</message>
<message>
<source>Path already exists, and is not a directory.</source>
<translation>Le chemin existe déjà et n'est pas un répertoire.</translation>
</message>
<message>
<source>Cannot create data directory here.</source>
<translation>Impossible de créer un répertoire de données ici.</translation>
</message>
</context>
<context>
<name>HelpMessageDialog</name>
<message>
<source>version</source>
<translation>version</translation>
</message>
<message>
<source>(%1-bit)</source>
<translation>(%1-bit)</translation>
</message>
<message>
<source>About %1</source>
<translation>À propos de %1</translation>
</message>
<message>
<source>Command-line options</source>
<translation>Options de ligne de commande</translation>
</message>
<message>
<source>Usage:</source>
<translation>Utilisation :</translation>
</message>
<message>
<source>command-line options</source>
<translation>options de ligne de commande</translation>
</message>
<message>
<source>UI Options:</source>
<translation>Options de l'IU :</translation>
</message>
<message>
<source>Choose data directory on startup (default: %u)</source>
<translation>Choisir un répertoire de données au démarrage (par défaut : %u)</translation>
</message>
<message>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation>Définir la langue, par exemple « fr_CA » (par défaut : la langue du système)</translation>
</message>
<message>
<source>Start minimized</source>
<translation>Démarrer minimisé</translation>
</message>
<message>
<source>Set SSL root certificates for payment request (default: -system-)</source>
<translation>Définir les certificats SSL racine pour les requêtes de paiement (par défaut : -system-)</translation>
</message>
<message>
<source>Show splash screen on startup (default: %u)</source>
<translation>Afficher l'écran d'accueil au démarrage (par défaut : %u)</translation>
</message>
<message>
<source>Reset all settings changed in the GUI</source>
<translation>Réinitialiser tous les paramètres changés dans l'IUG</translation>
</message>
</context>
<context>
<name>Intro</name>
<message>
<source>Welcome</source>
<translation>Bienvenue</translation>
</message>
<message>
<source>Welcome to %1.</source>
<translation>Bienvenue à %1.</translation>
</message>
<message>
<source>As this is the first time the program is launched, you can choose where %1 will store its data.</source>
<translation>Puisque c'est la première fois que le logiciel est lancé, vous pouvez choisir où %1 stockera ses données.</translation>
</message>
<message>
<source>%1 will download and store a copy of the Smartcoin block chain. At least %2GB of data will be stored in this directory, and it will grow over time. The wallet will also be stored in this directory.</source>
<translation>%1 téléchargera et stockera une copie de la chaîne de blocs de Smartcoin. Au moins %2 Go de données seront stockés dans ce répertoire et sa taille augmentera avec le temps. Le porte-monnaie sera également stocké dans ce répertoire.</translation>
</message>
<message>
<source>Use the default data directory</source>
<translation>Utiliser le répertoire de données par défaut</translation>
</message>
<message>
<source>Use a custom data directory:</source>
<translation>Utiliser un répertoire de données personnalisé :</translation>
</message>
<message>
<source>Error: Specified data directory "%1" cannot be created.</source>
<translation>Erreur : le répertoire de données spécifié « %1 » ne peut pas être créé.</translation>
</message>
<message>
<source>Error</source>
<translation>Erreur</translation>
</message>
<message numerus="yes">
<source>%n GB of free space available</source>
<translation><numerusform>%n Go d'espace libre disponible</numerusform><numerusform>%n Go d'espace libre disponibles</numerusform></translation>
</message>
<message numerus="yes">
<source>(of %n GB needed)</source>
<translation><numerusform>(sur %n Go requis)</numerusform><numerusform>(sur %n Go requis)</numerusform></translation>
</message>
</context>
<context>
<name>ModalOverlay</name>
<message>
<source>Form</source>
<translation>Formulaire</translation>
</message>
<message>
<source>Recent transactions may not yet be visible, and therefore your wallet's balance might be incorrect. This information will be correct once your wallet has finished synchronizing with the smartcoin network, as detailed below.</source>
<translation>Les transactions récentes ne sont peut-être pas encore visibles, et par conséquent, le solde de votre porte-monnaie est peut-être erroné. Cette information sera juste une fois que votre porte-monnaie aura fini de se synchroniser avec le réseau Bitcoin, comme décrit ci-dessous. </translation>
</message>
<message>
<source>Attempting to spend smartcoins that are affected by not-yet-displayed transactions will not be accepted by the network.</source>
<translation>Toute tentative de dépense de smartcoins affectés par des transactions qui ne sont pas encore affichées ne sera pas acceptée par le réseau.</translation>
</message>
<message>
<source>Number of blocks left</source>
<translation>Nombre de blocs restants</translation>
</message>
<message>
<source>Unknown...</source>
<translation>Inconnu...</translation>
</message>
<message>
<source>Last block time</source>
<translation>Estampille temporelle du dernier bloc</translation>
</message>
<message>
<source>Progress</source>
<translation>Progression</translation>
</message>
<message>
<source>Progress increase per hour</source>
<translation>Avancement de la progression par heure</translation>
</message>
<message>
<source>calculating...</source>
<translation>calcul en cours...</translation>
</message>
<message>
<source>Estimated time left until synced</source>
<translation>Temps estimé avant la fin de la synchronisation</translation>
</message>
<message>
<source>Hide</source>
<translation>Cacher</translation>
</message>
<message>
<source>Unknown. Syncing Headers (%1)...</source>
<translation>Inconnu. Synchronisation des en-têtes (%1)...</translation>
</message>
</context>
<context>
<name>OpenURIDialog</name>
<message>
<source>Open URI</source>
<translation>Ouvrir une URI</translation>
</message>
<message>
<source>Open payment request from URI or file</source>
<translation>Ouvrir une demande de paiement à partir d'une URI ou d'un fichier</translation>
</message>
<message>
<source>URI:</source>
<translation>URI :</translation>
</message>
<message>
<source>Select payment request file</source>
<translation>Choisir le fichier de demande de paiement</translation>
</message>
<message>
<source>Select payment request file to open</source>
<translation>Choisir le fichier de demande de paiement à ouvrir</translation>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<source>Options</source>
<translation>Options</translation>
</message>
<message>
<source>&Main</source>
<translation>&Principaux</translation>
</message>
<message>
<source>Automatically start %1 after logging in to the system.</source>
<translation>Démarrer %1 automatiquement après avoir ouvert une session sur l'ordinateur.</translation>
</message>
<message>
<source>&Start %1 on system login</source>
<translation>&Démarrer %1 lors de l'ouverture d'une session</translation>
</message>
<message>
<source>Size of &database cache</source>
<translation>Taille du cache de la base de &données</translation>
</message>
<message>
<source>MB</source>
<translation>Mo</translation>
</message>
<message>
<source>Number of script &verification threads</source>
<translation>Nombre de fils de &vérification de script</translation>
</message>
<message>
<source>Accept connections from outside</source>
<translation>Accepter les connexions provenant de l'extérieur</translation>
</message>
<message>
<source>Allow incoming connections</source>
<translation>Permettre les transactions entrantes</translation>
</message>
<message>
<source>IP address of the proxy (e.g. IPv4: 127.0.0.1 / IPv6: ::1)</source>
<translation>Adresse IP du mandataire (p. ex. IPv4 : 127.0.0.1 / IPv6 : ::1)</translation>
</message>
<message>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Exit in the menu.</source>
<translation>Minimiser au lieu de quitter l'application lorsque la fenêtre est fermée. Si cette option est activée, l'application ne sera fermée qu'en sélectionnant Quitter dans le menu.</translation>
</message>
<message>
<source>Third party URLs (e.g. a block explorer) that appear in the transactions tab as context menu items. %s in the URL is replaced by transaction hash. Multiple URLs are separated by vertical bar |.</source>
<translation>URL de tiers (p. ex. un explorateur de blocs) apparaissant dans l'onglet des transactions comme éléments du menu contextuel. %s dans l'URL est remplacé par le hachage de la transaction. Les URL multiples sont séparées par une barre verticale |.</translation>
</message>
<message>
<source>Third party transaction URLs</source>
<translation>URL de transaction d'un tiers</translation>
</message>
<message>
<source>Active command-line options that override above options:</source>
<translation>Options actives de ligne de commande qui annulent les options ci-dessus :</translation>
</message>
<message>
<source>Reset all client options to default.</source>
<translation>Réinitialiser toutes les options du client aux valeurs par défaut.</translation>
</message>
<message>
<source>&Reset Options</source>
<translation>&Réinitialiser les options</translation>
</message>
<message>
<source>&Network</source>
<translation>&Réseau</translation>
</message>
<message>
<source>(0 = auto, <0 = leave that many cores free)</source>
<translation>(0 = auto, < 0 = laisser ce nombre de cœurs inutilisés)</translation>
</message>
<message>
<source>W&allet</source>
<translation>&Porte-monnaie</translation>
</message>
<message>
<source>Expert</source>
<translation>Expert</translation>
</message>
<message>
<source>Enable coin &control features</source>
<translation>Activer les fonctions de &contrôle des pièces</translation>
</message>
<message>
<source>If you disable the spending of unconfirmed change, the change from a transaction cannot be used until that transaction has at least one confirmation. This also affects how your balance is computed.</source>
<translation>Si vous désactivé la dépense de la monnaie non confirmée, la monnaie d'une transaction ne peut pas être utilisée tant que cette transaction n'a pas reçu au moins une confirmation. Celai affecte aussi le calcul de votre solde.</translation>
</message>
<message>
<source>&Spend unconfirmed change</source>
<translation>&Dépenser la monnaie non confirmée</translation>
</message>
<message>
<source>Automatically open the Smartcoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>Ouvrir automatiquement le port du client Smartcoin sur le routeur. Cela ne fonctionne que si votre routeur prend en charge l'UPnP et si la fonction est activée.</translation>
</message>
<message>
<source>Map port using &UPnP</source>
<translation>Mapper le port avec l'&UPnP</translation>
</message>
<message>
<source>Connect to the Smartcoin network through a SOCKS5 proxy.</source>
<translation>Se connecter au réseau Smartcoin par un mandataire SOCKS5.</translation>
</message>
<message>
<source>&Connect through SOCKS5 proxy (default proxy):</source>
<translation>Se &connecter par un mandataire SOCKS5 (mandataire par défaut) :</translation>
</message>
<message>
<source>Proxy &IP:</source>
<translation>&IP du mandataire :</translation>
</message>
<message>
<source>&Port:</source>
<translation>&Port :</translation>
</message>
<message>
<source>Port of the proxy (e.g. 9050)</source>
<translation>Port du mandataire (p. ex. 9050)</translation>
</message>
<message>
<source>Used for reaching peers via:</source>
<translation>Utilisé pour rejoindre les pairs par :</translation>
</message>
<message>
<source>Shows, if the supplied default SOCKS5 proxy is used to reach peers via this network type.</source>
<translation>S'affiche, si le mandataire SOCKS5 par défaut fourni est utilisé pour atteindre les pairs par ce type de réseau.</translation>
</message>
<message>
<source>IPv4</source>
<translation>IPv4</translation>
</message>
<message>
<source>IPv6</source>
<translation>IPv6</translation>
</message>
<message>
<source>Tor</source>
<translation>Tor</translation>
</message>
<message>
<source>Connect to the Smartcoin network through a separate SOCKS5 proxy for Tor hidden services.</source>
<translation>Se connecter au réseau Smartcoin au travers d'un mandataire SOCKS5 séparé pour les services cachés de Tor.</translation>
</message>
<message>
<source>Use separate SOCKS5 proxy to reach peers via Tor hidden services:</source>
<translation>Utiliser un mandataire SOCKS5 séparé pour atteindre les pairs grâce aux services cachés de Tor :</translation>
</message>
<message>
<source>&Window</source>
<translation>&Fenêtre</translation>
</message>
<message>
<source>&Hide the icon from the system tray.</source>
<translation>&Cacher l'icône dans la zone de notification.</translation>
</message>
<message>
<source>Hide tray icon</source>
<translation>Cacher l'icône de la zone de notification</translation>
</message>
<message>
<source>Show only a tray icon after minimizing the window.</source>
<translation>N'afficher qu'une icône dans la zone de notification après minimisation.</translation>
</message>
<message>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&Minimiser dans la zone de notification au lieu de la barre des tâches</translation>
</message>
<message>
<source>M&inimize on close</source>
<translation>M&inimiser lors de la fermeture</translation>
</message>
<message>
<source>&Display</source>
<translation>&Affichage</translation>
</message>
<message>
<source>User Interface &language:</source>
<translation>&Langue de l'interface utilisateur :</translation>
</message>
<message>
<source>The user interface language can be set here. This setting will take effect after restarting %1.</source>
<translation>La langue de l'interface utilisateur peut être définie ici. Ce réglage sera pris en compte après redémarrage de %1.</translation>
</message>
<message>
<source>&Unit to show amounts in:</source>
<translation>&Unité d'affichage des montants :</translation>
</message>
<message>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>Choisir la sous-unité par défaut d'affichage dans l'interface et lors d'envoi de pièces.</translation>
</message>
<message>
<source>Whether to show coin control features or not.</source>
<translation>Afficher ou non les fonctions de contrôle des pièces.</translation>
</message>
<message>
<source>&OK</source>
<translation>&OK</translation>
</message>
<message>
<source>&Cancel</source>
<translation>A&nnuler</translation>
</message>
<message>
<source>default</source>
<translation>par défaut</translation>
</message>
<message>
<source>none</source>
<translation>aucune</translation>
</message>
<message>
<source>Confirm options reset</source>
<translation>Confirmer la réinitialisation des options</translation>
</message>
<message>
<source>Client restart required to activate changes.</source>
<translation>Le redémarrage du client est exigé pour activer les changements.</translation>
</message>
<message>
<source>Client will be shut down. Do you want to proceed?</source>
<translation>Le client sera arrêté. Voulez-vous continuer ?</translation>
</message>
<message>
<source>This change would require a client restart.</source>
<translation>Ce changement demanderait un redémarrage du client.</translation>
</message>
<message>
<source>The supplied proxy address is invalid.</source>
<translation>L'adresse de serveur mandataire fournie est invalide.</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<source>Form</source>
<translation>Formulaire</translation>
</message>
<message>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the Smartcoin network after a connection is established, but this process has not completed yet.</source>
<translation>Les informations affichées peuvent être obsolètes. Votre porte-monnaie est automatiquement synchronisé avec le réseau Smartcoin lorsque la connexion s'établit, or ce processus n'est pas encore terminé.</translation>
</message>
<message>
<source>Watch-only:</source>
<translation>Juste-regarder :</translation>
</message>
<message>
<source>Available:</source>
<translation>Disponible :</translation>
</message>
<message>
<source>Your current spendable balance</source>
<translation>Votre solde actuel disponible</translation>
</message>
<message>
<source>Pending:</source>
<translation>En attente :</translation>
</message>
<message>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the spendable balance</source>
<translation>Total des transactions qui doivent encore être confirmées et qui ne sont pas prises en compte dans le solde disponible</translation>
</message>
<message>
<source>Immature:</source>
<translation>Immature :</translation>
</message>
<message>
<source>Mined balance that has not yet matured</source>
<translation>Le solde miné n'est pas encore mûr</translation>
</message>
<message>
<source>Balances</source>
<translation>Soldes</translation>
</message>
<message>
<source>Total:</source>
<translation>Total :</translation>
</message>
<message>
<source>Your current total balance</source>
<translation>Votre solde total actuel</translation>
</message>
<message>
<source>Your current balance in watch-only addresses</source>
<translation>Votre balance actuelle en adresses juste-regarder</translation>
</message>
<message>
<source>Spendable:</source>
<translation>Disponible :</translation>
</message>
<message>
<source>Recent transactions</source>
<translation>Transactions récentes</translation>
</message>
<message>
<source>Unconfirmed transactions to watch-only addresses</source>
<translation>Transactions non confirmées vers des adresses juste-regarder</translation>
</message>
<message>
<source>Mined balance in watch-only addresses that has not yet matured</source>
<translation>Le solde miné dans des adresses juste-regarder, qui n'est pas encore mûr</translation>
</message>
<message>
<source>Current total balance in watch-only addresses</source>
<translation>Solde total actuel dans des adresses juste-regarder</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<source>Payment request error</source>
<translation>Erreur de demande de paiement</translation>
</message>
<message>
<source>Cannot start smartcoin: click-to-pay handler</source>
<translation>Impossible de démarrer le gestionnaire de cliquer-pour-payer smartcoin:</translation>
</message>
<message>
<source>URI handling</source>
<translation>Gestion des URI</translation>
</message>
<message>
<source>Payment request fetch URL is invalid: %1</source>
<translation>L'URL de récupération de la demande de paiement est invalide : %1</translation>
</message>
<message>
<source>Invalid payment address %1</source>
<translation>Adresse de paiement invalide %1</translation>
</message>
<message>
<source>URI cannot be parsed! This can be caused by an invalid Smartcoin address or malformed URI parameters.</source>
<translation>L'URI ne peut pas être analysée ! Cela peut être causé par une adresse Smartcoin invalide ou par des paramètres d'URI mal formés.</translation>
</message>
<message>
<source>Payment request file handling</source>
<translation>Gestion des fichiers de demande de paiement</translation>
</message>
<message>
<source>Payment request file cannot be read! This can be caused by an invalid payment request file.</source>
<translation>Le fichier de demande de paiement ne peut pas être lu ! Cela peut être causé par un fichier de demande de paiement invalide.</translation>
</message>
<message>
<source>Payment request rejected</source>
<translation>Demande de paiement rejetée</translation>
</message>
<message>
<source>Payment request network doesn't match client network.</source>
<translation>Le réseau de la demande de paiement ne correspond pas au réseau du client.</translation>
</message>
<message>
<source>Payment request expired.</source>
<translation>La demande de paiement a expiré</translation>
</message>
<message>
<source>Payment request is not initialized.</source>
<translation>La demande de paiement n'est pas initialisée.</translation>
</message>
<message>
<source>Unverified payment requests to custom payment scripts are unsupported.</source>
<translation>Les demandes de paiements non vérifiées vers des scripts de paiement personnalisés ne sont pas prises en charge.</translation>
</message>
<message>
<source>Invalid payment request.</source>
<translation>Demande de paiement invalide.</translation>
</message>
<message>
<source>Requested payment amount of %1 is too small (considered dust).</source>
<translation>Le paiement demandé d'un montant de %1 est trop faible (considéré comme de la poussière).</translation>
</message>
<message>
<source>Refund from %1</source>
<translation>Remboursement de %1</translation>
</message>
<message>
<source>Payment request %1 is too large (%2 bytes, allowed %3 bytes).</source>
<translation>La demande de paiement %1 est trop grande (%2 octets, %3 octets permis).</translation>
</message>
<message>
<source>Error communicating with %1: %2</source>
<translation>Erreur de communication avec %1 : %2</translation>
</message>
<message>
<source>Payment request cannot be parsed!</source>
<translation>La demande de paiement ne peut pas être analysée !</translation>
</message>
<message>
<source>Bad response from server %1</source>
<translation>Mauvaise réponse du serveur %1</translation>
</message>
<message>
<source>Network request error</source>
<translation>Erreur de demande réseau</translation>
</message>
<message>
<source>Payment acknowledged</source>
<translation>Le paiement a été confirmé</translation>
</message>
</context>
<context>
<name>PeerTableModel</name>
<message>
<source>User Agent</source>
<translation>Agent utilisateur</translation>
</message>
<message>
<source>Node/Service</source>
<translation>Nœud/service</translation>
</message>
<message>
<source>NodeId</source>
<translation>ID de nœud</translation>
</message>
<message>
<source>Ping</source>
<translation>Ping</translation>
</message>
</context>
<context>
<name>QObject</name>
<message>
<source>Amount</source>
<translation>Montant</translation>
</message>
<message>
<source>Enter a Smartcoin address (e.g. %1)</source>
<translation>Saisir une adresse Smartcoin (p. ex. %1)</translation>
</message>
<message>
<source>%1 d</source>
<translation>%1 j</translation>
</message>
<message>
<source>%1 h</source>
<translation>%1 h</translation>
</message>
<message>
<source>%1 m</source>
<translation>%1 min</translation>
</message>
<message>
<source>%1 s</source>
<translation>%1 s</translation>
</message>
<message>
<source>None</source>
<translation>Aucun</translation>
</message>
<message>
<source>N/A</source>
<translation>N.D.</translation>
</message>
<message>
<source>%1 ms</source>
<translation>%1 ms</translation>
</message>
<message numerus="yes">
<source>%n second(s)</source>
<translation><numerusform>%n seconde</numerusform><numerusform>%n secondes</numerusform></translation>
</message>
<message numerus="yes">
<source>%n minute(s)</source>
<translation><numerusform>%n minute</numerusform><numerusform>%n minutes</numerusform></translation>
</message>
<message numerus="yes">
<source>%n hour(s)</source>
<translation><numerusform>%n heure</numerusform><numerusform>%n heures</numerusform></translation>
</message>
<message numerus="yes">
<source>%n day(s)</source>
<translation><numerusform>%n jour</numerusform><numerusform>%n jours</numerusform></translation>
</message>
<message numerus="yes">
<source>%n week(s)</source>
<translation><numerusform>%n semaine</numerusform><numerusform>%n semaines</numerusform></translation>
</message>
<message>
<source>%1 and %2</source>
<translation>%1 et %2</translation>
</message>
<message numerus="yes">
<source>%n year(s)</source>
<translation><numerusform>%n an</numerusform><numerusform>%n ans</numerusform></translation>
</message>
<message>
<source>%1 didn't yet exit safely...</source>
<translation>%1 ne s'est pas encore arrêté en toute sécurité...</translation>
</message>
</context>
<context>
<name>QObject::QObject</name>
<message>
<source>Error: Specified data directory "%1" does not exist.</source>
<translation>Erreur : le répertoire de données indiqué « %1 » n'existe pas.</translation>
</message>
<message>
<source>Error: Cannot parse configuration file: %1. Only use key=value syntax.</source>
<translation>Erreur : impossible d'analyser le fichier de configuration : %1. N’utiliser que la syntaxe clef=valeur.</translation>
</message>
<message>
<source>Error: %1</source>
<translation>Erreur : %1</translation>
</message>
</context>
<context>
<name>QRImageWidget</name>
<message>
<source>&Save Image...</source>
<translation>&Enregistrer l'image...</translation>
</message>
<message>
<source>&Copy Image</source>
<translation>&Copier l'image</translation>
</message>
<message>
<source>Save QR Code</source>
<translation>Enregistrer le code QR</translation>
</message>
<message>
<source>PNG Image (*.png)</source>
<translation>Image PNG (*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<source>N/A</source>
<translation>N.D.</translation>
</message>
<message>
<source>Client version</source>
<translation>Version du client</translation>
</message>
<message>
<source>&Information</source>
<translation>&Informations</translation>
</message>
<message>
<source>Debug window</source>
<translation>Fenêtre de débogage</translation>
</message>
<message>
<source>General</source>
<translation>Général</translation>
</message>
<message>
<source>Using BerkeleyDB version</source>
<translation>Version BerkeleyDB utilisée</translation>
</message>
<message>
<source>Datadir</source>
<translation>Datadir</translation>
</message>
<message>
<source>Startup time</source>
<translation>Heure de démarrage</translation>
</message>
<message>
<source>Network</source>
<translation>Réseau</translation>
</message>
<message>
<source>Name</source>
<translation>Nom</translation>
</message>
<message>
<source>Number of connections</source>
<translation>Nombre de connexions</translation>
</message>
<message>
<source>Block chain</source>
<translation>Chaîne de blocs</translation>
</message>
<message>
<source>Current number of blocks</source>
<translation>Nombre actuel de blocs</translation>
</message>
<message>
<source>Memory Pool</source>
<translation>Réserve de mémoire</translation>
</message>
<message>
<source>Current number of transactions</source>
<translation>Nombre actuel de transactions</translation>
</message>
<message>
<source>Memory usage</source>
<translation>Utilisation de la mémoire</translation>
</message>
<message>
<source>Received</source>
<translation>Reçu</translation>
</message>
<message>
<source>Sent</source>
<translation>Envoyé</translation>
</message>
<message>
<source>&Peers</source>
<translation>&Pairs</translation>
</message>
<message>
<source>Banned peers</source>
<translation>Pairs bannis</translation>
</message>
<message>
<source>Select a peer to view detailed information.</source>
<translation>Choisir un pair pour voir l'information détaillée.</translation>
</message>
<message>
<source>Whitelisted</source>
<translation>Dans la liste blanche</translation>
</message>
<message>
<source>Direction</source>
<translation>Direction</translation>
</message>
<message>
<source>Version</source>
<translation>Version</translation>
</message>
<message>
<source>Starting Block</source>
<translation>Bloc de départ</translation>
</message>
<message>
<source>Synced Headers</source>
<translation>En-têtes synchronisés</translation>
</message>
<message>
<source>Synced Blocks</source>
<translation>Blocs synchronisés</translation>
</message>
<message>
<source>User Agent</source>
<translation>Agent utilisateur</translation>
</message>
<message>
<source>Open the %1 debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation>Ouvrir le fichier journal de débogage de %1 à partir du répertoire de données actuel. Cela peut prendre quelques secondes pour les fichiers journaux de grande taille.</translation>
</message>
<message>
<source>Decrease font size</source>
<translation>Diminuer la taille de police</translation>
</message>
<message>
<source>Increase font size</source>
<translation>Augmenter la taille de police</translation>
</message>
<message>
<source>Services</source>
<translation>Services</translation>
</message>
<message>
<source>Ban Score</source>
<translation>Pointage des bannissements</translation>
</message>
<message>
<source>Connection Time</source>
<translation>Temps de connexion</translation>
</message>
<message>
<source>Last Send</source>
<translation>Dernier envoi</translation>
</message>
<message>
<source>Last Receive</source>
<translation>Dernière réception</translation>
</message>
<message>
<source>Ping Time</source>
<translation>Temps de ping</translation>
</message>
<message>
<source>The duration of a currently outstanding ping.</source>
<translation>La durée d'un ping en cours.</translation>
</message>
<message>
<source>Ping Wait</source>
<translation>Attente du ping</translation>
</message>
<message>
<source>Min Ping</source>
<translation>Ping min.</translation>
</message>
<message>
<source>Time Offset</source>
<translation>Décalage temporel</translation>
</message>
<message>
<source>Last block time</source>
<translation>Estampille temporelle du dernier bloc</translation>
</message>
<message>
<source>&Open</source>
<translation>&Ouvrir</translation>
</message>
<message>
<source>&Console</source>
<translation>&Console</translation>
</message>
<message>
<source>&Network Traffic</source>
<translation>Trafic &réseau</translation>
</message>
<message>
<source>&Clear</source>
<translation>&Effacer</translation>
</message>
<message>
<source>Totals</source>
<translation>Totaux</translation>
</message>
<message>
<source>In:</source>
<translation>Entrant :</translation>
</message>
<message>
<source>Out:</source>
<translation>Sortant :</translation>
</message>
<message>
<source>Debug log file</source>
<translation>Fichier journal de débogage</translation>
</message>
<message>
<source>Clear console</source>
<translation>Effacer la console</translation>
</message>
<message>
<source>1 &hour</source>
<translation>1 &heure</translation>
</message>
<message>
<source>1 &day</source>
<translation>1 &jour</translation>
</message>
<message>
<source>1 &week</source>
<translation>1 &semaine</translation>
</message>
<message>
<source>1 &year</source>
<translation>1 &an</translation>
</message>
<message>
<source>&Disconnect</source>
<translation>&Déconnecter</translation>
</message>
<message>
<source>Ban for</source>
<translation>Bannir pendant</translation>
</message>
<message>
<source>&Unban</source>
<translation>&Réhabiliter</translation>
</message>
<message>
<source>Welcome to the %1 RPC console.</source>
<translation>Bienvenue sur la console RPC de %1.</translation>
</message>
<message>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation>Utiliser les touches de déplacement pour naviguer dans l'historique et <b>Ctrl-L</b> pour effacer l'écran.</translation>
</message>
<message>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation>Taper <b>help</b> pour afficher une vue générale des commandes proposées.</translation>
</message>
<message>
<source>WARNING: Scammers have been active, telling users to type commands here, stealing their wallet contents. Do not use this console without fully understanding the ramification of a command.</source>
<translation>AVERTISSEMENT : des fraudeurs sont réputés être à l'oeuvre, demandant aux utilisateurs de taper des commandes ici, et dérobant le contenu de leurs porte-monnaie. Ne pas utiliser cette console sans une compréhension parfaite des conséquences d'une commande.</translation>
</message>
<message>
<source>Network activity disabled</source>
<translation>L'activité réseau est désactivée.</translation>
</message>
<message>
<source>%1 B</source>
<translation>%1 o</translation>
</message>
<message>
<source>%1 KB</source>
<translation>%1 Ko</translation>
</message>
<message>
<source>%1 MB</source>
<translation>%1 Mo</translation>
</message>
<message>
<source>%1 GB</source>
<translation>%1 Go</translation>
</message>
<message>
<source>(node id: %1)</source>
<translation>(ID de nœud : %1)</translation>
</message>
<message>
<source>via %1</source>
<translation>par %1</translation>
</message>
<message>
<source>never</source>
<translation>jamais</translation>
</message>
<message>
<source>Inbound</source>
<translation>Entrant</translation>
</message>
<message>
<source>Outbound</source>
<translation>Sortant</translation>
</message>
<message>
<source>Yes</source>
<translation>Oui</translation>
</message>
<message>
<source>No</source>
<translation>Non</translation>
</message>
<message>
<source>Unknown</source>
<translation>Inconnu</translation>
</message>
</context>
<context>
<name>ReceiveCoinsDialog</name>
<message>
<source>&Amount:</source>
<translation>&Montant :</translation>
</message>
<message>
<source>&Label:</source>
<translation>&Étiquette :</translation>
</message>
<message>
<source>&Message:</source>
<translation>M&essage :</translation>
</message>
<message>
<source>Reuse one of the previously used receiving addresses. Reusing addresses has security and privacy issues. Do not use this unless re-generating a payment request made before.</source>
<translation>Réutiliser une adresse de réception utilisée précédemment. Réutiliser une adresse comporte des problèmes de sécurité et de confidentialité. À ne pas utiliser, sauf pour générer une demande de paiement faite au préalable.</translation>
</message>
<message>
<source>R&euse an existing receiving address (not recommended)</source>
<translation>Ré&utiliser une adresse de réception existante (non recommandé)</translation>
</message>
<message>
<source>An optional message to attach to the payment request, which will be displayed when the request is opened. Note: The message will not be sent with the payment over the Smartcoin network.</source>
<translation>Un message facultatif à joindre à la demande de paiement et qui sera affiché à l'ouverture de celle-ci. Note : le message ne sera pas envoyé avec le paiement par le réseau Smartcoin.</translation>
</message>
<message>
<source>An optional label to associate with the new receiving address.</source>
<translation>Un étiquette facultative à associer à la nouvelle adresse de réception.</translation>
</message>
<message>
<source>Use this form to request payments. All fields are <b>optional</b>.</source>
<translation>Utiliser ce formulaire pour demander des paiements. Tous les champs sont <b>facultatifs</b>.</translation>
</message>
<message>
<source>An optional amount to request. Leave this empty or zero to not request a specific amount.</source>
<translation>Un montant facultatif à demander. Ne rien saisir ou un zéro pour ne pas demander de montant spécifique.</translation>
</message>
<message>
<source>Clear all fields of the form.</source>
<translation>Effacer tous les champs du formulaire.</translation>
</message>
<message>
<source>Clear</source>
<translation>Effacer</translation>
</message>
<message>
<source>Requested payments history</source>
<translation>Historique des paiements demandés</translation>
</message>
<message>
<source>&Request payment</source>
<translation>&Demander un paiement</translation>
</message>
<message>
<source>Show the selected request (does the same as double clicking an entry)</source>
<translation>Afficher la demande choisie (comme double-cliquer sur une entrée)</translation>
</message>
<message>
<source>Show</source>
<translation>Afficher</translation>
</message>
<message>
<source>Remove the selected entries from the list</source>
<translation>Retirer les entrées sélectionnées de la liste</translation>
</message>
<message>
<source>Remove</source>
<translation>Retirer</translation>
</message>
<message>
<source>Copy URI</source>
<translation>Copier l'URI</translation>
</message>
<message>
<source>Copy label</source>
<translation>Copier l’étiquette</translation>
</message>
<message>
<source>Copy message</source>
<translation>Copier le message</translation>
</message>
<message>
<source>Copy amount</source>
<translation>Copier le montant</translation>
</message>
</context>
<context>
<name>ReceiveRequestDialog</name>
<message>
<source>QR Code</source>
<translation>Code QR</translation>
</message>
<message>
<source>Copy &URI</source>
<translation>Copier l'&URI</translation>
</message>
<message>
<source>Copy &Address</source>
<translation>Copier l'&adresse</translation>
</message>
<message>
<source>&Save Image...</source>
<translation>&Enregistrer l'image...</translation>
</message>
<message>
<source>Request payment to %1</source>
<translation>Demande de paiement à %1</translation>
</message>
<message>
<source>Payment information</source>
<translation>Informations de paiement</translation>
</message>
<message>
<source>URI</source>
<translation>URI</translation>
</message>
<message>
<source>Address</source>
<translation>Adresse</translation>
</message>
<message>
<source>Amount</source>
<translation>Montant</translation>
</message>
<message>
<source>Label</source>
<translation>Étiquette</translation>
</message>
<message>
<source>Message</source>
<translation>Message</translation>
</message>
<message>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation>L'URI résultante est trop longue. Essayez de réduire le texte de l'étiquette ou du message.</translation>
</message>
<message>
<source>Error encoding URI into QR Code.</source>
<translation>Erreur d'encodage de l'URI en code QR.</translation>
</message>
</context>
<context>
<name>RecentRequestsTableModel</name>
<message>
<source>Date</source>
<translation>Date</translation>
</message>
<message>
<source>Label</source>
<translation>Étiquette</translation>
</message>
<message>
<source>Message</source>
<translation>Message</translation>
</message>
<message>
<source>(no label)</source>
<translation>(aucune étiquette)</translation>
</message>
<message>
<source>(no message)</source>
<translation>(aucun message)</translation>
</message>
<message>
<source>(no amount requested)</source>
<translation>(aucun montant demandé)</translation>
</message>
<message>
<source>Requested</source>
<translation>Demandée</translation>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<source>Send Coins</source>
<translation>Envoyer des pièces</translation>
</message>
<message>
<source>Coin Control Features</source>
<translation>Fonctions de contrôle des pièces</translation>
</message>
<message>
<source>Inputs...</source>
<translation>Entrants...</translation>
</message>
<message>
<source>automatically selected</source>
<translation>choisi automatiquement</translation>
</message>
<message>
<source>Insufficient funds!</source>
<translation>Fonds insuffisants !</translation>
</message>
<message>
<source>Quantity:</source>
<translation>Quantité :</translation>
</message>
<message>
<source>Bytes:</source>
<translation>Octets :</translation>
</message>
<message>
<source>Amount:</source>
<translation>Montant :</translation>
</message>
<message>
<source>Fee:</source>
<translation>Frais :</translation>
</message>
<message>
<source>After Fee:</source>
<translation>Après les frais :</translation>
</message>
<message>
<source>Change:</source>
<translation>Monnaie :</translation>
</message>
<message>
<source>If this is activated, but the change address is empty or invalid, change will be sent to a newly generated address.</source>
<translation>Si cette option est activée et l'adresse de monnaie est vide ou invalide, la monnaie sera envoyée vers une adresse nouvellement générée.</translation>
</message>
<message>
<source>Custom change address</source>
<translation>Adresse personnalisée de monnaie</translation>
</message>
<message>
<source>Transaction Fee:</source>
<translation>Frais de transaction :</translation>
</message>
<message>
<source>Choose...</source>
<translation>Choisir...</translation>
</message>
<message>
<source>collapse fee-settings</source>
<translation>réduire les paramètres des frais</translation>
</message>
<message>
<source>per kilobyte</source>
<translation>par kilo-octet</translation>
</message>
<message>
<source>If the custom fee is set to 1000 koinu and the transaction is only 250 bytes, then "per kilobyte" only pays 250 koinu in fee, while "total at least" pays 1000 koinu. For transactions bigger than a kilobyte both pay by kilobyte.</source>
<translation>Si les frais personnalisés sont définis à 1 000 koinu et que la transaction est seulement de 250 octets, donc le « par kilo-octet » ne paiera que 250 koinu de frais, alors que le « total au moins » paiera 1 000 koinu. Pour des transactions supérieures à un kilo-octet, les deux paieront par kilo-octets.</translation>
</message>
<message>
<source>Hide</source>
<translation>Cacher</translation>
</message>
<message>
<source>total at least</source>
<translation>total au moins</translation>
</message>
<message>
<source>Paying only the minimum fee is just fine as long as there is less transaction volume than space in the blocks. But be aware that this can end up in a never confirming transaction once there is more demand for smartcoin transactions than the network can process.</source>
<translation>Il est correct de payer les frais minimum tant que le volume transactionnel est inférieur à l'espace dans les blocs. Mais soyez conscient que cela pourrait résulter en une transaction n'étant jamais confirmée une fois qu'il y aura plus de transactions que le réseau ne pourra en traiter.</translation>
</message>
<message>
<source>(read the tooltip)</source>
<translation>(lire l'infobulle)</translation>
</message>
<message>
<source>Recommended:</source>
<translation>Recommandés :</translation>
</message>
<message>
<source>Custom:</source>
<translation>Personnalisés : </translation>
</message>
<message>
<source>(Smart fee not initialized yet. This usually takes a few blocks...)</source>
<translation>(Les frais intelligents ne sont pas encore initialisés. Cela prend habituellement quelques blocs...)</translation>
</message>
<message>
<source>normal</source>
<translation>normal</translation>
</message>
<message>
<source>fast</source>
<translation>rapide</translation>
</message>
<message>
<source>Send to multiple recipients at once</source>
<translation>Envoyer à plusieurs destinataires à la fois</translation>
</message>
<message>
<source>Add &Recipient</source>
<translation>Ajouter un &destinataire</translation>
</message>
<message>
<source>Clear all fields of the form.</source>
<translation>Effacer tous les champs du formulaire.</translation>
</message>
<message>
<source>Dust:</source>
<translation>Poussière :</translation>
</message>
<message>
<source>Confirmation time target:</source>
<translation>Estimation du délai de confirmation :</translation>
</message>
<message>
<source>Clear &All</source>
<translation>&Tout effacer</translation>
</message>
<message>
<source>Balance:</source>
<translation>Solde :</translation>
</message>
<message>
<source>Confirm the send action</source>
<translation>Confirmer l’action d'envoi</translation>
</message>
<message>
<source>S&end</source>
<translation>E&nvoyer</translation>
</message>
<message>
<source>Copy quantity</source>
<translation>Copier la quantité</translation>
</message>
<message>
<source>Copy amount</source>
<translation>Copier le montant</translation>
</message>
<message>
<source>Copy fee</source>
<translation>Copier les frais</translation>
</message>
<message>
<source>Copy after fee</source>
<translation>Copier après les frais</translation>
</message>
<message>
<source>Copy bytes</source>
<translation>Copier les octets</translation>
</message>
<message>
<source>Copy dust</source>
<translation>Copier la poussière</translation>
</message>
<message>
<source>Copy change</source>
<translation>Copier la monnaie</translation>
</message>
<message>
<source>%1 to %2</source>
<translation>%1 à %2</translation>
</message>
<message>
<source>Are you sure you want to send?</source>
<translation>Voulez-vous vraiment envoyer ?</translation>
</message>
<message>
<source>added as transaction fee</source>
<translation>ajoutés comme frais de transaction</translation>
</message>
<message>
<source>Total Amount %1</source>
<translation>Montant total %1</translation>
</message>
<message>
<source>or</source>
<translation>ou</translation>
</message>
<message>
<source>Confirm send coins</source>
<translation>Confirmer l’envoi de pièces</translation>
</message>
<message>
<source>The recipient address is not valid. Please recheck.</source>
<translation>L'adresse du destinataire est invalide. Veuillez la revérifier.</translation>
</message>
<message>
<source>The amount to pay must be larger than 0.</source>
<translation>Le montant à payer doit être supérieur à 0.</translation>
</message>
<message>
<source>The amount exceeds your balance.</source>
<translation>Le montant dépasse votre solde.</translation>
</message>
<message>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>Le montant dépasse votre solde lorsque les frais de transaction de %1 sont inclus.</translation>
</message>
<message>
<source>Duplicate address found: addresses should only be used once each.</source>
<translation>Adresse identique trouvée : chaque adresse ne devrait être utilisée qu'une fois.</translation>
</message>
<message>
<source>Transaction creation failed!</source>
<translation>Échec de création de la transaction !</translation>
</message>
<message>
<source>The transaction was rejected with the following reason: %1</source>
<translation>La transaction a été rejetée pour la raison suivante : %1</translation>
</message>
<message>
<source>A fee higher than %1 is considered an absurdly high fee.</source>
<translation>Des frais supérieurs à %1 sont considérés comme ridiculement élevés.</translation>
</message>
<message>
<source>Payment request expired.</source>
<translation>La demande de paiement a expiré</translation>
</message>
<message numerus="yes">
<source>%n block(s)</source>
<translation><numerusform>%n bloc</numerusform><numerusform>%n blocs</numerusform></translation>
</message>
<message>
<source>Pay only the required fee of %1</source>
<translation>Payer seulement les frais exigés de %1</translation>
</message>
<message numerus="yes">
<source>Estimated to begin confirmation within %n block(s).</source>
<translation><numerusform>Il est estimé que la confirmation commencera dans %n bloc.</numerusform><numerusform>Il est estimé que la confirmation commencera dans %n blocs.</numerusform></translation>
</message>
<message>
<source>Warning: Invalid Smartcoin address</source>
<translation>Avertissement : adresse Smartcoin invalide</translation>
</message>
<message>
<source>Warning: Unknown change address</source>
<translation>Avertissement : adresse de monnaie inconnue</translation>
</message>
<message>
<source>Confirm custom change address</source>
<translation>Confimer l'adresse personnalisée de monnaie</translation>
</message>
<message>
<source>The address you selected for change is not part of this wallet. Any or all funds in your wallet may be sent to this address. Are you sure?</source>
<translation>L'adresse que vous avez sélectionnée pour la monnaie ne fait pas partie de ce porte-monnaie. Les fonds de ce porte-monnaie peuvent en partie ou en totalité être envoyés vers cette adresse. Êtes-vous certain ?</translation>
</message>
<message>
<source>(no label)</source>
<translation>(aucune étiquette)</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<source>A&mount:</source>
<translation>&Montant :</translation>
</message>
<message>
<source>Pay &To:</source>
<translation>&Payer à :</translation>
</message>
<message>
<source>&Label:</source>
<translation>É&tiquette :</translation>
</message>
<message>
<source>Choose previously used address</source>
<translation>Choisir une adresse déjà utilisée</translation>
</message>
<message>
<source>This is a normal payment.</source>
<translation>Ceci est un paiement normal.</translation>
</message>
<message>
<source>The Smartcoin address to send the payment to</source>
<translation>L'adresse Smartcoin à laquelle envoyer le paiement</translation>
</message>
<message>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<source>Paste address from clipboard</source>
<translation>Coller l'adresse du presse-papiers</translation>
</message>
<message>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<source>Remove this entry</source>
<translation>Retirer cette entrée</translation>
</message>
<message>
<source>The fee will be deducted from the amount being sent. The recipient will receive less smartcoins than you enter in the amount field. If multiple recipients are selected, the fee is split equally.</source>
<translation>Les frais seront déduits du montant envoyé. Le destinataire recevra moins de smartcoins que le montant saisi dans le champ de montant. Si plusieurs destinataires sont sélectionnés, les frais seront partagés également..</translation>
</message>
<message>
<source>S&ubtract fee from amount</source>
<translation>S&oustraire les frais du montant</translation>
</message>
<message>
<source>Message:</source>
<translation>Message :</translation>
</message>
<message>
<source>This is an unauthenticated payment request.</source>
<translation>Cette demande de paiement n'est pas authentifiée.</translation>
</message>
<message>
<source>This is an authenticated payment request.</source>
<translation>Cette demande de paiement est authentifiée.</translation>
</message>
<message>
<source>Enter a label for this address to add it to the list of used addresses</source>
<translation>Saisir une étiquette pour cette adresse afin de l'ajouter à la liste d'adresses utilisées</translation>
</message>
<message>
<source>A message that was attached to the smartcoin: URI which will be stored with the transaction for your reference. Note: This message will not be sent over the Smartcoin network.</source>
<translation>Un message qui était joint à l'URI smartcoin: et qui sera stocké avec la transaction pour référence. Note : ce message ne sera pas envoyé par le réseau Smartcoin.</translation>
</message>
<message>
<source>Pay To:</source>
<translation>Payer à :</translation>
</message>
<message>
<source>Memo:</source>
<translation>Mémo :</translation>
</message>
<message>
<source>Enter a label for this address to add it to your address book</source>
<translation>Saisir une étiquette pour cette adresse afin de l’ajouter à votre carnet d’adresses</translation>
</message>
</context>
<context>
<name>SendConfirmationDialog</name>
<message>
<source>Yes</source>
<translation>Oui</translation>
</message>
</context>
<context>
<name>ShutdownWindow</name>
<message>
<source>%1 is shutting down...</source>
<translation>Arrêt de %1...</translation>
</message>
<message>
<source>Do not shut down the computer until this window disappears.</source>
<translation>Ne pas éteindre l'ordinateur jusqu'à la disparition de cette fenêtre.</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<source>Signatures - Sign / Verify a Message</source>
<translation>Signatures - Signer / vérifier un message</translation>
</message>
<message>
<source>&Sign Message</source>
<translation>&Signer un message</translation>
</message>
<message>
<source>You can sign messages/agreements with your addresses to prove you can receive smartcoins sent to them. Be careful not to sign anything vague or random, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation>Vous pouvez signer des messages ou des accords avec vos adresses pour prouver que vous pouvez recevoir des smartcoins à ces dernières. Faites attention de ne rien signer de vague ou au hasard, car des attaques d'hameçonnage pourraient essayer de vous faire signer avec votre identité afin de l'usurper. Ne signez que des déclarations entièrement détaillées et avec lesquelles vous êtes d'accord.</translation>
</message>
<message>
<source>The Smartcoin address to sign the message with</source>
<translation>L'adresse Smartcoin avec laquelle signer le message</translation>
</message>
<message>
<source>Choose previously used address</source>
<translation>Choisir une adresse déjà utilisée</translation>
</message>
<message>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<source>Paste address from clipboard</source>
<translation>Coller une adresse du presse-papiers</translation>
</message>
<message>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<source>Enter the message you want to sign here</source>
<translation>Saisir ici le message que vous désirez signer</translation>
</message>
<message>
<source>Signature</source>
<translation>Signature</translation>
</message>
<message>
<source>Copy the current signature to the system clipboard</source>
<translation>Copier la signature actuelle dans le presse-papiers</translation>
</message>
<message>
<source>Sign the message to prove you own this Smartcoin address</source>
<translation>Signer le message afin de prouver que vous détenez cette adresse Smartcoin</translation>
</message>
<message>
<source>Sign &Message</source>
<translation>Signer le &message</translation>
</message>
<message>
<source>Reset all sign message fields</source>
<translation>Réinitialiser tous les champs de signature de message</translation>
</message>
<message>
<source>Clear &All</source>
<translation>&Tout effacer</translation>
</message>
<message>
<source>&Verify Message</source>
<translation>&Vérifier un message</translation>
</message>
<message>
<source>Enter the receiver's address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack. Note that this only proves the signing party receives with the address, it cannot prove sendership of any transaction!</source>
<translation>Saisir ci-dessous l'adresse du destinataire, le message (s'assurer de copier fidèlement les retours à la ligne, les espaces, les tabulations, etc.) et la signature pour vérifier le message. Faire attention à ne pas déduire davantage de la signature que ce qui est contenu dans le message signé même, pour éviter d'être trompé par une attaque d'homme du milieu. Prendre en compte que cela ne fait que prouver que le signataire reçoit l'adresse et ne peut pas prouver la provenance d'une transaction !</translation>
</message>
<message>
<source>The Smartcoin address the message was signed with</source>
<translation>L'adresse Smartcoin avec laquelle le message a été signé</translation>
</message>
<message>
<source>Verify the message to ensure it was signed with the specified Smartcoin address</source>
<translation>Vérifier le message pour s'assurer qu'il a été signé avec l'adresse Smartcoin spécifiée</translation>
</message>
<message>
<source>Verify &Message</source>
<translation>Vérifier le &message</translation>
</message>
<message>
<source>Reset all verify message fields</source>
<translation>Réinitialiser tous les champs de vérification de message</translation>
</message>
<message>
<source>Click "Sign Message" to generate signature</source>
<translation>Cliquez sur « Signer le message » pour générer la signature</translation>
</message>
<message>
<source>The entered address is invalid.</source>
<translation>L'adresse saisie est invalide.</translation>
</message>
<message>
<source>Please check the address and try again.</source>
<translation>Veuillez vérifier l'adresse et ressayer.</translation>
</message>
<message>
<source>The entered address does not refer to a key.</source>
<translation>L'adresse saisie ne fait pas référence à une clé.</translation>
</message>
<message>
<source>Wallet unlock was cancelled.</source>
<translation>Le déverrouillage du porte-monnaie a été annulé.</translation>
</message>
<message>
<source>Private key for the entered address is not available.</source>
<translation>La clé privée n'est pas disponible pour l'adresse saisie.</translation>
</message>
<message>
<source>Message signing failed.</source>
<translation>Échec de signature du message.</translation>
</message>
<message>
<source>Message signed.</source>
<translation>Le message a été signé.</translation>
</message>
<message>
<source>The signature could not be decoded.</source>
<translation>La signature n'a pu être décodée.</translation>
</message>
<message>
<source>Please check the signature and try again.</source>
<translation>Veuillez vérifier la signature et ressayer.</translation>
</message>
<message>
<source>The signature did not match the message digest.</source>
<translation>La signature ne correspond pas au condensé du message.</translation>
</message>
<message>
<source>Message verification failed.</source>
<translation>Échec de vérification du message.</translation>
</message>
<message>
<source>Message verified.</source>
<translation>Le message a été vérifié.</translation>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
</context>
<context>
<name>TrafficGraphWidget</name>
<message>
<source>KB/s</source>
<translation>Ko/s</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message numerus="yes">
<source>Open for %n more block(s)</source>
<translation><numerusform>Ouvert pendant encore %n bloc</numerusform><numerusform>Ouvert pendant encore %n blocs</numerusform></translation>
</message>
<message>
<source>Open until %1</source>
<translation>Ouvert jusqu'à %1</translation>
</message>
<message>
<source>conflicted with a transaction with %1 confirmations</source>
<translation>est en conflit avec une transaction ayant %1 confirmations</translation>
</message>
<message>
<source>%1/offline</source>
<translation>%1/hors ligne</translation>
</message>
<message>
<source>0/unconfirmed, %1</source>
<translation>0/non confirmées, %1</translation>
</message>
<message>
<source>in memory pool</source>
<translation>dans la réserve de mémoire</translation>
</message>
<message>
<source>not in memory pool</source>
<translation>pas dans la réserve de mémoire</translation>
</message>
<message>
<source>abandoned</source>
<translation>abandonnée</translation>
</message>
<message>
<source>%1/unconfirmed</source>
<translation>%1/non confirmée</translation>
</message>
<message>
<source>%1 confirmations</source>
<translation>%1 confirmations</translation>
</message>
<message>
<source>Status</source>
<translation>État</translation>
</message>
<message>
<source>, has not been successfully broadcast yet</source>
<translation>, n’a pas encore été diffusée avec succès</translation>
</message>
<message numerus="yes">
<source>, broadcast through %n node(s)</source>
<translation><numerusform>, diffusée par %n nœud</numerusform><numerusform>, diffusée par %n nœuds</numerusform></translation>
</message>
<message>
<source>Date</source>
<translation>Date</translation>
</message>
<message>
<source>Source</source>
<translation>Source</translation>
</message>
<message>
<source>Generated</source>
<translation>Générée</translation>
</message>
<message>
<source>From</source>
<translation>De</translation>
</message>
<message>
<source>unknown</source>
<translation>inconnue</translation>
</message>
<message>
<source>To</source>
<translation>À</translation>
</message>
<message>
<source>own address</source>
<translation>votre adresse</translation>
</message>
<message>
<source>watch-only</source>
<translation>juste-regarder</translation>
</message>
<message>
<source>label</source>
<translation>étiquette</translation>
</message>
<message>
<source>Credit</source>
<translation>Crédit</translation>
</message>
<message numerus="yes">
<source>matures in %n more block(s)</source>
<translation><numerusform>arrivera à maturité dans %n bloc</numerusform><numerusform>arrivera à maturité dans %n blocs</numerusform></translation>
</message>
<message>
<source>not accepted</source>
<translation>refusée</translation>
</message>
<message>
<source>Debit</source>
<translation>Débit</translation>
</message>
<message>
<source>Total debit</source>
<translation>Débit total</translation>
</message>
<message>
<source>Total credit</source>
<translation>Crédit total</translation>
</message>
<message>
<source>Transaction fee</source>
<translation>Frais de transaction</translation>
</message>
<message>
<source>Net amount</source>
<translation>Montant net</translation>
</message>
<message>
<source>Message</source>
<translation>Message</translation>
</message>
<message>
<source>Comment</source>
<translation>Commentaire</translation>
</message>
<message>
<source>Transaction ID</source>
<translation>ID de la transaction</translation>
</message>
<message>
<source>Transaction total size</source>
<translation>Taille totale de la transaction</translation>
</message>
<message>
<source>Output index</source>
<translation>Index de sorties</translation>
</message>
<message>
<source>Merchant</source>
<translation>Marchand</translation>
</message>
<message>
<source>Generated coins must mature %1 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation>Les pièces générées doivent mûrir pendant %1 blocs avant de pouvoir être dépensées. Lorsque ce bloc a été généré, il a été diffusé sur le réseau pour être ajouté à la chaîne de blocs. Si son intégration à la chaîne échoue, son état sera modifié en « refusée » et il ne sera pas possible de le dépenser. Cela peut arriver occasionnellement si un autre nœud génère un bloc à quelques secondes du vôtre.</translation>
</message>
<message>
<source>Debug information</source>
<translation>Informations de débogage</translation>
</message>
<message>
<source>Transaction</source>
<translation>Transaction</translation>
</message>
<message>
<source>Inputs</source>
<translation>Entrées</translation>
</message>
<message>
<source>Amount</source>
<translation>Montant</translation>
</message>
<message>
<source>true</source>
<translation>vrai</translation>
</message>
<message>
<source>false</source>
<translation>faux</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<source>This pane shows a detailed description of the transaction</source>
<translation>Ce panneau affiche une description détaillée de la transaction</translation>
</message>
<message>
<source>Details for %1</source>
<translation>Détails de %1</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<source>Date</source>
<translation>Date</translation>
</message>
<message>
<source>Type</source>
<translation>Type</translation>
</message>
<message>
<source>Label</source>
<translation>Étiquette</translation>
</message>
<message numerus="yes">
<source>Open for %n more block(s)</source>
<translation><numerusform>Ouvert pendant encore %n bloc</numerusform><numerusform>Ouvert pendant encore %n blocs</numerusform></translation>
</message>
<message>
<source>Open until %1</source>
<translation>Ouvert jusqu'à %1</translation>
</message>
<message>
<source>Offline</source>
<translation>Hors ligne</translation>
</message>
<message>
<source>Unconfirmed</source>
<translation>Non confirmée</translation>
</message>
<message>
<source>Abandoned</source>
<translation>Abandonnée</translation>
</message>
<message>
<source>Confirming (%1 of %2 recommended confirmations)</source>
<translation>Confirmation (%1 sur %2 confirmations recommandées)</translation>
</message>
<message>
<source>Confirmed (%1 confirmations)</source>
<translation>Confirmée (%1 confirmations)</translation>
</message>
<message>
<source>Conflicted</source>
<translation>En conflit</translation>
</message>
<message>
<source>Immature (%1 confirmations, will be available after %2)</source>
<translation>Immature (%1 confirmations, sera disponible après %2)</translation>
</message>
<message>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>Ce bloc n’a été reçu par aucun autre nœud et ne sera probablement pas accepté !</translation>
</message>
<message>
<source>Generated but not accepted</source>
<translation>Générée mais refusée</translation>
</message>
<message>
<source>Received with</source>
<translation>Reçue avec</translation>
</message>
<message>
<source>Received from</source>
<translation>Reçue de</translation>
</message>
<message>
<source>Sent to</source>
<translation>Envoyée à</translation>
</message>
<message>
<source>Payment to yourself</source>
<translation>Paiement à vous-même</translation>
</message>
<message>
<source>Mined</source>
<translation>Miné</translation>
</message>
<message>
<source>watch-only</source>
<translation>juste-regarder</translation>
</message>
<message>
<source>(n/a)</source>
<translation>(n.d)</translation>
</message>
<message>
<source>(no label)</source>
<translation>(aucune étiquette)</translation>
</message>
<message>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>État de la transaction. Survoler ce champ avec la souris pour afficher le nombre de confirmations.</translation>
</message>
<message>
<source>Date and time that the transaction was received.</source>
<translation>Date et heure de réception de la transaction.</translation>
</message>
<message>
<source>Type of transaction.</source>
<translation>Type de transaction.</translation>
</message>
<message>
<source>Whether or not a watch-only address is involved in this transaction.</source>
<translation>Une adresse juste-regarder est-elle ou non impliquée dans cette transaction.</translation>
</message>
<message>
<source>User-defined intent/purpose of the transaction.</source>
<translation>Intention/but de la transaction défini par l'utilisateur.</translation>
</message>
<message>
<source>Amount removed from or added to balance.</source>
<translation>Le montant a été ajouté ou soustrait du solde.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<source>All</source>
<translation>Toutes</translation>
</message>
<message>
<source>Today</source>
<translation>Aujourd’hui</translation>
</message>
<message>
<source>This week</source>
<translation>Cette semaine</translation>
</message>
<message>
<source>This month</source>
<translation>Ce mois</translation>
</message>
<message>
<source>Last month</source>
<translation>Le mois dernier</translation>
</message>
<message>
<source>This year</source>
<translation>Cette année</translation>
</message>
<message>
<source>Range...</source>
<translation>Plage…</translation>
</message>
<message>
<source>Received with</source>
<translation>Reçue avec</translation>
</message>
<message>
<source>Sent to</source>
<translation>Envoyée à</translation>
</message>
<message>
<source>To yourself</source>
<translation>À vous-même</translation>
</message>
<message>
<source>Mined</source>
<translation>Miné </translation>
</message>
<message>
<source>Other</source>
<translation>Autres </translation>
</message>
<message>
<source>Enter address or label to search</source>
<translation>Saisir une adresse ou une étiquette à rechercher</translation>
</message>
<message>
<source>Min amount</source>
<translation>Montant min.</translation>
</message>
<message>
<source>Abandon transaction</source>
<translation>Abandonner la transaction</translation>
</message>
<message>
<source>Copy address</source>
<translation>Copier l’adresse</translation>
</message>
<message>
<source>Copy label</source>
<translation>Copier l’étiquette </translation>
</message>
<message>
<source>Copy amount</source>
<translation>Copier le montant </translation>
</message>
<message>
<source>Copy transaction ID</source>
<translation>Copier l'ID de la transaction</translation>
</message>
<message>
<source>Copy raw transaction</source>
<translation>Copier la transaction brute</translation>
</message>
<message>
<source>Copy full transaction details</source>
<translation>Copier tous les détails de la transaction</translation>
</message>
<message>
<source>Edit label</source>
<translation>Modifier l’étiquette </translation>
</message>
<message>
<source>Show transaction details</source>
<translation>Afficher les détails de la transaction</translation>
</message>
<message>
<source>Export Transaction History</source>
<translation>Exporter l'historique transactionnel</translation>
</message>
<message>
<source>Comma separated file (*.csv)</source>
<translation>Valeurs séparées par des virgules (*.csv)</translation>
</message>
<message>
<source>Confirmed</source>
<translation>Confirmée</translation>
</message>
<message>
<source>Watch-only</source>
<translation>Juste-regarder</translation>
</message>
<message>
<source>Date</source>
<translation>Date </translation>
</message>
<message>
<source>Type</source>
<translation>Type </translation>
</message>
<message>
<source>Label</source>
<translation>Étiquette</translation>
</message>
<message>
<source>Address</source>
<translation>Adresse</translation>
</message>
<message>
<source>ID</source>
<translation>ID </translation>
</message>
<message>
<source>Exporting Failed</source>
<translation>Échec d'exportation</translation>
</message>
<message>
<source>There was an error trying to save the transaction history to %1.</source>
<translation>Une erreur est survenue lors de l'enregistrement de l'historique transactionnel vers %1.</translation>
</message>
<message>
<source>Exporting Successful</source>
<translation>L'exportation est réussie</translation>
</message>
<message>
<source>The transaction history was successfully saved to %1.</source>
<translation>L'historique transactionnel a été enregistré avec succès vers %1.</translation>
</message>
<message>
<source>Range:</source>
<translation>Plage :</translation>
</message>
<message>
<source>to</source>
<translation>à </translation>
</message>
</context>
<context>
<name>UnitDisplayStatusBarControl</name>
<message>
<source>Unit to show amounts in. Click to select another unit.</source>
<translation>Unité d'affichage des montants. Cliquer pour choisir une autre unité.</translation>
</message>
</context>
<context>
<name>WalletFrame</name>
<message>
<source>No wallet has been loaded.</source>
<translation>Aucun porte-monnaie n'a été chargé.</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<source>Send Coins</source>
<translation>Envoyer des pièces</translation>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<source>&Export</source>
<translation>&Exporter</translation>
</message>
<message>
<source>Export the data in the current tab to a file</source>
<translation>Exporter les données de l'onglet actuel vers un fichier</translation>
</message>
<message>
<source>Backup Wallet</source>
<translation>Sauvegarder le porte-monnaie</translation>
</message>
<message>
<source>Wallet Data (*.dat)</source>
<translation>Données du porte-monnaie (*.dat)</translation>
</message>
<message>
<source>Backup Failed</source>
<translation>Échec de la sauvegarde</translation>
</message>
<message>
<source>There was an error trying to save the wallet data to %1.</source>
<translation>Une erreur est survenue lors de l'enregistrement des données du porte-monnaie vers %1.</translation>
</message>
<message>
<source>Backup Successful</source>
<translation>La sauvegarde est réussie</translation>
</message>
<message>
<source>The wallet data was successfully saved to %1.</source>
<translation>Les données du porte-monnaie ont été enregistrées avec succès vers %1</translation>
</message>
</context>
<context>
<name>smartcoin-core</name>
<message>
<source>Options:</source>
<translation>Options :</translation>
</message>
<message>
<source>Specify data directory</source>
<translation>Spécifier le répertoire de données</translation>
</message>
<message>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation>Se connecter à un nœud pour obtenir des adresses de pairs puis se déconnecter</translation>
</message>
<message>
<source>Specify your own public address</source>
<translation>Spécifier votre propre adresse publique</translation>
</message>
<message>
<source>Accept command line and JSON-RPC commands</source>
<translation>Accepter les commandes JSON-RPC et en ligne de commande</translation>
</message>
<message>
<source>Accept connections from outside (default: 1 if no -proxy or -connect/-noconnect)</source>
<translation>Accepter des connexions de l'extérieur (par défaut : 1 si aucun -proxy ou -connect/-noconnect)</translation>
</message>
<message>
<source>Connect only to the specified node(s); -noconnect or -connect=0 alone to disable automatic connections</source>
<translation>Se connecter seulement aux nœuds précisés ; -noconnect ou -connect=0 seul pour désactiver les connexions automatiques</translation>
</message>
<message>
<source>Distributed under the MIT software license, see the accompanying file %s or %s</source>
<translation>Distribué sous la licence MIT d'utilisation d'un logiciel. Consulter le fichier joint %s ou %s</translation>
</message>
<message>
<source>If <category> is not supplied or if <category> = 1, output all debugging information.</source>
<translation>Si <category> n'est pas indiqué ou si <category> = 1, extraire toutes les données de débogage.</translation>
</message>
<message>
<source>Prune configured below the minimum of %d MiB. Please use a higher number.</source>
<translation>L'élagage est configuré au-dessous du minimum de %d Mio. Veuillez utiliser un nombre plus élevé.</translation>
</message>
<message>
<source>Prune: last wallet synchronisation goes beyond pruned data. You need to -reindex (download the whole blockchain again in case of pruned node)</source>
<translation>Élagage : la dernière synchronisation de porte-monnaie va par-delà les données élaguées. Vous devez -reindex (réindexer, télécharger de nouveau toute la chaîne de blocs en cas de nœud élagué)</translation>
</message>
<message>
<source>Rescans are not possible in pruned mode. You will need to use -reindex which will download the whole blockchain again.</source>
<translation>Les rebalayages sont impossibles en mode élagage. Vous devrez utiliser -reindex, ce qui téléchargera de nouveau la chaîne de blocs en entier.</translation>
</message>
<message>
<source>Error: A fatal internal error occurred, see debug.log for details</source>
<translation>Erreur : une erreur interne fatale s'est produite. Voir debug.log pour plus de détails</translation>
</message>
<message>
<source>Fee (in %s/kB) to add to transactions you send (default: %s)</source>
<translation>Les frais (en %s/ko) à ajouter aux transactions que vous envoyez (par défaut : %s)</translation>
</message>
<message>
<source>Pruning blockstore...</source>
<translation>Élagage du magasin de blocs...</translation>
</message>
<message>
<source>Run in the background as a daemon and accept commands</source>
<translation>Fonctionner en arrière-plan en tant que démon et accepter les commandes</translation>
</message>
<message>
<source>Unable to start HTTP server. See debug log for details.</source>
<translation>Impossible de démarrer le serveur HTTP. Voir le journal de débogage pour plus de détails.</translation>
</message>
<message>
<source>Smartcoin Core</source>
<translation>Smartcoin Core</translation>
</message>
<message>
<source>The %s developers</source>
<translation>Les développeurs de %s</translation>
</message>
<message>
<source>A fee rate (in %s/kB) that will be used when fee estimation has insufficient data (default: %s)</source>
<translation>Un taux de frais (en %s/Ko) qui sera utilisé si l'estimation de frais ne possède pas suffisamment de données (par défaut : %s)</translation>
</message>
<message>
<source>Accept relayed transactions received from whitelisted peers even when not relaying transactions (default: %d)</source>
<translation>Accepter les transactions relayées reçues de pairs de la liste blanche même si le nœud ne relaie pas les transactions (par défaut : %d)</translation>
</message>
<message>
<source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source>
<translation>Se lier à l'adresse donnée et toujours l'écouter. Utiliser la notation [host]:port pour l'IPv6</translation>
</message>
<message>
<source>Cannot obtain a lock on data directory %s. %s is probably already running.</source>
<translation>Impossible d’obtenir un verrou sur le répertoire de données %s. %s fonctionne probablement déjà.</translation>
</message>
<message>
<source>Delete all wallet transactions and only recover those parts of the blockchain through -rescan on startup</source>
<translation>Supprimer toutes les transactions du porte-monnaie et ne récupérer que ces parties de la chaîne de blocs avec -rescan au démarrage</translation>
</message>
<message>
<source>Error loading %s: You can't enable HD on a already existing non-HD wallet</source>
<translation>Erreur de chargement de %s : vous ne pouvez pas activer HD sur un porte-monnaie non HD existant</translation>
</message>
<message>
<source>Error reading %s! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation>Erreur de lecture de %s ! Toutes les clés ont été lues correctement, mais les données transactionnelles ou les entrées du carnet d'adresses sont peut-être manquantes ou incorrectes.</translation>
</message>
<message>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation>Exécuter la commande lorsqu'une transaction de porte-monnaie change (%s dans la commande est remplacée par TxID)</translation>
</message>
<message>
<source>If this block is in the chain assume that it and its ancestors are valid and potentially skip their script verification (0 to verify all, default: %s, testnet: %s)</source>
<translation>Si ce bloc est dans la chaîne, supposer qu'il est valide, ainsi que ces ancêtres, et ignorer potentiellement la vérification de leur script (0 pour tout vérifier, valeur par défaut : %s, réseau de test : %s)</translation>
</message>
<message>
<source>Maximum allowed median peer time offset adjustment. Local perspective of time may be influenced by peers forward or backward by this amount. (default: %u seconds)</source>
<translation>Réglage moyen maximal autorisé de décalage de l'heure d'un pair. La perspective locale du temps peut être influencée par les pairs, en avance ou en retard, de cette valeur. (Par défaut : %u secondes)</translation>
</message>
<message>
<source>Maximum total fees (in %s) to use in a single wallet transaction or raw transaction; setting this too low may abort large transactions (default: %s)</source>
<translation>Frais totaux maximaux (en %s) à utiliser en une seule transaction de porte-monnaie ou transaction brute ; les définir trop bas pourrait interrompre les grosses transactions (par défaut : %s)</translation>
</message>
<message>
<source>Please check that your computer's date and time are correct! If your clock is wrong, %s will not work properly.</source>
<translation>Veuillez vérifier que l'heure et la date de votre ordinateur sont justes ! Si votre horloge n'est pas à l'heure, %s ne fonctionnera pas correctement.</translation>
</message>
<message>
<source>Please contribute if you find %s useful. Visit %s for further information about the software.</source>
<translation>Si vous trouvez %s utile, vous pouvez y contribuer. Vous trouverez davantage d'informations à propos du logiciel sur %s.</translation>
</message>
<message>
<source>Reduce storage requirements by enabling pruning (deleting) of old blocks. This allows the pruneblockchain RPC to be called to delete specific blocks, and enables automatic pruning of old blocks if a target size in MiB is provided. This mode is incompatible with -txindex and -rescan. Warning: Reverting this setting requires re-downloading the entire blockchain. (default: 0 = disable pruning blocks, 1 = allow manual pruning via RPC, >%u = automatically prune block files to stay under the specified target size in MiB)</source>
<translation>Réduire les exigences de stockage en activant l'élagage (suppression) des anciens blocs. Cela permet d'appeler le RPC « pruneblockchain » pour supprimer des blocs précis et active l'élagage automatique des anciens blocs si une taille cible en Mio est fournie. Ce mode n'est pas compatible avec -txindex et -rescan. Avertissement : ramener ce paramètre à sa valeur antérieure exige de retélécharger l'intégralité de la chaîne de blocs (par défaut : 0 = désactiver l'élagage des blocs, 1 = permettre l'élagage manuel par RPC, >%u = élaguer automatiquement les fichiers de blocs pour rester en deçà de la taille cible précisée en Mio).</translation>
</message>
<message>
<source>Set lowest fee rate (in %s/kB) for transactions to be included in block creation. (default: %s)</source>
<translation>Définir le taux minimal de frais (en %s/ko) pour les transactions à inclure dans la création de blocs (par défaut : %s)</translation>
</message>
<message>
<source>Set the number of script verification threads (%u to %d, 0 = auto, <0 = leave that many cores free, default: %d)</source>
<translation>Définir le nombre de fils de vérification des scripts (%u à %d, 0 = auto, < 0 = laisser ce nombre de cœurs inutilisés, par défaut : %d)</translation>
</message>
<message>
<source>The block database contains a block which appears to be from the future. This may be due to your computer's date and time being set incorrectly. Only rebuild the block database if you are sure that your computer's date and time are correct</source>
<translation>La base de données de blocs contient un bloc qui semble provenir du futur. Cela pourrait être causé par la date et l'heure erronées de votre ordinateur. Ne reconstruisez la base de données de blocs que si vous êtes certain que la date et l'heure de votre ordinateur sont justes.</translation>
</message>
<message>
<source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source>
<translation>Ceci est une préversion de test - son utilisation est entièrement à vos risques - ne pas l'utiliser pour miner ou pour des applications marchandes</translation>
</message>
<message>
<source>Unable to rewind the database to a pre-fork state. You will need to redownload the blockchain</source>
<translation>Impossible de rebobiner la base de données à un état préfourche. Vous devrez retélécharger la chaîne de blocs</translation>
</message>
<message>
<source>Use UPnP to map the listening port (default: 1 when listening and no -proxy)</source>
<translation>Utiliser l'UPnP pour mapper le port d'écoute (par défaut : 1 en écoute et sans -proxy)</translation>
</message>
<message>
<source>Username and hashed password for JSON-RPC connections. The field <userpw> comes in the format: <USERNAME>:<SALT>$<HASH>. A canonical python script is included in share/rpcuser. The client then connects normally using the rpcuser=<USERNAME>/rpcpassword=<PASSWORD> pair of arguments. This option can be specified multiple times</source>
<translation>Nom d'utilisateur et mot de passe haché pour les connexions JSON-RPC. Le champ <userpw> est au format : <USERNAME>:<SALT>$<HASH>. Un script python canonique est inclus dans share/rpcuser. Le client se connecte ensuite normalement en utilisant la paire d'arguments rpcuser=<USERNAME>/rpcpassword=<PASSWORD>. Cette option peut être spécifiée plusieurs fois.</translation>
</message>
<message>
<source>Wallet will not create transactions that violate mempool chain limits (default: %u)</source>
<translation>Un porte-monnaie ne créera aucune transaction qui enfreint les limites de chaîne de la réserve de mémoire (par défaut : %u)</translation>
</message>
<message>
<source>Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.</source>
<translation>Avertissement : le réseau ne semble pas totalement d'accord ! Certains mineurs semblent éprouver des problèmes.</translation>
</message>
<message>
<source>Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade.</source>
<translation>Avertissement : nous ne semblons pas être en accord complet avec nos pairs ! Une mise à niveau pourrait être nécessaire pour vous ou pour d'autres nœuds du réseau.</translation>
</message>
<message>
<source>You need to rebuild the database using -reindex-chainstate to change -txindex</source>
<translation>Vous devez reconstruire la base de données avec -reindex-chainstate pour changer -txindex</translation>
</message>
<message>
<source>%s corrupt, salvage failed</source>
<translation>%s corrompu, la récupération a échoué</translation>
</message>
<message>
<source>-maxmempool must be at least %d MB</source>
<translation>-maxmempool doit être d'au moins %d Mo</translation>
</message>
<message>
<source><category> can be:</source>
<translation><category> peut être :</translation>
</message>
<message>
<source>Append comment to the user agent string</source>
<translation>Ajouter un commentaire à la chaîne d'agent utilisateur</translation>
</message>
<message>
<source>Attempt to recover private keys from a corrupt wallet on startup</source>
<translation>Tenter de récupérer les clés privées d'un porte-monnaie corrompu lors du démarrage</translation>
</message>
<message>
<source>Block creation options:</source>
<translation>Options de création de blocs :</translation>
</message>
<message>
<source>Cannot resolve -%s address: '%s'</source>
<translation>Impossible de résoudre l'adresse -%s : « %s »</translation>
</message>
<message>
<source>Chain selection options:</source>
<translation>Options de sélection de la chaîne :</translation>
</message>
<message>
<source>Change index out of range</source>
<translation>L'index de changement est hors échelle</translation>
</message>
<message>
<source>Connection options:</source>
<translation>Options de connexion :</translation>
</message>
<message>
<source>Copyright (C) %i-%i</source>
<translation>Tous droits réservés (C) %i-%i</translation>
</message>
<message>
<source>Corrupted block database detected</source>
<translation>Une base de données de blocs corrompue a été détectée</translation>
</message>
<message>
<source>Debugging/Testing options:</source>
<translation>Options de débogage/de test :</translation>
</message>
<message>
<source>Do not load the wallet and disable wallet RPC calls</source>
<translation>Ne pas charger le porte-monnaie et désactiver les appels RPC</translation>
</message>
<message>
<source>Do you want to rebuild the block database now?</source>
<translation>Voulez-vous reconstruire la base de données de blocs maintenant ?</translation>
</message>
<message>
<source>Enable publish hash block in <address></source>
<translation>Activer la publication du bloc de hachage dans <address></translation>
</message>
<message>
<source>Enable publish hash transaction in <address></source>
<translation>Activer la publication de la transaction de hachage dans <address></translation>
</message>
<message>
<source>Enable publish raw block in <address></source>
<translation>Activer la publication du bloc brut dans <address></translation>
</message>
<message>
<source>Enable publish raw transaction in <address></source>
<translation>Activer la publication de la transaction brute dans <address></translation>
</message>
<message>
<source>Enable transaction replacement in the memory pool (default: %u)</source>
<translation>Activer le remplacement de transactions dans la réserve de mémoire (par défaut : %u)</translation>
</message>
<message>
<source>Error initializing block database</source>
<translation>Erreur d'initialisation de la base de données de blocs</translation>
</message>
<message>
<source>Error initializing wallet database environment %s!</source>
<translation>Erreur d'initialisation de l'environnement de la base de données du porte-monnaie %s !</translation>
</message>
<message>
<source>Error loading %s</source>
<translation>Erreur de chargement de %s</translation>
</message>
<message>
<source>Error loading %s: Wallet corrupted</source>
<translation>Erreur de chargement de %s : porte-monnaie corrompu</translation>
</message>
<message>
<source>Error loading %s: Wallet requires newer version of %s</source>
<translation>Erreur de chargement de %s : le porte-monnaie exige une version plus récente de %s</translation>
</message>
<message>
<source>Error loading %s: You can't disable HD on a already existing HD wallet</source>
<translation>Erreur de chargement de %s : vous ne pouvez pas désactiver HD sur un porte-monnaie HD existant</translation>
</message>
<message>
<source>Error loading block database</source>
<translation>Erreur de chargement de la base de données de blocs</translation>
</message>
<message>
<source>Error opening block database</source>
<translation>Erreur d'ouverture de la base de données de blocs</translation>
</message>
<message>
<source>Error: Disk space is low!</source>
<translation>Erreur : l'espace disque est faible !</translation>
</message>
<message>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation>Échec d'écoute sur un port quelconque. Utiliser -listen=0 si vous le voulez.</translation>
</message>
<message>
<source>Importing...</source>
<translation>Importation...</translation>
</message>
<message>
<source>Incorrect or no genesis block found. Wrong datadir for network?</source>
<translation>Bloc de genèse incorrect ou introuvable. Mauvais datadir pour le réseau ?</translation>
</message>
<message>
<source>Initialization sanity check failed. %s is shutting down.</source>
<translation>L'initialisation du test de cohérence a échoué. %s est en cours de fermeture. </translation>
</message>
<message>
<source>Invalid -onion address: '%s'</source>
<translation>Adresse -onion invalide : « %s »</translation>
</message>
<message>
<source>Invalid amount for -%s=<amount>: '%s'</source>
<translation>Montant invalide pour -%s=<amount> : « %s »</translation>
</message>
<message>
<source>Invalid amount for -fallbackfee=<amount>: '%s'</source>
<translation>Montant invalide pour -fallbackfee=<amount> : « %s »</translation>
</message>
<message>
<source>Keep the transaction memory pool below <n> megabytes (default: %u)</source>
<translation>Garder la réserve de mémoire transactionnelle sous <n> mégaoctets (par défaut : %u)</translation>
</message>
<message>
<source>Loading banlist...</source>
<translation>Chargement de la liste d'interdiction...</translation>
</message>
<message>
<source>Location of the auth cookie (default: data dir)</source>
<translation>Emplacement du fichier témoin auth (par défaut : data dir)</translation>
</message>
<message>
<source>Not enough file descriptors available.</source>
<translation>Pas assez de descripteurs de fichiers proposés.</translation>
</message>
<message>
<source>Only connect to nodes in network <net> (ipv4, ipv6 or onion)</source>
<translation>Seulement se connecter aux nœuds du réseau <net> (IPv4, IPv6 ou oignon)</translation>
</message>
<message>
<source>Print this help message and exit</source>
<translation>Imprimer ce message d'aide et quitter</translation>
</message>
<message>
<source>Print version and exit</source>
<translation>Imprimer la version et quitter</translation>
</message>
<message>
<source>Prune cannot be configured with a negative value.</source>
<translation>L'élagage ne peut pas être configuré avec une valeur négative.</translation>
</message>
<message>
<source>Prune mode is incompatible with -txindex.</source>
<translation>Le mode élagage n'est pas compatible avec -txindex.</translation>
</message>
<message>
<source>Rebuild chain state and block index from the blk*.dat files on disk</source>
<translation>Reconstruire l'état de la chaîne et l'index des blocs à partir des fichiers blk*.dat sur le disque</translation>
</message>
<message>
<source>Rebuild chain state from the currently indexed blocks</source>
<translation>Reconstruire l'état de la chaîne à partir des blocs indexés actuellement</translation>
</message>
<message>
<source>Rewinding blocks...</source>
<translation>Rebobinage des blocs...</translation>
</message>
<message>
<source>Set database cache size in megabytes (%d to %d, default: %d)</source>
<translation>Définir la taille du cache de la base de données en mégaoctets (%d à %d, default: %d)</translation>
</message>
<message>
<source>Set maximum block size in bytes (default: %d)</source>
<translation>Définir la taille minimale de bloc en octets (par défaut : %d)</translation>
</message>
<message>
<source>Specify wallet file (within data directory)</source>
<translation>Spécifiez le fichier de porte-monnaie (dans le répertoire de données)</translation>
</message>
<message>
<source>The source code is available from %s.</source>
<translation>Le code source est disponible sur %s.</translation>
</message>
<message>
<source>Unable to bind to %s on this computer. %s is probably already running.</source>
<translation>Impossible de se lier à %s sur cet ordinateur. %s fonctionne probablement déjà.</translation>
</message>
<message>
<source>Unsupported argument -benchmark ignored, use -debug=bench.</source>
<translation>Argument non pris en charge -benchmark ignoré, utiliser -debug=bench.</translation>
</message>
<message>
<source>Unsupported argument -debugnet ignored, use -debug=net.</source>
<translation>Argument non pris en charge -debugnet ignoré, utiliser -debug=net.</translation>
</message>
<message>
<source>Unsupported argument -tor found, use -onion.</source>
<translation>Argument non pris en charge -tor trouvé, utiliser -onion</translation>
</message>
<message>
<source>Use UPnP to map the listening port (default: %u)</source>
<translation>Utiliser l'UPnP pour mapper le port d'écoute (par défaut : %u)</translation>
</message>
<message>
<source>Use the test chain</source>
<translation>Utiliser la chaîne de test</translation>
</message>
<message>
<source>User Agent comment (%s) contains unsafe characters.</source>
<translation>Le commentaire d'agent utilisateur (%s) contient des caractères dangereux.</translation>
</message>
<message>
<source>Verifying blocks...</source>
<translation>Vérification des blocs... </translation>
</message>
<message>
<source>Verifying wallet...</source>
<translation>Vérification du porte-monnaie...</translation>
</message>
<message>
<source>Wallet %s resides outside data directory %s</source>
<translation>Le porte-monnaie %s réside en dehors du répertoire de données %s</translation>
</message>
<message>
<source>Wallet debugging/testing options:</source>
<translation>Options de débogage/de test du porte-monnaie :</translation>
</message>
<message>
<source>Wallet needed to be rewritten: restart %s to complete</source>
<translation>Le porte-monnaie devait être réécrit : redémarrer %s pour terminer l'opération.</translation>
</message>
<message>
<source>Wallet options:</source>
<translation>Options du porte-monnaie :</translation>
</message>
<message>
<source>Allow JSON-RPC connections from specified source. Valid for <ip> are a single IP (e.g. 1.2.3.4), a network/netmask (e.g. 1.2.3.4/255.255.255.0) or a network/CIDR (e.g. 1.2.3.4/24). This option can be specified multiple times</source>
<translation>Permettre les connexions JSON-RPC de sources spécifiques. Valide pour <ip> qui sont une IP simple (p. ex. 1.2.3.4), un réseau/masque réseau (p. ex. 1.2.3.4/255.255.255.0) ou un réseau/CIDR (p. ex. 1.2.3.4/24). Cette option peut être être spécifiée plusieurs fois</translation>
</message>
<message>
<source>Bind to given address and whitelist peers connecting to it. Use [host]:port notation for IPv6</source>
<translation>Se lier à l'adresse donnée et aux pairs s'y connectant. Utiliser la notation [host]:port pour l'IPv6</translation>
</message>
<message>
<source>Bind to given address to listen for JSON-RPC connections. Use [host]:port notation for IPv6. This option can be specified multiple times (default: bind to all interfaces)</source>
<translation>Se lier à l'adresse donnée pour écouter des connexions JSON-RPC. Utiliser la notation [host]:port pour l'IPv6. Cette option peut être spécifiée plusieurs fois (par défaut : se lier à toutes les interfaces)</translation>
</message>
<message>
<source>Create new files with system default permissions, instead of umask 077 (only effective with disabled wallet functionality)</source>
<translation>Créer de nouveaux fichiers avec les permissions système par défaut, au lieu de umask 077 (effectif seulement avec la fonction du porte-monnaie désactivée)</translation>
</message>
<message>
<source>Discover own IP addresses (default: 1 when listening and no -externalip or -proxy)</source>
<translation>Découvrir ses propres adresses (par défaut : 1 en écoute et sans externalip ou -proxy)</translation>
</message>
<message>
<source>Error: Listening for incoming connections failed (listen returned error %s)</source>
<translation>Erreur : l'écoute des connexions entrantes a échoué (l'écoute a retourné l'erreur %s)</translation>
</message>
<message>
<source>Execute command when a relevant alert is received or we see a really long fork (%s in cmd is replaced by message)</source>
<translation>Exécuter une commande lorsqu'une alerte pertinente est reçue, ou si nous voyons une bifurcation vraiment étendue (%s dans la commande est remplacé par le message)</translation>
</message>
<message>
<source>Fees (in %s/kB) smaller than this are considered zero fee for relaying, mining and transaction creation (default: %s)</source>
<translation>Les frais (en %s/Ko) inférieurs à ce seuil sont considérés comme étant nuls pour le relais, le minage et la création de transactions (par défaut : %s)</translation>
</message>
<message>
<source>If paytxfee is not set, include enough fee so transactions begin confirmation on average within n blocks (default: %u)</source>
<translation>Si paytxfee n'est pas défini, inclure suffisamment de frais afin que les transactions commencent la confirmation en moyenne avant n blocs (par défaut : %u)</translation>
</message>
<message>
<source>Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)</source>
<translation>Montant invalide pour -maxtxfee=<amount> : « %s » (doit être au moins les frais minrelay de %s pour prévenir le blocage des transactions)</translation>
</message>
<message>
<source>Maximum size of data in data carrier transactions we relay and mine (default: %u)</source>
<translation>Quantité maximale de données dans les transactions du porteur de données que nous relayons et minons (par défaut : %u)</translation>
</message>
<message>
<source>Randomize credentials for every proxy connection. This enables Tor stream isolation (default: %u)</source>
<translation>Aléer les authentifiants pour chaque connexion mandataire. Cela active l'isolement de flux de Tor (par défaut : %u) </translation>
</message>
<message>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: %d)</source>
<translation>Définir la taille maximale en octets des transactions à priorité élevée et frais modiques (par défaut : %d)</translation>
</message>
<message>
<source>The transaction amount is too small to send after the fee has been deducted</source>
<translation>Le montant de la transaction est trop bas pour être envoyé une fois que les frais ont été déduits</translation>
</message>
<message>
<source>Use hierarchical deterministic key generation (HD) after BIP32. Only has effect during wallet creation/first start</source>
<translation>Utiliser une génération de clé hiérarchique déterministe (HD) après BIP32. N'a d'effet que lors de la création ou du lancement intitial du porte-monnaie</translation>
</message>
<message>
<source>Whitelisted peers cannot be DoS banned and their transactions are always relayed, even if they are already in the mempool, useful e.g. for a gateway</source>
<translation>Les pairs de la liste blanche ne peuvent pas être bannis DoS et leurs transactions sont toujours relayées, même si elles sont déjà dans le mempool, utile p. ex. pour une passerelle</translation>
</message>
<message>
<source>You need to rebuild the database using -reindex to go back to unpruned mode. This will redownload the entire blockchain</source>
<translation>Vous devez reconstruire la base de données en utilisant -reindex afin de revenir au mode sans élagage. Cela retéléchargera complètement la chaîne de blocs.</translation>
</message>
<message>
<source>(default: %u)</source>
<translation>(par défaut : %u)</translation>
</message>
<message>
<source>Accept public REST requests (default: %u)</source>
<translation>Accepter les demandes REST publiques (par défaut : %u)</translation>
</message>
<message>
<source>Automatically create Tor hidden service (default: %d)</source>
<translation>Créer automatiquement un service caché Tor (par défaut : %d)</translation>
</message>
<message>
<source>Connect through SOCKS5 proxy</source>
<translation>Se connecter par un mandataire SOCKS5</translation>
</message>
<message>
<source>Error reading from database, shutting down.</source>
<translation>Erreur de lecture de la base de données, fermeture en cours.</translation>
</message>
<message>
<source>Imports blocks from external blk000??.dat file on startup</source>
<translation>Importe des blocs à partir d'un fichier blk000??.dat externe lors du démarrage</translation>
</message>
<message>
<source>Information</source>
<translation>Informations</translation>
</message>
<message>
<source>Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)</source>
<translation>Montant invalide pour -paytxfee=<montant> : « %s » (doit être au moins %s)</translation>
</message>
<message>
<source>Invalid netmask specified in -whitelist: '%s'</source>
<translation>Masque réseau invalide spécifié dans -whitelist : « %s »</translation>
</message>
<message>
<source>Keep at most <n> unconnectable transactions in memory (default: %u)</source>
<translation>Garder au plus <n> transactions non connectables en mémoire (par défaut : %u)</translation>
</message>
<message>
<source>Need to specify a port with -whitebind: '%s'</source>
<translation>Un port doit être spécifié avec -whitebind : « %s »</translation>
</message>
<message>
<source>Node relay options:</source>
<translation>Options de relais du nœud :</translation>
</message>
<message>
<source>RPC server options:</source>
<translation>Options du serveur RPC :</translation>
</message>
<message>
<source>Reducing -maxconnections from %d to %d, because of system limitations.</source>
<translation>Réduction de -maxconnections de %d à %d, due aux restrictions du système</translation>
</message>
<message>
<source>Rescan the block chain for missing wallet transactions on startup</source>
<translation>Réanalyser la chaîne de blocs au démarrage, à la recherche de transactions de porte-monnaie manquantes</translation>
</message>
<message>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Envoyer les infos de débogage/trace à la console au lieu du fichier debug.log</translation>
</message>
<message>
<source>Send transactions as zero-fee transactions if possible (default: %u)</source>
<translation>Envoyer si possible les transactions comme étant sans frais (par défaut : %u)</translation>
</message>
<message>
<source>Show all debugging options (usage: --help -help-debug)</source>
<translation>Montrer toutes les options de débogage (utilisation : --help --help-debug)</translation>
</message>
<message>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation>Réduire le fichier debug.log lors du démarrage du client (par défaut : 1 sans -debug)</translation>
</message>
<message>
<source>Signing transaction failed</source>
<translation>Échec de signature de la transaction</translation>
</message>
<message>
<source>The transaction amount is too small to pay the fee</source>
<translation>Le montant de la transaction est trop bas pour que les frais soient payés</translation>
</message>
<message>
<source>This is experimental software.</source>
<translation>Ceci est un logiciel expérimental.</translation>
</message>
<message>
<source>Tor control port password (default: empty)</source>
<translation>Mot de passe du port de contrôle Tor (par défaut : vide)</translation>
</message>
<message>
<source>Tor control port to use if onion listening enabled (default: %s)</source>
<translation>Port de contrôle Tor à utiliser si l'écoute onion est activée (par défaut :%s)</translation>
</message>
<message>
<source>Transaction amount too small</source>
<translation>Le montant de la transaction est trop bas</translation>
</message>
<message>
<source>Transaction too large for fee policy</source>
<translation>La transaction est trop grosse pour la politique de frais</translation>
</message>
<message>
<source>Transaction too large</source>
<translation>La transaction est trop grosse</translation>
</message>
<message>
<source>Unable to bind to %s on this computer (bind returned error %s)</source>
<translation>Impossible de se lier à %s sur cet ordinateur (bind a retourné l'erreur %s)</translation>
</message>
<message>
<source>Upgrade wallet to latest format on startup</source>
<translation>Mettre à niveau le porte-monnaie au démarrage vers le format le plus récent</translation>
</message>
<message>
<source>Username for JSON-RPC connections</source>
<translation>Nom d'utilisateur pour les connexions JSON-RPC</translation>
</message>
<message>
<source>Warning</source>
<translation>Avertissement</translation>
</message>
<message>
<source>Warning: unknown new rules activated (versionbit %i)</source>
<translation>Avertissement : nouvelles règles inconnues activées (bit de version %i)</translation>
</message>
<message>
<source>Whether to operate in a blocks only mode (default: %u)</source>
<translation>Faut-il fonctionner en mode blocs seulement (par défaut : %u)</translation>
</message>
<message>
<source>Zapping all transactions from wallet...</source>
<translation>Supprimer toutes les transactions du porte-monnaie...</translation>
</message>
<message>
<source>ZeroMQ notification options:</source>
<translation>Options de notification ZeroMQ</translation>
</message>
<message>
<source>Password for JSON-RPC connections</source>
<translation>Mot de passe pour les connexions JSON-RPC</translation>
</message>
<message>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>Exécuter la commande lorsque le meilleur bloc change (%s dans cmd est remplacé par le hachage du bloc)</translation>
</message>
<message>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>Autoriser les recherches DNS pour -addnode, -seednode et -connect</translation>
</message>
<message>
<source>Loading addresses...</source>
<translation>Chargement des adresses…</translation>
</message>
<message>
<source>(1 = keep tx meta data e.g. account owner and payment request information, 2 = drop tx meta data)</source>
<translation>(1 = conserver les métadonnées de transmission, p. ex. les informations du propriétaire du compte et de demande de paiement, 2 = abandonner les métadonnées de transmission)</translation>
</message>
<message>
<source>-maxtxfee is set very high! Fees this large could be paid on a single transaction.</source>
<translation>La valeur -maxtxfee est très élevée ! Des frais aussi élevés pourraient être payés en une seule transaction.</translation>
</message>
<message>
<source>Do not keep transactions in the mempool longer than <n> hours (default: %u)</source>
<translation>Ne pas conserver de transactions dans la réserve de mémoire plus de <n> heures (par défaut : %u)</translation>
</message>
<message>
<source>Equivalent bytes per sigop in transactions for relay and mining (default: %u)</source>
<translation>Octets équivalents par sigop dans les transactions pour relayer et miner (par défaut : %u)</translation>
</message>
<message>
<source>Fees (in %s/kB) smaller than this are considered zero fee for transaction creation (default: %s)</source>
<translation>Les frais (en %s/Ko) inférieurs à ce seuil sont considérés comme étant nuls pour la création de transactions (par défaut : %s)</translation>
</message>
<message>
<source>Force relay of transactions from whitelisted peers even if they violate local relay policy (default: %d)</source>
<translation>Forcer le relais de transactions des pairs de la liste blanche même s'ils transgressent la politique locale de relais (par défaut : %d)</translation>
</message>
<message>
<source>How thorough the block verification of -checkblocks is (0-4, default: %u)</source>
<translation>Degré de profondeur de la vérification des blocs -checkblocks (0-4, par défaut : %u)</translation>
</message>
<message>
<source>Maintain a full transaction index, used by the getrawtransaction rpc call (default: %u)</source>
<translation>Maintenir un index complet des transactions, utilisé par l'appel RPC getrawtransaction (obtenir la transaction brute) (par défaut : %u)</translation>
</message>
<message>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: %u)</source>
<translation>Délai en secondes de refus de reconnexion pour les pairs présentant un mauvais comportement (par défaut : %u)</translation>
</message>
<message>
<source>Output debugging information (default: %u, supplying <category> is optional)</source>
<translation>Extraire les informations de débogage (par défaut : %u, fournir <category> est facultatif)</translation>
</message>
<message>
<source>Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect/-noconnect)</source>
<translation>Requête d'adresses de paires par recherche DNS, si il y a peu d'adresses (par défaut : 1 sauf si -connect/-noconnect)</translation>
</message>
<message>
<source>Sets the serialization of raw transaction or block hex returned in non-verbose mode, non-segwit(0) or segwit(1) (default: %d)</source>
<translation>Définit la sérialisation de la transaction brute ou les données hexa de bloc retournées en mode non-verbose, non-segwit(0) ou segwit(1) (par défaut : %d)</translation>
</message>
<message>
<source>Support filtering of blocks and transaction with bloom filters (default: %u)</source>
<translation>Prendre en charge le filtrage des blocs et des transactions avec les filtres bloom (par défaut : %u)</translation>
</message>
<message>
<source>This is the transaction fee you may pay when fee estimates are not available.</source>
<translation>Il s'agit des frais de transaction que vous pourriez payer si aucune estimation de frais n'est proposée.</translation>
</message>
<message>
<source>This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit %s and cryptographic software written by Eric Young and UPnP software written by Thomas Bernard.</source>
<translation>Ce produit comprend des logiciels développés par le Projet OpenSSL pour être utilisés dans la boîte à outils OpenSSL %s, et un logiciel cryptographique écrit par Eric Young, ainsi qu'un logiciel UPnP écrit par Thomas Bernard.</translation>
</message>
<message>
<source>Total length of network version string (%i) exceeds maximum length (%i). Reduce the number or size of uacomments.</source>
<translation>La taille totale de la chaîne de version de réseau (%i) dépasse la longueur maximale (%i). Réduire le nombre ou la taille des commentaires uacomments.</translation>
</message>
<message>
<source>Tries to keep outbound traffic under the given target (in MiB per 24h), 0 = no limit (default: %d)</source>
<translation>Tente de garder le trafic sortant sous la cible donnée (en Mio par 24 h), 0 = sans limite (par défaut : %d)</translation>
</message>
<message>
<source>Unsupported argument -socks found. Setting SOCKS version isn't possible anymore, only SOCKS5 proxies are supported.</source>
<translation>L'argument non pris en charge -socks a été trouvé. Il n'est plus possible de définir la version de SOCKS, seuls les mandataires SOCKS5 sont pris en charge.</translation>
</message>
<message>
<source>Unsupported argument -whitelistalwaysrelay ignored, use -whitelistrelay and/or -whitelistforcerelay.</source>
<translation>Argument non pris charge -whitelistalwaysrelay ignoré, utiliser -whitelistrelay et/ou -whitelistforcerelay.</translation>
</message>
<message>
<source>Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: %s)</source>
<translation>Utiliser un serveur mandataire SOCKS5 séparé pour atteindre les pairs par les services cachés de Tor (par défaut : %s)</translation>
</message>
<message>
<source>Warning: Unknown block versions being mined! It's possible unknown rules are in effect</source>
<translation>Avertissement : des versions de blocs inconnues sont minées ! Il est possible que des règles inconnues soient en vigeur</translation>
</message>
<message>
<source>Warning: Wallet file corrupt, data salvaged! Original %s saved as %s in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation>Avertissement : le fichier du porte-monnaie est corrompu, les données ont été récupérées ! Le fichier %s original a été enregistré en tant que %s dans %s ; si votre solde ou vos transactions sont incorrects, vous devriez restaurer une sauvegarde.</translation>
</message>
<message>
<source>Whitelist peers connecting from the given IP address (e.g. 1.2.3.4) or CIDR notated network (e.g. 1.2.3.0/24). Can be specified multiple times.</source>
<translation>Pairs de la liste blanche se connectant à partir de l'adresse IP donnée (p. ex. 1.2.3.4) ou du réseau noté CIDR (p. ex. 1.2.3.0/24). Peut être spécifié plusieurs fois.</translation>
</message>
<message>
<source>%s is set very high!</source>
<translation>La valeur %s est très élevée !</translation>
</message>
<message>
<source>(default: %s)</source>
<translation>(par défaut : %s)</translation>
</message>
<message>
<source>Always query for peer addresses via DNS lookup (default: %u)</source>
<translation>Toujours demander les adresses des pairs par recherche DNS (par défaut : %u)</translation>
</message>
<message>
<source>How many blocks to check at startup (default: %u, 0 = all)</source>
<translation>Nombre de blocs à vérifier au démarrage (par défaut : %u, 0 = tous)</translation>
</message>
<message>
<source>Include IP addresses in debug output (default: %u)</source>
<translation>Inclure les adresses IP à la sortie de débogage (par défaut : %u)</translation>
</message>
<message>
<source>Invalid -proxy address: '%s'</source>
<translation>Adresse -proxy invalide : « %s »</translation>
</message>
<message>
<source>Keypool ran out, please call keypoolrefill first</source>
<translation>La réserve de clés est épuisée, veuillez d'abord appeler « keypoolrefill »</translation>
</message>
<message>
<source>Listen for JSON-RPC connections on <port> (default: %u or testnet: %u)</source>
<translation>Écouter les connexions JSON-RPC sur <port> (par défaut : %u ou tesnet : %u)</translation>
</message>
<message>
<source>Listen for connections on <port> (default: %u or testnet: %u)</source>
<translation>Écouter les connexions sur <port> (par défaut : %u ou tesnet : %u)</translation>
</message>
<message>
<source>Maintain at most <n> connections to peers (default: %u)</source>
<translation>Garder au plus <n> connexions avec les pairs (par défaut : %u)</translation>
</message>
<message>
<source>Make the wallet broadcast transactions</source>
<translation>Obliger le porte-monnaie à diffuser les transactions</translation>
</message>
<message>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: %u)</source>
<translation>Tampon maximal de réception par connexion, <n>*1000 octets (par défaut : %u)</translation>
</message>
<message>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: %u)</source>
<translation>Tampon maximal d'envoi par connexion », <n>*1000 octets (par défaut : %u)</translation>
</message>
<message>
<source>Prepend debug output with timestamp (default: %u)</source>
<translation>Ajouter l'estampille temporelle au début de la sortie de débogage (par défaut : %u)</translation>
</message>
<message>
<source>Relay and mine data carrier transactions (default: %u)</source>
<translation>Relayer et miner les transactions du porteur de données (par défaut : %u)</translation>
</message>
<message>
<source>Relay non-P2SH multisig (default: %u)</source>
<translation>Relayer les multisignatures non-P2SH (par défaut : %u)</translation>
</message>
<message>
<source>Send transactions with full-RBF opt-in enabled (default: %u)</source>
<translation>Envoyer des transactions avec « RBF opt-in » complet activé (par défaut : %u)</translation>
</message>
<message>
<source>Set key pool size to <n> (default: %u)</source>
<translation>Définir la taille de la réserve de clés à <n> (par défaut : %u)</translation>
</message>
<message>
<source>Set maximum BIP141 block weight (default: %d)</source>
<translation>Définir le poids maximal de bloc BIP141 (par défaut : %d)</translation>
</message>
<message>
<source>Set the number of threads to service RPC calls (default: %d)</source>
<translation>Définir le nombre de fils pour les appels RPC (par défaut : %d)</translation>
</message>
<message>
<source>Specify configuration file (default: %s)</source>
<translation>Spécifier le fichier de configuration (par défaut : %s)</translation>
</message>
<message>
<source>Specify connection timeout in milliseconds (minimum: 1, default: %d)</source>
<translation>Spécifier le délai d'expiration de la connexion en millisecondes (minimum : 1, par défaut : %d)</translation>
</message>
<message>
<source>Specify pid file (default: %s)</source>
<translation>Spécifier le fichier pid (par défaut : %s)</translation>
</message>
<message>
<source>Spend unconfirmed change when sending transactions (default: %u)</source>
<translation>Dépenser la monnaie non confirmée lors de l'envoi de transactions (par défaut : %u)</translation>
</message>
<message>
<source>Starting network threads...</source>
<translation>Démarrage des processus réseau...</translation>
</message>
<message>
<source>The wallet will avoid paying less than the minimum relay fee.</source>
<translation>Le porte-monnaie évitera de payer moins que les frais minimaux de relais. </translation>
</message>
<message>
<source>This is the minimum transaction fee you pay on every transaction.</source>
<translation>Il s'agit des frais minimaux que vous payez pour chaque transaction. </translation>
</message>
<message>
<source>This is the transaction fee you will pay if you send a transaction.</source>
<translation>Il s'agit des frais minimaux que vous payez si vous envoyez une transaction.</translation>
</message>
<message>
<source>Threshold for disconnecting misbehaving peers (default: %u)</source>
<translation>Seuil de déconnexion des pairs présentant un mauvais comportement (par défaut : %u)</translation>
</message>
<message>
<source>Transaction amounts must not be negative</source>
<translation>Les montants transactionnels ne doivent pas être négatifs</translation>
</message>
<message>
<source>Transaction has too long of a mempool chain</source>
<translation>La chaîne de la réserve de mémoire de la transaction est trop longue</translation>
</message>
<message>
<source>Transaction must have at least one recipient</source>
<translation>La transaction doit comporter au moins un destinataire</translation>
</message>
<message>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>Réseau inconnu spécifié dans -onlynet : « %s »</translation>
</message>
<message>
<source>Insufficient funds</source>
<translation>Fonds insuffisants</translation>
</message>
<message>
<source>Loading block index...</source>
<translation>Chargement de l’index des blocs…</translation>
</message>
<message>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Ajouter un nœud auquel se connecter et tenter de garder la connexion ouverte</translation>
</message>
<message>
<source>Loading wallet...</source>
<translation>Chargement du porte-monnaie…</translation>
</message>
<message>
<source>Cannot downgrade wallet</source>
<translation>Impossible de revenir à une version inférieure du porte-monnaie</translation>
</message>
<message>
<source>Cannot write default address</source>
<translation>Impossible d'écrire l'adresse par défaut</translation>
</message>
<message>
<source>Rescanning...</source>
<translation>Nouvelle analyse…</translation>
</message>
<message>
<source>Done loading</source>
<translation>Chargement terminé</translation>
</message>
<message>
<source>Error</source>
<translation>Erreur</translation>
</message>
</context>
</TS><|fim▁end|> | </message> |
<|file_name|>models.py<|end_file_name|><|fim▁begin|><|fim▁hole|>
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.core.cache import cache
from django.db.models.signals import post_save, post_delete
class BlockIP(models.Model):
network = models.CharField(_('IP address or mask'), max_length=18)
reason_for_block = models.TextField(blank=True, null=True, help_text=_("Optional reason for block"))
def __unicode__(self):
return 'BlockIP: %s' % self.network
def get_network(self):
return ipcalc.Network(self.network)
class Meta:
verbose_name = _('IPs & masks to ban')
verbose_name_plural = _('IPs & masks to ban')
def _clear_cache(sender, instance, **kwargs):
cache.set('blockip:list', BlockIP.objects.all())
post_save.connect(_clear_cache, sender=BlockIP)
post_delete.connect(_clear_cache, sender=BlockIP)<|fim▁end|> | import ipcalc |
<|file_name|>BookmarkPaymentFragment.java<|end_file_name|><|fim▁begin|>package com.mapswithme.maps.purchase;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.android.billingclient.api.SkuDetails;
import com.bumptech.glide.Glide;
import com.mapswithme.maps.Framework;
import com.mapswithme.maps.PrivateVariables;
import com.mapswithme.maps.PurchaseOperationObservable;
import com.mapswithme.maps.R;
import com.mapswithme.maps.base.BaseMwmFragment;
import com.mapswithme.maps.bookmarks.data.PaymentData;
import com.mapswithme.maps.dialog.AlertDialogCallback;
import com.mapswithme.util.Utils;
import com.mapswithme.util.log.Logger;
import com.mapswithme.util.log.LoggerFactory;
import com.mapswithme.util.statistics.Statistics;
import java.util.Collections;
import java.util.List;
public class BookmarkPaymentFragment extends BaseMwmFragment
implements AlertDialogCallback, PurchaseStateActivator<BookmarkPaymentState>
{
static final String ARG_PAYMENT_DATA = "arg_payment_data";
private static final Logger LOGGER = LoggerFactory.INSTANCE.getLogger(LoggerFactory.Type.BILLING);
private static final String TAG = BookmarkPaymentFragment.class.getSimpleName();
private static final String EXTRA_CURRENT_STATE = "extra_current_state";
private static final String EXTRA_PRODUCT_DETAILS = "extra_product_details";
private static final String EXTRA_SUBS_PRODUCT_DETAILS = "extra_subs_product_details";
private static final String EXTRA_VALIDATION_RESULT = "extra_validation_result";
@SuppressWarnings("NullableProblems")
@NonNull
private PurchaseController<PurchaseCallback> mPurchaseController;
@SuppressWarnings("NullableProblems")
@NonNull
private BookmarkPurchaseCallback mPurchaseCallback;
@SuppressWarnings("NullableProblems")
@NonNull
private PaymentData mPaymentData;
@Nullable
private ProductDetails mProductDetails;
@Nullable
private ProductDetails mSubsProductDetails;
private boolean mValidationResult;
@NonNull
private BookmarkPaymentState mState = BookmarkPaymentState.NONE;
@SuppressWarnings("NullableProblems")
@NonNull
private BillingManager<PlayStoreBillingCallback> mSubsProductDetailsLoadingManager;
@NonNull
private final SubsProductDetailsCallback mSubsProductDetailsCallback
= new SubsProductDetailsCallback();
@Override
public void onCreate(@Nullable Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Bundle args = getArguments();
if (args == null)
throw new IllegalStateException("Args must be provided for payment fragment!");
PaymentData paymentData = args.getParcelable(ARG_PAYMENT_DATA);
if (paymentData == null)
throw new IllegalStateException("Payment data must be provided for payment fragment!");
mPaymentData = paymentData;
mPurchaseCallback = new BookmarkPurchaseCallback(mPaymentData.getServerId());
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable
Bundle savedInstanceState)
{
mPurchaseController = PurchaseFactory.createBookmarkPurchaseController(requireContext(),
mPaymentData.getProductId(),
mPaymentData.getServerId());
if (savedInstanceState != null)
mPurchaseController.onRestore(savedInstanceState);
mPurchaseController.initialize(requireActivity());
mSubsProductDetailsLoadingManager = PurchaseFactory.createSubscriptionBillingManager();
mSubsProductDetailsLoadingManager.initialize(requireActivity());
mSubsProductDetailsLoadingManager.addCallback(mSubsProductDetailsCallback);
mSubsProductDetailsCallback.attach(this);
View root = inflater.inflate(R.layout.fragment_bookmark_payment, container, false);
View subscriptionButton = root.findViewById(R.id.buy_subs_btn);
subscriptionButton.setOnClickListener(v -> onBuySubscriptionClicked());
TextView buyInappBtn = root.findViewById(R.id.buy_inapp_btn);
buyInappBtn.setOnClickListener(v -> onBuyInappClicked());
return root;
}
private void onBuySubscriptionClicked()
{
SubscriptionType type = SubscriptionType.getTypeByBookmarksGroup(mPaymentData.getGroup());
if (type.equals(SubscriptionType.BOOKMARKS_SIGHTS))
{
BookmarksSightsSubscriptionActivity.startForResult
(this, PurchaseUtils.REQ_CODE_PAY_SUBSCRIPTION, Statistics.ParamValue.CARD);
return;
}
BookmarksAllSubscriptionActivity.startForResult
(this, PurchaseUtils.REQ_CODE_PAY_SUBSCRIPTION, Statistics.ParamValue.CARD);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != Activity.RESULT_OK)
return;
if (requestCode == PurchaseUtils.REQ_CODE_PAY_SUBSCRIPTION)
{
Intent intent = new Intent();
intent.putExtra(PurchaseUtils.EXTRA_IS_SUBSCRIPTION, true);
requireActivity().setResult(Activity.RESULT_OK, intent);
requireActivity().finish();
}
}
private void onBuyInappClicked()
{
Statistics.INSTANCE.trackPurchasePreviewSelect(mPaymentData.getServerId(),
mPaymentData.getProductId());
Statistics.INSTANCE.trackPurchaseEvent(Statistics.EventName.INAPP_PURCHASE_PREVIEW_PAY,
mPaymentData.getServerId(),
Statistics.STATISTICS_CHANNEL_REALTIME);
startPurchaseTransaction();
}
@Override
public boolean onBackPressed()
{
if (mState == BookmarkPaymentState.VALIDATION)
{
Toast.makeText(requireContext(), R.string.purchase_please_wait_toast, Toast.LENGTH_SHORT)
.show();
return true;
}
Statistics.INSTANCE.trackPurchaseEvent(Statistics.EventName.INAPP_PURCHASE_PREVIEW_CANCEL,
mPaymentData.getServerId());
return super.onBackPressed();
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
if (savedInstanceState == null)
Statistics.INSTANCE.trackPurchasePreviewShow(mPaymentData.getServerId(),
PrivateVariables.bookmarksVendor(),
mPaymentData.getProductId());
LOGGER.d(TAG, "onViewCreated savedInstanceState = " + savedInstanceState);
setInitialPaymentData();
loadImage();
if (savedInstanceState != null)
{
mProductDetails = savedInstanceState.getParcelable(EXTRA_PRODUCT_DETAILS);
if (mProductDetails != null)
updateProductDetails();
mSubsProductDetails = savedInstanceState.getParcelable(EXTRA_SUBS_PRODUCT_DETAILS);
if (mSubsProductDetails != null)
updateSubsProductDetails();
mValidationResult = savedInstanceState.getBoolean(EXTRA_VALIDATION_RESULT);
BookmarkPaymentState savedState
= BookmarkPaymentState.values()[savedInstanceState.getInt(EXTRA_CURRENT_STATE)];
activateState(savedState);
return;
}
activateState(BookmarkPaymentState.PRODUCT_DETAILS_LOADING);
mPurchaseController.queryProductDetails();
SubscriptionType type = SubscriptionType.getTypeByBookmarksGroup(mPaymentData.getGroup());
List<String> subsProductIds =
Collections.singletonList(type.getMonthlyProductId());
mSubsProductDetailsLoadingManager.queryProductDetails(subsProductIds);
}
@Override
public void onDestroyView()
{
super.onDestroyView();
mPurchaseController.destroy();
mSubsProductDetailsLoadingManager.removeCallback(mSubsProductDetailsCallback);
mSubsProductDetailsCallback.detach();
mSubsProductDetailsLoadingManager.destroy();
}
private void startPurchaseTransaction()
{
activateState(BookmarkPaymentState.TRANSACTION_STARTING);
Framework.nativeStartPurchaseTransaction(mPaymentData.getServerId(),
PrivateVariables.bookmarksVendor());
}
void launchBillingFlow()
{
mPurchaseController.launchPurchaseFlow(mPaymentData.getProductId());
activateState(BookmarkPaymentState.PAYMENT_IN_PROGRESS);
}
@Override
public void onStart()
{
super.onStart();
PurchaseOperationObservable observable = PurchaseOperationObservable.from(requireContext());
observable.addTransactionObserver(mPurchaseCallback);
mPurchaseController.addCallback(mPurchaseCallback);
mPurchaseCallback.attach(this);
}
@Override
public void onStop()
{
super.onStop();
PurchaseOperationObservable observable = PurchaseOperationObservable.from(requireContext());
observable.removeTransactionObserver(mPurchaseCallback);
mPurchaseController.removeCallback();
mPurchaseCallback.detach();
}
@Override
public void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
LOGGER.d(TAG, "onSaveInstanceState");
outState.putInt(EXTRA_CURRENT_STATE, mState.ordinal());
outState.putParcelable(EXTRA_PRODUCT_DETAILS, mProductDetails);
outState.putParcelable(EXTRA_SUBS_PRODUCT_DETAILS, mSubsProductDetails);
mPurchaseController.onSave(outState);
}
@Override
public void activateState(@NonNull BookmarkPaymentState state)
{
if (state == mState)
return;
LOGGER.i(TAG, "Activate state: " + state);
mState = state;
mState.activate(this);
}
private void loadImage()
{
if (TextUtils.isEmpty(mPaymentData.getImgUrl()))
return;
ImageView imageView = getViewOrThrow().findViewById(R.id.image);
Glide.with(imageView.getContext())
.load(mPaymentData.getImgUrl())
.centerCrop()
.into(imageView);
}
private void setInitialPaymentData()
{
TextView name = getViewOrThrow().findViewById(R.id.product_catalog_name);
name.setText(mPaymentData.getName());
TextView author = getViewOrThrow().findViewById(R.id.author_name);
author.setText(mPaymentData.getAuthorName());
}
void handleProductDetails(@NonNull List<SkuDetails> details)
{
if (details.isEmpty())
return;
SkuDetails skuDetails = details.get(0);
mProductDetails = PurchaseUtils.toProductDetails(skuDetails);
}
void handleSubsProductDetails(@NonNull List<SkuDetails> details)
{
if (details.isEmpty())
return;
SkuDetails skuDetails = details.get(0);<|fim▁hole|> {
mValidationResult = validationResult;
}
@Override
public void onAlertDialogPositiveClick(int requestCode, int which)
{
handleErrorDialogEvent(requestCode);
}
@Override
public void onAlertDialogNegativeClick(int requestCode, int which)
{
// Do nothing by default.
}
@Override
public void onAlertDialogCancel(int requestCode)
{
handleErrorDialogEvent(requestCode);
}
private void handleErrorDialogEvent(int requestCode)
{
switch (requestCode)
{
case PurchaseUtils.REQ_CODE_PRODUCT_DETAILS_FAILURE:
requireActivity().finish();
break;
case PurchaseUtils.REQ_CODE_START_TRANSACTION_FAILURE:
case PurchaseUtils.REQ_CODE_PAYMENT_FAILURE:
activateState(BookmarkPaymentState.PRODUCT_DETAILS_LOADED);
break;
}
}
void updateProductDetails()
{
if (mProductDetails == null)
throw new AssertionError("Product details must be obtained at this moment!");
TextView buyButton = getViewOrThrow().findViewById(R.id.buy_inapp_btn);
String price = Utils.formatCurrencyString(mProductDetails.getPrice(),
mProductDetails.getCurrencyCode());
buyButton.setText(getString(R.string.buy_btn, price));
TextView storeName = getViewOrThrow().findViewById(R.id.product_store_name);
storeName.setText(mProductDetails.getTitle());
}
void updateSubsProductDetails()
{
if (mSubsProductDetails == null)
throw new AssertionError("Subs product details must be obtained at this moment!");
String formattedPrice = Utils.formatCurrencyString(mSubsProductDetails.getPrice(),
mSubsProductDetails.getCurrencyCode());
TextView subsButton = getViewOrThrow().findViewById(R.id.buy_subs_btn);
subsButton.setText(getString(R.string.buy_btn_for_subscription_version_2, formattedPrice));
}
void finishValidation()
{
if (mValidationResult)
requireActivity().setResult(Activity.RESULT_OK);
requireActivity().finish();
}
}<|fim▁end|> | mSubsProductDetails = PurchaseUtils.toProductDetails(skuDetails);
}
void handleValidationResult(boolean validationResult) |
<|file_name|>compiler.py<|end_file_name|><|fim▁begin|>#-*- coding: utf-8 -*-
# stino/compiler.py
import os
import re
import threading
import subprocess
import sublime
from . import fileutil
from . import textutil
from . import constant
from . import serial
from . import base
from . import preprocess
from . import sketch
from . import console
ram_size_dict = {}
ram_size_dict['attiny44'] = '256'
ram_size_dict['attiny45'] = '256'
ram_size_dict['attiny84'] = '512'
ram_size_dict['attiny85'] = '512'
ram_size_dict['atmega8'] = '1024'
ram_size_dict['atmega168'] = '1024'
ram_size_dict['atmega328p'] = '2048'
ram_size_dict['atmega644'] = '4096'
ram_size_dict['atmega644p'] = '4096'
ram_size_dict['atmega1284'] = '16384'
ram_size_dict['atmega1284p'] = '16384'
ram_size_dict['atmega1280'] = '4096'
ram_size_dict['atmega2560'] = '8196'
ram_size_dict['atmega32u4'] = '2560'
ram_size_dict['at90usb162'] = '512'
ram_size_dict['at90usb646'] = '4096'
ram_size_dict['at90usb1286'] = '8192'
ram_size_dict['cortex-m3'] = '98304'
ram_size_dict['cortex-m4'] = '16384'
class Args:
def __init__(self, cur_project, arduino_info):
self.args = getFullArgs(cur_project, arduino_info)
def getArgs(self):
return self.args
class Command:
def __init__(self, command):
self.in_file = ''
self.out_file = ''
self.command = command
self.calc_size = False
self.stdout = ''
self.out_text = ''
def run(self, output_console):
output_console.printText(self.out_text)
if self.out_file:
message = 'Creating %s...\n' % self.out_file
output_console.printText(message)
cur_command = formatCommand(self.command)
compile_proc = subprocess.Popen(cur_command, stdout = subprocess.PIPE,
stderr = subprocess.PIPE, shell = True)
result = compile_proc.communicate()
return_code = compile_proc.returncode
stdout = result[0].decode(constant.sys_encoding).replace('\r', '')
stderr = result[1].decode(constant.sys_encoding).replace('\r', '')
self.stdout = stdout
show_compilation_output = constant.sketch_settings.get('show_compilation_output', False)
if show_compilation_output:
output_console.printText(self.command)
output_console.printText('\n')
output_console.printText(stdout)
output_console.printText(stderr)
return return_code
def isSizeCommand(self):
return self.calc_size
def setSizeCommand(self):
self.calc_size = True
def getOutFile(self):
return self.out_file
def getCommand(self):
return self.command
def getStdout(self):
return self.stdout
def setInFile(self, in_file):
self.in_file = in_file
def setOutFile(self, out_file):
self.out_file = out_file
def setCommand(self, command):
self.command = command
def setOutputText(self, text):
self.out_text = text
class Compiler:
def __init__(self, arduino_info, cur_project, args):
self.arduino_info = arduino_info
self.cur_project = cur_project
self.args = args.getArgs()
self.output_console = console.Console(cur_project.getName())
self.no_error = True
self.is_finished = False
self.prepare()
def getOutputConsole(self):
return self.output_console
def isFinished(self):
return self.is_finished
def noError(self):
return self.no_error
def prepare(self):
self.command_list = []
if self.args:
self.command_list = genCommandList(self.args, self.cur_project, self.arduino_info)
def run(self):
if self.command_list:
compilation_thread = threading.Thread(target=self.compile)
compilation_thread.start()
else:
self.no_error = False
self.is_finished = True
self.output_console.printText('Please choose the Ardunio Application Folder.')
def compile(self):
self.output_console.printText('Compiling %s...\n' % self.cur_project.getName())
for cur_command in self.command_list:
return_code = cur_command.run(self.output_console)
if return_code > 0:
self.output_console.printText('[Stino - Error %d]\n' % return_code)
self.no_error = False
break
else:
if cur_command.isSizeCommand():
stdout = cur_command.getStdout()
printSizeInfo(self.output_console, stdout, self.args)
if self.no_error:
self.output_console.printText('[Stino - Done compiling.]\n')
self.is_finished = True
def getChosenArgs(arduino_info):
args = {}
platform_list = arduino_info.getPlatformList()
if len(platform_list) > 1:
platform_id = constant.sketch_settings.get('platform', -1)
if not ((platform_id > 0) and (platform_id < len(platform_list))):
platform_id = 1
cur_platform = platform_list[platform_id]
platform_name = cur_platform.getName()
constant.sketch_settings.set('platform', platform_id)
constant.sketch_settings.set('platform_name', platform_name)
selected_platform = platform_list[platform_id]
board_list = selected_platform.getBoardList()
board_id = constant.sketch_settings.get('board', -1)
if board_list:
serial_port = getSelectedSerialPort()
args['serial.port'] = serial_port
if not (board_id > -1 or board_id < len(board_list)):
board_id = 0
constant.sketch_settings.set('board', board_id)
selected_board = board_list[board_id]
args.update(selected_board.getArgs())
board_option_list = selected_board.getOptionList()
if board_option_list:
board_option_key = '%d.%d' % (platform_id, board_id)
board_option_dict = constant.sketch_settings.get('board_option', {})
if board_option_key in board_option_dict:
option_item_id_list = board_option_dict[board_option_key]
if len(option_item_id_list) < len(board_option_list):
option_item_id_list = []
else:
option_item_id_list = []
if not option_item_id_list:
for board_option in board_option_list:
option_item_id_list.append(0)
for board_option in board_option_list:
index = board_option_list.index(board_option)
option_item_id = option_item_id_list[index]
option_item_list = board_option.getItemList()
option_item = option_item_list[option_item_id]
option_item_args = option_item.getArgs()
args.update(option_item_args)
if 'build.vid' in args:
if not 'build.extra_flags' in args:
args['build.extra_flags'] = '-DUSB_VID={build.vid} -DUSB_PID={build.pid}'
if 'bootloader.path' in args:
bootloader_path = args['bootloader.path']
if 'bootloader.file' in args:
bootloader_file = args['bootloader.file']
bootloader_file = bootloader_path + '/' + bootloader_file
args['bootloader.file'] = bootloader_file
programmer_list = selected_platform.getProgrammerList()
if programmer_list:
platform_programmer_dict = constant.sketch_settings.get('programmer', {})
if str(platform_id) in platform_programmer_dict:
programmer_id = platform_programmer_dict[str(platform_id)]
else:
programmer_id = 0
programmer = programmer_list[programmer_id]
programmer_args = programmer.getArgs()
args.update(programmer_args)
platform_file = getPlatformFile(arduino_info)
args = addBuildUsbValue(args, platform_file)
args = replaceAllDictValue(args)
if not 'upload.maximum_ram_size' in args:
args['upload.maximum_ram_size'] = '0'
if 'build.mcu' in args:
build_mcu = args['build.mcu']
if build_mcu in ram_size_dict:
args['upload.maximum_ram_size'] = ram_size_dict[build_mcu]
if 'build.elide_constructors' in args:
if args['build.elide_constructors'] == 'true':
args['build.elide_constructors'] = '-felide-constructors'
else:
args['build.elide_constructors'] = ''
if 'build.cpu' in args:
args['build.mcu'] = args['build.cpu']
if 'build.gnu0x' in args:
if args['build.gnu0x'] == 'true':
args['build.gnu0x'] = '-std=gnu++0x'
else:
args['build.gnu0x'] = ''
if 'build.cpp0x' in args:
if args['build.cpp0x'] == 'true':
args['build.cpp0x'] = '-std=c++0x'
else:
args['build.cpp0x'] = ''
return args
def getSelectedSerialPort():
serial_port = 'no_serial_port'
serial_port_list = serial.getSerialPortList()
if serial_port_list:
serial_port_id = constant.sketch_settings.get('serial_port', -1)
if not (serial_port_id > -1 and serial_port_id < len(serial_port_list)):
serial_port_id = 0
constant.sketch_settings.set('serial_port', serial_port_id)
serial_port = serial_port_list[serial_port_id]
return serial_port
def getReplaceTextList(text):
pattern_text = r'\{\S+?}'
pattern = re.compile(pattern_text)
replace_text_list = pattern.findall(text)
return replace_text_list
def replaceValueText(value_text, args_dict):
replace_text_list = getReplaceTextList(value_text)
for replace_text in replace_text_list:
key = replace_text[1:-1]
if key in args_dict:
value = args_dict[key]
else:
value = ''
value_text = value_text.replace(replace_text, value)
return value_text
def replaceAllDictValue(args_dict):
for key in args_dict:
value_text = args_dict[key]
value_text = replaceValueText(value_text, args_dict)
args_dict[key] = value_text
return args_dict
def addBuildUsbValue(args, platform_file):
lines = fileutil.readFileLines(platform_file)
for line in lines:
line = line.strip()
if line and not '#' in line:
(key, value) = textutil.getKeyValue(line)
if 'extra_flags' in key:
continue
if 'build.' in key:
if 'usb_manufacturer' in key:
if not value:
value = 'unknown'
value = replaceValueText(value, args)
if constant.sys_platform == 'windows':
value = value.replace('"', '\\"')
value = value.replace('\'', '"')
args[key] = value
return args
def getDefaultArgs(cur_project, arduino_info):
core_folder = getCoreFolder(arduino_info)
arduino_folder = base.getArduinoFolder()
ide_path = os.path.join(arduino_folder, 'hardware')
project_name = cur_project.getName()
serial_port = getSelectedSerialPort()
archive_file = 'core.a'
build_system_path = os.path.join(core_folder, 'system')
arduino_version = arduino_info.getVersion()
build_folder = getBuildFolder(cur_project)
args = {}
args['runtime.ide.path'] = arduino_folder
args['ide.path'] = ide_path
args['build.project_name'] = project_name
args['serial.port.file'] = serial_port
args['archive_file'] = archive_file
args['software'] = 'ARDUINO'
args['runtime.ide.version'] = '%d' % arduino_version
args['source_file'] = '{source_file}'
args['object_file'] = '{object_file}'
args['object_files'] = '{object_files}'
args['includes'] = '{includes}'
args['build.path'] = build_folder
return args
def getBuildFolder(cur_project):
build_folder = constant.sketch_settings.get('build_folder', '')
if not (build_folder and os.path.isdir(build_folder)):
document_folder = fileutil.getDocumentFolder()
build_folder = os.path.join(document_folder, 'Arduino_Build')
project_name = cur_project.getName()
build_folder = os.path.join(build_folder, project_name)
checkBuildFolder(build_folder)
return build_folder
def checkBuildFolder(build_folder):
if os.path.isfile(build_folder):
os.remove(build_folder)
if not os.path.exists(build_folder):
os.makedirs(build_folder)
file_name_list = fileutil.listDir(build_folder, with_dirs = False)
for file_name in file_name_list:
file_ext = os.path.splitext(file_name)[1]
if file_ext in ['.d']:
cur_file = os.path.join(build_folder, file_name)
os.remove(cur_file)
def getDefaultPlatformFile(arduino_info):
file_name = 'arduino_avr.txt'
platform_file = ''
platform_list = arduino_info.getPlatformList()
platform_id = constant.sketch_settings.get('platform', 1)
platform = platform_list[platform_id]
platform_name = platform.getName()
if 'Arduino ARM' in platform_name:
file_name = 'arduino_arm.txt'
elif 'Teensy' in platform_name:
board_list = platform.getBoardList()
board_id = constant.sketch_settings.get('board', 0)
board = board_list[board_id]
board_name = board.getName()
board_version = float(board_name.split()[1])
if board_version >= 3.0:
file_name = 'teensy_arm.txt'
else:
file_name = 'teensy_avr.txt'
elif 'Zpuino' in platform_name:
file_name = 'zpuino.txt'
platform_file = os.path.join(constant.compile_root, file_name)
return platform_file
def getCoreFolder(arduino_info):
platform_list = arduino_info.getPlatformList()
platform_id = constant.sketch_settings.get('platform', -1)
if not ((platform_id > 0) and (platform_id < len(platform_list))):
platform_id = 1
cur_platform = platform_list[platform_id]
platform_name = cur_platform.getName()
constant.sketch_settings.set('platform', platform_id)
constant.sketch_settings.set('platform_name', platform_name)
platform = platform_list[platform_id]
core_folder = ''
core_folder_list = platform.getCoreFolderList()
for cur_core_folder in core_folder_list:
platform_file = os.path.join(cur_core_folder, 'platform.txt')
if os.path.isfile(platform_file):
core_folder = cur_core_folder
break
return core_folder
def getPlatformFile(arduino_info):
core_folder = getCoreFolder(arduino_info)
if core_folder:
platform_file = os.path.join(core_folder, 'platform.txt')
else:
platform_file = getDefaultPlatformFile(arduino_info)
return platform_file
def splitPlatformFile(platform_file):
text = fileutil.readFile(platform_file)
index = text.index('recipe.')
text_header = text[:index]
text_body = text[index:]
return (text_header, text_body)
def getPlatformArgs(platform_text, args):
lines = platform_text.split('\n')
for line in lines:
line = line.strip()
if line and not '#' in line:
(key, value) = textutil.getKeyValue(line)
value = replaceValueText(value, args)
if 'tools.avrdude.' in key:
key = key.replace('tools.avrdude.', '')
if 'tools.bossac.' in key:
key = key.replace('tools.bossac.', '')
if 'tools.teensy.' in key:
key = key.replace('tools.teensy.', '')
if 'params.' in key:
key = key.replace('params.', '')
if constant.sys_platform == 'linux':
if '.linux' in key:
key = key.replace('.linux', '')
show_upload_output = constant.sketch_settings.get('show_upload_output', False)
if not show_upload_output:
if '.quiet' in key:
key = key.replace('.quiet', '.verbose')
if '.verbose' in key:
verify_code = constant.sketch_settings.get('verify_code', False)
if verify_code:
value += ' -V'
if key == 'build.extra_flags':
if key in args:
continue
args[key] = value
return args
def getFullArgs(cur_project, arduino_info):
args = {}
board_args = getChosenArgs(arduino_info)
if board_args:
default_args = getDefaultArgs(cur_project, arduino_info)
args.update(default_args)
args.update(board_args)
platform_file = getPlatformFile(arduino_info)
(platform_text_header, platform_text_body) = splitPlatformFile(platform_file)
args = getPlatformArgs(platform_text_header, args)
variant_folder = args['build.variants_folder']
cores_folder = args['build.cores_folder']
build_core = args['build.core']
build_core_folder = os.path.join(cores_folder, build_core)
args['build.core_folder'] = build_core_folder
if 'build.variant' in args:
build_variant = args['build.variant']
build_variant_folder = os.path.join(variant_folder, build_variant)
args['build.variant.path'] = build_variant_folder
else:
args['build.variant.path'] = build_core_folder
if 'compiler.path' in args:
compiler_path = args['compiler.path']
else:
runtime_ide_path = args['runtime.ide.path']
compiler_path = runtime_ide_path + '/hardware/tools/avr/bin/'
compiler_c_cmd = args['compiler.c.cmd']
if constant.sys_platform == 'windows':
compiler_c_cmd += '.exe'
compiler_c_cmd_file = os.path.join(compiler_path, compiler_c_cmd)
if os.path.isfile(compiler_c_cmd_file):
args['compiler.path'] = compiler_path
else:
args['compiler.path'] = ''
extra_flags = constant.sketch_settings.get('extra_flag', '')
if 'build.extra_flags' in args:
build_extra_flags = args['build.extra_flags']
else:
build_extra_flags = ''
if extra_flags:
build_extra_flags += ' '
build_extra_flags += extra_flags
args['build.extra_flags'] = build_extra_flags
args = getPlatformArgs(platform_text_body, args)
return args
def getLibFolderListFromProject(cur_project, arduino_info):
lib_folder_list = []
platform_list = arduino_info.getPlatformList()
platform_id = constant.sketch_settings.get('platform', 1)
general_platform = platform_list[0]
selected_platform = platform_list[platform_id]
general_h_lib_dict = general_platform.getHLibDict()
selected_h_lib_dict = selected_platform.getHLibDict()
ino_src_file_list = cur_project.getInoSrcFileList()
c_src_file_list = cur_project.getCSrcFileList()
h_list = preprocess.getHListFromSrcList(ino_src_file_list + c_src_file_list)
for h in h_list:
lib_folder = ''
if h in selected_h_lib_dict:
lib_folder = selected_h_lib_dict[h]
elif h in general_h_lib_dict:
lib_folder = general_h_lib_dict[h]
if lib_folder:
if not lib_folder in lib_folder_list:
lib_folder_list.append(lib_folder)
return lib_folder_list
def genBuildCppFile(build_folder, cur_project, arduino_info):
project_name = cur_project.getName()
cpp_file_name = project_name + '.ino.cpp'
cpp_file = os.path.join(build_folder, cpp_file_name)
ino_src_file_list = cur_project.getInoSrcFileList()
arduino_version = arduino_info.getVersion()
doMunge = not constant.sketch_settings.get('set_bare_gcc_only', False)
preprocess.genCppFileFromInoFileList(cpp_file, ino_src_file_list, arduino_version, preprocess=doMunge)
return cpp_file
def genIncludesPara(build_folder, project_folder, core_folder_list, compiler_include_folder):
folder_list = sketch.getFolderListFromFolderList(core_folder_list)
include_folder_list = []
include_folder_list.append(build_folder)
include_folder_list.append(project_folder)
include_folder_list.append(compiler_include_folder)
include_folder_list += folder_list
includes = ''
for include_folder in include_folder_list:
includes += '"-I%s" ' % include_folder
return includes
def getCompileCommand(c_file, args, includes_para):
build_folder = args['build.path']
file_name = os.path.split(c_file)[1]
file_ext = os.path.splitext(c_file)[1]
obj_file_name = file_name + '.o'
obj_file = os.path.join(build_folder, obj_file_name)
if file_ext in ['.S']:
command = args['recipe.S.o.pattern']
elif file_ext in ['.c']:
command = args['recipe.c.o.pattern']
else:
command = args['recipe.cpp.o.pattern']
command = command.replace('{includes}', includes_para)
command = command.replace('{source_file}', c_file)
command = command.replace('{object_file}', obj_file)
cur_command = Command(command)
cur_command.setInFile(c_file)
cur_command.setOutFile(obj_file)
return cur_command
def getCompileCommandList(c_file_list, args, includes_para):
command_list = []
for c_file in c_file_list:
cur_command = getCompileCommand(c_file, args, includes_para)
command_list.append(cur_command)
return command_list
def getArCommand(args, core_command_list):
build_folder = args['build.path']
archive_file_name = args['archive_file']
archive_file = os.path.join(build_folder, archive_file_name)
object_files = ''
for core_command in core_command_list:
core_obj_file = core_command.getOutFile()
object_files += '"%s" ' % core_obj_file
object_files = object_files[:-1]
command_text = args['recipe.ar.pattern']
command_text = command_text.replace('"{object_file}"', object_files)
ar_command = Command(command_text)
ar_command.setOutFile(archive_file)
return ar_command
def getElfCommand(args, project_command_list):
build_folder = args['build.path']
project_name = args['build.project_name']
elf_file_name = project_name + '.elf'<|fim▁hole|> elf_file = os.path.join(build_folder, elf_file_name)
object_files = ''
for project_command in project_command_list:
project_obj_file = project_command.getOutFile()
object_files += '"%s" ' % project_obj_file
object_files = object_files[:-1]
command_text = args['recipe.c.combine.pattern']
command_text = command_text.replace('{object_files}', object_files)
elf_command = Command(command_text)
elf_command.setOutFile(elf_file)
return elf_command
def getEepCommand(args):
build_folder = args['build.path']
project_name = args['build.project_name']
eep_file_name = project_name + '.eep'
eep_file = os.path.join(build_folder, eep_file_name)
command_text = args['recipe.objcopy.eep.pattern']
eep_command = Command(command_text)
eep_command.setOutFile(eep_file)
return eep_command
def getHexCommand(args):
command_text = args['recipe.objcopy.hex.pattern']
hex_command = Command(command_text)
build_folder = args['build.path']
project_name = args['build.project_name']
ext = command_text[-5:-1]
hex_file_name = project_name + ext
hex_file = os.path.join(build_folder, hex_file_name)
hex_command.setOutFile(hex_file)
return hex_command
def getSizeCommand(args):
command_text = args['recipe.size.pattern']
command_text = command_text.replace('-A', '')
command_text = command_text.replace('.hex', '.elf')
size_command = Command(command_text)
size_command.setSizeCommand()
return size_command
def genCommandList(args, cur_project, arduino_info):
build_folder = args['build.path']
project_folder = cur_project.getFolder()
build_cpp_file = genBuildCppFile(build_folder, cur_project, arduino_info)
build_core_folder = args['build.core_folder']
build_variant_folder = args['build.variant.path']
lib_folder_list = getLibFolderListFromProject(cur_project, arduino_info)
core_folder_list = [build_core_folder, build_variant_folder] + lib_folder_list
compiler_bin_folder = args['compiler.path']
compiler_folder = os.path.split(compiler_bin_folder)[0]
compiler_folder = os.path.split(compiler_folder)[0]
compiler_name = os.path.split(compiler_folder)[1]
compiler_folder = os.path.join(compiler_folder, compiler_name)
compiler_include_folder = os.path.join(compiler_folder, 'include')
compiler_include_folder = compiler_include_folder.replace('/', os.path.sep)
# core_folder_list.append(compiler_include_folder)
includes_para = genIncludesPara(build_folder, project_folder, core_folder_list, compiler_include_folder)
project_C_file_list = [build_cpp_file] + cur_project.getCSrcFileList() + cur_project.getAsmSrcFileList()
core_C_file_list = sketch.getCSrcFileListFromFolderList(core_folder_list) + sketch.getAsmSrcFileListFromFolderList(core_folder_list)
project_command_list = getCompileCommandList(project_C_file_list, args, includes_para)
core_command_list = getCompileCommandList(core_C_file_list, args, includes_para)
ar_command = getArCommand(args, core_command_list)
elf_command = getElfCommand(args, project_command_list)
eep_command = getEepCommand(args)
hex_command = getHexCommand(args)
size_command = getSizeCommand(args)
full_compilation = constant.sketch_settings.get('full_compilation', True)
archive_file_name = args['archive_file']
archive_file = os.path.join(build_folder, archive_file_name)
if not os.path.isfile(archive_file):
full_compilation = True
command_list = []
command_list += project_command_list
if full_compilation:
if os.path.isfile(archive_file):
os.remove(archive_file)
command_list += core_command_list
command_list.append(ar_command)
command_list.append(elf_command)
if args['recipe.objcopy.eep.pattern']:
command_list.append(eep_command)
command_list.append(hex_command)
command_list.append(size_command)
return command_list
def getCommandList(cur_project, arduino_info):
command_list = []
args = getFullArgs(cur_project, arduino_info)
if args:
command_list = genCommandList(args, cur_project, arduino_info)
return command_list
def printSizeInfo(output_console, stdout, args):
flash_size_key = 'upload.maximum_size'
ram_size_key = 'upload.maximum_ram_size'
max_flash_size = int(args[flash_size_key])
max_ram_size = int(args[ram_size_key])
size_line = stdout.split('\n')[-2].strip()
info_list = re.findall(r'\S+', size_line)
text_size = int(info_list[0])
data_size = int(info_list[1])
bss_size = int(info_list[2])
flash_size = text_size + data_size
ram_size = data_size + bss_size
flash_percent = float(flash_size) / max_flash_size * 100
text = 'Binary sketch size: %d bytes (of a %d byte maximum, %.2f percent).\n' % (flash_size, max_flash_size, flash_percent)
if max_ram_size > 0:
ram_percent = float(ram_size) / max_ram_size * 100
text += 'Estimated memory use: %d bytes (of a %d byte maximum, %.2f percent).\n' % (ram_size, max_ram_size, ram_percent)
output_console.printText(text)
def formatCommand(command):
if constant.sys_version < 3:
if constant.sys_platform == 'windows':
command = command.replace('/"', '"')
command = command.replace('/', os.path.sep)
command = '"' + command + '"'
if constant.sys_version < 3:
if isinstance(command, unicode):
command = command.encode(constant.sys_encoding)
return command<|fim▁end|> | |
<|file_name|>models.py<|end_file_name|><|fim▁begin|>import hashlib
from datetime import datetime
from flask import request
from flask_login import UserMixin
from werkzeug.security import generate_password_hash, check_password_hash
from . import db, login_manager
#pylint: disable-msg=E1101
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
#pylint: disable-msg=E1101
class User(UserMixin, db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
email = db.Column(db.String(64),
nullable=False,
unique=True,
index=True)
username = db.Column(db.String(64),
nullable=False,
unique=True,
index=True)
is_admin = db.Column(db.Boolean)
name = db.Column(db.String(64))
location = db.Column(db.String(64))
bio = db.Column(db.Text)
password_hash = db.Column(db.String(128))
avatar_hash = db.Column(db.String(32))
member_since = db.Column(db.DateTime(), default = datetime.utcnow)
fb_token = db.Column(db.Text)
posts = db.relationship('Post', backref='author', lazy='dynamic')
def __init__(self, **kwargs):
super(User, self).__init__(**kwargs)
if self.email is not None and self.avatar_hash is None:
self.avatar_hash = hashlib.md5(self.email.encode('utf-8')).hexdigest()
#pylint: disable-msg=R0201
@property
def password(self):
raise AttributeError('Password is not a readable attribute')
@password.setter
def password(self, password):
self.password_hash = generate_password_hash(password)
def verify_password(self, password):
return check_password_hash(self.password_hash, password)
def gravatar(self, size=100, default='identicon', rating='g'):
if request.is_secure:
url = 'https://secure.gravatar.com/avatar'
else:
url = 'http://www.gravatar.com/avatar'
h = self.avatar_hash or \
hashlib.md5(self.email.encode('utf-8')).hexdigest()
return '{u}/{h}?s={s}&d={d}&r={r}'.format(u=url,
h=h,
s=size,
d=default,
r=rating)
class Post(db.Model):
__tablename__ = 'posts'
__searchable__ = ['title', 'body_html']
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
title = db.Column(db.String(64))
body = db.Column(db.Text)
body_html = db.Column(db.Text)
language = db.Column(db.String(4), default='is')
timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow)
author_id = db.Column(db.Integer, db.ForeignKey('users.id'))
category_id = db.Column(db.Integer, db.ForeignKey('categories.id'))
def __init__(self, **kwargs):
super(Post, self).__init__(**kwargs)
@classmethod
def get_all(cls, descending=True):
if descending:
return cls.query.order_by(cls.timestamp.desc()).all()
else:
return cls.query.order_by(cls.timestamp).all()
@classmethod
def get_all_by_lang(cls, descending=True, lang='is'):
if descending:
return cls.query.order_by(cls.timestamp.desc())\
.filter_by(language=lang)\
.all()
else:
return cls.query.order_by(cls.timestamp)\
.filter_by(language=lang)\
.all()
@classmethod
def get_per_page(cls, page, per_page=5, descending=True, lang='is'):
if descending:
return cls.query.order_by(cls.timestamp.desc())\
.filter_by(language=lang)\
.paginate(page, per_page, False)
else:
return cls.query.order_by(cls.timestamp)\
.filter_by(language=lang)\
.paginate(page, per_page, False)
@classmethod
def get_by_id(cls, aid):
return cls.query.filter_by(id=aid).first_or_404()
#pylint: disable-msg=R0913
@classmethod
def get_by_category(cls, cid, page, per_page=5, descending=True, lang='is'):
if descending:
return cls.query.filter(cls.category_id == cid)\
.filter_by(language=lang)\
.order_by(cls.timestamp.desc())\
.paginate(page, per_page, False)
else:
return cls.query.filter(cls.category_id == cid)\
.filter_by(language=lang)\
.order_by(cls.timestamp)\
.paginate(page, per_page, False)
@classmethod
def search(cls, query, page, per_page=4, descending=True):
if descending:
return cls.query.whoosh_search(query)\
.order_by(cls.timestamp.desc())\
.paginate(page, per_page, False)
else:
return cls.query.whoosh_search(query)\
.order_by(cls.timestamp)\
.paginate(page, per_page, False)
class Category(db.Model):
__tablename__ = 'categories'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.String(64), nullable=False, unique=True)
name_en = db.Column(db.String(64), nullable=False, unique=True)
active = db.Column(db.Boolean, nullable=False, default=False)
posts = db.relationship('Post', backref='category', lazy='dynamic')
def __init__(self, **kwargs):
super(Category, self).__init__(**kwargs)
@classmethod
def get_all_active(cls, active=True):
if active:
return cls.query.filter_by(active=True)\
.filter(cls.name != 'Almenn frétt').all()<|fim▁hole|> @classmethod
def get_by_name(cls, name):
return cls.query.filter_by(name=name).first()
class Image(db.Model):
__tablename__ = 'images'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
filename = db.Column(db.String(120), nullable=True)
ad_html = db.Column(db.Text)
location = db.Column(db.String(120), nullable=False)
type = db.Column(db.Integer, nullable=False)
url = db.Column(db.String(120))
active = db.Column(db.Boolean, default=False)
timestamp = db.Column(db.DateTime,
nullable=False,
default=datetime.utcnow)
def __init__(self, **kwargs):
super(Image, self).__init__(**kwargs)
@classmethod
def get_all_imgs(cls, descending=True):
if descending:
return cls.query.filter(cls.type >= 10)\
.order_by(cls.timestamp.desc()).all()
else:
return cls.query.filter(cls.type >= 10)\
.order_by(cls.timestamp).all()
@classmethod
def get_all_ads(cls, descending=True, only_active=True):
if descending:
if only_active:
return cls.query.filter(cls.type < 10)\
.filter(cls.active == True)\
.order_by(cls.timestamp.desc()).all()
else:
return cls.query.filter(cls.type < 10)\
.order_by(cls.timestamp.desc()).all()
else:
if only_active:
return cls.query.filter(cls.type < 10)\
.filter(cls.active == True)\
.order_by(cls.timestamp).all()
else:
return cls.query.filter(cls.type < 10)\
.order_by(cls.timestamp).all()
@classmethod
def get_by_id(cls, aid):
return cls.query.filter_by(id=aid).first()
#pylint: disable-msg=R0903
class About(db.Model):
__tablename__ = 'about'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
body = db.Column(db.Text)
timestamp = db.Column(db.DateTime,
nullable=False,
default=datetime.utcnow)
def __init__(self, **kwargs):
super(About, self).__init__(**kwargs)<|fim▁end|> | else:
return cls.query.filter_by(active=False)\
.filter(cls.name != 'Almenn frétt').all()
|
<|file_name|>Element.Data.Specs.js<|end_file_name|><|fim▁begin|>/*
---
name: Element.Data.Specs
description: n/a
requires: [Behavior/Element.Data]
provides: [Element.Data.Specs]
...<|fim▁hole|>
(function(){
var target = new Element('div', {
'data-filters': 'Test1 Test2',
'data-json':'{"foo": "bar", "nine": 9, "arr": [1, 2, 3]}'
});
describe('Element.Data', function(){
it('should get a data property from an element', function(){
expect(target.getData('filters')).toBe('Test1 Test2');
});
it('should set a data property on an element', function(){
target.setData('foo', 'bar');
expect(target.getData('foo')).toBe('bar');
});
it('should read a property as JSON', function(){
var json = target.getJSONData('json');
expect(json.foo).toBe('bar');
expect(json.nine).toBe(9);
expect(json.arr).toEqual([1,2,3]);
});
it('should set a property as JSON', function(){
target.setJSONData('json2', {
foo: 'bar', nine: 9, arr: [1,2,3]
});
var json = target.getJSONData('json2');
expect(json.foo).toBe('bar');
expect(json.nine).toBe(9);
expect(json.arr).toEqual([1,2,3]);
});
it('should return null for a non-defined property', function(){
expect(target.getData('baz')).toBeNull();
});
});
})();<|fim▁end|> | */ |
<|file_name|>timeline-view.js<|end_file_name|><|fim▁begin|>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
function drawApplicationTimeline(groupArray, eventObjArray, startTime, offset) {
var groups = new vis.DataSet(groupArray);
var items = new vis.DataSet(eventObjArray);
var container = $("#application-timeline")[0];
var options = {
groupOrder: function(a, b) {
return a.value - b.value
},
editable: false,
align: 'left',
showCurrentTime: false,
start: startTime,
zoomable: false,
locale: "en",
moment: function (date) {
return vis.moment(date).utcOffset(offset);
}
};
var applicationTimeline = new vis.Timeline(container);
applicationTimeline.setOptions(options);
applicationTimeline.setGroups(groups);
applicationTimeline.setItems(items);
setupZoomable("#application-timeline-zoom-lock", applicationTimeline);
setupExecutorEventAction();
function getIdForJobEntry(baseElem) {
var jobIdText = $($(baseElem).find(".application-timeline-content")[0]).text();
var jobId = jobIdText.match("\\(Job (\\d+)\\)$")[1];
return jobId;
}
function getSelectorForJobEntry(jobId) {
return "#job-" + jobId;
}
function setupJobEventAction() {
$(".vis-item.vis-range.job.application-timeline-object").each(function() {
$(this).click(function() {
var jobId = getIdForJobEntry(this);
var jobPagePath = uiRoot + appBasePath + "/jobs/job/?id=" + jobId;
window.location.href = jobPagePath;
});
$(this).hover(
function() {
$(getSelectorForJobEntry(getIdForJobEntry(this))).addClass("corresponding-item-hover");
$($(this).find("div.application-timeline-content")[0]).tooltip("show");
},
function() {
$(getSelectorForJobEntry(getIdForJobEntry(this))).removeClass("corresponding-item-hover");
$($(this).find("div.application-timeline-content")[0]).tooltip("hide");
}
);
});
}
setupJobEventAction();
$("span.expand-application-timeline").click(function() {
var status = window.localStorage.getItem("expand-application-timeline") == "true";
status = !status;
$("#application-timeline").toggleClass('collapsed');
var visibilityState = status ? "" : "none";
$("#application-timeline").css("display", visibilityState);
// Switch the class of the arrow from open to closed.
$(this).find('.expand-application-timeline-arrow').toggleClass('arrow-open');
$(this).find('.expand-application-timeline-arrow').toggleClass('arrow-closed');
window.localStorage.setItem("expand-application-timeline", "" + status);
});
}
$(function () {
if ($("span.expand-application-timeline").length &&
window.localStorage.getItem("expand-application-timeline") == "true") {
// Set it to false so that the click function can revert it
window.localStorage.setItem("expand-application-timeline", "false");
$("span.expand-application-timeline").trigger('click');
} else {
$("#application-timeline").css("display", "none");
}
});
function drawJobTimeline(groupArray, eventObjArray, startTime, offset) {
var groups = new vis.DataSet(groupArray);
var items = new vis.DataSet(eventObjArray);
var container = $('#job-timeline')[0];
var options = {
groupOrder: function(a, b) {
return a.value - b.value;
},
editable: false,
align: 'left',
showCurrentTime: false,
start: startTime,
zoomable: false,
locale: "en",
moment: function (date) {
return vis.moment(date).utcOffset(offset);
}
};
var jobTimeline = new vis.Timeline(container);<|fim▁hole|> jobTimeline.setGroups(groups);
jobTimeline.setItems(items);
setupZoomable("#job-timeline-zoom-lock", jobTimeline);
setupExecutorEventAction();
function getStageIdAndAttemptForStageEntry(baseElem) {
var stageIdText = $($(baseElem).find(".job-timeline-content")[0]).text();
var stageIdAndAttempt = stageIdText.match("\\(Stage (\\d+\\.\\d+)\\)$")[1].split(".");
return stageIdAndAttempt;
}
function getSelectorForStageEntry(stageIdAndAttempt) {
return "#stage-" + stageIdAndAttempt[0] + "-" + stageIdAndAttempt[1];
}
function setupStageEventAction() {
$(".vis-item.vis-range.stage.job-timeline-object").each(function() {
$(this).click(function() {
var stageIdAndAttempt = getStageIdAndAttemptForStageEntry(this);
var stagePagePath = uiRoot + appBasePath +
"/stages/stage/?id=" + stageIdAndAttempt[0] + "&attempt=" + stageIdAndAttempt[1];
window.location.href = stagePagePath;
});
$(this).hover(
function() {
$(getSelectorForStageEntry(getStageIdAndAttemptForStageEntry(this)))
.addClass("corresponding-item-hover");
$($(this).find("div.job-timeline-content")[0]).tooltip("show");
},
function() {
$(getSelectorForStageEntry(getStageIdAndAttemptForStageEntry(this)))
.removeClass("corresponding-item-hover");
$($(this).find("div.job-timeline-content")[0]).tooltip("hide");
}
);
});
}
setupStageEventAction();
$("span.expand-job-timeline").click(function() {
var status = window.localStorage.getItem("expand-job-timeline") == "true";
status = !status;
$("#job-timeline").toggleClass('collapsed');
var visibilityState = status ? "" : "none";
$("#job-timeline").css("display", visibilityState);
// Switch the class of the arrow from open to closed.
$(this).find('.expand-job-timeline-arrow').toggleClass('arrow-open');
$(this).find('.expand-job-timeline-arrow').toggleClass('arrow-closed');
window.localStorage.setItem("expand-job-timeline", "" + status);
});
}
$(function () {
if ($("span.expand-job-timeline").length &&
window.localStorage.getItem("expand-job-timeline") == "true") {
// Set it to false so that the click function can revert it
window.localStorage.setItem("expand-job-timeline", "false");
$("span.expand-job-timeline").trigger('click');
} else {
$("#job-timeline").css("display", "none");
}
});
function drawTaskAssignmentTimeline(groupArray, eventObjArray, minLaunchTime, maxFinishTime, offset) {
var groups = new vis.DataSet(groupArray);
var items = new vis.DataSet(eventObjArray);
var container = $("#task-assignment-timeline")[0];
var options = {
groupOrder: function(a, b) {
return a.value - b.value
},
editable: false,
align: 'left',
selectable: false,
showCurrentTime: false,
start: minLaunchTime,
end: maxFinishTime,
zoomable: false,
locale: "en",
moment: function (date) {
return vis.moment(date).utcOffset(offset);
}
};
var taskTimeline = new vis.Timeline(container);
taskTimeline.setOptions(options);
taskTimeline.setGroups(groups);
taskTimeline.setItems(items);
// If a user zooms while a tooltip is displayed, the user may zoom such that the cursor is no
// longer over the task that the tooltip corresponds to. So, when a user zooms, we should hide
// any currently displayed tooltips.
var currentDisplayedTooltip = null;
$("#task-assignment-timeline").on({
"mouseenter": function() {
currentDisplayedTooltip = this;
},
"mouseleave": function() {
currentDisplayedTooltip = null;
}
}, ".task-assignment-timeline-content");
taskTimeline.on("rangechange", function(prop) {
if (currentDisplayedTooltip !== null) {
$(currentDisplayedTooltip).tooltip("hide");
}
});
setupZoomable("#task-assignment-timeline-zoom-lock", taskTimeline);
$("span.expand-task-assignment-timeline").click(function() {
var status = window.localStorage.getItem("expand-task-assignment-timeline") == "true";
status = !status;
$("#task-assignment-timeline").toggleClass("collapsed");
var visibilityState = status ? "" : "none";
$("#task-assignment-timeline").css("display", visibilityState);
// Switch the class of the arrow from open to closed.
$(this).find(".expand-task-assignment-timeline-arrow").toggleClass("arrow-open");
$(this).find(".expand-task-assignment-timeline-arrow").toggleClass("arrow-closed");
window.localStorage.setItem("expand-task-assignment-timeline", "" + status);
});
}
$(function () {
if ($("span.expand-task-assignment-timeline").length &&
window.localStorage.getItem("expand-task-assignment-timeline") == "true") {
// Set it to false so that the click function can revert it
window.localStorage.setItem("expand-task-assignment-timeline", "false");
$("span.expand-task-assignment-timeline").trigger('click');
} else {
$("#task-assignment-timeline").css("display", "none");
}
});
function setupExecutorEventAction() {
$(".vis-item.vis-box.executor").each(function () {
$(this).hover(
function() {
$($(this).find(".executor-event-content")[0]).tooltip("show");
},
function() {
$($(this).find(".executor-event-content")[0]).tooltip("hide");
}
);
});
}
function setupZoomable(id, timeline) {
$(id + ' > input[type="checkbox"]').click(function() {
if (this.checked) {
timeline.setOptions({zoomable: true});
} else {
timeline.setOptions({zoomable: false});
}
});
$(id + " > span").click(function() {
$(this).parent().find('input:checkbox').trigger('click');
});
}<|fim▁end|> | jobTimeline.setOptions(options); |
<|file_name|>714_best-time-to-buy-and-sell-stock-with-transaction-fee.py<|end_file_name|><|fim▁begin|>class Solution:
def maxProfit(self, prices, fee):
dp = [[-prices[0]], [0]]
for i in range(1, len(prices)):<|fim▁hole|> dp[1].append(max(dp[0][i-1]+prices[i]-fee, dp[1][i-1]))
return dp[1][-1]
print(Solution().maxProfit([1, 3, 2, 8, 4, 9], 2))<|fim▁end|> | dp[0].append(max(dp[0][i-1], dp[1][i-1]-prices[i])) |
<|file_name|>test_complex_ops.py<|end_file_name|><|fim▁begin|>#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import decimal
import datetime
import pandas as pd
from pyspark import pandas as ps
from pyspark.pandas.tests.data_type_ops.testing_utils import TestCasesUtils
from pyspark.testing.pandasutils import PandasOnSparkTestCase
class ComplexOpsTest(PandasOnSparkTestCase, TestCasesUtils):
@property
def pser(self):
return pd.Series([[1, 2, 3]])
@property
def psser(self):
return ps.from_pandas(self.pser)
@property
def numeric_array_pdf(self):
psers = {
"int": pd.Series([[1, 2, 3]]),
"float": pd.Series([[0.1, 0.2, 0.3]]),
"decimal": pd.Series([[decimal.Decimal(1), decimal.Decimal(2), decimal.Decimal(3)]]),
}
return pd.concat(psers, axis=1)
@property
def numeric_array_psdf(self):
return ps.from_pandas(self.numeric_array_pdf)
@property
def numeric_array_df_cols(self):
return self.numeric_array_pdf.columns
@property
def non_numeric_array_pdf(self):
psers = {
"string": pd.Series([["x", "y", "z"]]),
"date": pd.Series(
[[datetime.date(1994, 1, 1), datetime.date(1994, 1, 2), datetime.date(1994, 1, 3)]]
),
"bool": pd.Series([[True, True, False]]),
}
return pd.concat(psers, axis=1)
@property
def non_numeric_array_psdf(self):
return ps.from_pandas(self.non_numeric_array_pdf)
@property
def non_numeric_array_df_cols(self):
return self.non_numeric_array_pdf.columns
@property
def array_pdf(self):
return pd.concat([self.numeric_array_pdf, self.non_numeric_array_pdf], axis=1)
@property
def array_psdf(self):
return ps.from_pandas(self.array_pdf)
@property
def array_df_cols(self):
return self.array_pdf.columns
@property
def complex_pdf(self):
psers = {
"this_array": self.pser,
"that_array": pd.Series([[2, 3, 4]]),
"this_struct": pd.Series([("x", 1)]),
"that_struct": pd.Series([("a", 2)]),
}
return pd.concat(psers, axis=1)
@property
def complex_psdf(self):
pssers = {
"this_array": self.psser,
"that_array": ps.Series([[2, 3, 4]]),
"this_struct": ps.Index([("x", 1)]).to_series().reset_index(drop=True),
"that_struct": ps.Index([("a", 2)]).to_series().reset_index(drop=True),
}
return ps.concat(pssers, axis=1)
def test_add(self):
pdf, psdf = self.array_pdf, self.array_psdf
for col in self.array_df_cols:
self.assert_eq(pdf[col] + pdf[col], psdf[col] + psdf[col])
# Numeric array + Numeric array
for col in self.numeric_array_df_cols:
pser1, psser1 = pdf[col], psdf[col]
for other_col in self.numeric_array_df_cols:
pser2, psser2 = pdf[other_col], psdf[other_col]
self.assert_eq((pser1 + pser2).sort_values(), (psser1 + psser2).sort_values())
# Non-numeric array + Non-numeric array
self.assertRaises(
TypeError,
lambda: psdf["string"] + psdf["bool"],
)
self.assertRaises(
TypeError,
lambda: psdf["string"] + psdf["date"],
)
self.assertRaises(
TypeError,
lambda: psdf["bool"] + psdf["date"],
)
for col in self.non_numeric_array_df_cols:
pser, psser = pdf[col], psdf[col]
self.assert_eq(pser + pser, psser + psser)
# Numeric array + Non-numeric array
for numeric_col in self.numeric_array_df_cols:
for non_numeric_col in self.non_numeric_array_df_cols:
self.assertRaises(TypeError, lambda: psdf[numeric_col] + psdf[non_numeric_col])
def test_sub(self):
self.assertRaises(TypeError, lambda: self.psser - "x")
self.assertRaises(TypeError, lambda: self.psser - 1)
psdf = self.array_psdf
for col in self.array_df_cols:
for other_col in self.array_df_cols:
self.assertRaises(TypeError, lambda: psdf[col] - psdf[other_col])
def test_mul(self):
self.assertRaises(TypeError, lambda: self.psser * "x")
self.assertRaises(TypeError, lambda: self.psser * 1)
psdf = self.array_psdf
for col in self.array_df_cols:
for other_col in self.array_df_cols:
self.assertRaises(TypeError, lambda: psdf[col] * psdf[other_col])
def test_truediv(self):
self.assertRaises(TypeError, lambda: self.psser / "x")
self.assertRaises(TypeError, lambda: self.psser / 1)
psdf = self.array_psdf
for col in self.array_df_cols:
for other_col in self.array_df_cols:
self.assertRaises(TypeError, lambda: psdf[col] / psdf[other_col])
def test_floordiv(self):
self.assertRaises(TypeError, lambda: self.psser // "x")
self.assertRaises(TypeError, lambda: self.psser // 1)
psdf = self.array_psdf
for col in self.array_df_cols:
for other_col in self.array_df_cols:
self.assertRaises(TypeError, lambda: psdf[col] // psdf[other_col])
def test_mod(self):
self.assertRaises(TypeError, lambda: self.psser % "x")
self.assertRaises(TypeError, lambda: self.psser % 1)
psdf = self.array_psdf
for col in self.array_df_cols:
for other_col in self.array_df_cols:
self.assertRaises(TypeError, lambda: psdf[col] % psdf[other_col])
def test_pow(self):
self.assertRaises(TypeError, lambda: self.psser ** "x")
self.assertRaises(TypeError, lambda: self.psser ** 1)
psdf = self.array_psdf
for col in self.array_df_cols:
for other_col in self.array_df_cols:
self.assertRaises(TypeError, lambda: psdf[col] ** psdf[other_col])
def test_radd(self):
self.assertRaises(TypeError, lambda: "x" + self.psser)
self.assertRaises(TypeError, lambda: 1 + self.psser)
def test_rsub(self):
self.assertRaises(TypeError, lambda: "x" - self.psser)
self.assertRaises(TypeError, lambda: 1 - self.psser)
def test_rmul(self):
self.assertRaises(TypeError, lambda: "x" * self.psser)
self.assertRaises(TypeError, lambda: 2 * self.psser)
def test_rtruediv(self):
self.assertRaises(TypeError, lambda: "x" / self.psser)
self.assertRaises(TypeError, lambda: 1 / self.psser)
def test_rfloordiv(self):
self.assertRaises(TypeError, lambda: "x" // self.psser)
self.assertRaises(TypeError, lambda: 1 // self.psser)
def test_rmod(self):
self.assertRaises(TypeError, lambda: 1 % self.psser)
def test_rpow(self):
self.assertRaises(TypeError, lambda: "x" ** self.psser)
self.assertRaises(TypeError, lambda: 1 ** self.psser)
def test_and(self):
self.assertRaises(TypeError, lambda: self.psser & True)
self.assertRaises(TypeError, lambda: self.psser & False)
self.assertRaises(TypeError, lambda: self.psser & self.psser)
def test_rand(self):
self.assertRaises(TypeError, lambda: True & self.psser)
self.assertRaises(TypeError, lambda: False & self.psser)
def test_or(self):
self.assertRaises(TypeError, lambda: self.psser | True)
self.assertRaises(TypeError, lambda: self.psser | False)
self.assertRaises(TypeError, lambda: self.psser | self.psser)
def test_ror(self):
self.assertRaises(TypeError, lambda: True | self.psser)
self.assertRaises(TypeError, lambda: False | self.psser)
def test_from_to_pandas(self):
pdf, psdf = self.array_pdf, self.array_psdf
for col in self.array_df_cols:
pser, psser = pdf[col], psdf[col]
self.assert_eq(pser, psser.to_pandas())
self.assert_eq(ps.from_pandas(pser), psser)
def test_isnull(self):
pdf, psdf = self.array_pdf, self.array_psdf
for col in self.array_df_cols:
pser, psser = pdf[col], psdf[col]
self.assert_eq(pser.isnull(), psser.isnull())
def test_astype(self):
self.assert_eq(self.pser.astype(str), self.psser.astype(str))
def test_neg(self):
self.assertRaises(TypeError, lambda: -self.psser)
def test_abs(self):
self.assertRaises(TypeError, lambda: abs(self.psser))
def test_invert(self):
self.assertRaises(TypeError, lambda: ~self.psser)
def test_eq(self):
pdf, psdf = self.complex_pdf, self.complex_pdf
self.assert_eq(
pdf["this_array"] == pdf["that_array"], psdf["this_array"] == psdf["that_array"]
)
self.assert_eq(
pdf["this_struct"] == pdf["that_struct"], psdf["this_struct"] == psdf["that_struct"]
)
self.assert_eq(
pdf["this_array"] == pdf["this_array"], psdf["this_array"] == psdf["this_array"]
)
self.assert_eq(
pdf["this_struct"] == pdf["this_struct"], psdf["this_struct"] == psdf["this_struct"]
)
def test_ne(self):
pdf, psdf = self.complex_pdf, self.complex_pdf
self.assert_eq(
pdf["this_array"] != pdf["that_array"], psdf["this_array"] != psdf["that_array"]
)
self.assert_eq(
pdf["this_struct"] != pdf["that_struct"], psdf["this_struct"] != psdf["that_struct"]
)
self.assert_eq(
pdf["this_array"] != pdf["this_array"], psdf["this_array"] != psdf["this_array"]
)
self.assert_eq(
pdf["this_struct"] != pdf["this_struct"], psdf["this_struct"] != psdf["this_struct"]
)
def test_lt(self):
pdf, psdf = self.complex_pdf, self.complex_pdf
self.assert_eq(
pdf["this_array"] < pdf["that_array"], psdf["this_array"] < psdf["that_array"]
)
self.assert_eq(
pdf["this_struct"] < pdf["that_struct"], psdf["this_struct"] < psdf["that_struct"]
)
self.assert_eq(
pdf["this_array"] < pdf["this_array"], psdf["this_array"] < psdf["this_array"]
)
self.assert_eq(
pdf["this_struct"] < pdf["this_struct"], psdf["this_struct"] < psdf["this_struct"]
)
def test_le(self):
pdf, psdf = self.complex_pdf, self.complex_pdf
self.assert_eq(
pdf["this_array"] <= pdf["that_array"], psdf["this_array"] <= psdf["that_array"]
)
self.assert_eq(
pdf["this_struct"] <= pdf["that_struct"], psdf["this_struct"] <= psdf["that_struct"]
)
self.assert_eq(
pdf["this_array"] <= pdf["this_array"], psdf["this_array"] <= psdf["this_array"]
)
self.assert_eq(
pdf["this_struct"] <= pdf["this_struct"], psdf["this_struct"] <= psdf["this_struct"]
)
def test_gt(self):
pdf, psdf = self.complex_pdf, self.complex_pdf
self.assert_eq(
pdf["this_array"] > pdf["that_array"], psdf["this_array"] > psdf["that_array"]
)
self.assert_eq(
pdf["this_struct"] > pdf["that_struct"], psdf["this_struct"] > psdf["that_struct"]
)
self.assert_eq(
pdf["this_array"] > pdf["this_array"], psdf["this_array"] > psdf["this_array"]
)
self.assert_eq(
pdf["this_struct"] > pdf["this_struct"], psdf["this_struct"] > psdf["this_struct"]
)
def test_ge(self):<|fim▁hole|> pdf, psdf = self.complex_pdf, self.complex_pdf
self.assert_eq(
pdf["this_array"] >= pdf["that_array"], psdf["this_array"] >= psdf["that_array"]
)
self.assert_eq(
pdf["this_struct"] >= pdf["that_struct"], psdf["this_struct"] >= psdf["that_struct"]
)
self.assert_eq(
pdf["this_array"] >= pdf["this_array"], psdf["this_array"] >= psdf["this_array"]
)
self.assert_eq(
pdf["this_struct"] >= pdf["this_struct"], psdf["this_struct"] >= psdf["this_struct"]
)
if __name__ == "__main__":
import unittest
from pyspark.pandas.tests.data_type_ops.test_complex_ops import * # noqa: F401
try:
import xmlrunner # type: ignore[import]
testRunner = xmlrunner.XMLTestRunner(output="target/test-reports", verbosity=2)
except ImportError:
testRunner = None
unittest.main(testRunner=testRunner, verbosity=2)<|fim▁end|> | |
<|file_name|>debug.rs<|end_file_name|><|fim▁begin|>// This file is part of zinc64.
// Copyright (c) 2016-2019 Sebastian Jastrzebski. All rights reserved.
// Licensed under the GPLv3. See LICENSE file in the project root for full license text.
#![allow(unused)]
#![cfg_attr(feature = "cargo-clippy", allow(clippy::cast_lossless))]
use std::sync::mpsc;
use std::sync::mpsc::Sender;
use std::time::Duration;
use byteorder::{BigEndian, WriteBytesExt};
use zinc64_debug::{Command, Output, RegData, RegOp};
use zinc64_emu::system::C64;
use crate::app::RuntimeState;
// DEFERRED debugger: impl io
struct CmdResult(Output, Option<RuntimeState>);
impl CmdResult {
pub fn ok(result: Output) -> Result<CmdResult, String> {
Ok(CmdResult(result, None))
}
pub fn ok_with_state(result: Output, state: RuntimeState) -> Result<CmdResult, String> {
Ok(CmdResult(result, Some(state)))
}
pub fn unit() -> Result<CmdResult, String> {
Ok(CmdResult(Output::Unit, None))
}
}
pub struct Debug {
debug_rx: mpsc::Receiver<Command>,
debugger: Option<Sender<Output>>,
}
impl Debug {
pub fn new(debug_rx: mpsc::Receiver<Command>) -> Self {
Self {
debug_rx,
debugger: None,
}
}
pub fn execute(
&mut self,
c64: &mut C64,
command: &Command,
) -> Result<Option<RuntimeState>, String> {
match self.execute_internal(c64, &command) {
Ok(CmdResult(Output::Await, new_state)) => Ok(new_state),
Ok(CmdResult(result, new_state)) => {
self.send_result(result);
Ok(new_state)
}
Err(error) => {
self.send_result(Output::Error(error.clone()));
Err(error)
}
}
}
pub fn halt(&mut self) -> Result<(), String> {
self.send_result(Output::Unit)
}
pub fn poll(&mut self, debugging: bool) -> Option<Command> {
if debugging {
self.debug_rx.recv_timeout(Duration::from_millis(1)).ok()
} else {
self.debug_rx.try_recv().ok()
}
}
fn execute_internal(&mut self, c64: &mut C64, command: &Command) -> Result<CmdResult, String> {
match *command {
Command::Attach(ref debugger) => self.attach(c64, debugger),
Command::Detach => self.detach(c64),
Command::Continue => self.continue_(c64),
Command::SysQuit => self.quit(c64),
Command::Step => self.step(c64),
Command::BpClear => self.bp_clear(c64),
Command::BpCondition(index, ref expr, radix) => {
self.bp_condition(c64, index, expr, radix)
}
Command::BpDisable(index) => self.bp_enable(c64, index, false),
Command::BpDisableAll => self.bp_enable_all(c64, false),
Command::BpEnable(index) => self.bp_enable(c64, index, true),
Command::BpEnableAll => self.bp_enable_all(c64, true),
Command::BpIgnore(index, count) => self.bp_ignore(c64, index, count),
Command::BpList => self.bp_list(c64),
Command::BpRemove(index) => self.bp_remove(c64, index),
Command::BpSet(address, autodelete) => self.bp_set(c64, address, autodelete),
Command::MemRead(start, end) => self.mem_read(c64, start, end),
Command::MemWrite(address, ref data) => self.mem_write(c64, address, data),
Command::RegRead => self.reg_read(c64),
Command::RegWrite(ref ops) => self.reg_write(c64, ops),
Command::SysReset(hard) => self.sys_reset(c64, hard),
Command::SysScreen => self.sys_screen(c64),
Command::SysStopwatch(reset) => self.sys_stopwatch(c64, reset),
}
}
fn send_result(&self, result: Output) -> Result<(), String> {
if let Some(ref debugger) = self.debugger {
debugger
.send(result)
.map_err(|_| "Failed to send result".to_string())
} else {
Ok(())
}
}
// -- Commands
fn attach(&mut self, c64: &mut C64, debugger: &Sender<Output>) -> Result<CmdResult, String> {
self.debugger = Some(debugger.clone());
CmdResult::ok_with_state(Output::Unit, RuntimeState::Halted)
}
fn detach(&mut self, c64: &mut C64) -> Result<CmdResult, String> {
self.debugger = None;
CmdResult::ok_with_state(Output::Unit, RuntimeState::Running)
}
fn continue_(&self, c64: &mut C64) -> Result<CmdResult, String> {
CmdResult::ok_with_state(Output::Await, RuntimeState::Running)
}
fn quit(&self, c64: &mut C64) -> Result<CmdResult, String> {
CmdResult::ok_with_state(Output::Unit, RuntimeState::Stopped)
}
fn step(&self, c64: &mut C64) -> Result<CmdResult, String> {
c64.step();
let bp_hit = if c64.check_breakpoints() { 1 } else { 0 };
CmdResult::ok(Output::Number(bp_hit))
}
fn bp_clear(&self, c64: &mut C64) -> Result<CmdResult, String> {
let bpm = c64.get_bpm_mut();
bpm.clear();
CmdResult::unit()
}
fn bp_condition(
&self,
c64: &mut C64,
index: u16,
expr: &str,
radix: u32,
) -> Result<CmdResult, String> {
let bpm = c64.get_bpm_mut();
bpm.set_condition(index, expr, Some(radix))?;
let bp = bpm.get(index)?;
let buffer = format!(
"Setting condition for breakpoint {} to: {}\n",
bp.index,
bp.condition
.as_ref()
.map(|cond| format!("{}", cond))<|fim▁hole|> .unwrap_or_else(|| "".to_string())
);
CmdResult::ok(Output::Text(buffer))
}
fn bp_enable(&self, c64: &mut C64, index: u16, enabled: bool) -> Result<CmdResult, String> {
let bpm = c64.get_bpm_mut();
bpm.set_enabled(index, enabled)?;
CmdResult::unit()
}
fn bp_enable_all(&self, c64: &mut C64, enabled: bool) -> Result<CmdResult, String> {
let bpm = c64.get_bpm_mut();
bpm.enable_all(enabled);
CmdResult::unit()
}
fn bp_ignore(&self, c64: &mut C64, index: u16, count: u16) -> Result<CmdResult, String> {
let bpm = c64.get_bpm_mut();
bpm.ignore(index, count)?;
CmdResult::unit()
}
fn bp_list(&self, c64: &mut C64) -> Result<CmdResult, String> {
let bpm = c64.get_bpm();
let mut buffer = String::new();
for bp in bpm.list() {
buffer.push_str(
format!(
"Bp {}: ${:04x}{}{}\n",
bp.index,
bp.address,
bp.condition
.as_ref()
.map_or(String::new(), |cond| format!(" if {}", cond)),
if bp.enabled { "" } else { " disabled" },
)
.as_str(),
);
}
if buffer.is_empty() {
buffer.push_str("No breakpoints are set\n");
}
CmdResult::ok(Output::Text(buffer))
}
fn bp_remove(&self, c64: &mut C64, index: u16) -> Result<CmdResult, String> {
let bpm = c64.get_bpm_mut();
bpm.remove(index)?;
CmdResult::unit()
}
fn bp_set(&self, c64: &mut C64, address: u16, autodelete: bool) -> Result<CmdResult, String> {
let bpm = c64.get_bpm_mut();
let index = bpm.set(address, autodelete);
let buffer = format!("Bp {}: ${:04x}\n", index, address);
CmdResult::ok(Output::Text(buffer))
}
fn mem_read(&self, c64: &mut C64, start: u16, end: u16) -> Result<CmdResult, String> {
let cpu = c64.get_cpu();
let mut buffer = Vec::new();
let mut address = start;
while address < end {
buffer.push(cpu.read(address));
address = address.wrapping_add(1);
}
CmdResult::ok(Output::Buffer(buffer))
}
fn mem_write(&self, c64: &mut C64, address: u16, data: &[u8]) -> Result<CmdResult, String> {
c64.load(data, address);
CmdResult::unit()
}
fn reg_read(&self, c64: &mut C64) -> Result<CmdResult, String> {
let clock = c64.get_clock().get();
let cpu = c64.get_cpu();
let regs = RegData {
a: cpu.get_a(),
x: cpu.get_x(),
y: cpu.get_y(),
p: cpu.get_p(),
sp: cpu.get_sp(),
pc: cpu.get_pc(),
port_00: cpu.read(0x00),
port_01: cpu.read(0x01),
clock,
};
CmdResult::ok(Output::Registers(regs))
}
fn reg_write(&self, c64: &mut C64, ops: &[RegOp]) -> Result<CmdResult, String> {
let cpu = c64.get_cpu_mut();
for op in ops {
match *op {
RegOp::SetA(value) => cpu.set_a(value),
RegOp::SetX(value) => cpu.set_x(value),
RegOp::SetY(value) => cpu.set_y(value),
RegOp::SetP(value) => cpu.set_p(value),
RegOp::SetSP(value) => cpu.set_sp(value),
RegOp::SetPC(value) => cpu.set_pc(value),
}
}
CmdResult::unit()
}
fn sys_reset(&self, c64: &mut C64, hard: bool) -> Result<CmdResult, String> {
c64.reset(hard);
CmdResult::unit()
}
fn sys_screen(&self, c64: &mut C64) -> Result<CmdResult, String> {
let cia2 = c64.get_cia_2();
let vic = c64.get_vic();
let cia2_port_a = cia2.borrow_mut().read(0x00);
let vm = (((vic.borrow_mut().read(0x18) & 0xf0) >> 4) as u16) << 10;
let vm_base = ((!cia2_port_a & 0x03) as u16) << 14 | vm;
CmdResult::ok(Output::Number(vm_base))
}
fn sys_stopwatch(&self, c64: &mut C64, reset: bool) -> Result<CmdResult, String> {
let clock = c64.get_clock();
if reset {
clock.reset();
}
let mut buffer = Vec::new();
buffer
.write_u64::<BigEndian>(clock.get())
.map_err(|_| "Op failed")?;
CmdResult::ok(Output::Buffer(buffer))
}
}<|fim▁end|> | |
<|file_name|>videoplayer.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
import functools
from nxtools import logging, log_traceback
from .utils import (
Qt,
QWidget,
QSlider,
QTimer,
QHBoxLayout,
QVBoxLayout,
QIcon,
RegionBar,
TimecodeWindow,
get_navbar,
)
try:
from .mpv import MPV
has_mpv = True
except OSError:
has_mpv = False
log_traceback()
logging.warning(
"Unable to load MPV libraries. Video preview will not be available."
)
class DummyPlayer:
def property_observer(self, *args):
return lambda x: x
def __setitem__(self, key, value):
return
def __getitem__(self, key):
return
def play(self, *args, **kwargs):
pass
def seek(self, *args, **kwargs):
pass
def frame_step(self, *args, **kwargs):
pass
def frame_back_step(self, *args, **kwargs):
pass
class VideoPlayer(QWidget):
def __init__(self, parent=None, pixlib=None):
super(VideoPlayer, self).__init__(parent)
self.pixlib = pixlib
self.markers = {}
self.video_window = QWidget(self)
self.video_window.setStyleSheet("background-color: #161616;")
if not has_mpv:
self.player = DummyPlayer()
else:
try:
self.player = MPV(
keep_open=True, wid=str(int(self.video_window.winId()))
)
except Exception:
log_traceback(handlers=False)
self.player = DummyPlayer()
self.position = 0
self.duration = 0
self.mark_in = 0
self.mark_out = 0
self.fps = 25.0
self.loaded = False
self.duration_changed = False
self.prev_position = 0
self.prev_duration = 0
self.prev_mark_in = 0
self.prev_mark_out = 0
#
# Displays
#
self.mark_in_display = TimecodeWindow(self)
self.mark_in_display.setToolTip("Selection start")
self.mark_in_display.returnPressed.connect(
functools.partial(self.on_mark_in, self.mark_in_display)
)
self.mark_out_display = TimecodeWindow(self)
self.mark_out_display.setToolTip("Selection end")
self.mark_out_display.returnPressed.connect(
functools.partial(self.on_mark_out, self.mark_out_display)
)
self.io_display = TimecodeWindow(self)
self.io_display.setToolTip("Selection duration")
self.io_display.setReadOnly(True)
self.position_display = TimecodeWindow(self)
self.position_display.setToolTip("Clip position")
self.position_display.returnPressed.connect(
functools.partial(self.seek, self.position_display)<|fim▁hole|> self.duration_display.setToolTip("Clip duration")
self.duration_display.setReadOnly(True)
#
# Controls
#
self.timeline = QSlider(Qt.Horizontal)
self.timeline.setRange(0, 0)
self.timeline.sliderMoved.connect(self.on_timeline_seek)
self.region_bar = RegionBar(self)
self.navbar = get_navbar(self)
#
# Layout
#
bottom_bar = QHBoxLayout()
top_bar = QHBoxLayout()
top_bar.addWidget(self.mark_in_display, 0)
top_bar.addStretch(1)
top_bar.addWidget(self.io_display, 0)
top_bar.addStretch(1)
top_bar.addWidget(self.mark_out_display, 0)
bottom_bar.addWidget(self.position_display, 0)
bottom_bar.addWidget(self.navbar, 1)
bottom_bar.addWidget(self.duration_display, 0)
layout = QVBoxLayout()
layout.addLayout(top_bar)
layout.addWidget(self.video_window)
layout.addWidget(self.region_bar)
layout.addWidget(self.timeline)
layout.addLayout(bottom_bar)
self.setLayout(layout)
self.navbar.setFocus(True)
@self.player.property_observer("time-pos")
def time_observer(_name, value):
self.on_time_change(value)
@self.player.property_observer("duration")
def duration_observer(_name, value):
self.on_duration_change(value)
@self.player.property_observer("pause")
def pause_observer(_name, value):
self.on_pause_change(value)
# Displays updater
self.display_timer = QTimer()
self.display_timer.timeout.connect(self.on_display_timer)
self.display_timer.start(40)
@property
def frame_dur(self):
return 1 / self.fps
def load(self, path, mark_in=0, mark_out=0, markers={}):
self.loaded = False
self.markers = markers
self.player["pause"] = True
self.player.play(path)
self.prev_mark_in = -1
self.prev_mark_out = -1
self.mark_in = mark_in
self.mark_out = mark_out
self.mark_in_display.set_value(0)
self.mark_out_display.set_value(0)
self.duration_display.set_value(0)
self.position_display.set_value(0)
def on_time_change(self, value):
self.position = value
def on_duration_change(self, value):
if value:
self.duration = value
self.loaded = True
else:
self.duration = 0
self.loaded = False
self.duration_changed = True
self.region_bar.update()
def on_pause_change(self, value):
if hasattr(self, "action_play"):
self.action_play.setIcon(QIcon(self.pixlib[["pause", "play"][int(value)]]))
def on_timeline_seek(self):
if not self.loaded:
return
try:
self.player["pause"] = True
self.player.seek(self.timeline.value() / 100.0, "absolute", "exact")
except Exception:
pass
def on_frame_next(self):
if not self.loaded:
return
self.player.frame_step()
def on_frame_prev(self):
if not self.loaded:
return
self.player.frame_back_step()
def on_5_next(self):
if not self.loaded:
return
self.player.seek(5 * self.frame_dur, "relative", "exact")
def on_5_prev(self):
if not self.loaded:
return
self.player.seek(-5 * self.frame_dur, "relative", "exact")
def on_go_start(self):
if not self.loaded:
return
self.player.seek(0, "absolute", "exact")
def on_go_end(self):
if not self.loaded:
return
self.player.seek(self.duration, "absolute", "exact")
def on_go_in(self):
if not self.loaded:
return
self.seek(self.mark_in)
def on_go_out(self):
if not self.loaded:
return
self.seek(self.mark_out or self.duration)
def on_mark_in(self, value=False):
if not self.loaded:
return
if value:
if isinstance(value, TimecodeWindow):
value = value.get_value()
self.seek(min(max(value, 0), self.duration))
self.mark_in = value
self.setFocus()
else:
self.mark_in = self.position
self.region_bar.update()
def on_mark_out(self, value=False):
if not self.loaded:
return
if value:
if isinstance(value, TimecodeWindow):
value = value.get_value()
self.seek(min(max(value, 0), self.duration))
self.mark_out = value
self.setFocus()
else:
self.mark_out = self.position
self.region_bar.update()
def on_clear_in(self):
if not self.loaded:
return
self.mark_in = 0
self.region_bar.update()
def on_clear_out(self):
if not self.loaded:
return
self.mark_out = 0
self.region_bar.update()
def on_clear_marks(self):
if not self.loaded:
return
self.mark_out = self.mark_in = 0
self.region_bar.update()
def seek(self, position):
if not self.loaded:
return
if isinstance(position, TimecodeWindow):
position = position.get_value()
self.setFocus()
self.player.seek(position, "absolute", "exact")
def on_pause(self):
if not self.loaded:
return
self.player["pause"] = not self.player["pause"]
def force_pause(self):
if not self.loaded:
return
if not self.player["pause"]:
self.player["pause"] = True
def update_marks(self):
i = self.mark_in
o = self.mark_out or self.duration
self.mark_in_display.set_value(i)
self.mark_out_display.set_value(o)
io = o - i + self.frame_dur
if io > 0:
self.io_display.set_value(io)
else:
self.io_display.set_value(0)
self.prev_mark_in = self.mark_in
self.prev_mark_out = self.mark_out
def on_display_timer(self):
if not self.loaded:
return
if self.position != self.prev_position and self.position is not None:
self.position_display.set_value(self.position)
self.timeline.setValue(int(self.position * 100))
self.prev_position = self.position
if self.duration != self.prev_duration and self.position is not None:
self.duration_display.set_value(self.duration)
self.timeline.setMaximum(int(self.duration * 100))
self.prev_duration = self.duration
if (
self.mark_in != self.prev_mark_in
or self.mark_out != self.prev_mark_out
or self.duration_changed
):
self.update_marks()
self.duration_changed = False<|fim▁end|> | )
self.duration_display = TimecodeWindow(self) |
<|file_name|>embed.js<|end_file_name|><|fim▁begin|>// NOTE: this file should only be included when embedding the inspector - no other files should be included (this will do everything)
// If gliEmbedDebug == true, split files will be used, otherwise the cat'ed scripts will be inserted
(function() {
var pathRoot = "";
var useDebug = window["gliEmbedDebug"];
// Find self in the <script> tags
var scripts = document.head.getElementsByTagName("script");
for (var n = 0; n < scripts.length; n++) {
var scriptTag = scripts[n];
var src = scriptTag.src.toLowerCase();
if (/core\/embed.js$/.test(src)) {
// Found ourself - strip our name and set the root
var index = src.lastIndexOf("embed.js");
pathRoot = scriptTag.src.substring(0, index);
break;
}
}
function insertHeaderNode(node) {
var targets = [ document.body, document.head, document.documentElement ];
for (var n = 0; n < targets.length; n++) {
var target = targets[n];
if (target) {
if (target.firstElementChild) {
target.insertBefore(node, target.firstElementChild);
} else {
target.appendChild(node);
}
break;
}
}
}
;
function insertStylesheet(url) {
var link = document.createElement("link");
link.rel = "stylesheet";
link.href = url;
insertHeaderNode(link);
return link;
}
;
function insertScript(url) {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = url;
insertHeaderNode(script);
return script;
}
;
if (useDebug) {
// Fall through below and use the loader to get things
} else {
var jsurl = pathRoot + "lib/gli.all.js";
var cssurl = pathRoot + "lib/gli.all.css";
window.gliCssUrl = cssurl;
insertStylesheet(cssurl);
insertScript(jsurl);
}
// Always load the loader
if (useDebug) {
var script = insertScript(pathRoot + "loader.js");
function scriptLoaded() {
gliloader.pathRoot = pathRoot;
if (useDebug) {
// In debug mode load all the scripts
gliloader.load([ "host", "replay", "ui" ]);
}
}
;
script.onreadystatechange = function() {
if (("loaded" === script.readyState || "complete" === script.readyState) && !script.loadCalled) {
this.loadCalled = true;
scriptLoaded();
}
};<|fim▁hole|> scriptLoaded();
}
};
}
// Hook canvas.getContext
var originalGetContext = HTMLCanvasElement.prototype.getContext;
if (!HTMLCanvasElement.prototype.getContextRaw) {
HTMLCanvasElement.prototype.getContextRaw = originalGetContext;
}
HTMLCanvasElement.prototype.getContext = function() {
var ignoreCanvas = this.internalInspectorSurface;
if (ignoreCanvas) {
return originalGetContext.apply(this, arguments);
}
var contextNames = [ "moz-webgl", "webkit-3d", "experimental-webgl", "webgl" ];
var requestingWebGL = contextNames.indexOf(arguments[0]) != -1;
if (requestingWebGL) {
// Page is requesting a WebGL context!
// TODO: something
}
var result = originalGetContext.apply(this, arguments);
if (result == null) {
return null;
}
if (requestingWebGL) {
// TODO: pull options from somewhere?
result = gli.host.inspectContext(this, result);
var hostUI = new gli.host.HostUI(result);
result.hostUI = hostUI; // just so we can access it later for
// debugging
}
return result;
};
})();<|fim▁end|> | script.onload = function() {
if (!script.loadCalled) {
this.loadCalled = true; |
<|file_name|>example.go<|end_file_name|><|fim▁begin|>package main
import (
"bufio"
"bytes"
"github.com/mediocregopher/manatcp"
"log"
"time"
)
////////////////////////////////////////////////////////////////////////////////
// Client definition
type ExClient struct{}
func (_ ExClient) Read(buf *bufio.Reader) (interface{}, error, bool) {
l, err := buf.ReadBytes('\n')
if err != nil {
return nil, err, true
}
tl := bytes.TrimRight(l, "\n")
return tl, nil, false
}
func (_ ExClient) IsPush(li interface{}) bool {
l := li.([]byte)
return l[0] != '~'
}
func (_ ExClient) Write(buf *bufio.Writer, item interface{}) (error, bool) {
if _, err := buf.Write(item.([]byte)); err != nil {
return err, true
}
if _, err := buf.Write([]byte{'\n'}); err != nil {
return err, true
}
return nil, false
}
////////////////////////////////////////////////////////////////////////////////
// Server definition
type ExServer struct{}
func (_ ExServer) Connected(
lc *manatcp.ListenerConn) (manatcp.ServerClient, bool) {
log.Println("SERVER: new client")
go serverClientSpin(lc)
return &ExServerClient{}, false
}
type ExServerClient struct{}
func (_ ExServerClient) Read(buf *bufio.Reader) (interface{}, bool) {
l, err := buf.ReadBytes('\n')
if err != nil {
return nil, true
}
tl := bytes.TrimRight(l, "\n")
return tl, false
}
func (_ ExServerClient) Write(buf *bufio.Writer, item interface{}) bool {
if _, err := buf.Write(item.([]byte)); err != nil {
log.Println(err)
return true
}
if _, err := buf.Write([]byte{'\n'}); err != nil {
log.Println(err)
return true
}
return false
}
func (_ ExServerClient) HandleCmd(cmd interface{}) (interface{}, bool, bool) {
log.Printf("SERVER: received '%s' from the client", string(cmd.([]byte)))
cmdB := cmd.([]byte)
res := make([]byte, 1, len(cmdB)+1)
res[0] = '~'
res = append(res, cmdB...)
log.Printf("SERVER: sending back '%s'", string(res))
return res, true, false
}
func (_ ExServerClient) Closing() {
log.Println("SERVER: closing the client connection")
}
////////////////////////////////////////////////////////////////////////////////
// Behavior
func serverClientSpin(lc *manatcp.ListenerConn) {
tick := time.Tick(10 * time.Second)
for {
select {
case <-tick:
log.Println("SERVER: Pushing HI to the client")
lc.PushCh <- []byte("HI")
case <-lc.CloseCh:
return
}
}
}
func main() {
_, err := manatcp.Listen(ExServer{}, ":9000")
if err != nil {
log.Fatal(err)
}
for {
log.Println("CLIENT: connecting")
conn, err := manatcp.Dial(ExClient{}, "localhost:9000")
if err != nil {
log.Fatal(err)
}
forloop:
for {
select {
case <-time.After(5 * time.Second):
log.Println("CLIENT: Sending command OHAI")
res, err, dead := conn.Cmd([]byte("OHAI"))
log.Printf("CLIENT: Got back: '%s', %v, %v", string(res.([]byte)), err, dead)
case push, ok := <-conn.PushCh:
if !ok {
log.Println("CLIENT: PushCh closed")
break forloop
}<|fim▁hole|> log.Println("CLIENT: closing")
conn.Close()
}
}<|fim▁end|> | log.Printf("CLIENT: Got push: '%s'", string(push.([]byte)))
}
} |
<|file_name|>lint-group-plugin.rs<|end_file_name|><|fim▁begin|>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at<|fim▁hole|>// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// aux-build:lint_group_plugin_test.rs
// ignore-stage1
// ignore-pretty
#![feature(plugin)]
#![plugin(lint_group_plugin_test)]
fn lintme() { } //~ WARNING item is named 'lintme'
fn pleaselintme() { } //~ WARNING item is named 'pleaselintme'
#[allow(lint_me)]
pub fn main() {
fn lintme() { }
fn pleaselintme() { }
}<|fim▁end|> | // http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or |
<|file_name|>NumberOfDiscIntersections_test.go<|end_file_name|><|fim▁begin|>package sorting
import (
. "gopkg.in/check.v1"
)
var _ = Suite(&MySuite{})
func (s *MySuite) TestNumberOfDiscIntersections(c *C) {<|fim▁hole|> for i := 0; i < c.N; i++ {
NumberOfDiscIntersections([]int{1, 5, 2, 1, 4, 0})
}
}<|fim▁end|> | c.Assert(NumberOfDiscIntersections([]int{1, 5, 2, 1, 4, 0}), Equals, 11)
}
func (s *MySuite) BenchmarkNumberOfDiscIntersections(c *C) { |
<|file_name|>pod.go<|end_file_name|><|fim▁begin|>/*
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package internalversion
import (
api "k8s.io/kubernetes/pkg/api"
restclient "k8s.io/kubernetes/pkg/client/restclient"
watch "k8s.io/kubernetes/pkg/watch"
)
// PodsGetter has a method to return a PodInterface.
// A group's client should implement this interface.
type PodsGetter interface {
Pods(namespace string) PodInterface
}
// PodInterface has methods to work with Pod resources.
type PodInterface interface {
Create(*api.Pod) (*api.Pod, error)
Update(*api.Pod) (*api.Pod, error)
UpdateStatus(*api.Pod) (*api.Pod, error)
Delete(name string, options *api.DeleteOptions) error
DeleteCollection(options *api.DeleteOptions, listOptions api.ListOptions) error
Get(name string) (*api.Pod, error)
List(opts api.ListOptions) (*api.PodList, error)
Watch(opts api.ListOptions) (watch.Interface, error)
Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *api.Pod, err error)
PodExpansion
}
// pods implements PodInterface
type pods struct {
client restclient.Interface
ns string
}
// newPods returns a Pods
func newPods(c *CoreClient, namespace string) *pods {
return &pods{
client: c.RESTClient(),
ns: namespace,
}
}
// Create takes the representation of a pod and creates it. Returns the server's representation of the pod, and an error, if there is any.
func (c *pods) Create(pod *api.Pod) (result *api.Pod, err error) {
result = &api.Pod{}
err = c.client.Post().
Namespace(c.ns).
Resource("pods").
Body(pod).
Do().
Into(result)
return
}
// Update takes the representation of a pod and updates it. Returns the server's representation of the pod, and an error, if there is any.
func (c *pods) Update(pod *api.Pod) (result *api.Pod, err error) {
result = &api.Pod{}
err = c.client.Put().
Namespace(c.ns).
Resource("pods").
Name(pod.Name).
Body(pod).
Do().
Into(result)
return
}
func (c *pods) UpdateStatus(pod *api.Pod) (result *api.Pod, err error) {
result = &api.Pod{}
err = c.client.Put().
Namespace(c.ns).
Resource("pods").
Name(pod.Name).
SubResource("status").
Body(pod).
Do().
Into(result)
return
}
// Delete takes name of the pod and deletes it. Returns an error if one occurs.
func (c *pods) Delete(name string, options *api.DeleteOptions) error {
return c.client.Delete().
Namespace(c.ns).
Resource("pods").
Name(name).
Body(options).
Do().<|fim▁hole|>func (c *pods) DeleteCollection(options *api.DeleteOptions, listOptions api.ListOptions) error {
return c.client.Delete().
Namespace(c.ns).
Resource("pods").
VersionedParams(&listOptions, api.ParameterCodec).
Body(options).
Do().
Error()
}
// Get takes name of the pod, and returns the corresponding pod object, and an error if there is any.
func (c *pods) Get(name string) (result *api.Pod, err error) {
result = &api.Pod{}
err = c.client.Get().
Namespace(c.ns).
Resource("pods").
Name(name).
Do().
Into(result)
return
}
// List takes label and field selectors, and returns the list of Pods that match those selectors.
func (c *pods) List(opts api.ListOptions) (result *api.PodList, err error) {
result = &api.PodList{}
err = c.client.Get().
Namespace(c.ns).
Resource("pods").
VersionedParams(&opts, api.ParameterCodec).
Do().
Into(result)
return
}
// Watch returns a watch.Interface that watches the requested pods.
func (c *pods) Watch(opts api.ListOptions) (watch.Interface, error) {
return c.client.Get().
Prefix("watch").
Namespace(c.ns).
Resource("pods").
VersionedParams(&opts, api.ParameterCodec).
Watch()
}
// Patch applies the patch and returns the patched pod.
func (c *pods) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *api.Pod, err error) {
result = &api.Pod{}
err = c.client.Patch(pt).
Namespace(c.ns).
Resource("pods").
SubResource(subresources...).
Name(name).
Body(data).
Do().
Into(result)
return
}<|fim▁end|> | Error()
}
// DeleteCollection deletes a collection of objects. |
<|file_name|>wf-outlives-ty-in-fn-or-trait.rs<|end_file_name|><|fim▁begin|>#![feature(rustc_attrs)]
#![allow(dead_code)]
trait Trait<'a, T> {
type Out;
}
impl<'a, T> Trait<'a, T> for usize {
type Out = &'a fn(T); //~ ERROR `T` may not live long enough
}
struct Foo<'a,T> {
f: &'a fn(T),<|fim▁hole|>
trait Baz<T> { }
impl<'a, T> Trait<'a, T> for u32 {
type Out = &'a dyn Baz<T>; //~ ERROR `T` may not live long enough
}
fn main() { }<|fim▁end|> | } |
<|file_name|>test_std.rs<|end_file_name|><|fim▁begin|>use permutohedron;
use itertools as it;
use crate::it::Itertools;
use crate::it::multizip;
use crate::it::multipeek;
use crate::it::free::rciter;
use crate::it::free::put_back_n;
use crate::it::FoldWhile;
use crate::it::cloned;
use crate::it::iproduct;
use crate::it::izip;
#[test]
fn product3() {
let prod = iproduct!(0..3, 0..2, 0..2);
assert_eq!(prod.size_hint(), (12, Some(12)));
let v = prod.collect_vec();
for i in 0..3 {
for j in 0..2 {
for k in 0..2 {
assert!((i, j, k) == v[(i * 2 * 2 + j * 2 + k) as usize]);
}
}
}
for (_, _, _, _) in iproduct!(0..3, 0..2, 0..2, 0..3) {
/* test compiles */
}
}
#[test]
fn interleave_shortest() {
let v0: Vec<i32> = vec![0, 2, 4];
let v1: Vec<i32> = vec![1, 3, 5, 7];
let it = v0.into_iter().interleave_shortest(v1.into_iter());
assert_eq!(it.size_hint(), (6, Some(6)));
assert_eq!(it.collect_vec(), vec![0, 1, 2, 3, 4, 5]);
let v0: Vec<i32> = vec![0, 2, 4, 6, 8];
let v1: Vec<i32> = vec![1, 3, 5];
let it = v0.into_iter().interleave_shortest(v1.into_iter());
assert_eq!(it.size_hint(), (7, Some(7)));
assert_eq!(it.collect_vec(), vec![0, 1, 2, 3, 4, 5, 6]);
let i0 = ::std::iter::repeat(0);
let v1: Vec<_> = vec![1, 3, 5];
let it = i0.interleave_shortest(v1.into_iter());
assert_eq!(it.size_hint(), (7, Some(7)));
let v0: Vec<_> = vec![0, 2, 4];
let i1 = ::std::iter::repeat(1);
let it = v0.into_iter().interleave_shortest(i1);
assert_eq!(it.size_hint(), (6, Some(6)));
}
#[test]
fn unique_by() {
let xs = ["aaa", "bbbbb", "aa", "ccc", "bbbb", "aaaaa", "cccc"];
let ys = ["aaa", "bbbbb", "ccc"];
it::assert_equal(ys.iter(), xs.iter().unique_by(|x| x[..2].to_string()));
}
#[test]
fn unique() {
let xs = [0, 1, 2, 3, 2, 1, 3];
let ys = [0, 1, 2, 3];
it::assert_equal(ys.iter(), xs.iter().unique());
let xs = [0, 1];
let ys = [0, 1];
it::assert_equal(ys.iter(), xs.iter().unique());
}
#[test]<|fim▁hole|> let text: String = v.concat();
assert_eq!(text, "a, , b, c".to_string());
let ys = [0, 1, 2, 3];
let mut it = ys[..0].iter().map(|x| *x).intersperse(1);
assert!(it.next() == None);
}
#[test]
fn dedup() {
let xs = [0, 1, 1, 1, 2, 1, 3, 3];
let ys = [0, 1, 2, 1, 3];
it::assert_equal(ys.iter(), xs.iter().dedup());
let xs = [0, 0, 0, 0, 0];
let ys = [0];
it::assert_equal(ys.iter(), xs.iter().dedup());
let xs = [0, 1, 1, 1, 2, 1, 3, 3];
let ys = [0, 1, 2, 1, 3];
let mut xs_d = Vec::new();
xs.iter().dedup().fold((), |(), &elt| xs_d.push(elt));
assert_eq!(&xs_d, &ys);
}
#[test]
fn dedup_by() {
let xs = [(0, 0), (0, 1), (1, 1), (2, 1), (0, 2), (3, 1), (0, 3), (1, 3)];
let ys = [(0, 0), (0, 1), (0, 2), (3, 1), (0, 3)];
it::assert_equal(ys.iter(), xs.iter().dedup_by(|x, y| x.1==y.1));
let xs = [(0, 1), (0, 2), (0, 3), (0, 4), (0, 5)];
let ys = [(0, 1)];
it::assert_equal(ys.iter(), xs.iter().dedup_by(|x, y| x.0==y.0));
let xs = [(0, 0), (0, 1), (1, 1), (2, 1), (0, 2), (3, 1), (0, 3), (1, 3)];
let ys = [(0, 0), (0, 1), (0, 2), (3, 1), (0, 3)];
let mut xs_d = Vec::new();
xs.iter().dedup_by(|x, y| x.1==y.1).fold((), |(), &elt| xs_d.push(elt));
assert_eq!(&xs_d, &ys);
}
#[test]
fn all_equal() {
assert!("".chars().all_equal());
assert!("A".chars().all_equal());
assert!(!"AABBCCC".chars().all_equal());
assert!("AAAAAAA".chars().all_equal());
for (_key, mut sub) in &"AABBCCC".chars().group_by(|&x| x) {
assert!(sub.all_equal());
}
}
#[test]
fn test_put_back_n() {
let xs = [0, 1, 1, 1, 2, 1, 3, 3];
let mut pb = put_back_n(xs.iter().cloned());
pb.next();
pb.next();
pb.put_back(1);
pb.put_back(0);
it::assert_equal(pb, xs.iter().cloned());
}
#[test]
fn tee() {
let xs = [0, 1, 2, 3];
let (mut t1, mut t2) = xs.iter().cloned().tee();
assert_eq!(t1.next(), Some(0));
assert_eq!(t2.next(), Some(0));
assert_eq!(t1.next(), Some(1));
assert_eq!(t1.next(), Some(2));
assert_eq!(t1.next(), Some(3));
assert_eq!(t1.next(), None);
assert_eq!(t2.next(), Some(1));
assert_eq!(t2.next(), Some(2));
assert_eq!(t1.next(), None);
assert_eq!(t2.next(), Some(3));
assert_eq!(t2.next(), None);
assert_eq!(t1.next(), None);
assert_eq!(t2.next(), None);
let (t1, t2) = xs.iter().cloned().tee();
it::assert_equal(t1, xs.iter().cloned());
it::assert_equal(t2, xs.iter().cloned());
let (t1, t2) = xs.iter().cloned().tee();
it::assert_equal(t1.zip(t2), xs.iter().cloned().zip(xs.iter().cloned()));
}
#[test]
fn test_rciter() {
let xs = [0, 1, 1, 1, 2, 1, 3, 5, 6];
let mut r1 = rciter(xs.iter().cloned());
let mut r2 = r1.clone();
assert_eq!(r1.next(), Some(0));
assert_eq!(r2.next(), Some(1));
let mut z = r1.zip(r2);
assert_eq!(z.next(), Some((1, 1)));
assert_eq!(z.next(), Some((2, 1)));
assert_eq!(z.next(), Some((3, 5)));
assert_eq!(z.next(), None);
// test intoiterator
let r1 = rciter(0..5);
let mut z = izip!(&r1, r1);
assert_eq!(z.next(), Some((0, 1)));
}
#[allow(deprecated)]
#[test]
fn trait_pointers() {
struct ByRef<'r, I: ?Sized>(&'r mut I) ;
impl<'r, X, I: ?Sized> Iterator for ByRef<'r, I> where
I: 'r + Iterator<Item=X>
{
type Item = X;
fn next(&mut self) -> Option<X>
{
self.0.next()
}
}
let mut it = Box::new(0..10) as Box<dyn Iterator<Item=i32>>;
assert_eq!(it.next(), Some(0));
{
/* make sure foreach works on non-Sized */
let jt: &mut dyn Iterator<Item = i32> = &mut *it;
assert_eq!(jt.next(), Some(1));
{
let mut r = ByRef(jt);
assert_eq!(r.next(), Some(2));
}
assert_eq!(jt.find_position(|x| *x == 4), Some((1, 4)));
jt.foreach(|_| ());
}
}
#[test]
fn merge_by() {
let odd : Vec<(u32, &str)> = vec![(1, "hello"), (3, "world"), (5, "!")];
let even = vec![(2, "foo"), (4, "bar"), (6, "baz")];
let expected = vec![(1, "hello"), (2, "foo"), (3, "world"), (4, "bar"), (5, "!"), (6, "baz")];
let results = odd.iter().merge_by(even.iter(), |a, b| a.0 <= b.0);
it::assert_equal(results, expected.iter());
}
#[test]
fn merge_by_btree() {
use std::collections::BTreeMap;
let mut bt1 = BTreeMap::new();
bt1.insert("hello", 1);
bt1.insert("world", 3);
let mut bt2 = BTreeMap::new();
bt2.insert("foo", 2);
bt2.insert("bar", 4);
let results = bt1.into_iter().merge_by(bt2.into_iter(), |a, b| a.0 <= b.0 );
let expected = vec![("bar", 4), ("foo", 2), ("hello", 1), ("world", 3)];
it::assert_equal(results, expected.into_iter());
}
#[allow(deprecated)]
#[test]
fn kmerge() {
let its = (0..4).map(|s| (s..10).step(4));
it::assert_equal(its.kmerge(), 0..10);
}
#[allow(deprecated)]
#[test]
fn kmerge_2() {
let its = vec![3, 2, 1, 0].into_iter().map(|s| (s..10).step(4));
it::assert_equal(its.kmerge(), 0..10);
}
#[test]
fn kmerge_empty() {
let its = (0..4).map(|_| 0..0);
assert_eq!(its.kmerge().next(), None);
}
#[test]
fn kmerge_size_hint() {
let its = (0..5).map(|_| (0..10));
assert_eq!(its.kmerge().size_hint(), (50, Some(50)));
}
#[test]
fn kmerge_empty_size_hint() {
let its = (0..5).map(|_| (0..0));
assert_eq!(its.kmerge().size_hint(), (0, Some(0)));
}
#[test]
fn join() {
let many = [1, 2, 3];
let one = [1];
let none: Vec<i32> = vec![];
assert_eq!(many.iter().join(", "), "1, 2, 3");
assert_eq!( one.iter().join(", "), "1");
assert_eq!(none.iter().join(", "), "");
}
#[test]
fn sorted_by() {
let sc = [3, 4, 1, 2].iter().cloned().sorted_by(|&a, &b| {
a.cmp(&b)
});
it::assert_equal(sc, vec![1, 2, 3, 4]);
let v = (0..5).sorted_by(|&a, &b| a.cmp(&b).reverse());
it::assert_equal(v, vec![4, 3, 2, 1, 0]);
}
#[test]
fn sorted_by_key() {
let sc = [3, 4, 1, 2].iter().cloned().sorted_by_key(|&x| x);
it::assert_equal(sc, vec![1, 2, 3, 4]);
let v = (0..5).sorted_by_key(|&x| -x);
it::assert_equal(v, vec![4, 3, 2, 1, 0]);
}
#[test]
fn test_multipeek() {
let nums = vec![1u8,2,3,4,5];
let mp = multipeek(nums.iter().map(|&x| x));
assert_eq!(nums, mp.collect::<Vec<_>>());
let mut mp = multipeek(nums.iter().map(|&x| x));
assert_eq!(mp.peek(), Some(&1));
assert_eq!(mp.next(), Some(1));
assert_eq!(mp.peek(), Some(&2));
assert_eq!(mp.peek(), Some(&3));
assert_eq!(mp.next(), Some(2));
assert_eq!(mp.peek(), Some(&3));
assert_eq!(mp.peek(), Some(&4));
assert_eq!(mp.peek(), Some(&5));
assert_eq!(mp.peek(), None);
assert_eq!(mp.next(), Some(3));
assert_eq!(mp.next(), Some(4));
assert_eq!(mp.peek(), Some(&5));
assert_eq!(mp.peek(), None);
assert_eq!(mp.next(), Some(5));
assert_eq!(mp.next(), None);
assert_eq!(mp.peek(), None);
}
#[test]
fn test_multipeek_reset() {
let data = [1, 2, 3, 4];
let mut mp = multipeek(cloned(&data));
assert_eq!(mp.peek(), Some(&1));
assert_eq!(mp.next(), Some(1));
assert_eq!(mp.peek(), Some(&2));
assert_eq!(mp.peek(), Some(&3));
mp.reset_peek();
assert_eq!(mp.peek(), Some(&2));
assert_eq!(mp.next(), Some(2));
}
#[test]
fn test_multipeek_peeking_next() {
use crate::it::PeekingNext;
let nums = vec![1u8,2,3,4,5,6,7];
let mut mp = multipeek(nums.iter().map(|&x| x));
assert_eq!(mp.peeking_next(|&x| x != 0), Some(1));
assert_eq!(mp.next(), Some(2));
assert_eq!(mp.peek(), Some(&3));
assert_eq!(mp.peek(), Some(&4));
assert_eq!(mp.peeking_next(|&x| x == 3), Some(3));
assert_eq!(mp.peek(), Some(&4));
assert_eq!(mp.peeking_next(|&x| x != 4), None);
assert_eq!(mp.peeking_next(|&x| x == 4), Some(4));
assert_eq!(mp.peek(), Some(&5));
assert_eq!(mp.peek(), Some(&6));
assert_eq!(mp.peeking_next(|&x| x != 5), None);
assert_eq!(mp.peek(), Some(&7));
assert_eq!(mp.peeking_next(|&x| x == 5), Some(5));
assert_eq!(mp.peeking_next(|&x| x == 6), Some(6));
assert_eq!(mp.peek(), Some(&7));
assert_eq!(mp.peek(), None);
assert_eq!(mp.next(), Some(7));
assert_eq!(mp.peek(), None);
}
#[test]
fn pad_using() {
it::assert_equal((0..0).pad_using(1, |_| 1), 1..2);
let v: Vec<usize> = vec![0, 1, 2];
let r = v.into_iter().pad_using(5, |n| n);
it::assert_equal(r, vec![0, 1, 2, 3, 4]);
let v: Vec<usize> = vec![0, 1, 2];
let r = v.into_iter().pad_using(1, |_| panic!());
it::assert_equal(r, vec![0, 1, 2]);
}
#[test]
fn group_by() {
for (ch1, sub) in &"AABBCCC".chars().group_by(|&x| x) {
for ch2 in sub {
assert_eq!(ch1, ch2);
}
}
for (ch1, sub) in &"AAABBBCCCCDDDD".chars().group_by(|&x| x) {
for ch2 in sub {
assert_eq!(ch1, ch2);
if ch1 == 'C' {
break;
}
}
}
let toupper = |ch: &char| ch.to_uppercase().nth(0).unwrap();
// try all possible orderings
for indices in permutohedron::Heap::new(&mut [0, 1, 2, 3]) {
let groups = "AaaBbbccCcDDDD".chars().group_by(&toupper);
let mut subs = groups.into_iter().collect_vec();
for &idx in &indices[..] {
let (key, text) = match idx {
0 => ('A', "Aaa".chars()),
1 => ('B', "Bbb".chars()),
2 => ('C', "ccCc".chars()),
3 => ('D', "DDDD".chars()),
_ => unreachable!(),
};
assert_eq!(key, subs[idx].0);
it::assert_equal(&mut subs[idx].1, text);
}
}
let groups = "AAABBBCCCCDDDD".chars().group_by(|&x| x);
let mut subs = groups.into_iter().map(|(_, g)| g).collect_vec();
let sd = subs.pop().unwrap();
let sc = subs.pop().unwrap();
let sb = subs.pop().unwrap();
let sa = subs.pop().unwrap();
for (a, b, c, d) in multizip((sa, sb, sc, sd)) {
assert_eq!(a, 'A');
assert_eq!(b, 'B');
assert_eq!(c, 'C');
assert_eq!(d, 'D');
}
// check that the key closure is called exactly n times
{
let mut ntimes = 0;
let text = "AABCCC";
for (_, sub) in &text.chars().group_by(|&x| { ntimes += 1; x}) {
for _ in sub {
}
}
assert_eq!(ntimes, text.len());
}
{
let mut ntimes = 0;
let text = "AABCCC";
for _ in &text.chars().group_by(|&x| { ntimes += 1; x}) {
}
assert_eq!(ntimes, text.len());
}
{
let text = "ABCCCDEEFGHIJJKK";
let gr = text.chars().group_by(|&x| x);
it::assert_equal(gr.into_iter().flat_map(|(_, sub)| sub), text.chars());
}
}
#[test]
fn group_by_lazy_2() {
let data = vec![0, 1];
let groups = data.iter().group_by(|k| *k);
let gs = groups.into_iter().collect_vec();
it::assert_equal(data.iter(), gs.into_iter().flat_map(|(_k, g)| g));
let data = vec![0, 1, 1, 0, 0];
let groups = data.iter().group_by(|k| *k);
let mut gs = groups.into_iter().collect_vec();
gs[1..].reverse();
it::assert_equal(&[0, 0, 0, 1, 1], gs.into_iter().flat_map(|(_, g)| g));
let grouper = data.iter().group_by(|k| *k);
let mut groups = Vec::new();
for (k, group) in &grouper {
if *k == 1 {
groups.push(group);
}
}
it::assert_equal(&mut groups[0], &[1, 1]);
let data = vec![0, 0, 0, 1, 1, 0, 0, 2, 2, 3, 3];
let grouper = data.iter().group_by(|k| *k);
let mut groups = Vec::new();
for (i, (_, group)) in grouper.into_iter().enumerate() {
if i < 2 {
groups.push(group);
} else if i < 4 {
for _ in group {
}
} else {
groups.push(group);
}
}
it::assert_equal(&mut groups[0], &[0, 0, 0]);
it::assert_equal(&mut groups[1], &[1, 1]);
it::assert_equal(&mut groups[2], &[3, 3]);
// use groups as chunks
let data = vec![0, 0, 0, 1, 1, 0, 0, 2, 2, 3, 3];
let mut i = 0;
let grouper = data.iter().group_by(move |_| { let k = i / 3; i += 1; k });
for (i, group) in &grouper {
match i {
0 => it::assert_equal(group, &[0, 0, 0]),
1 => it::assert_equal(group, &[1, 1, 0]),
2 => it::assert_equal(group, &[0, 2, 2]),
3 => it::assert_equal(group, &[3, 3]),
_ => unreachable!(),
}
}
}
#[test]
fn group_by_lazy_3() {
// test consuming each group on the lap after it was produced
let data = vec![0, 0, 0, 1, 1, 0, 0, 1, 1, 2, 2];
let grouper = data.iter().group_by(|elt| *elt);
let mut last = None;
for (key, group) in &grouper {
if let Some(gr) = last.take() {
for elt in gr {
assert!(elt != key && i32::abs(elt - key) == 1);
}
}
last = Some(group);
}
}
#[test]
fn chunks() {
let data = vec![0, 0, 0, 1, 1, 0, 0, 2, 2, 3, 3];
let grouper = data.iter().chunks(3);
for (i, chunk) in grouper.into_iter().enumerate() {
match i {
0 => it::assert_equal(chunk, &[0, 0, 0]),
1 => it::assert_equal(chunk, &[1, 1, 0]),
2 => it::assert_equal(chunk, &[0, 2, 2]),
3 => it::assert_equal(chunk, &[3, 3]),
_ => unreachable!(),
}
}
}
#[test]
fn concat_empty() {
let data: Vec<Vec<()>> = Vec::new();
assert_eq!(data.into_iter().concat(), Vec::new())
}
#[test]
fn concat_non_empty() {
let data = vec![vec![1,2,3], vec![4,5,6], vec![7,8,9]];
assert_eq!(data.into_iter().concat(), vec![1,2,3,4,5,6,7,8,9])
}
#[test]
fn combinations() {
assert!((1..3).combinations(5).next().is_none());
let it = (1..3).combinations(2);
it::assert_equal(it, vec![
vec![1, 2],
]);
let it = (1..5).combinations(2);
it::assert_equal(it, vec![
vec![1, 2],
vec![1, 3],
vec![1, 4],
vec![2, 3],
vec![2, 4],
vec![3, 4],
]);
it::assert_equal((0..0).tuple_combinations::<(_, _)>(), <Vec<_>>::new());
it::assert_equal((0..1).tuple_combinations::<(_, _)>(), <Vec<_>>::new());
it::assert_equal((0..2).tuple_combinations::<(_, _)>(), vec![(0, 1)]);
it::assert_equal((0..0).combinations(2), <Vec<Vec<_>>>::new());
it::assert_equal((0..1).combinations(1), vec![vec![0]]);
it::assert_equal((0..2).combinations(1), vec![vec![0], vec![1]]);
it::assert_equal((0..2).combinations(2), vec![vec![0, 1]]);
}
#[test]
fn combinations_of_too_short() {
for i in 1..10 {
assert!((0..0).combinations(i).next().is_none());
assert!((0..i - 1).combinations(i).next().is_none());
}
}
#[test]
fn combinations_zero() {
it::assert_equal((1..3).combinations(0), vec![vec![]]);
it::assert_equal((0..0).combinations(0), vec![vec![]]);
}
#[test]
fn permutations_zero() {
it::assert_equal((1..3).permutations(0), vec![vec![]]);
it::assert_equal((0..0).permutations(0), vec![vec![]]);
}
#[test]
fn combinations_with_replacement() {
// Pool smaller than n
it::assert_equal((0..1).combinations_with_replacement(2), vec![vec![0, 0]]);
// Pool larger than n
it::assert_equal(
(0..3).combinations_with_replacement(2),
vec![
vec![0, 0],
vec![0, 1],
vec![0, 2],
vec![1, 1],
vec![1, 2],
vec![2, 2],
],
);
// Zero size
it::assert_equal(
(0..3).combinations_with_replacement(0),
vec![vec![]],
);
// Zero size on empty pool
it::assert_equal(
(0..0).combinations_with_replacement(0),
vec![vec![]],
);
// Empty pool
it::assert_equal(
(0..0).combinations_with_replacement(2),
<Vec<Vec<_>>>::new(),
);
}
#[test]
fn diff_mismatch() {
let a = vec![1, 2, 3, 4];
let b = vec![1.0, 5.0, 3.0, 4.0];
let b_map = b.into_iter().map(|f| f as i32);
let diff = it::diff_with(a.iter(), b_map, |a, b| *a == b);
assert!(match diff {
Some(it::Diff::FirstMismatch(1, _, from_diff)) =>
from_diff.collect::<Vec<_>>() == vec![5, 3, 4],
_ => false,
});
}
#[test]
fn diff_longer() {
let a = vec![1, 2, 3, 4];
let b = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0];
let b_map = b.into_iter().map(|f| f as i32);
let diff = it::diff_with(a.iter(), b_map, |a, b| *a == b);
assert!(match diff {
Some(it::Diff::Longer(_, remaining)) =>
remaining.collect::<Vec<_>>() == vec![5, 6],
_ => false,
});
}
#[test]
fn diff_shorter() {
let a = vec![1, 2, 3, 4];
let b = vec![1.0, 2.0];
let b_map = b.into_iter().map(|f| f as i32);
let diff = it::diff_with(a.iter(), b_map, |a, b| *a == b);
assert!(match diff {
Some(it::Diff::Shorter(len, _)) => len == 2,
_ => false,
});
}
#[test]
fn minmax() {
use std::cmp::Ordering;
use crate::it::MinMaxResult;
// A peculiar type: Equality compares both tuple items, but ordering only the
// first item. This is so we can check the stability property easily.
#[derive(Clone, Debug, PartialEq, Eq)]
struct Val(u32, u32);
impl PartialOrd<Val> for Val {
fn partial_cmp(&self, other: &Val) -> Option<Ordering> {
self.0.partial_cmp(&other.0)
}
}
impl Ord for Val {
fn cmp(&self, other: &Val) -> Ordering {
self.0.cmp(&other.0)
}
}
assert_eq!(None::<Option<u32>>.iter().minmax(), MinMaxResult::NoElements);
assert_eq!(Some(1u32).iter().minmax(), MinMaxResult::OneElement(&1));
let data = vec![Val(0, 1), Val(2, 0), Val(0, 2), Val(1, 0), Val(2, 1)];
let minmax = data.iter().minmax();
assert_eq!(minmax, MinMaxResult::MinMax(&Val(0, 1), &Val(2, 1)));
let (min, max) = data.iter().minmax_by_key(|v| v.1).into_option().unwrap();
assert_eq!(min, &Val(2, 0));
assert_eq!(max, &Val(0, 2));
let (min, max) = data.iter().minmax_by(|x, y| x.1.cmp(&y.1)).into_option().unwrap();
assert_eq!(min, &Val(2, 0));
assert_eq!(max, &Val(0, 2));
}
#[test]
fn format() {
let data = [0, 1, 2, 3];
let ans1 = "0, 1, 2, 3";
let ans2 = "0--1--2--3";
let t1 = format!("{}", data.iter().format(", "));
assert_eq!(t1, ans1);
let t2 = format!("{:?}", data.iter().format("--"));
assert_eq!(t2, ans2);
let dataf = [1.1, 2.71828, -22.];
let t3 = format!("{:.2e}", dataf.iter().format(", "));
assert_eq!(t3, "1.10e0, 2.72e0, -2.20e1");
}
#[test]
fn while_some() {
let ns = (1..10).map(|x| if x % 5 != 0 { Some(x) } else { None })
.while_some();
it::assert_equal(ns, vec![1, 2, 3, 4]);
}
#[allow(deprecated)]
#[test]
fn fold_while() {
let mut iterations = 0;
let vec = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let sum = vec.into_iter().fold_while(0, |acc, item| {
iterations += 1;
let new_sum = acc.clone() + item;
if new_sum <= 20 {
FoldWhile::Continue(new_sum)
} else {
FoldWhile::Done(acc)
}
}).into_inner();
assert_eq!(iterations, 6);
assert_eq!(sum, 15);
}
#[test]
fn tree_fold1() {
let x = [
"",
"0",
"0 1 x",
"0 1 x 2 x",
"0 1 x 2 3 x x",
"0 1 x 2 3 x x 4 x",
"0 1 x 2 3 x x 4 5 x x",
"0 1 x 2 3 x x 4 5 x 6 x x",
"0 1 x 2 3 x x 4 5 x 6 7 x x x",
"0 1 x 2 3 x x 4 5 x 6 7 x x x 8 x",
"0 1 x 2 3 x x 4 5 x 6 7 x x x 8 9 x x",
"0 1 x 2 3 x x 4 5 x 6 7 x x x 8 9 x 10 x x",
"0 1 x 2 3 x x 4 5 x 6 7 x x x 8 9 x 10 11 x x x",
"0 1 x 2 3 x x 4 5 x 6 7 x x x 8 9 x 10 11 x x 12 x x",
"0 1 x 2 3 x x 4 5 x 6 7 x x x 8 9 x 10 11 x x 12 13 x x x",
"0 1 x 2 3 x x 4 5 x 6 7 x x x 8 9 x 10 11 x x 12 13 x 14 x x x",
"0 1 x 2 3 x x 4 5 x 6 7 x x x 8 9 x 10 11 x x 12 13 x 14 15 x x x x",
];
for (i, &s) in x.iter().enumerate() {
let expected = if s == "" { None } else { Some(s.to_string()) };
let num_strings = (0..i).map(|x| x.to_string());
let actual = num_strings.tree_fold1(|a, b| format!("{} {} x", a, b));
assert_eq!(actual, expected);
}
}<|fim▁end|> | fn intersperse() {
let xs = ["a", "", "b", "c"];
let v: Vec<&str> = xs.iter().map(|x| x.clone()).intersperse(", ").collect(); |
<|file_name|>event_tests.py<|end_file_name|><|fim▁begin|>import csv
import unittest
from datetime import datetime, timedelta
from hackertracker import event
from hackertracker.database import Model, Session
from sqlalchemy import create_engine
class TestEvents(unittest.TestCase):
def setUp(self):
engine = create_engine('sqlite:///:memory:', echo=True)
Model.metadata.create_all(engine)
Session.configure(bind=engine)
event.Event.for_name("Drink glass of water", create=True)
def tearDown(self):
Session.remove()<|fim▁hole|> self.assertEqual(w1.replace(microsecond=0), w2.replace(microsecond=0))
def test_get_event(self):
e = event.Event.for_name("Drink pint of water", create=True)
self.assertEqual(e.name, "Drink pint of water")
e = event.Event.for_name("Drink pint of water")
self.assertEqual(e.name, "Drink pint of water")
self.assertRaises(event.EventNotFound, event.Event.for_name, "You'll never find me")
def test_basic_track(self):
e = event.Event.for_name("Drink glass of water")
o = e.track()
self.assertEqual(list(e.entries()), [o])
def test_events_persist(self):
e = event.Event.for_name("Drink glass of water")
o = e.track(attrs=dict(size="16", location="office"))
when = o.when
attrs = dict(o.attrs)
# Reload from db
Session.commit()
Session.remove()
e = event.Event.for_name("Drink glass of water")
o1 = e.entries()[0]
self.assertDatetimesEqual(when, o1.when)
self.assertEqual(attrs, o1.attrs)
def test_entry_count(self):
e = event.Event.for_name("Drink glass of water")
e.track()
e.track()
e.track()
Session.commit()
self.assertEqual(e.entry_count(), 3)
def test_latest_entry(self):
e = event.Event.for_name("Drink glass of water")
e.track(when=earlier(seconds=3))
e.track(when=earlier(seconds=2))
f = e.track(when=earlier(seconds=1))
Session.commit()
self.assertEqual(e.latest_entry().id, f.id)
def test_display_entry(self):
e = event.Event.for_name("Drink glass of water")
o = e.track(when=datetime(2014, 1, 1, 16, 6, 20, 216238))
self.assertEqual(str(o), "Jan 01, 2014 04:06PM")
o = e.track(when=datetime(2015, 3, 2, 0, 34, 53, 327128))
self.assertEqual(str(o), "Mar 02, 2015 12:34AM")
def test_list_events(self):
e1 = event.Event.for_name("Drink glass of water")
e2 = event.Event.for_name("Clean litter box", create=True)
self.assertEqual(event.Event.all(), [e2, e1])
def test_alternate_time(self):
e = event.Event.for_name("Drink glass of water")
o = e.track()
self.assertDatetimesEqual(o.when, datetime.utcnow())
when = earlier(hours=10)
o = e.track(when)
self.assertDatetimesEqual(o.when, when)
def test_attributes(self):
e = event.Event.for_name("Drink glass of water")
o = e.track(attrs=dict(size="16", location="office"))
self.assertEqual(o.attrs, {
"size": "16",
"location": "office"
})
def test_list_attributes(self):
e = event.Event.for_name("Drink glass of water")
e.track(attrs=dict(size="16", location="office"))
e.track(attrs=dict(hello="world"))
e.track(attrs=dict(hello="goodbye", location="office"))
event.Event.for_name("Fire ze missile", create=True).track(attrs=dict(le_tired="true"))
Session.commit()
self.assertEqual(e.attributes(), ["hello", "location", "size"])
def test_slug(self):
e = event.Event.for_name("Drink glass of water")
self.assertEqual(e.slug, "Drink_glass_of_water")
def test_exports_csv(self):
e = event.Event.for_name("Drink glass of water")
o = e.track(when=earlier(seconds=-1), attrs=dict(size="16", location="office"))
e.track(attrs=dict(hello="world", when="now"))
e.track(attrs=dict(hello="goodbye", location="office"))
Session.commit()
csv_file = list(csv.reader(e.export_csv().splitlines()))
self.assertEqual(csv_file[0], ["When", "hello", "location", "size", "when"])
self.assertEqual(csv_file[1], [str(o.when), "", "office", "16", ""])
self.assertEqual(len(csv_file), 4)
def earlier(**kwargs):
return datetime.utcnow() - timedelta(**kwargs)<|fim▁end|> |
def assertDatetimesEqual(self, w1, w2):
"Assert datetimes are equal to the second" |
<|file_name|>Rosenblatt_perceptron.py<|end_file_name|><|fim▁begin|>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
def plot_decision_regions(X, y, clf, res=0.02):
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, res),
np.arange(y_min, y_max, res))
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
plt.contourf(xx, yy, Z, alpha=0.4)
plt.scatter(X[:, 0], X[:, 1], c=y, alpha=0.8)
plt.xlim(xx.min(), xx.max())
plt.ylim(yy.min(), yy.max())
class Perceptron(object):
def __init__(self, eta=0.01, epochs=50):
self.eta = eta
self.epochs = epochs
def train(self, X, y):
self.w_ = np.zeros(1 + X.shape[1])
self.errors_ = []
for _ in range(self.epochs):
errors = 0
for xi, target in zip(X, y):
update = self.eta * (target - self.predict(xi))
self.w_[1:] += update * xi
self.w_[0] += update
errors += int(update != 0.0)
self.errors_.append(errors)
return self
def net_input(self, X):
return np.dot(X, self.w_[1:]) + self.w_[0]
def predict(self, X):
return np.where(self.net_input(X) >= 0.0, 1, -1)
# Корректные выходы перцептрона для данной выборки
y = np.array([[1],[1],[1],[1],[-1],[-1],[-1],[-1]]).reshape(8,1)
# Массив входных данных для перцептрона<|fim▁hole|>
ppn.train(X, y)
plot_decision_regions(X, y, clf=ppn)
plt.title('Perceptron')
plt.xlabel('X')
plt.ylabel('Y')
plt.show()
plt.plot(range(1, len(ppn.errors_)+1), ppn.errors_, marker='o')
plt.xlabel('Iterations')
plt.ylabel('Misclassifications')
plt.show()<|fim▁end|> | X = np.array([[0,3],[1,2],[2,2],[4,0],[-1,2],[2,0],[3,-1],[4,-1]]).reshape(8,2)
ppn = Perceptron(epochs=10, eta=0.1) |
<|file_name|>test_crafting.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3
# -*- coding: utf-8 -*-
# test_crafting.py
import os
import sys
import unittest
root_folder = os.path.abspath(os.path.dirname(os.path.abspath(__file__)) + os.sep + ".." )
pth = root_folder #+ os.sep + 'worldbuild'
sys.path.append(pth)
from worldbuild.crafting import craft as mod_craft
class TestTemplate(unittest.TestCase):<|fim▁hole|> def tearDown(self):
unittest.TestCase.tearDown(self)
def test_01_recipe(self):
res = mod_craft.Recipe('1', 'new recipe','20','mix')
#print(res)
self.assertEqual(str(res),'new recipe')
def test_02_dataset_recipe(self):
recipes = mod_craft.DataSet(mod_craft.Recipe, mod_craft.get_fullname('recipes.csv'))
self.assertTrue(len(recipes.object_list) > 18)
tot_time_to_build = 0
for recipe in recipes.object_list:
#print(recipe)
tot_time_to_build += int(recipe.base_time_to_build)
#print('total time to build all recipes = ' + str(tot_time_to_build))
self.assertEqual(str(recipes.object_list[0]), 'Torch')
self.assertEqual(str(recipes.object_list[1]), 'Wooden Plank')
self.assertTrue(tot_time_to_build > 10)
if __name__ == '__main__':
unittest.main()<|fim▁end|> | def setUp(self):
unittest.TestCase.setUp(self)
|
<|file_name|>excise.py<|end_file_name|><|fim▁begin|>def excise(conn, qrelname, tid):
with conn.cursor() as cur:
# Assume 'id' column exists and print that for bookkeeping.
#
# TODO: Instead should find unique constraints and print
# those, or try to print all attributes that are not corrupt.
sql = 'DELETE FROM {0} WHERE ctid = %s RETURNING id'.format(qrelname)
params = (tid,)
cur.execute(sql, params)<|fim▁hole|> if row:
return row[0]
return None<|fim▁end|> |
row = cur.fetchone() |
<|file_name|>lpeobject.cpp<|end_file_name|><|fim▁begin|>/*
* Copyright (C) Johan Engelen 2007-2008 <j.b.c.engelen@utwente.nl>
* Abhishek Sharma
*
* Released under GNU GPL, read the file 'COPYING' for more information
*/
#include "live_effects/lpeobject.h"
#include "live_effects/effect.h"
#include "xml/repr.h"
#include "xml/node-event-vector.h"
#include "sp-object.h"
#include "attributes.h"
#include "document.h"
#include "document-private.h"
#include <glibmm/i18n.h>
//#define LIVEPATHEFFECT_VERBOSE
static void livepatheffect_on_repr_attr_changed (Inkscape::XML::Node * repr, const gchar *key, const gchar *oldval, const gchar *newval, bool is_interactive, void * data);
static Inkscape::XML::NodeEventVector const livepatheffect_repr_events = {
NULL, /* child_added */
NULL, /* child_removed */
livepatheffect_on_repr_attr_changed,
NULL, /* content_changed */
NULL /* order_changed */
};
LivePathEffectObject::LivePathEffectObject()
: SPObject(), effecttype(Inkscape::LivePathEffect::INVALID_LPE), effecttype_set(false),
lpe(NULL)
{
#ifdef LIVEPATHEFFECT_VERBOSE
g_message("Init livepatheffectobject");
#endif
}
LivePathEffectObject::~LivePathEffectObject() {
}
/**
* Virtual build: set livepatheffect attributes from its associated XML node.
*/
void LivePathEffectObject::build(SPDocument *document, Inkscape::XML::Node *repr) {
g_assert(this != NULL);
g_assert(SP_IS_OBJECT(this));
SPObject::build(document, repr);
this->readAttr( "effect" );
if (repr) {
repr->addListener (&livepatheffect_repr_events, this);
}
/* Register ourselves, is this necessary? */
// document->addResource("path-effect", object);
}
/**
* Virtual release of livepatheffect members before destruction.
*/
void LivePathEffectObject::release() {
this->getRepr()->removeListenerByData(this);
/*
if (object->document) {
// Unregister ourselves
sp_document_removeResource(object->document, "livepatheffect", object);
}
if (gradient->ref) {
gradient->modified_connection.disconnect();
gradient->ref->detach();
delete gradient->ref;
gradient->ref = NULL;
}
gradient->modified_connection.~connection();
*/
if (this->lpe) {
delete this->lpe;
this->lpe = NULL;
}
this->effecttype = Inkscape::LivePathEffect::INVALID_LPE;
SPObject::release();
}
/**
* Virtual set: set attribute to value.
*/
void LivePathEffectObject::set(unsigned key, gchar const *value) {
#ifdef LIVEPATHEFFECT_VERBOSE
g_print("Set livepatheffect");
#endif
switch (key) {
case SP_PROP_PATH_EFFECT:
if (this->lpe) {
delete this->lpe;
this->lpe = NULL;
}
if ( value && Inkscape::LivePathEffect::LPETypeConverter.is_valid_key(value) ) {
this->effecttype = Inkscape::LivePathEffect::LPETypeConverter.get_id_from_key(value);
this->lpe = Inkscape::LivePathEffect::Effect::New(this->effecttype, this);
this->effecttype_set = true;
} else {
this->effecttype = Inkscape::LivePathEffect::INVALID_LPE;
this->effecttype_set = false;
}
this->requestModified(SP_OBJECT_MODIFIED_FLAG);
break;
}
SPObject::set(key, value);
}
/**
* Virtual write: write object attributes to repr.
*/
Inkscape::XML::Node* LivePathEffectObject::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) {
if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) {
repr = xml_doc->createElement("inkscape:path-effect");
}
if ((flags & SP_OBJECT_WRITE_ALL) || this->lpe) {
repr->setAttribute("effect", Inkscape::LivePathEffect::LPETypeConverter.get_key(this->effecttype).c_str());
this->lpe->writeParamsToSVG();
}
SPObject::write(xml_doc, repr, flags);
return repr;
}
static void
livepatheffect_on_repr_attr_changed ( Inkscape::XML::Node * /*repr*/,
const gchar *key,
const gchar */*oldval*/,
const gchar *newval,
bool /*is_interactive*/,
void * data )
{
#ifdef LIVEPATHEFFECT_VERBOSE
g_print("livepatheffect_on_repr_attr_changed");
#endif
if (!data)
return;
LivePathEffectObject *lpeobj = (LivePathEffectObject*) data;
if (!lpeobj->get_lpe())
return;
lpeobj->get_lpe()->setParameter(key, newval);
lpeobj->requestModified(SP_OBJECT_MODIFIED_FLAG);
}
/**
* If this has other users, create a new private duplicate and return it
* returns 'this' when no forking was necessary (and therefore no duplicate was made)
* Check out SPLPEItem::forkPathEffectsIfNecessary !
*/
LivePathEffectObject *LivePathEffectObject::fork_private_if_necessary(unsigned int nr_of_allowed_users)
{
if (hrefcount > nr_of_allowed_users) {
SPDocument *doc = this->document;
Inkscape::XML::Document *xml_doc = doc->getReprDoc();
Inkscape::XML::Node *dup_repr = this->getRepr()->duplicate(xml_doc);
doc->getDefs()->getRepr()->addChild(dup_repr, NULL);
LivePathEffectObject *lpeobj_new = LIVEPATHEFFECT( doc->getObjectByRepr(dup_repr) );
Inkscape::GC::release(dup_repr);
return lpeobj_new;
}
return this;
}
<|fim▁hole|> c-file-style:"stroustrup"
c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
indent-tabs-mode:nil
fill-column:99
End:
*/
// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :<|fim▁end|> | /*
Local Variables:
mode:c++ |
<|file_name|>rechteck.py<|end_file_name|><|fim▁begin|>import numpy as np
import uncertainties.unumpy as unp
from uncertainties.unumpy import (nominal_values as noms, std_devs as stds)
import matplotlib.pyplot as plt
import matplotlib as mpl
from scipy.optimize import curve_fit
plt.rcParams['figure.figsize'] = (12, 8)
plt.rcParams['font.size'] = 13
plt.rcParams['lines.linewidth'] = 1
csfont = {'fontname': 'Times New Roman'}
# U_mess = b_n
n, b_n = np.genfromtxt('rechteck.txt', unpack=True, skip_header=2)
x = np.log(n)
y = np.log(b_n)
def f(x, a, b):
return a * x + b
params, covariance = curve_fit(f, x, y)
errors = np.sqrt(np.diag(covariance))
print('a =', params[0], '+-', errors[0])
print('b =', params[1], '+-', errors[1])
# a =-1.19204784746 +- 0.0898910034039
# b = 0.326461420388 +- 0.123423011824
# mit ungeraden Oberwellen:
# a = -0.909247906044 +- 0.0770070259187
# b = 0.409244475522 +- 0.144772240047
x_plot = np.linspace(min(x), max(x))
plt.plot(x_plot, f(x_plot, *params), 'b-', label='linearer Fit')
plt.plot(x, y, 'rx', label='Messwerte')
plt.ylabel(r'$\mathrm{log(b_n)}$')
plt.xlabel(r'$\mathrm{log(n)}$')
# plt.title('Messungen')
plt.grid()
plt.legend()<|fim▁hole|><|fim▁end|> | plt.tight_layout()
plt.savefig('bilder/rechteck.pdf')
plt.show() |
<|file_name|>JournalDAO.java<|end_file_name|><|fim▁begin|>/*
* Copyright (C) 2000 - 2016 Silverpeas
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* As a special exception to the terms and conditions of version 3.0 of
* the GPL, you may redistribute this Program in connection with Free/Libre
* Open Source Software ("FLOSS") applications as described in Silverpeas's
* FLOSS exception. You should have recieved a copy of the text describing
* the FLOSS exception, and it is also available here:
* "http://www.silverpeas.org/docs/core/legal/floss_exception.html"
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.silverpeas.core.personalorganizer.service;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import org.silverpeas.core.personalorganizer.model.JournalHeader;
import org.silverpeas.core.personalorganizer.model.ParticipationStatus;
import org.silverpeas.core.personalorganizer.model.SchedulableCount;
import org.silverpeas.core.personalorganizer.socialnetwork.SocialInformationEvent;
import org.silverpeas.core.util.StringUtil;
import org.silverpeas.core.silvertrace.SilverTrace;
import org.silverpeas.core.persistence.jdbc.DBUtil;
import org.silverpeas.core.util.DateUtil;
import org.silverpeas.core.exception.SilverpeasException;
import org.silverpeas.core.exception.UtilException;
public class JournalDAO {
public static final String COLUMNNAMES =
"id, name, delegatorId, description, priority, classification, startDay, startHour, endDay, endHour, externalId";
private static final String JOURNALCOLUMNNAMES =
"CalendarJournal.id, CalendarJournal.name, CalendarJournal.delegatorId, CalendarJournal.description, CalendarJournal.priority, "
+ " CalendarJournal.classification, CalendarJournal.startDay, CalendarJournal.startHour, CalendarJournal.endDay, CalendarJournal.endHour, CalendarJournal.externalId";
private static final String INSERT_JOURNAL = "INSERT INTO CalendarJournal ("
+ COLUMNNAMES + ") values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
private static final String UPDATE_JOURNAL = "UPDATE CalendarJournal SET name = ?, "
+ "delegatorId = ?, description = ?, priority = ?, classification = ?, "
+ "startDay = ?, startHour = ?, endDay = ?, endHour = ?, externalId = ? WHERE id = ?";
private static final String DELETE_JOURNAL = "DELETE FROM CalendarJournal WHERE id = ?";
public String addJournal(Connection con, JournalHeader journal)
throws SQLException, UtilException, CalendarException {
PreparedStatement prepStmt = null;
int id = 0;
try {
prepStmt = con.prepareStatement(INSERT_JOURNAL);
id = DBUtil.getNextId("CalendarJournal", "id");
prepStmt.setInt(1, id);
prepStmt.setString(2, journal.getName());
prepStmt.setString(3, journal.getDelegatorId());
prepStmt.setString(4, journal.getDescription());
prepStmt.setInt(5, journal.getPriority().getValue());
prepStmt.setString(6, journal.getClassification().getString());
prepStmt.setString(7, journal.getStartDay());
prepStmt.setString(8, journal.getStartHour());
prepStmt.setString(9, journal.getEndDay());
prepStmt.setString(10, journal.getEndHour());
prepStmt.setString(11, journal.getExternalId());
if (prepStmt.executeUpdate() == 0) {
throw new CalendarException(
"JournalDAO.Connection con, addJournal(Connection con, JournalHeader journal)",
SilverpeasException.ERROR, "calendar.EX_EXCUTE_INSERT_EMPTY");
}
} finally {
DBUtil.close(prepStmt);
}
return String.valueOf(id);
}
public void updateJournal(Connection con, JournalHeader journal)
throws SQLException, CalendarException {
PreparedStatement prepStmt = null;
try {
prepStmt = con.prepareStatement(UPDATE_JOURNAL);
prepStmt.setString(1, journal.getName());
prepStmt.setString(2, journal.getDelegatorId());
prepStmt.setString(3, journal.getDescription());
prepStmt.setInt(4, journal.getPriority().getValue());
prepStmt.setString(5, journal.getClassification().getString());
prepStmt.setString(6, journal.getStartDay());
prepStmt.setString(7, journal.getStartHour());
prepStmt.setString(8, journal.getEndDay());
prepStmt.setString(9, journal.getEndHour());
prepStmt.setString(10, journal.getExternalId());
prepStmt.setInt(11, Integer.parseInt(journal.getId()));
if (prepStmt.executeUpdate() == 0) {
throw new CalendarException(
"JournalDAO.Connection con, updateJournal(Connection con, JournalHeader journal)",
SilverpeasException.ERROR, "calendar.EX_EXCUTE_UPDATE_EMPTY");
}
} finally {
DBUtil.close(prepStmt);
}
}
public void removeJournal(Connection con, String id)
throws SQLException, CalendarException {
PreparedStatement prepStmt = null;
try {
prepStmt = con.prepareStatement(DELETE_JOURNAL);
prepStmt.setInt(1, Integer.parseInt(id));
if (prepStmt.executeUpdate() == 0) {
throw new CalendarException(
"JournalDAO.Connection con, removeJournal(Connection con, JournalHeader journal)",
SilverpeasException.ERROR, "calendar.EX_EXCUTE_DELETE_EMPTY");
}
} finally {
DBUtil.close(prepStmt);
}
}
public boolean hasTentativeJournalsForUser(Connection con,
String userId) throws SQLException, java.text.ParseException {
PreparedStatement prepStmt = null;
ResultSet rs = null;
try {
prepStmt = getTentativePreparedStatement(con, userId);
rs = prepStmt.executeQuery();
return rs.next();
} finally {
DBUtil.close(rs, prepStmt);
}
}
public Collection<JournalHeader> getTentativeJournalHeadersForUser(Connection con,
String userId) throws SQLException, java.text.ParseException {
PreparedStatement prepStmt = null;
ResultSet rs = null;
List<JournalHeader> list = new ArrayList<JournalHeader>();
try {
prepStmt = getTentativePreparedStatement(con, userId);
rs = prepStmt.executeQuery();
while (rs.next()) {
JournalHeader journal = getJournalHeaderFromResultSet(rs);
list.add(journal);
}
} finally {
DBUtil.close(rs, prepStmt);
}
return list;
}
private PreparedStatement getTentativePreparedStatement(
Connection con, String userId) throws SQLException {
String selectStatement = "select distinct " + JournalDAO.JOURNALCOLUMNNAMES
+ " from CalendarJournal, CalendarJournalAttendee "
+ " WHERE (CalendarJournal.id = CalendarJournalAttendee.journalId) "
+ " and (CalendarJournalAttendee.participationStatus = ?) "<|fim▁hole|> PreparedStatement prepStmt = con.prepareStatement(selectStatement);
prepStmt.setString(1, ParticipationStatus.TENTATIVE);
prepStmt.setString(2, userId);
return prepStmt;
}
private Collection<JournalHeader> getJournalHeadersForUser(Connection con,
String day, String userId, String categoryId, String participation,
String comparator) throws SQLException, java.text.ParseException {
StringBuilder selectStatement = new StringBuilder();
selectStatement.append("select distinct ").append(
JournalDAO.JOURNALCOLUMNNAMES).append(
" from CalendarJournal, CalendarJournalAttendee ");
if (categoryId != null) {
selectStatement.append(", CalendarJournalCategory ");
}
selectStatement.append(" where (CalendarJournal.id = CalendarJournalAttendee.journalId) ");
selectStatement.append(" and (userId = '").append(userId).append("'");
selectStatement.append(" and participationStatus = '").append(participation).append("') ");
if (categoryId != null) {
selectStatement.append(" and (CalendarJournal.id = CalendarJournalCategory.journalId) ");
selectStatement.append(" and (CalendarJournalCategory.categoryId = '").append(categoryId).
append("') ");
}
selectStatement.append(" and ((startDay ").append(comparator).append(" '").append(day).append(
"') or (startDay <= '").append(day).append(
"' and endDay >= '").append(day).append("')) ");
if (participation.equals(ParticipationStatus.ACCEPTED)) {
selectStatement.append("union ").append("select distinct ").append(
JournalDAO.JOURNALCOLUMNNAMES).append(" from CalendarJournal ");
if (categoryId != null) {
selectStatement.append(", CalendarJournalCategory ");
}
selectStatement.append(" where (delegatorId = '").append(userId).append(
"') ");
if (categoryId != null) {
selectStatement.append(" and (CalendarJournal.id = CalendarJournalCategory.journalId) ");
selectStatement.append(" and (CalendarJournalCategory.categoryId = '").append(categoryId).
append("') ");
}
selectStatement.append(" and ((startDay ").append(comparator).append(" '").append(day)
.append(
"') or (startDay <= '").append(day).append("' and endDay >= '").append(day).append(
"')) ");
}
selectStatement.append(" order by 7 , 8 "); // Modif PHiL -> Interbase
PreparedStatement prepStmt = null;
ResultSet rs = null;
List<JournalHeader> list = null;
try {
prepStmt = con.prepareStatement(selectStatement.toString());
rs = prepStmt.executeQuery();
list = new ArrayList<JournalHeader>();
while (rs.next()) {
JournalHeader journal = getJournalHeaderFromResultSet(rs);
list.add(journal);
}
} finally {
DBUtil.close(rs, prepStmt);
}
return list;
}
public Collection<JournalHeader> getDayJournalHeadersForUser(Connection con,
String day, String userId, String categoryId, String participation)
throws SQLException, java.text.ParseException {
return getJournalHeadersForUser(con, day, userId, categoryId,
participation, "=");
}
public Collection<JournalHeader> getNextJournalHeadersForUser(Connection con,
String day, String userId, String categoryId, String participation)
throws SQLException, java.text.ParseException {
return getJournalHeadersForUser(con, day, userId, categoryId,
participation, ">=");
}
/**
* get next JournalHeader for this user accordint to the type of data base
* used(PostgreSQL,Oracle,MMS)
* @param con
* @param day
* @param userId
* @param classification
* @param limit
* @param offset
* @return
* @throws SQLException
* @throws java.text.ParseException
*/
public List<JournalHeader> getNextEventsForUser(Connection con,
String day, String userId, String classification, Date begin, Date end)
throws SQLException, java.text.ParseException {
String selectNextEvents =
"select distinct " + JournalDAO.JOURNALCOLUMNNAMES + " from CalendarJournal "
+ " where delegatorId = ? and endDay >= ? ";
int classificationIndex = 2;
int limitIndex = 3;
if (StringUtil.isDefined(classification)) {
selectNextEvents += " and classification = ? ";
classificationIndex++;
limitIndex++;
}
selectNextEvents += " and CalendarJournal.startDay >= ? and CalendarJournal.startDay <= ?";
selectNextEvents += " order by CalendarJournal.startDay, CalendarJournal.startHour ";
PreparedStatement prepStmt = null;
ResultSet rs = null;
List<JournalHeader> list = null;
try {
prepStmt = con.prepareStatement(selectNextEvents);
prepStmt.setString(1, userId);
prepStmt.setString(2, day);
if (classificationIndex == 3)// Classification param not null
{
prepStmt.setString(classificationIndex, classification);
}
prepStmt.setString(limitIndex, DateUtil.date2SQLDate(begin));
prepStmt.setString(limitIndex + 1, DateUtil.date2SQLDate(end));
rs = prepStmt.executeQuery();
list = new ArrayList<JournalHeader>();
while (rs.next()) {
JournalHeader journal = getJournalHeaderFromResultSet(rs);
list.add(journal);
}
} finally {
DBUtil.close(rs, prepStmt);
}
return list;
}
public Collection<SchedulableCount> countMonthJournalsForUser(Connection con,
String month, String userId, String categoryId, String participation)
throws SQLException {
StringBuilder selectStatement = new StringBuilder(200);
String theDay = "";
selectStatement
.append(
"select count(distinct CalendarJournal.id), ? from CalendarJournal, CalendarJournalAttendee ");
if (categoryId != null) {
selectStatement.append(", CalendarJournalCategory ");
}
selectStatement.append("where (CalendarJournal.id = CalendarJournalAttendee.journalId) ");
selectStatement.append("and (userId = ").append(userId);
selectStatement.append(" and participationStatus = '").append(participation).append("')");
selectStatement.append(" and ((startDay = ?) or ((startDay <= ?) and (endDay >= ?))) ");
if (categoryId != null) {
selectStatement.append(" and (CalendarJournal.id = CalendarJournalCategory.journalId)");
selectStatement.append(" and (CalendarJournalCategory.categoryId = '").append(categoryId).
append("') ");
}
selectStatement.append("group by ?");
if (participation.equals(ParticipationStatus.ACCEPTED)) {
selectStatement.append(
"union select count(distinct CalendarJournal.id), ? from CalendarJournal ");
if (categoryId != null) {
selectStatement.append(", CalendarJournalCategory ");
}
selectStatement.append("where (delegatorId = '").append(userId).append(
"')");
selectStatement.append(" and ((startDay = ?) or ((startDay <= ?) and (endDay >= ?)))");
if (categoryId != null) {
selectStatement.append(" and (CalendarJournal.id = CalendarJournalCategory.journalId)");
selectStatement.append(" and (CalendarJournalCategory.categoryId = '").append(categoryId).
append("') ");
}
selectStatement.append("group by ?");
}
List<SchedulableCount> list = new ArrayList<SchedulableCount>();
int number;
String date = "";
PreparedStatement prepStmt = null;
try {
ResultSet rs = null;
prepStmt = con.prepareStatement(selectStatement.toString());
for (int day = 1; day == 31; day++) {
if (day < 10) {
theDay = month + "0" + String.valueOf(day);
} else {
theDay = month + String.valueOf(day);
}
prepStmt.setString(1, theDay);
prepStmt.setString(2, theDay);
prepStmt.setString(3, theDay);
prepStmt.setString(4, theDay);
prepStmt.setString(5, theDay);
prepStmt.setString(6, theDay);
prepStmt.setString(7, theDay);
prepStmt.setString(8, theDay);
prepStmt.setString(9, theDay);
prepStmt.setString(10, theDay);
rs = prepStmt.executeQuery();
while (rs.next()) {
number = rs.getInt(1);
date = rs.getString(2);
SchedulableCount count = new SchedulableCount(number, date);
list.add(count);
}
DBUtil.close(rs);
}
} finally {
DBUtil.close(prepStmt);
}
return list;
}
public Collection<JournalHeader> getPeriodJournalHeadersForUser(Connection con,
String begin, String end, String userId, String categoryId,
String participation) throws SQLException, java.text.ParseException {
StringBuilder selectStatement = new StringBuilder(200);
selectStatement.append("select distinct ").append(JournalDAO.COLUMNNAMES).append(
" from CalendarJournal, CalendarJournalAttendee ");
if (categoryId != null) {
selectStatement.append(", CalendarJournalCategory ");
}
selectStatement.append(" where (CalendarJournal.id = CalendarJournalAttendee.journalId) ");
selectStatement.append(" and (userId = '").append(userId).append("' ");
selectStatement.append(" and participationStatus = '").append(participation).append("') ");
if (categoryId != null) {
selectStatement.append(" and (CalendarJournal.id = CalendarJournalCategory.journalId) ");
selectStatement.append(" and (categoryId = '").append(categoryId).append(
"') ");
}
selectStatement.append(" and ( (startDay >= '").append(begin).append(
"' and startDay <= '").append(end).append("')");
selectStatement.append(" or (endDay >= '").append(begin).append(
"' and endDay <= '").append(end).append("')");
selectStatement.append(" or ('").append(begin).append("' >= startDay and '").append(begin).
append("' <= endDay) ");
selectStatement.append(" or ('").append(end).append("' >= startDay and '").append(end).append(
"' <= endDay) ) ");
if (participation.equals(ParticipationStatus.ACCEPTED)) {
selectStatement.append(" union select distinct ").append(
JournalDAO.COLUMNNAMES).append(" from CalendarJournal ");
if (categoryId != null) {
selectStatement.append(", CalendarJournalCategory ");
}
selectStatement.append("where (delegatorId = '").append(userId).append(
"') ");
if (categoryId != null) {
selectStatement.append(" and (CalendarJournal.id = CalendarJournalCategory.journalId) ");
selectStatement.append(" and (categoryId = '").append(categoryId).append("') ");
}
selectStatement.append(" and ( (startDay >= '").append(begin).append(
"' and startDay <= '").append(end).append("')");
selectStatement.append(" or (endDay >= '").append(begin).append(
"' and endDay <= '").append(end).append("')");
selectStatement.append(" or ('").append(begin).append(
"' >= startDay and '").append(begin).append("' <= endDay) ");
selectStatement.append(" or ('").append(end).append("' >= startDay and '").append(end)
.append(
"' <= endDay) ) ");
}
selectStatement.append(" order by 7 , 8 ");
PreparedStatement prepStmt = null;
ResultSet rs = null;
List<JournalHeader> list = null;
try {
prepStmt = con.prepareStatement(selectStatement.toString());
rs = prepStmt.executeQuery();
list = new ArrayList<JournalHeader>();
while (rs.next()) {
JournalHeader journal = getJournalHeaderFromResultSet(rs);
list.add(journal);
}
} finally {
DBUtil.close(rs, prepStmt);
}
return list;
}
public JournalHeader getJournalHeaderFromResultSet(ResultSet rs) throws SQLException,
java.text.ParseException {
String id = String.valueOf(rs.getInt(1));
String name = rs.getString(2);
String delegatorId = rs.getString(3);
JournalHeader journal = new JournalHeader(id, name, delegatorId);
journal.setDescription(rs.getString(4));
try {
journal.getPriority().setValue(rs.getInt(5));
} catch (Exception e) {
SilverTrace.warn("calendar",
"JournalDAO.getJournalHeaderFromResultSet(ResultSet rs)",
"calendar_MSG_NOT_GET_PRIORITY");
}
journal.getClassification().setString(rs.getString(6));
journal.setStartDay(rs.getString(7));
journal.setStartHour(rs.getString(8));
journal.setEndDay(rs.getString(9));
journal.setEndHour(rs.getString(10));
journal.setExternalId(rs.getString(11));
return journal;
}
public JournalHeader getJournalHeader(Connection con, String journalId)
throws SQLException, CalendarException, java.text.ParseException {
String selectStatement = "select " + JournalDAO.COLUMNNAMES
+ " from CalendarJournal " + "where id = ?";
PreparedStatement prepStmt = null;
ResultSet rs = null;
JournalHeader journal;
try {
prepStmt = con.prepareStatement(selectStatement);
prepStmt.setInt(1, Integer.parseInt(journalId));
rs = prepStmt.executeQuery();
if (rs.next()) {
journal = getJournalHeaderFromResultSet(rs);
} else {
throw new CalendarException(
"JournalDAO.Connection con, String journalId",
SilverpeasException.ERROR, "calendar.EX_RS_EMPTY", "journalId="
+ journalId);
}
return journal;
} finally {
DBUtil.close(rs, prepStmt);
}
}
public Collection<JournalHeader> getOutlookJournalHeadersForUser(Connection con,
String userId) throws SQLException, CalendarException,
java.text.ParseException {
String selectStatement = "select " + JournalDAO.COLUMNNAMES
+ " from CalendarJournal "
+ "where delegatorId = ? and externalId is not null";
PreparedStatement prepStmt = null;
ResultSet rs = null;
try {
prepStmt = con.prepareStatement(selectStatement);
prepStmt.setString(1, userId);
rs = prepStmt.executeQuery();
Collection<JournalHeader> list = new ArrayList<JournalHeader>();
while (rs.next()) {
JournalHeader journal = getJournalHeaderFromResultSet(rs);
list.add(journal);
}
return list;
} finally {
DBUtil.close(rs, prepStmt);
}
}
public Collection<JournalHeader> getOutlookJournalHeadersForUserAfterDate(
Connection con, String userId, java.util.Date startDate)
throws SQLException, CalendarException, java.text.ParseException {
String selectStatement = "select " + JournalDAO.COLUMNNAMES
+ " from CalendarJournal "
+ "where delegatorId = ? and startDay >= ? and externalId is not null";
PreparedStatement prepStmt = null;
ResultSet rs = null;
Collection<JournalHeader> list = null;
try {
prepStmt = con.prepareStatement(selectStatement);
prepStmt.setString(1, userId);
prepStmt.setString(2, DateUtil.date2SQLDate(startDate));
rs = prepStmt.executeQuery();
list = new ArrayList<JournalHeader>();
while (rs.next()) {
JournalHeader journal = getJournalHeaderFromResultSet(rs);
list.add(journal);
}
return list;
} finally {
DBUtil.close(rs, prepStmt);
}
}
public Collection<JournalHeader> getJournalHeadersForUserAfterDate(Connection con,
String userId, java.util.Date startDate, int nbReturned)
throws SQLException, CalendarException, java.text.ParseException {
String selectStatement = "select " + JournalDAO.COLUMNNAMES
+ " from CalendarJournal " + "where delegatorId = ? "
+ "and ((startDay >= ?) or (startDay <= ? and endDay >= ?))"
+ " order by startDay, startHour";
PreparedStatement prepStmt = null;
ResultSet rs = null;
String startDateString = DateUtil.date2SQLDate(startDate);
try {
int count = 0;
prepStmt = con.prepareStatement(selectStatement);
prepStmt.setString(1, userId);
prepStmt.setString(2, startDateString);
prepStmt.setString(3, startDateString);
prepStmt.setString(4, startDateString);
rs = prepStmt.executeQuery();
Collection<JournalHeader> list = new ArrayList<JournalHeader>();
while (rs.next() && nbReturned != count) {
JournalHeader journal = getJournalHeaderFromResultSet(rs);
list.add(journal);
count++;
}
return list;
} finally {
DBUtil.close(rs, prepStmt);
}
}
/**
* get Next Social Events for a given list of my Contacts accordint to the type of data base
* used(PostgreSQL,Oracle,MMS) . This includes all kinds of events
* @param con
* @param day
* @param myId
* @param myContactsIds
* @param begin
* @param end
* @return List<SocialInformationEvent>
* @throws SQLException
* @throws ParseException
*/
public List<SocialInformationEvent> getNextEventsForMyContacts(Connection con, String day,
String myId, List<String> myContactsIds, Date begin, Date end) throws SQLException,
ParseException {
String selectNextEvents =
"select distinct " + JournalDAO.JOURNALCOLUMNNAMES + " from CalendarJournal "
+ " where endDay >= ? and delegatorId in(" + toSqlString(myContactsIds) + ") "
+ " and startDay >= ? and startDay <= ? "
+ " order by startDay ASC, startHour ASC";
PreparedStatement prepStmt = null;
ResultSet rs = null;
try {
prepStmt = con.prepareStatement(selectNextEvents);
prepStmt.setString(1, day);
prepStmt.setString(2, DateUtil.date2SQLDate(begin));
prepStmt.setString(3, DateUtil.date2SQLDate(end));
rs = prepStmt.executeQuery();
List<SocialInformationEvent> list = new ArrayList<SocialInformationEvent>();
while (rs.next()) {
JournalHeader journal = getJournalHeaderFromResultSet(rs);
list.add(new SocialInformationEvent(journal, journal.getId().equals(myId)));
}
return list;
} finally {
DBUtil.close(rs, prepStmt);
}
}
private static String toSqlString(List<String> list) {
StringBuilder result = new StringBuilder(100);
if (list == null || list.isEmpty()) {
return "''";
}
int i = 0;
for (String var : list) {
if (i != 0) {
result.append(",");
}
result.append("'").append(var).append("'");
i++;
}
return result.toString();
}
/**
* get Last Social Events for a given list of my Contacts accordint to the type of data base
* used(PostgreSQL,Oracle,MMS) . This includes all kinds of events
* @param con
* @param day
* @param myId
* @param myContactsIds
* @param begin
* @param end
* @return List<SocialInformationEvent>
* @throws SQLException
* @throws ParseException
*/
public List<SocialInformationEvent> getLastEventsForMyContacts(Connection con, String day,
String myId, List<String> myContactsIds, Date begin, Date end) throws SQLException,
ParseException {
String selectNextEvents =
"select distinct " + JournalDAO.JOURNALCOLUMNNAMES + " from CalendarJournal "
+ " where endDay < ? and delegatorId in(" + toSqlString(myContactsIds) + ") "
+ " and startDay >= ? and startDay <= ? "
+ " order by startDay desc, startHour desc";
PreparedStatement prepStmt = null;
ResultSet rs = null;
List<SocialInformationEvent> list = null;
try {
prepStmt = con.prepareStatement(selectNextEvents);
prepStmt.setString(1, day);
prepStmt.setString(2, DateUtil.date2SQLDate(begin));
prepStmt.setString(3, DateUtil.date2SQLDate(end));
rs = prepStmt.executeQuery();
list = new ArrayList<SocialInformationEvent>();
while (rs.next()) {
JournalHeader journal = getJournalHeaderFromResultSet(rs);
list.add(new SocialInformationEvent(journal, journal.getId().equals(myId)));
}
} finally {
DBUtil.close(rs, prepStmt);
}
return list;
}
/**
* get my Last Social Events accordint to the type of data base used(PostgreSQL,Oracle,MMS) . This
* includes all kinds of events
* @param con
* @param day
* @param myId
* @param numberOfElement
* @param firstIndex
* @return List<SocialInformationEvent>
* @throws SQLException
* @throws ParseException
*/
public List<SocialInformationEvent> getMyLastEvents(Connection con, String day, String myId,
Date begin, Date end) throws SQLException,
ParseException {
String selectNextEvents =
"select distinct " + JournalDAO.JOURNALCOLUMNNAMES
+ " from CalendarJournal " + " where endDay < ? and delegatorId = ? "
+ " and startDay >= ? and startDay <= ? "
+ " order by startDay desc, startHour desc ";
PreparedStatement prepStmt = null;
ResultSet rs = null;
List<SocialInformationEvent> list = null;
try {
prepStmt = con.prepareStatement(selectNextEvents);
prepStmt.setString(1, day);
prepStmt.setString(2, myId);
prepStmt.setString(3, DateUtil.date2SQLDate(begin));
prepStmt.setString(4, DateUtil.date2SQLDate(end));
rs = prepStmt.executeQuery();
list = new ArrayList<SocialInformationEvent>();
while (rs.next()) {
JournalHeader journal = getJournalHeaderFromResultSet(rs);
list.add(new SocialInformationEvent(journal));
}
} finally {
DBUtil.close(rs, prepStmt);
}
return list;
}
/**
* get my Last Social Events when data base is MMS. This includes all kinds of events
* @param con
* @param day
* @param myId
* @param numberOfElement
* @param firstIndex
* @return
* @throws SQLException
* @throws java.text.ParseException
*/
public List<SocialInformationEvent> getMyLastEvents_MSS(Connection con,
String day, String myId, Date begin, Date end) throws
SQLException, java.text.ParseException {
String selectNextEvents =
"select distinct " + JournalDAO.JOURNALCOLUMNNAMES
+ " from CalendarJournal "
+ " where endDay < ? and delegatorId = ? "
+ " and startDay >= ? and startDay <= ? "
+ " order by CalendarJournal.startDay desc, CalendarJournal.startHour desc";
PreparedStatement prepStmt = null;
ResultSet rs = null;
List<SocialInformationEvent> list = null;
try {
prepStmt = con.prepareStatement(selectNextEvents);
prepStmt.setString(1, day);
prepStmt.setString(2, myId);
prepStmt.setString(3, DateUtil.date2SQLDate(begin));
prepStmt.setString(4, DateUtil.date2SQLDate(end));
rs = prepStmt.executeQuery();
list = new ArrayList<SocialInformationEvent>();
while (rs.next()) {
JournalHeader journal = getJournalHeaderFromResultSet(rs);
list.add(new SocialInformationEvent(journal));
}
} finally {
DBUtil.close(rs, prepStmt);
}
return list;
}
}<|fim▁end|> | + " and (userId = ?) " + " order by startDay, startHour"; |
<|file_name|>i16_add_with_overflow.rs<|end_file_name|><|fim▁begin|>#![feature(core, core_intrinsics)]
extern crate core;
#[cfg(test)]
mod tests {
use core::intrinsics::i16_add_with_overflow;
// pub fn i16_add_with_overflow(x: i16, y: i16) -> (i16, bool);
#[test]
fn i16_add_with_overflow_test1() {
let x: i16 = 0x7f00; // 32512
let y: i16 = 0x00ff; // 255
let (result, is_overflow): (i16, bool) = unsafe {
i16_add_with_overflow(x, y)
};
assert_eq!(result, 0x7fff); // 32767
assert_eq!(is_overflow, false);
}
#[test]
#[allow(overflowing_literals)]
fn i16_add_with_overflow_test2() {
let x: i16 = 0x7fff; // 32767
let y: i16 = 0x0001; // 1
let (result, is_overflow): (i16, bool) = unsafe {
i16_add_with_overflow(x, y)
};
<|fim▁hole|> }
#[test]
#[allow(overflowing_literals)]
fn i16_add_with_overflow_test3() {
let x: i16 = 0x8000; // -32768
let y: i16 = 0xffff; // -1
let (result, is_overflow): (i16, bool) = unsafe {
i16_add_with_overflow(x, y)
};
assert_eq!(result, 0x7fff); // 32767
assert_eq!(is_overflow, true);
}
}<|fim▁end|> | assert_eq!(result, 0x8000); // -32768
assert_eq!(is_overflow, true); |
<|file_name|>0004_remove_redundant_packs.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#pylint: skip-file
import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
class Migration(DataMigration):
def forwards(self, orm):
"Write your forwards methods here."
# Note: Remember to use orm['appname.ModelName'] rather than "from appname.models..."
Package = orm['core.Package']
Backup = orm['core.PackageBackup']
prev = None
to_be_del = []
for pack in Package.objects.order_by('name', 'id').all():
# for packages with the same name,
# only keep the one which has the smallest id
if prev is None or prev.name != pack.name:
prev = pack
else:
to_be_del.append(pack.id)
Backup.objects.filter(pid__in=to_be_del).update(isdel=True)
Package.objects.filter(id__in=to_be_del).delete()
def backwards(self, orm):
"Write your backwards methods here."
Package = orm['core.Package']
Backup = orm['core.PackageBackup']
to_be_add = [Package(id=bak.pid,
name=bak.name,
gittree_id=bak.tid)
for bak in Backup.objects.filter(isdel=True).all()]
Package.objects.bulk_create(to_be_add)
Backup.objects.filter(isdel=True).update(isdel=False)
models = {
u'auth.group': {
'Meta': {'object_name': 'Group'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
u'auth.permission': {
'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
u'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Group']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Permission']"}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '225'})
},
u'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'core.domain': {
'Meta': {'object_name': 'Domain'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'})
},
'core.domainrole': {
'Meta': {'object_name': 'DomainRole', '_ormbases': [u'auth.Group']},
'domain': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'role_set'", 'to': "orm['core.Domain']"}),
u'group_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': u"orm['auth.Group']", 'unique': 'True', 'primary_key': 'True'}),
'role': ('django.db.models.fields.CharField', [], {'max_length': '15', 'db_index': 'True'})
},
'core.gittree': {
'Meta': {'object_name': 'GitTree'},
'gitpath': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'licenses': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['core.License']", 'symmetrical': 'False'}),
'subdomain': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.SubDomain']"})
},
'core.gittreerole': {
'Meta': {'object_name': 'GitTreeRole', '_ormbases': [u'auth.Group']},
'gittree': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'role_set'", 'to': "orm['core.GitTree']"}),
u'group_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': u"orm['auth.Group']", 'unique': 'True', 'primary_key': 'True'}),
'role': ('django.db.models.fields.CharField', [], {'max_length': '15', 'db_index': 'True'})
},
'core.image': {
'Meta': {'object_name': 'Image'},
'arch': ('django.db.models.fields.TextField', [], {}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.TextField', [], {}),
'product': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.Product']"}),
'target': ('django.db.models.fields.TextField', [], {})
},
'core.imagebuild': {
'Meta': {'object_name': 'ImageBuild'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'image': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.Image']"}),
'log': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['core.Log']", 'unique': 'True', 'null': 'True', 'on_delete': 'models.SET_NULL', 'blank': 'True'}),
'name': ('django.db.models.fields.TextField', [], {}),
'status': ('django.db.models.fields.CharField', [], {'max_length': '8'})
},
'core.license': {
'Meta': {'object_name': 'License'},
'fullname': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'shortname': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}),
'text': ('django.db.models.fields.TextField', [], {})
},
'core.log': {
'Meta': {'object_name': 'Log'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'url': ('django.db.models.fields.URLField', [], {'max_length': '200'})
},
'core.package': {
'Meta': {'unique_together': "(('name', 'gittree'),)", 'object_name': 'Package'},
'gittree': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.GitTree']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'})
},
'core.packagebackup': {
'Meta': {'object_name': 'PackageBackup'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'isdel': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),<|fim▁hole|> 'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}),
'pid': ('django.db.models.fields.IntegerField', [], {}),
'tid': ('django.db.models.fields.IntegerField', [], {})
},
'core.packagebuild': {
'Meta': {'object_name': 'PackageBuild'},
'arch': ('django.db.models.fields.TextField', [], {}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'log': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['core.Log']", 'unique': 'True', 'null': 'True', 'on_delete': 'models.SET_NULL', 'blank': 'True'}),
'package': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.Package']"}),
'status': ('django.db.models.fields.CharField', [], {'max_length': '8'}),
'target': ('django.db.models.fields.TextField', [], {})
},
'core.product': {
'Meta': {'object_name': 'Product'},
'description': ('django.db.models.fields.TextField', [], {}),
'gittrees': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['core.GitTree']", 'symmetrical': 'False'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'})
},
'core.productrole': {
'Meta': {'object_name': 'ProductRole', '_ormbases': [u'auth.Group']},
u'group_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': u"orm['auth.Group']", 'unique': 'True', 'primary_key': 'True'}),
'product': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.Product']"}),
'role': ('django.db.models.fields.CharField', [], {'max_length': '15', 'db_index': 'True'})
},
'core.subdomain': {
'Meta': {'unique_together': "(('name', 'domain'),)", 'object_name': 'SubDomain'},
'domain': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.Domain']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'})
},
'core.subdomainrole': {
'Meta': {'object_name': 'SubDomainRole', '_ormbases': [u'auth.Group']},
u'group_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': u"orm['auth.Group']", 'unique': 'True', 'primary_key': 'True'}),
'role': ('django.db.models.fields.CharField', [], {'max_length': '15', 'db_index': 'True'}),
'subdomain': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.SubDomain']"})
},
'core.submission': {
'Meta': {'object_name': 'Submission'},
'comment': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'commit': ('django.db.models.fields.CharField', [], {'max_length': '40'}),
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'gittree': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['core.GitTree']", 'symmetrical': 'False', 'blank': 'True'}),
'ibuilds': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['core.ImageBuild']", 'symmetrical': 'False', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '80', 'db_index': 'True'}),
'pbuilds': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['core.PackageBuild']", 'symmetrical': 'False', 'blank': 'True'}),
'product': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.Product']", 'null': 'True', 'on_delete': 'models.SET_NULL', 'blank': 'True'}),
'status': ('django.db.models.fields.CharField', [], {'max_length': '16', 'db_index': 'True'}),
'submitters': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.User']", 'symmetrical': 'False'}),
'testresults': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['core.TestResult']", 'symmetrical': 'False', 'blank': 'True'}),
'updated': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'})
},
'core.submissiongroup': {
'Meta': {'object_name': 'SubmissionGroup'},
'author': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']"}),
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '80', 'db_index': 'True'}),
'product': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.Product']", 'null': 'True', 'on_delete': 'models.SET_NULL', 'blank': 'True'}),
'status': ('django.db.models.fields.CharField', [], {'max_length': '16'}),
'submissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['core.Submission']", 'symmetrical': 'False'}),
'updated': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'})
},
'core.testresult': {
'Meta': {'object_name': 'TestResult'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'log': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['core.Log']", 'unique': 'True', 'null': 'True', 'on_delete': 'models.SET_NULL', 'blank': 'True'}),
'name': ('django.db.models.fields.TextField', [], {}),
'status': ('django.db.models.fields.CharField', [], {'max_length': '16'})
},
'core.userparty': {
'Meta': {'object_name': 'UserParty', '_ormbases': [u'auth.Group']},
u'group_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': u"orm['auth.Group']", 'unique': 'True', 'primary_key': 'True'}),
'party': ('django.db.models.fields.CharField', [], {'max_length': '15'})
},
'core.userprofile': {
'Meta': {'object_name': 'UserProfile'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'user': ('django.db.models.fields.related.OneToOneField', [], {'to': u"orm['auth.User']", 'unique': 'True'})
}
}
complete_apps = ['core']
symmetrical = True<|fim▁end|> | |
<|file_name|>pcl_test.py<|end_file_name|><|fim▁begin|>import pcl<|fim▁hole|>fil.set_mean_k (50)
fil.set_std_dev_mul_thresh (1.0)
fil.filter().to_file("inliers.pcd")<|fim▁end|> | p = pcl.PointCloud()
p.from_file("test_pcd.pcd")
fil = p.make_statistical_outlier_filter() |
<|file_name|>celery.py<|end_file_name|><|fim▁begin|>from __future__ import absolute_import, unicode_literals
from celery.bin import celery
from djcelery.app import app
from djcelery.management.base import CeleryCommand
base = celery.CeleryCommand(app=app)<|fim▁hole|> help = 'celery commands, see celery help'
requires_model_validation = True
options = (CeleryCommand.options
+ base.get_options()
+ base.preload_options)
def run_from_argv(self, argv):
argv = self.handle_default_options(argv)
base.execute_from_commandline(
['{0[0]} {0[1]}'.format(argv)] + argv[2:])<|fim▁end|> |
class Command(CeleryCommand):
"""The celery command.""" |
<|file_name|>githubissuetracker.py<|end_file_name|><|fim▁begin|>"""
file: gitissuetracker.py
author: Christoffer Rosen <cbr4830@rit.edu>
date: December, 2013
description: Represents a Github Issue tracker object used
for getting the dates issues were opened.
12/12/13: Doesn't currently support private repos
"""
import requests, json, dateutil.parser, time
from caslogging import logging
class GithubIssueTracker:
"""
GitIssueTracker()
Represents a Github Issue Tracker Object
"""
owner = None # Owner of the github repo
repo = None # The repo name
request_repos = "https://api.github.com/repos" # Request url to get issue info
request_auth = "https://api.github.com/authorizations" # Request url for auth
def __init__(self, owner, repo):
"""
Constructor
"""
self.owner = owner
self.repo = repo
self.auth_token = None
self.authenticate() # Authenticate our app
def authenticate(self):
"""
authenticate()
Authenticates this application to github using
the cas-user git user credentials. This is temporary!
"""
s = requests.Session()
s.auth = ("cas-user", "riskykiwi1")
payload = {"scopes": ["repo"]}
r = s.get(self.request_auth, params=payload)
if r.headers.get('x-ratelimit-remaining') == '0':
logging.info("Github quota limit hit -- waiting")
# Wait up to a hour until we can continue..
while r.headers.get('x-ratelimit-remaining') == '0':
time.sleep(600) # Wait 10 minutes and try again
r = s.get(self.request_auth, params=payload)
data = r.json()
data = r.json()[0]
if r.status_code >= 400:
msg = data.get('message')
logging.error("Failed to authenticate issue tracker: \n" +msg)
return # Exit
else:
self.auth_token = data.get("token")
requests_left = r.headers.get('x-ratelimit-remaining')
logging.info("Analyzer has " + requests_left + " issue tracker calls left this hour")
def getDateOpened(self, issueNumber):
"""<|fim▁hole|> Gets the date the issue number was opened in unix time
If issue cannot be found for whichever reason, returns null.
"""
header = {'Authorization': 'token ' + self.auth_token}
r = requests.get(self.request_repos + "/" + self.owner + "/" +
self.repo + "/issues/" + issueNumber, headers=header)
data = r.json()
# If forbidden
if r.status_code == 403:
# Check the api quota
if r.headers.get('x-ratelimit-remaining') == '0':
logging.info("Github quota limit hit -- waiting")
# Wait up to a hour until we can continue..
while r.headers.get('x-ratelimit-remaining') == '0':
time.sleep(600) # Wait 10 minutes and try again
r = requests.get(self.request_repos + "/" + self.owner + "/" +
self.repo + "/issues/" + issueNumber, headers=header)
data = r.json()
# Check for other error codes
elif r.status_code >= 400:
msg = data.get('message')
logging.error("ISSUE TRACKER FAILURE: \n" + msg)
return None
else:
try:
date = (dateutil.parser.parse(data.get('created_at'))).timestamp()
return date
except:
logging.error("ISSUE TRACKER FAILURE: Could not get created_at from github issues API")
return None<|fim▁end|> | getDateOpened() |
<|file_name|>wxglvideo.py<|end_file_name|><|fim▁begin|>import wx
import wx.glcanvas
import pyglet
import pyglet.gl as gl
import pyglet.gl
import motmot.wxvideo.wxvideo as wxvideo
# XXX TODO:
# check off-by-one error in width/coordinate settings (e.g. glOrtho call)
# allow sharing of OpenGL context between instances
NewImageReadyEvent = wx.NewEventType() # use to trigger GUI thread action from grab thread
class PygWxContext:
_gl_begin = False
_workaround_unpack_row_length = False
def __init__(self, glcanvas ):
# glcanvas is instance of wx.glcanvas.GLCanvas
self.glcanvas = glcanvas
pyglet.gl._contexts.append( self )
def SetCurrent(self):
self.glcanvas.GetParent().Show()
if pyglet.version[:3] >= '1.1':
# tested on 1.1beta1
pyglet.gl.current_context = self
else:
# tested on 1.0
pyglet.gl._current_context = self
self.glcanvas.SetCurrent()
class DynamicImageCanvas(wx.glcanvas.GLCanvas):
"""Display image data to OpenGL using as few resources as possible"""
def _setcurrent(self,hack_ok=True):
self.wxcontext.SetCurrent()
def __init__(self, *args, **kw):
attribList = kw.get('attribList',None)
if attribList is None:
attribList = [
wx.glcanvas.WX_GL_RGBA,
wx.glcanvas.WX_GL_DOUBLEBUFFER, # force double buffering
wx.glcanvas.WX_GL_DEPTH_SIZE, 16,]
kw['attribList']=attribList
super(DynamicImageCanvas, self).__init__(*args,**kw)
self.init = False
self.Connect( -1, -1, NewImageReadyEvent, self.OnDraw )
self.flip_lr = False
self.fullcanvas = False
self.rotate_180 = False
wx.EVT_ERASE_BACKGROUND(self, self.OnEraseBackground)
wx.EVT_SIZE(self, self.OnSize)
wx.EVT_PAINT(self, self.OnPaint)
self._pygimage = None
self.wxcontext = PygWxContext( self )
self.wxcontext.SetCurrent()
def OnEraseBackground(self, event):
pass # Do nothing, to avoid flashing on MSW. (inhereted from wxDemo)
def set_flip_LR(self,value):
self.flip_lr = value
self._reset_projection()
set_flip_LR.__doc__ = wxvideo.DynamicImageCanvas.set_flip_LR.__doc__<|fim▁hole|> self.fullcanvas = value
self._reset_projection()
def set_rotate_180(self,value):
self.rotate_180 = value
self._reset_projection()
set_rotate_180.__doc__ = wxvideo.DynamicImageCanvas.set_rotate_180.__doc__
def OnSize(self, event):
size = self.GetClientSize()
if self.GetContext():
self.wxcontext.SetCurrent()
gl.glViewport(0, 0, size.width, size.height)
event.Skip()
def OnPaint(self, event):
dc = wx.PaintDC(self)
self.wxcontext.SetCurrent()
if not self.init:
self.InitGL()
self.init = True
self.OnDraw()
def InitGL(self):
self.wxcontext.SetCurrent()
gl.glEnable(gl.GL_BLEND)
gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)
self._reset_projection()
self.extra_initgl()
def extra_initgl(self):
pass
def _reset_projection(self):
if self.fullcanvas:
if self._pygimage is None:
return
width, height = self._pygimage.width, self._pygimage.height
else:
size = self.GetClientSize()
width, height = size.width, size.height
b = 0
t = height
if self.flip_lr:
l = width
r = 0
else:
l = 0
r = width
if self.rotate_180:
l,r=r,l
b,t=t,b
if width==0 or height==0:
# prevent OpenGL error
return
self.wxcontext.SetCurrent()
gl.glMatrixMode(gl.GL_PROJECTION)
gl.glLoadIdentity()
gl.glOrtho(l,r,b,t, -1, 1)
gl.glMatrixMode(gl.GL_MODELVIEW)
def new_image(self, image):
self._pygimage = image
self._reset_projection() # always trigger re-calculation of projection - necessary if self.fullcanvas
def update_image(self, image):
"""update the image to be displayed"""
self.wxcontext.SetCurrent()
self._pygimage.view_new_array( image )
event = wx.CommandEvent(NewImageReadyEvent)
event.SetEventObject(self)
wx.PostEvent(self, event)
def core_draw(self):
if self._pygimage is not None:
self._pygimage.blit(0, 0, 0)
def OnDraw(self,event=None):
self.wxcontext.SetCurrent()
gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)
self.core_draw()
self.SwapBuffers()<|fim▁end|> |
def set_fullcanvas(self,value): |
<|file_name|>base.py<|end_file_name|><|fim▁begin|>"""
Django ID mapper
Modified for Evennia by making sure that no model references
leave caching unexpectedly (no use if WeakRefs).
Also adds cache_size() for monitoring the size of the cache.
"""
import os, threading
#from twisted.internet import reactor
#from twisted.internet.threads import blockingCallFromThread
from twisted.internet.reactor import callFromThread
from django.core.exceptions import ObjectDoesNotExist, FieldError
from django.db.models.base import Model, ModelBase
from django.db.models.signals import post_save, pre_delete, post_syncdb
from src.utils.utils import dbref, get_evennia_pids, to_str
from manager import SharedMemoryManager
_FIELD_CACHE_GET = None
_FIELD_CACHE_SET = None
_GA = object.__getattribute__
_SA = object.__setattr__
_DA = object.__delattr__
# determine if our current pid is different from the server PID (i.e.
# if we are in a subprocess or not)
from src import PROC_MODIFIED_OBJS
# get info about the current process and thread
_SELF_PID = os.getpid()
_SERVER_PID, _PORTAL_PID = get_evennia_pids()
_IS_SUBPROCESS = (_SERVER_PID and _PORTAL_PID) and not _SELF_PID in (_SERVER_PID, _PORTAL_PID)
_IS_MAIN_THREAD = threading.currentThread().getName() == "MainThread"
#_SERVER_PID = None
#_PORTAL_PID = None
# #global _SERVER_PID, _PORTAL_PID, _IS_SUBPROCESS, _SELF_PID
# if not _SERVER_PID and not _PORTAL_PID:
# _IS_SUBPROCESS = (_SERVER_PID and _PORTAL_PID) and not _SELF_PID in (_SERVER_PID, _PORTAL_PID)
class SharedMemoryModelBase(ModelBase):
# CL: upstream had a __new__ method that skipped ModelBase's __new__ if
# SharedMemoryModelBase was not in the model class's ancestors. It's not
# clear what was the intended purpose, but skipping ModelBase.__new__
# broke things; in particular, default manager inheritance.
def __call__(cls, *args, **kwargs):
"""
this method will either create an instance (by calling the default implementation)
or try to retrieve one from the class-wide cache by infering the pk value from
args and kwargs. If instance caching is enabled for this class, the cache is
populated whenever possible (ie when it is possible to infer the pk value).
"""
def new_instance():
return super(SharedMemoryModelBase, cls).__call__(*args, **kwargs)
instance_key = cls._get_cache_key(args, kwargs)
# depending on the arguments, we might not be able to infer the PK, so in that case we create a new instance
if instance_key is None:
return new_instance()
cached_instance = cls.get_cached_instance(instance_key)
if cached_instance is None:
cached_instance = new_instance()
cls.cache_instance(cached_instance)
return cached_instance
def _prepare(cls):
cls.__instance_cache__ = {} #WeakValueDictionary()
super(SharedMemoryModelBase, cls)._prepare()
def __new__(cls, classname, bases, classdict, *args, **kwargs):
"""
Field shortcut creation:
Takes field names db_* and creates property wrappers named without the db_ prefix. So db_key -> key
This wrapper happens on the class level, so there is no overhead when creating objects. If a class
already has a wrapper of the given name, the automatic creation is skipped. Note: Remember to
document this auto-wrapping in the class header, this could seem very much like magic to the user otherwise.
"""
def create_wrapper(cls, fieldname, wrappername, editable=True, foreignkey=False):
"Helper method to create property wrappers with unique names (must be in separate call)"
def _get(cls, fname):
"Wrapper for getting database field"
#print "_get:", fieldname, wrappername,_GA(cls,fieldname)
return _GA(cls, fieldname)
def _get_foreign(cls, fname):
"Wrapper for returing foreignkey fields"
value = _GA(cls, fieldname)
#print "_get_foreign:value:", value
try:
return _GA(value, "typeclass")
except:
return value
def _set_nonedit(cls, fname, value):
"Wrapper for blocking editing of field"
raise FieldError("Field %s cannot be edited." % fname)
def _set(cls, fname, value):
"Wrapper for setting database field"
_SA(cls, fname, value)
# only use explicit update_fields in save if we actually have a
# primary key assigned already (won't be set when first creating object)
update_fields = [fname] if _GA(cls, "_get_pk_val")(_GA(cls, "_meta")) is not None else None
_GA(cls, "save")(update_fields=update_fields)
def _set_foreign(cls, fname, value):
"Setter only used on foreign key relations, allows setting with #dbref"
try:
value = _GA(value, "dbobj")
except AttributeError:
pass
if isinstance(value, (basestring, int)):
value = to_str(value, force_string=True)
if (value.isdigit() or value.startswith("#")):
# we also allow setting using dbrefs, if so we try to load the matching object.
# (we assume the object is of the same type as the class holding the field, if
# not a custom handler must be used for that field)
dbid = dbref(value, reqhash=False)
if dbid:
model = _GA(cls, "_meta").get_field(fname).model
try:
value = model._default_manager.get(id=dbid)
except ObjectDoesNotExist:
# maybe it is just a name that happens to look like a dbid
pass
_SA(cls, fname, value)
# only use explicit update_fields in save if we actually have a
# primary key assigned already (won't be set when first creating object)
update_fields = [fname] if _GA(cls, "_get_pk_val")(_GA(cls, "_meta")) is not None else None
_GA(cls, "save")(update_fields=update_fields)
def _del_nonedit(cls, fname):
"wrapper for not allowing deletion"
raise FieldError("Field %s cannot be edited." % fname)
def _del(cls, fname):
"Wrapper for clearing database field - sets it to None"<|fim▁hole|> _GA(cls, "save")(update_fields=update_fields)
# wrapper factories
fget = lambda cls: _get(cls, fieldname)
if not editable:
fset = lambda cls, val: _set_nonedit(cls, fieldname, val)
elif foreignkey:
fget = lambda cls: _get_foreign(cls, fieldname)
fset = lambda cls, val: _set_foreign(cls, fieldname, val)
else:
fset = lambda cls, val: _set(cls, fieldname, val)
fdel = lambda cls: _del(cls, fieldname) if editable else _del_nonedit(cls,fieldname)
# assigning
classdict[wrappername] = property(fget, fset, fdel)
#type(cls).__setattr__(cls, wrappername, property(fget, fset, fdel))#, doc))
# exclude some models that should not auto-create wrapper fields
if cls.__name__ in ("ServerConfig", "TypeNick"):
return
# dynamically create the wrapper properties for all fields not already handled (manytomanyfields are always handlers)
for fieldname, field in ((fname, field) for fname, field in classdict.items()
if fname.startswith("db_") and type(field).__name__ != "ManyToManyField"):
foreignkey = type(field).__name__ == "ForeignKey"
#print fieldname, type(field).__name__, field
wrappername = "dbid" if fieldname == "id" else fieldname.replace("db_", "", 1)
if wrappername not in classdict:
# makes sure not to overload manually created wrappers on the model
#print "wrapping %s -> %s" % (fieldname, wrappername)
create_wrapper(cls, fieldname, wrappername, editable=field.editable, foreignkey=foreignkey)
return super(SharedMemoryModelBase, cls).__new__(cls, classname, bases, classdict, *args, **kwargs)
#def __init__(cls, *args, **kwargs):
# """
# Field shortcut creation:
# Takes field names db_* and creates property wrappers named without the db_ prefix. So db_key -> key
# This wrapper happens on the class level, so there is no overhead when creating objects. If a class
# already has a wrapper of the given name, the automatic creation is skipped. Note: Remember to
# document this auto-wrapping in the class header, this could seem very much like magic to the user otherwise.
# """
# super(SharedMemoryModelBase, cls).__init__(*args, **kwargs)
# def create_wrapper(cls, fieldname, wrappername, editable=True):
# "Helper method to create property wrappers with unique names (must be in separate call)"
# def _get(cls, fname):
# "Wrapper for getting database field"
# value = _GA(cls, fieldname)
# if type(value) in (basestring, int, float, bool):
# return value
# elif hasattr(value, "typeclass"):
# return _GA(value, "typeclass")
# return value
# def _set_nonedit(cls, fname, value):
# "Wrapper for blocking editing of field"
# raise FieldError("Field %s cannot be edited." % fname)
# def _set(cls, fname, value):
# "Wrapper for setting database field"
# #print "_set:", fname
# if hasattr(value, "dbobj"):
# value = _GA(value, "dbobj")
# elif isinstance(value, basestring) and (value.isdigit() or value.startswith("#")):
# # we also allow setting using dbrefs, if so we try to load the matching object.
# # (we assume the object is of the same type as the class holding the field, if
# # not a custom handler must be used for that field)
# dbid = dbref(value, reqhash=False)
# if dbid:
# try:
# value = cls._default_manager.get(id=dbid)
# except ObjectDoesNotExist:
# # maybe it is just a name that happens to look like a dbid
# from src.utils.logger import log_trace
# log_trace()
# #print "_set wrapper:", fname, value, type(value), cls._get_pk_val(cls._meta)
# _SA(cls, fname, value)
# # only use explicit update_fields in save if we actually have a
# # primary key assigned already (won't be set when first creating object)
# update_fields = [fname] if _GA(cls, "_get_pk_val")(_GA(cls, "_meta")) is not None else None
# _GA(cls, "save")(update_fields=update_fields)
# def _del_nonedit(cls, fname):
# "wrapper for not allowing deletion"
# raise FieldError("Field %s cannot be edited." % fname)
# def _del(cls, fname):
# "Wrapper for clearing database field - sets it to None"
# _SA(cls, fname, None)
# update_fields = [fname] if _GA(cls, "_get_pk_val")(_GA(cls, "_meta")) is not None else None
# _GA(cls, "save")(update_fields=update_fields)
# # create class field wrappers
# fget = lambda cls: _get(cls, fieldname)
# fset = lambda cls, val: _set(cls, fieldname, val) if editable else _set_nonedit(cls, fieldname, val)
# fdel = lambda cls: _del(cls, fieldname) if editable else _del_nonedit(cls,fieldname)
# type(cls).__setattr__(cls, wrappername, property(fget, fset, fdel))#, doc))
# # exclude some models that should not auto-create wrapper fields
# if cls.__name__ in ("ServerConfig", "TypeNick"):
# return
# # dynamically create the wrapper properties for all fields not already handled
# for field in cls._meta.fields:
# fieldname = field.name
# if fieldname.startswith("db_"):
# wrappername = "dbid" if fieldname == "id" else fieldname.replace("db_", "")
# if not hasattr(cls, wrappername):
# # makes sure not to overload manually created wrappers on the model
# #print "wrapping %s -> %s" % (fieldname, wrappername)
# create_wrapper(cls, fieldname, wrappername, editable=field.editable)
class SharedMemoryModel(Model):
# CL: setting abstract correctly to allow subclasses to inherit the default
# manager.
__metaclass__ = SharedMemoryModelBase
objects = SharedMemoryManager()
class Meta:
abstract = True
def _get_cache_key(cls, args, kwargs):
"""
This method is used by the caching subsystem to infer the PK value from the constructor arguments.
It is used to decide if an instance has to be built or is already in the cache.
"""
result = None
# Quick hack for my composites work for now.
if hasattr(cls._meta, 'pks'):
pk = cls._meta.pks[0]
else:
pk = cls._meta.pk
# get the index of the pk in the class fields. this should be calculated *once*, but isn't atm
pk_position = cls._meta.fields.index(pk)
if len(args) > pk_position:
# if it's in the args, we can get it easily by index
result = args[pk_position]
elif pk.attname in kwargs:
# retrieve the pk value. Note that we use attname instead of name, to handle the case where the pk is a
# a ForeignKey.
result = kwargs[pk.attname]
elif pk.name != pk.attname and pk.name in kwargs:
# ok we couldn't find the value, but maybe it's a FK and we can find the corresponding object instead
result = kwargs[pk.name]
if result is not None and isinstance(result, Model):
# if the pk value happens to be a model instance (which can happen wich a FK), we'd rather use its own pk as the key
result = result._get_pk_val()
return result
_get_cache_key = classmethod(_get_cache_key)
def _flush_cached_by_key(cls, key):
try:
del cls.__instance_cache__[key]
except KeyError:
pass
_flush_cached_by_key = classmethod(_flush_cached_by_key)
def get_cached_instance(cls, id):
"""
Method to retrieve a cached instance by pk value. Returns None when not found
(which will always be the case when caching is disabled for this class). Please
note that the lookup will be done even when instance caching is disabled.
"""
return cls.__instance_cache__.get(id)
get_cached_instance = classmethod(get_cached_instance)
def cache_instance(cls, instance):
"""
Method to store an instance in the cache.
"""
if instance._get_pk_val() is not None:
cls.__instance_cache__[instance._get_pk_val()] = instance
cache_instance = classmethod(cache_instance)
def get_all_cached_instances(cls):
"return the objects so far cached by idmapper for this class."
return cls.__instance_cache__.values()
get_all_cached_instances = classmethod(get_all_cached_instances)
def flush_cached_instance(cls, instance):
"""
Method to flush an instance from the cache. The instance will always be flushed from the cache,
since this is most likely called from delete(), and we want to make sure we don't cache dead objects.
"""
cls._flush_cached_by_key(instance._get_pk_val())
flush_cached_instance = classmethod(flush_cached_instance)
def flush_instance_cache(cls):
cls.__instance_cache__ = {} #WeakValueDictionary()
flush_instance_cache = classmethod(flush_instance_cache)
def save(cls, *args, **kwargs):
"save method tracking process/thread issues"
if _IS_SUBPROCESS:
# we keep a store of objects modified in subprocesses so
# we know to update their caches in the central process
PROC_MODIFIED_OBJS.append(cls)
if _IS_MAIN_THREAD:
# in main thread - normal operation
super(SharedMemoryModel, cls).save(*args, **kwargs)
else:
# in another thread; make sure to save in reactor thread
def _save_callback(cls, *args, **kwargs):
super(SharedMemoryModel, cls).save(*args, **kwargs)
#blockingCallFromThread(reactor, _save_callback, cls, *args, **kwargs)
callFromThread(_save_callback, cls, *args, **kwargs)
# Use a signal so we make sure to catch cascades.
def flush_cache(**kwargs):
def class_hierarchy(root):
"""Recursively yield a class hierarchy."""
yield root
for subcls in root.__subclasses__():
for cls in class_hierarchy(subcls):
yield cls
for model in class_hierarchy(SharedMemoryModel):
model.flush_instance_cache()
#request_finished.connect(flush_cache)
post_syncdb.connect(flush_cache)
def flush_cached_instance(sender, instance, **kwargs):
# XXX: Is this the best way to make sure we can flush?
if not hasattr(instance, 'flush_cached_instance'):
return
sender.flush_cached_instance(instance)
pre_delete.connect(flush_cached_instance)
def update_cached_instance(sender, instance, **kwargs):
if not hasattr(instance, 'cache_instance'):
return
sender.cache_instance(instance)
post_save.connect(update_cached_instance)
def cache_size(mb=True):
"""
Returns a dictionary with estimates of the
cache size of each subclass.
mb - return the result in MB.
"""
import sys
sizedict = {"_total": [0, 0]}
def getsize(model):
instances = model.get_all_cached_instances()
linst = len(instances)
size = sum([sys.getsizeof(o) for o in instances])
size = (mb and size/1024.0) or size
return (linst, size)
def get_recurse(submodels):
for submodel in submodels:
subclasses = submodel.__subclasses__()
if not subclasses:
tup = getsize(submodel)
sizedict["_total"][0] += tup[0]
sizedict["_total"][1] += tup[1]
sizedict[submodel.__name__] = tup
else:
get_recurse(subclasses)
get_recurse(SharedMemoryModel.__subclasses__())
sizedict["_total"] = tuple(sizedict["_total"])
return sizedict<|fim▁end|> | _SA(cls, fname, None)
update_fields = [fname] if _GA(cls, "_get_pk_val")(_GA(cls, "_meta")) is not None else None |
<|file_name|>mainpage.go<|end_file_name|><|fim▁begin|>package web
import (
"net/http"
"brooce/heartbeat"
"brooce/listing"
"brooce/task"
)
type mainpageOutputType struct {
Queues map[string]*listing.QueueInfoType
RunningJobs []*task.Task
RunningWorkers []*heartbeat.HeartbeatType
TotalThreads int
}
func mainpageHandler(req *http.Request, rep *httpReply) (err error) {
output := &mainpageOutputType{}
output.RunningJobs, err = listing.RunningJobs(true)
if err != nil {
return
}
output.RunningWorkers, err = listing.RunningWorkers()
if err != nil {
return<|fim▁hole|> return
}
for _, worker := range output.RunningWorkers {
output.TotalThreads += len(worker.Threads)
}
err = templates.ExecuteTemplate(rep, "mainpage", output)
return
}<|fim▁end|> | }
output.Queues, err = listing.Queues(false)
if err != nil { |
<|file_name|>click_object.rs<|end_file_name|><|fim▁begin|>extern crate gtk;
use gtk::{ScrolledWindow,ContainerExt,Box,Orientation,Entry,EntryExt,Frame};
use std::vec::Vec;
pub trait Attachable{
fn attach<F:ContainerExt>(&self,parent: &F);
}
pub struct Control {}
impl Control {
pub fn play(&self){
println!("Play")
}
pub fn rew(&self){
println!("Rewind")
}
pub fn ff(&self){
println!("Fast Forward")
}
}
impl Clone for Control{
fn clone(&self)->Self{
return Control{}
}
}
impl Copy for Control {}
<|fim▁hole|>}
impl LabelFrame{
pub fn new(labels:Vec<Label>)->LabelFrame{
let label_box=Box::new(Orientation::Vertical,0);
//Add labels here
for label in &labels{
label.attach(&label_box)
}
LabelFrame{label_box: label_box,labels:labels}
}
}
impl Attachable for LabelFrame{
fn attach<F:ContainerExt>(&self,parent: &F){
let scroll=ScrolledWindow::new(None,None);
scroll.add(&self.label_box);
parent.add(&scroll);
}
}
pub struct Label{
key:String,
value:Entry
}
impl Label{
pub fn new(label:&str)->Label{
let k = String::from(label);
let v = Entry::new();
v.set_text("0");
Label{key:k,value:v}
}
}
impl Attachable for Label{
fn attach<F:ContainerExt>(&self,parent: &F){
let f=Frame::new(Some(self.key.as_str()));
f.add(&self.value);
parent.add(&f);
}
}<|fim▁end|> | pub struct LabelFrame {
label_box:Box,
labels:Vec<Label> |
<|file_name|>daemonsetcontroller.go<|end_file_name|><|fim▁begin|>/*
Copyright 2018 The Kubernetes Authors.<|fim▁hole|>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package options
import (
"github.com/spf13/pflag"
"k8s.io/kubernetes/pkg/apis/componentconfig"
)
// DaemonSetControllerOptions holds the DaemonSetController options.
type DaemonSetControllerOptions struct {
ConcurrentDaemonSetSyncs int32
}
// AddFlags adds flags related to DaemonSetController for controller manager to the specified FlagSet.
func (o *DaemonSetControllerOptions) AddFlags(fs *pflag.FlagSet) {
if o == nil {
return
}
}
// ApplyTo fills up DaemonSetController config with options.
func (o *DaemonSetControllerOptions) ApplyTo(cfg *componentconfig.DaemonSetControllerConfiguration) error {
if o == nil {
return nil
}
cfg.ConcurrentDaemonSetSyncs = o.ConcurrentDaemonSetSyncs
return nil
}
// Validate checks validation of DaemonSetControllerOptions.
func (o *DaemonSetControllerOptions) Validate() []error {
if o == nil {
return nil
}
errs := []error{}
return errs
}<|fim▁end|> | |
<|file_name|>semi-after-macro-ty.rs<|end_file_name|><|fim▁begin|>// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.<|fim▁hole|>//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
macro_rules! foo {
($t:ty; $p:path;) => {}
}
fn main() {
foo!(i32; i32;);
}<|fim▁end|> | |
<|file_name|>inherited_account_account_type.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright 2017 KMEE
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class AccountAccountType(models.Model):
_inherit = 'account.account.type'
_order = 'sequence asc'<|fim▁hole|><|fim▁end|> |
sequence = fields.Integer(
string=u'Sequence',
) |
<|file_name|>test_submit_button.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Copyright (C) 2015 McKinsey Academy
#
# Authors:
# Jonathan Piacenti <jonathan@opencraft.com>
#
# This software's license gives you freedom; you can copy, convey,
# propagate, redistribute and/or modify this program under the terms of
# the GNU Affero General Public License (AGPL) as published by the Free
# Software Foundation (FSF), either version 3 of the License, or (at your
# option) any later version of the AGPL published by the FSF.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
# General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program in a file in the toplevel directory called
# "AGPLv3". If not, see <http://www.gnu.org/licenses/>.<|fim▁hole|>
from __future__ import absolute_import
from tests.integration.base_test import PollBaseTest
from unittest import skip
class TestSubmitButton(PollBaseTest):
@skip("Flaky test")
def test_submit_button(self):
"""
Goal: We have to make sure that submit button gets disabled right
after it is clicked. We cannot test with 100% assurance by adding a
method in other tests such as test_functions.py because in that case
submit button is anyway disabled after the ajax request.
We can utilize infinite submission feature and check if the submit
button was disabled (because of js) and then re-enabled (because of
ajax request).
"""
self.go_to_page('Poll Submit Button')
# Find all the radio choices
answer_elements = self.browser.find_elements_by_css_selector('label.poll-answer-text')
# Select the first choice
answer_elements[1].click()
# When an answer is selected, make sure submit is enabled.
self.wait_until_exists('input[name=poll-submit]:enabled')
submit_button = self.get_submit()
submit_button.click()
# Make sure that submit button is disabled right away
self.assertFalse(submit_button.is_enabled())
self.wait_until_clickable(self.browser.find_element_by_css_selector('.poll-voting-thanks'))
# Wait until the ajax request is finished and submit button is enabled
self.assertTrue(self.get_submit().is_enabled())<|fim▁end|> | # |
<|file_name|>test_microsites.py<|end_file_name|><|fim▁begin|>"""
Tests related to the Microsites feature
"""
from django.conf import settings
from django.core.urlresolvers import reverse
from django.test.utils import override_settings
from nose.plugins.attrib import attr
from courseware.tests.helpers import LoginEnrollmentTestCase
from course_modes.models import CourseMode
from xmodule.course_module import (
CATALOG_VISIBILITY_CATALOG_AND_ABOUT, CATALOG_VISIBILITY_NONE)
from xmodule.modulestore.tests.factories import CourseFactory, ItemFactory
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
@attr('shard_1')
class TestMicrosites(ModuleStoreTestCase, LoginEnrollmentTestCase):
"""
This is testing of the Microsite feature
"""
STUDENT_INFO = [('view@test.com', 'foo'), ('view2@test.com', 'foo')]
def setUp(self):
super(TestMicrosites, self).setUp()
# use a different hostname to test Microsites since they are
# triggered on subdomain mappings
#
# NOTE: The Microsite Configuration is in lms/envs/test.py. The content for the Test Microsite is in
# test_microsites/test_microsite.
#
# IMPORTANT: For these tests to work, this domain must be defined via
# DNS configuration (either local or published)
self.course = CourseFactory.create(
display_name='Robot_Super_Course',
org='TestMicrositeX',
emit_signals=True,
)
self.chapter0 = ItemFactory.create(parent_location=self.course.location,
display_name='Overview')
self.chapter9 = ItemFactory.create(parent_location=self.course.location,
display_name='factory_chapter')
self.section0 = ItemFactory.create(parent_location=self.chapter0.location,
display_name='Welcome')
self.section9 = ItemFactory.create(parent_location=self.chapter9.location,
display_name='factory_section')
self.course_outside_microsite = CourseFactory.create(
display_name='Robot_Course_Outside_Microsite',
org='FooX',
emit_signals=True,<|fim▁hole|>
# have a course which explicitly sets visibility in catalog to False
self.course_hidden_visibility = CourseFactory.create(
display_name='Hidden_course',
org='TestMicrositeX',
catalog_visibility=CATALOG_VISIBILITY_NONE,
emit_signals=True,
)
# have a course which explicitly sets visibility in catalog and about to true
self.course_with_visibility = CourseFactory.create(
display_name='visible_course',
org='TestMicrositeX',
course="foo",
catalog_visibility=CATALOG_VISIBILITY_CATALOG_AND_ABOUT,
emit_signals=True,
)
def setup_users(self):
# Create student accounts and activate them.
for i in range(len(self.STUDENT_INFO)):
email, password = self.STUDENT_INFO[i]
username = 'u{0}'.format(i)
self.create_account(username, email, password)
self.activate_user(email)
@override_settings(SITE_NAME=settings.MICROSITE_TEST_HOSTNAME)
def test_microsite_anonymous_homepage_content(self):
"""
Verify that the homepage, when accessed via a Microsite domain, returns
HTML that reflects the Microsite branding elements
"""
resp = self.client.get('/', HTTP_HOST=settings.MICROSITE_TEST_HOSTNAME)
self.assertEqual(resp.status_code, 200)
# assert various branding definitions on this Microsite
# as per the configuration and Microsite overrides
self.assertContains(resp, 'This is a Test Microsite Overlay') # Overlay test message
self.assertContains(resp, 'test_microsite/images/header-logo.png') # logo swap
self.assertContains(resp, 'test_microsite/css/test_microsite') # css override
self.assertContains(resp, 'Test Microsite') # page title
# assert that test course display name is visible
self.assertContains(resp, 'Robot_Super_Course')
# assert that test course with 'visible_in_catalog' to True is showing up
self.assertContains(resp, 'visible_course')
# assert that test course that is outside microsite is not visible
self.assertNotContains(resp, 'Robot_Course_Outside_Microsite')
# assert that a course that has visible_in_catalog=False is not visible
self.assertNotContains(resp, 'Hidden_course')
# assert that footer template has been properly overriden on homepage
self.assertContains(resp, 'This is a Test Microsite footer')
# assert that the edX partners section is not in the HTML
self.assertNotContains(resp, '<section class="university-partners university-partners2x6">')
# assert that the edX partners tag line is not in the HTML
self.assertNotContains(resp, 'Explore free courses from')
def test_not_microsite_anonymous_homepage_content(self):
"""
Make sure we see the right content on the homepage if we are not in a microsite
"""
resp = self.client.get('/')
self.assertEqual(resp.status_code, 200)
# assert various branding definitions on this Microsite ARE NOT VISIBLE
self.assertNotContains(resp, 'This is a Test Microsite Overlay') # Overlay test message
self.assertNotContains(resp, 'test_microsite/images/header-logo.png') # logo swap
self.assertNotContains(resp, 'test_microsite/css/test_microsite') # css override
self.assertNotContains(resp, '<title>Test Microsite</title>') # page title
# assert that test course display name IS NOT VISIBLE, since that is a Microsite only course
self.assertNotContains(resp, 'Robot_Super_Course')
# assert that test course that is outside microsite IS VISIBLE
self.assertContains(resp, 'Robot_Course_Outside_Microsite')
# assert that footer template has been properly overriden on homepage
self.assertNotContains(resp, 'This is a Test Microsite footer')
def test_no_redirect_on_homepage_when_no_enrollments(self):
"""
Verify that a user going to homepage will not redirect if he/she has no course enrollments
"""
self.setup_users()
email, password = self.STUDENT_INFO[0]
self.login(email, password)
resp = self.client.get(reverse('root'), HTTP_HOST=settings.MICROSITE_TEST_HOSTNAME)
self.assertEquals(resp.status_code, 200)
def test_no_redirect_on_homepage_when_has_enrollments(self):
"""
Verify that a user going to homepage will not redirect to dashboard if he/she has
a course enrollment
"""
self.setup_users()
email, password = self.STUDENT_INFO[0]
self.login(email, password)
self.enroll(self.course, True)
resp = self.client.get(reverse('root'), HTTP_HOST=settings.MICROSITE_TEST_HOSTNAME)
self.assertEquals(resp.status_code, 200)
def test_microsite_course_enrollment(self):
"""
Enroll user in a course scoped in a Microsite and one course outside of a Microsite
and make sure that they are only visible in the right Dashboards
"""
self.setup_users()
email, password = self.STUDENT_INFO[1]
self.login(email, password)
self.enroll(self.course, True)
self.enroll(self.course_outside_microsite, True)
# Access the microsite dashboard and make sure the right courses appear
resp = self.client.get(reverse('dashboard'), HTTP_HOST=settings.MICROSITE_TEST_HOSTNAME)
self.assertContains(resp, 'Robot_Super_Course')
self.assertNotContains(resp, 'Robot_Course_Outside_Microsite')
# Now access the non-microsite dashboard and make sure the right courses appear
resp = self.client.get(reverse('dashboard'))
self.assertNotContains(resp, 'Robot_Super_Course')
self.assertContains(resp, 'Robot_Course_Outside_Microsite')
@override_settings(SITE_NAME=settings.MICROSITE_TEST_HOSTNAME)
def test_visible_about_page_settings(self):
"""
Make sure the Microsite is honoring the visible_about_page permissions that is
set in configuration
"""
url = reverse('about_course', args=[self.course_with_visibility.id.to_deprecated_string()])
resp = self.client.get(url, HTTP_HOST=settings.MICROSITE_TEST_HOSTNAME)
self.assertEqual(resp.status_code, 200)
url = reverse('about_course', args=[self.course_hidden_visibility.id.to_deprecated_string()])
resp = self.client.get(url, HTTP_HOST=settings.MICROSITE_TEST_HOSTNAME)
self.assertEqual(resp.status_code, 404)
@override_settings(SITE_NAME=settings.MICROSITE_TEST_HOSTNAME)
def test_paid_course_registration(self):
"""
Make sure that Microsite overrides on the ENABLE_SHOPPING_CART and
ENABLE_PAID_COURSE_ENROLLMENTS are honored
"""
course_mode = CourseMode(
course_id=self.course_with_visibility.id,
mode_slug=CourseMode.DEFAULT_MODE_SLUG,
mode_display_name=CourseMode.DEFAULT_MODE_SLUG,
min_price=10,
)
course_mode.save()
# first try on the non microsite, which
# should pick up the global configuration (where ENABLE_PAID_COURSE_REGISTRATIONS = False)
url = reverse('about_course', args=[self.course_with_visibility.id.to_deprecated_string()])
resp = self.client.get(url)
self.assertEqual(resp.status_code, 200)
self.assertIn("Enroll in {}".format(self.course_with_visibility.id.course), resp.content)
self.assertNotIn("Add {} to Cart ($10)".format(self.course_with_visibility.id.course), resp.content)
# now try on the microsite
url = reverse('about_course', args=[self.course_with_visibility.id.to_deprecated_string()])
resp = self.client.get(url, HTTP_HOST=settings.MICROSITE_TEST_HOSTNAME)
self.assertEqual(resp.status_code, 200)
self.assertNotIn("Enroll in {}".format(self.course_with_visibility.id.course), resp.content)
self.assertIn("Add {} to Cart <span>($10 USD)</span>".format(
self.course_with_visibility.id.course
), resp.content)
self.assertIn('$("#add_to_cart_post").click', resp.content)<|fim▁end|> | ) |
<|file_name|>state_based_validator.go<|end_file_name|><|fim▁begin|>/*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package statebasedval
import (
"github.com/hyperledger/fabric/common/flogging"
"github.com/hyperledger/fabric/core/ledger/kvledger/txmgmt/privacyenabledstate"
"github.com/hyperledger/fabric/core/ledger/kvledger/txmgmt/rwsetutil"
"github.com/hyperledger/fabric/core/ledger/kvledger/txmgmt/statedb"
"github.com/hyperledger/fabric/core/ledger/kvledger/txmgmt/validator/internal"
"github.com/hyperledger/fabric/core/ledger/kvledger/txmgmt/version"
"github.com/hyperledger/fabric/protos/ledger/rwset/kvrwset"
"github.com/hyperledger/fabric/protos/peer"
)
var logger = flogging.MustGetLogger("statebasedval")
// Validator validates a tx against the latest committed state
// and preceding valid transactions with in the same block
type Validator struct {
db privacyenabledstate.DB
}
// NewValidator constructs StateValidator
func NewValidator(db privacyenabledstate.DB) *Validator {
return &Validator{db}
}
// preLoadCommittedVersionOfRSet loads committed version of all keys in each
// transaction's read set into a cache.
func (v *Validator) preLoadCommittedVersionOfRSet(block *internal.Block) error {
// Collect both public and hashed keys in read sets of all transactions in a given block
var pubKeys []*statedb.CompositeKey
var hashedKeys []*privacyenabledstate.HashedCompositeKey
// pubKeysMap and hashedKeysMap are used to avoid duplicate entries in the
// pubKeys and hashedKeys. Though map alone can be used to collect keys in
// read sets and pass as an argument in LoadCommittedVersionOfPubAndHashedKeys(),
// array is used for better code readability. On the negative side, this approach
// might use some extra memory.
pubKeysMap := make(map[statedb.CompositeKey]interface{})
hashedKeysMap := make(map[privacyenabledstate.HashedCompositeKey]interface{})
for _, tx := range block.Txs {
for _, nsRWSet := range tx.RWSet.NsRwSets {
for _, kvRead := range nsRWSet.KvRwSet.Reads {
compositeKey := statedb.CompositeKey{
Namespace: nsRWSet.NameSpace,
Key: kvRead.Key,
}
if _, ok := pubKeysMap[compositeKey]; !ok {
pubKeysMap[compositeKey] = nil
pubKeys = append(pubKeys, &compositeKey)
}
}
for _, colHashedRwSet := range nsRWSet.CollHashedRwSets {
for _, kvHashedRead := range colHashedRwSet.HashedRwSet.HashedReads {
hashedCompositeKey := privacyenabledstate.HashedCompositeKey{
Namespace: nsRWSet.NameSpace,
CollectionName: colHashedRwSet.CollectionName,
KeyHash: string(kvHashedRead.KeyHash),
}
if _, ok := hashedKeysMap[hashedCompositeKey]; !ok {
hashedKeysMap[hashedCompositeKey] = nil
hashedKeys = append(hashedKeys, &hashedCompositeKey)
}
}
}
}
}
// Load committed version of all keys into a cache
if len(pubKeys) > 0 || len(hashedKeys) > 0 {
err := v.db.LoadCommittedVersionsOfPubAndHashedKeys(pubKeys, hashedKeys)
if err != nil {
return err
}
}
return nil
}
// ValidateAndPrepareBatch implements method in Validator interface
func (v *Validator) ValidateAndPrepareBatch(block *internal.Block, doMVCCValidation bool) (*internal.PubAndHashUpdates, error) {
// Check whether statedb implements BulkOptimizable interface. For now,
// only CouchDB implements BulkOptimizable to reduce the number of REST
// API calls from peer to CouchDB instance.
if v.db.IsBulkOptimizable() {
err := v.preLoadCommittedVersionOfRSet(block)
if err != nil {
return nil, err
}
}
updates := internal.NewPubAndHashUpdates()
for _, tx := range block.Txs {
var validationCode peer.TxValidationCode
var err error
if validationCode, err = v.validateEndorserTX(tx.RWSet, doMVCCValidation, updates); err != nil {
return nil, err
}
tx.ValidationCode = validationCode
if validationCode == peer.TxValidationCode_VALID {
logger.Debugf("Block [%d] Transaction index [%d] TxId [%s] marked as valid by state validator", block.Num, tx.IndexInBlock, tx.ID)
committingTxHeight := version.NewHeight(block.Num, uint64(tx.IndexInBlock))
updates.ApplyWriteSet(tx.RWSet, committingTxHeight, v.db)
} else {
logger.Warningf("Block [%d] Transaction index [%d] TxId [%s] marked as invalid by state validator. Reason code [%s]",
block.Num, tx.IndexInBlock, tx.ID, validationCode.String())
}
}
return updates, nil
}
// validateEndorserTX validates endorser transaction
func (v *Validator) validateEndorserTX(
txRWSet *rwsetutil.TxRwSet,
doMVCCValidation bool,
updates *internal.PubAndHashUpdates) (peer.TxValidationCode, error) {
var validationCode = peer.TxValidationCode_VALID
var err error
//mvccvalidation, may invalidate transaction
if doMVCCValidation {
validationCode, err = v.validateTx(txRWSet, updates)
}
return validationCode, err
}
func (v *Validator) validateTx(txRWSet *rwsetutil.TxRwSet, updates *internal.PubAndHashUpdates) (peer.TxValidationCode, error) {
// Uncomment the following only for local debugging. Don't want to print data in the logs in production
//logger.Debugf("validateTx - validating txRWSet: %s", spew.Sdump(txRWSet))
for _, nsRWSet := range txRWSet.NsRwSets {
ns := nsRWSet.NameSpace
// Validate public reads
if valid, err := v.validateReadSet(ns, nsRWSet.KvRwSet.Reads, updates.PubUpdates); !valid || err != nil {
if err != nil {
return peer.TxValidationCode(-1), err
}
return peer.TxValidationCode_MVCC_READ_CONFLICT, nil
}
// Validate range queries for phantom items
if valid, err := v.validateRangeQueries(ns, nsRWSet.KvRwSet.RangeQueriesInfo, updates.PubUpdates); !valid || err != nil {
if err != nil {
return peer.TxValidationCode(-1), err
}
return peer.TxValidationCode_PHANTOM_READ_CONFLICT, nil
}
// Validate hashes for private reads
if valid, err := v.validateNsHashedReadSets(ns, nsRWSet.CollHashedRwSets, updates.HashUpdates); !valid || err != nil {
if err != nil {
return peer.TxValidationCode(-1), err
}
return peer.TxValidationCode_MVCC_READ_CONFLICT, nil
}
}
return peer.TxValidationCode_VALID, nil
}
////////////////////////////////////////////////////////////////////////////////
///// Validation of public read-set
////////////////////////////////////////////////////////////////////////////////
func (v *Validator) validateReadSet(ns string, kvReads []*kvrwset.KVRead, updates *privacyenabledstate.PubUpdateBatch) (bool, error) {
for _, kvRead := range kvReads {
if valid, err := v.validateKVRead(ns, kvRead, updates); !valid || err != nil {
return valid, err
}
}
return true, nil
}
// validateKVRead performs mvcc check for a key read during transaction simulation.
// i.e., it checks whether a key/version combination is already updated in the statedb (by an already committed block)
// or in the updates (by a preceding valid transaction in the current block)
func (v *Validator) validateKVRead(ns string, kvRead *kvrwset.KVRead, updates *privacyenabledstate.PubUpdateBatch) (bool, error) {
if updates.Exists(ns, kvRead.Key) {
return false, nil
}
committedVersion, err := v.db.GetVersion(ns, kvRead.Key)
if err != nil {
return false, err
}
logger.Debugf("Comparing versions for key [%s]: committed version=%#v and read version=%#v",
kvRead.Key, committedVersion, rwsetutil.NewVersion(kvRead.Version))
if !version.AreSame(committedVersion, rwsetutil.NewVersion(kvRead.Version)) {
logger.Debugf("Version mismatch for key [%s:%s]. Committed version = [%#v], Version in readSet [%#v]",
ns, kvRead.Key, committedVersion, kvRead.Version)
return false, nil
}
return true, nil
}
////////////////////////////////////////////////////////////////////////////////
///// Validation of range queries
////////////////////////////////////////////////////////////////////////////////
func (v *Validator) validateRangeQueries(ns string, rangeQueriesInfo []*kvrwset.RangeQueryInfo, updates *privacyenabledstate.PubUpdateBatch) (bool, error) {
for _, rqi := range rangeQueriesInfo {
if valid, err := v.validateRangeQuery(ns, rqi, updates); !valid || err != nil {
return valid, err
}
}
return true, nil
}
// validateRangeQuery performs a phantom read check i.e., it
// checks whether the results of the range query are still the same when executed on the
// statedb (latest state as of last committed block) + updates (prepared by the writes of preceding valid transactions
// in the current block and yet to be committed as part of group commit at the end of the validation of the block)
func (v *Validator) validateRangeQuery(ns string, rangeQueryInfo *kvrwset.RangeQueryInfo, updates *privacyenabledstate.PubUpdateBatch) (bool, error) {
logger.Debugf("validateRangeQuery: ns=%s, rangeQueryInfo=%s", ns, rangeQueryInfo)
// If during simulation, the caller had not exhausted the iterator so
// rangeQueryInfo.EndKey is not actual endKey given by the caller in the range query
// but rather it is the last key seen by the caller and hence the combinedItr should include the endKey in the results.
includeEndKey := !rangeQueryInfo.ItrExhausted
combinedItr, err := newCombinedIterator(v.db, updates.UpdateBatch,
ns, rangeQueryInfo.StartKey, rangeQueryInfo.EndKey, includeEndKey)
if err != nil {
return false, err
}
defer combinedItr.Close()
var validator rangeQueryValidator
if rangeQueryInfo.GetReadsMerkleHashes() != nil {
logger.Debug(`Hashing results are present in the range query info hence, initiating hashing based validation`)
validator = &rangeQueryHashValidator{}
} else {
logger.Debug(`Hashing results are not present in the range query info hence, initiating raw KVReads based validation`)
validator = &rangeQueryResultsValidator{}
}
validator.init(rangeQueryInfo, combinedItr)
return validator.validate()<|fim▁hole|>
////////////////////////////////////////////////////////////////////////////////
///// Validation of hashed read-set
////////////////////////////////////////////////////////////////////////////////
func (v *Validator) validateNsHashedReadSets(ns string, collHashedRWSets []*rwsetutil.CollHashedRwSet,
updates *privacyenabledstate.HashedUpdateBatch) (bool, error) {
for _, collHashedRWSet := range collHashedRWSets {
if valid, err := v.validateCollHashedReadSet(ns, collHashedRWSet.CollectionName, collHashedRWSet.HashedRwSet.HashedReads, updates); !valid || err != nil {
return valid, err
}
}
return true, nil
}
func (v *Validator) validateCollHashedReadSet(ns, coll string, kvReadHashes []*kvrwset.KVReadHash,
updates *privacyenabledstate.HashedUpdateBatch) (bool, error) {
for _, kvReadHash := range kvReadHashes {
if valid, err := v.validateKVReadHash(ns, coll, kvReadHash, updates); !valid || err != nil {
return valid, err
}
}
return true, nil
}
// validateKVReadHash performs mvcc check for a hash of a key that is present in the private data space
// i.e., it checks whether a key/version combination is already updated in the statedb (by an already committed block)
// or in the updates (by a preceding valid transaction in the current block)
func (v *Validator) validateKVReadHash(ns, coll string, kvReadHash *kvrwset.KVReadHash,
updates *privacyenabledstate.HashedUpdateBatch) (bool, error) {
if updates.Contains(ns, coll, kvReadHash.KeyHash) {
return false, nil
}
committedVersion, err := v.db.GetKeyHashVersion(ns, coll, kvReadHash.KeyHash)
if err != nil {
return false, err
}
if !version.AreSame(committedVersion, rwsetutil.NewVersion(kvReadHash.Version)) {
logger.Debugf("Version mismatch for key hash [%s:%s:%#v]. Committed version = [%s], Version in hashedReadSet [%s]",
ns, coll, kvReadHash.KeyHash, committedVersion, kvReadHash.Version)
return false, nil
}
return true, nil
}<|fim▁end|> | } |
<|file_name|>pretty-color.js<|end_file_name|><|fim▁begin|><|fim▁hole|> classNames: ['pretty-color'],
attributeBindings: ['style'],
style: function(){
return 'color: ' + this.get('name') + ';';
}.property('name')
});<|fim▁end|> | export default Ember.Component.extend({
|
<|file_name|>plot.py<|end_file_name|><|fim▁begin|><|fim▁hole|>import operator
import h5py
import numpy as np
import matplotlib.pyplot as plt
def get_time_potential_charge_absrbd_on_anode_from_h5( filename ):
h5 = h5py.File( filename, mode="r")
absorbed_charge = h5["/InnerRegions/anode"].attrs["total_absorbed_charge"][0]
time = h5["/TimeGrid"].attrs["current_time"][0]
potential = h5["/InnerRegions/anode"].attrs["potential"][0]
h5.close()
# return( {"time": time,
# "potential": potential,
# "absorbed_charge": absorbed_charge } )
return( (time,
potential,
absorbed_charge ) )
os.chdir("./")
# todo: remove hardcoding
prev_step_filename = "V*_*0900.h5"
last_step_filename = "V*_*1000.h5"
prev_step_vals = []
last_step_vals = []
for f in glob.glob( prev_step_filename ):
prev_step_vals.append( get_time_potential_charge_absrbd_on_anode_from_h5( f ) )
for f in glob.glob( last_step_filename ):
last_step_vals.append( get_time_potential_charge_absrbd_on_anode_from_h5( f ) )
prev_step_vals.sort( key = operator.itemgetter(1) )
last_step_vals.sort( key = operator.itemgetter(1) )
current = []
voltage = []
cgs_to_v = 300
for (t1,V1,q1), (t2,V2,q2) in zip( prev_step_vals, last_step_vals ):
print( t2 - t1, V2 - V1, q2 - q1 )
current.append( abs( ( q2 - q1 ) ) / ( t2 - t1 ) )
voltage.append( V1 * cgs_to_v )
#print( current, voltage )
#A,B = np.polyfit( np.ln( current ), voltage, 1 )
plt.figure()
axes = plt.gca()
axes.set_xlabel( "Voltage [V]" )
axes.set_ylabel( "Current [?]" )
#axes.set_xlim( [0, 1500] )
plt.plot( voltage, current,
linestyle='', marker='o',
label = "Num" )
#plt.plot( current_an, voltage_an,
# label = "An" )
plt.legend()
plt.savefig('diode_VC.png')<|fim▁end|> | import os, glob |
<|file_name|>TestPushNotifications.java<|end_file_name|><|fim▁begin|>import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.stream.Stream;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
<|fim▁hole|>import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import org.daisy.pipeline.client.PipelineClient;
import org.daisy.pipeline.webservice.jaxb.job.Job;
import org.daisy.pipeline.webservice.jaxb.job.JobStatus;
import org.daisy.pipeline.webservice.jaxb.job.Messages;
import org.daisy.pipeline.webservice.jaxb.request.Callback;
import org.daisy.pipeline.webservice.jaxb.request.CallbackType;
import org.daisy.pipeline.webservice.jaxb.request.Input;
import org.daisy.pipeline.webservice.jaxb.request.Item;
import org.daisy.pipeline.webservice.jaxb.request.JobRequest;
import org.daisy.pipeline.webservice.jaxb.request.ObjectFactory;
import org.daisy.pipeline.webservice.jaxb.request.Script;
import org.daisy.pipeline.webservice.jaxb.request.Priority;
import org.junit.Assert;
import org.junit.Test;
public class TestPushNotifications extends Base {
private static final PipelineClient client = newClient(TestClientJobs.CREDS_DEF.clientId, TestClientJobs.CREDS_DEF.secret);
@Override
protected PipelineClient client() {
return client;
}
@Override
protected Properties systemProperties() {
Properties p = super.systemProperties();
// client authentication is required for push notifications
p.setProperty("org.daisy.pipeline.ws.authentication", "true");
p.setProperty("org.daisy.pipeline.ws.authentication.key", TestClientJobs.CREDS_DEF.clientId);
p.setProperty("org.daisy.pipeline.ws.authentication.secret", TestClientJobs.CREDS_DEF.secret);
return p;
}
@Test
public void testPushNotifications() throws Exception {
AbstractCallback testStatusAndMessages = new AbstractCallback() {
JobStatus lastStatus = null;
BigDecimal lastProgress = BigDecimal.ZERO;
Iterator<BigDecimal> mustSee = stream(".25", ".375", ".5", ".55", ".675", ".8", ".9").map(d -> new BigDecimal(d)).iterator();
BigDecimal mustSeeNext = mustSee.next();
List<BigDecimal> seen = new ArrayList<BigDecimal>();
@Override
void handleStatus(JobStatus status) {
lastStatus = status;
}
@Override
void handleMessages(Messages messages) {
BigDecimal progress = messages.getProgress();
if (progress.compareTo(lastProgress) != 0) {
Assert.assertTrue("Progress must be monotonic non-decreasing", progress.compareTo(lastProgress) >= 0);
if (mustSeeNext != null) {
if (progress.compareTo(mustSeeNext) == 0) {
seen.clear();
mustSeeNext = mustSee.hasNext() ? mustSee.next() : null;
} else {
seen.add(progress);
Assert.assertTrue("Expected " + mustSeeNext + " but got " + seen, progress.compareTo(mustSeeNext) < 0);
}
}
lastProgress = progress;
}
}
@Override
void finalTest() {
Assert.assertEquals(JobStatus.SUCCESS, lastStatus);
Assert.assertTrue("Expected " + mustSeeNext + " but got " + seen, mustSeeNext == null);
}
};
HttpServer server; {
server = HttpServer.create(new InetSocketAddress(8080), 0);
server.createContext("/notify", testStatusAndMessages);
server.setExecutor(null);
server.start();
}
try {
JobRequest req; {
ObjectFactory oFactory = new ObjectFactory();
req = oFactory.createJobRequest();
Script script = oFactory.createScript(); {
Optional<String> href = getScriptHref("mock-messages-script");
Assert.assertTrue(href.isPresent());
script.setHref(href.get());
}
req.getScriptOrNicenameOrPriority().add(script);
Input input = oFactory.createInput(); {
Item source = oFactory.createItem();
source.setValue(getResource("hello.xml").toURI().toString());
input.getItem().add(source);
input.setName("source");
}
req.getScriptOrNicenameOrPriority().add(input);
req.getScriptOrNicenameOrPriority().add(oFactory.createNicename("NICE_NAME"));
req.getScriptOrNicenameOrPriority().add(oFactory.createPriority(Priority.LOW));
Callback callback = oFactory.createCallback(); {
callback.setType(CallbackType.MESSAGES);
callback.setHref("http://localhost:8080/notify");
callback.setFrequency("1");
}
req.getScriptOrNicenameOrPriority().add(callback);
callback = oFactory.createCallback(); {
callback.setType(CallbackType.STATUS);
callback.setHref("http://localhost:8080/notify");
callback.setFrequency("1");
}
req.getScriptOrNicenameOrPriority().add(callback);
}
Job job = client().sendJob(req);
deleteAfterTest(job);
waitForStatus(JobStatus.SUCCESS, job, 10000);
// wait until all updates have been pushed
Thread.sleep(1000);
testStatusAndMessages.finalTest();
} finally {
server.stop(1);
}
}
public static abstract class AbstractCallback implements HttpHandler {
abstract void handleStatus(JobStatus status);
abstract void handleMessages(Messages messages);
abstract void finalTest();
@Override
public void handle(HttpExchange t) throws IOException {
Job job; {
try {
job = (Job)JAXBContext.newInstance(Job.class).createUnmarshaller().unmarshal(t.getRequestBody());
} catch (JAXBException e) {
throw new RuntimeException(e);
}
}
handleStatus(job.getStatus());
Optional<Messages> messages = getMessages(job);
if (messages.isPresent())
handleMessages(messages.get());
String response = "got it";
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
static Optional<Messages> getMessages(Job job) {
return Optional.fromNullable(
Iterables.getOnlyElement(
Iterables.filter(
job.getNicenameOrBatchIdOrScript(),
Messages.class),
null));
}
static <T> Stream<T> stream(T... array) {
return Arrays.<T>stream(array);
}
}<|fim▁end|> | import com.google.common.base.Optional;
import com.google.common.collect.Iterables;
|
<|file_name|>framework.go<|end_file_name|><|fim▁begin|>/*
Copyright 2019 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package v1alpha1
import (
"context"<|fim▁hole|> "time"
"k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/util/workqueue"
"k8s.io/klog"
"k8s.io/kubernetes/pkg/scheduler/apis/config"
"k8s.io/kubernetes/pkg/scheduler/internal/cache"
schedutil "k8s.io/kubernetes/pkg/scheduler/util"
)
// framework is the component responsible for initializing and running scheduler
// plugins.
type framework struct {
registry Registry
nodeInfoSnapshot *cache.NodeInfoSnapshot
waitingPods *waitingPodsMap
pluginNameToWeightMap map[string]int
queueSortPlugins []QueueSortPlugin
prefilterPlugins []PrefilterPlugin
filterPlugins []FilterPlugin
scorePlugins []ScorePlugin
reservePlugins []ReservePlugin
prebindPlugins []PrebindPlugin
bindPlugins []BindPlugin
postbindPlugins []PostbindPlugin
unreservePlugins []UnreservePlugin
permitPlugins []PermitPlugin
}
const (
// Specifies the maximum timeout a permit plugin can return.
maxTimeout time.Duration = 15 * time.Minute
)
var _ = Framework(&framework{})
// NewFramework initializes plugins given the configuration and the registry.
func NewFramework(r Registry, plugins *config.Plugins, args []config.PluginConfig) (Framework, error) {
f := &framework{
registry: r,
nodeInfoSnapshot: cache.NewNodeInfoSnapshot(),
pluginNameToWeightMap: make(map[string]int),
waitingPods: newWaitingPodsMap(),
}
if plugins == nil {
return f, nil
}
// get needed plugins from config
pg := pluginsNeeded(plugins)
if len(pg) == 0 {
return f, nil
}
pluginConfig := pluginNameToConfig(args)
pluginsMap := make(map[string]Plugin)
for name, factory := range r {
// initialize only needed plugins
if _, ok := pg[name]; !ok {
continue
}
// find the config args of a plugin
pc := pluginConfig[name]
p, err := factory(pc, f)
if err != nil {
return nil, fmt.Errorf("error initializing plugin %v: %v", name, err)
}
pluginsMap[name] = p
// A weight of zero is not permitted, plugins can be disabled explicitly
// when configured.
f.pluginNameToWeightMap[name] = int(pg[name].Weight)
if f.pluginNameToWeightMap[name] == 0 {
f.pluginNameToWeightMap[name] = 1
}
}
if plugins.PreFilter != nil {
for _, pf := range plugins.PreFilter.Enabled {
if pg, ok := pluginsMap[pf.Name]; ok {
p, ok := pg.(PrefilterPlugin)
if !ok {
return nil, fmt.Errorf("plugin %v does not extend prefilter plugin", pf.Name)
}
f.prefilterPlugins = append(f.prefilterPlugins, p)
} else {
return nil, fmt.Errorf("prefilter plugin %v does not exist", pf.Name)
}
}
}
if plugins.Filter != nil {
for _, r := range plugins.Filter.Enabled {
if pg, ok := pluginsMap[r.Name]; ok {
p, ok := pg.(FilterPlugin)
if !ok {
return nil, fmt.Errorf("plugin %v does not extend filter plugin", r.Name)
}
f.filterPlugins = append(f.filterPlugins, p)
} else {
return nil, fmt.Errorf("filter plugin %v does not exist", r.Name)
}
}
}
if plugins.Score != nil {
for _, sc := range plugins.Score.Enabled {
if pg, ok := pluginsMap[sc.Name]; ok {
p, ok := pg.(ScorePlugin)
if !ok {
return nil, fmt.Errorf("plugin %v does not extend score plugin", sc.Name)
}
if f.pluginNameToWeightMap[p.Name()] == 0 {
return nil, fmt.Errorf("score plugin %v is not configured with weight", p.Name())
}
f.scorePlugins = append(f.scorePlugins, p)
} else {
return nil, fmt.Errorf("score plugin %v does not exist", sc.Name)
}
}
}
if plugins.Reserve != nil {
for _, r := range plugins.Reserve.Enabled {
if pg, ok := pluginsMap[r.Name]; ok {
p, ok := pg.(ReservePlugin)
if !ok {
return nil, fmt.Errorf("plugin %v does not extend reserve plugin", r.Name)
}
f.reservePlugins = append(f.reservePlugins, p)
} else {
return nil, fmt.Errorf("reserve plugin %v does not exist", r.Name)
}
}
}
if plugins.PreBind != nil {
for _, pb := range plugins.PreBind.Enabled {
if pg, ok := pluginsMap[pb.Name]; ok {
p, ok := pg.(PrebindPlugin)
if !ok {
return nil, fmt.Errorf("plugin %v does not extend prebind plugin", pb.Name)
}
f.prebindPlugins = append(f.prebindPlugins, p)
} else {
return nil, fmt.Errorf("prebind plugin %v does not exist", pb.Name)
}
}
}
if plugins.Bind != nil {
for _, pb := range plugins.Bind.Enabled {
if pg, ok := pluginsMap[pb.Name]; ok {
p, ok := pg.(BindPlugin)
if !ok {
return nil, fmt.Errorf("plugin %v does not extend bind plugin", pb.Name)
}
f.bindPlugins = append(f.bindPlugins, p)
} else {
return nil, fmt.Errorf("bind plugin %v does not exist", pb.Name)
}
}
}
if plugins.PostBind != nil {
for _, pb := range plugins.PostBind.Enabled {
if pg, ok := pluginsMap[pb.Name]; ok {
p, ok := pg.(PostbindPlugin)
if !ok {
return nil, fmt.Errorf("plugin %v does not extend postbind plugin", pb.Name)
}
f.postbindPlugins = append(f.postbindPlugins, p)
} else {
return nil, fmt.Errorf("postbind plugin %v does not exist", pb.Name)
}
}
}
if plugins.Unreserve != nil {
for _, ur := range plugins.Unreserve.Enabled {
if pg, ok := pluginsMap[ur.Name]; ok {
p, ok := pg.(UnreservePlugin)
if !ok {
return nil, fmt.Errorf("plugin %v does not extend unreserve plugin", ur.Name)
}
f.unreservePlugins = append(f.unreservePlugins, p)
} else {
return nil, fmt.Errorf("unreserve plugin %v does not exist", ur.Name)
}
}
}
if plugins.Permit != nil {
for _, pr := range plugins.Permit.Enabled {
if pg, ok := pluginsMap[pr.Name]; ok {
p, ok := pg.(PermitPlugin)
if !ok {
return nil, fmt.Errorf("plugin %v does not extend permit plugin", pr.Name)
}
f.permitPlugins = append(f.permitPlugins, p)
} else {
return nil, fmt.Errorf("permit plugin %v does not exist", pr.Name)
}
}
}
if plugins.QueueSort != nil {
for _, qs := range plugins.QueueSort.Enabled {
if pg, ok := pluginsMap[qs.Name]; ok {
p, ok := pg.(QueueSortPlugin)
if !ok {
return nil, fmt.Errorf("plugin %v does not extend queue sort plugin", qs.Name)
}
f.queueSortPlugins = append(f.queueSortPlugins, p)
if len(f.queueSortPlugins) > 1 {
return nil, fmt.Errorf("only one queue sort plugin can be enabled")
}
} else {
return nil, fmt.Errorf("queue sort plugin %v does not exist", qs.Name)
}
}
}
return f, nil
}
// QueueSortFunc returns the function to sort pods in scheduling queue
func (f *framework) QueueSortFunc() LessFunc {
if len(f.queueSortPlugins) == 0 {
return nil
}
// Only one QueueSort plugin can be enabled.
return f.queueSortPlugins[0].Less
}
// RunPrefilterPlugins runs the set of configured prefilter plugins. It returns
// *Status and its code is set to non-success if any of the plugins returns
// anything but Success. If a non-success status is returned, then the scheduling
// cycle is aborted.
func (f *framework) RunPrefilterPlugins(
pc *PluginContext, pod *v1.Pod) *Status {
for _, pl := range f.prefilterPlugins {
status := pl.Prefilter(pc, pod)
if !status.IsSuccess() {
if status.Code() == Unschedulable {
msg := fmt.Sprintf("rejected by %v at prefilter: %v", pl.Name(), status.Message())
klog.V(4).Infof(msg)
return NewStatus(status.Code(), msg)
}
msg := fmt.Sprintf("error while running %v prefilter plugin for pod %v: %v", pl.Name(), pod.Name, status.Message())
klog.Error(msg)
return NewStatus(Error, msg)
}
}
return nil
}
// RunFilterPlugins runs the set of configured Filter plugins for pod on
// the given node. If any of these plugins doesn't return "Success", the
// given node is not suitable for running pod.
// Meanwhile, the failure message and status are set for the given node.
func (f *framework) RunFilterPlugins(pc *PluginContext,
pod *v1.Pod, nodeName string) *Status {
for _, p := range f.filterPlugins {
status := p.Filter(pc, pod, nodeName)
if !status.IsSuccess() {
if status.Code() != Unschedulable {
errMsg := fmt.Sprintf("RunFilterPlugins: error while running %s filter plugin for pod %s: %s",
p.Name(), pod.Name, status.Message())
klog.Error(errMsg)
return NewStatus(Error, errMsg)
}
return status
}
}
return nil
}
// RunScorePlugins runs the set of configured scoring plugins. It returns a map that
// stores for each scoring plugin name the corresponding NodeScoreList(s).
// It also returns *Status, which is set to non-success if any of the plugins returns
// a non-success status.
func (f *framework) RunScorePlugins(pc *PluginContext, pod *v1.Pod, nodes []*v1.Node) (PluginToNodeScoreMap, *Status) {
pluginToNodeScoreMap := make(PluginToNodeScoreMap, len(f.scorePlugins))
for _, pl := range f.scorePlugins {
pluginToNodeScoreMap[pl.Name()] = make(NodeScoreList, len(nodes))
}
ctx, cancel := context.WithCancel(context.Background())
errCh := schedutil.NewErrorChannel()
workqueue.ParallelizeUntil(ctx, 16, len(nodes), func(index int) {
for _, pl := range f.scorePlugins {
// Score plugins' weight has been checked when they are initialized.
weight := f.pluginNameToWeightMap[pl.Name()]
score, status := pl.Score(pc, pod, nodes[index].Name)
if !status.IsSuccess() {
errCh.SendErrorWithCancel(fmt.Errorf(status.Message()), cancel)
return
}
pluginToNodeScoreMap[pl.Name()][index] = score * weight
}
})
if err := errCh.ReceiveError(); err != nil {
msg := fmt.Sprintf("error while running score plugin for pod %v: %v", pod.Name, err)
klog.Error(msg)
return nil, NewStatus(Error, msg)
}
return pluginToNodeScoreMap, nil
}
// RunPrebindPlugins runs the set of configured prebind plugins. It returns a
// failure (bool) if any of the plugins returns an error. It also returns an
// error containing the rejection message or the error occurred in the plugin.
func (f *framework) RunPrebindPlugins(
pc *PluginContext, pod *v1.Pod, nodeName string) *Status {
for _, pl := range f.prebindPlugins {
status := pl.Prebind(pc, pod, nodeName)
if !status.IsSuccess() {
if status.Code() == Unschedulable {
msg := fmt.Sprintf("rejected by %v at prebind: %v", pl.Name(), status.Message())
klog.V(4).Infof(msg)
return NewStatus(status.Code(), msg)
}
msg := fmt.Sprintf("error while running %v prebind plugin for pod %v: %v", pl.Name(), pod.Name, status.Message())
klog.Error(msg)
return NewStatus(Error, msg)
}
}
return nil
}
// RunBindPlugins runs the set of configured bind plugins until one returns a non `Skip` status.
func (f *framework) RunBindPlugins(pc *PluginContext, pod *v1.Pod, nodeName string) *Status {
if len(f.bindPlugins) == 0 {
return NewStatus(Skip, "")
}
var status *Status
for _, bp := range f.bindPlugins {
status = bp.Bind(pc, pod, nodeName)
if status != nil && status.Code() == Skip {
continue
}
if !status.IsSuccess() {
msg := fmt.Sprintf("bind plugin %v failed to bind pod %v/%v: %v", bp.Name(), pod.Namespace, pod.Name, status.Message())
klog.Error(msg)
return NewStatus(Error, msg)
}
return status
}
return status
}
// RunPostbindPlugins runs the set of configured postbind plugins.
func (f *framework) RunPostbindPlugins(
pc *PluginContext, pod *v1.Pod, nodeName string) {
for _, pl := range f.postbindPlugins {
pl.Postbind(pc, pod, nodeName)
}
}
// RunReservePlugins runs the set of configured reserve plugins. If any of these
// plugins returns an error, it does not continue running the remaining ones and
// returns the error. In such case, pod will not be scheduled.
func (f *framework) RunReservePlugins(
pc *PluginContext, pod *v1.Pod, nodeName string) *Status {
for _, pl := range f.reservePlugins {
status := pl.Reserve(pc, pod, nodeName)
if !status.IsSuccess() {
msg := fmt.Sprintf("error while running %v reserve plugin for pod %v: %v", pl.Name(), pod.Name, status.Message())
klog.Error(msg)
return NewStatus(Error, msg)
}
}
return nil
}
// RunUnreservePlugins runs the set of configured unreserve plugins.
func (f *framework) RunUnreservePlugins(
pc *PluginContext, pod *v1.Pod, nodeName string) {
for _, pl := range f.unreservePlugins {
pl.Unreserve(pc, pod, nodeName)
}
}
// RunPermitPlugins runs the set of configured permit plugins. If any of these
// plugins returns a status other than "Success" or "Wait", it does not continue
// running the remaining plugins and returns an error. Otherwise, if any of the
// plugins returns "Wait", then this function will block for the timeout period
// returned by the plugin, if the time expires, then it will return an error.
// Note that if multiple plugins asked to wait, then we wait for the minimum
// timeout duration.
func (f *framework) RunPermitPlugins(
pc *PluginContext, pod *v1.Pod, nodeName string) *Status {
timeout := maxTimeout
statusCode := Success
for _, pl := range f.permitPlugins {
status, d := pl.Permit(pc, pod, nodeName)
if !status.IsSuccess() {
if status.Code() == Unschedulable {
msg := fmt.Sprintf("rejected by %v at permit: %v", pl.Name(), status.Message())
klog.V(4).Infof(msg)
return NewStatus(status.Code(), msg)
}
if status.Code() == Wait {
// Use the minimum timeout duration.
if timeout > d {
timeout = d
}
statusCode = Wait
} else {
msg := fmt.Sprintf("error while running %v permit plugin for pod %v: %v", pl.Name(), pod.Name, status.Message())
klog.Error(msg)
return NewStatus(Error, msg)
}
}
}
// We now wait for the minimum duration if at least one plugin asked to
// wait (and no plugin rejected the pod)
if statusCode == Wait {
w := newWaitingPod(pod)
f.waitingPods.add(w)
defer f.waitingPods.remove(pod.UID)
timer := time.NewTimer(timeout)
klog.V(4).Infof("waiting for %v for pod %v at permit", timeout, pod.Name)
select {
case <-timer.C:
msg := fmt.Sprintf("pod %v rejected due to timeout after waiting %v at permit", pod.Name, timeout)
klog.V(4).Infof(msg)
return NewStatus(Unschedulable, msg)
case s := <-w.s:
if !s.IsSuccess() {
if s.Code() == Unschedulable {
msg := fmt.Sprintf("rejected while waiting at permit: %v", s.Message())
klog.V(4).Infof(msg)
return NewStatus(s.Code(), msg)
}
msg := fmt.Sprintf("error received while waiting at permit for pod %v: %v", pod.Name, s.Message())
klog.Error(msg)
return NewStatus(Error, msg)
}
}
}
return nil
}
// NodeInfoSnapshot returns the latest NodeInfo snapshot. The snapshot
// is taken at the beginning of a scheduling cycle and remains unchanged until a
// pod finishes "Reserve". There is no guarantee that the information remains
// unchanged after "Reserve".
func (f *framework) NodeInfoSnapshot() *cache.NodeInfoSnapshot {
return f.nodeInfoSnapshot
}
// IterateOverWaitingPods acquires a read lock and iterates over the WaitingPods map.
func (f *framework) IterateOverWaitingPods(callback func(WaitingPod)) {
f.waitingPods.iterate(callback)
}
// GetWaitingPod returns a reference to a WaitingPod given its UID.
func (f *framework) GetWaitingPod(uid types.UID) WaitingPod {
return f.waitingPods.get(uid)
}
func pluginNameToConfig(args []config.PluginConfig) map[string]*runtime.Unknown {
pc := make(map[string]*runtime.Unknown, 0)
for _, p := range args {
pc[p.Name] = &p.Args
}
return pc
}
func pluginsNeeded(plugins *config.Plugins) map[string]config.Plugin {
pgMap := make(map[string]config.Plugin, 0)
if plugins == nil {
return pgMap
}
find := func(pgs *config.PluginSet) {
if pgs == nil {
return
}
for _, pg := range pgs.Enabled {
pgMap[pg.Name] = pg
}
}
find(plugins.QueueSort)
find(plugins.PreFilter)
find(plugins.Filter)
find(plugins.PostFilter)
find(plugins.Score)
find(plugins.NormalizeScore)
find(plugins.Reserve)
find(plugins.Permit)
find(plugins.PreBind)
find(plugins.Bind)
find(plugins.PostBind)
find(plugins.Unreserve)
return pgMap
}<|fim▁end|> | "fmt" |
<|file_name|>bytecode.rs<|end_file_name|><|fim▁begin|>use ein_syntax::ast::{BinaryOp, Expr, Stmt, UnaryOp};
use crate::Value;
#[derive(Debug)]
pub enum Instruction {
// Stack control
Return,
Pop,
// Loads
LoadNil,
LoadTrue,
LoadFalse,
LoadConstant(u8),
LoadGlobal(u8),
// Stores
DefineGlobal(u8),
StoreGlobal(u8),
// Jumps
Jump(u8),
JumpIfTrue(u8),
JumpIfFalse(u8),
Loop(u8),
// Operators
Add,
Subtract,
Multiply,
Divide,
Negate,
}
pub trait Emit {
fn emit(&self, chunk: &mut Chunk);
}
impl Emit for Expr {
fn emit(&self, chunk: &mut Chunk) {
match self {
Expr::Nil => {
chunk.add_instruction(Instruction::LoadNil);
}
Expr::Identifier(name) => {
let constant = chunk.add_constant(Value::String(name.clone()));
chunk.add_instruction(Instruction::LoadGlobal(constant));
}
Expr::NumberLiteral(v) => {
let constant = chunk.add_constant(Value::Number(*v));
chunk.add_instruction(Instruction::LoadConstant(constant));
}
Expr::StringLiteral(v) => {
let constant = chunk.add_constant(Value::String(v.clone()));
chunk.add_instruction(Instruction::LoadConstant(constant));
}
Expr::BooleanLiteral(v) => {
chunk.add_instruction(if *v {
Instruction::LoadTrue
} else {
Instruction::LoadFalse
});
}
Expr::Assign(name, value) => {
value.emit(chunk);
let constant = chunk.add_constant(Value::String(name.clone()));
chunk.add_instruction(Instruction::StoreGlobal(constant));
}
Expr::Function(_, _) => unimplemented!(),
Expr::Call(_, _) => unimplemented!(),
Expr::UnaryOp(op, val) => {
val.emit(chunk);
chunk.add_instruction(match op {
UnaryOp::Not => unimplemented!(),
UnaryOp::UnaryMinus => Instruction::Negate,
});
}
Expr::BinaryOp(op, lhs, rhs) => match op {
BinaryOp::And => {
lhs.emit(chunk);
let jump = chunk.add_instruction(Instruction::JumpIfFalse(0));
chunk.add_instruction(Instruction::Pop);
rhs.emit(chunk);
chunk.patch_jump(jump);
}
BinaryOp::Or => {
lhs.emit(chunk);
let jump = chunk.add_instruction(Instruction::JumpIfTrue(0));
chunk.add_instruction(Instruction::Pop);
rhs.emit(chunk);
chunk.patch_jump(jump)
}
BinaryOp::Equals => unimplemented!(),
BinaryOp::NotEquals => unimplemented!(),
BinaryOp::GreaterThan => unimplemented!(),
BinaryOp::GreaterEquals => unimplemented!(),
BinaryOp::LessThan => unimplemented!(),
BinaryOp::LessEquals => unimplemented!(),
BinaryOp::Add => {
lhs.emit(chunk);
rhs.emit(chunk);
chunk.add_instruction(Instruction::Add);
}
BinaryOp::Subtract => {
lhs.emit(chunk);
rhs.emit(chunk);
chunk.add_instruction(Instruction::Subtract);
}
BinaryOp::Multiply => {
lhs.emit(chunk);
rhs.emit(chunk);
chunk.add_instruction(Instruction::Multiply);
}
BinaryOp::Divide => {<|fim▁hole|> },
}
}
}
impl Emit for Stmt {
fn emit(&self, chunk: &mut Chunk) {
match self {
Stmt::Return(_) => unimplemented!(),
Stmt::ExprStmt(e) => {
e.emit(chunk);
chunk.add_instruction(Instruction::Pop);
}
Stmt::Declaration(name, value) => {
value.emit(chunk);
let constant = chunk.add_constant(Value::String(name.clone()));
chunk.add_instruction(Instruction::DefineGlobal(constant));
}
Stmt::If(condition, when_true, when_false) => {
condition.emit(chunk);
let else_jump = chunk.add_instruction(Instruction::JumpIfFalse(0));
chunk.add_instruction(Instruction::Pop);
when_true.emit(chunk);
let then_jump = chunk.add_instruction(Instruction::Jump(0));
chunk.patch_jump(else_jump);
chunk.add_instruction(Instruction::Pop);
when_false.emit(chunk);
chunk.patch_jump(then_jump);
}
Stmt::While(condition, body) => {
let loop_start = chunk.next_instruction();
condition.emit(chunk);
let exit_jump = chunk.add_instruction(Instruction::JumpIfFalse(0));
chunk.add_instruction(Instruction::Pop);
body.emit(chunk);
chunk.emit_loop(loop_start);
chunk.patch_jump(exit_jump);
chunk.add_instruction(Instruction::Pop);
}
Stmt::Block(_) => unimplemented!(),
}
}
}
impl Emit for Vec<Stmt> {
fn emit(&self, chunk: &mut Chunk) {
for stmt in self {
stmt.emit(chunk)
}
}
}
#[derive(Debug)]
pub struct Chunk {
constants: Vec<Value>,
instructions: Vec<Instruction>,
}
impl Chunk {
pub fn new() -> Chunk {
Chunk {
constants: vec![],
instructions: vec![],
}
}
pub fn add_instruction(&mut self, instruction: Instruction) -> usize {
let i = self.instructions.len();
self.instructions.push(instruction);
i
}
pub fn get_instruction(&self, addr: usize) -> &Instruction {
&self.instructions[addr]
}
pub fn get_instruction_mut(&mut self, addr: usize) -> &mut Instruction {
&mut self.instructions[addr]
}
pub fn set_instruction(&mut self, addr: usize, instruction: Instruction) {
self.instructions[addr] = instruction;
}
pub fn prev_instruction(&self) -> usize {
self.instructions.len() - 1
}
pub fn next_instruction(&self) -> usize {
self.instructions.len()
}
pub fn patch_jump(&mut self, addr: usize) {
let next = self.next_instruction();
match self.get_instruction_mut(addr) {
Instruction::Jump(old)
| Instruction::JumpIfTrue(old)
| Instruction::JumpIfFalse(old) => {
*old = (next - addr) as u8 - 1;
}
other => panic!("{:?} is not a jump instruction", other),
}
}
pub fn emit_loop(&mut self, target: usize) {
let next = self.next_instruction();
self.add_instruction(Instruction::Loop((next - target) as u8 + 1));
}
pub fn add_constant(&mut self, value: Value) -> u8 {
let i = self.constants.len();
if i >= u8::max_value() as usize {
panic!("Chunks cannot contain more than 255 constants.");
}
self.constants.push(value);
i as u8
}
pub fn get_constant(&self, idx: u8) -> &Value {
&self.constants[idx as usize]
}
pub fn emit<T>(&mut self, node: &T)
where
T: Emit,
{
node.emit(self)
}
}<|fim▁end|> | lhs.emit(chunk);
rhs.emit(chunk);
chunk.add_instruction(Instruction::Divide);
} |
<|file_name|>qgsstylemanagerdialog.cpp<|end_file_name|><|fim▁begin|>/***************************************************************************
qgsstylemanagerdialog.cpp
---------------------
begin : November 2009
copyright : (C) 2009 by Martin Dobias
email : wonder dot sk at gmail dot com
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "qgsstylemanagerdialog.h"
#include "qgsstylesavedialog.h"
#include "qgsstyle.h"
#include "qgssymbol.h"
#include "qgssymbollayerutils.h"
#include "qgscolorramp.h"
#include "qgssymbolselectordialog.h"
#include "qgsgradientcolorrampdialog.h"
#include "qgslimitedrandomcolorrampdialog.h"
#include "qgscolorbrewercolorrampdialog.h"
#include "qgspresetcolorrampdialog.h"
#include "qgscptcitycolorrampdialog.h"
#include "qgsstyleexportimportdialog.h"
#include "qgssmartgroupeditordialog.h"
#include "qgssettings.h"
#include <QAction>
#include <QFile>
#include <QFileDialog>
#include <QInputDialog>
#include <QMessageBox>
#include <QPushButton>
#include <QStandardItemModel>
#include <QMenu>
#include "qgsapplication.h"
#include "qgslogger.h"
QgsStyleManagerDialog::QgsStyleManagerDialog( QgsStyle *style, QWidget *parent )
: QDialog( parent )
, mStyle( style )
, mModified( false )
{
setupUi( this );
connect( tabItemType, &QTabWidget::currentChanged, this, &QgsStyleManagerDialog::tabItemType_currentChanged );
connect( buttonBox, &QDialogButtonBox::helpRequested, this, &QgsStyleManagerDialog::showHelp );
connect( buttonBox, &QDialogButtonBox::rejected, this, &QgsStyleManagerDialog::onClose );
#ifdef Q_OS_MAC
setWindowModality( Qt::WindowModal );
#endif
QgsSettings settings;
restoreGeometry( settings.value( QStringLiteral( "Windows/StyleV2Manager/geometry" ) ).toByteArray() );
mSplitter->setSizes( QList<int>() << 170 << 540 );
mSplitter->restoreState( settings.value( QStringLiteral( "Windows/StyleV2Manager/splitter" ) ).toByteArray() );
tabItemType->setDocumentMode( true );
searchBox->setPlaceholderText( trUtf8( "Filter symbols…" ) );
connect( this, &QDialog::finished, this, &QgsStyleManagerDialog::onFinished );
connect( listItems, &QAbstractItemView::doubleClicked, this, &QgsStyleManagerDialog::editItem );
connect( btnAddItem, &QPushButton::clicked, this, [ = ]( bool ) { addItem(); }
);
connect( btnEditItem, &QPushButton::clicked, this, [ = ]( bool ) { editItem(); }
);
connect( actnEditItem, &QAction::triggered, this, [ = ]( bool ) { editItem(); }
);
connect( btnRemoveItem, &QPushButton::clicked, this, [ = ]( bool ) { removeItem(); }
);
connect( actnRemoveItem, &QAction::triggered, this, [ = ]( bool ) { removeItem(); }
);
QMenu *shareMenu = new QMenu( tr( "Share menu" ), this );
QAction *exportAction = new QAction( tr( "Export symbol(s)…" ), this );
exportAction->setIcon( QIcon( QgsApplication::iconPath( "mActionFileSave.svg" ) ) );
shareMenu->addAction( exportAction );
QAction *importAction = new QAction( tr( "Import symbol(s)…" ), this );
importAction->setIcon( QIcon( QgsApplication::iconPath( "mActionFileOpen.svg" ) ) );
shareMenu->addAction( importAction );
shareMenu->addSeparator();
shareMenu->addAction( actnExportAsPNG );
shareMenu->addAction( actnExportAsSVG );
connect( actnExportAsPNG, &QAction::triggered, this, &QgsStyleManagerDialog::exportItemsPNG );
connect( actnExportAsSVG, &QAction::triggered, this, &QgsStyleManagerDialog::exportItemsSVG );
connect( exportAction, &QAction::triggered, this, &QgsStyleManagerDialog::exportItems );
connect( importAction, &QAction::triggered, this, &QgsStyleManagerDialog::importItems );
btnShare->setMenu( shareMenu );
// Set editing mode off by default
mGrouppingMode = false;
QStandardItemModel *model = new QStandardItemModel( listItems );
listItems->setModel( model );
listItems->setSelectionMode( QAbstractItemView::ExtendedSelection );
connect( model, &QStandardItemModel::itemChanged, this, &QgsStyleManagerDialog::itemChanged );
connect( listItems->selectionModel(), &QItemSelectionModel::currentChanged,
this, &QgsStyleManagerDialog::symbolSelected );
connect( listItems->selectionModel(), &QItemSelectionModel::selectionChanged,
this, &QgsStyleManagerDialog::selectedSymbolsChanged );
populateTypes();
QStandardItemModel *groupModel = new QStandardItemModel( groupTree );
groupTree->setModel( groupModel );
groupTree->setHeaderHidden( true );
populateGroups();
groupTree->setCurrentIndex( groupTree->model()->index( 0, 0 ) );
connect( groupTree->selectionModel(), &QItemSelectionModel::currentChanged,
this, &QgsStyleManagerDialog::groupChanged );
connect( groupModel, &QStandardItemModel::itemChanged,
this, &QgsStyleManagerDialog::groupRenamed );
QMenu *groupMenu = new QMenu( tr( "Group actions" ), this );
connect( actnTagSymbols, &QAction::triggered, this, &QgsStyleManagerDialog::tagSymbolsAction );
groupMenu->addAction( actnTagSymbols );
connect( actnFinishTagging, &QAction::triggered, this, &QgsStyleManagerDialog::tagSymbolsAction );
actnFinishTagging->setVisible( false );
groupMenu->addAction( actnFinishTagging );
groupMenu->addAction( actnEditSmartGroup );
btnManageGroups->setMenu( groupMenu );
connect( searchBox, &QLineEdit::textChanged, this, &QgsStyleManagerDialog::filterSymbols );
// Context menu for groupTree
groupTree->setContextMenuPolicy( Qt::CustomContextMenu );
connect( groupTree, &QWidget::customContextMenuRequested,
this, &QgsStyleManagerDialog::grouptreeContextMenu );
// Context menu for listItems
listItems->setContextMenuPolicy( Qt::CustomContextMenu );
connect( listItems, &QWidget::customContextMenuRequested,
this, &QgsStyleManagerDialog::listitemsContextMenu );
// Menu for the "Add item" toolbutton when in colorramp mode
QStringList rampTypes;
rampTypes << tr( "Gradient" ) << tr( "Color presets" ) << tr( "Random" ) << tr( "Catalog: cpt-city" );
rampTypes << tr( "Catalog: ColorBrewer" );
mMenuBtnAddItemColorRamp = new QMenu( this );
Q_FOREACH ( const QString &rampType, rampTypes )
mMenuBtnAddItemColorRamp->addAction( new QAction( rampType, this ) );
connect( mMenuBtnAddItemColorRamp, &QMenu::triggered,
this, static_cast<bool ( QgsStyleManagerDialog::* )( QAction * )>( &QgsStyleManagerDialog::addColorRamp ) );
// Context menu for symbols/colorramps. The menu entries for every group are created when displaying the menu.
mGroupMenu = new QMenu( this );
connect( actnAddFavorite, &QAction::triggered, this, &QgsStyleManagerDialog::addFavoriteSelectedSymbols );
mGroupMenu->addAction( actnAddFavorite );
connect( actnRemoveFavorite, &QAction::triggered, this, &QgsStyleManagerDialog::removeFavoriteSelectedSymbols );
mGroupMenu->addAction( actnRemoveFavorite );
mGroupMenu->addSeparator()->setParent( this );
mGroupListMenu = new QMenu( mGroupMenu );
mGroupListMenu->setTitle( tr( "Add to tag" ) );
mGroupListMenu->setEnabled( false );
mGroupMenu->addMenu( mGroupListMenu );
actnDetag->setData( 0 );
connect( actnDetag, &QAction::triggered, this, &QgsStyleManagerDialog::detagSelectedSymbols );
mGroupMenu->addAction( actnDetag );
mGroupMenu->addSeparator()->setParent( this );
mGroupMenu->addAction( actnRemoveItem );
mGroupMenu->addAction( actnEditItem );
mGroupMenu->addSeparator()->setParent( this );
mGroupMenu->addAction( actnExportAsPNG );
mGroupMenu->addAction( actnExportAsSVG );
// Context menu for the group tree
mGroupTreeContextMenu = new QMenu( this );
connect( actnEditSmartGroup, &QAction::triggered, this, &QgsStyleManagerDialog::editSmartgroupAction );
mGroupTreeContextMenu->addAction( actnEditSmartGroup );
connect( actnAddTag, &QAction::triggered, this, [ = ]( bool ) { addTag(); }
);
mGroupTreeContextMenu->addAction( actnAddTag );
connect( actnAddSmartgroup, &QAction::triggered, this, [ = ]( bool ) { addSmartgroup(); }
);
mGroupTreeContextMenu->addAction( actnAddSmartgroup );
connect( actnRemoveGroup, &QAction::triggered, this, &QgsStyleManagerDialog::removeGroup );
mGroupTreeContextMenu->addAction( actnRemoveGroup );
tabItemType_currentChanged( 0 );
}
void QgsStyleManagerDialog::onFinished()
{
if ( mModified )
{
mStyle->save();
}
QgsSettings settings;
settings.setValue( QStringLiteral( "Windows/StyleV2Manager/geometry" ), saveGeometry() );
settings.setValue( QStringLiteral( "Windows/StyleV2Manager/splitter" ), mSplitter->saveState() );
}
void QgsStyleManagerDialog::populateTypes()
{
#if 0
// save current selection index in types combo
int current = ( tabItemType->count() > 0 ? tabItemType->currentIndex() : 0 );
// no counting of style items
int markerCount = 0, lineCount = 0, fillCount = 0;
QStringList symbolNames = mStyle->symbolNames();
for ( int i = 0; i < symbolNames.count(); ++i )
{
switch ( mStyle->symbolRef( symbolNames[i] )->type() )
{
case QgsSymbol::Marker:
markerCount++;
break;
case QgsSymbol::Line:
lineCount++;
break;
case QgsSymbol::Fill:
fillCount++;
break;
default:
Q_ASSERT( 0 && "unknown symbol type" );
break;
}
}
cboItemType->clear();
cboItemType->addItem( tr( "Marker symbol (%1)" ).arg( markerCount ), QVariant( QgsSymbol::Marker ) );
cboItemType->addItem( tr( "Line symbol (%1)" ).arg( lineCount ), QVariant( QgsSymbol::Line ) );
cboItemType->addItem( tr( "Fill symbol (%1)" ).arg( fillCount ), QVariant( QgsSymbol::Fill ) );
cboItemType->addItem( tr( "Color ramp (%1)" ).arg( mStyle->colorRampCount() ), QVariant( 3 ) );
// update current index to previous selection
cboItemType->setCurrentIndex( current );
#endif
}
void QgsStyleManagerDialog::tabItemType_currentChanged( int )
{
// when in Color Ramp tab, add menu to add item button and hide "Export symbols as PNG/SVG"
bool flag = currentItemType() != 3;
searchBox->setPlaceholderText( flag ? trUtf8( "Filter symbols…" ) : trUtf8( "Filter color ramps…" ) );
btnAddItem->setMenu( flag ? nullptr : mMenuBtnAddItemColorRamp );
actnExportAsPNG->setVisible( flag );
actnExportAsSVG->setVisible( flag );
listItems->setIconSize( QSize( 100, 90 ) );
listItems->setGridSize( QSize( 120, 110 ) );
populateList();
}
void QgsStyleManagerDialog::populateList()
{
if ( currentItemType() > 3 )
{
Q_ASSERT( false && "not implemented" );
return;
}
groupChanged( groupTree->selectionModel()->currentIndex() );
}
void QgsStyleManagerDialog::populateSymbols( const QStringList &symbolNames, bool check )
{
QStandardItemModel *model = qobject_cast<QStandardItemModel *>( listItems->model() );
model->clear();
int type = currentItemType();
for ( int i = 0; i < symbolNames.count(); ++i )
{
QString name = symbolNames[i];
QgsSymbol *symbol = mStyle->symbol( name );
if ( symbol && symbol->type() == type )
{
QStringList tags = mStyle->tagsOfSymbol( QgsStyle::SymbolEntity, name );
QStandardItem *item = new QStandardItem( name );
QIcon icon = QgsSymbolLayerUtils::symbolPreviewIcon( symbol, listItems->iconSize(), 18 );
item->setIcon( icon );
item->setData( name ); // used to find out original name when user edited the name
item->setCheckable( check );
item->setToolTip( QStringLiteral( "<b>%1</b><br><i>%2</i>" ).arg( name, tags.count() > 0 ? tags.join( QStringLiteral( ", " ) ) : tr( "Not tagged" ) ) );
// add to model
model->appendRow( item );
}
delete symbol;
}
selectedSymbolsChanged( QItemSelection(), QItemSelection() );
symbolSelected( listItems->currentIndex() );
}
void QgsStyleManagerDialog::populateColorRamps( const QStringList &colorRamps, bool check )
{
QStandardItemModel *model = qobject_cast<QStandardItemModel *>( listItems->model() );
model->clear();
for ( int i = 0; i < colorRamps.count(); ++i )
{
QString name = colorRamps[i];
std::unique_ptr< QgsColorRamp > ramp( mStyle->colorRamp( name ) );
QStandardItem *item = new QStandardItem( name );
QIcon icon = QgsSymbolLayerUtils::colorRampPreviewIcon( ramp.get(), listItems->iconSize(), 18 );
item->setIcon( icon );
item->setData( name ); // used to find out original name when user edited the name
item->setCheckable( check );
item->setToolTip( name );
model->appendRow( item );
}
selectedSymbolsChanged( QItemSelection(), QItemSelection() );
symbolSelected( listItems->currentIndex() );
}
int QgsStyleManagerDialog::currentItemType()
{
switch ( tabItemType->currentIndex() )
{
case 0:
return QgsSymbol::Marker;
case 1:
return QgsSymbol::Line;
case 2:
return QgsSymbol::Fill;
case 3:
return 3;
default:
return 0;
}
}
QString QgsStyleManagerDialog::currentItemName()
{
QModelIndex index = listItems->selectionModel()->currentIndex();
if ( !index.isValid() )
return QString();
return index.model()->data( index, 0 ).toString();
}
void QgsStyleManagerDialog::addItem()
{
bool changed = false;
if ( currentItemType() < 3 )
{
changed = addSymbol();
}
else if ( currentItemType() == 3 )
{
changed = addColorRamp();
}
else
{
Q_ASSERT( false && "not implemented" );
}
if ( changed )
{
populateList();
populateTypes();
}
}
bool QgsStyleManagerDialog::addSymbol()
{
// create new symbol with current type
QgsSymbol *symbol = nullptr;
QString name = tr( "new symbol" );
switch ( currentItemType() )
{
case QgsSymbol::Marker:
symbol = new QgsMarkerSymbol();
name = tr( "new marker" );
break;
case QgsSymbol::Line:
symbol = new QgsLineSymbol();
name = tr( "new line" );
break;
case QgsSymbol::Fill:
symbol = new QgsFillSymbol();
name = tr( "new fill symbol" );
break;
default:
Q_ASSERT( false && "unknown symbol type" );
return false;
}
// get symbol design
// NOTE : Set the parent widget as "this" to notify the Symbol selector
// that, it is being called by Style Manager, so recursive calling
// of style manager and symbol selector can be arrested
// See also: editSymbol()
QgsSymbolSelectorDialog dlg( symbol, mStyle, nullptr, this );
if ( dlg.exec() == 0 )
{
delete symbol;
return false;
}
QgsStyleSaveDialog saveDlg( this );
if ( !saveDlg.exec() )
{
delete symbol;
return false;
}
name = saveDlg.name();
// request valid/unique name
bool nameInvalid = true;
while ( nameInvalid )
{
// validate name
if ( name.isEmpty() )
{
QMessageBox::warning( this, tr( "Save symbol" ),
tr( "Cannot save symbol without name. Enter a name." ) );
}
else if ( mStyle->symbolNames().contains( name ) )
{
int res = QMessageBox::warning( this, tr( "Save symbol" ),
tr( "Symbol with name '%1' already exists. Overwrite?" )
.arg( name ),
QMessageBox::Yes | QMessageBox::No );
if ( res == QMessageBox::Yes )
{
mStyle->removeSymbol( name );
nameInvalid = false;
}
}
else
{
// valid name
nameInvalid = false;
}
if ( nameInvalid )
{
bool ok;
name = QInputDialog::getText( this, tr( "Symbol Name" ),
tr( "Please enter a name for new symbol:" ),
QLineEdit::Normal, name, &ok );
if ( !ok )
{
delete symbol;
return false;
}
}
}
QStringList symbolTags = saveDlg.tags().split( ',' );
// add new symbol to style and re-populate the list
mStyle->addSymbol( name, symbol );
mStyle->saveSymbol( name, symbol, saveDlg.isFavorite(), symbolTags );
mModified = true;
return true;
}
QString QgsStyleManagerDialog::addColorRampStatic( QWidget *parent, QgsStyle *style, QString rampType )
{
// let the user choose the color ramp type if rampType is not given
bool ok = true;
if ( rampType.isEmpty() )
{
QStringList rampTypes;
rampTypes << tr( "Gradient" ) << tr( "Color presets" ) << tr( "Random" ) << tr( "Catalog: cpt-city" );
rampTypes << tr( "Catalog: ColorBrewer" );
rampType = QInputDialog::getItem( parent, tr( "Color ramp type" ),
tr( "Please select color ramp type:" ), rampTypes, 0, false, &ok );
}
if ( !ok || rampType.isEmpty() )
return QString();
QString name = tr( "new ramp" );
std::unique_ptr< QgsColorRamp > ramp;
if ( rampType == tr( "Gradient" ) )
{
QgsGradientColorRampDialog dlg( QgsGradientColorRamp(), parent );
if ( !dlg.exec() )
{
return QString();
}
ramp.reset( dlg.ramp().clone() );
name = tr( "new gradient ramp" );
}
else if ( rampType == tr( "Random" ) )
{
QgsLimitedRandomColorRampDialog dlg( QgsLimitedRandomColorRamp(), parent );
if ( !dlg.exec() )
{
return QString();
}
ramp.reset( dlg.ramp().clone() );
name = tr( "new random ramp" );
}
else if ( rampType == tr( "Catalog: ColorBrewer" ) )
{
QgsColorBrewerColorRampDialog dlg( QgsColorBrewerColorRamp(), parent );
if ( !dlg.exec() )
{
return QString();
}
ramp.reset( dlg.ramp().clone() );
name = dlg.ramp().schemeName() + QString::number( dlg.ramp().colors() );
}
else if ( rampType == tr( "Color presets" ) )
{
QgsPresetColorRampDialog dlg( QgsPresetSchemeColorRamp(), parent );
if ( !dlg.exec() )
{
return QString();
}
ramp.reset( dlg.ramp().clone() );
name = tr( "new preset ramp" );
}
else if ( rampType == tr( "Catalog: cpt-city" ) )
{
QgsCptCityColorRampDialog dlg( QgsCptCityColorRamp( QLatin1String( "" ), QLatin1String( "" ) ), parent );
if ( !dlg.exec() )
{
return QString();
}
// name = dlg.selectedName();
name = QFileInfo( dlg.ramp().schemeName() ).baseName() + dlg.ramp().variantName();
if ( dlg.saveAsGradientRamp() )
{
ramp.reset( dlg.ramp().cloneGradientRamp() );
}
else
{
ramp.reset( dlg.ramp().clone() );
}
}
else
{
// Q_ASSERT( 0 && "invalid ramp type" );
// bailing out is rather harsh!
QgsDebugMsg( "invalid ramp type " + rampType );
return QString();
}
QgsStyleSaveDialog saveDlg( parent, QgsStyle::ColorrampEntity );
if ( !saveDlg.exec() )
{
return QString();
}
name = saveDlg.name();
// get valid/unique name
bool nameInvalid = true;
while ( nameInvalid )
{
// validate name
if ( name.isEmpty() )
{
QMessageBox::warning( parent, tr( "Save Color Ramp" ),
tr( "Cannot save color ramp without name. Enter a name." ) );
}
else if ( style->colorRampNames().contains( name ) )
{
int res = QMessageBox::warning( parent, tr( "Save color ramp" ),
tr( "Color ramp with name '%1' already exists. Overwrite?" )
.arg( name ),
QMessageBox::Yes | QMessageBox::No );
if ( res == QMessageBox::Yes )
{
nameInvalid = false;
}
}
else
{
// valid name
nameInvalid = false;
}
if ( nameInvalid )
{
bool ok;
name = QInputDialog::getText( parent, tr( "Color Ramp Name" ),
tr( "Please enter a name for new color ramp:" ),
QLineEdit::Normal, name, &ok );
if ( !ok )
{
return QString();
}
}
}
QStringList colorRampTags = saveDlg.tags().split( ',' );
QgsColorRamp *r = ramp.release();
// add new symbol to style and re-populate the list
style->addColorRamp( name, r );
style->saveColorRamp( name, r, saveDlg.isFavorite(), colorRampTags );
return name;
}
bool QgsStyleManagerDialog::addColorRamp()
{
return addColorRamp( nullptr );
}
bool QgsStyleManagerDialog::addColorRamp( QAction *action )
{
// pass the action text, which is the color ramp type
QString rampName = addColorRampStatic( this, mStyle,
action ? action->text() : QString() );
if ( !rampName.isEmpty() )
{
mModified = true;
populateList();
return true;
}
return false;
}
void QgsStyleManagerDialog::editItem()
{
bool changed = false;
if ( currentItemType() < 3 )
{
changed = editSymbol();
}
else if ( currentItemType() == 3 )
{
changed = editColorRamp();
}
else
{
Q_ASSERT( false && "not implemented" );
}
if ( changed )
populateList();
}
bool QgsStyleManagerDialog::editSymbol()
{
QString symbolName = currentItemName();
if ( symbolName.isEmpty() )
return false;
QgsSymbol *symbol = mStyle->symbol( symbolName );
// let the user edit the symbol and update list when done
QgsSymbolSelectorDialog dlg( symbol, mStyle, nullptr, this );
if ( dlg.exec() == 0 )
{
delete symbol;
return false;
}
// by adding symbol to style with the same name the old effectively gets overwritten
mStyle->addSymbol( symbolName, symbol, true );
mModified = true;
return true;
}
bool QgsStyleManagerDialog::editColorRamp()
{
QString name = currentItemName();
if ( name.isEmpty() )
return false;
std::unique_ptr< QgsColorRamp > ramp( mStyle->colorRamp( name ) );
if ( ramp->type() == QLatin1String( "gradient" ) )
{
QgsGradientColorRamp *gradRamp = static_cast<QgsGradientColorRamp *>( ramp.get() );
QgsGradientColorRampDialog dlg( *gradRamp, this );
if ( !dlg.exec() )
{
return false;
}
ramp.reset( dlg.ramp().clone() );
}
else if ( ramp->type() == QLatin1String( "random" ) )
{
QgsLimitedRandomColorRamp *randRamp = static_cast<QgsLimitedRandomColorRamp *>( ramp.get() );
QgsLimitedRandomColorRampDialog dlg( *randRamp, this );
if ( !dlg.exec() )
{
return false;
}
ramp.reset( dlg.ramp().clone() );
}
else if ( ramp->type() == QLatin1String( "colorbrewer" ) )
{
QgsColorBrewerColorRamp *brewerRamp = static_cast<QgsColorBrewerColorRamp *>( ramp.get() );
QgsColorBrewerColorRampDialog dlg( *brewerRamp, this );
if ( !dlg.exec() )
{
return false;
}
ramp.reset( dlg.ramp().clone() );
}
else if ( ramp->type() == QLatin1String( "preset" ) )
{
QgsPresetSchemeColorRamp *presetRamp = static_cast<QgsPresetSchemeColorRamp *>( ramp.get() );
QgsPresetColorRampDialog dlg( *presetRamp, this );
if ( !dlg.exec() )
{
return false;
}
ramp.reset( dlg.ramp().clone() );
}
else if ( ramp->type() == QLatin1String( "cpt-city" ) )
{
QgsCptCityColorRamp *cptCityRamp = static_cast<QgsCptCityColorRamp *>( ramp.get() );
QgsCptCityColorRampDialog dlg( *cptCityRamp, this );
if ( !dlg.exec() )
{
return false;
}
if ( dlg.saveAsGradientRamp() )
{
ramp.reset( dlg.ramp().cloneGradientRamp() );
}
else
{
ramp.reset( dlg.ramp().clone() );
}
}
else
{
Q_ASSERT( false && "invalid ramp type" );
}
mStyle->addColorRamp( name, ramp.release(), true );
mModified = true;
return true;
}
void QgsStyleManagerDialog::removeItem()
{
bool changed = false;
if ( currentItemType() < 3 )
{
changed = removeSymbol();
}
else if ( currentItemType() == 3 )
{
changed = removeColorRamp();
}
else
{
Q_ASSERT( false && "not implemented" );
}
if ( changed )
{
populateList();
populateTypes();
}
}
bool QgsStyleManagerDialog::removeSymbol()
{
QModelIndexList indexes = listItems->selectionModel()->selectedIndexes();
if ( QMessageBox::Yes != QMessageBox::question( this, tr( "Confirm removal" ),
QString( tr( "Do you really want to remove %n symbol(s)?", nullptr, indexes.count() ) ),
QMessageBox::Yes,
QMessageBox::No ) )
return false;
Q_FOREACH ( const QModelIndex &index, indexes )
{
QString symbolName = index.data().toString();
// delete from style and update list
if ( !symbolName.isEmpty() )
mStyle->removeSymbol( symbolName );
}
mModified = true;
return true;
}
bool QgsStyleManagerDialog::removeColorRamp()
{
QModelIndexList indexes = listItems->selectionModel()->selectedIndexes();
if ( QMessageBox::Yes != QMessageBox::question( this, tr( "Confirm removal" ),
QString( tr( "Do you really want to remove %n ramp(s)?", nullptr, indexes.count() ) ),
QMessageBox::Yes,
QMessageBox::No ) )
return false;
Q_FOREACH ( const QModelIndex &index, indexes )
{
QString rampName = index.data().toString();
// delete from style and update list
if ( !rampName.isEmpty() )
mStyle->removeColorRamp( rampName );
}
mModified = true;
return true;
}
void QgsStyleManagerDialog::itemChanged( QStandardItem *item )
{
// an item has been edited
QString oldName = item->data().toString();
bool changed = false;
if ( currentItemType() < 3 )
{
changed = mStyle->renameSymbol( oldName, item->text() );
}
else if ( currentItemType() == 3 )
{
changed = mStyle->renameColorRamp( oldName, item->text() );
}
if ( changed )
{
populateList();
mModified = true;
}
else
{
QMessageBox::critical( this, tr( "Cannot rename item" ),
tr( "Name is already taken by another item. Choose a different name." ) );
item->setText( oldName );
}
}
void QgsStyleManagerDialog::exportItemsPNG()
{
QString dir = QFileDialog::getExistingDirectory( this, tr( "Exported selected symbols as PNG" ),
QDir::home().absolutePath(),
QFileDialog::ShowDirsOnly
| QFileDialog::DontResolveSymlinks );
exportSelectedItemsImages( dir, QStringLiteral( "png" ), QSize( 32, 32 ) );
}
void QgsStyleManagerDialog::exportItemsSVG()
{
QString dir = QFileDialog::getExistingDirectory( this, tr( "Exported selected symbols as SVG" ),
QDir::home().absolutePath(),
QFileDialog::ShowDirsOnly
| QFileDialog::DontResolveSymlinks );
exportSelectedItemsImages( dir, QStringLiteral( "svg" ), QSize( 32, 32 ) );
}
void QgsStyleManagerDialog::exportSelectedItemsImages( const QString &dir, const QString &format, QSize size )
{
if ( dir.isEmpty() )
return;
QModelIndexList indexes = listItems->selectionModel()->selection().indexes();
Q_FOREACH ( const QModelIndex &index, indexes )
{
QString name = index.data().toString();
QString path = dir + '/' + name + '.' + format;
QgsSymbol *sym = mStyle->symbol( name );
sym->exportImage( path, format, size );
}
}
void QgsStyleManagerDialog::exportItems()
{
QgsStyleExportImportDialog dlg( mStyle, this, QgsStyleExportImportDialog::Export );
dlg.exec();
}
void QgsStyleManagerDialog::importItems()
{
QgsStyleExportImportDialog dlg( mStyle, this, QgsStyleExportImportDialog::Import );
dlg.exec();
populateList();
populateGroups();
}
void QgsStyleManagerDialog::setBold( QStandardItem *item )
{
QFont font = item->font();
font.setBold( true );
item->setFont( font );
}
void QgsStyleManagerDialog::populateGroups()
{
QStandardItemModel *model = qobject_cast<QStandardItemModel *>( groupTree->model() );
model->clear();
QStandardItem *favoriteSymbols = new QStandardItem( tr( "Favorites" ) );
favoriteSymbols->setData( "favorite" );
favoriteSymbols->setEditable( false );
setBold( favoriteSymbols );
model->appendRow( favoriteSymbols );
QStandardItem *allSymbols = new QStandardItem( tr( "All Symbols" ) );
allSymbols->setData( "all" );
allSymbols->setEditable( false );
setBold( allSymbols );
model->appendRow( allSymbols );
QStandardItem *taggroup = new QStandardItem( QLatin1String( "" ) ); //require empty name to get first order groups
taggroup->setData( "tags" );
taggroup->setEditable( false );
QStringList tags = mStyle->tags();
tags.sort();
Q_FOREACH ( const QString &tag, tags )
{
QStandardItem *item = new QStandardItem( tag );
item->setData( mStyle->tagId( tag ) );
taggroup->appendRow( item );
}
taggroup->setText( tr( "Tags" ) );//set title later
setBold( taggroup );
model->appendRow( taggroup );
QStandardItem *smart = new QStandardItem( tr( "Smart Groups" ) );
smart->setData( "smartgroups" );
smart->setEditable( false );
setBold( smart );
QgsSymbolGroupMap sgMap = mStyle->smartgroupsListMap();
QgsSymbolGroupMap::const_iterator i = sgMap.constBegin();
while ( i != sgMap.constEnd() )
{
QStandardItem *item = new QStandardItem( i.value() );
item->setData( i.key() );
smart->appendRow( item );
++i;
}
model->appendRow( smart );
// expand things in the group tree
int rows = model->rowCount( model->indexFromItem( model->invisibleRootItem() ) );
for ( int i = 0; i < rows; i++ )
{
groupTree->setExpanded( model->indexFromItem( model->item( i ) ), true );
}
}
void QgsStyleManagerDialog::groupChanged( const QModelIndex &index )
{
QStringList symbolNames;
QStringList groupSymbols;
QgsStyle::StyleEntity type = currentItemType() < 3 ? QgsStyle::SymbolEntity : QgsStyle::ColorrampEntity;
if ( currentItemType() > 3 )
{
QgsDebugMsg( "Entity not implemented" );
return;
}
QString category = index.data( Qt::UserRole + 1 ).toString();
if ( category == QLatin1String( "all" ) || category == QLatin1String( "tags" ) || category == QLatin1String( "smartgroups" ) )
{
enableGroupInputs( false );
if ( category == QLatin1String( "tags" ) )
{
actnAddTag->setEnabled( true );
actnAddSmartgroup->setEnabled( false );
}
else if ( category == QLatin1String( "smartgroups" ) )
{
actnAddTag->setEnabled( false );
actnAddSmartgroup->setEnabled( true );
}
symbolNames = currentItemType() < 3 ? mStyle->symbolNames() : mStyle->colorRampNames();
}
else if ( category == QLatin1String( "favorite" ) )
{
enableGroupInputs( false );
symbolNames = mStyle->symbolsOfFavorite( type );
}
else if ( index.parent().data( Qt::UserRole + 1 ) == "smartgroups" )
{
actnRemoveGroup->setEnabled( true );
btnManageGroups->setEnabled( true );
int groupId = index.data( Qt::UserRole + 1 ).toInt();
symbolNames = mStyle->symbolsOfSmartgroup( type, groupId );
}
else // tags
{
enableGroupInputs( true );
int tagId = index.data( Qt::UserRole + 1 ).toInt();
symbolNames = mStyle->symbolsWithTag( type, tagId );
if ( mGrouppingMode && tagId )
{
groupSymbols = symbolNames;
symbolNames = type == QgsStyle::SymbolEntity ? mStyle->symbolNames() : mStyle->colorRampNames();
}
}
symbolNames.sort();
if ( currentItemType() < 3 )
{
populateSymbols( symbolNames, mGrouppingMode );
}
else if ( currentItemType() == 3 )
{
populateColorRamps( symbolNames, mGrouppingMode );
}
if ( mGrouppingMode )
{
setSymbolsChecked( groupSymbols );
}
actnEditSmartGroup->setVisible( false );
actnAddTag->setVisible( false );
actnAddSmartgroup->setVisible( false );
actnRemoveGroup->setVisible( false );
actnTagSymbols->setVisible( false );
actnFinishTagging->setVisible( false );
if ( index.parent().isValid() )
{
if ( index.parent().data( Qt::UserRole + 1 ).toString() == QLatin1String( "smartgroups" ) )
{
actnEditSmartGroup->setVisible( !mGrouppingMode );
}
else if ( index.parent().data( Qt::UserRole + 1 ).toString() == QLatin1String( "tags" ) )
{
actnAddTag->setVisible( !mGrouppingMode );
actnTagSymbols->setVisible( !mGrouppingMode );
actnFinishTagging->setVisible( mGrouppingMode );
}
actnRemoveGroup->setVisible( true );
}
else if ( index.data( Qt::UserRole + 1 ) == "smartgroups" )
{
actnAddSmartgroup->setVisible( !mGrouppingMode );
}
else if ( index.data( Qt::UserRole + 1 ) == "tags" )
{
actnAddTag->setVisible( !mGrouppingMode );
}
}
int QgsStyleManagerDialog::addTag()
{
QStandardItemModel *model = qobject_cast<QStandardItemModel *>( groupTree->model() );
QModelIndex index;
for ( int i = 0; i < groupTree->model()->rowCount(); i++ )
{
index = groupTree->model()->index( i, 0 );
QString data = index.data( Qt::UserRole + 1 ).toString();
if ( data == QLatin1String( "tags" ) )
{
break;
}
}
QString itemName;
int id;
bool ok;
itemName = QInputDialog::getText( this, tr( "Tag name" ),
tr( "Please enter name for the new tag:" ), QLineEdit::Normal, tr( "New tag" ), &ok ).trimmed();
if ( !ok || itemName.isEmpty() )
return 0;
int check = mStyle->tagId( itemName );
if ( check > 0 )
{
QMessageBox::critical( this, tr( "Error!" ),
tr( "Tag name already exists in your symbol database." ) );
return 0;
}
id = mStyle->addTag( itemName );
if ( !id )
{
QMessageBox::critical( this, tr( "Error!" ),
tr( "New tag could not be created.\n"
"There was a problem with your symbol database." ) );
return 0;
}
QStandardItem *parentItem = model->itemFromIndex( index );
QStandardItem *childItem = new QStandardItem( itemName );
childItem->setData( id );
parentItem->appendRow( childItem );
return id;
}
int QgsStyleManagerDialog::addSmartgroup()
{
QStandardItemModel *model = qobject_cast<QStandardItemModel *>( groupTree->model() );
QModelIndex index;
for ( int i = 0; i < groupTree->model()->rowCount(); i++ )
{
index = groupTree->model()->index( i, 0 );
QString data = index.data( Qt::UserRole + 1 ).toString();
if ( data == QLatin1String( "smartgroups" ) )
{
break;
}
}
QString itemName;
int id;
QgsSmartGroupEditorDialog dlg( mStyle, this );
if ( dlg.exec() == QDialog::Rejected )
return 0;
id = mStyle->addSmartgroup( dlg.smartgroupName(), dlg.conditionOperator(), dlg.conditionMap() );
if ( !id )
return 0;
itemName = dlg.smartgroupName();
QStandardItem *parentItem = model->itemFromIndex( index );
QStandardItem *childItem = new QStandardItem( itemName );
childItem->setData( id );
parentItem->appendRow( childItem );
return id;
}
void QgsStyleManagerDialog::removeGroup()
{
QStandardItemModel *model = qobject_cast<QStandardItemModel *>( groupTree->model() );
QModelIndex index = groupTree->currentIndex();
// do not allow removal of system-defined groupings
QString data = index.data( Qt::UserRole + 1 ).toString();
if ( data == QLatin1String( "all" ) || data == QLatin1String( "favorite" ) || data == QLatin1String( "tags" ) || index.data() == "smartgroups" )
{
int err = QMessageBox::critical( this, tr( "Invalid selection" ),
tr( "Cannot delete system defined categories.\n"
"Kindly select a group or smart group you might want to delete." ) );
if ( err )
return;
}
QStandardItem *parentItem = model->itemFromIndex( index.parent() );
if ( parentItem->data( Qt::UserRole + 1 ).toString() == QLatin1String( "smartgroups" ) )
{
mStyle->remove( QgsStyle::SmartgroupEntity, index.data( Qt::UserRole + 1 ).toInt() );
}
else
{
mStyle->remove( QgsStyle::TagEntity, index.data( Qt::UserRole + 1 ).toInt() );
}
parentItem->removeRow( index.row() );
}
void QgsStyleManagerDialog::groupRenamed( QStandardItem *item )
{
QgsDebugMsg( "Symbol group edited: data=" + item->data( Qt::UserRole + 1 ).toString() + " text=" + item->text() );
int id = item->data( Qt::UserRole + 1 ).toInt();
QString name = item->text();
if ( item->parent()->data( Qt::UserRole + 1 ) == "smartgroups" )
{
mStyle->rename( QgsStyle::SmartgroupEntity, id, name );
}
else
{
mStyle->rename( QgsStyle::TagEntity, id, name );
}
}
void QgsStyleManagerDialog::tagSymbolsAction()
{
QStandardItemModel *treeModel = qobject_cast<QStandardItemModel *>( groupTree->model() );
QStandardItemModel *model = qobject_cast<QStandardItemModel *>( listItems->model() );
if ( mGrouppingMode )
{
mGrouppingMode = false;
actnTagSymbols->setVisible( true );
actnFinishTagging->setVisible( false );
// disconnect slot which handles regrouping
disconnect( model, &QStandardItemModel::itemChanged,
this, &QgsStyleManagerDialog::regrouped );
// disabel all items except groups in groupTree
enableItemsForGroupingMode( true );
groupChanged( groupTree->currentIndex() );
// Finally: Reconnect all Symbol editing functionalities
connect( treeModel, &QStandardItemModel::itemChanged,
this, &QgsStyleManagerDialog::groupRenamed );
connect( model, &QStandardItemModel::itemChanged,
this, &QgsStyleManagerDialog::itemChanged );
// Reset the selection mode
listItems->setSelectionMode( QAbstractItemView::ExtendedSelection );
}
else
{
bool validGroup = false;
// determine whether it is a valid group
QModelIndex present = groupTree->currentIndex();
while ( present.parent().isValid() )
{
if ( present.parent().data() == "Tags" )
{
validGroup = true;
break;
}
present = present.parent();
}
if ( !validGroup )
return;
mGrouppingMode = true;
// Change visibility of actions
actnTagSymbols->setVisible( false );
actnFinishTagging->setVisible( true );
// Remove all Symbol editing functionalities
disconnect( treeModel, &QStandardItemModel::itemChanged,
this, &QgsStyleManagerDialog::groupRenamed );
disconnect( model, &QStandardItemModel::itemChanged,
this, &QgsStyleManagerDialog::itemChanged );
<|fim▁hole|> // disabel all items except groups in groupTree
enableItemsForGroupingMode( false );
groupChanged( groupTree->currentIndex() );
btnManageGroups->setEnabled( true );
// Connect to slot which handles regrouping
connect( model, &QStandardItemModel::itemChanged,
this, &QgsStyleManagerDialog::regrouped );
// No selection should be possible
listItems->setSelectionMode( QAbstractItemView::NoSelection );
}
}
void QgsStyleManagerDialog::regrouped( QStandardItem *item )
{
QgsStyle::StyleEntity type = ( currentItemType() < 3 ) ? QgsStyle::SymbolEntity : QgsStyle::ColorrampEntity;
if ( currentItemType() > 3 )
{
QgsDebugMsg( "Unknown style entity" );
return;
}
QStandardItemModel *treeModel = qobject_cast<QStandardItemModel *>( groupTree->model() );
QString tag = treeModel->itemFromIndex( groupTree->currentIndex() )->text();
QString symbolName = item->text();
bool regrouped;
if ( item->checkState() == Qt::Checked )
regrouped = mStyle->tagSymbol( type, symbolName, QStringList( tag ) );
else
regrouped = mStyle->detagSymbol( type, symbolName, QStringList( tag ) );
if ( !regrouped )
{
int er = QMessageBox::critical( this, tr( "Database Error" ),
tr( "There was a problem with the Symbols database while regrouping." ) );
// call the slot again to get back to normal
if ( er )
tagSymbolsAction();
}
}
void QgsStyleManagerDialog::setSymbolsChecked( const QStringList &symbols )
{
QStandardItemModel *model = qobject_cast<QStandardItemModel *>( listItems->model() );
Q_FOREACH ( const QString &symbol, symbols )
{
QList<QStandardItem *> items = model->findItems( symbol );
Q_FOREACH ( QStandardItem *item, items )
item->setCheckState( Qt::Checked );
}
}
void QgsStyleManagerDialog::filterSymbols( const QString &qword )
{
QStringList items;
items = mStyle->findSymbols( currentItemType() < 3 ? QgsStyle::SymbolEntity : QgsStyle::ColorrampEntity, qword );
items.sort();
if ( currentItemType() == 3 )
{
populateColorRamps( items );
}
else
{
populateSymbols( items );
}
}
void QgsStyleManagerDialog::symbolSelected( const QModelIndex &index )
{
actnEditItem->setEnabled( index.isValid() && !mGrouppingMode );
}
void QgsStyleManagerDialog::selectedSymbolsChanged( const QItemSelection &selected, const QItemSelection &deselected )
{
Q_UNUSED( selected );
Q_UNUSED( deselected );
bool nothingSelected = listItems->selectionModel()->selectedIndexes().empty();
actnRemoveItem->setDisabled( nothingSelected );
actnAddFavorite->setDisabled( nothingSelected );
actnRemoveFavorite->setDisabled( nothingSelected );
mGroupListMenu->setDisabled( nothingSelected );
actnDetag->setDisabled( nothingSelected );
actnExportAsPNG->setDisabled( nothingSelected );
actnExportAsSVG->setDisabled( nothingSelected );
actnEditItem->setDisabled( nothingSelected );
}
void QgsStyleManagerDialog::enableSymbolInputs( bool enable )
{
groupTree->setEnabled( enable );
btnAddTag->setEnabled( enable );
btnAddSmartgroup->setEnabled( enable );
actnAddTag->setEnabled( enable );
actnAddSmartgroup->setEnabled( enable );
actnRemoveGroup->setEnabled( enable );
btnManageGroups->setEnabled( enable || mGrouppingMode ); // always enabled in grouping mode, as it is the only way to leave grouping mode
searchBox->setEnabled( enable );
}
void QgsStyleManagerDialog::enableGroupInputs( bool enable )
{
actnRemoveGroup->setEnabled( enable );
btnManageGroups->setEnabled( enable || mGrouppingMode ); // always enabled in grouping mode, as it is the only way to leave grouping mode
}
void QgsStyleManagerDialog::enableItemsForGroupingMode( bool enable )
{
QStandardItemModel *treeModel = qobject_cast<QStandardItemModel *>( groupTree->model() );
for ( int i = 0; i < treeModel->rowCount(); i++ )
{
treeModel->item( i )->setEnabled( enable );
if ( treeModel->item( i )->data() == "smartgroups" )
{
for ( int j = 0; j < treeModel->item( i )->rowCount(); j++ )
{
treeModel->item( i )->child( j )->setEnabled( enable );
}
}
}
// The buttons
// NOTE: if you ever change the layout name in the .ui file edit here too
for ( int i = 0; i < symbolBtnsLayout->count(); i++ )
{
QWidget *w = qobject_cast<QWidget *>( symbolBtnsLayout->itemAt( i )->widget() );
if ( w )
w->setEnabled( enable );
}
// The actions
actnRemoveItem->setEnabled( enable );
actnEditItem->setEnabled( enable );
}
void QgsStyleManagerDialog::grouptreeContextMenu( QPoint point )
{
QPoint globalPos = groupTree->viewport()->mapToGlobal( point );
QModelIndex index = groupTree->indexAt( point );
QgsDebugMsg( "Now you clicked: " + index.data().toString() );
if ( index.isValid() && !mGrouppingMode )
mGroupTreeContextMenu->popup( globalPos );
}
void QgsStyleManagerDialog::listitemsContextMenu( QPoint point )
{
QPoint globalPos = listItems->viewport()->mapToGlobal( point );
// Clear all actions and create new actions for every group
mGroupListMenu->clear();
QAction *a = nullptr;
QStringList tags = mStyle->tags();
tags.sort();
Q_FOREACH ( const QString &tag, tags )
{
a = new QAction( tag, mGroupListMenu );
a->setData( tag );
connect( a, &QAction::triggered, this, [ = ]( bool ) { tagSelectedSymbols(); }
);
mGroupListMenu->addAction( a );
}
if ( tags.count() > 0 )
{
mGroupListMenu->addSeparator();
}
a = new QAction( tr( "Create new tag…" ), mGroupListMenu );
connect( a, &QAction::triggered, this, [ = ]( bool ) { tagSelectedSymbols( true ); }
);
mGroupListMenu->addAction( a );
mGroupMenu->popup( globalPos );
}
void QgsStyleManagerDialog::addFavoriteSelectedSymbols()
{
QgsStyle::StyleEntity type = ( currentItemType() < 3 ) ? QgsStyle::SymbolEntity : QgsStyle::ColorrampEntity;
if ( currentItemType() > 3 )
{
QgsDebugMsg( "unknown entity type" );
return;
}
QModelIndexList indexes = listItems->selectionModel()->selectedIndexes();
Q_FOREACH ( const QModelIndex &index, indexes )
{
mStyle->addFavorite( type, index.data().toString() );
}
populateList();
}
void QgsStyleManagerDialog::removeFavoriteSelectedSymbols()
{
QgsStyle::StyleEntity type = ( currentItemType() < 3 ) ? QgsStyle::SymbolEntity : QgsStyle::ColorrampEntity;
if ( currentItemType() > 3 )
{
QgsDebugMsg( "unknown entity type" );
return;
}
QModelIndexList indexes = listItems->selectionModel()->selectedIndexes();
Q_FOREACH ( const QModelIndex &index, indexes )
{
mStyle->removeFavorite( type, index.data().toString() );
}
populateList();
}
void QgsStyleManagerDialog::tagSelectedSymbols( bool newTag )
{
QAction *selectedItem = qobject_cast<QAction *>( sender() );
if ( selectedItem )
{
QgsStyle::StyleEntity type = ( currentItemType() < 3 ) ? QgsStyle::SymbolEntity : QgsStyle::ColorrampEntity;
if ( currentItemType() > 3 )
{
QgsDebugMsg( "unknown entity type" );
return;
}
QString tag;
if ( newTag )
{
int id = addTag();
if ( id == 0 )
{
return;
}
tag = mStyle->tag( id );
}
else
{
tag = selectedItem->data().toString();
}
QModelIndexList indexes = listItems->selectionModel()->selectedIndexes();
Q_FOREACH ( const QModelIndex &index, indexes )
{
mStyle->tagSymbol( type, index.data().toString(), QStringList( tag ) );
}
populateList();
QgsDebugMsg( "Selected Action: " + selectedItem->text() );
}
}
void QgsStyleManagerDialog::detagSelectedSymbols()
{
QAction *selectedItem = qobject_cast<QAction *>( sender() );
if ( selectedItem )
{
QgsStyle::StyleEntity type = ( currentItemType() < 3 ) ? QgsStyle::SymbolEntity : QgsStyle::ColorrampEntity;
if ( currentItemType() > 3 )
{
QgsDebugMsg( "unknown entity type" );
return;
}
QModelIndexList indexes = listItems->selectionModel()->selectedIndexes();
Q_FOREACH ( const QModelIndex &index, indexes )
{
mStyle->detagSymbol( type, index.data().toString() );
}
populateList();
QgsDebugMsg( "Selected Action: " + selectedItem->text() );
}
}
void QgsStyleManagerDialog::editSmartgroupAction()
{
QStandardItemModel *treeModel = qobject_cast<QStandardItemModel *>( groupTree->model() );
// determine whether it is a valid group
QModelIndex present = groupTree->currentIndex();
if ( present.parent().data( Qt::UserRole + 1 ) != "smartgroups" )
{
QMessageBox::critical( this, tr( "Invalid Selection" ),
tr( "You have not selected a Smart Group. Kindly select a Smart Group to edit." ) );
return;
}
QStandardItem *item = treeModel->itemFromIndex( present );
QgsSmartGroupEditorDialog dlg( mStyle, this );
QgsSmartConditionMap map = mStyle->smartgroup( present.data( Qt::UserRole + 1 ).toInt() );
dlg.setSmartgroupName( item->text() );
dlg.setOperator( mStyle->smartgroupOperator( item->data().toInt() ) );
dlg.setConditionMap( map );
if ( dlg.exec() == QDialog::Rejected )
return;
mStyle->remove( QgsStyle::SmartgroupEntity, item->data().toInt() );
int id = mStyle->addSmartgroup( dlg.smartgroupName(), dlg.conditionOperator(), dlg.conditionMap() );
if ( !id )
{
QMessageBox::critical( this, tr( "Database Error!" ),
tr( "There was some error while editing the smart group." ) );
return;
}
item->setText( dlg.smartgroupName() );
item->setData( id );
groupChanged( present );
}
void QgsStyleManagerDialog::onClose()
{
reject();
}
void QgsStyleManagerDialog::showHelp()
{
QgsHelp::openHelp( QStringLiteral( "working_with_vector/style_library.html#the-style-manager" ) );
}<|fim▁end|> | |
<|file_name|>ntp_client.py<|end_file_name|><|fim▁begin|>#!/bin/env python
"""
#######################################################################
# #
# Copyright (c) 2012, Prateek Sureka. All Rights Reserved. #
# This module provides an idempotent mechanism to remotely configure #
# ntp sync to a server on a host. #
# #
#######################################################################
"""
from fabric.api import task, run, env
from fabric.colors import red
from utils import reconfigure, is_debian_or_ubuntu
env.warn_only = True
from config import config
NTP_CONF_PATH = "/etc/ntp.conf"
@task
def timezone(timezone=config.get("ntp_client", {}).get("ntp_timezone", "Asia/Calcutta")):
""" Set the timezone. """
if not is_debian_or_ubuntu():
print red("Cannot deploy to non-debian/ubuntu host: %s" % env.host)
return
import apt
apt.ensure(tzdata="latest")
return run("cp -f /usr/share/zoneinfo/%s /etc/localtime" % timezone)
@task
def configure(server=config.get("ntp_client", {}).get("ntp_server", "")):
""" Configure NTP sync to server. """
if not is_debian_or_ubuntu():
print red("Cannot deploy to non-debian/ubuntu host: %s" % env.host)
return
# Upload configuration
params = {'server':server}
reconfigure("ntp_client.conf.template", params, NTP_CONF_PATH)
@task
def deploy(server=config.get("ntp_client", {}).get("ntp_server", "")):
""" Install, configure and start ntp sync and timezone. """
if not is_debian_or_ubuntu():
print red("Cannot deploy to non-debian/ubuntu host: %s" % env.host)
return
import apt, service
packages = {"ntp":"latest", "ntpdate":"latest"}
apt.ensure(**packages)
configure()<|fim▁hole|>
# Sync with server
run("ntpdate %s" % server)
# Sync hardware clock to correct time
run("hwclock --systohc")
service.ensure(ntp="restarted")
timezone()
@task
def status():
""" List the servers with which the host is synchronized. """
print run("ntpq -p")
print run("ntpdc -p")<|fim▁end|> | |
<|file_name|>freicoin_ca_ES.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.0" language="ca_ES">
<defaultcodec>UTF-8</defaultcodec>
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About Calcoin</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+39"/>
<source><b>Calcoin</b> version</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+41"/>
<source>Copyright © 2009-2012 Calcoin developers
Copyright © 2011-2012 Calcoin developers
The conceptual marriage of Gesell's Freigeld with Calcoin is due to one individual without whom this project would never have started: Jorge Timón. The initial release would not have been possible without further contributions from developers Mark Friedenbach, Matthew Redmond, Aaron Blumenshine, and an anonymous contributor.
The initial development of Calcoin was made possible through generous financial support from Martin Auer, Matthew Redmond, Carsten Langer, Manolis Afentakis, Dave Berzack, Marco Bluethgen, Jamie Derkenne, Josef Dietl, Claas Kähler, Alex Glaser, Trent Larson, James O'Keefe, David Rodrigues, Lucas Vázquez Besteiro, Reinoud Zandijk, and anonymous supporters.
Last but certainly not least, we all owe a debt to the legacy of Silvio Gesell, as it is upon his theory of free money that Calcoin is built.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+23"/>
<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"></translation>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>llibreta d'adreces</translation>
</message>
<message>
<location line="+6"/>
<source>These are your Calcoin 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"></translation>
</message>
<message>
<location line="+16"/>
<source>Double-click to edit address or label</source>
<translation>Feu doble clic per editar la direcció o l'etiqueta</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>Crear una nova adreça</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Copieu l'adreça seleccionada al porta-retalls del sistema</translation>
</message>
<message>
<location line="+25"/>
<source>Sign a message to prove you own a Calcoin address</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="-36"/>
<source>&New Address</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+14"/>
<source>&Copy Address</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+14"/>
<source>Sign &Message</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+11"/>
<source>Verify a message to ensure it was signed with a specified Calcoin address</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+14"/>
<source>Delete the currently selected address from the list</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="-11"/>
<source>&Verify Message</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>&Borrar</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+65"/>
<source>Copy &Label</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+2"/>
<source>&Edit</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+250"/>
<source>Export Address Book Data</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+142"/>
<source>Label</source>
<translation>Etiqueta</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Direcció</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation type="unfinished"></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 type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>Xifrar la cartera</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+0"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR CALCOINS</b>!</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+11"/>
<source>Calcoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your calcoins from being stolen by malware infecting your computer.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+4"/>
<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"></translation>
</message>
<message>
<location line="+100"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="-130"/>
<location line="+58"/>
<source>Wallet encrypted</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="-43"/>
<location line="+7"/>
<location line="+42"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="-54"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+7"/>
<location line="+48"/>
<source>The supplied passphrases do not match.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="-37"/>
<source>Wallet unlock failed</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<location line="+11"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+87"/>
<source>Network Alert</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Editar Adreça</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation type="unfinished"></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 type="unfinished"></translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+20"/>
<source>New receiving address</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+60"/>
<source>The entered address "%1" is already in the address book.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+5"/>
<source>The entered address "%1" is not a valid Calcoin address.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+5"/>
<source>Could not unlock wallet.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>CalcoinGUI</name>
<message>
<location filename="../calcoin.cpp" line="+109"/>
<source>A fatal error occured. Calcoin can no longer continue safely and will quit.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../calcoingui.cpp" line="+74"/>
<source>Calcoin</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+0"/>
<source>Wallet</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+124"/>
<source>&Overview</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation type="unfinished">Mostra panorama general de la cartera</translation>
</message>
<message>
<location line="+6"/>
<source>Send coins to a Calcoin address</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+6"/>
<source>Show the list of addresses for receiving payments</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+5"/>
<source>&Transactions</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation type="unfinished">Cerca a l'historial de transaccions</translation>
</message>
<message>
<location line="-13"/>
<source>&Send</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+6"/>
<source>&Receive</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+12"/>
<source>&Contacts</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Edit the list of stored addresses and labels</source>
<translation type="unfinished">Edita la llista d'adreces emmagatzemada i etiquetes</translation>
</message>
<message>
<location line="+16"/>
<source>E&xit</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation type="unfinished">Sortir de l'aplicació</translation>
</message>
<message>
<location line="+3"/>
<source>&About Calcoin</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Calcoin</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation type="unfinished">&Opcions ...</translation>
</message>
<message>
<location line="+1"/>
<source>Modify configuration options for Calcoin</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+2"/>
<source>Show / &Hide</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>&Encrypt Wallet...</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt or decrypt wallet</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+2"/>
<source>&Backup Wallet...</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Backup wallet to another location</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>&Change Passphrase...</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Change the passphrase used for wallet encryption</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Sign &message...</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>&Verify message...</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+2"/>
<source>&Export...</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Export the data in the current tab to a file</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>&Debug window</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+25"/>
<source>&File</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+8"/>
<source>&Settings</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+6"/>
<source>&Help</source>
<translation type="unfinished">&Ajuda</translation>
</message>
<message>
<location line="+9"/>
<source>Tabs toolbar</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+8"/>
<source>Actions toolbar</source>
<translation type="unfinished">Accions de la barra d'eines</translation>
</message>
<message>
<location line="+13"/>
<location line="+9"/>
<source>[testnet]</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+0"/>
<location line="+60"/>
<source>Calcoin client</source>
<translation type="unfinished"></translation>
</message>
<message numerus="yes">
<location line="+69"/>
<source>%n active connection(s) to Calcoin network</source>
<translation type="unfinished">
<numerusform></numerusform>
<numerusform></numerusform>
<numerusform></numerusform>
</translation>
</message>
<message>
<location line="+24"/>
<source>Synchronizing with network...</source>
<translation type="unfinished">Sincronització amb la xarxa ...</translation>
</message>
<message numerus="yes">
<location line="+2"/>
<source>~%n block(s) remaining</source>
<translation type="unfinished">
<numerusform></numerusform>
<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"></translation>
</message>
<message>
<location line="+8"/>
<source>Downloaded %1 blocks of transaction history.</source>
<translation type="unfinished"></translation>
</message>
<message numerus="yes">
<location line="+22"/>
<source>%n second(s) ago</source>
<translation type="unfinished">
<numerusform></numerusform>
<numerusform></numerusform>
<numerusform></numerusform>
</translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n minute(s) ago</source>
<translation type="unfinished">
<numerusform></numerusform>
<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>
<numerusform></numerusform>
</translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s) ago</source>
<translation type="unfinished">
<numerusform></numerusform>
<numerusform></numerusform>
<numerusform></numerusform>
</translation>
</message>
<message>
<location line="+6"/>
<source>Up to date</source>
<translation type="unfinished">Al dia</translation>
</message>
<message>
<location line="+7"/>
<source>Catching up...</source>
<translation type="unfinished">Posar-se al dia ...</translation>
</message>
<message>
<location line="+10"/>
<source>Last received block was generated %1.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+81"/>
<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"></translation>
</message>
<message>
<location line="+5"/>
<source>Confirm transaction fee</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+28"/>
<source>Sent transaction</source>
<translation type="unfinished">Transacció enviada</translation>
</message>
<message>
<location line="+1"/>
<source>Incoming transaction</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+100"/>
<location line="+15"/>
<source>URI handling</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="-15"/>
<location line="+15"/>
<source>URI can not be parsed! This can be caused by an invalid Calcoin address or malformed URI parameters.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+16"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+23"/>
<source>Backup Wallet</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+419"/>
<source>version</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+0"/>
<location line="+12"/>
<source>Calcoin-Qt</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="-10"/>
<source>Usage:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+41"/>
<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"></translation>
</message>
<message>
<location line="+24"/>
<source>&Network</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+9"/>
<source>Map port using &UPnP</source>
<translation>Port obert amb &UPnP</translation>
</message>
<message>
<location line="-43"/>
<source>Automatically start Calcoin after logging in to the system.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+3"/>
<source>&Start Calcoin on system login</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+10"/>
<source>D&etach databases at shutdown</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+27"/>
<source>Automatically open the Calcoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+10"/>
<source>Connect to the Calcoin network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+12"/>
<source>Proxy &IP:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+91"/>
<source>Display addresses in &transaction list</source>
<translation type="unfinished"></translation>
</message><|fim▁hole|> <message>
<location line="-81"/>
<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"></translation>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting Calcoin.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+33"/>
<source>Whether to show Calcoin addresses in the transaction list or not.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="-22"/>
<source>&Unit to show amounts in:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="-182"/>
<source>Connect through &SOCKS proxy:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+119"/>
<source>Minimize to the &tray instead of the taskbar</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+76"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+83"/>
<source>&OK</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+55"/>
<source>default</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+147"/>
<location line="+9"/>
<source>Warning</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting Calcoin.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+75"/>
<source>Balance:</source>
<translation>Balanç:</translation>
</message>
<message>
<location line="+58"/>
<source>Number of transactions:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="-29"/>
<source>Unconfirmed:</source>
<translation>Sense confirmar:</translation>
</message>
<message>
<location line="-78"/>
<source>Wallet</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+7"/>
<location line="+183"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the Calcoin network after a connection is established, but this process has not completed yet.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="-66"/>
<source>Immature:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="-118"/>
<source>Your current balance</source>
<translation>El seu balanç 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 type="unfinished"></translation>
</message>
<message>
<location line="+20"/>
<source>Total number of transactions in wallet</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="+114"/>
<location line="+1"/>
<source>out of sync</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<location line="+23"/>
<location filename="../rpcconsole.cpp" line="+348"/>
<source>N/A</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="-10"/>
<source>Calcoin - Debug window</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+25"/>
<source>Calcoin Core</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+53"/>
<source>Using OpenSSL version</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+49"/>
<source>Open the Calcoin debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+3"/>
<source>&Open</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+7"/>
<source>Show the Calcoin-Qt help message to get a list with possible Calcoin command-line options.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+200"/>
<source>Debug log file</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+109"/>
<source>Clear console</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-33"/>
<source>Welcome to the Calcoin RPC console.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+127"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>Enviar monedes</translation>
</message>
<message>
<location line="+50"/>
<source>Send to multiple recipients at once</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+3"/>
<source>&Clear All</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+22"/>
<source>Balance:</source>
<translation>Balanç:</translation>
</message>
<message>
<location line="+10"/>
<source>123.456 FRC</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-59"/>
<source><b>%1</b> to %2 (%3)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+23"/>
<source>The recipient address is not valid, please recheck.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>La quantitat a pagar ha de ser major que 0.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+24"/>
<location filename="../sendcoinsentry.cpp" line="+25"/>
<source>Enter a label for this address to add it to your address book</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+9"/>
<source>&Label:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+18"/>
<source>The address to send the payment to (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+10"/>
<source>Choose address from address book</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+10"/>
<source>Alt+D</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a Calcoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation type="unfinished"></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"></translation>
</message>
<message>
<location line="+13"/>
<location line="+127"/>
<source>&Sign Message</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="-121"/>
<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"></translation>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+10"/>
<location line="+206"/>
<source>Choose an address from the address book</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="-196"/>
<location line="+206"/>
<source>Alt+A</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="-196"/>
<source>Paste address from clipboard</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+24"/>
<source>Copy the current signature to the system clipboard</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+10"/>
<source>Alt+Y</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+14"/>
<source>Sign the message to prove you own this Calcoin address</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+20"/>
<location line="+146"/>
<source>&Clear All</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="-20"/>
<source>Verify the message to ensure it was signed with the specified Calcoin address</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="-129"/>
<source>Reset all sign message fields</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+62"/>
<location line="+70"/>
<source>&Verify Message</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="-64"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+57"/>
<source>Reset all verify message fields</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+28"/>
<source>Click "Sign Message" to generate signature</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="-1"/>
<location line="+3"/>
<source>Enter a Calcoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Enter Calcoin signature</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+19"/>
<source>Open until %1</source>
<translation type="unfinished"></translation>
</message>
<message numerus="yes">
<location line="-2"/>
<source>Open for %n block(s)</source>
<translation type="unfinished">
<numerusform></numerusform>
<numerusform></numerusform>
<numerusform></numerusform>
</translation>
</message>
<message>
<location line="+8"/>
<source>%1/offline</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation type="unfinished"></translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation type="unfinished">
<numerusform></numerusform>
<numerusform></numerusform>
<numerusform></numerusform>
</translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+32"/>
<source>Credit</source>
<translation type="unfinished"></translation>
</message>
<message numerus="yes">
<location line="-104"/>
<source>matures in %n more block(s)</source>
<translation type="unfinished">
<numerusform></numerusform>
<numerusform></numerusform>
<numerusform></numerusform>
</translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+32"/>
<source>Debit</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="-41"/>
<source>Transaction fee</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+2"/>
<source>Reference Height</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation type="unfinished"></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 type="unfinished"></translation>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+5"/>
<source>Inputs</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="-213"/>
<source>, has not been successfully broadcast yet</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+35"/>
<source>unknown</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+227"/>
<source>Date</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Direcció</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+0"/>
<source>Ref-height</source>
<translation type="unfinished"></translation>
</message>
<message numerus="yes">
<location line="+57"/>
<source>Open for %n block(s)</source>
<translation type="unfinished">
<numerusform></numerusform>
<numerusform></numerusform>
<numerusform></numerusform>
</translation>
</message>
<message>
<location line="+3"/>
<source>Open until %1</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+3"/>
<source>Offline (%1 confirmations)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed (%1 confirmations)</source>
<translation type="unfinished"></translation>
</message>
<message numerus="yes">
<location line="+8"/>
<source>Mined balance will be available when it matures in %n more block(s)</source>
<translation type="unfinished">
<numerusform></numerusform>
<numerusform></numerusform>
<numerusform></numerusform>
</translation>
</message>
<message>
<location line="+5"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+43"/>
<source>Received with</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+223"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+2"/>
<source>Reference block number that amount is pegged to.</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+55"/>
<location line="+16"/>
<source>All</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+13"/>
<source>Min height</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+150"/>
<source>Export Transaction Data</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>Etiqueta</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Direcció</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+95"/>
<source>Range:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+196"/>
<source>Sending...</source>
<translation>L'enviament de ...</translation>
</message>
</context>
<context>
<name>calcoin-core</name>
<message>
<location filename="../calcoinstrings.cpp" line="+9"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=calcoinrpc
rpcpassword=%s
(you do not need to remember this password)
If the file does not exist, create it with owner-readable-only file permissions.
</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+9"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+3"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+2"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. Calcoin is probably already running.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+3"/>
<source>Detach block and address databases. Increases shutdown time (default: 0)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+2"/>
<source>Error initializing database environment %s! To recover, BACKUP THAT DIRECTORY, then remove everything from it except for wallet.dat.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+3"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+4"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds </source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+3"/>
<source>Listen for JSON-RPC connections on <port> (default: 8638 or testnet: 18638)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+2"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+3"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+3"/>
<source>Unable to bind to %s on this computer. Calcoin is probably already running.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+2"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation type="unfinished"></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"></translation>
</message>
<message>
<location line="+3"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong Calcoin will not work properly.</source>
<translation type="unfinished"></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"></translation>
</message>
<message>
<location line="+3"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+4"/>
<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"></translation>
</message>
<message>
<location line="+5"/>
<source>Accept command line and JSON-RPC commands</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Bind to given address. Use [host]:port notation for IPv6</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Block creation options:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Cannot downgrade wallet</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Cannot initialize keypool</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Cannot write default address</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Connect only to the specified node(s)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Connect through socks proxy</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Don't generate coins</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Done loading</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Error loading blkindex.dat</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat: Wallet requires newer version of Calcoin</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Error</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Error: Transaction creation failed </source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Error: Wallet locked, unable to create transaction </source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Error: could not start node</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Fee per KB to add to transactions you send</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Find peers using DNS lookup (default: 1 unless -connect)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Find peers using internet relay chat (default: 0)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Calcoin version</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Calcoin</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Generate coins</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Get help for a command</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>How many blocks to check at startup (default: 2500, 0 = all)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-6, default: 1)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Importing blockchain data file.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Importing bootstrap blockchain data file.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Imports blocks from external blk000?.dat file</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Insufficient funds</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Invalid -proxy address: '%s'</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Invalid -tor address: '%s'</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>List commands</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Listen for connections on <port> (default: 8639 or testnet: 18639)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Loading addresses...</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Loading block index...</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Loading wallet...</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Options:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Password for JSON-RPC connections</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Prepend debug output with timestamp</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Rescanning...</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Run in the background as a daemon and accept commands</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>SSL options: (see the Calcoin Wiki for SSL setup instructions)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Send command to -server or calcoind</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Sending...</source>
<translation type="unfinished">L'enviament de ...</translation>
</message>
<message>
<location line="+1"/>
<source>Server certificate file (default: server.cert)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Set database disk log size in megabytes (default: 100)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Specify configuration file (default: calcoin.conf)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Specify data directory</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Specify pid file (default: calcoind.pid)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Specify your own public address</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>This help message</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>To use the %s option</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Upgrade wallet to latest format</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Usage:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Use the test network</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Username for JSON-RPC connections</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Verifying database integrity...</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Wallet needed to be rewritten: restart Calcoin to complete</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Warning: Disk space is low!</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation type="unfinished"></translation>
</message>
</context>
</TS><|fim▁end|> | |
<|file_name|>message_box_dialog.cc<|end_file_name|><|fim▁begin|>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/simple_message_box.h"
#include <utility>
#include "base/bind.h"
#include "base/callback.h"
#include "base/compiler_specific.h"
#include "base/macros.h"
#include "base/message_loop/message_loop_current.h"
#include "base/run_loop.h"
#include "build/build_config.h"
#include "chrome/browser/ui/browser_dialogs.h"
#include "chrome/browser/ui/simple_message_box_internal.h"
#include "chrome/browser/ui/views/message_box_dialog.h"
#include "chrome/grit/generated_resources.h"
#include "components/constrained_window/constrained_window_views.h"
#include "components/startup_metric_utils/browser/startup_metric_utils.h"
#include "components/strings/grit/components_strings.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/display/screen.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/views/controls/message_box_view.h"
#include "ui/views/widget/widget.h"
#include "ui/views/window/dialog_delegate.h"
#if defined(OS_WIN)
#include "ui/base/win/message_box_win.h"
#include "ui/views/win/hwnd_util.h"
#endif
#if defined(OS_MACOSX)
#include "chrome/browser/ui/cocoa/simple_message_box_cocoa.h"
#endif
namespace {
#if defined(OS_WIN)
UINT GetMessageBoxFlagsFromType(chrome::MessageBoxType type) {
UINT flags = MB_SETFOREGROUND;
switch (type) {
case chrome::MESSAGE_BOX_TYPE_WARNING:
return flags | MB_OK | MB_ICONWARNING;
case chrome::MESSAGE_BOX_TYPE_QUESTION:
return flags | MB_YESNO | MB_ICONQUESTION;
}
NOTREACHED();
return flags | MB_OK | MB_ICONWARNING;
}
#endif
// static
chrome::MessageBoxResult ShowSync(gfx::NativeWindow parent,
const base::string16& title,
const base::string16& message,
chrome::MessageBoxType type,
const base::string16& yes_text,
const base::string16& no_text,
const base::string16& checkbox_text) {
chrome::MessageBoxResult result = chrome::MESSAGE_BOX_RESULT_NO;
// TODO(pkotwicz): Exit message loop when the dialog is closed by some other
// means than |Cancel| or |Accept|. crbug.com/404385
base::RunLoop run_loop(base::RunLoop::Type::kNestableTasksAllowed);
MessageBoxDialog::Show(
parent, title, message, type, yes_text, no_text, checkbox_text,
base::BindOnce(
[](base::RunLoop* run_loop, chrome::MessageBoxResult* out_result,
chrome::MessageBoxResult messagebox_result) {
*out_result = messagebox_result;
run_loop->Quit();
},
&run_loop, &result));
run_loop.Run();
return result;
}
} // namespace
////////////////////////////////////////////////////////////////////////////////
// MessageBoxDialog, public:
// static
chrome::MessageBoxResult MessageBoxDialog::Show(
gfx::NativeWindow parent,
const base::string16& title,
const base::string16& message,
chrome::MessageBoxType type,
const base::string16& yes_text,
const base::string16& no_text,
const base::string16& checkbox_text,
MessageBoxDialog::MessageBoxResultCallback callback) {
if (!callback)
return ShowSync(parent, title, message, type, yes_text, no_text,
checkbox_text);
startup_metric_utils::SetNonBrowserUIDisplayed();
if (chrome::internal::g_should_skip_message_box_for_test) {
std::move(callback).Run(chrome::MESSAGE_BOX_RESULT_YES);
return chrome::MESSAGE_BOX_RESULT_DEFERRED;
}
// Views dialogs cannot be shown outside the UI thread message loop or if the
// ResourceBundle is not initialized yet.
// Fallback to logging with a default response or a Windows MessageBox.
#if defined(OS_WIN)
if (!base::MessageLoopCurrentForUI::IsSet() ||
!base::RunLoop::IsRunningOnCurrentThread() ||
!ui::ResourceBundle::HasSharedInstance()) {
LOG_IF(ERROR, !checkbox_text.empty()) << "Dialog checkbox won't be shown";
int result = ui::MessageBox(views::HWNDForNativeWindow(parent), message,
title, GetMessageBoxFlagsFromType(type));
std::move(callback).Run((result == IDYES || result == IDOK)
? chrome::MESSAGE_BOX_RESULT_YES
: chrome::MESSAGE_BOX_RESULT_NO);
return chrome::MESSAGE_BOX_RESULT_DEFERRED;
}
#elif defined(OS_MACOSX)
if (!base::MessageLoopCurrentForUI::IsSet() ||
!base::RunLoop::IsRunningOnCurrentThread() ||
!ui::ResourceBundle::HasSharedInstance()) {
// Even though this function could return a value synchronously here in
// principle, in practice call sites do not expect any behavior other than a
// return of DEFERRED and an invocation of the callback.
std::move(callback).Run(
chrome::ShowMessageBoxCocoa(message, type, checkbox_text));
return chrome::MESSAGE_BOX_RESULT_DEFERRED;
}
#else
if (!base::MessageLoopCurrentForUI::IsSet() ||
!ui::ResourceBundle::HasSharedInstance() ||
!display::Screen::GetScreen()) {
LOG(ERROR) << "Unable to show a dialog outside the UI thread message loop: "
<< title << " - " << message;
std::move(callback).Run(chrome::MESSAGE_BOX_RESULT_NO);
return chrome::MESSAGE_BOX_RESULT_DEFERRED;
}
#endif
bool is_system_modal = !parent;
#if defined(OS_MACOSX)
// Mac does not support system modals, so never ask MessageBoxDialog to
// be system modal.
is_system_modal = false;
#endif
MessageBoxDialog* dialog = new MessageBoxDialog(
title, message, type, yes_text, no_text, checkbox_text, is_system_modal);
views::Widget* widget =
constrained_window::CreateBrowserModalDialogViews(dialog, parent);
#if defined(OS_MACOSX)
// Mac does not support system modal dialogs. If there is no parent window to
// attach to, move the dialog's widget on top so other windows do not obscure
// it.
if (!parent)
widget->SetZOrderLevel(ui::ZOrderLevel::kFloatingWindow);
#endif
widget->Show();
dialog->Run(std::move(callback));
return chrome::MESSAGE_BOX_RESULT_DEFERRED;
}
void MessageBoxDialog::OnDialogAccepted() {
if (!message_box_view_->HasCheckBox() ||
message_box_view_->IsCheckBoxSelected()) {
Done(chrome::MESSAGE_BOX_RESULT_YES);
} else {
Done(chrome::MESSAGE_BOX_RESULT_NO);
}
}
base::string16 MessageBoxDialog::GetWindowTitle() const {
return window_title_;
}
void MessageBoxDialog::DeleteDelegate() {
delete this;
}
ui::ModalType MessageBoxDialog::GetModalType() const {
return is_system_modal_ ? ui::MODAL_TYPE_SYSTEM : ui::MODAL_TYPE_WINDOW;
}
views::View* MessageBoxDialog::GetContentsView() {
return message_box_view_;
}
bool MessageBoxDialog::ShouldShowCloseButton() const {
return true;
}
void MessageBoxDialog::OnWidgetActivationChanged(views::Widget* widget,
bool active) {
if (!active)
GetWidget()->Close();
}
////////////////////////////////////////////////////////////////////////////////
// MessageBoxDialog, private:
MessageBoxDialog::MessageBoxDialog(const base::string16& title,
const base::string16& message,
chrome::MessageBoxType type,
const base::string16& yes_text,
const base::string16& no_text,
const base::string16& checkbox_text,
bool is_system_modal)
: window_title_(title),
type_(type),
message_box_view_(new views::MessageBoxView(
views::MessageBoxView::InitParams(message))),
is_system_modal_(is_system_modal) {
SetButtons(type_ == chrome::MESSAGE_BOX_TYPE_QUESTION
? ui::DIALOG_BUTTON_OK | ui::DIALOG_BUTTON_CANCEL
: ui::DIALOG_BUTTON_OK);
SetAcceptCallback(base::BindOnce(&MessageBoxDialog::OnDialogAccepted,
base::Unretained(this)));
SetCancelCallback(base::BindOnce(&MessageBoxDialog::Done,
base::Unretained(this),
chrome::MESSAGE_BOX_RESULT_NO));
SetCloseCallback(base::BindOnce(&MessageBoxDialog::Done,
base::Unretained(this),
chrome::MESSAGE_BOX_RESULT_NO));
base::string16 ok_text = yes_text;
if (ok_text.empty()) {
ok_text =
type_ == chrome::MESSAGE_BOX_TYPE_QUESTION
? l10n_util::GetStringUTF16(IDS_CONFIRM_MESSAGEBOX_YES_BUTTON_LABEL)<|fim▁hole|> // Only MESSAGE_BOX_TYPE_QUESTION has a Cancel button.
if (type_ == chrome::MESSAGE_BOX_TYPE_QUESTION) {
base::string16 cancel_text = no_text;
if (cancel_text.empty())
cancel_text = l10n_util::GetStringUTF16(IDS_CANCEL);
SetButtonLabel(ui::DIALOG_BUTTON_CANCEL, cancel_text);
}
if (!checkbox_text.empty())
message_box_view_->SetCheckBoxLabel(checkbox_text);
chrome::RecordDialogCreation(chrome::DialogIdentifier::SIMPLE_MESSAGE_BOX);
}
MessageBoxDialog::~MessageBoxDialog() {
GetWidget()->RemoveObserver(this);
}
void MessageBoxDialog::Run(MessageBoxResultCallback result_callback) {
GetWidget()->AddObserver(this);
result_callback_ = std::move(result_callback);
}
void MessageBoxDialog::Done(chrome::MessageBoxResult result) {
CHECK(!result_callback_.is_null());
std::move(result_callback_).Run(result);
}
views::Widget* MessageBoxDialog::GetWidget() {
return message_box_view_->GetWidget();
}
const views::Widget* MessageBoxDialog::GetWidget() const {
return message_box_view_->GetWidget();
}
namespace chrome {
void ShowWarningMessageBox(gfx::NativeWindow parent,
const base::string16& title,
const base::string16& message) {
MessageBoxDialog::Show(parent, title, message,
chrome::MESSAGE_BOX_TYPE_WARNING, base::string16(),
base::string16(), base::string16());
}
void ShowWarningMessageBoxWithCheckbox(
gfx::NativeWindow parent,
const base::string16& title,
const base::string16& message,
const base::string16& checkbox_text,
base::OnceCallback<void(bool checked)> callback) {
MessageBoxDialog::Show(parent, title, message,
chrome::MESSAGE_BOX_TYPE_WARNING, base::string16(),
base::string16(), checkbox_text,
base::BindOnce(
[](base::OnceCallback<void(bool checked)> callback,
MessageBoxResult message_box_result) {
std::move(callback).Run(message_box_result ==
MESSAGE_BOX_RESULT_YES);
},
base::Passed(std::move(callback))));
}
MessageBoxResult ShowQuestionMessageBox(gfx::NativeWindow parent,
const base::string16& title,
const base::string16& message) {
return MessageBoxDialog::Show(
parent, title, message, chrome::MESSAGE_BOX_TYPE_QUESTION,
base::string16(), base::string16(), base::string16());
}
MessageBoxResult ShowMessageBoxWithButtonText(gfx::NativeWindow parent,
const base::string16& title,
const base::string16& message,
const base::string16& yes_text,
const base::string16& no_text) {
return MessageBoxDialog::Show(parent, title, message,
chrome::MESSAGE_BOX_TYPE_QUESTION, yes_text,
no_text, base::string16());
}
} // namespace chrome<|fim▁end|> | : l10n_util::GetStringUTF16(IDS_OK);
}
SetButtonLabel(ui::DIALOG_BUTTON_OK, ok_text);
|
<|file_name|>atom.rs<|end_file_name|><|fim▁begin|>use crate::syntax::Type;
use proc_macro2::Ident;
use std::fmt::{self, Display};
#[derive(Copy, Clone, PartialEq)]
pub enum Atom {
Bool,
Char, // C char, not Rust char
U8,
U16,
U32,
U64,
Usize,
I8,
I16,
I32,
I64,
Isize,
F32,
F64,
CxxString,
RustString,
}
impl Atom {
pub fn from(ident: &Ident) -> Option<Self> {
Self::from_str(ident.to_string().as_str())<|fim▁hole|> use self::Atom::*;
match s {
"bool" => Some(Bool),
"c_char" => Some(Char),
"u8" => Some(U8),
"u16" => Some(U16),
"u32" => Some(U32),
"u64" => Some(U64),
"usize" => Some(Usize),
"i8" => Some(I8),
"i16" => Some(I16),
"i32" => Some(I32),
"i64" => Some(I64),
"isize" => Some(Isize),
"f32" => Some(F32),
"f64" => Some(F64),
"CxxString" => Some(CxxString),
"String" => Some(RustString),
_ => None,
}
}
}
impl Display for Atom {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str(self.as_ref())
}
}
impl AsRef<str> for Atom {
fn as_ref(&self) -> &str {
use self::Atom::*;
match self {
Bool => "bool",
Char => "c_char",
U8 => "u8",
U16 => "u16",
U32 => "u32",
U64 => "u64",
Usize => "usize",
I8 => "i8",
I16 => "i16",
I32 => "i32",
I64 => "i64",
Isize => "isize",
F32 => "f32",
F64 => "f64",
CxxString => "CxxString",
RustString => "String",
}
}
}
impl PartialEq<Atom> for Type {
fn eq(&self, atom: &Atom) -> bool {
match self {
Type::Ident(ident) => ident.rust == atom,
_ => false,
}
}
}
impl PartialEq<Atom> for &Ident {
fn eq(&self, atom: &Atom) -> bool {
*self == atom
}
}
impl PartialEq<Atom> for &Type {
fn eq(&self, atom: &Atom) -> bool {
*self == atom
}
}<|fim▁end|> | }
pub fn from_str(s: &str) -> Option<Self> { |
<|file_name|>auth.guard.ts<|end_file_name|><|fim▁begin|>import { Inject, Injectable } from '@angular/core';
import { CanActivate, Router } from "@angular/router";
import { AuthService } from "../services/auth.service";<|fim▁hole|> constructor(private _auth: AuthService,
private _router: Router) { }
canActivate(): boolean {
if (!this._auth.isLoggedIn()) {
this._router.navigate(['/login']);
return false;
}
return true;
}
}<|fim▁end|> |
@Injectable()
export class AuthGuard implements CanActivate { |
<|file_name|>keyboard.js<|end_file_name|><|fim▁begin|>define(['omega/entity', 'omega/core'], function (e, o) {
'use strict';
var triggerKey = function (action, e) {
o.trigger(action, {
keyCode: e.keyCode,<|fim▁hole|> shiftKey: e.shiftKey,
ctrlKey: e.ctrlKey,
altKey: e.altKey
});
};
window.onkeydown = function (e) {
triggerKey('KeyDown', e);
};
window.onkeyup = function (e) {
triggerKey('KeyUp', e);
};
// ---
return e.extend({
keyboard: {keys: {}},
init: function () {
o.bind('KeyDown', function (e) {
this.keyboard.keys[e.keyCode] = true;
this.trigger('KeyDown', e);
}, this);
o.bind('KeyUp', function (e) {
this.keyboard.keys[e.keyCode] = false;
this.trigger('KeyUp', e);
}, this);
},
isKeyDown: function (keyCode) {
return (this.keyboard.keys[keyCode]);
}
});
});<|fim▁end|> | |
<|file_name|>encoder.rs<|end_file_name|><|fim▁begin|>// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Metadata encoding
#![allow(unused_must_use)] // everything is just a MemWriter, can't fail
#![allow(non_camel_case_types)]
pub use self::InlinedItemRef::*;
use ast_map::{self, LinkedPath, PathElem, PathElems};
use back::svh::Svh;
use session::config;
use metadata::common::*;
use metadata::cstore;
use metadata::decoder;
use metadata::tyencode;
use middle::def;
use middle::ty::{self, Ty};
use middle::stability;
use util::nodemap::{FnvHashMap, NodeMap, NodeSet};
use serialize::Encodable;
use std::cell::RefCell;
use std::hash::{Hash, Hasher, SipHasher};
use std::io::prelude::*;
use std::io::{Cursor, SeekFrom};
use syntax::abi;
use syntax::ast::{self, DefId, NodeId};
use syntax::ast_util::*;
use syntax::ast_util;
use syntax::attr;
use syntax::attr::AttrMetaMethods;
use syntax::diagnostic::SpanHandler;
use syntax::parse::token::special_idents;
use syntax::parse::token;
use syntax::print::pprust;
use syntax::ptr::P;
use syntax::visit::Visitor;
use syntax::visit;
use syntax;
use rbml::writer::Encoder;
/// A borrowed version of `ast::InlinedItem`.
pub enum InlinedItemRef<'a> {
IIItemRef(&'a ast::Item),
IITraitItemRef(DefId, &'a ast::TraitItem),
IIImplItemRef(DefId, &'a ast::ImplItem),
IIForeignRef(&'a ast::ForeignItem)
}
pub type EncodeInlinedItem<'a> =
Box<FnMut(&EncodeContext, &mut Encoder, InlinedItemRef) + 'a>;
pub struct EncodeParams<'a, 'tcx: 'a> {
pub diag: &'a SpanHandler,
pub tcx: &'a ty::ctxt<'tcx>,
pub reexports: &'a def::ExportMap,
pub item_symbols: &'a RefCell<NodeMap<String>>,
pub link_meta: &'a LinkMeta,
pub cstore: &'a cstore::CStore,
pub encode_inlined_item: EncodeInlinedItem<'a>,
pub reachable: &'a NodeSet,
}
pub struct EncodeContext<'a, 'tcx: 'a> {
pub diag: &'a SpanHandler,
pub tcx: &'a ty::ctxt<'tcx>,
pub reexports: &'a def::ExportMap,
pub item_symbols: &'a RefCell<NodeMap<String>>,
pub link_meta: &'a LinkMeta,
pub cstore: &'a cstore::CStore,
pub encode_inlined_item: RefCell<EncodeInlinedItem<'a>>,
pub type_abbrevs: tyencode::abbrev_map<'tcx>,
pub reachable: &'a NodeSet,
}
fn encode_name(rbml_w: &mut Encoder, name: ast::Name) {
rbml_w.wr_tagged_str(tag_paths_data_name, &token::get_name(name));
}
fn encode_impl_type_basename(rbml_w: &mut Encoder, name: ast::Name) {
rbml_w.wr_tagged_str(tag_item_impl_type_basename, &token::get_name(name));
}
fn encode_def_id(rbml_w: &mut Encoder, id: DefId) {
rbml_w.wr_tagged_u64(tag_def_id, def_to_u64(id));
}
#[derive(Clone)]
struct entry<T> {
val: T,
pos: u64
}
fn encode_trait_ref<'a, 'tcx>(rbml_w: &mut Encoder,
ecx: &EncodeContext<'a, 'tcx>,
trait_ref: ty::TraitRef<'tcx>,
tag: usize) {
let ty_str_ctxt = &tyencode::ctxt {
diag: ecx.diag,
ds: def_to_string,
tcx: ecx.tcx,
abbrevs: &ecx.type_abbrevs
};
rbml_w.start_tag(tag);
tyencode::enc_trait_ref(rbml_w, ty_str_ctxt, trait_ref);
rbml_w.end_tag();
}
// Item info table encoding
fn encode_family(rbml_w: &mut Encoder, c: char) {
rbml_w.wr_tagged_u8(tag_items_data_item_family, c as u8);
}
pub fn def_to_u64(did: DefId) -> u64 {
(did.krate as u64) << 32 | (did.node as u64)
}
pub fn def_to_string(did: DefId) -> String {
format!("{}:{}", did.krate, did.node)
}
fn encode_item_variances(rbml_w: &mut Encoder,
ecx: &EncodeContext,
id: NodeId) {
let v = ecx.tcx.item_variances(ast_util::local_def(id));
rbml_w.start_tag(tag_item_variances);
v.encode(rbml_w);
rbml_w.end_tag();
}
fn encode_bounds_and_type_for_item<'a, 'tcx>(rbml_w: &mut Encoder,
ecx: &EncodeContext<'a, 'tcx>,
id: ast::NodeId) {
encode_bounds_and_type(rbml_w,
ecx,
&ecx.tcx.lookup_item_type(local_def(id)),
&ecx.tcx.lookup_predicates(local_def(id)));
}
fn encode_bounds_and_type<'a, 'tcx>(rbml_w: &mut Encoder,
ecx: &EncodeContext<'a, 'tcx>,
scheme: &ty::TypeScheme<'tcx>,
predicates: &ty::GenericPredicates<'tcx>) {
encode_generics(rbml_w, ecx, &scheme.generics, &predicates, tag_item_generics);
encode_type(ecx, rbml_w, scheme.ty);
}
fn encode_variant_id(rbml_w: &mut Encoder, vid: DefId) {
let id = def_to_u64(vid);
rbml_w.wr_tagged_u64(tag_items_data_item_variant, id);
rbml_w.wr_tagged_u64(tag_mod_child, id);
}
pub fn write_closure_type<'a, 'tcx>(ecx: &EncodeContext<'a, 'tcx>,
rbml_w: &mut Encoder,
closure_type: &ty::ClosureTy<'tcx>) {
let ty_str_ctxt = &tyencode::ctxt {
diag: ecx.diag,
ds: def_to_string,
tcx: ecx.tcx,
abbrevs: &ecx.type_abbrevs
};
tyencode::enc_closure_ty(rbml_w, ty_str_ctxt, closure_type);
}
pub fn write_type<'a, 'tcx>(ecx: &EncodeContext<'a, 'tcx>,
rbml_w: &mut Encoder,
typ: Ty<'tcx>) {
let ty_str_ctxt = &tyencode::ctxt {
diag: ecx.diag,
ds: def_to_string,
tcx: ecx.tcx,
abbrevs: &ecx.type_abbrevs
};
tyencode::enc_ty(rbml_w, ty_str_ctxt, typ);
}
pub fn write_trait_ref<'a, 'tcx>(ecx: &EncodeContext<'a, 'tcx>,
rbml_w: &mut Encoder,
trait_ref: &ty::TraitRef<'tcx>) {
let ty_str_ctxt = &tyencode::ctxt {
diag: ecx.diag,
ds: def_to_string,
tcx: ecx.tcx,
abbrevs: &ecx.type_abbrevs
};
tyencode::enc_trait_ref(rbml_w, ty_str_ctxt, *trait_ref);
}
pub fn write_region(ecx: &EncodeContext,
rbml_w: &mut Encoder,
r: ty::Region) {
let ty_str_ctxt = &tyencode::ctxt {
diag: ecx.diag,
ds: def_to_string,
tcx: ecx.tcx,
abbrevs: &ecx.type_abbrevs
};
tyencode::enc_region(rbml_w, ty_str_ctxt, r);
}
fn encode_type<'a, 'tcx>(ecx: &EncodeContext<'a, 'tcx>,
rbml_w: &mut Encoder,
typ: Ty<'tcx>) {
rbml_w.start_tag(tag_items_data_item_type);
write_type(ecx, rbml_w, typ);
rbml_w.end_tag();
}
fn encode_region(ecx: &EncodeContext,
rbml_w: &mut Encoder,
r: ty::Region) {
rbml_w.start_tag(tag_items_data_region);
write_region(ecx, rbml_w, r);
rbml_w.end_tag();
}
fn encode_method_fty<'a, 'tcx>(ecx: &EncodeContext<'a, 'tcx>,
rbml_w: &mut Encoder,
typ: &ty::BareFnTy<'tcx>) {
rbml_w.start_tag(tag_item_method_fty);
let ty_str_ctxt = &tyencode::ctxt {
diag: ecx.diag,
ds: def_to_string,
tcx: ecx.tcx,
abbrevs: &ecx.type_abbrevs
};
tyencode::enc_bare_fn_ty(rbml_w, ty_str_ctxt, typ);
rbml_w.end_tag();
}
fn encode_symbol(ecx: &EncodeContext,
rbml_w: &mut Encoder,
id: NodeId) {
match ecx.item_symbols.borrow().get(&id) {
Some(x) => {
debug!("encode_symbol(id={}, str={})", id, *x);
rbml_w.wr_tagged_str(tag_items_data_item_symbol, x);
}
None => {
ecx.diag.handler().bug(
&format!("encode_symbol: id not found {}", id));
}
}
}
fn encode_disr_val(_: &EncodeContext,
rbml_w: &mut Encoder,
disr_val: ty::Disr) {
rbml_w.wr_tagged_str(tag_disr_val, &disr_val.to_string());
}
fn encode_parent_item(rbml_w: &mut Encoder, id: DefId) {
rbml_w.wr_tagged_u64(tag_items_data_parent_item, def_to_u64(id));
}
fn encode_struct_fields(rbml_w: &mut Encoder,
fields: &[ty::FieldTy],
origin: DefId) {
for f in fields {
if f.name == special_idents::unnamed_field.name {
rbml_w.start_tag(tag_item_unnamed_field);
} else {
rbml_w.start_tag(tag_item_field);
encode_name(rbml_w, f.name);
}
encode_struct_field_family(rbml_w, f.vis);
encode_def_id(rbml_w, f.id);
rbml_w.wr_tagged_u64(tag_item_field_origin, def_to_u64(origin));
rbml_w.end_tag();
}
}
fn encode_enum_variant_info(ecx: &EncodeContext,
rbml_w: &mut Encoder,
id: NodeId,
variants: &[P<ast::Variant>],
index: &mut Vec<entry<i64>>) {
debug!("encode_enum_variant_info(id={})", id);
let mut disr_val = 0;
let mut i = 0;
let vi = ecx.tcx.enum_variants(local_def(id));
for variant in variants {
let def_id = local_def(variant.node.id);
index.push(entry {
val: variant.node.id as i64,
pos: rbml_w.mark_stable_position(),
});
rbml_w.start_tag(tag_items_data_item);
encode_def_id(rbml_w, def_id);
match variant.node.kind {
ast::TupleVariantKind(_) => encode_family(rbml_w, 'v'),
ast::StructVariantKind(_) => encode_family(rbml_w, 'V')
}
encode_name(rbml_w, variant.node.name.name);
encode_parent_item(rbml_w, local_def(id));
encode_visibility(rbml_w, variant.node.vis);
encode_attributes(rbml_w, &variant.node.attrs);
encode_repr_attrs(rbml_w, ecx, &variant.node.attrs);
let stab = stability::lookup(ecx.tcx, ast_util::local_def(variant.node.id));
encode_stability(rbml_w, stab);
match variant.node.kind {
ast::TupleVariantKind(_) => {},
ast::StructVariantKind(_) => {
let fields = ecx.tcx.lookup_struct_fields(def_id);
let idx = encode_info_for_struct(ecx,
rbml_w,
&fields[..],
index);
encode_struct_fields(rbml_w, &fields[..], def_id);
encode_index(rbml_w, idx, write_i64);
}
}
let specified_disr_val = vi[i].disr_val;
if specified_disr_val != disr_val {
encode_disr_val(ecx, rbml_w, specified_disr_val);
disr_val = specified_disr_val;
}
encode_bounds_and_type_for_item(rbml_w, ecx, def_id.local_id());
ecx.tcx.map.with_path(variant.node.id, |path| encode_path(rbml_w, path));
rbml_w.end_tag();
disr_val = disr_val.wrapping_add(1);
i += 1;
}
}
fn encode_path<PI: Iterator<Item=PathElem>>(rbml_w: &mut Encoder, path: PI) {
let path = path.collect::<Vec<_>>();
rbml_w.start_tag(tag_path);
rbml_w.wr_tagged_u32(tag_path_len, path.len() as u32);
for pe in &path {
let tag = match *pe {
ast_map::PathMod(_) => tag_path_elem_mod,
ast_map::PathName(_) => tag_path_elem_name
};
rbml_w.wr_tagged_str(tag, &token::get_name(pe.name()));
}
rbml_w.end_tag();
}
fn encode_reexported_static_method(rbml_w: &mut Encoder,
exp: &def::Export,
method_def_id: DefId,
method_name: ast::Name) {
debug!("(encode reexported static method) {}::{}",
exp.name, token::get_name(method_name));
rbml_w.start_tag(tag_items_data_item_reexport);
rbml_w.wr_tagged_u64(tag_items_data_item_reexport_def_id,
def_to_u64(method_def_id));
rbml_w.wr_tagged_str(tag_items_data_item_reexport_name,
&format!("{}::{}", exp.name,
token::get_name(method_name)));
rbml_w.end_tag();
}
fn encode_reexported_static_base_methods(ecx: &EncodeContext,
rbml_w: &mut Encoder,
exp: &def::Export)
-> bool {
let impl_items = ecx.tcx.impl_items.borrow();
match ecx.tcx.inherent_impls.borrow().get(&exp.def_id) {
Some(implementations) => {
for base_impl_did in implementations.iter() {
for &method_did in impl_items.get(base_impl_did).unwrap() {
let impl_item = ecx.tcx.impl_or_trait_item(method_did.def_id());
if let ty::MethodTraitItem(ref m) = impl_item {
encode_reexported_static_method(rbml_w,
exp,
m.def_id,
m.name);
}
}
}
true
}
None => { false }
}
}
fn encode_reexported_static_trait_methods(ecx: &EncodeContext,
rbml_w: &mut Encoder,
exp: &def::Export)
-> bool {
match ecx.tcx.trait_items_cache.borrow().get(&exp.def_id) {
Some(trait_items) => {
for trait_item in trait_items.iter() {
if let ty::MethodTraitItem(ref m) = *trait_item {
encode_reexported_static_method(rbml_w,
exp,
m.def_id,
m.name);
}
}
true
}
None => { false }
}
}
fn encode_reexported_static_methods(ecx: &EncodeContext,
rbml_w: &mut Encoder,
mod_path: PathElems,
exp: &def::Export) {
if let Some(ast_map::NodeItem(item)) = ecx.tcx.map.find(exp.def_id.node) {
let path_differs = ecx.tcx.map.with_path(exp.def_id.node, |path| {
let (mut a, mut b) = (path, mod_path.clone());
loop {
match (a.next(), b.next()) {
(None, None) => return true,
(None, _) | (_, None) => return false,
(Some(x), Some(y)) => if x != y { return false },
}
}
});
//
// We don't need to reexport static methods on items
// declared in the same module as our `pub use ...` since
// that's done when we encode the item itself.
//
// The only exception is when the reexport *changes* the
// name e.g. `pub use Foo = self::Bar` -- we have
// encoded metadata for static methods relative to Bar,
// but not yet for Foo.
//
if path_differs || item.ident.name != exp.name {
if !encode_reexported_static_base_methods(ecx, rbml_w, exp) {
if encode_reexported_static_trait_methods(ecx, rbml_w, exp) {
debug!("(encode reexported static methods) {} [trait]",
item.ident.name);
}
}
else {
debug!("(encode reexported static methods) {} [base]",
item.ident.name);
}
}
}
}
/// Iterates through "auxiliary node IDs", which are node IDs that describe
/// top-level items that are sub-items of the given item. Specifically:
///
/// * For newtype structs, iterates through the node ID of the constructor.
fn each_auxiliary_node_id<F>(item: &ast::Item, callback: F) -> bool where
F: FnOnce(NodeId) -> bool,
{
let mut continue_ = true;
match item.node {
ast::ItemStruct(ref struct_def, _) => {
// If this is a newtype struct, return the constructor.
match struct_def.ctor_id {
Some(ctor_id) if !struct_def.fields.is_empty() &&
struct_def.fields[0].node.kind.is_unnamed() => {
continue_ = callback(ctor_id);
}
_ => {}
}
}
_ => {}
}
continue_
}
fn encode_reexports(ecx: &EncodeContext,
rbml_w: &mut Encoder,
id: NodeId,
path: PathElems) {
debug!("(encoding info for module) encoding reexports for {}", id);
match ecx.reexports.get(&id) {
Some(exports) => {
debug!("(encoding info for module) found reexports for {}", id);
for exp in exports {
debug!("(encoding info for module) reexport '{}' ({}/{}) for \
{}",
exp.name,
exp.def_id.krate,
exp.def_id.node,
id);
rbml_w.start_tag(tag_items_data_item_reexport);
rbml_w.wr_tagged_u64(tag_items_data_item_reexport_def_id,
def_to_u64(exp.def_id));
rbml_w.wr_tagged_str(tag_items_data_item_reexport_name,
exp.name.as_str());
rbml_w.end_tag();
encode_reexported_static_methods(ecx, rbml_w, path.clone(), exp);
}
}
None => {
debug!("(encoding info for module) found no reexports for {}",
id);
}
}
}
fn encode_info_for_mod(ecx: &EncodeContext,
rbml_w: &mut Encoder,
md: &ast::Mod,
attrs: &[ast::Attribute],
id: NodeId,
path: PathElems,
name: ast::Name,
vis: ast::Visibility) {
rbml_w.start_tag(tag_items_data_item);
encode_def_id(rbml_w, local_def(id));
encode_family(rbml_w, 'm');
encode_name(rbml_w, name);
debug!("(encoding info for module) encoding info for module ID {}", id);
// Encode info about all the module children.
for item in &md.items {
rbml_w.wr_tagged_u64(tag_mod_child,
def_to_u64(local_def(item.id)));
each_auxiliary_node_id(&**item, |auxiliary_node_id| {
rbml_w.wr_tagged_u64(tag_mod_child,
def_to_u64(local_def(auxiliary_node_id)));
true
});
if let ast::ItemImpl(..) = item.node {
let (ident, did) = (item.ident, item.id);
debug!("(encoding info for module) ... encoding impl {} ({}/{})",
token::get_ident(ident),
did, ecx.tcx.map.node_to_string(did));
rbml_w.wr_tagged_u64(tag_mod_impl, def_to_u64(local_def(did)));
}
}
encode_path(rbml_w, path.clone());
encode_visibility(rbml_w, vis);
let stab = stability::lookup(ecx.tcx, ast_util::local_def(id));
encode_stability(rbml_w, stab);
// Encode the reexports of this module, if this module is public.
if vis == ast::Public {
debug!("(encoding info for module) encoding reexports for {}", id);
encode_reexports(ecx, rbml_w, id, path);
}
encode_attributes(rbml_w, attrs);
rbml_w.end_tag();
}
fn encode_struct_field_family(rbml_w: &mut Encoder,
visibility: ast::Visibility) {
encode_family(rbml_w, match visibility {
ast::Public => 'g',
ast::Inherited => 'N'
});
}
fn encode_visibility(rbml_w: &mut Encoder, visibility: ast::Visibility) {
let ch = match visibility {
ast::Public => 'y',
ast::Inherited => 'i',
};
rbml_w.wr_tagged_u8(tag_items_data_item_visibility, ch as u8);
}
fn encode_constness(rbml_w: &mut Encoder, constness: ast::Constness) {
rbml_w.start_tag(tag_items_data_item_constness);
let ch = match constness {
ast::Constness::Const => 'c',
ast::Constness::NotConst => 'n',
};
rbml_w.wr_str(&ch.to_string());
rbml_w.end_tag();
}
fn encode_explicit_self(rbml_w: &mut Encoder,
explicit_self: &ty::ExplicitSelfCategory) {
let tag = tag_item_trait_method_explicit_self;
// Encode the base self type.
match *explicit_self {
ty::StaticExplicitSelfCategory => {
rbml_w.wr_tagged_bytes(tag, &['s' as u8]);
}
ty::ByValueExplicitSelfCategory => {
rbml_w.wr_tagged_bytes(tag, &['v' as u8]);
}
ty::ByBoxExplicitSelfCategory => {
rbml_w.wr_tagged_bytes(tag, &['~' as u8]);
}
ty::ByReferenceExplicitSelfCategory(_, m) => {
// FIXME(#4846) encode custom lifetime
let ch = encode_mutability(m);
rbml_w.wr_tagged_bytes(tag, &['&' as u8, ch]);
}
}
fn encode_mutability(m: ast::Mutability) -> u8 {
match m {
ast::MutImmutable => 'i' as u8,
ast::MutMutable => 'm' as u8,
}
}
}
fn encode_item_sort(rbml_w: &mut Encoder, sort: char) {
rbml_w.wr_tagged_u8(tag_item_trait_item_sort, sort as u8);
}
fn encode_parent_sort(rbml_w: &mut Encoder, sort: char) {
rbml_w.wr_tagged_u8(tag_item_trait_parent_sort, sort as u8);
}
fn encode_provided_source(rbml_w: &mut Encoder,
source_opt: Option<DefId>) {
if let Some(source) = source_opt {
rbml_w.wr_tagged_u64(tag_item_method_provided_source, def_to_u64(source));
}
}
/* Returns an index of items in this class */
fn encode_info_for_struct(ecx: &EncodeContext,
rbml_w: &mut Encoder,
fields: &[ty::FieldTy],
global_index: &mut Vec<entry<i64>>)
-> Vec<entry<i64>> {
/* Each class has its own index, since different classes
may have fields with the same name */
let mut index = Vec::new();
/* We encode both private and public fields -- need to include
private fields to get the offsets right */
for field in fields {
let nm = field.name;
let id = field.id.node;
let pos = rbml_w.mark_stable_position();
index.push(entry {val: id as i64, pos: pos});
global_index.push(entry {
val: id as i64,
pos: pos,
});
rbml_w.start_tag(tag_items_data_item);
debug!("encode_info_for_struct: doing {} {}",
token::get_name(nm), id);
encode_struct_field_family(rbml_w, field.vis);
encode_name(rbml_w, nm);
encode_bounds_and_type_for_item(rbml_w, ecx, id);
encode_def_id(rbml_w, local_def(id));
let stab = stability::lookup(ecx.tcx, field.id);
encode_stability(rbml_w, stab);
rbml_w.end_tag();
}
index
}
fn encode_info_for_struct_ctor(ecx: &EncodeContext,
rbml_w: &mut Encoder,
name: ast::Name,
ctor_id: NodeId,
index: &mut Vec<entry<i64>>,
struct_id: NodeId) {
index.push(entry {
val: ctor_id as i64,
pos: rbml_w.mark_stable_position(),
});
rbml_w.start_tag(tag_items_data_item);
encode_def_id(rbml_w, local_def(ctor_id));
encode_family(rbml_w, 'o');
encode_bounds_and_type_for_item(rbml_w, ecx, ctor_id);
encode_name(rbml_w, name);
ecx.tcx.map.with_path(ctor_id, |path| encode_path(rbml_w, path));
encode_parent_item(rbml_w, local_def(struct_id));
if ecx.item_symbols.borrow().contains_key(&ctor_id) {
encode_symbol(ecx, rbml_w, ctor_id);
}
let stab = stability::lookup(ecx.tcx, ast_util::local_def(ctor_id));
encode_stability(rbml_w, stab);
// indicate that this is a tuple struct ctor, because downstream users will normally want
// the tuple struct definition, but without this there is no way for them to tell that
// they actually have a ctor rather than a normal function
rbml_w.wr_tagged_bytes(tag_items_data_item_is_tuple_struct_ctor, &[]);
rbml_w.end_tag();
}
fn encode_generics<'a, 'tcx>(rbml_w: &mut Encoder,
ecx: &EncodeContext<'a, 'tcx>,
generics: &ty::Generics<'tcx>,
predicates: &ty::GenericPredicates<'tcx>,
tag: usize)
{
rbml_w.start_tag(tag);
// Type parameters
let ty_str_ctxt = &tyencode::ctxt {
diag: ecx.diag,
ds: def_to_string,
tcx: ecx.tcx,
abbrevs: &ecx.type_abbrevs
};
for param in &generics.types {
rbml_w.start_tag(tag_type_param_def);
tyencode::enc_type_param_def(rbml_w, ty_str_ctxt, param);
rbml_w.end_tag();
}
// Region parameters
for param in &generics.regions {
rbml_w.start_tag(tag_region_param_def);
rbml_w.start_tag(tag_region_param_def_ident);
encode_name(rbml_w, param.name);
rbml_w.end_tag();
rbml_w.wr_tagged_u64(tag_region_param_def_def_id,
def_to_u64(param.def_id));
rbml_w.wr_tagged_u64(tag_region_param_def_space,
param.space.to_uint() as u64);
rbml_w.wr_tagged_u64(tag_region_param_def_index,
param.index as u64);
for &bound_region in ¶m.bounds {
encode_region(ecx, rbml_w, bound_region);
}
rbml_w.end_tag();
}
encode_predicates_in_current_doc(rbml_w, ecx, predicates);
rbml_w.end_tag();
}
fn encode_predicates_in_current_doc<'a,'tcx>(rbml_w: &mut Encoder,
ecx: &EncodeContext<'a,'tcx>,
predicates: &ty::GenericPredicates<'tcx>)
{
let ty_str_ctxt = &tyencode::ctxt {
diag: ecx.diag,
ds: def_to_string,
tcx: ecx.tcx,
abbrevs: &ecx.type_abbrevs
};
for (space, _, predicate) in predicates.predicates.iter_enumerated() {
rbml_w.start_tag(tag_predicate);
rbml_w.wr_tagged_u8(tag_predicate_space, space as u8);
rbml_w.start_tag(tag_predicate_data);
tyencode::enc_predicate(rbml_w, ty_str_ctxt, predicate);
rbml_w.end_tag();
rbml_w.end_tag();
}
}
fn encode_predicates<'a,'tcx>(rbml_w: &mut Encoder,
ecx: &EncodeContext<'a,'tcx>,
predicates: &ty::GenericPredicates<'tcx>,
tag: usize)
{
rbml_w.start_tag(tag);
encode_predicates_in_current_doc(rbml_w, ecx, predicates);
rbml_w.end_tag();
}
fn encode_method_ty_fields<'a, 'tcx>(ecx: &EncodeContext<'a, 'tcx>,
rbml_w: &mut Encoder,
method_ty: &ty::Method<'tcx>) {
encode_def_id(rbml_w, method_ty.def_id);
encode_name(rbml_w, method_ty.name);
encode_generics(rbml_w, ecx, &method_ty.generics, &method_ty.predicates,
tag_method_ty_generics);
encode_method_fty(ecx, rbml_w, &method_ty.fty);
encode_visibility(rbml_w, method_ty.vis);
encode_explicit_self(rbml_w, &method_ty.explicit_self);
match method_ty.explicit_self {
ty::StaticExplicitSelfCategory => {
encode_family(rbml_w, STATIC_METHOD_FAMILY);
}
_ => encode_family(rbml_w, METHOD_FAMILY)
}
encode_provided_source(rbml_w, method_ty.provided_source);
}
fn encode_info_for_associated_const(ecx: &EncodeContext,
rbml_w: &mut Encoder,
associated_const: &ty::AssociatedConst,
impl_path: PathElems,
parent_id: NodeId,
impl_item_opt: Option<&ast::ImplItem>) {
debug!("encode_info_for_associated_const({:?},{:?})",
associated_const.def_id,
token::get_name(associated_const.name));
rbml_w.start_tag(tag_items_data_item);
encode_def_id(rbml_w, associated_const.def_id);
encode_name(rbml_w, associated_const.name);
encode_visibility(rbml_w, associated_const.vis);
encode_family(rbml_w, 'C');
encode_provided_source(rbml_w, associated_const.default);
encode_parent_item(rbml_w, local_def(parent_id));
encode_item_sort(rbml_w, 'C');
encode_bounds_and_type_for_item(rbml_w, ecx, associated_const.def_id.local_id());
let stab = stability::lookup(ecx.tcx, associated_const.def_id);
encode_stability(rbml_w, stab);
let elem = ast_map::PathName(associated_const.name);
encode_path(rbml_w, impl_path.chain(Some(elem)));
if let Some(ii) = impl_item_opt {
encode_attributes(rbml_w, &ii.attrs);
encode_inlined_item(ecx, rbml_w, IIImplItemRef(local_def(parent_id), ii));
}
rbml_w.end_tag();
}
fn encode_info_for_method<'a, 'tcx>(ecx: &EncodeContext<'a, 'tcx>,
rbml_w: &mut Encoder,
m: &ty::Method<'tcx>,
impl_path: PathElems,
is_default_impl: bool,
parent_id: NodeId,
impl_item_opt: Option<&ast::ImplItem>) {
debug!("encode_info_for_method: {:?} {:?}", m.def_id,
token::get_name(m.name));
rbml_w.start_tag(tag_items_data_item);
encode_method_ty_fields(ecx, rbml_w, m);
encode_parent_item(rbml_w, local_def(parent_id));
encode_item_sort(rbml_w, 'r');
let stab = stability::lookup(ecx.tcx, m.def_id);
encode_stability(rbml_w, stab);
// The type for methods gets encoded twice, which is unfortunate.
encode_bounds_and_type_for_item(rbml_w, ecx, m.def_id.local_id());
let elem = ast_map::PathName(m.name);
encode_path(rbml_w, impl_path.chain(Some(elem)));
if let Some(impl_item) = impl_item_opt {
if let ast::MethodImplItem(ref sig, _) = impl_item.node {
encode_attributes(rbml_w, &impl_item.attrs);
let scheme = ecx.tcx.lookup_item_type(m.def_id);
let any_types = !scheme.generics.types.is_empty();
let needs_inline = any_types || is_default_impl ||
attr::requests_inline(&impl_item.attrs);
if needs_inline || sig.constness == ast::Constness::Const {
encode_inlined_item(ecx, rbml_w, IIImplItemRef(local_def(parent_id),
impl_item));
}
encode_constness(rbml_w, sig.constness);
if !any_types {
encode_symbol(ecx, rbml_w, m.def_id.node);
}
encode_method_argument_names(rbml_w, &sig.decl);
}
}
rbml_w.end_tag();
}
fn encode_info_for_associated_type<'a, 'tcx>(ecx: &EncodeContext<'a, 'tcx>,
rbml_w: &mut Encoder,
associated_type: &ty::AssociatedType<'tcx>,
impl_path: PathElems,
parent_id: NodeId,
impl_item_opt: Option<&ast::ImplItem>) {
debug!("encode_info_for_associated_type({:?},{:?})",
associated_type.def_id,
token::get_name(associated_type.name));
rbml_w.start_tag(tag_items_data_item);
encode_def_id(rbml_w, associated_type.def_id);
encode_name(rbml_w, associated_type.name);
encode_visibility(rbml_w, associated_type.vis);
encode_family(rbml_w, 'y');
encode_parent_item(rbml_w, local_def(parent_id));
encode_item_sort(rbml_w, 't');
let stab = stability::lookup(ecx.tcx, associated_type.def_id);
encode_stability(rbml_w, stab);
let elem = ast_map::PathName(associated_type.name);
encode_path(rbml_w, impl_path.chain(Some(elem)));
if let Some(ii) = impl_item_opt {
encode_attributes(rbml_w, &ii.attrs);
} else {
encode_predicates(rbml_w, ecx,
&ecx.tcx.lookup_predicates(associated_type.def_id),
tag_item_generics);
}
if let Some(ty) = associated_type.ty {
encode_type(ecx, rbml_w, ty);
}
rbml_w.end_tag();
}
fn encode_method_argument_names(rbml_w: &mut Encoder,
decl: &ast::FnDecl) {
rbml_w.start_tag(tag_method_argument_names);
for arg in &decl.inputs {
let tag = tag_method_argument_name;
if let ast::PatIdent(_, ref path1, _) = arg.pat.node {
let name = token::get_name(path1.node.name);
rbml_w.wr_tagged_bytes(tag, name.as_bytes());
} else {
rbml_w.wr_tagged_bytes(tag, &[]);
}
}
rbml_w.end_tag();
}
fn encode_repr_attrs(rbml_w: &mut Encoder,
ecx: &EncodeContext,
attrs: &[ast::Attribute]) {
let mut repr_attrs = Vec::new();
for attr in attrs {
repr_attrs.extend(attr::find_repr_attrs(ecx.tcx.sess.diagnostic(),
attr));
}
rbml_w.start_tag(tag_items_data_item_repr);
repr_attrs.encode(rbml_w);
rbml_w.end_tag();
}
fn encode_inlined_item(ecx: &EncodeContext,
rbml_w: &mut Encoder,
ii: InlinedItemRef) {
let mut eii = ecx.encode_inlined_item.borrow_mut();
let eii: &mut EncodeInlinedItem = &mut *eii;
eii(ecx, rbml_w, ii)
}
const FN_FAMILY: char = 'f';
const STATIC_METHOD_FAMILY: char = 'F';
const METHOD_FAMILY: char = 'h';
// Encodes the inherent implementations of a structure, enumeration, or trait.
fn encode_inherent_implementations(ecx: &EncodeContext,
rbml_w: &mut Encoder,
def_id: DefId) {
match ecx.tcx.inherent_impls.borrow().get(&def_id) {
None => {}<|fim▁hole|> for &impl_def_id in implementations.iter() {
rbml_w.start_tag(tag_items_data_item_inherent_impl);
encode_def_id(rbml_w, impl_def_id);
rbml_w.end_tag();
}
}
}
}
// Encodes the implementations of a trait defined in this crate.
fn encode_extension_implementations(ecx: &EncodeContext,
rbml_w: &mut Encoder,
trait_def_id: DefId) {
assert!(ast_util::is_local(trait_def_id));
let def = ecx.tcx.lookup_trait_def(trait_def_id);
def.for_each_impl(ecx.tcx, |impl_def_id| {
rbml_w.start_tag(tag_items_data_item_extension_impl);
encode_def_id(rbml_w, impl_def_id);
rbml_w.end_tag();
});
}
fn encode_stability(rbml_w: &mut Encoder, stab_opt: Option<&attr::Stability>) {
stab_opt.map(|stab| {
rbml_w.start_tag(tag_items_data_item_stability);
stab.encode(rbml_w).unwrap();
rbml_w.end_tag();
});
}
fn encode_info_for_item(ecx: &EncodeContext,
rbml_w: &mut Encoder,
item: &ast::Item,
index: &mut Vec<entry<i64>>,
path: PathElems,
vis: ast::Visibility) {
let tcx = ecx.tcx;
fn add_to_index(item: &ast::Item, rbml_w: &mut Encoder,
index: &mut Vec<entry<i64>>) {
index.push(entry {
val: item.id as i64,
pos: rbml_w.mark_stable_position(),
});
}
debug!("encoding info for item at {}",
tcx.sess.codemap().span_to_string(item.span));
let def_id = local_def(item.id);
let stab = stability::lookup(tcx, ast_util::local_def(item.id));
match item.node {
ast::ItemStatic(_, m, _) => {
add_to_index(item, rbml_w, index);
rbml_w.start_tag(tag_items_data_item);
encode_def_id(rbml_w, def_id);
if m == ast::MutMutable {
encode_family(rbml_w, 'b');
} else {
encode_family(rbml_w, 'c');
}
encode_bounds_and_type_for_item(rbml_w, ecx, item.id);
encode_symbol(ecx, rbml_w, item.id);
encode_name(rbml_w, item.ident.name);
encode_path(rbml_w, path);
encode_visibility(rbml_w, vis);
encode_stability(rbml_w, stab);
encode_attributes(rbml_w, &item.attrs);
rbml_w.end_tag();
}
ast::ItemConst(_, _) => {
add_to_index(item, rbml_w, index);
rbml_w.start_tag(tag_items_data_item);
encode_def_id(rbml_w, def_id);
encode_family(rbml_w, 'C');
encode_bounds_and_type_for_item(rbml_w, ecx, item.id);
encode_name(rbml_w, item.ident.name);
encode_path(rbml_w, path);
encode_attributes(rbml_w, &item.attrs);
encode_inlined_item(ecx, rbml_w, IIItemRef(item));
encode_visibility(rbml_w, vis);
encode_stability(rbml_w, stab);
rbml_w.end_tag();
}
ast::ItemFn(ref decl, _, constness, _, ref generics, _) => {
add_to_index(item, rbml_w, index);
rbml_w.start_tag(tag_items_data_item);
encode_def_id(rbml_w, def_id);
encode_family(rbml_w, FN_FAMILY);
let tps_len = generics.ty_params.len();
encode_bounds_and_type_for_item(rbml_w, ecx, item.id);
encode_name(rbml_w, item.ident.name);
encode_path(rbml_w, path);
encode_attributes(rbml_w, &item.attrs);
let needs_inline = tps_len > 0 || attr::requests_inline(&item.attrs);
if needs_inline || constness == ast::Constness::Const {
encode_inlined_item(ecx, rbml_w, IIItemRef(item));
}
if tps_len == 0 {
encode_symbol(ecx, rbml_w, item.id);
}
encode_constness(rbml_w, constness);
encode_visibility(rbml_w, vis);
encode_stability(rbml_w, stab);
encode_method_argument_names(rbml_w, &**decl);
rbml_w.end_tag();
}
ast::ItemMod(ref m) => {
add_to_index(item, rbml_w, index);
encode_info_for_mod(ecx,
rbml_w,
m,
&item.attrs,
item.id,
path,
item.ident.name,
item.vis);
}
ast::ItemForeignMod(ref fm) => {
add_to_index(item, rbml_w, index);
rbml_w.start_tag(tag_items_data_item);
encode_def_id(rbml_w, def_id);
encode_family(rbml_w, 'n');
encode_name(rbml_w, item.ident.name);
encode_path(rbml_w, path);
// Encode all the items in this module.
for foreign_item in &fm.items {
rbml_w.wr_tagged_u64(tag_mod_child,
def_to_u64(local_def(foreign_item.id)));
}
encode_visibility(rbml_w, vis);
encode_stability(rbml_w, stab);
rbml_w.end_tag();
}
ast::ItemTy(..) => {
add_to_index(item, rbml_w, index);
rbml_w.start_tag(tag_items_data_item);
encode_def_id(rbml_w, def_id);
encode_family(rbml_w, 'y');
encode_bounds_and_type_for_item(rbml_w, ecx, item.id);
encode_name(rbml_w, item.ident.name);
encode_path(rbml_w, path);
encode_visibility(rbml_w, vis);
encode_stability(rbml_w, stab);
rbml_w.end_tag();
}
ast::ItemEnum(ref enum_definition, _) => {
add_to_index(item, rbml_w, index);
rbml_w.start_tag(tag_items_data_item);
encode_def_id(rbml_w, def_id);
encode_family(rbml_w, 't');
encode_item_variances(rbml_w, ecx, item.id);
encode_bounds_and_type_for_item(rbml_w, ecx, item.id);
encode_name(rbml_w, item.ident.name);
encode_attributes(rbml_w, &item.attrs);
encode_repr_attrs(rbml_w, ecx, &item.attrs);
for v in &enum_definition.variants {
encode_variant_id(rbml_w, local_def(v.node.id));
}
encode_inlined_item(ecx, rbml_w, IIItemRef(item));
encode_path(rbml_w, path);
// Encode inherent implementations for this enumeration.
encode_inherent_implementations(ecx, rbml_w, def_id);
encode_visibility(rbml_w, vis);
encode_stability(rbml_w, stab);
rbml_w.end_tag();
encode_enum_variant_info(ecx,
rbml_w,
item.id,
&(*enum_definition).variants,
index);
}
ast::ItemStruct(ref struct_def, _) => {
let fields = tcx.lookup_struct_fields(def_id);
/* First, encode the fields
These come first because we need to write them to make
the index, and the index needs to be in the item for the
class itself */
let idx = encode_info_for_struct(ecx,
rbml_w,
&fields[..],
index);
/* Index the class*/
add_to_index(item, rbml_w, index);
/* Now, make an item for the class itself */
rbml_w.start_tag(tag_items_data_item);
encode_def_id(rbml_w, def_id);
encode_family(rbml_w, 'S');
encode_bounds_and_type_for_item(rbml_w, ecx, item.id);
encode_item_variances(rbml_w, ecx, item.id);
encode_name(rbml_w, item.ident.name);
encode_attributes(rbml_w, &item.attrs);
encode_path(rbml_w, path.clone());
encode_stability(rbml_w, stab);
encode_visibility(rbml_w, vis);
encode_repr_attrs(rbml_w, ecx, &item.attrs);
/* Encode def_ids for each field and method
for methods, write all the stuff get_trait_method
needs to know*/
encode_struct_fields(rbml_w, &fields[..], def_id);
encode_inlined_item(ecx, rbml_w, IIItemRef(item));
// Encode inherent implementations for this structure.
encode_inherent_implementations(ecx, rbml_w, def_id);
/* Each class has its own index -- encode it */
encode_index(rbml_w, idx, write_i64);
rbml_w.end_tag();
// If this is a tuple-like struct, encode the type of the constructor.
match struct_def.ctor_id {
Some(ctor_id) => {
encode_info_for_struct_ctor(ecx, rbml_w, item.ident.name,
ctor_id, index, def_id.node);
}
None => {}
}
}
ast::ItemDefaultImpl(unsafety, _) => {
add_to_index(item, rbml_w, index);
rbml_w.start_tag(tag_items_data_item);
encode_def_id(rbml_w, def_id);
encode_family(rbml_w, 'd');
encode_name(rbml_w, item.ident.name);
encode_unsafety(rbml_w, unsafety);
let trait_ref = tcx.impl_trait_ref(local_def(item.id)).unwrap();
encode_trait_ref(rbml_w, ecx, trait_ref, tag_item_trait_ref);
rbml_w.end_tag();
}
ast::ItemImpl(unsafety, polarity, _, _, ref ty, ref ast_items) => {
// We need to encode information about the default methods we
// have inherited, so we drive this based on the impl structure.
let impl_items = tcx.impl_items.borrow();
let items = impl_items.get(&def_id).unwrap();
add_to_index(item, rbml_w, index);
rbml_w.start_tag(tag_items_data_item);
encode_def_id(rbml_w, def_id);
encode_family(rbml_w, 'i');
encode_bounds_and_type_for_item(rbml_w, ecx, item.id);
encode_name(rbml_w, item.ident.name);
encode_attributes(rbml_w, &item.attrs);
encode_unsafety(rbml_w, unsafety);
encode_polarity(rbml_w, polarity);
match tcx.custom_coerce_unsized_kinds.borrow().get(&local_def(item.id)) {
Some(&kind) => {
rbml_w.start_tag(tag_impl_coerce_unsized_kind);
kind.encode(rbml_w);
rbml_w.end_tag();
}
None => {}
}
match ty.node {
ast::TyPath(None, ref path) if path.segments.len() == 1 => {
let name = path.segments.last().unwrap().identifier.name;
encode_impl_type_basename(rbml_w, name);
}
_ => {}
}
for &item_def_id in items {
rbml_w.start_tag(tag_item_impl_item);
match item_def_id {
ty::ConstTraitItemId(item_def_id) => {
encode_def_id(rbml_w, item_def_id);
encode_item_sort(rbml_w, 'C');
}
ty::MethodTraitItemId(item_def_id) => {
encode_def_id(rbml_w, item_def_id);
encode_item_sort(rbml_w, 'r');
}
ty::TypeTraitItemId(item_def_id) => {
encode_def_id(rbml_w, item_def_id);
encode_item_sort(rbml_w, 't');
}
}
rbml_w.end_tag();
}
if let Some(trait_ref) = tcx.impl_trait_ref(local_def(item.id)) {
encode_trait_ref(rbml_w, ecx, trait_ref, tag_item_trait_ref);
}
encode_path(rbml_w, path.clone());
encode_stability(rbml_w, stab);
rbml_w.end_tag();
// Iterate down the trait items, emitting them. We rely on the
// assumption that all of the actually implemented trait items
// appear first in the impl structure, in the same order they do
// in the ast. This is a little sketchy.
let num_implemented_methods = ast_items.len();
for (i, &trait_item_def_id) in items.iter().enumerate() {
let ast_item = if i < num_implemented_methods {
Some(&*ast_items[i])
} else {
None
};
index.push(entry {
val: trait_item_def_id.def_id().node as i64,
pos: rbml_w.mark_stable_position(),
});
match tcx.impl_or_trait_item(trait_item_def_id.def_id()) {
ty::ConstTraitItem(ref associated_const) => {
encode_info_for_associated_const(ecx,
rbml_w,
&*associated_const,
path.clone(),
item.id,
ast_item)
}
ty::MethodTraitItem(ref method_type) => {
encode_info_for_method(ecx,
rbml_w,
&**method_type,
path.clone(),
false,
item.id,
ast_item)
}
ty::TypeTraitItem(ref associated_type) => {
encode_info_for_associated_type(ecx,
rbml_w,
&**associated_type,
path.clone(),
item.id,
ast_item)
}
}
}
}
ast::ItemTrait(_, _, _, ref ms) => {
add_to_index(item, rbml_w, index);
rbml_w.start_tag(tag_items_data_item);
encode_def_id(rbml_w, def_id);
encode_family(rbml_w, 'I');
encode_item_variances(rbml_w, ecx, item.id);
let trait_def = tcx.lookup_trait_def(def_id);
let trait_predicates = tcx.lookup_predicates(def_id);
encode_unsafety(rbml_w, trait_def.unsafety);
encode_paren_sugar(rbml_w, trait_def.paren_sugar);
encode_defaulted(rbml_w, tcx.trait_has_default_impl(def_id));
encode_associated_type_names(rbml_w, &trait_def.associated_type_names);
encode_generics(rbml_w, ecx, &trait_def.generics, &trait_predicates,
tag_item_generics);
encode_predicates(rbml_w, ecx, &tcx.lookup_super_predicates(def_id),
tag_item_super_predicates);
encode_trait_ref(rbml_w, ecx, trait_def.trait_ref, tag_item_trait_ref);
encode_name(rbml_w, item.ident.name);
encode_attributes(rbml_w, &item.attrs);
encode_visibility(rbml_w, vis);
encode_stability(rbml_w, stab);
for &method_def_id in tcx.trait_item_def_ids(def_id).iter() {
rbml_w.start_tag(tag_item_trait_item);
match method_def_id {
ty::ConstTraitItemId(const_def_id) => {
encode_def_id(rbml_w, const_def_id);
encode_item_sort(rbml_w, 'C');
}
ty::MethodTraitItemId(method_def_id) => {
encode_def_id(rbml_w, method_def_id);
encode_item_sort(rbml_w, 'r');
}
ty::TypeTraitItemId(type_def_id) => {
encode_def_id(rbml_w, type_def_id);
encode_item_sort(rbml_w, 't');
}
}
rbml_w.end_tag();
rbml_w.wr_tagged_u64(tag_mod_child,
def_to_u64(method_def_id.def_id()));
}
encode_path(rbml_w, path.clone());
// Encode the implementations of this trait.
encode_extension_implementations(ecx, rbml_w, def_id);
// Encode inherent implementations for this trait.
encode_inherent_implementations(ecx, rbml_w, def_id);
rbml_w.end_tag();
// Now output the trait item info for each trait item.
let r = tcx.trait_item_def_ids(def_id);
for (i, &item_def_id) in r.iter().enumerate() {
assert_eq!(item_def_id.def_id().krate, ast::LOCAL_CRATE);
index.push(entry {
val: item_def_id.def_id().node as i64,
pos: rbml_w.mark_stable_position(),
});
rbml_w.start_tag(tag_items_data_item);
encode_parent_item(rbml_w, def_id);
let stab = stability::lookup(tcx, item_def_id.def_id());
encode_stability(rbml_w, stab);
let trait_item_type =
tcx.impl_or_trait_item(item_def_id.def_id());
let is_nonstatic_method;
match trait_item_type {
ty::ConstTraitItem(associated_const) => {
encode_name(rbml_w, associated_const.name);
encode_def_id(rbml_w, associated_const.def_id);
encode_visibility(rbml_w, associated_const.vis);
encode_provided_source(rbml_w, associated_const.default);
let elem = ast_map::PathName(associated_const.name);
encode_path(rbml_w,
path.clone().chain(Some(elem)));
encode_item_sort(rbml_w, 'C');
encode_family(rbml_w, 'C');
encode_bounds_and_type_for_item(rbml_w, ecx,
associated_const.def_id.local_id());
is_nonstatic_method = false;
}
ty::MethodTraitItem(method_ty) => {
let method_def_id = item_def_id.def_id();
encode_method_ty_fields(ecx, rbml_w, &*method_ty);
let elem = ast_map::PathName(method_ty.name);
encode_path(rbml_w,
path.clone().chain(Some(elem)));
match method_ty.explicit_self {
ty::StaticExplicitSelfCategory => {
encode_family(rbml_w,
STATIC_METHOD_FAMILY);
}
_ => {
encode_family(rbml_w,
METHOD_FAMILY);
}
}
encode_bounds_and_type_for_item(rbml_w, ecx, method_def_id.local_id());
is_nonstatic_method = method_ty.explicit_self !=
ty::StaticExplicitSelfCategory;
}
ty::TypeTraitItem(associated_type) => {
encode_name(rbml_w, associated_type.name);
encode_def_id(rbml_w, associated_type.def_id);
let elem = ast_map::PathName(associated_type.name);
encode_path(rbml_w,
path.clone().chain(Some(elem)));
encode_item_sort(rbml_w, 't');
encode_family(rbml_w, 'y');
if let Some(ty) = associated_type.ty {
encode_type(ecx, rbml_w, ty);
}
is_nonstatic_method = false;
}
}
encode_parent_sort(rbml_w, 't');
let trait_item = &*ms[i];
encode_attributes(rbml_w, &trait_item.attrs);
match trait_item.node {
ast::ConstTraitItem(_, _) => {
encode_inlined_item(ecx, rbml_w,
IITraitItemRef(def_id, trait_item));
}
ast::MethodTraitItem(ref sig, ref body) => {
// If this is a static method, we've already
// encoded this.
if is_nonstatic_method {
// FIXME: I feel like there is something funny
// going on.
encode_bounds_and_type_for_item(rbml_w, ecx,
item_def_id.def_id().local_id());
}
if body.is_some() {
encode_item_sort(rbml_w, 'p');
encode_inlined_item(ecx, rbml_w, IITraitItemRef(def_id, trait_item));
} else {
encode_item_sort(rbml_w, 'r');
}
encode_method_argument_names(rbml_w, &sig.decl);
}
ast::TypeTraitItem(..) => {}
}
rbml_w.end_tag();
}
}
ast::ItemExternCrate(_) | ast::ItemUse(_) |ast::ItemMac(..) => {
// these are encoded separately
}
}
}
fn encode_info_for_foreign_item(ecx: &EncodeContext,
rbml_w: &mut Encoder,
nitem: &ast::ForeignItem,
index: &mut Vec<entry<i64>>,
path: PathElems,
abi: abi::Abi) {
index.push(entry {
val: nitem.id as i64,
pos: rbml_w.mark_stable_position(),
});
rbml_w.start_tag(tag_items_data_item);
encode_def_id(rbml_w, local_def(nitem.id));
encode_visibility(rbml_w, nitem.vis);
match nitem.node {
ast::ForeignItemFn(ref fndecl, _) => {
encode_family(rbml_w, FN_FAMILY);
encode_bounds_and_type_for_item(rbml_w, ecx, nitem.id);
encode_name(rbml_w, nitem.ident.name);
if abi == abi::RustIntrinsic {
encode_inlined_item(ecx, rbml_w, IIForeignRef(nitem));
}
encode_attributes(rbml_w, &*nitem.attrs);
let stab = stability::lookup(ecx.tcx, ast_util::local_def(nitem.id));
encode_stability(rbml_w, stab);
encode_symbol(ecx, rbml_w, nitem.id);
encode_method_argument_names(rbml_w, &*fndecl);
}
ast::ForeignItemStatic(_, mutbl) => {
if mutbl {
encode_family(rbml_w, 'b');
} else {
encode_family(rbml_w, 'c');
}
encode_bounds_and_type_for_item(rbml_w, ecx, nitem.id);
encode_attributes(rbml_w, &*nitem.attrs);
let stab = stability::lookup(ecx.tcx, ast_util::local_def(nitem.id));
encode_stability(rbml_w, stab);
encode_symbol(ecx, rbml_w, nitem.id);
encode_name(rbml_w, nitem.ident.name);
}
}
encode_path(rbml_w, path);
rbml_w.end_tag();
}
fn my_visit_expr(_e: &ast::Expr) { }
fn my_visit_item(i: &ast::Item,
rbml_w: &mut Encoder,
ecx: &EncodeContext,
index: &mut Vec<entry<i64>>) {
ecx.tcx.map.with_path(i.id, |path| {
encode_info_for_item(ecx, rbml_w, i, index, path, i.vis);
});
}
fn my_visit_foreign_item(ni: &ast::ForeignItem,
rbml_w: &mut Encoder,
ecx: &EncodeContext,
index: &mut Vec<entry<i64>>) {
debug!("writing foreign item {}::{}",
ecx.tcx.map.path_to_string(ni.id),
token::get_ident(ni.ident));
let abi = ecx.tcx.map.get_foreign_abi(ni.id);
ecx.tcx.map.with_path(ni.id, |path| {
encode_info_for_foreign_item(ecx, rbml_w,
ni, index,
path, abi);
});
}
struct EncodeVisitor<'a, 'b:'a, 'c:'a, 'tcx:'c> {
rbml_w_for_visit_item: &'a mut Encoder<'b>,
ecx: &'a EncodeContext<'c,'tcx>,
index: &'a mut Vec<entry<i64>>,
}
impl<'a, 'b, 'c, 'tcx, 'v> Visitor<'v> for EncodeVisitor<'a, 'b, 'c, 'tcx> {
fn visit_expr(&mut self, ex: &ast::Expr) {
visit::walk_expr(self, ex);
my_visit_expr(ex);
}
fn visit_item(&mut self, i: &ast::Item) {
visit::walk_item(self, i);
my_visit_item(i,
self.rbml_w_for_visit_item,
self.ecx,
self.index);
}
fn visit_foreign_item(&mut self, ni: &ast::ForeignItem) {
visit::walk_foreign_item(self, ni);
my_visit_foreign_item(ni,
self.rbml_w_for_visit_item,
self.ecx,
self.index);
}
}
fn encode_info_for_items(ecx: &EncodeContext,
rbml_w: &mut Encoder,
krate: &ast::Crate)
-> Vec<entry<i64>> {
let mut index = Vec::new();
rbml_w.start_tag(tag_items_data);
index.push(entry {
val: ast::CRATE_NODE_ID as i64,
pos: rbml_w.mark_stable_position(),
});
encode_info_for_mod(ecx,
rbml_w,
&krate.module,
&[],
ast::CRATE_NODE_ID,
[].iter().cloned().chain(LinkedPath::empty()),
syntax::parse::token::special_idents::invalid.name,
ast::Public);
visit::walk_crate(&mut EncodeVisitor {
index: &mut index,
ecx: ecx,
rbml_w_for_visit_item: &mut *rbml_w,
}, krate);
rbml_w.end_tag();
index
}
// Path and definition ID indexing
fn encode_index<T, F>(rbml_w: &mut Encoder, index: Vec<entry<T>>, mut write_fn: F) where
F: FnMut(&mut Cursor<Vec<u8>>, &T),
T: Hash,
{
let mut buckets: Vec<Vec<entry<T>>> = (0..256u16).map(|_| Vec::new()).collect();
for elt in index {
let mut s = SipHasher::new();
elt.val.hash(&mut s);
let h = s.finish() as usize;
(&mut buckets[h % 256]).push(elt);
}
rbml_w.start_tag(tag_index);
let mut bucket_locs = Vec::new();
rbml_w.start_tag(tag_index_buckets);
for bucket in &buckets {
bucket_locs.push(rbml_w.mark_stable_position());
rbml_w.start_tag(tag_index_buckets_bucket);
for elt in bucket {
rbml_w.start_tag(tag_index_buckets_bucket_elt);
assert!(elt.pos < 0xffff_ffff);
{
let wr: &mut Cursor<Vec<u8>> = rbml_w.writer;
write_be_u32(wr, elt.pos as u32);
}
write_fn(rbml_w.writer, &elt.val);
rbml_w.end_tag();
}
rbml_w.end_tag();
}
rbml_w.end_tag();
rbml_w.start_tag(tag_index_table);
for pos in &bucket_locs {
assert!(*pos < 0xffff_ffff);
let wr: &mut Cursor<Vec<u8>> = rbml_w.writer;
write_be_u32(wr, *pos as u32);
}
rbml_w.end_tag();
rbml_w.end_tag();
}
fn write_i64(writer: &mut Cursor<Vec<u8>>, &n: &i64) {
let wr: &mut Cursor<Vec<u8>> = writer;
assert!(n < 0x7fff_ffff);
write_be_u32(wr, n as u32);
}
fn write_be_u32(w: &mut Write, u: u32) {
w.write_all(&[
(u >> 24) as u8,
(u >> 16) as u8,
(u >> 8) as u8,
(u >> 0) as u8,
]);
}
fn encode_meta_item(rbml_w: &mut Encoder, mi: &ast::MetaItem) {
match mi.node {
ast::MetaWord(ref name) => {
rbml_w.start_tag(tag_meta_item_word);
rbml_w.wr_tagged_str(tag_meta_item_name, name);
rbml_w.end_tag();
}
ast::MetaNameValue(ref name, ref value) => {
match value.node {
ast::LitStr(ref value, _) => {
rbml_w.start_tag(tag_meta_item_name_value);
rbml_w.wr_tagged_str(tag_meta_item_name, name);
rbml_w.wr_tagged_str(tag_meta_item_value, value);
rbml_w.end_tag();
}
_ => {/* FIXME (#623): encode other variants */ }
}
}
ast::MetaList(ref name, ref items) => {
rbml_w.start_tag(tag_meta_item_list);
rbml_w.wr_tagged_str(tag_meta_item_name, name);
for inner_item in items {
encode_meta_item(rbml_w, &**inner_item);
}
rbml_w.end_tag();
}
}
}
fn encode_attributes(rbml_w: &mut Encoder, attrs: &[ast::Attribute]) {
rbml_w.start_tag(tag_attributes);
for attr in attrs {
rbml_w.start_tag(tag_attribute);
rbml_w.wr_tagged_u8(tag_attribute_is_sugared_doc, attr.node.is_sugared_doc as u8);
encode_meta_item(rbml_w, &*attr.node.value);
rbml_w.end_tag();
}
rbml_w.end_tag();
}
fn encode_unsafety(rbml_w: &mut Encoder, unsafety: ast::Unsafety) {
let byte: u8 = match unsafety {
ast::Unsafety::Normal => 0,
ast::Unsafety::Unsafe => 1,
};
rbml_w.wr_tagged_u8(tag_unsafety, byte);
}
fn encode_paren_sugar(rbml_w: &mut Encoder, paren_sugar: bool) {
let byte: u8 = if paren_sugar {1} else {0};
rbml_w.wr_tagged_u8(tag_paren_sugar, byte);
}
fn encode_defaulted(rbml_w: &mut Encoder, is_defaulted: bool) {
let byte: u8 = if is_defaulted {1} else {0};
rbml_w.wr_tagged_u8(tag_defaulted_trait, byte);
}
fn encode_associated_type_names(rbml_w: &mut Encoder, names: &[ast::Name]) {
rbml_w.start_tag(tag_associated_type_names);
for &name in names {
rbml_w.wr_tagged_str(tag_associated_type_name, &token::get_name(name));
}
rbml_w.end_tag();
}
fn encode_polarity(rbml_w: &mut Encoder, polarity: ast::ImplPolarity) {
let byte: u8 = match polarity {
ast::ImplPolarity::Positive => 0,
ast::ImplPolarity::Negative => 1,
};
rbml_w.wr_tagged_u8(tag_polarity, byte);
}
fn encode_crate_deps(rbml_w: &mut Encoder, cstore: &cstore::CStore) {
fn get_ordered_deps(cstore: &cstore::CStore) -> Vec<decoder::CrateDep> {
// Pull the cnums and name,vers,hash out of cstore
let mut deps = Vec::new();
cstore.iter_crate_data(|key, val| {
let dep = decoder::CrateDep {
cnum: key,
name: decoder::get_crate_name(val.data()),
hash: decoder::get_crate_hash(val.data()),
};
deps.push(dep);
});
// Sort by cnum
deps.sort_by(|kv1, kv2| kv1.cnum.cmp(&kv2.cnum));
// Sanity-check the crate numbers
let mut expected_cnum = 1;
for n in &deps {
assert_eq!(n.cnum, expected_cnum);
expected_cnum += 1;
}
deps
}
// We're just going to write a list of crate 'name-hash-version's, with
// the assumption that they are numbered 1 to n.
// FIXME (#2166): This is not nearly enough to support correct versioning
// but is enough to get transitive crate dependencies working.
rbml_w.start_tag(tag_crate_deps);
let r = get_ordered_deps(cstore);
for dep in &r {
encode_crate_dep(rbml_w, (*dep).clone());
}
rbml_w.end_tag();
}
fn encode_lang_items(ecx: &EncodeContext, rbml_w: &mut Encoder) {
rbml_w.start_tag(tag_lang_items);
for (i, &def_id) in ecx.tcx.lang_items.items() {
if let Some(id) = def_id {
if id.krate == ast::LOCAL_CRATE {
rbml_w.start_tag(tag_lang_items_item);
rbml_w.wr_tagged_u32(tag_lang_items_item_id, i as u32);
rbml_w.wr_tagged_u32(tag_lang_items_item_node_id, id.node as u32);
rbml_w.end_tag();
}
}
}
for i in &ecx.tcx.lang_items.missing {
rbml_w.wr_tagged_u32(tag_lang_items_missing, *i as u32);
}
rbml_w.end_tag(); // tag_lang_items
}
fn encode_native_libraries(ecx: &EncodeContext, rbml_w: &mut Encoder) {
rbml_w.start_tag(tag_native_libraries);
for &(ref lib, kind) in ecx.tcx.sess.cstore.get_used_libraries()
.borrow().iter() {
match kind {
cstore::NativeStatic => {} // these libraries are not propagated
cstore::NativeFramework | cstore::NativeUnknown => {
rbml_w.start_tag(tag_native_libraries_lib);
rbml_w.wr_tagged_u32(tag_native_libraries_kind, kind as u32);
rbml_w.wr_tagged_str(tag_native_libraries_name, lib);
rbml_w.end_tag();
}
}
}
rbml_w.end_tag();
}
fn encode_plugin_registrar_fn(ecx: &EncodeContext, rbml_w: &mut Encoder) {
match ecx.tcx.sess.plugin_registrar_fn.get() {
Some(id) => { rbml_w.wr_tagged_u32(tag_plugin_registrar_fn, id); }
None => {}
}
}
fn encode_codemap(ecx: &EncodeContext, rbml_w: &mut Encoder) {
rbml_w.start_tag(tag_codemap);
let codemap = ecx.tcx.sess.codemap();
for filemap in &codemap.files.borrow()[..] {
if filemap.lines.borrow().is_empty() || filemap.is_imported() {
// No need to export empty filemaps, as they can't contain spans
// that need translation.
// Also no need to re-export imported filemaps, as any downstream
// crate will import them from their original source.
continue;
}
rbml_w.start_tag(tag_codemap_filemap);
filemap.encode(rbml_w);
rbml_w.end_tag();
}
rbml_w.end_tag();
}
/// Serialize the text of the exported macros
fn encode_macro_defs(rbml_w: &mut Encoder,
krate: &ast::Crate) {
rbml_w.start_tag(tag_macro_defs);
for def in &krate.exported_macros {
rbml_w.start_tag(tag_macro_def);
encode_name(rbml_w, def.ident.name);
encode_attributes(rbml_w, &def.attrs);
rbml_w.wr_tagged_str(tag_macro_def_body,
&pprust::tts_to_string(&def.body));
rbml_w.end_tag();
}
rbml_w.end_tag();
}
fn encode_struct_field_attrs(rbml_w: &mut Encoder, krate: &ast::Crate) {
struct StructFieldVisitor<'a, 'b:'a> {
rbml_w: &'a mut Encoder<'b>,
}
impl<'a, 'b, 'v> Visitor<'v> for StructFieldVisitor<'a, 'b> {
fn visit_struct_field(&mut self, field: &ast::StructField) {
self.rbml_w.start_tag(tag_struct_field);
self.rbml_w.wr_tagged_u32(tag_struct_field_id, field.node.id);
encode_attributes(self.rbml_w, &field.node.attrs);
self.rbml_w.end_tag();
}
}
rbml_w.start_tag(tag_struct_fields);
visit::walk_crate(&mut StructFieldVisitor {
rbml_w: rbml_w
}, krate);
rbml_w.end_tag();
}
struct ImplVisitor<'a, 'b:'a, 'c:'a, 'tcx:'b> {
ecx: &'a EncodeContext<'b, 'tcx>,
rbml_w: &'a mut Encoder<'c>,
}
impl<'a, 'b, 'c, 'tcx, 'v> Visitor<'v> for ImplVisitor<'a, 'b, 'c, 'tcx> {
fn visit_item(&mut self, item: &ast::Item) {
if let ast::ItemImpl(_, _, _, Some(ref trait_ref), _, _) = item.node {
let def_id = self.ecx.tcx.def_map.borrow().get(&trait_ref.ref_id).unwrap().def_id();
// Load eagerly if this is an implementation of the Drop trait
// or if the trait is not defined in this crate.
if Some(def_id) == self.ecx.tcx.lang_items.drop_trait() ||
def_id.krate != ast::LOCAL_CRATE {
self.rbml_w.start_tag(tag_impls_impl);
encode_def_id(self.rbml_w, local_def(item.id));
self.rbml_w.wr_tagged_u64(tag_impls_impl_trait_def_id, def_to_u64(def_id));
self.rbml_w.end_tag();
}
}
visit::walk_item(self, item);
}
}
/// Encodes implementations that are eagerly loaded.
///
/// None of this is necessary in theory; we can load all implementations
/// lazily. However, in two cases the optimizations to lazily load
/// implementations are not yet implemented. These two cases, which require us
/// to load implementations eagerly, are:
///
/// * Destructors (implementations of the Drop trait).
///
/// * Implementations of traits not defined in this crate.
fn encode_impls<'a>(ecx: &'a EncodeContext,
krate: &ast::Crate,
rbml_w: &'a mut Encoder) {
rbml_w.start_tag(tag_impls);
{
let mut visitor = ImplVisitor {
ecx: ecx,
rbml_w: rbml_w,
};
visit::walk_crate(&mut visitor, krate);
}
rbml_w.end_tag();
}
fn encode_misc_info(ecx: &EncodeContext,
krate: &ast::Crate,
rbml_w: &mut Encoder) {
rbml_w.start_tag(tag_misc_info);
rbml_w.start_tag(tag_misc_info_crate_items);
for item in &krate.module.items {
rbml_w.wr_tagged_u64(tag_mod_child,
def_to_u64(local_def(item.id)));
each_auxiliary_node_id(&**item, |auxiliary_node_id| {
rbml_w.wr_tagged_u64(tag_mod_child,
def_to_u64(local_def(auxiliary_node_id)));
true
});
}
// Encode reexports for the root module.
encode_reexports(ecx, rbml_w, 0, [].iter().cloned().chain(LinkedPath::empty()));
rbml_w.end_tag();
rbml_w.end_tag();
}
fn encode_reachable_extern_fns(ecx: &EncodeContext, rbml_w: &mut Encoder) {
rbml_w.start_tag(tag_reachable_extern_fns);
for id in ecx.reachable {
if let Some(ast_map::NodeItem(i)) = ecx.tcx.map.find(*id) {
if let ast::ItemFn(_, _, _, abi, ref generics, _) = i.node {
if abi != abi::Rust && !generics.is_type_parameterized() {
rbml_w.wr_tagged_u32(tag_reachable_extern_fn_id, *id);
}
}
}
}
rbml_w.end_tag();
}
fn encode_crate_dep(rbml_w: &mut Encoder,
dep: decoder::CrateDep) {
rbml_w.start_tag(tag_crate_dep);
rbml_w.wr_tagged_str(tag_crate_dep_crate_name, &dep.name);
rbml_w.wr_tagged_str(tag_crate_dep_hash, dep.hash.as_str());
rbml_w.end_tag();
}
fn encode_hash(rbml_w: &mut Encoder, hash: &Svh) {
rbml_w.wr_tagged_str(tag_crate_hash, hash.as_str());
}
fn encode_crate_name(rbml_w: &mut Encoder, crate_name: &str) {
rbml_w.wr_tagged_str(tag_crate_crate_name, crate_name);
}
fn encode_crate_triple(rbml_w: &mut Encoder, triple: &str) {
rbml_w.wr_tagged_str(tag_crate_triple, triple);
}
fn encode_dylib_dependency_formats(rbml_w: &mut Encoder, ecx: &EncodeContext) {
let tag = tag_dylib_dependency_formats;
match ecx.tcx.dependency_formats.borrow().get(&config::CrateTypeDylib) {
Some(arr) => {
let s = arr.iter().enumerate().filter_map(|(i, slot)| {
slot.map(|kind| (format!("{}:{}", i + 1, match kind {
cstore::RequireDynamic => "d",
cstore::RequireStatic => "s",
})).to_string())
}).collect::<Vec<String>>();
rbml_w.wr_tagged_str(tag, &s.join(","));
}
None => {
rbml_w.wr_tagged_str(tag, "");
}
}
}
// NB: Increment this as you change the metadata encoding version.
#[allow(non_upper_case_globals)]
pub const metadata_encoding_version : &'static [u8] = &[b'r', b'u', b's', b't', 0, 0, 0, 2 ];
pub fn encode_metadata(parms: EncodeParams, krate: &ast::Crate) -> Vec<u8> {
let mut wr = Cursor::new(Vec::new());
encode_metadata_inner(&mut wr, parms, krate);
// RBML compacts the encoded bytes whenever appropriate,
// so there are some garbages left after the end of the data.
let metalen = wr.seek(SeekFrom::Current(0)).unwrap() as usize;
let mut v = wr.into_inner();
v.truncate(metalen);
assert_eq!(v.len(), metalen);
// And here we run into yet another obscure archive bug: in which metadata
// loaded from archives may have trailing garbage bytes. Awhile back one of
// our tests was failing sporadically on the OSX 64-bit builders (both nopt
// and opt) by having rbml generate an out-of-bounds panic when looking at
// metadata.
//
// Upon investigation it turned out that the metadata file inside of an rlib
// (and ar archive) was being corrupted. Some compilations would generate a
// metadata file which would end in a few extra bytes, while other
// compilations would not have these extra bytes appended to the end. These
// extra bytes were interpreted by rbml as an extra tag, so they ended up
// being interpreted causing the out-of-bounds.
//
// The root cause of why these extra bytes were appearing was never
// discovered, and in the meantime the solution we're employing is to insert
// the length of the metadata to the start of the metadata. Later on this
// will allow us to slice the metadata to the precise length that we just
// generated regardless of trailing bytes that end up in it.
let len = v.len() as u32;
v.insert(0, (len >> 0) as u8);
v.insert(0, (len >> 8) as u8);
v.insert(0, (len >> 16) as u8);
v.insert(0, (len >> 24) as u8);
return v;
}
fn encode_metadata_inner(wr: &mut Cursor<Vec<u8>>,
parms: EncodeParams,
krate: &ast::Crate) {
struct Stats {
attr_bytes: u64,
dep_bytes: u64,
lang_item_bytes: u64,
native_lib_bytes: u64,
plugin_registrar_fn_bytes: u64,
codemap_bytes: u64,
macro_defs_bytes: u64,
impl_bytes: u64,
misc_bytes: u64,
item_bytes: u64,
index_bytes: u64,
zero_bytes: u64,
total_bytes: u64,
}
let mut stats = Stats {
attr_bytes: 0,
dep_bytes: 0,
lang_item_bytes: 0,
native_lib_bytes: 0,
plugin_registrar_fn_bytes: 0,
codemap_bytes: 0,
macro_defs_bytes: 0,
impl_bytes: 0,
misc_bytes: 0,
item_bytes: 0,
index_bytes: 0,
zero_bytes: 0,
total_bytes: 0,
};
let EncodeParams {
item_symbols,
diag,
tcx,
reexports,
cstore,
encode_inlined_item,
link_meta,
reachable,
..
} = parms;
let ecx = EncodeContext {
diag: diag,
tcx: tcx,
reexports: reexports,
item_symbols: item_symbols,
link_meta: link_meta,
cstore: cstore,
encode_inlined_item: RefCell::new(encode_inlined_item),
type_abbrevs: RefCell::new(FnvHashMap()),
reachable: reachable,
};
let mut rbml_w = Encoder::new(wr);
encode_crate_name(&mut rbml_w, &ecx.link_meta.crate_name);
encode_crate_triple(&mut rbml_w, &tcx.sess.opts.target_triple);
encode_hash(&mut rbml_w, &ecx.link_meta.crate_hash);
encode_dylib_dependency_formats(&mut rbml_w, &ecx);
let mut i = rbml_w.writer.seek(SeekFrom::Current(0)).unwrap();
encode_attributes(&mut rbml_w, &krate.attrs);
stats.attr_bytes = rbml_w.writer.seek(SeekFrom::Current(0)).unwrap() - i;
i = rbml_w.writer.seek(SeekFrom::Current(0)).unwrap();
encode_crate_deps(&mut rbml_w, ecx.cstore);
stats.dep_bytes = rbml_w.writer.seek(SeekFrom::Current(0)).unwrap() - i;
// Encode the language items.
i = rbml_w.writer.seek(SeekFrom::Current(0)).unwrap();
encode_lang_items(&ecx, &mut rbml_w);
stats.lang_item_bytes = rbml_w.writer.seek(SeekFrom::Current(0)).unwrap() - i;
// Encode the native libraries used
i = rbml_w.writer.seek(SeekFrom::Current(0)).unwrap();
encode_native_libraries(&ecx, &mut rbml_w);
stats.native_lib_bytes = rbml_w.writer.seek(SeekFrom::Current(0)).unwrap() - i;
// Encode the plugin registrar function
i = rbml_w.writer.seek(SeekFrom::Current(0)).unwrap();
encode_plugin_registrar_fn(&ecx, &mut rbml_w);
stats.plugin_registrar_fn_bytes = rbml_w.writer.seek(SeekFrom::Current(0)).unwrap() - i;
// Encode codemap
i = rbml_w.writer.seek(SeekFrom::Current(0)).unwrap();
encode_codemap(&ecx, &mut rbml_w);
stats.codemap_bytes = rbml_w.writer.seek(SeekFrom::Current(0)).unwrap() - i;
// Encode macro definitions
i = rbml_w.writer.seek(SeekFrom::Current(0)).unwrap();
encode_macro_defs(&mut rbml_w, krate);
stats.macro_defs_bytes = rbml_w.writer.seek(SeekFrom::Current(0)).unwrap() - i;
// Encode the def IDs of impls, for coherence checking.
i = rbml_w.writer.seek(SeekFrom::Current(0)).unwrap();
encode_impls(&ecx, krate, &mut rbml_w);
stats.impl_bytes = rbml_w.writer.seek(SeekFrom::Current(0)).unwrap() - i;
// Encode miscellaneous info.
i = rbml_w.writer.seek(SeekFrom::Current(0)).unwrap();
encode_misc_info(&ecx, krate, &mut rbml_w);
encode_reachable_extern_fns(&ecx, &mut rbml_w);
stats.misc_bytes = rbml_w.writer.seek(SeekFrom::Current(0)).unwrap() - i;
// Encode and index the items.
rbml_w.start_tag(tag_items);
i = rbml_w.writer.seek(SeekFrom::Current(0)).unwrap();
let items_index = encode_info_for_items(&ecx, &mut rbml_w, krate);
stats.item_bytes = rbml_w.writer.seek(SeekFrom::Current(0)).unwrap() - i;
i = rbml_w.writer.seek(SeekFrom::Current(0)).unwrap();
encode_index(&mut rbml_w, items_index, write_i64);
stats.index_bytes = rbml_w.writer.seek(SeekFrom::Current(0)).unwrap() - i;
rbml_w.end_tag();
encode_struct_field_attrs(&mut rbml_w, krate);
stats.total_bytes = rbml_w.writer.seek(SeekFrom::Current(0)).unwrap();
if tcx.sess.meta_stats() {
for e in rbml_w.writer.get_ref() {
if *e == 0 {
stats.zero_bytes += 1;
}
}
println!("metadata stats:");
println!(" attribute bytes: {}", stats.attr_bytes);
println!(" dep bytes: {}", stats.dep_bytes);
println!(" lang item bytes: {}", stats.lang_item_bytes);
println!(" native bytes: {}", stats.native_lib_bytes);
println!("plugin registrar bytes: {}", stats.plugin_registrar_fn_bytes);
println!(" codemap bytes: {}", stats.codemap_bytes);
println!(" macro def bytes: {}", stats.macro_defs_bytes);
println!(" impl bytes: {}", stats.impl_bytes);
println!(" misc bytes: {}", stats.misc_bytes);
println!(" item bytes: {}", stats.item_bytes);
println!(" index bytes: {}", stats.index_bytes);
println!(" zero bytes: {}", stats.zero_bytes);
println!(" total bytes: {}", stats.total_bytes);
}
}
// Get the encoded string for a type
pub fn encoded_ty<'tcx>(tcx: &ty::ctxt<'tcx>, t: Ty<'tcx>) -> String {
let mut wr = Cursor::new(Vec::new());
tyencode::enc_ty(&mut Encoder::new(&mut wr), &tyencode::ctxt {
diag: tcx.sess.diagnostic(),
ds: def_to_string,
tcx: tcx,
abbrevs: &RefCell::new(FnvHashMap())
}, t);
String::from_utf8(wr.into_inner()).unwrap()
}<|fim▁end|> | Some(implementations) => { |
<|file_name|>main.js<|end_file_name|><|fim▁begin|>(function () {
var common;
this.setAsDefault = function () {
var _external = window.external;
if (_external && ('AddSearchProvider' in _external) && ('IsSearchProviderInstalled' in _external)) {
var isInstalled = 0;
try {
isInstalled = _external.IsSearchProviderInstalled('https://gusouk.com');
if (isInstalled > 0) {
alert("已添加过此搜索引擎");
}
} catch (err) {
isInstalled = 0;
}
console.log("isInstalled: " + isInstalled);
_external.AddSearchProvider('https://gusouk.com/opensearch.xml');
} else {
window.open('http://mlongbo.com/set_as_default_search_engine/');
}
return false;
};
/**
* 切换弹出框显示
* @param {[type]} id [弹出框元素id]
* @param {[type]} eventName [事件名称]
*/
this.swithPopver = function (id,eventName) {
var ele = document.getElementById(id);
if ((eventName && eventName === 'blur') || ele.style.display === 'block') {
ele.style.display = 'none';
} else {
ele.style.display = 'block';
}
};<|fim▁hole|>console.info("本站使用开源项目gso(https://github.com/lenbo-ma/gso)搭建");
console.info("希望能够让更多的获取知识,加油!");<|fim▁end|> | })();
console.info("谷搜客基于Google搜索,为喜爱谷歌搜索的朋友们免费提供高速稳定的搜索服务。搜索结果通过Google.com实时抓取,欢迎您在日常生活学习中使用谷搜客查询资料。");
console.info("如果你觉得谷搜客对你有帮助,请资助(支付宝账号: mlongbo@gmail.com)我一下,资金将用于支持我开发及购买服务器资源。^_^"); |
<|file_name|>handle.rs<|end_file_name|><|fim▁begin|>pub mod prelude {
pub use super::Handle;
}
<|fim▁hole|><|fim▁end|> | pub trait Handle<T> {
fn as_ptr(&self) -> *mut T;
} |
<|file_name|>productReducer.spec.js<|end_file_name|><|fim▁begin|>import { expect } from 'chai';
import productReducer from './productReducer';
import * as actions from '../actions/productActions';
import * as types from '../constants/actionTypes';
import initialState from './initialState';
describe('Product Reducer', () => {
it ('should set isFetching to true on all request actions', () => {
let newState = productReducer({ ...initialState.products }, actions.updateProduct({}));
expect(newState.isFetching).to.equal(true);
newState = productReducer({ ...initialState.products }, actions.deleteProduct(0));
expect(newState.isFetching).to.equal(true);
newState = productReducer({ ...initialState.products }, actions.createProduct({}));
expect(newState.isFetching).to.equal(true);
newState = productReducer({ ...initialState.products }, actions.getProduct(0));
expect(newState.isFetching).to.equal(true);
newState = productReducer({ ...initialState.products }, actions.getAllProducts());
expect(newState.isFetching).to.equal(true);
});
it ('should set isFetching to false on all request completions', () => {
let newState = productReducer({ ...initialState.products, isFetching: true }, { type: types.PRODUCTS_REQUEST_SUCCESS });
expect(newState.isFetching).to.equal(false);
newState = productReducer({ ...initialState.products, isFetching: true }, { type: types.PRODUCT_REQUEST_SUCCESS });
expect(newState.isFetching).to.equal(false);
newState = productReducer({ ...initialState.products, isFetching: true }, { type: types.UPDATE_PRODUCT_SUCCESS });
expect(newState.isFetching).to.equal(false);
newState = productReducer({ ...initialState.products, isFetching: true }, { type: types.DELETE_PRODUCT_SUCCESS });
expect(newState.isFetching).to.equal(false);
newState = productReducer({ ...initialState.products, isFetching: true }, { type: types.PRODUCT_REQUEST_FAILURE });
expect(newState.isFetching).to.equal(false);
});
it ('should set editing values on modal actions', () => {
const product = {
id: 0,
name: 'test'
};
const action = actions.showEditModal(product);
let newState = productReducer({ ...initialState.products }, action);
expect(newState.editing.modalOpen).to.equal(true);
expect(newState.editing.product).to.deep.equal(product);
newState = productReducer(newState, actions.closeEditModal());
expect(newState.editing.modalOpen).to.equal(false);
});
it (`should set product list on ${types.UPDATE_PRODUCT_SUCCESS}`, () => {
const state = {
list: [{
id: 1,
name: 'test'
},{
id: 2,
name: 'test'
}]
};
const newName = 'test2';
const action = {
type: types.UPDATE_PRODUCT_SUCCESS,
result: {
id: 1,
name: newName
}
};
let newState = productReducer(state, action);
expect(newState.list[1].name).to.equal(newName);
});
it (`should set product list on ${types.CREATE_PRODUCT_SUCCESS}`, () => {
const state = {
list: [{
id: 1,
name: 'test'
},{
id: 2,
name: 'test'
}]
};
const action = {
type: types.CREATE_PRODUCT_SUCCESS,
result: {
id: 3,
name: 'test3'
}
};
let newState = productReducer(state, action);
expect(newState.list[2].name).to.equal('test3');
});
it (`should set product list on ${types.DELETE_PRODUCT_SUCCESS}`, () => {
const state = {
list: [{
id: 1,
name: 'test'
},{
id: 2,
name: 'test'
}]
};
const action = {
type: types.DELETE_PRODUCT_SUCCESS,<|fim▁hole|> result: {
id: 1
}
};
let newState = productReducer(state, action);
expect(newState.list[0].id).to.equal(2);
});
it (`should set error on ${types.PRODUCT_REQUEST_FAILURE}`, () => {
const error = {
message: 'test'
};
const action = {
type: types.PRODUCT_REQUEST_FAILURE,
error
};
let newState = productReducer({ ...initialState.products }, action);
expect(newState.error).to.deep.equal(error);
});
});<|fim▁end|> | |
<|file_name|>dailyrls_wp_jh.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
'''
Exodus Add-on
Copyright (C) 2016 Exodus
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
'''
import re,urllib,urlparse
from resources.lib.modules import cleantitle
from resources.lib.modules import client
from resources.lib.modules import debrid
class source:
def __init__(self):
self.language = ['en']
self.domains = ['dailyreleases.net']
self.base_link = 'http://dailyreleases.net'
self.search_link = '/search/%s/feed/rss2/'
def movie(self, imdb, title, year):
try:
url = {'imdb': imdb, 'title': title, 'year': year}
url = urllib.urlencode(url)
return url
except:
return
def tvshow(self, imdb, tvdb, tvshowtitle, year):
try:
url = {'imdb': imdb, 'tvdb': tvdb, 'tvshowtitle': tvshowtitle, 'year': year}
url = urllib.urlencode(url)
return url
except:
return
def episode(self, url, imdb, tvdb, title, premiered, season, episode):
try:
if url == None: return
url = urlparse.parse_qs(url)
url = dict([(i, url[i][0]) if url[i] else (i, '') for i in url])
url['title'], url['premiered'], url['season'], url['episode'] = title, premiered, season, episode
url = urllib.urlencode(url)
return url
except:
return
def sources(self, url, hostDict, hostprDict):
try:
sources = []
if url == None: return sources
if debrid.status() == False: raise Exception()
data = urlparse.parse_qs(url)
data = dict([(i, data[i][0]) if data[i] else (i, '') for i in data])
title = data['tvshowtitle'] if 'tvshowtitle' in data else data['title']
hdlr = 'S%02dE%02d' % (int(data['season']), int(data['episode'])) if 'tvshowtitle' in data else data['year']
query = '%s S%02dE%02d' % (data['tvshowtitle'], int(data['season']), int(data['episode'])) if 'tvshowtitle' in data else '%s %s' % (data['title'], data['year'])
query = re.sub('(\\\|/| -|:|;|\*|\?|"|\'|<|>|\|)', ' ', query)
url = self.search_link % urllib.quote_plus(query)
url = urlparse.urljoin(self.base_link, url)
r = client.request(url)
posts = client.parseDOM(r, 'item')
hostDict = hostprDict + hostDict
items = []
for post in posts:
try:
items += zip(client.parseDOM(post, 'a', attrs={'target': '_blank'}), client.parseDOM(post, 'a', ret='href', attrs={'target': '_blank'}))
except:
pass
for item in items:
try:
name = item[0]
name = client.replaceHTMLCodes(name)
t = re.sub('(\.|\(|\[|\s)(\d{4}|S\d*E\d*|S\d*|3D)(\.|\)|\]|\s|)(.+|)', '', name)
if not cleantitle.get(t) == cleantitle.get(title): raise Exception()
y = re.findall('[\.|\(|\[|\s](\d{4}|S\d*E\d*|S\d*)[\.|\)|\]|\s]', name)[-1].upper()
if not y == hdlr: raise Exception()
fmt = re.sub('(.+)(\.|\(|\[|\s)(\d{4}|S\d*E\d*|S\d*)(\.|\)|\]|\s)', '', name.upper())
fmt = re.split('\.|\(|\)|\[|\]|\s|\-', fmt)
fmt = [i.lower() for i in fmt]
if any(i.endswith(('subs', 'sub', 'dubbed', 'dub')) for i in fmt): raise Exception()
if any(i in ['extras'] for i in fmt): raise Exception()
if '1080p' in fmt: quality = '1080p'
elif '720p' in fmt: quality = 'HD'
else: quality = 'SD'
if any(i in ['dvdscr', 'r5', 'r6'] for i in fmt): quality = 'SCR'
elif any(i in ['camrip', 'tsrip', 'hdcam', 'hdts', 'dvdcam', 'dvdts', 'cam', 'telesync', 'ts'] for i in fmt): quality = 'CAM'<|fim▁hole|> info = []
if '3d' in fmt: info.append('3D')
try:
size = re.findall('((?:\d+\.\d+|\d+\,\d+|\d+) [M|G]B)', name)[-1]
div = 1 if size.endswith(' GB') else 1024
size = float(re.sub('[^0-9|/.|/,]', '', size))/div
size = '%.2f GB' % size
info.append(size)
except:
pass
if any(i in ['hevc', 'h265', 'x265'] for i in fmt): info.append('HEVC')
info = ' | '.join(info)
url = item[1]
if any(x in url for x in ['.rar', '.zip', '.iso']): raise Exception()
url = client.replaceHTMLCodes(url)
url = url.encode('utf-8')
host = re.findall('([\w]+[.][\w]+)$', urlparse.urlparse(url.strip().lower()).netloc)[0]
if not host in hostDict: raise Exception()
host = client.replaceHTMLCodes(host)
host = host.encode('utf-8')
sources.append({'source': host, 'quality': quality, 'provider': 'Dailyrls', 'url': url, 'info': info, 'direct': False, 'debridonly': True})
except:
pass
check = [i for i in sources if not i['quality'] == 'CAM']
if check: sources = check
return sources
except:
return sources
def resolve(self, url):
return url<|fim▁end|> | |
<|file_name|>a11y.js<|end_file_name|><|fim▁begin|>'use strict';<|fim▁hole|> grunt.config(
'a11y', {
live: {
options: {
urls: ['www.google.com']
}
}
});
};<|fim▁end|> |
module.exports = function (grunt) { |
<|file_name|>demo.js<|end_file_name|><|fim▁begin|>// wrapped by build app
define("FileSaver/demo/demo", ["dojo","dijit","dojox"], function(dojo,dijit,dojox){
/* FileSaver.js demo script
* 2012-01-23
*
* By Eli Grey, http://eligrey.com
* License: X11/MIT
* See LICENSE.md
*/
/*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/demo/demo.js */
(function(view) {
"use strict";
// The canvas drawing portion of the demo is based off the demo at
// http://www.williammalone.com/articles/create-html5-canvas-javascript-drawing-app/
var
document = view.document
, $ = function(id) {
return document.getElementById(id);
}
, session = view.sessionStorage
// only get URL when necessary in case Blob.js hasn't defined it yet
, get_blob = function() {
return view.Blob;
}
, canvas = $("canvas")
, canvas_options_form = $("canvas-options")
, canvas_filename = $("canvas-filename")
, canvas_clear_button = $("canvas-clear")
, text = $("text")
, text_options_form = $("text-options")
, text_filename = $("text-filename")
, html = $("html")
, html_options_form = $("html-options")
, html_filename = $("html-filename")
, ctx = canvas.getContext("2d")
, drawing = false
, x_points = session.x_points || []
, y_points = session.y_points || []
, drag_points = session.drag_points || []
, add_point = function(x, y, dragging) {
x_points.push(x);
y_points.push(y);
drag_points.push(dragging);
}
, draw = function(){
canvas.width = canvas.width;
ctx.lineWidth = 6;
ctx.lineJoin = "round";
ctx.strokeStyle = "#000000";
var
i = 0
, len = x_points.length
;
for(; i < len; i++) {
ctx.beginPath();
if (i && drag_points[i]) {
ctx.moveTo(x_points[i-1], y_points[i-1]);
} else {
ctx.moveTo(x_points[i]-1, y_points[i]);
}
ctx.lineTo(x_points[i], y_points[i]);
ctx.closePath();
ctx.stroke();
}
}
, stop_drawing = function() {
drawing = false;
}
// Title guesser and document creator available at https://gist.github.com/1059648
, guess_title = function(doc) {
var
h = "h6 h5 h4 h3 h2 h1".split(" ")
, i = h.length
, headers
, header_text
;
while (i--) {
headers = doc.getElementsByTagName(h[i]);
for (var j = 0, len = headers.length; j < len; j++) {
header_text = headers[j].textContent.trim();
if (header_text) {
return header_text;
}
}
}
}
, doc_impl = document.implementation
, create_html_doc = function(html) {
var
dt = doc_impl.createDocumentType('html', null, null)
, doc = doc_impl.createDocument("http://www.w3.org/1999/xhtml", "html", dt)
, doc_el = doc.documentElement
, head = doc_el.appendChild(doc.createElement("head"))
, charset_meta = head.appendChild(doc.createElement("meta"))
, title = head.appendChild(doc.createElement("title"))
, body = doc_el.appendChild(doc.createElement("body"))
, i = 0
, len = html.childNodes.length
;
charset_meta.setAttribute("charset", html.ownerDocument.characterSet);
for (; i < len; i++) {
body.appendChild(doc.importNode(html.childNodes.item(i), true));
}
var title_text = guess_title(doc);
if (title_text) {
title.appendChild(doc.createTextNode(title_text));
}
return doc;
}
;
canvas.width = 500;
canvas.height = 300;
if (typeof x_points === "string") {
x_points = JSON.parse(x_points);
} if (typeof y_points === "string") {
y_points = JSON.parse(y_points);
} if (typeof drag_points === "string") {
drag_points = JSON.parse(drag_points);
} if (session.canvas_filename) {
canvas_filename.value = session.canvas_filename;
} if (session.text) {
text.value = session.text;
} if (session.text_filename) {
text_filename.value = session.text_filename;
} if (session.html) {
html.innerHTML = session.html;
} if (session.html_filename) {
html_filename.value = session.html_filename;
}
drawing = true;
draw();
drawing = false;
canvas_clear_button.addEventListener("click", function() {
canvas.width = canvas.width;
x_points.length =
y_points.length =
drag_points.length =
0;
}, false);
canvas.addEventListener("mousedown", function(event) {
event.preventDefault();<|fim▁hole|>}, false);
canvas.addEventListener("mousemove", function(event) {
if (drawing) {
add_point(event.pageX - canvas.offsetLeft, event.pageY - canvas.offsetTop, true);
draw();
}
}, false);
canvas.addEventListener("mouseup", stop_drawing, false);
canvas.addEventListener("mouseout", stop_drawing, false);
canvas_options_form.addEventListener("submit", function(event) {
event.preventDefault();
canvas.toBlob(function(blob) {
saveAs(
blob
, (canvas_filename.value || canvas_filename.placeholder) + ".png"
);
}, "image/png");
}, false);
text_options_form.addEventListener("submit", function(event) {
event.preventDefault();
var BB = get_blob();
saveAs(
new BB(
[text.value || text.placeholder]
, {type: "text/plain;charset=" + document.characterSet}
)
, (text_filename.value || text_filename.placeholder) + ".txt"
);
}, false);
html_options_form.addEventListener("submit", function(event) {
event.preventDefault();
var
BB = get_blob()
, xml_serializer = new XMLSerializer
, doc = create_html_doc(html)
;
saveAs(
new BB(
[xml_serializer.serializeToString(doc)]
, {type: "application/xhtml+xml;charset=" + document.characterSet}
)
, (html_filename.value || html_filename.placeholder) + ".xhtml"
);
}, false);
view.addEventListener("unload", function() {
session.x_points = JSON.stringify(x_points);
session.y_points = JSON.stringify(y_points);
session.drag_points = JSON.stringify(drag_points);
session.canvas_filename = canvas_filename.value;
session.text = text.value;
session.text_filename = text_filename.value;
session.html = html.innerHTML;
session.html_filename = html_filename.value;
}, false);
}(self));
});<|fim▁end|> | drawing = true;
add_point(event.pageX - canvas.offsetLeft, event.pageY - canvas.offsetTop, false);
draw(); |
<|file_name|>camerarotation.py<|end_file_name|><|fim▁begin|># Inviwo Python script
import inviwo
import math
import time
start = time.clock()
scale = 1;
<|fim▁hole|> x = d*math.sin(r)
z = -d*math.cos(r)
inviwo.setPropertyValue("EntryExitPoints.camera",((x*scale,3*scale,z*scale),(0,0,0),(0,1,0)))
for i in range(0, steps):
r = (2 * 3.14 * i) / (steps)
x = 1.0*math.sin(r)
z = 1.0*math.cos(r)
inviwo.setCameraUp("EntryExitPoints.camera",(x*scale,z*scale,0))
end = time.clock()
fps = 2*steps / (end - start)
fps = round(fps,3)
print("Frames per second: " + str(fps))
print("Time per frame: " + str(round(1000/fps,1)) + " ms")<|fim▁end|> | d = 15
steps = 120
for i in range(0, steps):
r = (2 * 3.14 * i) / steps
|
<|file_name|>32e5974ada25_add_neutron_resources_table.py<|end_file_name|><|fim▁begin|><|fim▁hole|>#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
from alembic import op
import sqlalchemy as sa
"""Add standard attribute table
Revision ID: 32e5974ada25
Revises: 13cfb89f881a
Create Date: 2015-09-10 00:22:47.618593
"""
# revision identifiers, used by Alembic.
revision = '32e5974ada25'
down_revision = '13cfb89f881a'
TABLES = ('ports', 'networks', 'subnets', 'subnetpools', 'securitygroups',
'floatingips', 'routers', 'securitygrouprules')
def upgrade():
op.create_table(
'standardattributes',
sa.Column('id', sa.BigInteger(), autoincrement=True),
sa.Column('resource_type', sa.String(length=255), nullable=False),
sa.PrimaryKeyConstraint('id')
)
for table in TABLES:
op.add_column(table, sa.Column('standard_attr_id', sa.BigInteger(),
nullable=True))<|fim▁end|> | #
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at |
<|file_name|>shootout-meteor.rs<|end_file_name|><|fim▁begin|>// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(phase)]
#[phase(syntax)] extern crate green;
extern crate sync;
use sync::Arc;
green_start!(main)
//
// Utilities.
//
// returns an infinite iterator of repeated applications of f to x,
// i.e. [x, f(x), f(f(x)), ...], as haskell iterate function.
fn iterate<'a, T>(x: T, f: |&T|: 'a -> T) -> Iterate<'a, T> {
Iterate {f: f, next: x}
}
struct Iterate<'a, T> {
f: |&T|: 'a -> T,
next: T
}
impl<'a, T> Iterator<T> for Iterate<'a, T> {
fn next(&mut self) -> Option<T> {
let mut res = (self.f)(&self.next);
std::mem::swap(&mut res, &mut self.next);
Some(res)
}
}
// a linked list using borrowed next.
enum List<'a, T> {
Nil,
Cons(T, &'a List<'a, T>)
}
struct ListIterator<'a, T> {
cur: &'a List<'a, T>
}
impl<'a, T> List<'a, T> {
fn iter(&'a self) -> ListIterator<'a, T> {
ListIterator{cur: self}
}
}
impl<'a, T> Iterator<&'a T> for ListIterator<'a, T> {
fn next(&mut self) -> Option<&'a T> {
match *self.cur {
Nil => None,
Cons(ref elt, next) => {
self.cur = next;
Some(elt)
}
}
}
}
//
// preprocess
//
// Takes a pieces p on the form [(y1, x1), (y2, x2), ...] and returns
// every possible transformations (the 6 rotations with their
// corresponding mirrored piece), with, as minimum coordinates, (0,
// 0). If all is false, only generate half of the possibilities (used
// to break the symetry of the board).
fn transform(piece: Vec<(int, int)> , all: bool) -> Vec<Vec<(int, int)>> {
let mut res: Vec<Vec<(int, int)>> =
// rotations
iterate(piece, |rot| rot.iter().map(|&(y, x)| (x + y, -y)).collect())
.take(if all {6} else {3})
// mirror
.flat_map(|cur_piece| {
iterate(cur_piece, |mir| mir.iter().map(|&(y, x)| (x, y)).collect())
.take(2)
}).collect();
// translating to (0, 0) as minimum coordinates.
for cur_piece in res.mut_iter() {
let (dy, dx) = *cur_piece.iter().min_by(|e| *e).unwrap();
for &(ref mut y, ref mut x) in cur_piece.mut_iter() {
*y -= dy; *x -= dx;
}
}
res
}
// A mask is a piece somewere on the board. It is represented as a
// u64: for i in the first 50 bits, m[i] = 1 if the cell at (i/5, i%5)
// is occuped. m[50 + id] = 1 if the identifier of the piece is id.
// Takes a piece with minimum coordinate (0, 0) (as generated by
// transform). Returns the corresponding mask if p translated by (dy,
// dx) is on the board.
fn mask(dy: int, dx: int, id: uint, p: &Vec<(int, int)>) -> Option<u64> {
let mut m = 1 << (50 + id);
for &(y, x) in p.iter() {
let x = x + dx + (y + (dy % 2)) / 2;
if x < 0 || x > 4 {return None;}
let y = y + dy;
if y < 0 || y > 9 {return None;}
m |= 1 << (y * 5 + x);
}
Some(m)
}
// Makes every possible masks. masks[i][id] correspond to every
// possible masks for piece with identifier id with minimum coordinate
// (i/5, i%5).
fn make_masks() -> Vec<Vec<Vec<u64> > > {
let pieces = vec!(
vec!((0,0),(0,1),(0,2),(0,3),(1,3)),
vec!((0,0),(0,2),(0,3),(1,0),(1,1)),
vec!((0,0),(0,1),(0,2),(1,2),(2,1)),
vec!((0,0),(0,1),(0,2),(1,1),(2,1)),
vec!((0,0),(0,2),(1,0),(1,1),(2,1)),
vec!((0,0),(0,1),(0,2),(1,1),(1,2)),
vec!((0,0),(0,1),(1,1),(1,2),(2,1)),
vec!((0,0),(0,1),(0,2),(1,0),(1,2)),
vec!((0,0),(0,1),(0,2),(1,2),(1,3)),
vec!((0,0),(0,1),(0,2),(0,3),(1,2)));
// To break the central symetry of the problem, every
// transformation must be taken except for one piece (piece 3
// here).
let transforms: Vec<Vec<Vec<(int, int)>>> =
pieces.move_iter().enumerate()
.map(|(id, p)| transform(p, id != 3))
.collect();
range(0, 50).map(|yx| {
transforms.iter().enumerate().map(|(id, t)| {
t.iter().filter_map(|p| mask(yx / 5, yx % 5, id, p)).collect()
}).collect()
}).collect()
}
// Check if all coordinates can be covered by an unused piece and that
// all unused piece can be placed on the board.
fn is_board_unfeasible(board: u64, masks: &Vec<Vec<Vec<u64>>>) -> bool {
let mut coverable = board;
for (i, masks_at) in masks.iter().enumerate() {
if board & 1 << i != 0 { continue; }
for (cur_id, pos_masks) in masks_at.iter().enumerate() {
if board & 1 << (50 + cur_id) != 0 { continue; }
for &cur_m in pos_masks.iter() {
if cur_m & board != 0 { continue; }
coverable |= cur_m;
// if every coordinates can be covered and every
// piece can be used.
if coverable == (1 << 60) - 1 { return false; }
}
}
if coverable & 1 << i == 0 { return true; }
}
true
}
// Filter the masks that we can prove to result to unfeasible board.
fn filter_masks(masks: &mut Vec<Vec<Vec<u64>>>) {
for i in range(0, masks.len()) {
for j in range(0, masks.get(i).len()) {
*masks.get_mut(i).get_mut(j) =
masks.get(i).get(j).iter().map(|&m| m)
.filter(|&m| !is_board_unfeasible(m, masks))
.collect();
}
}
}
// Gets the identifier of a mask.
fn get_id(m: u64) -> u8 {
for id in range(0u8, 10) {
if m & (1 << (id + 50)) != 0 {return id;}
}
fail!("{:016x} does not have a valid identifier", m);
}
// Converts a list of mask to a StrBuf.
fn to_vec(raw_sol: &List<u64>) -> Vec<u8> {
let mut sol = Vec::from_elem(50, '.' as u8);
for &m in raw_sol.iter() {
let id = '0' as u8 + get_id(m);
for i in range(0u, 50) {
if m & 1 << i != 0 {
*sol.get_mut(i) = id;
}
}
}
sol
}
// Prints a solution in StrBuf form.
fn print_sol(sol: &Vec<u8>) {
for (i, c) in sol.iter().enumerate() {
if (i) % 5 == 0 { println!(""); }
if (i + 5) % 10 == 0 { print!(" "); }
print!("{} ", *c as char);
}
println!("");
}
// The data managed during the search
struct Data {
// Number of solution found.
nb: int,
// Lexicographically minimal solution found.
min: Vec<u8>,
// Lexicographically maximal solution found.
max: Vec<u8>
}
impl Data {
fn new() -> Data {
Data {nb: 0, min: vec!(), max: vec!()}
}
fn reduce_from(&mut self, other: Data) {
self.nb += other.nb;
let Data { min: min, max: max, ..} = other;
if min < self.min { self.min = min; }
if max > self.max { self.max = max; }
}
}
// Records a new found solution. Returns false if the search must be
// stopped.
fn handle_sol(raw_sol: &List<u64>, data: &mut Data) {
// because we break the symetry, 2 solutions correspond to a call
// to this method: the normal solution, and the same solution in
// reverse order, i.e. the board rotated by half a turn.
data.nb += 2;
let sol1 = to_vec(raw_sol);
let sol2: Vec<u8> = sol1.iter().rev().map(|x| *x).collect();
if data.nb == 2 {
data.min = sol1.clone();
data.max = sol1.clone();
}
if sol1 < data.min {data.min = sol1;}
else if sol1 > data.max {data.max = sol1;}
if sol2 < data.min {data.min = sol2;}
else if sol2 > data.max {data.max = sol2;}
}
fn search(
masks: &Vec<Vec<Vec<u64>>>,
board: u64,
mut i: uint,
cur: List<u64>,
data: &mut Data)
{
// Search for the lesser empty coordinate.
while board & (1 << i) != 0 && i < 50 {i += 1;}
// the board is full: a solution is found.
if i >= 50 {return handle_sol(&cur, data);}
let masks_at = masks.get(i);
// for every unused piece
for id in range(0u, 10).filter(|id| board & (1 << (id + 50)) == 0) {
// for each mask that fits on the board
for &m in masks_at.get(id).iter().filter(|&m| board & *m == 0) {
// This check is too costy.
//if is_board_unfeasible(board | m, masks) {continue;}
search(masks, board | m, i + 1, Cons(m, &cur), data);
}
}
}
fn par_search(masks: Vec<Vec<Vec<u64>>>) -> Data {
let masks = Arc::new(masks);
let (tx, rx) = channel();
// launching the search in parallel on every masks at minimum
// coordinate (0,0)
for &m in masks.get(0).iter().flat_map(|masks_pos| masks_pos.iter()) {
let masks = masks.clone();
let tx = tx.clone();
spawn(proc() {
let mut data = Data::new();
search(&*masks, m, 1, Cons(m, &Nil), &mut data);
tx.send(data);
});
}
// collecting the results
drop(tx);
let mut data = rx.recv();
for d in rx.iter() { data.reduce_from(d); }
data
}
fn main () {
let mut masks = make_masks();<|fim▁hole|> print_sol(&data.max);
println!("");
}<|fim▁end|> | filter_masks(&mut masks);
let data = par_search(masks);
println!("{} solutions found", data.nb);
print_sol(&data.min); |
<|file_name|>gametime.rs<|end_file_name|><|fim▁begin|>extern crate time;
#[derive(Debug, Clone, Copy)]
pub struct GameTime {
prev_frame_time: time::Timespec,
curr_frame_time: time::Timespec,
}
#[allow(dead_code)]
impl GameTime {
pub fn new() -> GameTime {
let now = time::get_time();
GameTime {
prev_frame_time: now,
curr_frame_time: now,
}
}
pub fn reset(&mut self) {
let now = time::get_time();
self.prev_frame_time = now;
self.curr_frame_time = now;
}
pub fn update(&mut self) {
self.prev_frame_time = self.curr_frame_time;
self.curr_frame_time = time::get_time();
}
pub fn delta(self) -> time::Duration {
self.curr_frame_time - self.prev_frame_time<|fim▁hole|> (self.delta().num_nanoseconds().unwrap() as f32) / 1_000_000_000_f32
}
}<|fim▁end|> | }
pub fn dt(self) -> f32 { |
<|file_name|>pre_processing_driver.py<|end_file_name|><|fim▁begin|>from feature_extraction.pre_processing.filter_precedent import precendent_directory_cleaner<|fim▁hole|>
def run(command_list):
precendent_directory_cleaner.run(command_list)<|fim▁end|> | |
<|file_name|>app.component.ts<|end_file_name|><|fim▁begin|>import { Component } from '@angular/core';<|fim▁hole|>import '../public/css/styles.css';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent { }<|fim▁end|> | |
<|file_name|>UVa492.py<|end_file_name|><|fim▁begin|>'''/* UVa problem:
*
* Topic:
*
* Level:
*
* Brief problem description:
*
*
*
* Solution Summary:
*
*
*
* Used Resources:
*
*
*
* I hereby certify that I have produced the following solution myself
* using the resources listed above in accordance with the CMPUT 403 <|fim▁hole|> *
* --- Dennis Truong
*/'''
pyg = 'ay'
original = raw_input('Enter a word:')
if len(original) > 0 and original.isalpha():
word = original.lower()
first = word[0]
if first == ('a' or 'e' or 'i' or 'o' or 'u'):
new_word = word + pyg
print new_word
else:
new_word = word[1:] + first + pyg
print new_word
else:
print 'empty'<|fim▁end|> | * collaboration policy. |
<|file_name|>iter.rs<|end_file_name|><|fim▁begin|>// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*!
Composable external iterators
# The `Iterator` trait
This module defines Rust's core iteration trait. The `Iterator` trait has one
unimplemented method, `next`. All other methods are derived through default
methods to perform operations such as `zip`, `chain`, `enumerate`, and `fold`.
The goal of this module is to unify iteration across all containers in Rust.
An iterator can be considered as a state machine which is used to track which
element will be yielded next.
There are various extensions also defined in this module to assist with various
types of iteration, such as the `DoubleEndedIterator` for iterating in reverse,
the `FromIterator` trait for creating a container from an iterator, and much
more.
## Rust's `for` loop
The special syntax used by rust's `for` loop is based around the `Iterator`
trait defined in this module. For loops can be viewed as a syntactical expansion
into a `loop`, for example, the `for` loop in this example is essentially
translated to the `loop` below.
```rust
let values = ~[1, 2, 3];
// "Syntactical sugar" taking advantage of an iterator
for &x in values.iter() {
println!("{}", x);
}
// Rough translation of the iteration without a `for` iterator.
let mut it = values.iter();
loop {
match it.next() {
Some(&x) => {
println!("{}", x);
}
None => { break }
}
}
```
This `for` loop syntax can be applied to any iterator over any type.
## Iteration protocol and more
More detailed information about iterators can be found in the [container
guide](http://static.rust-lang.org/doc/master/guide-container.html) with
the rest of the rust manuals.
*/
use cmp;
use num::{Zero, One, CheckedAdd, CheckedSub, Saturating, ToPrimitive, Int};
use option::{Option, Some, None};
use ops::{Add, Mul, Sub};
use cmp::{Eq, Ord, TotalOrd};
use clone::Clone;
use uint;
use mem;
/// Conversion from an `Iterator`
pub trait FromIterator<A> {
/// Build a container with elements from an external iterator.
fn from_iter<T: Iterator<A>>(iterator: T) -> Self;
}
/// A type growable from an `Iterator` implementation
pub trait Extendable<A>: FromIterator<A> {
/// Extend a container with the elements yielded by an iterator
fn extend<T: Iterator<A>>(&mut self, iterator: T);
}
/// An interface for dealing with "external iterators". These types of iterators
/// can be resumed at any time as all state is stored internally as opposed to
/// being located on the call stack.
///
/// The Iterator protocol states that an iterator yields a (potentially-empty,
/// potentially-infinite) sequence of values, and returns `None` to signal that
/// it's finished. The Iterator protocol does not define behavior after `None`
/// is returned. A concrete Iterator implementation may choose to behave however
/// it wishes, either by returning `None` infinitely, or by doing something
/// else.
pub trait Iterator<A> {
/// Advance the iterator and return the next value. Return `None` when the end is reached.
fn next(&mut self) -> Option<A>;
/// Return a lower bound and upper bound on the remaining length of the iterator.
///
/// The common use case for the estimate is pre-allocating space to store the results.
#[inline]
fn size_hint(&self) -> (uint, Option<uint>) { (0, None) }
/// Chain this iterator with another, returning a new iterator which will
/// finish iterating over the current iterator, and then it will iterate
/// over the other specified iterator.
///
/// # Example
///
/// ```rust
/// let a = [0];
/// let b = [1];
/// let mut it = a.iter().chain(b.iter());
/// assert_eq!(it.next().unwrap(), &0);
/// assert_eq!(it.next().unwrap(), &1);
/// assert!(it.next().is_none());
/// ```
#[inline]
fn chain<U: Iterator<A>>(self, other: U) -> Chain<Self, U> {
Chain{a: self, b: other, flag: false}
}
/// Creates an iterator which iterates over both this and the specified
/// iterators simultaneously, yielding the two elements as pairs. When
/// either iterator returns None, all further invocations of next() will
/// return None.
///
/// # Example
///
/// ```rust
/// let a = [0];
/// let b = [1];
/// let mut it = a.iter().zip(b.iter());
/// assert_eq!(it.next().unwrap(), (&0, &1));
/// assert!(it.next().is_none());
/// ```
#[inline]
fn zip<B, U: Iterator<B>>(self, other: U) -> Zip<Self, U> {
Zip{a: self, b: other}
}
/// Creates a new iterator which will apply the specified function to each
/// element returned by the first, yielding the mapped element instead.
///
/// # Example
///
/// ```rust
/// let a = [1, 2];
/// let mut it = a.iter().map(|&x| 2 * x);
/// assert_eq!(it.next().unwrap(), 2);
/// assert_eq!(it.next().unwrap(), 4);
/// assert!(it.next().is_none());
/// ```
#[inline]
fn map<'r, B>(self, f: |A|: 'r -> B) -> Map<'r, A, B, Self> {
Map{iter: self, f: f}
}
/// Creates an iterator which applies the predicate to each element returned
/// by this iterator. Only elements which have the predicate evaluate to
/// `true` will be yielded.
///
/// # Example
///
/// ```rust
/// let a = [1, 2];
/// let mut it = a.iter().filter(|&x| *x > 1);
/// assert_eq!(it.next().unwrap(), &2);
/// assert!(it.next().is_none());
/// ```
#[inline]
fn filter<'r>(self, predicate: |&A|: 'r -> bool) -> Filter<'r, A, Self> {
Filter{iter: self, predicate: predicate}
}
/// Creates an iterator which both filters and maps elements.
/// If the specified function returns None, the element is skipped.
/// Otherwise the option is unwrapped and the new value is yielded.
///
/// # Example
///
/// ```rust
/// let a = [1, 2];
/// let mut it = a.iter().filter_map(|&x| if x > 1 {Some(2 * x)} else {None});
/// assert_eq!(it.next().unwrap(), 4);
/// assert!(it.next().is_none());
/// ```
#[inline]
fn filter_map<'r, B>(self, f: |A|: 'r -> Option<B>) -> FilterMap<'r, A, B, Self> {
FilterMap { iter: self, f: f }
}
/// Creates an iterator which yields a pair of the value returned by this
/// iterator plus the current index of iteration.
///
/// # Example
///
/// ```rust
/// let a = [100, 200];
/// let mut it = a.iter().enumerate();
/// assert_eq!(it.next().unwrap(), (0, &100));
/// assert_eq!(it.next().unwrap(), (1, &200));
/// assert!(it.next().is_none());
/// ```
#[inline]
fn enumerate(self) -> Enumerate<Self> {
Enumerate{iter: self, count: 0}
}
/// Creates an iterator that has a `.peek()` method
/// that returns an optional reference to the next element.
///
/// # Example
///
/// ```rust
/// let xs = [100, 200, 300];
/// let mut it = xs.iter().map(|x| *x).peekable();
/// assert_eq!(it.peek().unwrap(), &100);
/// assert_eq!(it.next().unwrap(), 100);
/// assert_eq!(it.next().unwrap(), 200);
/// assert_eq!(it.peek().unwrap(), &300);
/// assert_eq!(it.peek().unwrap(), &300);
/// assert_eq!(it.next().unwrap(), 300);
/// assert!(it.peek().is_none());
/// assert!(it.next().is_none());
/// ```
#[inline]
fn peekable(self) -> Peekable<A, Self> {
Peekable{iter: self, peeked: None}
}
/// Creates an iterator which invokes the predicate on elements until it
/// returns false. Once the predicate returns false, all further elements are
/// yielded.
///
/// # Example
///
/// ```rust
/// let a = [1, 2, 3, 2, 1];
/// let mut it = a.iter().skip_while(|&a| *a < 3);
/// assert_eq!(it.next().unwrap(), &3);
/// assert_eq!(it.next().unwrap(), &2);
/// assert_eq!(it.next().unwrap(), &1);
/// assert!(it.next().is_none());
/// ```
#[inline]
fn skip_while<'r>(self, predicate: |&A|: 'r -> bool) -> SkipWhile<'r, A, Self> {
SkipWhile{iter: self, flag: false, predicate: predicate}
}
/// Creates an iterator which yields elements so long as the predicate
/// returns true. After the predicate returns false for the first time, no
/// further elements will be yielded.
///
/// # Example
///
/// ```rust
/// let a = [1, 2, 3, 2, 1];
/// let mut it = a.iter().take_while(|&a| *a < 3);
/// assert_eq!(it.next().unwrap(), &1);
/// assert_eq!(it.next().unwrap(), &2);
/// assert!(it.next().is_none());
/// ```
#[inline]
fn take_while<'r>(self, predicate: |&A|: 'r -> bool) -> TakeWhile<'r, A, Self> {
TakeWhile{iter: self, flag: false, predicate: predicate}
}
/// Creates an iterator which skips the first `n` elements of this iterator,
/// and then it yields all further items.
///
/// # Example
///
/// ```rust
/// let a = [1, 2, 3, 4, 5];
/// let mut it = a.iter().skip(3);
/// assert_eq!(it.next().unwrap(), &4);
/// assert_eq!(it.next().unwrap(), &5);
/// assert!(it.next().is_none());
/// ```
#[inline]
fn skip(self, n: uint) -> Skip<Self> {
Skip{iter: self, n: n}
}
/// Creates an iterator which yields the first `n` elements of this
/// iterator, and then it will always return None.
///
/// # Example
///
/// ```rust
/// let a = [1, 2, 3, 4, 5];
/// let mut it = a.iter().take(3);
/// assert_eq!(it.next().unwrap(), &1);
/// assert_eq!(it.next().unwrap(), &2);
/// assert_eq!(it.next().unwrap(), &3);
/// assert!(it.next().is_none());
/// ```
#[inline]
fn take(self, n: uint) -> Take<Self> {
Take{iter: self, n: n}
}
/// Creates a new iterator which behaves in a similar fashion to fold.
/// There is a state which is passed between each iteration and can be
/// mutated as necessary. The yielded values from the closure are yielded
/// from the Scan instance when not None.
///
/// # Example
///
/// ```rust
/// let a = [1, 2, 3, 4, 5];
/// let mut it = a.iter().scan(1, |fac, &x| {
/// *fac = *fac * x;
/// Some(*fac)
/// });
/// assert_eq!(it.next().unwrap(), 1);
/// assert_eq!(it.next().unwrap(), 2);
/// assert_eq!(it.next().unwrap(), 6);
/// assert_eq!(it.next().unwrap(), 24);
/// assert_eq!(it.next().unwrap(), 120);
/// assert!(it.next().is_none());
/// ```
#[inline]
fn scan<'r, St, B>(self, initial_state: St, f: |&mut St, A|: 'r -> Option<B>)
-> Scan<'r, A, B, Self, St> {
Scan{iter: self, f: f, state: initial_state}
}
/// Creates an iterator that maps each element to an iterator,
/// and yields the elements of the produced iterators
///
/// # Example
///
/// ```rust
/// use std::iter::count;
///
/// let xs = [2u, 3];
/// let ys = [0u, 1, 0, 1, 2];
/// let mut it = xs.iter().flat_map(|&x| count(0u, 1).take(x));
/// // Check that `it` has the same elements as `ys`
/// let mut i = 0;
/// for x in it {
/// assert_eq!(x, ys[i]);
/// i += 1;
/// }
/// ```
#[inline]
fn flat_map<'r, B, U: Iterator<B>>(self, f: |A|: 'r -> U)
-> FlatMap<'r, A, Self, U> {
FlatMap{iter: self, f: f, frontiter: None, backiter: None }
}
/// Creates an iterator that yields `None` forever after the underlying
/// iterator yields `None`. Random-access iterator behavior is not
/// affected, only single and double-ended iterator behavior.
///
/// # Example
///
/// ```rust
/// fn process<U: Iterator<int>>(it: U) -> int {
/// let mut it = it.fuse();
/// let mut sum = 0;
/// for x in it {
/// if x > 5 {
/// continue;
/// }
/// sum += x;
/// }
/// // did we exhaust the iterator?
/// if it.next().is_none() {
/// sum += 1000;
/// }
/// sum
/// }
/// let x = ~[1,2,3,7,8,9];
/// assert_eq!(process(x.move_iter()), 1006);
/// ```
#[inline]
fn fuse(self) -> Fuse<Self> {
Fuse{iter: self, done: false}
}
/// Creates an iterator that calls a function with a reference to each
/// element before yielding it. This is often useful for debugging an
/// iterator pipeline.
///
/// # Example
///
/// ```rust
/// use std::iter::AdditiveIterator;
///
/// let xs = [1u, 4, 2, 3, 8, 9, 6];
/// let sum = xs.iter()
/// .map(|&x| x)
/// .inspect(|&x| println!("filtering {}", x))
/// .filter(|&x| x % 2 == 0)
/// .inspect(|&x| println!("{} made it through", x))
/// .sum();
/// println!("{}", sum);
/// ```
#[inline]
fn inspect<'r>(self, f: |&A|: 'r) -> Inspect<'r, A, Self> {
Inspect{iter: self, f: f}
}
/// Creates a wrapper around a mutable reference to the iterator.
///
/// This is useful to allow applying iterator adaptors while still
/// retaining ownership of the original iterator value.
///
/// # Example
///
/// ```rust
/// let mut xs = range(0, 10);
/// // sum the first five values
/// let partial_sum = xs.by_ref().take(5).fold(0, |a, b| a + b);
/// assert!(partial_sum == 10);
/// // xs.next() is now `5`
/// assert!(xs.next() == Some(5));
/// ```
fn by_ref<'r>(&'r mut self) -> ByRef<'r, Self> {
ByRef{iter: self}
}
/// Apply a function to each element, or stop iterating if the
/// function returns `false`.
///
/// # Example
///
/// ```rust
/// range(0, 5).advance(|x| {print!("{} ", x); true});
/// ```
#[inline]
fn advance(&mut self, f: |A| -> bool) -> bool {
loop {
match self.next() {
Some(x) => {
if !f(x) { return false; }
}
None => { return true; }
}
}
}
/// Loops through the entire iterator, collecting all of the elements into
/// a container implementing `FromIterator`.
///
/// # Example
///
/// ```rust
/// let a = [1, 2, 3, 4, 5];
/// let b: Vec<int> = a.iter().map(|&x| x).collect();
/// assert!(a.as_slice() == b.as_slice());
/// ```
#[inline]
fn collect<B: FromIterator<A>>(&mut self) -> B {
FromIterator::from_iter(self.by_ref())
}
/// Loops through `n` iterations, returning the `n`th element of the
/// iterator.
///
/// # Example
///
/// ```rust
/// let a = [1, 2, 3, 4, 5];
/// let mut it = a.iter();
/// assert!(it.nth(2).unwrap() == &3);
/// assert!(it.nth(2) == None);
/// ```
#[inline]
fn nth(&mut self, mut n: uint) -> Option<A> {
loop {
match self.next() {
Some(x) => if n == 0 { return Some(x) },
None => return None
}
n -= 1;
}
}
/// Loops through the entire iterator, returning the last element of the
/// iterator.
///
/// # Example
///
/// ```rust
/// let a = [1, 2, 3, 4, 5];
/// assert!(a.iter().last().unwrap() == &5);
/// ```
#[inline]
fn last(&mut self) -> Option<A> {
let mut last = None;
for x in *self { last = Some(x); }
last
}
/// Performs a fold operation over the entire iterator, returning the
/// eventual state at the end of the iteration.
///
/// # Example
///
/// ```rust
/// let a = [1, 2, 3, 4, 5];
/// assert!(a.iter().fold(0, |a, &b| a + b) == 15);
/// ```
#[inline]
fn fold<B>(&mut self, init: B, f: |B, A| -> B) -> B {
let mut accum = init;
loop {
match self.next() {
Some(x) => { accum = f(accum, x); }
None => { break; }
}
}
accum
}
/// Counts the number of elements in this iterator.
///
/// # Example
///
/// ```rust
/// let a = [1, 2, 3, 4, 5];
/// let mut it = a.iter();
/// assert!(it.len() == 5);
/// assert!(it.len() == 0);
/// ```
#[inline]
fn len(&mut self) -> uint {
self.fold(0, |cnt, _x| cnt + 1)
}
/// Tests whether the predicate holds true for all elements in the iterator.
///
/// # Example
///
/// ```rust
/// let a = [1, 2, 3, 4, 5];
/// assert!(a.iter().all(|x| *x > 0));
/// assert!(!a.iter().all(|x| *x > 2));
/// ```
#[inline]
fn all(&mut self, f: |A| -> bool) -> bool {
for x in *self { if !f(x) { return false; } }
true
}
/// Tests whether any element of an iterator satisfies the specified
/// predicate.
///
/// # Example
///
/// ```rust
/// let a = [1, 2, 3, 4, 5];
/// let mut it = a.iter();
/// assert!(it.any(|x| *x == 3));
/// assert!(!it.any(|x| *x == 3));
/// ```
#[inline]
fn any(&mut self, f: |A| -> bool) -> bool {
for x in *self { if f(x) { return true; } }
false
}
/// Return the first element satisfying the specified predicate
#[inline]
fn find(&mut self, predicate: |&A| -> bool) -> Option<A> {
for x in *self {
if predicate(&x) { return Some(x) }
}
None
}
/// Return the index of the first element satisfying the specified predicate
#[inline]
fn position(&mut self, predicate: |A| -> bool) -> Option<uint> {
let mut i = 0;
for x in *self {
if predicate(x) {
return Some(i);
}
i += 1;
}
None
}
/// Count the number of elements satisfying the specified predicate
#[inline]
fn count(&mut self, predicate: |A| -> bool) -> uint {
let mut i = 0;
for x in *self {
if predicate(x) { i += 1 }
}
i
}
/// Return the element that gives the maximum value from the
/// specified function.
///
/// # Example
///
/// ```rust
/// let xs = [-3i, 0, 1, 5, -10];
/// assert_eq!(*xs.iter().max_by(|x| x.abs()).unwrap(), -10);
/// ```
#[inline]
fn max_by<B: TotalOrd>(&mut self, f: |&A| -> B) -> Option<A> {
self.fold(None, |max: Option<(A, B)>, x| {
let x_val = f(&x);
match max {
None => Some((x, x_val)),
Some((y, y_val)) => if x_val > y_val {
Some((x, x_val))
} else {
Some((y, y_val))
}
}
}).map(|(x, _)| x)
}
/// Return the element that gives the minimum value from the
/// specified function.
///
/// # Example
///
/// ```rust
/// let xs = [-3i, 0, 1, 5, -10];
/// assert_eq!(*xs.iter().min_by(|x| x.abs()).unwrap(), 0);
/// ```
#[inline]
fn min_by<B: TotalOrd>(&mut self, f: |&A| -> B) -> Option<A> {
self.fold(None, |min: Option<(A, B)>, x| {
let x_val = f(&x);
match min {
None => Some((x, x_val)),
Some((y, y_val)) => if x_val < y_val {
Some((x, x_val))
} else {
Some((y, y_val))
}
}
}).map(|(x, _)| x)
}
}
/// A range iterator able to yield elements from both ends
pub trait DoubleEndedIterator<A>: Iterator<A> {
/// Yield an element from the end of the range, returning `None` if the range is empty.
fn next_back(&mut self) -> Option<A>;
/// Change the direction of the iterator
///
/// The flipped iterator swaps the ends on an iterator that can already
/// be iterated from the front and from the back.
///
///
/// If the iterator also implements RandomAccessIterator, the flipped
/// iterator is also random access, with the indices starting at the back
/// of the original iterator.
///
/// Note: Random access with flipped indices still only applies to the first
/// `uint::MAX` elements of the original iterator.
#[inline]
fn rev(self) -> Rev<Self> {
Rev{iter: self}
}
}
/// A double-ended iterator yielding mutable references
pub trait MutableDoubleEndedIterator {
// FIXME: #5898: should be called `reverse`
/// Use an iterator to reverse a container in-place
fn reverse_(&mut self);
}
impl<'a, A, T: DoubleEndedIterator<&'a mut A>> MutableDoubleEndedIterator for T {
// FIXME: #5898: should be called `reverse`
/// Use an iterator to reverse a container in-place
fn reverse_(&mut self) {
loop {
match (self.next(), self.next_back()) {
(Some(x), Some(y)) => mem::swap(x, y),
_ => break
}
}
}
}
/// An object implementing random access indexing by `uint`
///
/// A `RandomAccessIterator` should be either infinite or a `DoubleEndedIterator`.
pub trait RandomAccessIterator<A>: Iterator<A> {
/// Return the number of indexable elements. At most `std::uint::MAX`
/// elements are indexable, even if the iterator represents a longer range.
fn indexable(&self) -> uint;
/// Return an element at an index
fn idx(&mut self, index: uint) -> Option<A>;
}
/// An iterator that knows its exact length
///
/// This trait is a helper for iterators like the vector iterator, so that
/// it can support double-ended enumeration.
///
/// `Iterator::size_hint` *must* return the exact size of the iterator.
/// Note that the size must fit in `uint`.
pub trait ExactSize<A> : DoubleEndedIterator<A> {
/// Return the index of the last element satisfying the specified predicate
///
/// If no element matches, None is returned.
#[inline]
fn rposition(&mut self, predicate: |A| -> bool) -> Option<uint> {
let (lower, upper) = self.size_hint();
assert!(upper == Some(lower));
let mut i = lower;
loop {
match self.next_back() {
None => break,
Some(x) => {
i = match i.checked_sub(&1) {
Some(x) => x,
None => fail!("rposition: incorrect ExactSize")
};
if predicate(x) {
return Some(i)
}
}
}
}
None
}
}
// All adaptors that preserve the size of the wrapped iterator are fine
// Adaptors that may overflow in `size_hint` are not, i.e. `Chain`.
impl<A, T: ExactSize<A>> ExactSize<(uint, A)> for Enumerate<T> {}
impl<'a, A, T: ExactSize<A>> ExactSize<A> for Inspect<'a, A, T> {}
impl<A, T: ExactSize<A>> ExactSize<A> for Rev<T> {}
impl<'a, A, B, T: ExactSize<A>> ExactSize<B> for Map<'a, A, B, T> {}
impl<A, B, T: ExactSize<A>, U: ExactSize<B>> ExactSize<(A, B)> for Zip<T, U> {}
/// An double-ended iterator with the direction inverted
#[deriving(Clone)]
pub struct Rev<T> {
iter: T
}
impl<A, T: DoubleEndedIterator<A>> Iterator<A> for Rev<T> {
#[inline]
fn next(&mut self) -> Option<A> { self.iter.next_back() }
#[inline]
fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
}
impl<A, T: DoubleEndedIterator<A>> DoubleEndedIterator<A> for Rev<T> {
#[inline]
fn next_back(&mut self) -> Option<A> { self.iter.next() }
}
impl<A, T: DoubleEndedIterator<A> + RandomAccessIterator<A>> RandomAccessIterator<A>
for Rev<T> {
#[inline]
fn indexable(&self) -> uint { self.iter.indexable() }
#[inline]
fn idx(&mut self, index: uint) -> Option<A> {
let amt = self.indexable();
self.iter.idx(amt - index - 1)
}
}
/// A mutable reference to an iterator
pub struct ByRef<'a, T> {
iter: &'a mut T
}
impl<'a, A, T: Iterator<A>> Iterator<A> for ByRef<'a, T> {
#[inline]
fn next(&mut self) -> Option<A> { self.iter.next() }
#[inline]
fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
}
impl<'a, A, T: DoubleEndedIterator<A>> DoubleEndedIterator<A> for ByRef<'a, T> {
#[inline]
fn next_back(&mut self) -> Option<A> { self.iter.next_back() }
}
/// A trait for iterators over elements which can be added together
pub trait AdditiveIterator<A> {
/// Iterates over the entire iterator, summing up all the elements
///
/// # Example
///
/// ```rust
/// use std::iter::AdditiveIterator;
///
/// let a = [1, 2, 3, 4, 5];
/// let mut it = a.iter().map(|&x| x);
/// assert!(it.sum() == 15);
/// ```
fn sum(&mut self) -> A;
}
impl<A: Add<A, A> + Zero, T: Iterator<A>> AdditiveIterator<A> for T {
#[inline]
fn sum(&mut self) -> A {
let zero: A = Zero::zero();
self.fold(zero, |s, x| s + x)
}
}
/// A trait for iterators over elements whose elements can be multiplied
/// together.
pub trait MultiplicativeIterator<A> {
/// Iterates over the entire iterator, multiplying all the elements
///
/// # Example
///
/// ```rust
/// use std::iter::{count, MultiplicativeIterator};
///
/// fn factorial(n: uint) -> uint {
/// count(1u, 1).take_while(|&i| i <= n).product()
/// }
/// assert!(factorial(0) == 1);
/// assert!(factorial(1) == 1);
/// assert!(factorial(5) == 120);
/// ```
fn product(&mut self) -> A;
}
impl<A: Mul<A, A> + One, T: Iterator<A>> MultiplicativeIterator<A> for T {
#[inline]
fn product(&mut self) -> A {
let one: A = One::one();
self.fold(one, |p, x| p * x)
}
}
/// A trait for iterators over elements which can be compared to one another.
/// The type of each element must ascribe to the `Ord` trait.
pub trait OrdIterator<A> {
/// Consumes the entire iterator to return the maximum element.
///
/// # Example
///
/// ```rust
/// let a = [1, 2, 3, 4, 5];
/// assert!(a.iter().max().unwrap() == &5);
/// ```
fn max(&mut self) -> Option<A>;
/// Consumes the entire iterator to return the minimum element.
///
/// # Example
///
/// ```rust
/// let a = [1, 2, 3, 4, 5];
/// assert!(a.iter().min().unwrap() == &1);
/// ```
fn min(&mut self) -> Option<A>;
/// `min_max` finds the minimum and maximum elements in the iterator.
///
/// The return type `MinMaxResult` is an enum of three variants:
/// - `NoElements` if the iterator is empty.
/// - `OneElement(x)` if the iterator has exactly one element.
/// - `MinMax(x, y)` is returned otherwise, where `x <= y`. Two values are equal if and only if
/// there is more than one element in the iterator and all elements are equal.
///
/// On an iterator of length `n`, `min_max` does `1.5 * n` comparisons,
/// and so faster than calling `min` and `max separately which does `2 * n` comparisons.
///
/// # Example
///
/// ```rust
/// use std::iter::{NoElements, OneElement, MinMax};
///
/// let v: [int, ..0] = [];
/// assert_eq!(v.iter().min_max(), NoElements);
///
/// let v = [1i];
/// assert!(v.iter().min_max() == OneElement(&1));
///
/// let v = [1i, 2, 3, 4, 5];
/// assert!(v.iter().min_max() == MinMax(&1, &5));
///
/// let v = [1i, 2, 3, 4, 5, 6];
/// assert!(v.iter().min_max() == MinMax(&1, &6));
///
/// let v = [1i, 1, 1, 1];
/// assert!(v.iter().min_max() == MinMax(&1, &1));
/// ```
fn min_max(&mut self) -> MinMaxResult<A>;
}
impl<A: TotalOrd, T: Iterator<A>> OrdIterator<A> for T {
#[inline]
fn max(&mut self) -> Option<A> {
self.fold(None, |max, x| {
match max {
None => Some(x),
Some(y) => Some(cmp::max(x, y))
}
})
}
#[inline]
fn min(&mut self) -> Option<A> {
self.fold(None, |min, x| {
match min {
None => Some(x),
Some(y) => Some(cmp::min(x, y))
}
})
}
fn min_max(&mut self) -> MinMaxResult<A> {
let (mut min, mut max) = match self.next() {
None => return NoElements,
Some(x) => {
match self.next() {
None => return OneElement(x),
Some(y) => if x < y {(x, y)} else {(y,x)}
}
}
};
loop {
// `first` and `second` are the two next elements we want to look at.
// We first compare `first` and `second` (#1). The smaller one is then compared to
// current minimum (#2). The larger one is compared to current maximum (#3). This
// way we do 3 comparisons for 2 elements.
let first = match self.next() {
None => break,
Some(x) => x
};
let second = match self.next() {
None => {
if first < min {
min = first;
} else if first > max {
max = first;
}
break;
}
Some(x) => x
};
if first < second {
if first < min {min = first;}
if max < second {max = second;}
} else {
if second < min {min = second;}
if max < first {max = first;}
}
}
MinMax(min, max)
}
}
/// `MinMaxResult` is an enum returned by `min_max`. See `OrdIterator::min_max` for more detail.
#[deriving(Clone, Eq, Show)]
pub enum MinMaxResult<T> {
/// Empty iterator
NoElements,
/// Iterator with one element, so the minimum and maximum are the same
OneElement(T),
/// More than one element in the iterator, the first element is not larger than the second
MinMax(T, T)
}
impl<T: Clone> MinMaxResult<T> {
/// `into_option` creates an `Option` of type `(T,T)`. The returned `Option` has variant
/// `None` if and only if the `MinMaxResult` has variant `NoElements`. Otherwise variant
/// `Some(x,y)` is returned where `x <= y`. If `MinMaxResult` has variant `OneElement(x)`,
/// performing this operation will make one clone of `x`.
///
/// # Example
///
/// ```rust
/// use std::iter::{NoElements, OneElement, MinMax, MinMaxResult};
///
/// let r: MinMaxResult<int> = NoElements;
/// assert_eq!(r.into_option(), None)
///
/// let r = OneElement(1);
/// assert_eq!(r.into_option(), Some((1,1)));
///
/// let r = MinMax(1,2);
/// assert_eq!(r.into_option(), Some((1,2)));
/// ```
pub fn into_option(self) -> Option<(T,T)> {
match self {
NoElements => None,
OneElement(x) => Some((x.clone(), x)),
MinMax(x, y) => Some((x, y))
}
}
}
/// A trait for iterators that are cloneable.
pub trait CloneableIterator {
/// Repeats an iterator endlessly
///
/// # Example
///
/// ```rust
/// use std::iter::{CloneableIterator, count};
///
/// let a = count(1,1).take(1);
/// let mut cy = a.cycle();
/// assert_eq!(cy.next(), Some(1));
/// assert_eq!(cy.next(), Some(1));
/// ```
fn cycle(self) -> Cycle<Self>;
}
impl<A, T: Clone + Iterator<A>> CloneableIterator for T {
#[inline]
fn cycle(self) -> Cycle<T> {
Cycle{orig: self.clone(), iter: self}
}
}
/// An iterator that repeats endlessly
#[deriving(Clone)]
pub struct Cycle<T> {
orig: T,
iter: T,
}
impl<A, T: Clone + Iterator<A>> Iterator<A> for Cycle<T> {
#[inline]
fn next(&mut self) -> Option<A> {
match self.iter.next() {
None => { self.iter = self.orig.clone(); self.iter.next() }
y => y
}
}
#[inline]
fn size_hint(&self) -> (uint, Option<uint>) {
// the cycle iterator is either empty or infinite
match self.orig.size_hint() {
sz @ (0, Some(0)) => sz,
(0, _) => (0, None),
_ => (uint::MAX, None)
}
}
}
impl<A, T: Clone + RandomAccessIterator<A>> RandomAccessIterator<A> for Cycle<T> {
#[inline]
fn indexable(&self) -> uint {
if self.orig.indexable() > 0 {
uint::MAX
} else {
0
}
}
#[inline]
fn idx(&mut self, index: uint) -> Option<A> {
let liter = self.iter.indexable();
let lorig = self.orig.indexable();
if lorig == 0 {
None
} else if index < liter {
self.iter.idx(index)
} else {
self.orig.idx((index - liter) % lorig)
}
}
}
/// An iterator which strings two iterators together
#[deriving(Clone)]
pub struct Chain<T, U> {
a: T,
b: U,
flag: bool,
}
impl<A, T: Iterator<A>, U: Iterator<A>> Iterator<A> for Chain<T, U> {
#[inline]
fn next(&mut self) -> Option<A> {
if self.flag {
self.b.next()
} else {
match self.a.next() {
Some(x) => return Some(x),
_ => ()
}
self.flag = true;
self.b.next()
}
}
#[inline]
fn size_hint(&self) -> (uint, Option<uint>) {
let (a_lower, a_upper) = self.a.size_hint();
let (b_lower, b_upper) = self.b.size_hint();
let lower = a_lower.saturating_add(b_lower);
let upper = match (a_upper, b_upper) {
(Some(x), Some(y)) => x.checked_add(&y),
_ => None
};
(lower, upper)
}
}
impl<A, T: DoubleEndedIterator<A>, U: DoubleEndedIterator<A>> DoubleEndedIterator<A>
for Chain<T, U> {
#[inline]
fn next_back(&mut self) -> Option<A> {
match self.b.next_back() {
Some(x) => Some(x),
None => self.a.next_back()
}
}
}
impl<A, T: RandomAccessIterator<A>, U: RandomAccessIterator<A>> RandomAccessIterator<A>
for Chain<T, U> {
#[inline]
fn indexable(&self) -> uint {
let (a, b) = (self.a.indexable(), self.b.indexable());
a.saturating_add(b)
}
#[inline]
fn idx(&mut self, index: uint) -> Option<A> {
let len = self.a.indexable();
if index < len {
self.a.idx(index)
} else {
self.b.idx(index - len)
}
}
}
/// An iterator which iterates two other iterators simultaneously
#[deriving(Clone)]
pub struct Zip<T, U> {
a: T,
b: U
}
impl<A, B, T: Iterator<A>, U: Iterator<B>> Iterator<(A, B)> for Zip<T, U> {
#[inline]
fn next(&mut self) -> Option<(A, B)> {
match self.a.next() {
None => None,
Some(x) => match self.b.next() {
None => None,
Some(y) => Some((x, y))
}
}
}
#[inline]
fn size_hint(&self) -> (uint, Option<uint>) {
let (a_lower, a_upper) = self.a.size_hint();
let (b_lower, b_upper) = self.b.size_hint();
let lower = cmp::min(a_lower, b_lower);
let upper = match (a_upper, b_upper) {
(Some(x), Some(y)) => Some(cmp::min(x,y)),
(Some(x), None) => Some(x),
(None, Some(y)) => Some(y),
(None, None) => None
};
(lower, upper)
}
}
impl<A, B, T: ExactSize<A>, U: ExactSize<B>> DoubleEndedIterator<(A, B)>
for Zip<T, U> {
#[inline]
fn next_back(&mut self) -> Option<(A, B)> {
let (a_sz, a_upper) = self.a.size_hint();
let (b_sz, b_upper) = self.b.size_hint();
assert!(a_upper == Some(a_sz));
assert!(b_upper == Some(b_sz));
if a_sz < b_sz {
for _ in range(0, b_sz - a_sz) { self.b.next_back(); }
} else if a_sz > b_sz {
for _ in range(0, a_sz - b_sz) { self.a.next_back(); }
}
let (a_sz, _) = self.a.size_hint();
let (b_sz, _) = self.b.size_hint();
assert!(a_sz == b_sz);
match (self.a.next_back(), self.b.next_back()) {
(Some(x), Some(y)) => Some((x, y)),
_ => None
}
}
}
impl<A, B, T: RandomAccessIterator<A>, U: RandomAccessIterator<B>>
RandomAccessIterator<(A, B)> for Zip<T, U> {
#[inline]
fn indexable(&self) -> uint {
cmp::min(self.a.indexable(), self.b.indexable())
}
#[inline]
fn idx(&mut self, index: uint) -> Option<(A, B)> {
match self.a.idx(index) {
None => None,
Some(x) => match self.b.idx(index) {
None => None,
Some(y) => Some((x, y))
}
}
}
}
/// An iterator which maps the values of `iter` with `f`
pub struct Map<'a, A, B, T> {
iter: T,
f: |A|: 'a -> B
}
impl<'a, A, B, T> Map<'a, A, B, T> {
#[inline]
fn do_map(&mut self, elt: Option<A>) -> Option<B> {
match elt {
Some(a) => Some((self.f)(a)),
_ => None
}
}
}
impl<'a, A, B, T: Iterator<A>> Iterator<B> for Map<'a, A, B, T> {
#[inline]
fn next(&mut self) -> Option<B> {
let next = self.iter.next();
self.do_map(next)
}
#[inline]
fn size_hint(&self) -> (uint, Option<uint>) {
self.iter.size_hint()
}
}
impl<'a, A, B, T: DoubleEndedIterator<A>> DoubleEndedIterator<B> for Map<'a, A, B, T> {
#[inline]
fn next_back(&mut self) -> Option<B> {
let next = self.iter.next_back();
self.do_map(next)
}
}
impl<'a, A, B, T: RandomAccessIterator<A>> RandomAccessIterator<B> for Map<'a, A, B, T> {
#[inline]
fn indexable(&self) -> uint {
self.iter.indexable()
}
#[inline]
fn idx(&mut self, index: uint) -> Option<B> {
let elt = self.iter.idx(index);
self.do_map(elt)
}
}
/// An iterator which filters the elements of `iter` with `predicate`
pub struct Filter<'a, A, T> {
iter: T,
predicate: |&A|: 'a -> bool
}
impl<'a, A, T: Iterator<A>> Iterator<A> for Filter<'a, A, T> {
#[inline]
fn next(&mut self) -> Option<A> {
for x in self.iter {
if (self.predicate)(&x) {
return Some(x);
} else {
continue
}
}
None
}
#[inline]
fn size_hint(&self) -> (uint, Option<uint>) {
let (_, upper) = self.iter.size_hint();
(0, upper) // can't know a lower bound, due to the predicate
}
}
impl<'a, A, T: DoubleEndedIterator<A>> DoubleEndedIterator<A> for Filter<'a, A, T> {
#[inline]
fn next_back(&mut self) -> Option<A> {
loop {
match self.iter.next_back() {
None => return None,
Some(x) => {
if (self.predicate)(&x) {
return Some(x);
} else {
continue
}
}
}
}
}
}
/// An iterator which uses `f` to both filter and map elements from `iter`
pub struct FilterMap<'a, A, B, T> {
iter: T,
f: |A|: 'a -> Option<B>
}
impl<'a, A, B, T: Iterator<A>> Iterator<B> for FilterMap<'a, A, B, T> {
#[inline]
fn next(&mut self) -> Option<B> {
for x in self.iter {
match (self.f)(x) {
Some(y) => return Some(y),
None => ()
}
}
None
}
#[inline]
fn size_hint(&self) -> (uint, Option<uint>) {
let (_, upper) = self.iter.size_hint();
(0, upper) // can't know a lower bound, due to the predicate
}
}
impl<'a, A, B, T: DoubleEndedIterator<A>> DoubleEndedIterator<B>
for FilterMap<'a, A, B, T> {
#[inline]
fn next_back(&mut self) -> Option<B> {
loop {
match self.iter.next_back() {
None => return None,
Some(x) => {
match (self.f)(x) {
Some(y) => return Some(y),
None => ()
}
}
}
}
}
}
/// An iterator which yields the current count and the element during iteration
#[deriving(Clone)]
pub struct Enumerate<T> {
iter: T,
count: uint
}
impl<A, T: Iterator<A>> Iterator<(uint, A)> for Enumerate<T> {
#[inline]
fn next(&mut self) -> Option<(uint, A)> {
match self.iter.next() {
Some(a) => {
let ret = Some((self.count, a));
self.count += 1;
ret
}
_ => None
}
}
#[inline]
fn size_hint(&self) -> (uint, Option<uint>) {
self.iter.size_hint()
}
}
impl<A, T: ExactSize<A>> DoubleEndedIterator<(uint, A)> for Enumerate<T> {
#[inline]
fn next_back(&mut self) -> Option<(uint, A)> {
match self.iter.next_back() {
Some(a) => {
let (lower, upper) = self.iter.size_hint();
assert!(upper == Some(lower));
Some((self.count + lower, a))
}
_ => None
}
}
}
impl<A, T: RandomAccessIterator<A>> RandomAccessIterator<(uint, A)> for Enumerate<T> {
#[inline]
fn indexable(&self) -> uint {
self.iter.indexable()
}
#[inline]
fn idx(&mut self, index: uint) -> Option<(uint, A)> {
match self.iter.idx(index) {
Some(a) => Some((self.count + index, a)),
_ => None,
}
}
}
/// An iterator with a `peek()` that returns an optional reference to the next element.
pub struct Peekable<A, T> {
iter: T,
peeked: Option<A>,
}
impl<A, T: Iterator<A>> Iterator<A> for Peekable<A, T> {
#[inline]
fn next(&mut self) -> Option<A> {
if self.peeked.is_some() { self.peeked.take() }
else { self.iter.next() }
}
#[inline]
fn size_hint(&self) -> (uint, Option<uint>) {
let (lo, hi) = self.iter.size_hint();
if self.peeked.is_some() {
let lo = lo.saturating_add(1);
let hi = match hi {
Some(x) => x.checked_add(&1),
None => None
};
(lo, hi)
} else {
(lo, hi)
}
}
}
impl<'a, A, T: Iterator<A>> Peekable<A, T> {
/// Return a reference to the next element of the iterator with out advancing it,
/// or None if the iterator is exhausted.
#[inline]
pub fn peek(&'a mut self) -> Option<&'a A> {
if self.peeked.is_none() {
self.peeked = self.iter.next();
}
match self.peeked {
Some(ref value) => Some(value),
None => None,
}
}
/// Check whether peekable iterator is empty or not.
#[inline]
pub fn is_empty(&mut self) -> bool {
self.peek().is_none()
}
}
/// An iterator which rejects elements while `predicate` is true
pub struct SkipWhile<'a, A, T> {
iter: T,
flag: bool,
predicate: |&A|: 'a -> bool
}
impl<'a, A, T: Iterator<A>> Iterator<A> for SkipWhile<'a, A, T> {
#[inline]
fn next(&mut self) -> Option<A> {
let mut next = self.iter.next();
if self.flag {
next
} else {
loop {
match next {
Some(x) => {
if (self.predicate)(&x) {
next = self.iter.next();
continue
} else {
self.flag = true;
return Some(x)
}
}
None => return None
}
}
}
}
#[inline]
fn size_hint(&self) -> (uint, Option<uint>) {
let (_, upper) = self.iter.size_hint();
(0, upper) // can't know a lower bound, due to the predicate
}
}
/// An iterator which only accepts elements while `predicate` is true
pub struct TakeWhile<'a, A, T> {
iter: T,
flag: bool,
predicate: |&A|: 'a -> bool
}
impl<'a, A, T: Iterator<A>> Iterator<A> for TakeWhile<'a, A, T> {
#[inline]
fn next(&mut self) -> Option<A> {
if self.flag {
None
} else {
match self.iter.next() {
Some(x) => {
if (self.predicate)(&x) {
Some(x)
} else {
self.flag = true;
None
}
}
None => None
}
}
}
#[inline]
fn size_hint(&self) -> (uint, Option<uint>) {
let (_, upper) = self.iter.size_hint();
(0, upper) // can't know a lower bound, due to the predicate
}
}
/// An iterator which skips over `n` elements of `iter`.
#[deriving(Clone)]
pub struct Skip<T> {
iter: T,
n: uint
}
impl<A, T: Iterator<A>> Iterator<A> for Skip<T> {
#[inline]
fn next(&mut self) -> Option<A> {
let mut next = self.iter.next();
if self.n == 0 {
next
} else {
let mut n = self.n;
while n > 0 {
n -= 1;
match next {
Some(_) => {
next = self.iter.next();
continue
}
None => {<|fim▁hole|> }
}
self.n = 0;
next
}
}
#[inline]
fn size_hint(&self) -> (uint, Option<uint>) {
let (lower, upper) = self.iter.size_hint();
let lower = lower.saturating_sub(self.n);
let upper = match upper {
Some(x) => Some(x.saturating_sub(self.n)),
None => None
};
(lower, upper)
}
}
impl<A, T: RandomAccessIterator<A>> RandomAccessIterator<A> for Skip<T> {
#[inline]
fn indexable(&self) -> uint {
self.iter.indexable().saturating_sub(self.n)
}
#[inline]
fn idx(&mut self, index: uint) -> Option<A> {
if index >= self.indexable() {
None
} else {
self.iter.idx(index + self.n)
}
}
}
/// An iterator which only iterates over the first `n` iterations of `iter`.
#[deriving(Clone)]
pub struct Take<T> {
iter: T,
n: uint
}
impl<A, T: Iterator<A>> Iterator<A> for Take<T> {
#[inline]
fn next(&mut self) -> Option<A> {
if self.n != 0 {
self.n -= 1;
self.iter.next()
} else {
None
}
}
#[inline]
fn size_hint(&self) -> (uint, Option<uint>) {
let (lower, upper) = self.iter.size_hint();
let lower = cmp::min(lower, self.n);
let upper = match upper {
Some(x) if x < self.n => Some(x),
_ => Some(self.n)
};
(lower, upper)
}
}
impl<A, T: RandomAccessIterator<A>> RandomAccessIterator<A> for Take<T> {
#[inline]
fn indexable(&self) -> uint {
cmp::min(self.iter.indexable(), self.n)
}
#[inline]
fn idx(&mut self, index: uint) -> Option<A> {
if index >= self.n {
None
} else {
self.iter.idx(index)
}
}
}
/// An iterator to maintain state while iterating another iterator
pub struct Scan<'a, A, B, T, St> {
iter: T,
f: |&mut St, A|: 'a -> Option<B>,
/// The current internal state to be passed to the closure next.
pub state: St,
}
impl<'a, A, B, T: Iterator<A>, St> Iterator<B> for Scan<'a, A, B, T, St> {
#[inline]
fn next(&mut self) -> Option<B> {
self.iter.next().and_then(|a| (self.f)(&mut self.state, a))
}
#[inline]
fn size_hint(&self) -> (uint, Option<uint>) {
let (_, upper) = self.iter.size_hint();
(0, upper) // can't know a lower bound, due to the scan function
}
}
/// An iterator that maps each element to an iterator,
/// and yields the elements of the produced iterators
///
pub struct FlatMap<'a, A, T, U> {
iter: T,
f: |A|: 'a -> U,
frontiter: Option<U>,
backiter: Option<U>,
}
impl<'a, A, T: Iterator<A>, B, U: Iterator<B>> Iterator<B> for FlatMap<'a, A, T, U> {
#[inline]
fn next(&mut self) -> Option<B> {
loop {
for inner in self.frontiter.mut_iter() {
for x in *inner {
return Some(x)
}
}
match self.iter.next().map(|x| (self.f)(x)) {
None => return self.backiter.as_mut().and_then(|it| it.next()),
next => self.frontiter = next,
}
}
}
#[inline]
fn size_hint(&self) -> (uint, Option<uint>) {
let (flo, fhi) = self.frontiter.as_ref().map_or((0, Some(0)), |it| it.size_hint());
let (blo, bhi) = self.backiter.as_ref().map_or((0, Some(0)), |it| it.size_hint());
let lo = flo.saturating_add(blo);
match (self.iter.size_hint(), fhi, bhi) {
((0, Some(0)), Some(a), Some(b)) => (lo, a.checked_add(&b)),
_ => (lo, None)
}
}
}
impl<'a,
A, T: DoubleEndedIterator<A>,
B, U: DoubleEndedIterator<B>> DoubleEndedIterator<B>
for FlatMap<'a, A, T, U> {
#[inline]
fn next_back(&mut self) -> Option<B> {
loop {
for inner in self.backiter.mut_iter() {
match inner.next_back() {
None => (),
y => return y
}
}
match self.iter.next_back().map(|x| (self.f)(x)) {
None => return self.frontiter.as_mut().and_then(|it| it.next_back()),
next => self.backiter = next,
}
}
}
}
/// An iterator that yields `None` forever after the underlying iterator
/// yields `None` once.
#[deriving(Clone)]
pub struct Fuse<T> {
iter: T,
done: bool
}
impl<A, T: Iterator<A>> Iterator<A> for Fuse<T> {
#[inline]
fn next(&mut self) -> Option<A> {
if self.done {
None
} else {
match self.iter.next() {
None => {
self.done = true;
None
}
x => x
}
}
}
#[inline]
fn size_hint(&self) -> (uint, Option<uint>) {
if self.done {
(0, Some(0))
} else {
self.iter.size_hint()
}
}
}
impl<A, T: DoubleEndedIterator<A>> DoubleEndedIterator<A> for Fuse<T> {
#[inline]
fn next_back(&mut self) -> Option<A> {
if self.done {
None
} else {
match self.iter.next_back() {
None => {
self.done = true;
None
}
x => x
}
}
}
}
// Allow RandomAccessIterators to be fused without affecting random-access behavior
impl<A, T: RandomAccessIterator<A>> RandomAccessIterator<A> for Fuse<T> {
#[inline]
fn indexable(&self) -> uint {
self.iter.indexable()
}
#[inline]
fn idx(&mut self, index: uint) -> Option<A> {
self.iter.idx(index)
}
}
impl<T> Fuse<T> {
/// Resets the fuse such that the next call to .next() or .next_back() will
/// call the underlying iterator again even if it previously returned None.
#[inline]
pub fn reset_fuse(&mut self) {
self.done = false
}
}
/// An iterator that calls a function with a reference to each
/// element before yielding it.
pub struct Inspect<'a, A, T> {
iter: T,
f: |&A|: 'a
}
impl<'a, A, T> Inspect<'a, A, T> {
#[inline]
fn do_inspect(&mut self, elt: Option<A>) -> Option<A> {
match elt {
Some(ref a) => (self.f)(a),
None => ()
}
elt
}
}
impl<'a, A, T: Iterator<A>> Iterator<A> for Inspect<'a, A, T> {
#[inline]
fn next(&mut self) -> Option<A> {
let next = self.iter.next();
self.do_inspect(next)
}
#[inline]
fn size_hint(&self) -> (uint, Option<uint>) {
self.iter.size_hint()
}
}
impl<'a, A, T: DoubleEndedIterator<A>> DoubleEndedIterator<A>
for Inspect<'a, A, T> {
#[inline]
fn next_back(&mut self) -> Option<A> {
let next = self.iter.next_back();
self.do_inspect(next)
}
}
impl<'a, A, T: RandomAccessIterator<A>> RandomAccessIterator<A>
for Inspect<'a, A, T> {
#[inline]
fn indexable(&self) -> uint {
self.iter.indexable()
}
#[inline]
fn idx(&mut self, index: uint) -> Option<A> {
let element = self.iter.idx(index);
self.do_inspect(element)
}
}
/// An iterator which just modifies the contained state throughout iteration.
pub struct Unfold<'a, A, St> {
f: |&mut St|: 'a -> Option<A>,
/// Internal state that will be yielded on the next iteration
pub state: St,
}
impl<'a, A, St> Unfold<'a, A, St> {
/// Creates a new iterator with the specified closure as the "iterator
/// function" and an initial state to eventually pass to the iterator
#[inline]
pub fn new<'a>(initial_state: St, f: |&mut St|: 'a -> Option<A>)
-> Unfold<'a, A, St> {
Unfold {
f: f,
state: initial_state
}
}
}
impl<'a, A, St> Iterator<A> for Unfold<'a, A, St> {
#[inline]
fn next(&mut self) -> Option<A> {
(self.f)(&mut self.state)
}
#[inline]
fn size_hint(&self) -> (uint, Option<uint>) {
// no possible known bounds at this point
(0, None)
}
}
/// An infinite iterator starting at `start` and advancing by `step` with each
/// iteration
#[deriving(Clone)]
pub struct Counter<A> {
/// The current state the counter is at (next value to be yielded)
state: A,
/// The amount that this iterator is stepping by
step: A,
}
/// Creates a new counter with the specified start/step
#[inline]
pub fn count<A>(start: A, step: A) -> Counter<A> {
Counter{state: start, step: step}
}
impl<A: Add<A, A> + Clone> Iterator<A> for Counter<A> {
#[inline]
fn next(&mut self) -> Option<A> {
let result = self.state.clone();
self.state = self.state + self.step;
Some(result)
}
#[inline]
fn size_hint(&self) -> (uint, Option<uint>) {
(uint::MAX, None) // Too bad we can't specify an infinite lower bound
}
}
/// An iterator over the range [start, stop)
#[deriving(Clone)]
pub struct Range<A> {
state: A,
stop: A,
one: A
}
/// Return an iterator over the range [start, stop)
#[inline]
pub fn range<A: Add<A, A> + Ord + Clone + One>(start: A, stop: A) -> Range<A> {
Range{state: start, stop: stop, one: One::one()}
}
// FIXME: #10414: Unfortunate type bound
impl<A: Add<A, A> + Ord + Clone + ToPrimitive> Iterator<A> for Range<A> {
#[inline]
fn next(&mut self) -> Option<A> {
if self.state < self.stop {
let result = self.state.clone();
self.state = self.state + self.one;
Some(result)
} else {
None
}
}
#[inline]
fn size_hint(&self) -> (uint, Option<uint>) {
// This first checks if the elements are representable as i64. If they aren't, try u64 (to
// handle cases like range(huge, huger)). We don't use uint/int because the difference of
// the i64/u64 might lie within their range.
let bound = match self.state.to_i64() {
Some(a) => {
let sz = self.stop.to_i64().map(|b| b.checked_sub(&a));
match sz {
Some(Some(bound)) => bound.to_uint(),
_ => None,
}
},
None => match self.state.to_u64() {
Some(a) => {
let sz = self.stop.to_u64().map(|b| b.checked_sub(&a));
match sz {
Some(Some(bound)) => bound.to_uint(),
_ => None
}
},
None => None
}
};
match bound {
Some(b) => (b, Some(b)),
// Standard fallback for unbounded/unrepresentable bounds
None => (0, None)
}
}
}
/// `Int` is required to ensure the range will be the same regardless of
/// the direction it is consumed.
impl<A: Int + Ord + Clone + ToPrimitive> DoubleEndedIterator<A> for Range<A> {
#[inline]
fn next_back(&mut self) -> Option<A> {
if self.stop > self.state {
self.stop = self.stop - self.one;
Some(self.stop.clone())
} else {
None
}
}
}
/// An iterator over the range [start, stop]
#[deriving(Clone)]
pub struct RangeInclusive<A> {
range: Range<A>,
done: bool,
}
/// Return an iterator over the range [start, stop]
#[inline]
pub fn range_inclusive<A: Add<A, A> + Ord + Clone + One + ToPrimitive>(start: A, stop: A)
-> RangeInclusive<A> {
RangeInclusive{range: range(start, stop), done: false}
}
impl<A: Add<A, A> + Ord + Clone + ToPrimitive> Iterator<A> for RangeInclusive<A> {
#[inline]
fn next(&mut self) -> Option<A> {
match self.range.next() {
Some(x) => Some(x),
None => {
if !self.done && self.range.state == self.range.stop {
self.done = true;
Some(self.range.stop.clone())
} else {
None
}
}
}
}
#[inline]
fn size_hint(&self) -> (uint, Option<uint>) {
let (lo, hi) = self.range.size_hint();
if self.done {
(lo, hi)
} else {
let lo = lo.saturating_add(1);
let hi = match hi {
Some(x) => x.checked_add(&1),
None => None
};
(lo, hi)
}
}
}
impl<A: Sub<A, A> + Int + Ord + Clone + ToPrimitive> DoubleEndedIterator<A>
for RangeInclusive<A> {
#[inline]
fn next_back(&mut self) -> Option<A> {
if self.range.stop > self.range.state {
let result = self.range.stop.clone();
self.range.stop = self.range.stop - self.range.one;
Some(result)
} else if !self.done && self.range.state == self.range.stop {
self.done = true;
Some(self.range.stop.clone())
} else {
None
}
}
}
/// An iterator over the range [start, stop) by `step`. It handles overflow by stopping.
#[deriving(Clone)]
pub struct RangeStep<A> {
state: A,
stop: A,
step: A,
rev: bool,
}
/// Return an iterator over the range [start, stop) by `step`. It handles overflow by stopping.
#[inline]
pub fn range_step<A: CheckedAdd + Ord + Clone + Zero>(start: A, stop: A, step: A) -> RangeStep<A> {
let rev = step < Zero::zero();
RangeStep{state: start, stop: stop, step: step, rev: rev}
}
impl<A: CheckedAdd + Ord + Clone> Iterator<A> for RangeStep<A> {
#[inline]
fn next(&mut self) -> Option<A> {
if (self.rev && self.state > self.stop) || (!self.rev && self.state < self.stop) {
let result = self.state.clone();
match self.state.checked_add(&self.step) {
Some(x) => self.state = x,
None => self.state = self.stop.clone()
}
Some(result)
} else {
None
}
}
}
/// An iterator over the range [start, stop] by `step`. It handles overflow by stopping.
#[deriving(Clone)]
pub struct RangeStepInclusive<A> {
state: A,
stop: A,
step: A,
rev: bool,
done: bool,
}
/// Return an iterator over the range [start, stop] by `step`. It handles overflow by stopping.
#[inline]
pub fn range_step_inclusive<A: CheckedAdd + Ord + Clone + Zero>(start: A, stop: A,
step: A) -> RangeStepInclusive<A> {
let rev = step < Zero::zero();
RangeStepInclusive{state: start, stop: stop, step: step, rev: rev, done: false}
}
impl<A: CheckedAdd + Ord + Clone + Eq> Iterator<A> for RangeStepInclusive<A> {
#[inline]
fn next(&mut self) -> Option<A> {
if !self.done && ((self.rev && self.state >= self.stop) ||
(!self.rev && self.state <= self.stop)) {
let result = self.state.clone();
match self.state.checked_add(&self.step) {
Some(x) => self.state = x,
None => self.done = true
}
Some(result)
} else {
None
}
}
}
/// An iterator that repeats an element endlessly
#[deriving(Clone)]
pub struct Repeat<A> {
element: A
}
impl<A: Clone> Repeat<A> {
/// Create a new `Repeat` that endlessly repeats the element `elt`.
#[inline]
pub fn new(elt: A) -> Repeat<A> {
Repeat{element: elt}
}
}
impl<A: Clone> Iterator<A> for Repeat<A> {
#[inline]
fn next(&mut self) -> Option<A> { self.idx(0) }
#[inline]
fn size_hint(&self) -> (uint, Option<uint>) { (uint::MAX, None) }
}
impl<A: Clone> DoubleEndedIterator<A> for Repeat<A> {
#[inline]
fn next_back(&mut self) -> Option<A> { self.idx(0) }
}
impl<A: Clone> RandomAccessIterator<A> for Repeat<A> {
#[inline]
fn indexable(&self) -> uint { uint::MAX }
#[inline]
fn idx(&mut self, _: uint) -> Option<A> { Some(self.element.clone()) }
}
/// Functions for lexicographical ordering of sequences.
///
/// Lexicographical ordering through `<`, `<=`, `>=`, `>` requires
/// that the elements implement both `Eq` and `Ord`.
///
/// If two sequences are equal up until the point where one ends,
/// the shorter sequence compares less.
pub mod order {
use cmp;
use cmp::{TotalEq, TotalOrd, Ord, Eq};
use option::{Some, None};
use super::Iterator;
/// Compare `a` and `b` for equality using `TotalEq`
pub fn equals<A: TotalEq, T: Iterator<A>>(mut a: T, mut b: T) -> bool {
loop {
match (a.next(), b.next()) {
(None, None) => return true,
(None, _) | (_, None) => return false,
(Some(x), Some(y)) => if x != y { return false },
}
}
}
/// Order `a` and `b` lexicographically using `TotalOrd`
pub fn cmp<A: TotalOrd, T: Iterator<A>>(mut a: T, mut b: T) -> cmp::Ordering {
loop {
match (a.next(), b.next()) {
(None, None) => return cmp::Equal,
(None, _ ) => return cmp::Less,
(_ , None) => return cmp::Greater,
(Some(x), Some(y)) => match x.cmp(&y) {
cmp::Equal => (),
non_eq => return non_eq,
},
}
}
}
/// Compare `a` and `b` for equality (Using partial equality, `Eq`)
pub fn eq<A: Eq, T: Iterator<A>>(mut a: T, mut b: T) -> bool {
loop {
match (a.next(), b.next()) {
(None, None) => return true,
(None, _) | (_, None) => return false,
(Some(x), Some(y)) => if !x.eq(&y) { return false },
}
}
}
/// Compare `a` and `b` for nonequality (Using partial equality, `Eq`)
pub fn ne<A: Eq, T: Iterator<A>>(mut a: T, mut b: T) -> bool {
loop {
match (a.next(), b.next()) {
(None, None) => return false,
(None, _) | (_, None) => return true,
(Some(x), Some(y)) => if x.ne(&y) { return true },
}
}
}
/// Return `a` < `b` lexicographically (Using partial order, `Ord`)
pub fn lt<A: Ord, T: Iterator<A>>(mut a: T, mut b: T) -> bool {
loop {
match (a.next(), b.next()) {
(None, None) => return false,
(None, _ ) => return true,
(_ , None) => return false,
(Some(x), Some(y)) => if x.ne(&y) { return x.lt(&y) },
}
}
}
/// Return `a` <= `b` lexicographically (Using partial order, `Ord`)
pub fn le<A: Ord, T: Iterator<A>>(mut a: T, mut b: T) -> bool {
loop {
match (a.next(), b.next()) {
(None, None) => return true,
(None, _ ) => return true,
(_ , None) => return false,
(Some(x), Some(y)) => if x.ne(&y) { return x.le(&y) },
}
}
}
/// Return `a` > `b` lexicographically (Using partial order, `Ord`)
pub fn gt<A: Ord, T: Iterator<A>>(mut a: T, mut b: T) -> bool {
loop {
match (a.next(), b.next()) {
(None, None) => return false,
(None, _ ) => return false,
(_ , None) => return true,
(Some(x), Some(y)) => if x.ne(&y) { return x.gt(&y) },
}
}
}
/// Return `a` >= `b` lexicographically (Using partial order, `Ord`)
pub fn ge<A: Ord, T: Iterator<A>>(mut a: T, mut b: T) -> bool {
loop {
match (a.next(), b.next()) {
(None, None) => return true,
(None, _ ) => return false,
(_ , None) => return true,
(Some(x), Some(y)) => if x.ne(&y) { return x.ge(&y) },
}
}
}
#[test]
fn test_lt() {
use slice::ImmutableVector;
let empty: [int, ..0] = [];
let xs = [1,2,3];
let ys = [1,2,0];
assert!(!lt(xs.iter(), ys.iter()));
assert!(!le(xs.iter(), ys.iter()));
assert!( gt(xs.iter(), ys.iter()));
assert!( ge(xs.iter(), ys.iter()));
assert!( lt(ys.iter(), xs.iter()));
assert!( le(ys.iter(), xs.iter()));
assert!(!gt(ys.iter(), xs.iter()));
assert!(!ge(ys.iter(), xs.iter()));
assert!( lt(empty.iter(), xs.iter()));
assert!( le(empty.iter(), xs.iter()));
assert!(!gt(empty.iter(), xs.iter()));
assert!(!ge(empty.iter(), xs.iter()));
// Sequence with NaN
let u = [1.0, 2.0];
let v = [0.0/0.0, 3.0];
assert!(!lt(u.iter(), v.iter()));
assert!(!le(u.iter(), v.iter()));
assert!(!gt(u.iter(), v.iter()));
assert!(!ge(u.iter(), v.iter()));
let a = [0.0/0.0];
let b = [1.0];
let c = [2.0];
assert!(lt(a.iter(), b.iter()) == (a[0] < b[0]));
assert!(le(a.iter(), b.iter()) == (a[0] <= b[0]));
assert!(gt(a.iter(), b.iter()) == (a[0] > b[0]));
assert!(ge(a.iter(), b.iter()) == (a[0] >= b[0]));
assert!(lt(c.iter(), b.iter()) == (c[0] < b[0]));
assert!(le(c.iter(), b.iter()) == (c[0] <= b[0]));
assert!(gt(c.iter(), b.iter()) == (c[0] > b[0]));
assert!(ge(c.iter(), b.iter()) == (c[0] >= b[0]));
}
}
#[cfg(test)]
mod tests {
use prelude::*;
use iter::*;
use num;
use realstd::vec::Vec;
use realstd::slice::Vector;
use cmp;
use realstd::owned::Box;
use uint;
impl<T> FromIterator<T> for Vec<T> {
fn from_iter<I: Iterator<T>>(mut iterator: I) -> Vec<T> {
let mut v = Vec::new();
for e in iterator {
v.push(e);
}
return v;
}
}
impl<'a, T> Iterator<&'a T> for ::realcore::slice::Items<'a, T> {
fn next(&mut self) -> Option<&'a T> {
use RealSome = realcore::option::Some;
use RealNone = realcore::option::None;
fn mynext<T, I: ::realcore::iter::Iterator<T>>(i: &mut I)
-> ::realcore::option::Option<T>
{
use realcore::iter::Iterator;
i.next()
}
match mynext(self) {
RealSome(t) => Some(t),
RealNone => None,
}
}
}
#[test]
fn test_counter_from_iter() {
let it = count(0, 5).take(10);
let xs: Vec<int> = FromIterator::from_iter(it);
assert!(xs == vec![0, 5, 10, 15, 20, 25, 30, 35, 40, 45]);
}
#[test]
fn test_iterator_chain() {
let xs = [0u, 1, 2, 3, 4, 5];
let ys = [30u, 40, 50, 60];
let expected = [0, 1, 2, 3, 4, 5, 30, 40, 50, 60];
let mut it = xs.iter().chain(ys.iter());
let mut i = 0;
for &x in it {
assert_eq!(x, expected[i]);
i += 1;
}
assert_eq!(i, expected.len());
let ys = count(30u, 10).take(4);
let mut it = xs.iter().map(|&x| x).chain(ys);
let mut i = 0;
for x in it {
assert_eq!(x, expected[i]);
i += 1;
}
assert_eq!(i, expected.len());
}
#[test]
fn test_filter_map() {
let mut it = count(0u, 1u).take(10)
.filter_map(|x| if x % 2 == 0 { Some(x*x) } else { None });
assert!(it.collect::<Vec<uint>>() == vec![0*0, 2*2, 4*4, 6*6, 8*8]);
}
#[test]
fn test_iterator_enumerate() {
let xs = [0u, 1, 2, 3, 4, 5];
let mut it = xs.iter().enumerate();
for (i, &x) in it {
assert_eq!(i, x);
}
}
#[test]
fn test_iterator_peekable() {
let xs = box [0u, 1, 2, 3, 4, 5];
let mut it = xs.iter().map(|&x|x).peekable();
assert_eq!(it.peek().unwrap(), &0);
assert_eq!(it.next().unwrap(), 0);
assert_eq!(it.next().unwrap(), 1);
assert_eq!(it.next().unwrap(), 2);
assert_eq!(it.peek().unwrap(), &3);
assert_eq!(it.peek().unwrap(), &3);
assert_eq!(it.next().unwrap(), 3);
assert_eq!(it.next().unwrap(), 4);
assert_eq!(it.peek().unwrap(), &5);
assert_eq!(it.next().unwrap(), 5);
assert!(it.peek().is_none());
assert!(it.next().is_none());
}
#[test]
fn test_iterator_take_while() {
let xs = [0u, 1, 2, 3, 5, 13, 15, 16, 17, 19];
let ys = [0u, 1, 2, 3, 5, 13];
let mut it = xs.iter().take_while(|&x| *x < 15u);
let mut i = 0;
for &x in it {
assert_eq!(x, ys[i]);
i += 1;
}
assert_eq!(i, ys.len());
}
#[test]
fn test_iterator_skip_while() {
let xs = [0u, 1, 2, 3, 5, 13, 15, 16, 17, 19];
let ys = [15, 16, 17, 19];
let mut it = xs.iter().skip_while(|&x| *x < 15u);
let mut i = 0;
for &x in it {
assert_eq!(x, ys[i]);
i += 1;
}
assert_eq!(i, ys.len());
}
#[test]
fn test_iterator_skip() {
let xs = [0u, 1, 2, 3, 5, 13, 15, 16, 17, 19, 20, 30];
let ys = [13, 15, 16, 17, 19, 20, 30];
let mut it = xs.iter().skip(5);
let mut i = 0;
for &x in it {
assert_eq!(x, ys[i]);
i += 1;
}
assert_eq!(i, ys.len());
}
#[test]
fn test_iterator_take() {
let xs = [0u, 1, 2, 3, 5, 13, 15, 16, 17, 19];
let ys = [0u, 1, 2, 3, 5];
let mut it = xs.iter().take(5);
let mut i = 0;
for &x in it {
assert_eq!(x, ys[i]);
i += 1;
}
assert_eq!(i, ys.len());
}
#[test]
fn test_iterator_scan() {
// test the type inference
fn add(old: &mut int, new: &uint) -> Option<f64> {
*old += *new as int;
Some(*old as f64)
}
let xs = [0u, 1, 2, 3, 4];
let ys = [0f64, 1.0, 3.0, 6.0, 10.0];
let mut it = xs.iter().scan(0, add);
let mut i = 0;
for x in it {
assert_eq!(x, ys[i]);
i += 1;
}
assert_eq!(i, ys.len());
}
#[test]
fn test_iterator_flat_map() {
let xs = [0u, 3, 6];
let ys = [0u, 1, 2, 3, 4, 5, 6, 7, 8];
let mut it = xs.iter().flat_map(|&x| count(x, 1).take(3));
let mut i = 0;
for x in it {
assert_eq!(x, ys[i]);
i += 1;
}
assert_eq!(i, ys.len());
}
#[test]
fn test_inspect() {
let xs = [1u, 2, 3, 4];
let mut n = 0;
let ys = xs.iter()
.map(|&x| x)
.inspect(|_| n += 1)
.collect::<Vec<uint>>();
assert_eq!(n, xs.len());
assert_eq!(xs.as_slice(), ys.as_slice());
}
#[test]
fn test_unfoldr() {
fn count(st: &mut uint) -> Option<uint> {
if *st < 10 {
let ret = Some(*st);
*st += 1;
ret
} else {
None
}
}
let mut it = Unfold::new(0, count);
let mut i = 0;
for counted in it {
assert_eq!(counted, i);
i += 1;
}
assert_eq!(i, 10);
}
#[test]
fn test_cycle() {
let cycle_len = 3;
let it = count(0u, 1).take(cycle_len).cycle();
assert_eq!(it.size_hint(), (uint::MAX, None));
for (i, x) in it.take(100).enumerate() {
assert_eq!(i % cycle_len, x);
}
let mut it = count(0u, 1).take(0).cycle();
assert_eq!(it.size_hint(), (0, Some(0)));
assert_eq!(it.next(), None);
}
#[test]
fn test_iterator_nth() {
let v = &[0, 1, 2, 3, 4];
for i in range(0u, v.len()) {
assert_eq!(v.iter().nth(i).unwrap(), &v[i]);
}
}
#[test]
fn test_iterator_last() {
let v = &[0, 1, 2, 3, 4];
assert_eq!(v.iter().last().unwrap(), &4);
assert_eq!(v.slice(0, 1).iter().last().unwrap(), &0);
}
#[test]
fn test_iterator_len() {
let v = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
assert_eq!(v.slice(0, 4).iter().len(), 4);
assert_eq!(v.slice(0, 10).iter().len(), 10);
assert_eq!(v.slice(0, 0).iter().len(), 0);
}
#[test]
fn test_iterator_sum() {
let v = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
assert_eq!(v.slice(0, 4).iter().map(|&x| x).sum(), 6);
assert_eq!(v.iter().map(|&x| x).sum(), 55);
assert_eq!(v.slice(0, 0).iter().map(|&x| x).sum(), 0);
}
#[test]
fn test_iterator_product() {
let v = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
assert_eq!(v.slice(0, 4).iter().map(|&x| x).product(), 0);
assert_eq!(v.slice(1, 5).iter().map(|&x| x).product(), 24);
assert_eq!(v.slice(0, 0).iter().map(|&x| x).product(), 1);
}
#[test]
fn test_iterator_max() {
let v = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
assert_eq!(v.slice(0, 4).iter().map(|&x| x).max(), Some(3));
assert_eq!(v.iter().map(|&x| x).max(), Some(10));
assert_eq!(v.slice(0, 0).iter().map(|&x| x).max(), None);
}
#[test]
fn test_iterator_min() {
let v = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
assert_eq!(v.slice(0, 4).iter().map(|&x| x).min(), Some(0));
assert_eq!(v.iter().map(|&x| x).min(), Some(0));
assert_eq!(v.slice(0, 0).iter().map(|&x| x).min(), None);
}
#[test]
fn test_iterator_size_hint() {
let c = count(0, 1);
let v = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
let v2 = &[10, 11, 12];
let vi = v.iter();
assert_eq!(c.size_hint(), (uint::MAX, None));
assert_eq!(vi.size_hint(), (10, Some(10)));
assert_eq!(c.take(5).size_hint(), (5, Some(5)));
assert_eq!(c.skip(5).size_hint().val1(), None);
assert_eq!(c.take_while(|_| false).size_hint(), (0, None));
assert_eq!(c.skip_while(|_| false).size_hint(), (0, None));
assert_eq!(c.enumerate().size_hint(), (uint::MAX, None));
assert_eq!(c.chain(vi.map(|&i| i)).size_hint(), (uint::MAX, None));
assert_eq!(c.zip(vi).size_hint(), (10, Some(10)));
assert_eq!(c.scan(0, |_,_| Some(0)).size_hint(), (0, None));
assert_eq!(c.filter(|_| false).size_hint(), (0, None));
assert_eq!(c.map(|_| 0).size_hint(), (uint::MAX, None));
assert_eq!(c.filter_map(|_| Some(0)).size_hint(), (0, None));
assert_eq!(vi.take(5).size_hint(), (5, Some(5)));
assert_eq!(vi.take(12).size_hint(), (10, Some(10)));
assert_eq!(vi.skip(3).size_hint(), (7, Some(7)));
assert_eq!(vi.skip(12).size_hint(), (0, Some(0)));
assert_eq!(vi.take_while(|_| false).size_hint(), (0, Some(10)));
assert_eq!(vi.skip_while(|_| false).size_hint(), (0, Some(10)));
assert_eq!(vi.enumerate().size_hint(), (10, Some(10)));
assert_eq!(vi.chain(v2.iter()).size_hint(), (13, Some(13)));
assert_eq!(vi.zip(v2.iter()).size_hint(), (3, Some(3)));
assert_eq!(vi.scan(0, |_,_| Some(0)).size_hint(), (0, Some(10)));
assert_eq!(vi.filter(|_| false).size_hint(), (0, Some(10)));
assert_eq!(vi.map(|i| i+1).size_hint(), (10, Some(10)));
assert_eq!(vi.filter_map(|_| Some(0)).size_hint(), (0, Some(10)));
}
#[test]
fn test_collect() {
let a = vec![1, 2, 3, 4, 5];
let b: Vec<int> = a.iter().map(|&x| x).collect();
assert!(a == b);
}
#[test]
fn test_all() {
let v: Box<&[int]> = box &[1, 2, 3, 4, 5];
assert!(v.iter().all(|&x| x < 10));
assert!(!v.iter().all(|&x| x % 2 == 0));
assert!(!v.iter().all(|&x| x > 100));
assert!(v.slice(0, 0).iter().all(|_| fail!()));
}
#[test]
fn test_any() {
let v: Box<&[int]> = box &[1, 2, 3, 4, 5];
assert!(v.iter().any(|&x| x < 10));
assert!(v.iter().any(|&x| x % 2 == 0));
assert!(!v.iter().any(|&x| x > 100));
assert!(!v.slice(0, 0).iter().any(|_| fail!()));
}
#[test]
fn test_find() {
let v: &[int] = &[1, 3, 9, 27, 103, 14, 11];
assert_eq!(*v.iter().find(|x| *x & 1 == 0).unwrap(), 14);
assert_eq!(*v.iter().find(|x| *x % 3 == 0).unwrap(), 3);
assert!(v.iter().find(|x| *x % 12 == 0).is_none());
}
#[test]
fn test_position() {
let v = &[1, 3, 9, 27, 103, 14, 11];
assert_eq!(v.iter().position(|x| *x & 1 == 0).unwrap(), 5);
assert_eq!(v.iter().position(|x| *x % 3 == 0).unwrap(), 1);
assert!(v.iter().position(|x| *x % 12 == 0).is_none());
}
#[test]
fn test_count() {
let xs = &[1, 2, 2, 1, 5, 9, 0, 2];
assert_eq!(xs.iter().count(|x| *x == 2), 3);
assert_eq!(xs.iter().count(|x| *x == 5), 1);
assert_eq!(xs.iter().count(|x| *x == 95), 0);
}
#[test]
fn test_max_by() {
let xs: &[int] = &[-3, 0, 1, 5, -10];
assert_eq!(*xs.iter().max_by(|x| x.abs()).unwrap(), -10);
}
#[test]
fn test_min_by() {
let xs: &[int] = &[-3, 0, 1, 5, -10];
assert_eq!(*xs.iter().min_by(|x| x.abs()).unwrap(), 0);
}
#[test]
fn test_by_ref() {
let mut xs = range(0, 10);
// sum the first five values
let partial_sum = xs.by_ref().take(5).fold(0, |a, b| a + b);
assert_eq!(partial_sum, 10);
assert_eq!(xs.next(), Some(5));
}
#[test]
fn test_rev() {
let xs = [2, 4, 6, 8, 10, 12, 14, 16];
let mut it = xs.iter();
it.next();
it.next();
assert!(it.rev().map(|&x| x).collect::<Vec<int>>() ==
vec![16, 14, 12, 10, 8, 6]);
}
#[test]
fn test_double_ended_map() {
let xs = [1, 2, 3, 4, 5, 6];
let mut it = xs.iter().map(|&x| x * -1);
assert_eq!(it.next(), Some(-1));
assert_eq!(it.next(), Some(-2));
assert_eq!(it.next_back(), Some(-6));
assert_eq!(it.next_back(), Some(-5));
assert_eq!(it.next(), Some(-3));
assert_eq!(it.next_back(), Some(-4));
assert_eq!(it.next(), None);
}
#[test]
fn test_double_ended_enumerate() {
let xs = [1, 2, 3, 4, 5, 6];
let mut it = xs.iter().map(|&x| x).enumerate();
assert_eq!(it.next(), Some((0, 1)));
assert_eq!(it.next(), Some((1, 2)));
assert_eq!(it.next_back(), Some((5, 6)));
assert_eq!(it.next_back(), Some((4, 5)));
assert_eq!(it.next_back(), Some((3, 4)));
assert_eq!(it.next_back(), Some((2, 3)));
assert_eq!(it.next(), None);
}
#[test]
fn test_double_ended_zip() {
let xs = [1, 2, 3, 4, 5, 6];
let ys = [1, 2, 3, 7];
let a = xs.iter().map(|&x| x);
let b = ys.iter().map(|&x| x);
let mut it = a.zip(b);
assert_eq!(it.next(), Some((1, 1)));
assert_eq!(it.next(), Some((2, 2)));
assert_eq!(it.next_back(), Some((4, 7)));
assert_eq!(it.next_back(), Some((3, 3)));
assert_eq!(it.next(), None);
}
#[test]
fn test_double_ended_filter() {
let xs = [1, 2, 3, 4, 5, 6];
let mut it = xs.iter().filter(|&x| *x & 1 == 0);
assert_eq!(it.next_back().unwrap(), &6);
assert_eq!(it.next_back().unwrap(), &4);
assert_eq!(it.next().unwrap(), &2);
assert_eq!(it.next_back(), None);
}
#[test]
fn test_double_ended_filter_map() {
let xs = [1, 2, 3, 4, 5, 6];
let mut it = xs.iter().filter_map(|&x| if x & 1 == 0 { Some(x * 2) } else { None });
assert_eq!(it.next_back().unwrap(), 12);
assert_eq!(it.next_back().unwrap(), 8);
assert_eq!(it.next().unwrap(), 4);
assert_eq!(it.next_back(), None);
}
#[test]
fn test_double_ended_chain() {
let xs = [1, 2, 3, 4, 5];
let ys = box [7, 9, 11];
let mut it = xs.iter().chain(ys.iter()).rev();
assert_eq!(it.next().unwrap(), &11)
assert_eq!(it.next().unwrap(), &9)
assert_eq!(it.next_back().unwrap(), &1)
assert_eq!(it.next_back().unwrap(), &2)
assert_eq!(it.next_back().unwrap(), &3)
assert_eq!(it.next_back().unwrap(), &4)
assert_eq!(it.next_back().unwrap(), &5)
assert_eq!(it.next_back().unwrap(), &7)
assert_eq!(it.next_back(), None)
}
#[test]
fn test_rposition() {
fn f(xy: &(int, char)) -> bool { let (_x, y) = *xy; y == 'b' }
fn g(xy: &(int, char)) -> bool { let (_x, y) = *xy; y == 'd' }
let v = box [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'b')];
assert_eq!(v.iter().rposition(f), Some(3u));
assert!(v.iter().rposition(g).is_none());
}
#[test]
#[should_fail]
fn test_rposition_fail() {
let v = [(box 0, @0), (box 0, @0), (box 0, @0), (box 0, @0)];
let mut i = 0;
v.iter().rposition(|_elt| {
if i == 2 {
fail!()
}
i += 1;
false
});
}
#[cfg(test)]
fn check_randacc_iter<A: Eq, T: Clone + RandomAccessIterator<A>>(a: T, len: uint)
{
let mut b = a.clone();
assert_eq!(len, b.indexable());
let mut n = 0;
for (i, elt) in a.enumerate() {
assert!(Some(elt) == b.idx(i));
n += 1;
}
assert_eq!(n, len);
assert!(None == b.idx(n));
// call recursively to check after picking off an element
if len > 0 {
b.next();
check_randacc_iter(b, len-1);
}
}
#[test]
fn test_double_ended_flat_map() {
let u = [0u,1];
let v = [5,6,7,8];
let mut it = u.iter().flat_map(|x| v.slice(*x, v.len()).iter());
assert_eq!(it.next_back().unwrap(), &8);
assert_eq!(it.next().unwrap(), &5);
assert_eq!(it.next_back().unwrap(), &7);
assert_eq!(it.next_back().unwrap(), &6);
assert_eq!(it.next_back().unwrap(), &8);
assert_eq!(it.next().unwrap(), &6);
assert_eq!(it.next_back().unwrap(), &7);
assert_eq!(it.next_back(), None);
assert_eq!(it.next(), None);
assert_eq!(it.next_back(), None);
}
#[test]
fn test_random_access_chain() {
let xs = [1, 2, 3, 4, 5];
let ys = box [7, 9, 11];
let mut it = xs.iter().chain(ys.iter());
assert_eq!(it.idx(0).unwrap(), &1);
assert_eq!(it.idx(5).unwrap(), &7);
assert_eq!(it.idx(7).unwrap(), &11);
assert!(it.idx(8).is_none());
it.next();
it.next();
it.next_back();
assert_eq!(it.idx(0).unwrap(), &3);
assert_eq!(it.idx(4).unwrap(), &9);
assert!(it.idx(6).is_none());
check_randacc_iter(it, xs.len() + ys.len() - 3);
}
#[test]
fn test_random_access_enumerate() {
let xs = [1, 2, 3, 4, 5];
check_randacc_iter(xs.iter().enumerate(), xs.len());
}
#[test]
fn test_random_access_rev() {
let xs = [1, 2, 3, 4, 5];
check_randacc_iter(xs.iter().rev(), xs.len());
let mut it = xs.iter().rev();
it.next();
it.next_back();
it.next();
check_randacc_iter(it, xs.len() - 3);
}
#[test]
fn test_random_access_zip() {
let xs = [1, 2, 3, 4, 5];
let ys = [7, 9, 11];
check_randacc_iter(xs.iter().zip(ys.iter()), cmp::min(xs.len(), ys.len()));
}
#[test]
fn test_random_access_take() {
let xs = [1, 2, 3, 4, 5];
let empty: &[int] = [];
check_randacc_iter(xs.iter().take(3), 3);
check_randacc_iter(xs.iter().take(20), xs.len());
check_randacc_iter(xs.iter().take(0), 0);
check_randacc_iter(empty.iter().take(2), 0);
}
#[test]
fn test_random_access_skip() {
let xs = [1, 2, 3, 4, 5];
let empty: &[int] = [];
check_randacc_iter(xs.iter().skip(2), xs.len() - 2);
check_randacc_iter(empty.iter().skip(2), 0);
}
#[test]
fn test_random_access_inspect() {
let xs = [1, 2, 3, 4, 5];
// test .map and .inspect that don't implement Clone
let mut it = xs.iter().inspect(|_| {});
assert_eq!(xs.len(), it.indexable());
for (i, elt) in xs.iter().enumerate() {
assert_eq!(Some(elt), it.idx(i));
}
}
#[test]
fn test_random_access_map() {
let xs = [1, 2, 3, 4, 5];
let mut it = xs.iter().map(|x| *x);
assert_eq!(xs.len(), it.indexable());
for (i, elt) in xs.iter().enumerate() {
assert_eq!(Some(*elt), it.idx(i));
}
}
#[test]
fn test_random_access_cycle() {
let xs = [1, 2, 3, 4, 5];
let empty: &[int] = [];
check_randacc_iter(xs.iter().cycle().take(27), 27);
check_randacc_iter(empty.iter().cycle(), 0);
}
#[test]
fn test_double_ended_range() {
assert!(range(11i, 14).rev().collect::<Vec<int>>() == vec![13i, 12, 11]);
for _ in range(10i, 0).rev() {
fail!("unreachable");
}
assert!(range(11u, 14).rev().collect::<Vec<uint>>() == vec![13u, 12, 11]);
for _ in range(10u, 0).rev() {
fail!("unreachable");
}
}
#[test]
fn test_range() {
/// A mock type to check Range when ToPrimitive returns None
struct Foo;
impl ToPrimitive for Foo {
fn to_i64(&self) -> Option<i64> { None }
fn to_u64(&self) -> Option<u64> { None }
}
impl Add<Foo, Foo> for Foo {
fn add(&self, _: &Foo) -> Foo {
Foo
}
}
impl Eq for Foo {
fn eq(&self, _: &Foo) -> bool {
true
}
}
impl Ord for Foo {
fn lt(&self, _: &Foo) -> bool {
false
}
}
impl Clone for Foo {
fn clone(&self) -> Foo {
Foo
}
}
impl Mul<Foo, Foo> for Foo {
fn mul(&self, _: &Foo) -> Foo {
Foo
}
}
impl num::One for Foo {
fn one() -> Foo {
Foo
}
}
assert!(range(0i, 5).collect::<Vec<int>>() == vec![0i, 1, 2, 3, 4]);
assert!(range(-10i, -1).collect::<Vec<int>>() ==
vec![-10, -9, -8, -7, -6, -5, -4, -3, -2]);
assert!(range(0i, 5).rev().collect::<Vec<int>>() == vec![4, 3, 2, 1, 0]);
assert_eq!(range(200, -5).len(), 0);
assert_eq!(range(200, -5).rev().len(), 0);
assert_eq!(range(200, 200).len(), 0);
assert_eq!(range(200, 200).rev().len(), 0);
assert_eq!(range(0i, 100).size_hint(), (100, Some(100)));
// this test is only meaningful when sizeof uint < sizeof u64
assert_eq!(range(uint::MAX - 1, uint::MAX).size_hint(), (1, Some(1)));
assert_eq!(range(-10i, -1).size_hint(), (9, Some(9)));
assert_eq!(range(Foo, Foo).size_hint(), (0, None));
}
#[test]
fn test_range_inclusive() {
assert!(range_inclusive(0i, 5).collect::<Vec<int>>() ==
vec![0i, 1, 2, 3, 4, 5]);
assert!(range_inclusive(0i, 5).rev().collect::<Vec<int>>() ==
vec![5i, 4, 3, 2, 1, 0]);
assert_eq!(range_inclusive(200, -5).len(), 0);
assert_eq!(range_inclusive(200, -5).rev().len(), 0);
assert!(range_inclusive(200, 200).collect::<Vec<int>>() == vec![200]);
assert!(range_inclusive(200, 200).rev().collect::<Vec<int>>() == vec![200]);
}
#[test]
fn test_range_step() {
assert!(range_step(0i, 20, 5).collect::<Vec<int>>() ==
vec![0, 5, 10, 15]);
assert!(range_step(20i, 0, -5).collect::<Vec<int>>() ==
vec![20, 15, 10, 5]);
assert!(range_step(20i, 0, -6).collect::<Vec<int>>() ==
vec![20, 14, 8, 2]);
assert!(range_step(200u8, 255, 50).collect::<Vec<u8>>() ==
vec![200u8, 250]);
assert!(range_step(200, -5, 1).collect::<Vec<int>>() == vec![]);
assert!(range_step(200, 200, 1).collect::<Vec<int>>() == vec![]);
}
#[test]
fn test_range_step_inclusive() {
assert!(range_step_inclusive(0i, 20, 5).collect::<Vec<int>>() ==
vec![0, 5, 10, 15, 20]);
assert!(range_step_inclusive(20i, 0, -5).collect::<Vec<int>>() ==
vec![20, 15, 10, 5, 0]);
assert!(range_step_inclusive(20i, 0, -6).collect::<Vec<int>>() ==
vec![20, 14, 8, 2]);
assert!(range_step_inclusive(200u8, 255, 50).collect::<Vec<u8>>() ==
vec![200u8, 250]);
assert!(range_step_inclusive(200, -5, 1).collect::<Vec<int>>() ==
vec![]);
assert!(range_step_inclusive(200, 200, 1).collect::<Vec<int>>() ==
vec![200]);
}
#[test]
fn test_reverse() {
let mut ys = [1, 2, 3, 4, 5];
ys.mut_iter().reverse_();
assert!(ys == [5, 4, 3, 2, 1]);
}
#[test]
fn test_peekable_is_empty() {
let a = [1];
let mut it = a.iter().peekable();
assert!( !it.is_empty() );
it.next();
assert!( it.is_empty() );
}
#[test]
fn test_min_max() {
let v: [int, ..0] = [];
assert_eq!(v.iter().min_max(), NoElements);
let v = [1i];
assert!(v.iter().min_max() == OneElement(&1));
let v = [1i, 2, 3, 4, 5];
assert!(v.iter().min_max() == MinMax(&1, &5));
let v = [1i, 2, 3, 4, 5, 6];
assert!(v.iter().min_max() == MinMax(&1, &6));
let v = [1i, 1, 1, 1];
assert!(v.iter().min_max() == MinMax(&1, &1));
}
#[test]
fn test_MinMaxResult() {
let r: MinMaxResult<int> = NoElements;
assert_eq!(r.into_option(), None)
let r = OneElement(1);
assert_eq!(r.into_option(), Some((1,1)));
let r = MinMax(1,2);
assert_eq!(r.into_option(), Some((1,2)));
}
}<|fim▁end|> | self.n = 0;
return None
} |
<|file_name|>grade_java.py<|end_file_name|><|fim▁begin|>import config, json, cgi, sys, Websheet, re, os
def grade(reference_solution, student_solution, translate_line, websheet, student):
if not re.match(r"^\w+$", websheet.classname):
return ("Internal Error (Compiling)", "Invalid overridden classname <tt>" + websheet.classname + " </tt>")
dump = {
"reference." + websheet.classname : reference_solution,
"student." + websheet.classname : student_solution[1],
"tester." + websheet.classname : websheet.make_tester()
}
# print(student_solution[1])
# print(reference_solution)
# print(websheet.make_tester())
for clazz in ["Grader", "Options", "Utils"]:
dump["websheets."+clazz] = "".join(open("grade_java_files/"+clazz+".java"))
for dep in websheet.dependencies:
depws = Websheet.Websheet.from_name(dep)
if depws == None:
return ("Internal Error", "Dependent websheet " + dep + " does not exist");
submission = config.load_submission(student, dep, True)
if submission == False:
return("Dependency Error",
"<div class='dependency-error'><i>Dependency error</i>: " +
"You need to successfully complete the <a href='javascript:websheets.load(\""+dep+"\")'><tt>"+dep+"</tt></a> websheet first (while logged in).</div>") # error text
submission = [{'code': x, 'from': {'line': 0, 'ch':0}, 'to': {'line': 0, 'ch': 0}} for x in submission]
dump["student."+dep] = depws.combine_with_template(submission, "student")[1]
dump["reference."+dep] = depws.get_reference_solution("reference")
compileRun = config.run_java(["traceprinter/ramtools/CompileToBytes"], json.dumps(dump))
compileResult = compileRun.stdout
if (compileResult==""):
return ("Internal Error (Compiling)", "<pre>\n" +
cgi.escape(compileRun.stderr) +
"</pre>"+"<!--"+compileRun._toString()+"-->")
compileObj = json.loads(compileResult)
# print(compileObj['status'])
if compileObj['status'] == 'Internal Error':
return ("Internal Error (Compiling)", "<pre>\n" +
cgi.escape(compileObj["errmsg"]) +
"</pre>")
elif compileObj['status'] == 'Compile-time Error':
errorObj = compileObj['error']
if errorObj['filename'] == ("student." + websheet.classname + ".java"):
result = "Syntax error (could not compile):"
result += "<br>"
result += '<tt>'+errorObj['filename'].split('.')[-2]+'.java</tt>, line '
result += str(translate_line(errorObj['row'])) + ':'
#result += str(errorObj['row']) + ':'
result += "<pre>\n"
#remove the safeexec bits
result += cgi.escape(errorObj["errmsg"]
.replace("stdlibpack.", "")
.replace("student.", "")
)
result += "</pre>"
return ("Syntax Error", result)
else:
return("Internal Error (Compiling reference solution and testing suite)",
'<b>File: </b><tt>'+errorObj['filename']+'</tt><br><b>Line number: '
+str(errorObj['row'])+"</b><pre>"
+errorObj['errmsg']+":\n"+dump[errorObj['filename'][:-5]].split("\n")[errorObj['row']-1]+"</pre>")<|fim▁hole|> #print(compileResult)
# prefetch all urls, pass them to the grader on stdin
compileObj["stdin"] = json.dumps({
"fetched_urls":websheet.prefetch_urls(True)
})
compileResult = json.dumps(compileObj)
runUser = config.run_java(["traceprinter/ramtools/RAMRun", "tester." + websheet.classname], compileResult)
#runUser = config.run_java("tester." + websheet.classname + " " + student)
#print(runUser.stdout)
RAMRunError = runUser.stdout.startswith("Error")
RAMRunErrmsg = runUser.stdout[:runUser.stdout.index('\n')]
runUser.stdout = runUser.stdout[runUser.stdout.index('\n')+1:]
#print(runUser.stdout)
#print(runUser.stderr)
if runUser.returncode != 0 or runUser.stdout.startswith("Time Limit Exceeded"):
errmsg = runUser.stderr.split('\n')[0]
result = runUser.stdout
result += "<div class='safeexec'>Crashed! The grader reported "
result += "<code>"
result += cgi.escape(errmsg)
result += "</code>"
result += "</div>"
result += "<!--" + runUser.stderr + "-->"
return ("Sandbox Limit", result)
if RAMRunError:
result += "<div class='safeexec'>Could not execute! "
result += "<code>"
result += cgi.escape(RAMRunErrmsg)
result += "</code>"
result += "</div>"
return ("Internal Error (RAMRun)", result)
runtimeOutput = re.sub(
re.compile("(at|from) line (\d+) "),
lambda match: match.group(1)+" line " + translate_line(match.group(2)) + " ",
runUser.stdout)
#print(runtimeOutput)
def ssf(s, t, u): # substring from of s from after t to before u
if t not in s: raise ValueError("Can't ssf("+s+","+t+","+u+")")
s = s[s.index(t)+len(t) : ]
return s[ : s.index(u)]
if "<div class='error'>Runtime error:" in runtimeOutput:
category = "Runtime Error"
errmsg = ssf(runtimeOutput[runtimeOutput.index("<div class='error'>Runtime error:"):], "<pre >", "\n")
elif "<div class='all-passed'>" in runtimeOutput:
category = "Passed"
epilogue = websheet.epilogue
else:
category = "Failed Tests"
if "<div class='error'>" in runtimeOutput:
errmsg = ssf(runtimeOutput, "<div class='error'>", '</div>')
else:
return ("Internal Error", "<b>stderr</b><pre>" + runUser.stderr + "</pre><b>stdout</b><br>" + runUser.stdout)
return (category, runtimeOutput)<|fim▁end|> | |
<|file_name|>server.js<|end_file_name|><|fim▁begin|>'use strict'
const assert = require('assert')
const http = require('http')
const https = require('https')
const { kState, kOptions } = require('./symbols')
const {
codes: { FST_ERR_HTTP2_INVALID_VERSION }
} = require('./errors')
function createServer (options, httpHandler) {
assert(options, 'Missing options')
assert(httpHandler, 'Missing http handler')
var server = null
if (options.serverFactory) {
server = options.serverFactory(httpHandler, options)
} else if (options.https) {
if (options.http2) {
server = http2().createSecureServer(options.https, httpHandler)
} else {
server = https.createServer(options.https, httpHandler)
}
} else if (options.http2) {
server = http2().createServer(httpHandler)
server.on('session', sessionTimeout(options.http2SessionTimeout))
} else {
server = http.createServer(httpHandler)
}
return { server, listen }
// `this` is the Fastify object
function listen () {
const normalizeListenArgs = (args) => {
if (args.length === 0) {
return { port: 0, host: 'localhost' }
}
const cb = typeof args[args.length - 1] === 'function' ? args.pop() : undefined
const options = { cb: cb }
const firstArg = args[0]
const argsLength = args.length
const lastArg = args[argsLength - 1]
/* Deal with listen (options) || (handle[, backlog]) */
if (typeof firstArg === 'object' && firstArg !== null) {
options.backlog = argsLength > 1 ? lastArg : undefined
Object.assign(options, firstArg)
} else if (typeof firstArg === 'string' && isNaN(firstArg)) {
/* Deal with listen (pipe[, backlog]) */
options.path = firstArg
options.backlog = argsLength > 1 ? lastArg : undefined
} else {
/* Deal with listen ([port[, host[, backlog]]]) */
options.port = argsLength >= 1 && firstArg ? firstArg : 0
// This will listen to what localhost is.
// It can be 127.0.0.1 or ::1, depending on the operating system.
// Fixes https://github.com/fastify/fastify/issues/1022.
options.host = argsLength >= 2 && args[1] ? args[1] : 'localhost'
options.backlog = argsLength >= 3 ? args[2] : undefined
}
return options
}
const listenOptions = normalizeListenArgs(Array.from(arguments))
const cb = listenOptions.cb
const wrap = err => {
server.removeListener('error', wrap)
if (!err) {
const address = logServerAddress()
cb(null, address)
} else {
this[kState].listening = false
cb(err, null)
}
}
const listenPromise = (listenOptions) => {
if (this[kState].listening) {
return Promise.reject(new Error('Fastify is already listening'))
}
return this.ready().then(() => {
var errEventHandler
var errEvent = new Promise((resolve, reject) => {
errEventHandler = (err) => {
this[kState].listening = false
reject(err)
}
server.once('error', errEventHandler)
})
var listen = new Promise((resolve, reject) => {
server.listen(listenOptions, () => {
server.removeListener('error', errEventHandler)
resolve(logServerAddress())
})
// we set it afterwards because listen can throw
this[kState].listening = true
})
return Promise.race([
errEvent, // e.g invalid port range error is always emitted before the server listening
listen
])
})
}
const logServerAddress = () => {<|fim▁hole|> var address = server.address()
const isUnixSocket = typeof address === 'string'
if (!isUnixSocket) {
if (address.address.indexOf(':') === -1) {
address = address.address + ':' + address.port
} else {
address = '[' + address.address + ']:' + address.port
}
}
address = (isUnixSocket ? '' : ('http' + (this[kOptions].https ? 's' : '') + '://')) + address
this.log.info('Server listening at ' + address)
return address
}
if (cb === undefined) return listenPromise(listenOptions)
this.ready(err => {
if (err != null) return cb(err)
if (this[kState].listening) {
return cb(new Error('Fastify is already listening'), null)
}
server.once('error', wrap)
server.listen(listenOptions, wrap)
this[kState].listening = true
})
}
}
function http2 () {
try {
return require('http2')
} catch (err) {
throw new FST_ERR_HTTP2_INVALID_VERSION()
}
}
function sessionTimeout (timeout) {
return function (session) {
session.setTimeout(timeout, close)
}
}
function close () {
this.close()
}
module.exports = { createServer }<|fim▁end|> | |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""Support for RainMachine devices."""
import logging
from datetime import timedelta
import voluptuous as vol
from homeassistant.config_entries import SOURCE_IMPORT
from homeassistant.const import (
ATTR_ATTRIBUTION, CONF_BINARY_SENSORS, CONF_IP_ADDRESS, CONF_PASSWORD,
CONF_PORT, CONF_SCAN_INTERVAL, CONF_SENSORS, CONF_SSL,
CONF_MONITORED_CONDITIONS, CONF_SWITCHES)
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers import aiohttp_client, config_validation as cv
from homeassistant.helpers.dispatcher import async_dispatcher_send
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.event import async_track_time_interval
from .config_flow import configured_instances
from .const import (
DATA_CLIENT, DEFAULT_PORT, DEFAULT_SCAN_INTERVAL, DEFAULT_SSL, DOMAIN)
REQUIREMENTS = ['regenmaschine==1.2.0']
_LOGGER = logging.getLogger(__name__)
DATA_LISTENER = 'listener'
PROGRAM_UPDATE_TOPIC = '{0}_program_update'.format(DOMAIN)
SENSOR_UPDATE_TOPIC = '{0}_data_update'.format(DOMAIN)
ZONE_UPDATE_TOPIC = '{0}_zone_update'.format(DOMAIN)
CONF_CONTROLLERS = 'controllers'
CONF_PROGRAM_ID = 'program_id'
CONF_SECONDS = 'seconds'
CONF_ZONE_ID = 'zone_id'
CONF_ZONE_RUN_TIME = 'zone_run_time'
DEFAULT_ATTRIBUTION = 'Data provided by Green Electronics LLC'
DEFAULT_ICON = 'mdi:water'
DEFAULT_ZONE_RUN = 60 * 10
TYPE_FREEZE = 'freeze'
TYPE_FREEZE_PROTECTION = 'freeze_protection'
TYPE_FREEZE_TEMP = 'freeze_protect_temp'
TYPE_HOT_DAYS = 'extra_water_on_hot_days'
TYPE_HOURLY = 'hourly'
TYPE_MONTH = 'month'
TYPE_RAINDELAY = 'raindelay'
TYPE_RAINSENSOR = 'rainsensor'
TYPE_WEEKDAY = 'weekday'
BINARY_SENSORS = {
TYPE_FREEZE: ('Freeze Restrictions', 'mdi:cancel'),
TYPE_FREEZE_PROTECTION: ('Freeze Protection', 'mdi:weather-snowy'),
TYPE_HOT_DAYS: ('Extra Water on Hot Days', 'mdi:thermometer-lines'),
TYPE_HOURLY: ('Hourly Restrictions', 'mdi:cancel'),
TYPE_MONTH: ('Month Restrictions', 'mdi:cancel'),
TYPE_RAINDELAY: ('Rain Delay Restrictions', 'mdi:cancel'),
TYPE_RAINSENSOR: ('Rain Sensor Restrictions', 'mdi:cancel'),
TYPE_WEEKDAY: ('Weekday Restrictions', 'mdi:cancel'),
}
SENSORS = {
TYPE_FREEZE_TEMP: ('Freeze Protect Temperature', 'mdi:thermometer', '°C'),
}
BINARY_SENSOR_SCHEMA = vol.Schema({
vol.Optional(CONF_MONITORED_CONDITIONS, default=list(BINARY_SENSORS)):
vol.All(cv.ensure_list, [vol.In(BINARY_SENSORS)])
})
SENSOR_SCHEMA = vol.Schema({
vol.Optional(CONF_MONITORED_CONDITIONS, default=list(SENSORS)):
vol.All(cv.ensure_list, [vol.In(SENSORS)])
})
SERVICE_PAUSE_WATERING = vol.Schema({
vol.Required(CONF_SECONDS): cv.positive_int,
})
SERVICE_START_PROGRAM_SCHEMA = vol.Schema({
vol.Required(CONF_PROGRAM_ID): cv.positive_int,
})
SERVICE_START_ZONE_SCHEMA = vol.Schema({
vol.Required(CONF_ZONE_ID): cv.positive_int,
vol.Optional(CONF_ZONE_RUN_TIME, default=DEFAULT_ZONE_RUN):
cv.positive_int,
})
SERVICE_STOP_PROGRAM_SCHEMA = vol.Schema({
vol.Required(CONF_PROGRAM_ID): cv.positive_int,
})
SERVICE_STOP_ZONE_SCHEMA = vol.Schema({
vol.Required(CONF_ZONE_ID): cv.positive_int,
})
SWITCH_SCHEMA = vol.Schema({vol.Optional(CONF_ZONE_RUN_TIME): cv.positive_int})
CONTROLLER_SCHEMA = vol.Schema({
vol.Required(CONF_IP_ADDRESS): cv.string,
vol.Required(CONF_PASSWORD): cv.string,
vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port,
vol.Optional(CONF_SSL, default=DEFAULT_SSL): cv.boolean,
vol.Optional(CONF_SCAN_INTERVAL, default=DEFAULT_SCAN_INTERVAL):
cv.time_period,
vol.Optional(CONF_BINARY_SENSORS, default={}): BINARY_SENSOR_SCHEMA,
vol.Optional(CONF_SENSORS, default={}): SENSOR_SCHEMA,
vol.Optional(CONF_SWITCHES, default={}): SWITCH_SCHEMA,
})
CONFIG_SCHEMA = vol.Schema({
DOMAIN: vol.Schema({
vol.Required(CONF_CONTROLLERS):
vol.All(cv.ensure_list, [CONTROLLER_SCHEMA]),
}),
}, extra=vol.ALLOW_EXTRA)
async def async_setup(hass, config):
"""Set up the RainMachine component."""
hass.data[DOMAIN] = {}
hass.data[DOMAIN][DATA_CLIENT] = {}
hass.data[DOMAIN][DATA_LISTENER] = {}
if DOMAIN not in config:
return True
conf = config[DOMAIN]
for controller in conf[CONF_CONTROLLERS]:
if controller[CONF_IP_ADDRESS] in configured_instances(hass):
continue
hass.async_create_task(
hass.config_entries.flow.async_init(
DOMAIN,
context={'source': SOURCE_IMPORT},
data=controller))
return True
async def async_setup_entry(hass, config_entry):
"""Set up RainMachine as config entry."""
from regenmaschine import login
from regenmaschine.errors import RainMachineError
websession = aiohttp_client.async_get_clientsession(hass)
try:
client = await login(
config_entry.data[CONF_IP_ADDRESS],
config_entry.data[CONF_PASSWORD],
websession,
port=config_entry.data[CONF_PORT],
ssl=config_entry.data[CONF_SSL])
rainmachine = RainMachine(
client,
config_entry.data.get(CONF_BINARY_SENSORS, {}).get(
CONF_MONITORED_CONDITIONS, list(BINARY_SENSORS)),
config_entry.data.get(CONF_SENSORS, {}).get(
CONF_MONITORED_CONDITIONS, list(SENSORS)),
config_entry.data.get(CONF_ZONE_RUN_TIME, DEFAULT_ZONE_RUN))
await rainmachine.async_update()
except RainMachineError as err:
_LOGGER.error('An error occurred: %s', err)
raise ConfigEntryNotReady
hass.data[DOMAIN][DATA_CLIENT][config_entry.entry_id] = rainmachine
for component in ('binary_sensor', 'sensor', 'switch'):
hass.async_create_task(
hass.config_entries.async_forward_entry_setup(
config_entry, component))
async def refresh(event_time):
"""Refresh RainMachine sensor data."""
_LOGGER.debug('Updating RainMachine sensor data')
await rainmachine.async_update()
async_dispatcher_send(hass, SENSOR_UPDATE_TOPIC)
hass.data[DOMAIN][DATA_LISTENER][
config_entry.entry_id] = async_track_time_interval(
hass,
refresh,
timedelta(seconds=config_entry.data[CONF_SCAN_INTERVAL]))
async def pause_watering(service):
"""Pause watering for a set number of seconds."""
await rainmachine.client.watering.pause_all(service.data[CONF_SECONDS])
async_dispatcher_send(hass, PROGRAM_UPDATE_TOPIC)
async def start_program(service):
"""Start a particular program."""
await rainmachine.client.programs.start(service.data[CONF_PROGRAM_ID])
async_dispatcher_send(hass, PROGRAM_UPDATE_TOPIC)
async def start_zone(service):
"""Start a particular zone for a certain amount of time."""
await rainmachine.client.zones.start(
service.data[CONF_ZONE_ID], service.data[CONF_ZONE_RUN_TIME])
async_dispatcher_send(hass, ZONE_UPDATE_TOPIC)
async def stop_all(service):
"""Stop all watering."""
await rainmachine.client.watering.stop_all()
async_dispatcher_send(hass, PROGRAM_UPDATE_TOPIC)
async def stop_program(service):
"""Stop a program."""
await rainmachine.client.programs.stop(service.data[CONF_PROGRAM_ID])
async_dispatcher_send(hass, PROGRAM_UPDATE_TOPIC)
async def stop_zone(service):
"""Stop a zone."""
await rainmachine.client.zones.stop(service.data[CONF_ZONE_ID])
async_dispatcher_send(hass, ZONE_UPDATE_TOPIC)
async def unpause_watering(service):
"""Unpause watering."""
await rainmachine.client.watering.unpause_all()
async_dispatcher_send(hass, PROGRAM_UPDATE_TOPIC)
for service, method, schema in [
('pause_watering', pause_watering, SERVICE_PAUSE_WATERING),
('start_program', start_program, SERVICE_START_PROGRAM_SCHEMA),
('start_zone', start_zone, SERVICE_START_ZONE_SCHEMA),
('stop_all', stop_all, {}),
('stop_program', stop_program, SERVICE_STOP_PROGRAM_SCHEMA),
('stop_zone', stop_zone, SERVICE_STOP_ZONE_SCHEMA),
('unpause_watering', unpause_watering, {}),
]:
hass.services.async_register(DOMAIN, service, method, schema=schema)
return True
<|fim▁hole|> remove_listener = hass.data[DOMAIN][DATA_LISTENER].pop(
config_entry.entry_id)
remove_listener()
for component in ('binary_sensor', 'sensor', 'switch'):
await hass.config_entries.async_forward_entry_unload(
config_entry, component)
return True
class RainMachine:
"""Define a generic RainMachine object."""
def __init__(
self, client, binary_sensor_conditions, sensor_conditions,
default_zone_runtime):
"""Initialize."""
self.binary_sensor_conditions = binary_sensor_conditions
self.client = client
self.default_zone_runtime = default_zone_runtime
self.device_mac = self.client.mac
self.restrictions = {}
self.sensor_conditions = sensor_conditions
async def async_update(self):
"""Update sensor/binary sensor data."""
self.restrictions.update({
'current': await self.client.restrictions.current(),
'global': await self.client.restrictions.universal()
})
class RainMachineEntity(Entity):
"""Define a generic RainMachine entity."""
def __init__(self, rainmachine):
"""Initialize."""
self._attrs = {ATTR_ATTRIBUTION: DEFAULT_ATTRIBUTION}
self._dispatcher_handlers = []
self._name = None
self.rainmachine = rainmachine
@property
def device_info(self):
"""Return device registry information for this entity."""
return {
'identifiers': {
(DOMAIN, self.rainmachine.client.mac)
},
'name': self.rainmachine.client.name,
'manufacturer': 'RainMachine',
'model': 'Version {0} (API: {1})'.format(
self.rainmachine.client.hardware_version,
self.rainmachine.client.api_version),
'sw_version': self.rainmachine.client.software_version,
}
@property
def device_state_attributes(self) -> dict:
"""Return the state attributes."""
return self._attrs
@property
def name(self) -> str:
"""Return the name of the entity."""
return self._name
async def async_will_remove_from_hass(self):
"""Disconnect dispatcher listener when removed."""
for handler in self._dispatcher_handlers:
handler()<|fim▁end|> | async def async_unload_entry(hass, config_entry):
"""Unload an OpenUV config entry."""
hass.data[DOMAIN][DATA_CLIENT].pop(config_entry.entry_id)
|
<|file_name|>GoogleSearchParameters.ts<|end_file_name|><|fim▁begin|>const querystring = require("querystring");
import IRequestParameters from "./IRequestParameters";
export default class GoogleSearchParameters implements IRequestParameters {
query: string;
private start: number;
constructor(searchQuery: string) {
this.query = searchQuery;
this.start = 0;
}
nextPage(): void {
this.start += 10;
}
goToPage(i: number): void {
if (i >= 0)
this.start = i * 10;
// raise error in case i is less than 0;
}
getUrl(): string {
const url = "https://www.google.co.in/search?q=" + this.query + "&start=" + this.start;
return url;
}
getExtraParameters(): any {<|fim▁hole|><|fim▁end|> | return undefined;
}
} |
<|file_name|>forms.py<|end_file_name|><|fim▁begin|>from flask.ext.wtf import Form
from wtforms import StringField, BooleanField, TextAreaField, SelectField, FileField, IntegerField
from wtforms.validators import DataRequired, regexp, NumberRange
from wtforms.ext.sqlalchemy.fields import QuerySelectField
from picture_hunt.models import Team, Task
class TeamForm(Form):
name = StringField('Team Name', validators=[DataRequired()])
note = TextAreaField('Note', validators=[DataRequired()])
class TaskForm(Form):
name = StringField('Task', validators=[DataRequired()])<|fim▁hole|>class UploadForm(Form):
team = SelectField('Team',coerce=int, choices=[(None, 'Make a Team first'),],validators=[NumberRange(min=0, message="Please choose a team first")] )
task = SelectField('Task',coerce=int, choices=[(None, 'Make a Task first'),] ,validators=[NumberRange(min=0, message="Please choose a team first")])
media = FileField('Media File', validators=[DataRequired()])
class SearchForm(Form):
team = QuerySelectField( query_factory=Team.query.all,
get_pk=lambda a: a.id,
get_label=lambda a: a.name,
allow_blank=True,
blank_text="All"
)
task = QuerySelectField( query_factory=Task.query.all,
get_pk=lambda a: a.id,
get_label=lambda a: a.name,
allow_blank=True,
blank_text="All"
)<|fim▁end|> | points = IntegerField('Points', validators=[DataRequired()])
note = TextAreaField('Note', validators=[DataRequired()])
|
<|file_name|>noise_driven_dynamics.py<|end_file_name|><|fim▁begin|>__author__ = 'duarte'
import sys
from preset import *
import numpy as np
"""
spike_noise_input
- standard network setup, driven with noisy, Poissonian input
- quantify and set population state
- run with noise_driven_dynamics in computations
- debug with noise_driven_dynamics script
"""
run = 'local'
data_label = 'example3_population_noisedriven'
def build_parameters(g, nu_x):
# ##################################################################################################################
# System / Kernel Parameters
# ##################################################################################################################
system = dict(
nodes=1,
ppn=16,
mem=64000,
walltime='01-00:00:00',
queue='defqueue',
transient_time=1000.,
sim_time=500.)
kernel_pars = set_kernel_defaults(run_type=run, data_label=data_label, **system)
np.random.seed(kernel_pars['np_seed'])
# ##################################################################################################################
# Neuron, Synapse and Network Parameters
# ##################################################################################################################
N = 10000
nE = 0.8 * N
nI = 0.2 * N
dE = 1.0
dI = 0.8
# Connection probabilities
pEE = 0.1
pEI = 0.2
pIE = 0.1
pII = 0.2
# connection weights
# g = 13.5
wE = 1.2
wI = -g * wE
recurrent_synapses = dict(
connected_populations=[('E', 'E'), ('E', 'I'), ('I', 'E'), ('I', 'I')],
synapse_models=['static_synapse', 'static_synapse', 'static_synapse', 'static_synapse'],
synapse_model_parameters=[{}, {}, {}, {}],
pre_computedW=[None, None, None, None],
weights=[{'distribution': 'normal_clipped', 'mu': wE, 'sigma': 0.5 * wE, 'low': 0.0001, 'high': 10. * wE},
{'distribution': 'normal_clipped', 'mu': wI, 'sigma': np.abs(0.5 * wI), 'low': 10. * wI, 'high': 0.0001},
{'distribution': 'normal_clipped', 'mu': wE, 'sigma': 0.5 * wE, 'low': 0.0001, 'high': 10. * wE},
{'distribution': 'normal_clipped', 'mu': wI, 'sigma': np.abs(0.5 * wI), 'low': 10. * wI, 'high': 0.0001}],
delays=[{'distribution': 'normal_clipped', 'mu': dE, 'sigma': 0.5 * dE, 'low': 0.1, 'high': 10. * dE},
{'distribution': 'normal_clipped', 'mu': dI, 'sigma': 0.5 * dI, 'low': 0.1, 'high': 10. * dI},
{'distribution': 'normal_clipped', 'mu': dE, 'sigma': 0.5 * dE, 'low': 0.1, 'high': 10. * dE},
{'distribution': 'normal_clipped', 'mu': dI, 'sigma': 0.5 * dI, 'low': 0.1, 'high': 10. * dI}],
conn_specs=[{'rule': 'pairwise_bernoulli', 'p': pEE},
{'rule': 'pairwise_bernoulli', 'p': pEI},
{'rule': 'pairwise_bernoulli', 'p': pIE},
{'rule': 'pairwise_bernoulli', 'p': pII}],
syn_specs=[{}, {}, {}, {}])
neuron_pars, net_pars, connection_pars = set_network_defaults(neuron_set=1, N=N, **recurrent_synapses)
net_pars['record_analogs'] = [True, False]
multimeter = rec_device_defaults(device_type='multimeter')
multimeter.update({'record_from': ['V_m', 'g_ex', 'g_in'], 'record_n': 1})
net_pars['analog_device_pars'] = [copy_dict(multimeter, {'label': ''}), {}]
# ######################################################################################################################
# Encoding Parameters
# ######################################################################################################################
# nu_x = 20.
k_x = pEE * nE
w_in = 1.
encoding_pars = set_encoding_defaults(default_set=0)
background_noise = dict(
start=0., stop=sys.float_info.max, origin=0.,
rate=nu_x*k_x, target_population_names=['E', 'I'],
additional_parameters={
'syn_specs': {},
'models': 'static_synapse',
'model_pars': {},
'weight_dist': {'distribution': 'normal_clipped', 'mu': w_in, 'sigma': 0.5*w_in, 'low': 0.0001,
'high': 10.*w_in},
'delay_dist': 0.1})
add_background_noise(encoding_pars, background_noise)
# ##################################################################################################################
# Extra analysis parameters (specific for this experiment)
# ==================================================================================================================
analysis_pars = {
# analysis depth
'depth': 2, # 1: save only summary of data, use only fastest measures
# 2: save all data, use only fastest measures
# 3: save only summary of data, use all available measures
# 4: save all data, use all available measures
'store_activity': False, # [int] - store all population activity in the last n steps of the test
# phase; if set True the entire test phase will be stored;
<|fim▁hole|> 'window_len': 100, # length of sliding time window (for time_resolved analysis)
'time_resolved': False, # perform time-resolved analysis
}
}
# ##################################################################################################################
# RETURN dictionary of Parameters dictionaries
# ==================================================================================================================
return dict([('kernel_pars', kernel_pars),
('neuron_pars', neuron_pars),
('net_pars', net_pars),
('encoding_pars', encoding_pars),
('connection_pars', connection_pars),
('analysis_pars', analysis_pars)])
# ######################################################################################################################
# PARAMETER RANGE declarations
# ======================================================================================================================
parameter_range = {
'g': [11.],
'nu_x': [14.]
}<|fim▁end|> | 'population_activity': {
'time_bin': 1., # bin width for spike counts, fano factors and correlation coefficients
'n_pairs': 500, # number of spike train pairs to consider in correlation coefficient
'tau': 20., # time constant of exponential filter (van Rossum distance) |
<|file_name|>Plugins.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
#
# Plugins.py
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307 USA
from .Plugin import Plugin
class Plugins(list):
def __init__(self):
list.__init__(self)
@property
def length(self):
return len(self)
def __getattr__(self, key):
return self.namedItem(key)
def __getitem__(self, key):
try:
key = int(key)
return self.item(key)
except:
return self.namedItem(key)
def item(self, index):
if index >= self.length:
return Plugin()
<|fim▁hole|> def namedItem(self, name):
index = 0
while index < self.length:
p = self.item(index)
if p['name'].startswith(name):
return p
index += 1
print 'PLUGIN NOT FOUND:', name
return Plugin()
def refresh(self, reloadDocuments = False):
pass<|fim▁end|> | return list.__getitem__(self, index)
|
<|file_name|>test_escala.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python2
# -*- coding: utf-8 -*-
# coding=utf-8<|fim▁hole|>from datetime import datetime
from lib.escala import Escala
import dirs
dirs.DEFAULT_DIR = dirs.TestDir()
class FrameTest(unittest.TestCase):
def setUp(self):
self.escala = Escala('fixtures/escala.xml')
self.dir = dirs.TestDir()
self.maxDiff = None
def tearDown(self):
pass
def test_attributos_voo_1(self):
p_voo = self.escala.escalas[0]
self.assertEqual(p_voo.activity_date, datetime(2013, 3, 1, 11, 36))
self.assertEqual(p_voo.present_location, 'VCP')
self.assertEqual(p_voo.flight_no, '4148')
self.assertEqual(p_voo.origin, 'VCP')
self.assertEqual(p_voo.destination, 'GYN')
self.assertEqual(p_voo.actype, 'E95')
self.assertTrue(p_voo.checkin)
self.assertEqual(p_voo.checkin_time, datetime(2013, 3, 1, 10, 36))
self.assertEqual(p_voo.std, datetime(2013, 3, 1, 13, 13))
self.assertEqual(p_voo.sta, datetime(2013, 3, 1, 11, 36))
self.assertEqual(p_voo.activity_info, 'AD4148')
self.assertFalse(p_voo.duty_design)
def test_attributos_voo_17(self):
p_voo = self.escala.escalas[17]
self.assertEqual(p_voo.activity_date, datetime(2013, 10, 28, 3, 0))
self.assertEqual(p_voo.present_location, 'VCP')
self.assertEqual(p_voo.flight_no, None)
self.assertEqual(p_voo.origin, 'VCP')
self.assertEqual(p_voo.destination, 'VCP')
self.assertEqual(p_voo.activity_info, 'P04')
self.assertEqual(p_voo.actype, None)
self.assertEqual(p_voo.sta, datetime(2013, 10, 28, 3, 0))
self.assertEqual(p_voo.std, datetime(2013, 10, 28, 15, 0))
self.assertFalse(p_voo.checkin)
self.assertEqual(p_voo.checkin_time, None)
self.assertFalse(p_voo.duty_design)
def test_attributos_voo_18(self):
p_voo = self.escala.escalas[18]
self.assertEqual(p_voo.activity_date, datetime(2013, 10, 29, 4, 58))
self.assertEqual(p_voo.present_location, 'VCP')
self.assertEqual(p_voo.flight_no, '4050')
self.assertEqual(p_voo.origin, 'VCP')
self.assertEqual(p_voo.destination, 'FLN')
self.assertEqual(p_voo.activity_info, 'AD4050')
self.assertEqual(p_voo.actype, 'E95')
self.assertEqual(p_voo.sta, datetime(2013, 10, 29, 4, 58))
self.assertEqual(p_voo.std, datetime(2013, 10, 29, 6, 15))
self.assertTrue(p_voo.checkin)
self.assertEqual(p_voo.checkin_time, datetime(2013, 10, 29, 5, 8))
self.assertFalse(p_voo.duty_design)
self.assertEqual(p_voo.horas_de_voo, '1:17')
def test_attributos_quarto_voo(self):
p_voo = self.escala.escalas[25]
self.assertFalse(p_voo.checkin)
self.assertEqual(p_voo.checkin_time, None)
self.assertEqual(p_voo.flight_no, '2872')
self.assertEqual(p_voo.activity_info, 'AD2872')
def test_calculo_horas_voadas(self):
s_horas = {
'h_diurno': '6:40',
'h_noturno': '6:47',
'h_total_voo': '13:27',
'h_faixa2': '0:00',
'h_sobreaviso': '40:00',
'h_reserva': '29:13'
}
self.assertEqual(self.escala.soma_horas(), s_horas)
def test_ics(self):
"""
Check ICS output
"""
escala = Escala('fixtures/escala_ics.xml')
f_result = open(self.dir.get_data_dir() + 'fixtures/escala.ics')
self.assertEqual(escala.ics(), f_result.read())
f_result.close()
def test_csv(self):
"""
Check CSV output
"""
f_result = open(self.dir.get_data_dir() + 'fixtures/escala.csv')
self.assertEqual(self.escala.csv(), f_result.read())
f_result.close()
def main():
unittest.main()
if __name__ == '__main__':
main()<|fim▁end|> |
import unittest |
<|file_name|>common.py<|end_file_name|><|fim▁begin|>import tkinter
FRAME_BORDER = 5
class PageView(object):
__root = None
bd = None
def __init__(self, root=None, main_frame=None):
param = self.params()
if root is None:
# standalone
self.__root = tkinter.Tk()
self.__root.title(param['title'])
self.__root.geometry('%sx%s+%s+%s' % (param['w'],
param['h'],
param['x'],
param['y']
))
else:
# inside
self.__root = root<|fim▁hole|>
if main_frame is None:
# standalone
main_f = tkinter.Frame(master=self.__root, bg='black', bd=self.bd)
main_f.pack(fill='both', expand=True)
else:
# inside
main_f = main_frame
self.make_widgets(main_f)
@property
def root(self):
return self.__root
def close(self):
self.__root.destroy()
self.__root.quit()
# Override
def make_widgets(self, main_frame):
pass
# Override
def params(self):
param = {
'x': 0,
'y': 0,
'w': 500,
'h': 500,
'title': '% Type Prog Title Here %',
}
return param
def mk_scrollable_area(obj, obj_frame, sbars):
obj.grid(row=0, column=0, sticky='NSWE')
if 'y' in sbars:
y_scrollbar = tkinter.ttk.Scrollbar(obj_frame)
y_scrollbar.grid(row=0, column=1, sticky='NS')
y_scrollbar['command'] = obj.yview
obj['yscrollcommand'] = y_scrollbar.set
if 'x' in sbars:
x_scrollbar = tkinter.ttk.Scrollbar(obj_frame, orient='horizontal')
x_scrollbar.grid(row=1, column=0, sticky='WE')
x_scrollbar['command'] = obj.xview
obj['xscrollcommand'] = x_scrollbar.set
obj_frame.columnconfigure(1, 'minsize')
obj_frame.columnconfigure(0, weight=1)
obj_frame.rowconfigure(1, 'minsize')
obj_frame.rowconfigure(0, weight=1)
def mk_listbox(frame, side='top', sbars='y', sel_mode=tkinter.EXTENDED):
BORDER = 0
COLOR = 'grey'
listbox_frame = tkinter.Frame(frame, bg=COLOR, bd=BORDER)
listbox_frame.pack(side=side, fill='both', expand=True)
listbox = tkinter.Listbox(listbox_frame, selectmode=sel_mode)
mk_scrollable_area(listbox, listbox_frame, sbars)
return listbox
def mk_treeview(frame, side='top', sbars='y'):
BORDER = 0
COLOR = 'grey'
treeview_frame = tkinter.Frame(frame, bg=COLOR, bd=BORDER)
treeview_frame.pack(side=side, fill='both', expand=True)
treeview = tkinter.ttk.Treeview(treeview_frame)
mk_scrollable_area(treeview, treeview_frame, sbars)
return treeview<|fim▁end|> |
self.bd = param['bd'] |
<|file_name|>unboxed-closure-sugar-used-on-struct.rs<|end_file_name|><|fim▁begin|>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.<|fim▁hole|>// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test that parentheses form doesn't work with struct types appearing in argument types.
struct Bar<A,R> {
f: A, r: R
}
fn foo(b: Box<Bar()>) {
//~^ ERROR parenthesized parameters may only be used with a trait
}
fn main() { }<|fim▁end|> | //
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or |
<|file_name|>freebase_key_needed_final.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
from json import loads
from pprint import pprint
from sys import argv
import urllib
class FREEBASE_KEY():
'''
please input the api_key here
'''
api_key = 'AIzaSyBWsQpGo34Lk0Qa3wD0kjW5H1Nfb2m5eaM'
def get_city_id(city_name):
query = city_name
service_url = 'https://www.googleapis.com/freebase/v1/search'
params = {
'query': query,
'key': FREEBASE_KEY.api_key,
}
url = service_url + '?' + urllib.urlencode(params)
response = loads(urllib.urlopen(url).read())
return response['result'][0]['id']
"""
This function query the freebase and get the topic id of input city
"""<|fim▁hole|> params = {
'filter': '/location/location',
'key': FREEBASE_KEY.api_key,
}
url = service_url + topic_id + '?' + urllib.urlencode(params)
topic = loads(urllib.urlopen(url).read())
return topic
"""
Notic:
Eden, please note that if you need the attractions, call: get_city_attractions(topic_id)['property']['/location/location/contains']
geo info call: get_city_attractions(topic_id)['/location/location/geolocation']
"""
def get_freebase_info(city_name):
'''
this function is used to extract the exact info we want
'''
freebase_dic = {}
city_data = get_city_attractions(city_name)
# freebase_dic['attractions'] = city_data['property']['/location/location/contains']
return city_data['property']['/location/location/contains']
# freebase_dic['latitude'] = city_data['property']['/location/location/geolocation']['values'][0]['property']['/location/geocode/latitude']['values'][0]['value']
# freebase_dic['longitude'] = city_data['property']['/location/location/geolocation']['values'][0]['property']['/location/geocode/longitude']['values'][0]['value']
# return freebase_dic
def main(location=None):
city_name = location
if not location:
city_name = argv[1]
output = get_freebase_info(city_name)
data = []
for value in output['values']:
data.append( value['text'])
return '<br /> '.join(data).encode('utf-8')
if __name__ == '__main__':
'''
just call the function get_freebase_info(city_name) and input the city_name, here is the sample
'''
print main()<|fim▁end|> | def get_city_attractions(city_name):
topic_id = get_city_id(city_name)
service_url = 'https://www.googleapis.com/freebase/v1/topic' |
<|file_name|>CorpusCreatorTest.java<|end_file_name|><|fim▁begin|>package org.voyanttools.trombone.tool.build;
import static org.junit.Assert.*;
import java.io.IOException;
import org.junit.Test;
import org.voyanttools.trombone.model.Corpus;
import org.voyanttools.trombone.storage.Storage;
import org.voyanttools.trombone.tool.build.RealCorpusCreator;
import org.voyanttools.trombone.util.FlexibleParameters;
import org.voyanttools.trombone.util.TestHelper;
import com.thoughtworks.xstream.XStream;
public class CorpusCreatorTest {
@Test
public void testSteps() throws IOException {
FlexibleParameters parameters = new FlexibleParameters(new String[]{"string=test","file="+TestHelper.getResource("formats/chars.rtf"),"steps=1"});
Storage storage = TestHelper.getDefaultTestStorage();
String nextStep;
// do a first pass one step at a time and make sure we get the right next steps
// store
RealCorpusCreator creator = new RealCorpusCreator(storage, parameters);
creator.run();
nextStep = creator.getNextCorpusCreatorStep();
assertEquals("expand", nextStep);
String storedStoredId = creator.getStoredId();
// expand
parameters.setParameter("nextCorpusCreatorStep", nextStep);
parameters.setParameter("storedId", storedStoredId);
creator.run();
nextStep = creator.getNextCorpusCreatorStep();
assertEquals("extract", nextStep);
String expandedStoredId = creator.getStoredId();
// extract
parameters.setParameter("nextCorpusCreatorStep", nextStep);
parameters.setParameter("storedId", expandedStoredId);
creator.run();
nextStep = creator.getNextCorpusCreatorStep();
assertEquals("index", nextStep);
String extractedStoredId = creator.getStoredId();
// index
parameters.setParameter("nextCorpusCreatorStep", nextStep);
parameters.setParameter("storedId", extractedStoredId);<|fim▁hole|> assertEquals("corpus", nextStep);
String indexedStoredId = creator.getStoredId();
// corpus
parameters.setParameter("nextCorpusCreatorStep", nextStep);
parameters.setParameter("storedId", extractedStoredId);
creator.run();
nextStep = creator.getNextCorpusCreatorStep();
assertEquals("done", nextStep);
String storedCorpusId = creator.getStoredId();
// do a second pass one step at a time and make sure we get the same IDs
String storedId;
parameters.removeParameter("nextCorpusCreatorStep");
// store
creator.run();
assertEquals(storedStoredId, creator.getStoredId());
parameters.setParameter("nextCorpusCreatorStep", creator.getNextCorpusCreatorStep());
parameters.setParameter("storedId", storedStoredId);
// expand
creator.run();
assertEquals(expandedStoredId, creator.getStoredId());
parameters.setParameter("nextCorpusCreatorStep", creator.getNextCorpusCreatorStep());
parameters.setParameter("storedId", expandedStoredId);
// extract
creator.run();
assertEquals(extractedStoredId, creator.getStoredId());
parameters.setParameter("nextCorpusCreatorStep", creator.getNextCorpusCreatorStep());
parameters.setParameter("storedId", extractedStoredId);
// index
creator.run();
assertEquals(indexedStoredId, creator.getStoredId());
parameters.setParameter("nextCorpusCreatorStep", creator.getNextCorpusCreatorStep());
parameters.setParameter("storedId", indexedStoredId);
// corpus
creator.run();
assertEquals(storedCorpusId, creator.getStoredId());
// now do a full pass with a new text
parameters = new FlexibleParameters(new String[]{"string=test","file="+TestHelper.getResource("formats/chars.rtf")});
creator = new RealCorpusCreator(storage, parameters);
creator.run();
assertEquals(storedCorpusId, creator.getStoredId());
// XStream xstream;
//
// // serialize to XML
// xstream = new XStream();
// xstream.autodetectAnnotations(true);
// String xml = xstream.toXML(creator);
// System.err.println(xml);
storage.destroy();
}
}<|fim▁end|> | creator.run();
nextStep = creator.getNextCorpusCreatorStep(); |
<|file_name|>from_into.rs<|end_file_name|><|fim▁begin|>// The From trait is used for value-to-value conversions.
// If From is implemented correctly for a type, the Into trait should work conversely.
// You can read more about it at https://doc.rust-lang.org/std/convert/trait.From.html
#[derive(Debug)]
struct Person {
name: String,
age: usize,
}
// We implement the Default trait to use it as a fallback
// when the provided string is not convertible into a Person object
impl Default for Person {
fn default() -> Person {
Person {
name: String::from("John"),
age: 30,
}
}
}
// I AM NOT DONE
// Your task is to complete this implementation
// in order for the line `let p = Person::from("Mark,20")` to compile
// Please note that you'll need to parse the age component into a `usize`
// with something like `"4".parse::<usize>()`. The outcome of this needs to
// be handled appropriately.
//
// Steps:
// 1. If the length of the provided string is 0, then return the default of Person
// 2. Split the given string on the commas present in it
// 3. Extract the first element from the split operation and use it as the name
// 4. If the name is empty, then return the default of Person
// 5. Extract the other element from the split operation and parse it into a `usize` as the age
// If while parsing the age, something goes wrong, then return the default of Person<|fim▁hole|>}
fn main() {
// Use the `from` function
let p1 = Person::from("Mark,20");
// Since From is implemented for Person, we should be able to use Into
let p2: Person = "Gerald,70".into();
println!("{:?}", p1);
println!("{:?}", p2);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_default() {
// Test that the default person is 30 year old John
let dp = Person::default();
assert_eq!(dp.name, "John");
assert_eq!(dp.age, 30);
}
#[test]
fn test_bad_convert() {
// Test that John is returned when bad string is provided
let p = Person::from("");
assert_eq!(p.name, "John");
assert_eq!(p.age, 30);
}
#[test]
fn test_good_convert() {
// Test that "Mark,20" works
let p = Person::from("Mark,20");
assert_eq!(p.name, "Mark");
assert_eq!(p.age, 20);
}
#[test]
fn test_bad_age() {
// Test that "Mark.twenty" will return the default person due to an error in parsing age
let p = Person::from("Mark,twenty");
assert_eq!(p.name, "John");
assert_eq!(p.age, 30);
}
#[test]
fn test_missing_comma_and_age() {
let p: Person = Person::from("Mark");
assert_eq!(p.name, "John");
assert_eq!(p.age, 30);
}
#[test]
fn test_missing_age() {
let p: Person = Person::from("Mark,");
assert_eq!(p.name, "John");
assert_eq!(p.age, 30);
}
#[test]
fn test_missing_name() {
let p: Person = Person::from(",1");
assert_eq!(p.name, "John");
assert_eq!(p.age, 30);
}
#[test]
fn test_missing_name_and_age() {
let p: Person = Person::from(",");
assert_eq!(p.name, "John");
assert_eq!(p.age, 30);
}
#[test]
fn test_missing_name_and_invalid_age() {
let p: Person = Person::from(",one");
assert_eq!(p.name, "John");
assert_eq!(p.age, 30);
}
}<|fim▁end|> | // Otherwise, then return an instantiated Person object with the results
impl From<&str> for Person {
fn from(s: &str) -> Person {
} |
<|file_name|>events.rs<|end_file_name|><|fim▁begin|>/* Copyright (C) 2018 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* version 2 along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
use crate::core::*;
use crate::smb::smb::*;
#[derive(AppLayerEvent)]
pub enum SMBEvent {
InternalError,
MalformedData,
RecordOverflow,
MalformedNtlmsspRequest,
MalformedNtlmsspResponse,<|fim▁hole|>
impl SMBTransaction {
/// Set event.
pub fn set_event(&mut self, e: SMBEvent) {
sc_app_layer_decoder_events_set_event_raw(&mut self.events, e as u8);
}
/// Set events from vector of events.
pub fn set_events(&mut self, events: Vec<SMBEvent>) {
for e in events {
sc_app_layer_decoder_events_set_event_raw(&mut self.events, e as u8);
}
}
}
impl SMBState {
/// Set an event. The event is set on the most recent transaction.
pub fn set_event(&mut self, event: SMBEvent) {
let len = self.transactions.len();
if len == 0 {
return;
}
let tx = &mut self.transactions[len - 1];
tx.set_event(event);
//sc_app_layer_decoder_events_set_event_raw(&mut tx.events, event as u8);
}
}<|fim▁end|> | DuplicateNegotiate,
NegotiateMalformedDialects,
FileOverlap,
} |
<|file_name|>util.js<|end_file_name|><|fim▁begin|>requirejs(['helper/util'], function(util){<|fim▁hole|><|fim▁end|> |
}); |
<|file_name|>main.rs<|end_file_name|><|fim▁begin|>#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
extern crate syslog;
extern crate libc;
extern crate pnet;
extern crate crossbeam;
extern crate scheduler;
extern crate clap;
extern crate yaml_rust;
extern crate parking_lot;
extern crate fnv;
extern crate chan_signal;
extern crate pcap;
extern crate bpfjit;
extern crate chrono;
extern crate influent;
extern crate concurrent_hash_map;
extern crate url;
use std::fmt;
use std::str::FromStr;
use std::cell::RefCell;
use std::thread;
use std::path::PathBuf;
use std::time::Duration;
use std::sync::Arc;
use std::net::Ipv4Addr;
use pnet::util::MacAddr;
use parking_lot::{RwLock,Mutex,Condvar};
use concurrent_hash_map::ConcurrentHashMap;
use std::collections::BTreeMap;
use std::hash::BuildHasherDefault;
use clap::{Arg, App, AppSettings, SubCommand};
use bpfjit::BpfJitFilter;
mod netmap;
mod cookie;
mod sha1;
mod packet;
mod csum;
mod util;
mod ring;
mod uptime;
mod config;
mod filter;
mod logging;
mod metrics;
use uptime::UptimeReader;
use packet::IngressPacket;
use netmap::{Direction,NetmapDescriptor};
// TODO: split "routing" into its own file
lazy_static! {
/* maps public IP to tcp parameters */
static ref GLOBAL_HOST_CONFIGURATION: RwLock<BTreeMap<Ipv4Addr, HostConfiguration>> = {
let hm = BTreeMap::new();
RwLock::new(hm)
};
}
// per thread "routing" table
// it's updated periodically in Rx/Tx threads
// lets us avoid contention
thread_local!(pub static LOCAL_ROUTING_TABLE: RefCell<BTreeMap<Ipv4Addr, HostConfiguration>> = {
let hm = BTreeMap::new();
RefCell::new(hm)
});
#[derive(Clone)]
struct StateTable {
map: ConcurrentHashMap<usize,usize, BuildHasherDefault<fnv::FnvHasher>>,
}
impl fmt::Debug for StateTable {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.map.len() == 0 {
try!(write!(f, "StateTable empty\n"));
}
let entries = self.map.entries();
fn decode_key(k: usize) -> (Ipv4Addr, u16, u16) {
let ip = Ipv4Addr::from((k >> 32) as u32);
let src_port = ((k & 0xffffffff) >> 16) as u16;
let dst_port = k as u16;
(ip, src_port, dst_port)
}
fn decode_val(v: usize) -> ConnState {
ConnState::from((v & 0xffffffff) - 1)
}
for entry in &entries {
try!(write!(f, "{:?} -> {:?}\n", decode_key(entry.0), decode_val(entry.1)));
}
write!(f, "StateTable: {} entries\n", self.map.len())
}
}
#[derive(Debug,Eq,PartialEq,Copy,Clone)]
enum ConnState {
Established, // first ACK received and valid
Closing, // FIN received
}
impl From<usize> for ConnState {
fn from(x: usize) -> Self {
match x {
0 => ConnState::Established,
1 => ConnState::Closing,
x => panic!("invalid connection state {}", x),
}
}
}
impl StateTable {
fn new(size: usize) -> Self {
StateTable {
map: ConcurrentHashMap::new_with_options(size as u32,
1024, 0.8,
BuildHasherDefault::<fnv::FnvHasher>::default()),
}
}
pub fn set_state(&mut self, ip: Ipv4Addr, source_port: u16, dest_port: u16, ts: u32, state: ConnState) {
let int_ip = u32::from(ip) as usize;
let key: usize = int_ip << 32
| (source_port as usize) << 16
| dest_port as usize;
let val: usize = (ts as usize) << 32 | ((state as usize) + 1);
self.map.insert(key, val);
}
pub fn get_state(&self, ip: Ipv4Addr, source_port: u16, dest_port: u16) -> Option<(u32,ConnState)> {
let int_ip = u32::from(ip) as usize;
let key: usize = int_ip << 32
| (source_port as usize) << 16
| dest_port as usize;
self.map.get(key).map(|val| ((val >> 32) as u32, ConnState::from((val & 0xffffffff) - 1)))
}
pub fn delete_state(&mut self, ip: Ipv4Addr, source_port: u16, dest_port: u16) {
let int_ip = u32::from(ip) as usize;
let key: usize = int_ip << 32
| (source_port as usize) << 16
| dest_port as usize;
self.map.remove(key);
}
}
// TODO: rename to sth. more appropriate (FibTable, ConfigTable?)
pub struct RoutingTable;
impl RoutingTable {
fn add_host(config: &config::HostConfig) {
info!("Configuration: {} -> {} Filters: {} Default policy: {:?} pt: {}",
config.ip, config.mac, config.filters.len(),
config.default_policy, config.passthrough);
let host_conf = HostConfiguration::new(config.mac, config.filters.clone(), config.default_policy, config.passthrough);
let mut w = GLOBAL_HOST_CONFIGURATION.write();
w.insert(config.ip, host_conf);
}
fn clear() {
let mut w = GLOBAL_HOST_CONFIGURATION.write();
w.clear();
}
pub fn get_ips() -> Vec<Ipv4Addr> {
let r = GLOBAL_HOST_CONFIGURATION.read();
r.keys().cloned().collect()
}
pub fn sync_tables() {
LOCAL_ROUTING_TABLE.with(|rt| {
use std::collections::btree_map::Entry;
let ips = ::RoutingTable::get_ips();
let mut cache = rt.borrow_mut();
// merge configurations
for ip in &ips {
::RoutingTable::with_host_config_global(*ip, |hc| {
match cache.entry(*ip) {
Entry::Vacant(ve) => {
ve.insert(hc.to_owned());
},
Entry::Occupied(mut oe) => {
let oe = oe.get_mut();
oe.merge(hc)
},
}
});
}
// remove extra keys
let ips: Vec<Ipv4Addr> = cache.keys().cloned().collect();
for ip in &ips {
if ::RoutingTable::with_host_config_global(*ip, |_| {}).is_none() {
cache.remove(ip);
}
}
})
}
pub fn dump_states() {
let ips = Self::get_ips();
LOCAL_ROUTING_TABLE.with(|rt| {
for ip in ips {
let r = rt.borrow();
if let Some(hc) = r.get(&ip) {
println!("[{}] {:?}", ip, hc.state_table);
}
}
});
}
pub fn with_host_config<F>(ip: Ipv4Addr, mut f: F) -> Option<()> where F: FnMut(&HostConfiguration) {
LOCAL_ROUTING_TABLE.with(|rt| {
let r = rt.borrow();
if let Some(hc) = r.get(&ip) {
f(hc);
Some(())
} else {
None
}
})
}
pub fn with_host_config_mut<F>(ip: Ipv4Addr, mut f: F) -> Option<()> where F: FnMut(&mut HostConfiguration) {
LOCAL_ROUTING_TABLE.with(|rt| {
let mut cache = rt.borrow_mut();
if let Some(hc) = cache.get_mut(&ip) {
f(hc);
Some(())
} else {
None
}
})
}
pub fn with_host_config_global<F>(ip: Ipv4Addr, mut f: F) -> Option<()> where F: FnMut(&HostConfiguration) {
let r = GLOBAL_HOST_CONFIGURATION.read();
if let Some(hc) = r.get(&ip) {
f(hc);
Some(())
} else {
None
}
}
pub fn with_host_config_global_mut<F>(ip: Ipv4Addr, mut f: F) -> Option<()> where F: FnMut(&mut HostConfiguration) {
let mut w = GLOBAL_HOST_CONFIGURATION.write();
if let Some(hc) = w.get_mut(&ip) {
f(hc);
Some(())
} else {
None
}
}
}
pub struct HostConfiguration {
mac: MacAddr,
tcp_timestamp: u32,
tcp_cookie_time: u32,
hz: u32,
syncookie_secret: [[u32;17];2],
state_table: StateTable,
filters: Arc<Vec<(BpfJitFilter,filter::FilterAction)>>,
default: filter::FilterAction,
passthrough: bool,
packets: u32,
}
impl HostConfiguration {
fn new(mac: MacAddr, filters: Vec<(BpfJitFilter,filter::FilterAction)>, default: filter::FilterAction, pt: bool) -> Self {
HostConfiguration {
mac: mac,
tcp_timestamp: 0,
tcp_cookie_time: 0,
hz: 300,
syncookie_secret: [[0;17];2],
state_table: StateTable::new(1024 * 1024),
filters: Arc::new(filters),
default: default,
passthrough: pt,
packets: 0,
}
}
fn merge(&mut self, other: &HostConfiguration) {
self.mac = other.mac;
self.tcp_timestamp = other.tcp_timestamp;
self.tcp_cookie_time = other.tcp_cookie_time;
self.hz = other.hz;
self.syncookie_secret = other.syncookie_secret;
self.filters = other.filters.clone();
self.default = other.default;
self.passthrough = other.passthrough;
// skip copying state_table
self.packets = other.packets;
}
}
impl Clone for HostConfiguration {
fn clone(&self) -> Self {
HostConfiguration {
mac: self.mac,
tcp_timestamp: self.tcp_timestamp,
tcp_cookie_time: self.tcp_cookie_time,
hz: self.hz,
syncookie_secret: self.syncookie_secret,
state_table: self.state_table.clone(),
filters: self.filters.clone(),
default: self.default,
passthrough: self.passthrough,
packets: self.packets,
}
}
}
#[derive(Debug)]
pub struct ForwardedPacket {
pub slot_ptr: usize,
pub buf_ptr: usize,
pub destination_mac: MacAddr,
}
pub enum OutgoingPacket {
Ingress(IngressPacket),
Forwarded((usize, usize, MacAddr)),
}
// spawn threads updating tcp cookie secrets / uptime
fn run_uptime_readers(reload_lock: Arc<(Mutex<bool>, Condvar)>, uptime_readers: Vec<(Ipv4Addr, Box<UptimeReader>)>) {
let one_sec = Duration::new(1, 0);
crossbeam::scope(|scope| {
for (ip, mut uptime_reader) in uptime_readers {
let reload_lock = reload_lock.clone();
info!("Uptime reader for {} starting", ip);
scope.spawn(move || loop {
::util::set_thread_name(&format!("syncookied/{}", ip));
match uptime_reader.read() {
Ok(buf) => if let Err(err) = uptime::update(ip, buf) {
error!("Failed to parse uptime: {:?}", err);
},
Err(err) => error!("Failed to read uptime: {:?}", err),
}
thread::sleep(one_sec);
let &(ref lock, _) = &*reload_lock;
let time_to_die = lock.lock();
if *time_to_die {
info!("Uptime reader for {} exiting", ip);
break;
}
});
}
});
let &(ref lock, ref cv) = &*reload_lock;
let mut time_to_die = lock.lock();
*time_to_die = false;
cv.notify_all();
info!("All uptime readers dead");
}
fn state_table_gc() {
const CLOSING_TIMEOUT: u32 = 120;
const ESTABLISHED_TIMEOUT: u32 = 600;
fn decode_val(val: usize) -> (ConnState, u32) {
let ts = (val >> 32) as u32;
let cs = ConnState::from((val & 0xffffffff) - 1);
(cs, ts)
}
fn decode_key(k: usize) -> (Ipv4Addr, u16, u16) {
let ip = Ipv4Addr::from((k >> 32) as u32);
let src_port = ((k & 0xffffffff) >> 16) as u16;
let dst_port = k as u16;
(ip, src_port, dst_port)
}
loop {
thread::sleep(Duration::new(30, 0));
::RoutingTable::sync_tables();
debug!("Dumping table states");
::RoutingTable::dump_states();
debug!("Starting GC");
let ips = ::RoutingTable::get_ips();
for ip in ips {
let mut entries = vec![];
let mut timestamp = 0;
let mut hz = 300;
::RoutingTable::with_host_config(ip, |hc| {
entries = hc.state_table.map.entries();
timestamp = hc.tcp_timestamp;
hz = hc.hz;
});
for e in entries {
let k = e.0;
let (cs, ts) = decode_val(e.1);
debug!("Curr. ts: {}, entry ts: {}", timestamp, ts);
match (cs, ts) {
(ConnState::Closing, ts) => if ts < timestamp - CLOSING_TIMEOUT * hz {
::RoutingTable::with_host_config_mut(ip, |hc| {
let (ip, sport, dport) = decode_key(k);
debug!("Deleting state for {:?} {} {}", ip, sport, dport);
hc.state_table.delete_state(ip, sport, dport);
});
},
(ConnState::Established, ts) => if ts < timestamp - ESTABLISHED_TIMEOUT * hz {
::RoutingTable::with_host_config_mut(ip, |hc| {
let (ip, sport, dport) = decode_key(k);
debug!("Deleting state for {:?} {} {}", ip, sport, dport);
hc.state_table.delete_state(ip, sport, dport);
});
},
}
}
}
debug!("Dumping table states");
::RoutingTable::dump_states();
debug!("End of GC");
}
}
fn handle_signals(path: PathBuf, reload_lock: Arc<(Mutex<bool>, Condvar)>) {
use chan_signal::Signal;
let signal = chan_signal::notify(&[Signal::HUP, Signal::INT, Signal::USR1]);
thread::spawn(move || loop {
::util::set_thread_name("syncookied/sig");
match signal.recv().unwrap() {
Signal::HUP => {
info!("SIGHUP received, reloading configuration");
match config::configure(&path) {
Ok(data) => {
let uptime_readers = data;
/* wait for old readers to die */
{
let &(ref lock, ref cv) = &*reload_lock;
let mut time_to_die = lock.lock();
*time_to_die = true;
while *time_to_die {
cv.wait(&mut time_to_die); // unlocks mutex
}
}
info!("Old readers are dead, all hail to new readers");
let reload_lock = reload_lock.clone();
thread::spawn(move || run_uptime_readers(reload_lock.clone(), uptime_readers));
},
Err(e) => error!("Error parsing config file {}: {:?}", path.display(), e),
}
},
Signal::USR1 => {
::RoutingTable::sync_tables();
::RoutingTable::dump_states();
},
Signal::INT => {
use std::process;
info!("SIGINT received, exiting");
process::exit(0);
},
_ => {
error!("Unhandled signal {:?}, ignoring", signal);
}
}
});
}
// TODO: too many parameters, put them into a struct
fn run(config: PathBuf, rx_iface: &str, tx_iface: &str,
rx_mac: MacAddr, _tx_mac: MacAddr,
qlen: u32, first_cpu: usize,
uptime_readers: Vec<(Ipv4Addr, Box<UptimeReader>)>,
metrics_server: Option<&str>) {
let rx_nm = Arc::new(Mutex::new(NetmapDescriptor::new(rx_iface).unwrap()));
let tx_nm = rx_nm.clone();
if rx_iface != tx_iface {
panic!("This option is not implemented");
}
let rx_count = {
let rx_nm = rx_nm.lock();
rx_nm.get_rx_rings_count()
};
let tx_count = {
let tx_nm = tx_nm.lock();
tx_nm.get_tx_rings_count()
};
info!("{} Rx rings @ {}, {} Tx rings @ {} Queue: {}", rx_count, rx_iface, tx_count, tx_iface, qlen);
if tx_count < rx_count {
panic!("We need at least as much Tx rings as Rx rings")
}
crossbeam::scope(|scope| {
let reload_lock = Arc::new((Mutex::new(false), Condvar::new()));
handle_signals(config, reload_lock.clone());
scope.spawn(move ||
run_uptime_readers(reload_lock.clone(), uptime_readers));
scope.spawn(state_table_gc);
// we spawn a thread per queue
for ring in 0..rx_count {
let ring = ring;
let rx_nm = rx_nm.clone();
scope.spawn(move || {
info!("Starting RX/TX thread for ring {} at {}", ring, rx_iface);
let mut ring_nm = {
let nm = rx_nm.lock();
nm.clone_ring(ring, Direction::InputOutput).unwrap()
};
let cpu = first_cpu + ring as usize;
ring::Worker::new(ring, cpu, &mut ring_nm, rx_mac, metrics_server).run();
});
}
});
}
fn main() {
let matches = App::new("syncookied")
.version(env!("CARGO_PKG_VERSION"))
.author(env!("CARGO_PKG_AUTHORS"))
.setting(AppSettings::SubcommandsNegateReqs)
.subcommand(
SubCommand::with_name("server")
.about("Run /proc/beget_uptime reader")
.arg(Arg::with_name("addr")
.takes_value(true)
.value_name("[tcp|udp]://ip:port")
.help("address to listen on"))
)
.arg(Arg::with_name("config")
.short("c")
.long("config")
.value_name("file")
.help("path to hosts.yml file")
.required(false)
.takes_value(true))
.arg(Arg::with_name("in")
.short("i")
.long("input-interface")
.value_name("iface")
.help("Interface to receive packets on")
.required(true)
.takes_value(true))
.arg(Arg::with_name("out")
.short("o")
.long("output-interface")
.value_name("iface")
.help("Interface to send packets on (input interface will be used if not set)")
.takes_value(true))
.arg(Arg::with_name("in-mac")
.short("I")
.required(false)
.long("input-mac")
.value_name("xx:xx:xx:xx:xx:xx")
.help("Input interface mac address")
.takes_value(true))
.arg(Arg::with_name("out-mac")
.short("O")
.required(false)
.long("output-mac")
.value_name("xx:xx:xx:xx:xx:xx")
.help("Output interface mac address")
.takes_value(true))
.arg(Arg::with_name("qlen")
.short("N")
.required(false)
.long("queue-length")
.help("Length of buffer queue")
.takes_value(true))
.arg(Arg::with_name("cpu")
.short("C")
.required(false)
.long("first-cpu")
.help("First cpu to use for Rx")
.takes_value(true))
.arg(Arg::with_name("debug")
.long("debug")
.help("Log to stdout")
.takes_value(false))
.arg(Arg::with_name("metrics-server")
.long("metrics-server")
.required(false)
.help("host:port of influxdb udp listener")
.takes_value(true))
.get_matches();
if let Some(matches) = matches.subcommand_matches("server") {
let addr = matches.value_of("addr").unwrap_or("127.0.0.1:1488");
uptime::run_server(addr);
} else {
println!("Hostname: {}", util::get_host_name().unwrap());
let conf = matches.value_of("config").unwrap_or("hosts.yml");
let rx_iface = matches.value_of("in").expect("Expected valid input interface");
let tx_iface = matches.value_of("out").unwrap_or(rx_iface);
let rx_mac: MacAddr = matches.value_of("in-mac")
.map(str::to_owned)
.or_else(|| util::get_iface_mac(rx_iface).ok())
.map(|mac| MacAddr::from_str(&mac).expect("Expected valid mac")).expect("Input mac not set");
let tx_mac: MacAddr = matches.value_of("out-mac")
.map(str::to_owned)
.or_else(|| util::get_iface_mac(tx_iface).ok())
.map(|mac| MacAddr::from_str(&mac).expect("Expected valid mac")).unwrap_or(rx_mac);
let ncpus = util::get_cpu_count();
let qlen = matches.value_of("qlen")
.map(|x| u32::from_str(x).expect("Expected number for queue length"))
.unwrap_or(1024 * 1024);
let cpu = matches.value_of("cpu")
.map(|x| usize::from_str(x).expect("Expected cpu number"))
.unwrap_or(0);
let metrics_server = matches.value_of("metrics-server");
let config_path = PathBuf::from(conf);
let debug = matches.is_present("debug");
logging::initialize(debug);
match config::configure(&config_path) {
Ok(config) => {
debug!("Config file {} loaded", config_path.display());
let uptime_readers = config;
info!("interfaces: [Rx: {}/{}, Tx: {}/{}] Cores: {}", rx_iface, rx_mac, tx_iface, tx_mac, ncpus);
run(config_path, rx_iface, tx_iface, rx_mac, tx_mac, qlen, cpu, uptime_readers, metrics_server);
},<|fim▁hole|> }
}<|fim▁end|> | Err(e) => error!("Error parsing config file {}: {:?}", config_path.display(), e),
} |
<|file_name|>test_volume.py<|end_file_name|><|fim▁begin|># Copyright 2010 OpenStack Foundation
# Copyright 2012 University Of Minho
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import mock
from jacket.compute import exception
from jacket.compute import test
from jacket.tests.compute.unit.virt.libvirt import fakelibvirt
from jacket.compute import utils
from jacket.compute.virt.libvirt import host
from jacket.compute.virt.libvirt.volume import volume
SECRET_UUID = '2a0a0d6c-babf-454d-b93e-9ac9957b95e0'
class FakeSecret(object):
def __init__(self):
self.uuid = SECRET_UUID
def getUUIDString(self):
return self.uuid
def UUIDString(self):
return self.uuid
def setValue(self, value):
self.value = value
return 0
def getValue(self, value):
return self.value
def undefine(self):
self.value = None
return 0
class LibvirtVolumeBaseTestCase(test.NoDBTestCase):
"""Contains common setup and helper methods for libvirt volume tests."""
def setUp(self):
super(LibvirtVolumeBaseTestCase, self).setUp()
self.executes = []
def fake_execute(*cmd, **kwargs):
self.executes.append(cmd)
return None, None
self.stubs.Set(utils, 'execute', fake_execute)
self.useFixture(fakelibvirt.FakeLibvirtFixture())
class FakeLibvirtDriver(object):
def __init__(self):
self._host = host.Host("qemu:///system")
def _get_all_block_devices(self):
return []
self.fake_conn = FakeLibvirtDriver()
self.connr = {
'ip': '127.0.0.1',
'initiator': 'fake_initiator',
'host': 'fake_host'
}
self.disk_info = {
"bus": "virtio",
"dev": "vde",
"type": "disk",
}
self.name = 'volume-00000001'
self.location = '10.0.2.15:3260'
self.iqn = 'iqn.2010-10.org.openstack:%s' % self.name
self.vol = {'id': 1, 'name': self.name}
self.uuid = '875a8070-d0b9-4949-8b31-104d125c9a64'
self.user = 'foo'
def _assertFileTypeEquals(self, tree, file_path):
self.assertEqual('file', tree.get('type'))
self.assertEqual(file_path, tree.find('./source').get('file'))
class LibvirtISCSIVolumeBaseTestCase(LibvirtVolumeBaseTestCase):
"""Contains common setup and helper methods for iSCSI volume tests."""
def iscsi_connection(self, volume, location, iqn, auth=False,
transport=None):
dev_name = 'ip-%s-iscsi-%s-lun-1' % (location, iqn)
if transport is not None:
dev_name = 'pci-0000:00:00.0-' + dev_name
dev_path = '/dev/disk/by-path/%s' % (dev_name)
ret = {
'driver_volume_type': 'iscsi',
'data': {
'volume_id': volume['id'],
'target_portal': location,
'target_iqn': iqn,
'target_lun': 1,
'device_path': dev_path,
'qos_specs': {
'total_bytes_sec': '102400',
'read_iops_sec': '200',
}
}
}
if auth:
ret['data']['auth_method'] = 'CHAP'
ret['data']['auth_username'] = 'foo'
ret['data']['auth_password'] = 'bar'
return ret
class LibvirtVolumeTestCase(LibvirtISCSIVolumeBaseTestCase):
def _assertDiskInfoEquals(self, tree, disk_info):
self.assertEqual(disk_info['type'], tree.get('device'))
self.assertEqual(disk_info['bus'], tree.find('./target').get('bus'))
self.assertEqual(disk_info['dev'], tree.find('./target').get('dev'))
def _test_libvirt_volume_driver_disk_info(self):
libvirt_driver = volume.LibvirtVolumeDriver(self.fake_conn)
connection_info = {
'driver_volume_type': 'fake',
'data': {
'device_path': '/foo',
},
'serial': 'fake_serial',
}
conf = libvirt_driver.get_config(connection_info, self.disk_info)
tree = conf.format_dom()
self._assertDiskInfoEquals(tree, self.disk_info)
def test_libvirt_volume_disk_info_type(self):
self.disk_info['type'] = 'cdrom'
self._test_libvirt_volume_driver_disk_info()
def test_libvirt_volume_disk_info_dev(self):
self.disk_info['dev'] = 'hdc'
self._test_libvirt_volume_driver_disk_info()
def test_libvirt_volume_disk_info_bus(self):
self.disk_info['bus'] = 'scsi'
self._test_libvirt_volume_driver_disk_info()
def test_libvirt_volume_driver_serial(self):
libvirt_driver = volume.LibvirtVolumeDriver(self.fake_conn)
connection_info = {<|fim▁hole|> 'driver_volume_type': 'fake',
'data': {
'device_path': '/foo',
},
'serial': 'fake_serial',
}
conf = libvirt_driver.get_config(connection_info, self.disk_info)
tree = conf.format_dom()
self.assertEqual('block', tree.get('type'))
self.assertEqual('fake_serial', tree.find('./serial').text)
self.assertIsNone(tree.find('./blockio'))
self.assertIsNone(tree.find("driver[@discard]"))
def test_libvirt_volume_driver_blockio(self):
libvirt_driver = volume.LibvirtVolumeDriver(self.fake_conn)
connection_info = {
'driver_volume_type': 'fake',
'data': {
'device_path': '/foo',
'logical_block_size': '4096',
'physical_block_size': '4096',
},
'serial': 'fake_serial',
}
disk_info = {
"bus": "virtio",
"dev": "vde",
"type": "disk",
}
conf = libvirt_driver.get_config(connection_info, disk_info)
tree = conf.format_dom()
blockio = tree.find('./blockio')
self.assertEqual('4096', blockio.get('logical_block_size'))
self.assertEqual('4096', blockio.get('physical_block_size'))
def test_libvirt_volume_driver_iotune(self):
libvirt_driver = volume.LibvirtVolumeDriver(self.fake_conn)
connection_info = {
'driver_volume_type': 'fake',
'data': {
"device_path": "/foo",
'qos_specs': 'bar',
},
}
disk_info = {
"bus": "virtio",
"dev": "vde",
"type": "disk",
}
conf = libvirt_driver.get_config(connection_info, disk_info)
tree = conf.format_dom()
iotune = tree.find('./iotune')
# ensure invalid qos_specs is ignored
self.assertIsNone(iotune)
specs = {
'total_bytes_sec': '102400',
'read_bytes_sec': '51200',
'write_bytes_sec': '0',
'total_iops_sec': '0',
'read_iops_sec': '200',
'write_iops_sec': '200',
}
del connection_info['data']['qos_specs']
connection_info['data'].update(dict(qos_specs=specs))
conf = libvirt_driver.get_config(connection_info, disk_info)
tree = conf.format_dom()
self.assertEqual('102400', tree.find('./iotune/total_bytes_sec').text)
self.assertEqual('51200', tree.find('./iotune/read_bytes_sec').text)
self.assertEqual('0', tree.find('./iotune/write_bytes_sec').text)
self.assertEqual('0', tree.find('./iotune/total_iops_sec').text)
self.assertEqual('200', tree.find('./iotune/read_iops_sec').text)
self.assertEqual('200', tree.find('./iotune/write_iops_sec').text)
def test_libvirt_volume_driver_readonly(self):
libvirt_driver = volume.LibvirtVolumeDriver(self.fake_conn)
connection_info = {
'driver_volume_type': 'fake',
'data': {
"device_path": "/foo",
'access_mode': 'bar',
},
}
disk_info = {
"bus": "virtio",
"dev": "vde",
"type": "disk",
}
self.assertRaises(exception.InvalidVolumeAccessMode,
libvirt_driver.get_config,
connection_info, self.disk_info)
connection_info['data']['access_mode'] = 'rw'
conf = libvirt_driver.get_config(connection_info, disk_info)
tree = conf.format_dom()
readonly = tree.find('./readonly')
self.assertIsNone(readonly)
connection_info['data']['access_mode'] = 'ro'
conf = libvirt_driver.get_config(connection_info, disk_info)
tree = conf.format_dom()
readonly = tree.find('./readonly')
self.assertIsNotNone(readonly)
@mock.patch('compute.virt.libvirt.host.Host.has_min_version')
def test_libvirt_volume_driver_discard_true(self, mock_has_min_version):
# Check the discard attrib is present in driver section
mock_has_min_version.return_value = True
libvirt_driver = volume.LibvirtVolumeDriver(self.fake_conn)
connection_info = {
'driver_volume_type': 'fake',
'data': {
'device_path': '/foo',
'discard': True,
},
'serial': 'fake_serial',
}
conf = libvirt_driver.get_config(connection_info, self.disk_info)
tree = conf.format_dom()
driver_node = tree.find("driver[@discard]")
self.assertIsNotNone(driver_node)
self.assertEqual('unmap', driver_node.attrib['discard'])
def test_libvirt_volume_driver_discard_false(self):
# Check the discard attrib is not present in driver section
libvirt_driver = volume.LibvirtVolumeDriver(self.fake_conn)
connection_info = {
'driver_volume_type': 'fake',
'data': {
'device_path': '/foo',
'discard': False,
},
'serial': 'fake_serial',
}
conf = libvirt_driver.get_config(connection_info, self.disk_info)
tree = conf.format_dom()
self.assertIsNone(tree.find("driver[@discard]"))
@mock.patch('compute.virt.libvirt.host.Host.has_min_version')
def test_libvirt_volume_driver_discard_true_bad_version(
self, mock_has_min_version):
# Check the discard attrib is not present in driver section
mock_has_min_version.return_value = False
libvirt_driver = volume.LibvirtVolumeDriver(self.fake_conn)
connection_info = {
'driver_volume_type': 'fake',
'data': {
'device_path': '/foo',
'discard': True,
},
'serial': 'fake_serial',
}
conf = libvirt_driver.get_config(connection_info, self.disk_info)
tree = conf.format_dom()
self.assertIsNone(tree.find("driver[@discard]"))<|fim▁end|> | |
<|file_name|>editable_selects.js<|end_file_name|><|fim▁begin|>/**
* $Id: sites/all/libraries/tinymce/jscripts/tiny_mce/utils/editable_selects.js 1.3 2010/02/18 14:49:08EST Linda M. Williams (WILLIAMSLM) Production $
*
* Makes select boxes editable.
*
* @author Moxiecode
* @copyright Copyright © 2004-2008, Moxiecode Systems AB, All rights reserved.
*/
var TinyMCE_EditableSelects = {
editSelectElm : null,
init : function() {
var nl = document.getElementsByTagName("select"), i, d = document, o;
for (i=0; i<nl.length; i++) {
if (nl[i].className.indexOf('mceEditableSelect') != -1) {
o = new Option('(value)', '__mce_add_custom__');
o.className = 'mceAddSelectValue';
nl[i].options[nl[i].options.length] = o;
nl[i].onchange = TinyMCE_EditableSelects.onChangeEditableSelect;
}
}
},
onChangeEditableSelect : function(e) {
var d = document, ne, se = window.event ? window.event.srcElement : e.target;
if (se.options[se.selectedIndex].value == '__mce_add_custom__') {
ne = d.createElement("input");
ne.id = se.id + "_custom";
ne.name = se.name + "_custom";
ne.type = "text";
ne.style.width = se.offsetWidth + 'px';
se.parentNode.insertBefore(ne, se);
se.style.display = 'none';
ne.focus();
ne.onblur = TinyMCE_EditableSelects.onBlurEditableSelectInput;
ne.onkeydown = TinyMCE_EditableSelects.onKeyDown;
TinyMCE_EditableSelects.editSelectElm = se;
}
},
onBlurEditableSelectInput : function() {
var se = TinyMCE_EditableSelects.editSelectElm;
if (se) {
if (se.previousSibling.value != '') {
addSelectValue(document.forms[0], se.id, se.previousSibling.value, se.previousSibling.value);
selectByValue(document.forms[0], se.id, se.previousSibling.value);
} else
selectByValue(document.forms[0], se.id, '');
se.style.display = 'inline';
se.parentNode.removeChild(se.previousSibling);
TinyMCE_EditableSelects.editSelectElm = null;
}
},
onKeyDown : function(e) {
e = e || window.event;
if (e.keyCode == 13)
<|fim▁hole|> }
};<|fim▁end|> | TinyMCE_EditableSelects.onBlurEditableSelectInput();
|
<|file_name|>ini.py<|end_file_name|><|fim▁begin|>from __future__ import absolute_import, unicode_literals
import logging
import os
from ...platformdirs import user_config_dir
from ..info import PY3<|fim▁hole|>from .convert import convert
class IniConfig(object):
VIRTUALENV_CONFIG_FILE_ENV_VAR = ensure_str("VIRTUALENV_CONFIG_FILE")
STATE = {None: "failed to parse", True: "active", False: "missing"}
section = "virtualenv"
def __init__(self, env=None):
env = os.environ if env is None else env
config_file = env.get(self.VIRTUALENV_CONFIG_FILE_ENV_VAR, None)
self.is_env_var = config_file is not None
config_file = (
Path(config_file)
if config_file is not None
else Path(user_config_dir(appname="virtualenv", appauthor="pypa")) / "virtualenv.ini"
)
self.config_file = config_file
self._cache = {}
exception = None
self.has_config_file = None
try:
self.has_config_file = self.config_file.exists()
except OSError as exc:
exception = exc
else:
if self.has_config_file:
self.config_file = self.config_file.resolve()
self.config_parser = ConfigParser.ConfigParser()
try:
self._load()
self.has_virtualenv_section = self.config_parser.has_section(self.section)
except Exception as exc:
exception = exc
if exception is not None:
logging.error("failed to read config file %s because %r", config_file, exception)
def _load(self):
with self.config_file.open("rt") as file_handler:
reader = getattr(self.config_parser, "read_file" if PY3 else "readfp")
reader(file_handler)
def get(self, key, as_type):
cache_key = key, as_type
if cache_key in self._cache:
return self._cache[cache_key]
# noinspection PyBroadException
try:
source = "file"
raw_value = self.config_parser.get(self.section, key.lower())
value = convert(raw_value, as_type, source)
result = value, source
except Exception:
result = None
self._cache[cache_key] = result
return result
def __bool__(self):
return bool(self.has_config_file) and bool(self.has_virtualenv_section)
@property
def epilog(self):
msg = "{}config file {} {} (change{} via env var {})"
return msg.format(
"\n",
self.config_file,
self.STATE[self.has_config_file],
"d" if self.is_env_var else "",
self.VIRTUALENV_CONFIG_FILE_ENV_VAR,
)<|fim▁end|> | from ..util import ConfigParser
from ..util.path import Path
from ..util.six import ensure_str
|
<|file_name|>User.java<|end_file_name|><|fim▁begin|>package ru.otus.java_2017_04.golovnin.hw09;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
@Entity(name = "user")
@Table(name = "users")
public class User extends DataSet{
@Column(name = "name")
private String name;
@Column(name = "age", nullable = false, length = 3)
private int age;
User(){
super();
name = "";
age = 0;
}
User(long id, String name, int age){
super(id);
this.name = name;
this.age = age;
}
String getName(){
return name;
}
int getAge() {
return age;<|fim▁hole|><|fim▁end|> | }
} |
<|file_name|>timestamps_test.py<|end_file_name|><|fim▁begin|># Copyright 2011 Google Inc.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
"""Unit tests for nss_cache/util/timestamps.py."""
__author__ = 'jaq@google.com (Jamie Wilkinson)'
<|fim▁hole|>import time
import unittest
import mox
from nss_cache.util import timestamps
class TestTimestamps(mox.MoxTestBase):
def setUp(self):
super(TestTimestamps, self).setUp()
self.workdir = tempfile.mkdtemp()
def tearDown(self):
super(TestTimestamps, self).tearDown()
shutil.rmtree(self.workdir)
def testReadTimestamp(self):
ts_filename = os.path.join(self.workdir, 'tsr')
ts_file = open(ts_filename, 'w')
ts_file.write('1970-01-01T00:00:01Z\n')
ts_file.close()
ts = timestamps.ReadTimestamp(ts_filename)
self.assertEqual(time.gmtime(1), ts)
def testReadTimestamp(self):
# TZ=UTC date -d @1306428781
# Thu May 26 16:53:01 UTC 2011
ts_filename = os.path.join(self.workdir, 'tsr')
ts_file = open(ts_filename, 'w')
ts_file.write('2011-05-26T16:53:01Z\n')
ts_file.close()
ts = timestamps.ReadTimestamp(ts_filename)
self.assertEqual(time.gmtime(1306428781), ts)
def testReadTimestampInFuture(self):
ts_filename = os.path.join(self.workdir, 'tsr')
ts_file = open(ts_filename, 'w')
ts_file.write('2011-05-26T16:02:00Z')
ts_file.close()
now = time.gmtime(1)
self.mox.StubOutWithMock(time, 'gmtime')
time.gmtime().AndReturn(now)
self.mox.ReplayAll()
ts = timestamps.ReadTimestamp(ts_filename)
self.assertEqual(now, ts)
def testWriteTimestamp(self):
ts_filename = os.path.join(self.workdir, 'tsw')
good_ts = time.gmtime(1)
timestamps.WriteTimestamp(good_ts, ts_filename)
self.assertEqual(good_ts, timestamps.ReadTimestamp(ts_filename))
ts_file = open(ts_filename, 'r')
self.assertEqual('1970-01-01T00:00:01Z\n', ts_file.read())
if __name__ == '__main__':
unittest.main()<|fim▁end|> | import os
import shutil
import tempfile |
<|file_name|>locations.py<|end_file_name|><|fim▁begin|># This file is part of Indico.
# Copyright (C) 2002 - 2017 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# Indico is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Indico; if not, see <http://www.gnu.org/licenses/>.
from collections import defaultdict
from datetime import time
from sqlalchemy import func
from indico.core.db import db
from indico.modules.rb.models.aspects import Aspect
from indico.util.caching import memoize_request
from indico.util.decorators import classproperty
from indico.util.i18n import _
from indico.util.locators import locator_property
from indico.util.string import return_ascii
class Location(db.Model):
__tablename__ = 'locations'
__table_args__ = {'schema': 'roombooking'}
# TODO: Turn this into a proper admin setting
working_time_periods = ((time(8, 30), time(12, 30)), (time(13, 30), time(17, 30)))
@classproperty
@classmethod
def working_time_start(cls):
return cls.working_time_periods[0][0]
@classproperty<|fim▁hole|> @classmethod
def working_time_end(cls):
return cls.working_time_periods[-1][1]
id = db.Column(
db.Integer,
primary_key=True
)
name = db.Column(
db.String,
nullable=False,
unique=True,
index=True
)
is_default = db.Column(
db.Boolean,
nullable=False,
default=False
)
default_aspect_id = db.Column(
db.Integer,
db.ForeignKey(
'roombooking.aspects.id',
use_alter=True,
name='fk_locations_default_aspect_id',
onupdate='CASCADE',
ondelete='SET NULL'
)
)
map_url_template = db.Column(
db.String,
nullable=False,
default=''
)
aspects = db.relationship(
'Aspect',
backref='location',
cascade='all, delete-orphan',
primaryjoin=(id == Aspect.location_id),
lazy='dynamic',
)
default_aspect = db.relationship(
'Aspect',
primaryjoin=default_aspect_id == Aspect.id,
post_update=True,
)
rooms = db.relationship(
'Room',
backref='location',
cascade='all, delete-orphan',
lazy=True
)
attributes = db.relationship(
'RoomAttribute',
backref='location',
cascade='all, delete-orphan',
lazy='dynamic'
)
equipment_types = db.relationship(
'EquipmentType',
backref='location',
lazy='dynamic',
cascade='all, delete-orphan'
)
holidays = db.relationship(
'Holiday',
backref='location',
cascade='all, delete-orphan',
lazy='dynamic'
)
# relationship backrefs:
# - breaks (Break.own_venue)
# - contributions (Contribution.own_venue)
# - events (Event.own_venue)
# - session_blocks (SessionBlock.own_venue)
# - sessions (Session.own_venue)
@return_ascii
def __repr__(self):
return u'<Location({0}, {1}, {2})>'.format(
self.id,
self.default_aspect_id,
self.name
)
@locator_property
def locator(self):
return {'locationId': self.name}
@property
@memoize_request
def is_map_available(self):
return self.aspects.count() > 0
@classproperty
@classmethod
@memoize_request
def default_location(cls):
return cls.query.filter_by(is_default=True).first()
def set_default(self):
if self.is_default:
return
(Location.query
.filter(Location.is_default | (Location.id == self.id))
.update({'is_default': func.not_(Location.is_default)}, synchronize_session='fetch'))
def get_attribute_by_name(self, name):
return self.attributes.filter_by(name=name).first()
def get_equipment_by_name(self, name):
return self.equipment_types.filter_by(name=name).first()
def get_buildings(self):
building_rooms = defaultdict(list)
for room in self.rooms:
building_rooms[room.building].append(room)
buildings = []
for building_name, rooms in building_rooms.iteritems():
room_with_lat_lon = next((r for r in rooms if r.longitude and r.latitude), None)
if not room_with_lat_lon:
continue
buildings.append({'number': building_name,
'title': _(u'Building {}'.format(building_name)),
'longitude': room_with_lat_lon.longitude,
'latitude': room_with_lat_lon.latitude,
'rooms': [r.to_serializable('__public_exhaustive__') for r in rooms]})
return buildings<|fim▁end|> | |
<|file_name|>LinkageType3Choice.go<|end_file_name|><|fim▁begin|>package iso20022
// Choice of format for the linkage type.
type LinkageType3Choice struct {
// Linkage type expressed as an ISO 20022 code.
Code *LinkageType1Code `xml:"Cd"`
// Linkage type expressed as a proprietary code.<|fim▁hole|> Proprietary *GenericIdentification30 `xml:"Prtry"`
}
func (l *LinkageType3Choice) SetCode(value string) {
l.Code = (*LinkageType1Code)(&value)
}
func (l *LinkageType3Choice) AddProprietary() *GenericIdentification30 {
l.Proprietary = new(GenericIdentification30)
return l.Proprietary
}<|fim▁end|> | |
<|file_name|>motif-careful-splits-lean.rs<|end_file_name|><|fim▁begin|>extern crate timely;
extern crate alg3_dynamic;
use std::sync::{Arc, Mutex};
use std::io::BufReader;
use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
use timely::dataflow::operators::*;
use alg3_dynamic::*;
type Node = u32;
fn main () {
let start = std::time::Instant::now();
let send = Arc::new(Mutex::new(0));
let send2 = send.clone();
let inspect = ::std::env::args().find(|x| x == "inspect").is_some();
timely::execute_from_args(std::env::args(), move |root| {
let send = send.clone();
// used to partition graph loading
let index = root.index();
let peers = root.peers();
let mut motif = vec![];
let query_size: usize = std::env::args().nth(1).unwrap().parse().unwrap();
for query in 0 .. query_size {
let attr1: usize = std::env::args().nth(2 * (query + 1) + 0).unwrap().parse().unwrap();
let attr2: usize = std::env::args().nth(2 * (query + 1) + 1).unwrap().parse().unwrap();
motif.push((attr1, attr2));
}
// load fragment of input graph into memory to avoid io while running.
let filename = std::env::args().nth(2 * (query_size) + 2).unwrap();
let number_files: usize = std::env::args().nth(2 * (query_size) + 3).unwrap().parse().unwrap();
let pre_load = std::env::args().nth(2 * (query_size) + 4).unwrap().parse().unwrap();
let query_filename = std::env::args().nth(2 * (query_size) + 5).unwrap();
let query_batch: usize = std::env::args().nth(2 * (query_size) + 6).unwrap().parse().unwrap();
if index==0 {
println!("motif:\t{:?}", motif);
println!("filename:\t{:?} , {:?}", filename, number_files);
}
// handles to input and probe, but also both indices so we can compact them.
let (mut input_graph1, mut input_graph2, mut input_delta, probe, load_probe1, load_probe2, handles) = root.dataflow::<Node,_,_>(move |builder| {
// inputs for initial edges and changes to the edge set, respectively.
let (graph_input1, graph1) = builder.new_input::<(Node, Node)>();
let (graph_input2, graph2) = builder.new_input::<(Node, Node)>();
let (delta_input, delta) = builder.new_input::<((Node, Node), i32)>();
// // create indices and handles from the initial edges plus updates.
let (graph_index, handles) = motif::GraphStreamIndex::from_separately_static(graph1, graph2, delta, |k| k as u64, |k| k as u64);
// construct the motif dataflow subgraph.
let motifs = graph_index.build_motif(&motif);
// if "inspect", report motif counts.
if inspect {
motifs
.count()
.inspect_batch(|t,x| println!("{:?}: {:?}", t, x))
.inspect_batch(move |_,x| {
if let Ok(mut bound) = send.lock() {
*bound += x[0];
}
});
}
let load_probe1 = graph_index.forward.handle.clone();
let load_probe2 = graph_index.reverse.handle.clone();
(graph_input1, graph_input2, delta_input, motifs.probe(), load_probe1, load_probe2, handles)
});
// start the experiment!
let start = ::std::time::Instant::now();
let mut remaining = pre_load;
let max_vertex = pre_load as Node;
let prev_time = input_delta.time().clone();
input_delta.advance_to(prev_time.inner + 1);
if number_files == 1 {
// Open the path in read-only mode, returns `io::Result<File>`
let mut lines = match File::open(&Path::new(&filename)) {
Ok(file) => BufReader::new(file).lines(),
Err(why) => {
panic!("EXCEPTION: couldn't open {}: {}",
Path::new(&filename).display(),
Error::description(&why))
},
};
// load up the graph, using the first `limit` lines in the file.
for (counter, line) in lines.by_ref().take(pre_load).enumerate() {
// each worker is responsible for a fraction of the queries
if counter % peers == index {
let good_line = line.ok().expect("EXCEPTION: read error");
if !good_line.starts_with('#') && good_line.len() > 0 {
let mut elements = good_line[..].split_whitespace();
let src: Node = elements.next().unwrap().parse().ok().expect("malformed src");
let dst: Node = elements.next().unwrap().parse().ok().expect("malformed dst");
input_graph1.send((src, dst));
}
}
}
// synchronize with other workers before reporting data loaded.
input_graph1.close();
root.step_while(|| load_probe1.less_than(input_delta.time()));
println!("{:?}\t[worker {}]\tforward index loaded", start.elapsed(), index);
//
// REPEAT ABOVE
// Open the path in read-only mode, returns `io::Result<File>`
let mut lines = match File::open(&Path::new(&filename)) {
Ok(file) => BufReader::new(file).lines(),
Err(why) => {
panic!("EXCEPTION: couldn't open {}: {}",
Path::new(&filename).display(),
Error::description(&why))
},
};
// load up the graph, using the first `limit` lines in the file.
for (counter, line) in lines.by_ref().take(pre_load).enumerate() {
// each worker is responsible for a fraction of the queries
if counter % peers == index {
let good_line = line.ok().expect("EXCEPTION: read error");
if !good_line.starts_with('#') && good_line.len() > 0 {
let mut elements = good_line[..].split_whitespace();
let src: Node = elements.next().unwrap().parse().ok().expect("malformed src");
let dst: Node = elements.next().unwrap().parse().ok().expect("malformed dst");
input_graph2.send((src, dst));
}
}
}
// synchronize with other workers before reporting data loaded.
input_graph2.close();
root.step_while(|| load_probe2.less_than(input_delta.time()));
println!("{:?}\t[worker {}]\treverse index loaded", start.elapsed(), index);
// END REPEAT
} else {
println!("Multiple files...");
for p in 0..number_files {
if p % peers != index {
// each partition will be handeled by one worker only.
continue;
}
let mut p_str = filename.clone().to_string();
if p / 10 == 0{
p_str = p_str + "0000"+ &(p.to_string());
}
else if p / 100 == 0{
p_str = p_str + "000"+ &(p.to_string());
}
else if p / 1000 == 0{
p_str = p_str + "00"+ &(p.to_string());
}
else if p / 10000 == 0{
p_str = p_str + "0"+ &(p.to_string());
}
else {
p_str = p_str + &(p.to_string());
}
println!("worker{:?} --> filename: {:?} {:?}", index,p, p_str);
let mut lines = match File::open(&Path::new(&p_str)) {
Ok(file) => BufReader::new(file).lines(),
Err(why) => {<|fim▁hole|> };
remaining = 0;
// load up all lines in the file.
for (counter, line) in lines.by_ref().enumerate() {
// count edges
remaining = remaining +1 ;
// each worker should load all available edges. Note that each partition is handled by one worker only.
let good_line = line.ok().expect("EXCEPTION: read error");
if !good_line.starts_with('#') && good_line.len() > 0 {
let mut elements = good_line[..].split_whitespace();
let src: Node = elements.next().unwrap().parse().ok().expect("malformed src");
let dst: Node = elements.next().unwrap().parse().ok().expect("malformed dst");
input_graph1.send((src, dst)); // send each edge to its responsible worker;
}
}
} // end loop on files for forward
// synchronize with other workers before reporting data loaded.
input_graph1.close();
root.step_while(|| load_probe1.less_than(input_delta.time()));
println!("{:?}\t[worker {}]\tforward index loaded", start.elapsed(), index);
// REPEAT ABOVE
for p in 0..number_files {
if p % peers != index {
// each partition will be handeled by one worker only.
continue;
}
let mut p_str = filename.clone().to_string();
if p / 10 == 0{
p_str = p_str + "0000"+ &(p.to_string());
}
else if p / 100 == 0{
p_str = p_str + "000"+ &(p.to_string());
}
else if p / 1000 == 0{
p_str = p_str + "00"+ &(p.to_string());
}
else if p / 10000 == 0{
p_str = p_str + "0"+ &(p.to_string());
}
else {
p_str = p_str + &(p.to_string());
}
println!("worker{:?} --> filename: {:?} {:?}", index,p, p_str);
let mut lines = match File::open(&Path::new(&p_str)) {
Ok(file) => BufReader::new(file).lines(),
Err(why) => {
panic!("EXCEPTION: couldn't open {}: {}",
Path::new(&p_str).display(),
Error::description(&why))
},
};
remaining = 0;
// Open the path in read-only mode, returns `io::Result<File>`
let mut lines = match File::open(&Path::new(&p_str)) {
Ok(file) => BufReader::new(file).lines(),
Err(why) => {
panic!("EXCEPTION: couldn't open {}: {}",
Path::new(&p_str).display(),
Error::description(&why))
},
};
// load up the graph, using the first `limit` lines in the file.
for (counter, line) in lines.by_ref().enumerate() {
// each worker is responsible for a fraction of the queries
let good_line = line.ok().expect("EXCEPTION: read error");
if !good_line.starts_with('#') && good_line.len() > 0 {
let mut elements = good_line[..].split_whitespace();
let src: Node = elements.next().unwrap().parse().ok().expect("malformed src");
let dst: Node = elements.next().unwrap().parse().ok().expect("malformed dst");
input_graph2.send((src, dst));
}
}
}//end loop on files
// synchronize with other workers before reporting data loaded.
input_graph2.close();
root.step_while(|| load_probe2.less_than(input_delta.time()));
println!("{:?}\t[worker {}]\treverse index loaded", start.elapsed(), index);
// END REPEAT
}// end if there are multi files
// loop { }
// merge all of the indices the worker maintains.
let prev_time = input_delta.time().clone();
handles.merge_to(&prev_time);
// synchronize with other workers before reporting indices merged.
let prev_time = input_delta.time().clone();
// input_graph.advance_to(prev_time.inner + 1);
input_delta.advance_to(prev_time.inner + 1);
root.step_while(|| probe.less_than(input_delta.time()));
println!("{:?}\t[worker {}]\tindices merged", start.elapsed(), index);
let lines = match File::open(&Path::new(&query_filename)) {
Ok(file) => BufReader::new(file).lines(),
Err(why) => {
panic!("EXCEPTION: couldn't open {}: {}",
Path::new(&query_filename).display(),
Error::description(&why))
},
};
// issue queries and updates, using the remaining lines in the file.
for (query_counter, line) in lines.enumerate() {
// each worker is responsible for a fraction of the queries
if query_counter % peers == index {
let good_line = line.ok().expect("EXCEPTION: read error");
if !good_line.starts_with('#') && good_line.len() > 0 {
let mut elements = good_line[..].split_whitespace();
let src: Node = elements.next().unwrap().parse().ok().expect("malformed src");
let dst: Node = elements.next().unwrap().parse().ok().expect("malformed dst");
input_delta.send(((src, dst), 1));
}
}
// synchronize and merge indices.
if query_counter % query_batch == (query_batch - 1) {
let prev_time = input_delta.time().clone();
// input_graph.advance_to(prev_time.inner + 1);
input_delta.advance_to(prev_time.inner + 1);
root.step_while(|| probe.less_than(input_delta.time()));
handles.merge_to(&prev_time);
}
}
}).unwrap();
let total = send2.lock().map(|x| *x).unwrap_or(0);
println!("elapsed: {:?}\ttotal motifs at this process: {:?}", start.elapsed(), total);
}<|fim▁end|> | panic!("EXCEPTION: couldn't open {}: {}",
Path::new(&p_str).display(),
Error::description(&why))
}, |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.