prompt
large_stringlengths
70
991k
completion
large_stringlengths
0
1.02k
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># Copyright (c) 2012 CNRS # Author: Florent Lamiraux # # This file is part of hpp-corbaserver. # hpp-corbaserver is free software: you can redistribute it<|fim▁hole|># License as published by the Free Software Foundation, either version # 3 of the License, or (at your option) any later version. # # hpp-corbaserver 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 Lesser Public License for more details. You should have # received a copy of the GNU Lesser General Public License along with # hpp-corbaserver. If not, see # <http://www.gnu.org/licenses/>. from .quaternion import Quaternion from .transform import Transform def retrieveRosResource(path): import os ros_package_paths = os.environ["ROS_PACKAGE_PATH"].split(':') if path.startswith("package://"): relpath = path[len("package://"):] for dir in ros_package_paths: abspath = os.path.join(dir,relpath) if os.path.exists(abspath): return abspath return IOError ("Could not find resource " + path) else: return path<|fim▁end|>
# and/or modify it under the terms of the GNU Lesser General Public
<|file_name|>trait-bounds-in-arc.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. // Tests that a heterogeneous list of existential types can be put inside an Arc // and shared between tasks as long as all types fulfill Send. extern crate sync; use sync::Arc; use std::task; trait Pet { fn name(&self, blk: |&str|); fn num_legs(&self) -> uint; fn of_good_pedigree(&self) -> bool; } struct Catte { num_whiskers: uint, name: StrBuf, } struct Dogge { bark_decibels: uint, tricks_known: uint, name: StrBuf, } struct Goldfyshe { swim_speed: uint, name: StrBuf, } impl Pet for Catte { fn name(&self, blk: |&str|) { blk(self.name.as_slice()) } fn num_legs(&self) -> uint { 4 } fn of_good_pedigree(&self) -> bool { self.num_whiskers >= 4 } } impl Pet for Dogge { fn name(&self, blk: |&str|) { blk(self.name.as_slice()) } fn num_legs(&self) -> uint { 4 } fn of_good_pedigree(&self) -> bool { self.bark_decibels < 70 || self.tricks_known > 20 } } impl Pet for Goldfyshe { fn name(&self, blk: |&str|) { blk(self.name.as_slice()) }<|fim▁hole|> fn of_good_pedigree(&self) -> bool { self.swim_speed >= 500 } } pub fn main() { let catte = Catte { num_whiskers: 7, name: "alonzo_church".to_strbuf() }; let dogge1 = Dogge { bark_decibels: 100, tricks_known: 42, name: "alan_turing".to_strbuf(), }; let dogge2 = Dogge { bark_decibels: 55, tricks_known: 11, name: "albert_einstein".to_strbuf(), }; let fishe = Goldfyshe { swim_speed: 998, name: "alec_guinness".to_strbuf(), }; let arc = Arc::new(vec!(box catte as Box<Pet:Share+Send>, box dogge1 as Box<Pet:Share+Send>, box fishe as Box<Pet:Share+Send>, box dogge2 as Box<Pet:Share+Send>)); let (tx1, rx1) = channel(); let arc1 = arc.clone(); task::spawn(proc() { check_legs(arc1); tx1.send(()); }); let (tx2, rx2) = channel(); let arc2 = arc.clone(); task::spawn(proc() { check_names(arc2); tx2.send(()); }); let (tx3, rx3) = channel(); let arc3 = arc.clone(); task::spawn(proc() { check_pedigree(arc3); tx3.send(()); }); rx1.recv(); rx2.recv(); rx3.recv(); } fn check_legs(arc: Arc<Vec<Box<Pet:Share+Send>>>) { let mut legs = 0; for pet in arc.iter() { legs += pet.num_legs(); } assert!(legs == 12); } fn check_names(arc: Arc<Vec<Box<Pet:Share+Send>>>) { for pet in arc.iter() { pet.name(|name| { assert!(name[0] == 'a' as u8 && name[1] == 'l' as u8); }) } } fn check_pedigree(arc: Arc<Vec<Box<Pet:Share+Send>>>) { for pet in arc.iter() { assert!(pet.of_good_pedigree()); } }<|fim▁end|>
fn num_legs(&self) -> uint { 0 }
<|file_name|>CreateConditionalForwarderResultJsonUnmarshaller.java<|end_file_name|><|fim▁begin|>/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights * Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 com.amazonaws.services.directory.model.transform; import java.util.Map; import java.util.Map.Entry; import java.math.*; import java.nio.ByteBuffer; import com.amazonaws.services.directory.model.*;<|fim▁hole|>import static com.fasterxml.jackson.core.JsonToken.*; /** * CreateConditionalForwarderResult JSON Unmarshaller */ public class CreateConditionalForwarderResultJsonUnmarshaller implements Unmarshaller<CreateConditionalForwarderResult, JsonUnmarshallerContext> { public CreateConditionalForwarderResult unmarshall( JsonUnmarshallerContext context) throws Exception { CreateConditionalForwarderResult createConditionalForwarderResult = new CreateConditionalForwarderResult(); return createConditionalForwarderResult; } private static CreateConditionalForwarderResultJsonUnmarshaller instance; public static CreateConditionalForwarderResultJsonUnmarshaller getInstance() { if (instance == null) instance = new CreateConditionalForwarderResultJsonUnmarshaller(); return instance; } }<|fim▁end|>
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken;
<|file_name|>respeqt_es.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" encoding="utf-8"?> <!DOCTYPE TS> <TS version="2.1" language="es_ES"> <context> <name>AboutDialog</name> <message> <location filename="../aboutdialog.ui" line="14"/> <source>About RespeQt</source> <translation>Acerca de RespeQt</translation> </message> <message> <location filename="../aboutdialog.ui" line="32"/> <source>RespeQt: Atari Serial Peripheral Emulator for Qt</source> <translation>RespeQt: Atari Emulador Serial de Periférico para Qt</translation> </message> <message> <location filename="../aboutdialog.ui" line="56"/> <location filename="../aboutdialog.cpp" line="23"/> <source>qrc:/documentation/about.html</source> <translation>qrc:/documentation/about_spanish.html</translation> </message> <message> <location filename="../aboutdialog.cpp" line="22"/> <source>version %1</source> <translation>versión %1</translation> </message> </context> <context> <name>AtariFileSystem</name> <message> <location filename="../atarifilesystem.cpp" line="261"/> <source>Atari file system error</source> <translation>Error del sistema de archivos de Atari</translation> </message> <message> <location filename="../atarifilesystem.cpp" line="261"/> <source>Cannot create directory &apos;%1&apos;.</source> <translation>No se puede crear directorio &apos;%1&apos;.</translation> </message> </context> <context> <name>AtariSioBackend</name> <message> <location filename="../serialport-unix.cpp" line="744"/> <source>Cannot open serial port &apos;%1&apos;: %2</source> <translation>No se puede abrir el puerto serial &apos;%1&apos;: %2</translation> </message> <message> <location filename="../serialport-unix.cpp" line="753"/> <location filename="../serialport-unix.cpp" line="761"/> <source>Cannot open AtariSio driver &apos;%1&apos;: %2</source> <translation>No se puede abrir el controlador AtariSio &apos;%1&apos;: %2</translation> </message> <message> <location filename="../serialport-unix.cpp" line="785"/> <source>Cannot set AtariSio driver mode: %1</source> <translation>No se puede establecer conexión con AtariSio: %1</translation> </message> <message> <location filename="../serialport-unix.cpp" line="792"/> <source>Cannot set AtariSio to autobaud mode: %1</source> <translation>No se puede establecer conexión con AtariSio para modo autobaudio %1</translation> </message> <message> <location filename="../serialport-unix.cpp" line="799"/> <source>Cannot create the cancel pipe</source> <translation>No se puede crear la tubería</translation> </message> <message> <location filename="../serialport-unix.cpp" line="817"/> <source>Emulation started through AtariSIO backend on &apos;%1&apos; with %2 handshaking.</source> <translation>Emulación inicia a través de backend en AtariSIO &apos;%1&apos; con el %2 handshaking.</translation> </message> <message> <location filename="../serialport-unix.cpp" line="833"/> <source>Cannot close serial port: %1</source> <translation>No se puede cerrar el puerto serial: %1</translation> </message> <message> <location filename="../serialport-unix.cpp" line="844"/> <source>Cannot stop AtariSio backend.</source> <translation>No se puede dejar de backend AtariSio.</translation> </message> <message> <location filename="../serialport-unix.cpp" line="855"/> <source>Cannot set AtariSio speed to %1: %2</source> <translation>No se puede establecer la velocidad de AtariSio %1: %2</translation> </message> <message> <location filename="../serialport-unix.cpp" line="858"/> <location filename="../serialport-unix.cpp" line="904"/> <source>%1 bits/sec</source> <translation>%1 bits/sec</translation> </message> <message> <location filename="../serialport-unix.cpp" line="859"/> <location filename="../serialport-unix.cpp" line="905"/> <source>Serial port speed set to %1.</source> <translation>Velocidad del puerto serial configurado para %1.</translation> </message> <message> <location filename="../serialport-unix.cpp" line="911"/> <source>Illegal condition using select!</source> <translation>Condición ilegal usando select!</translation> </message> <message> <location filename="../serialport-unix.cpp" line="936"/> <source>Cannot read data frame: %1</source> <translation>No se puede leer trama de datos: %1</translation> </message> <message> <location filename="../serialport-unix.cpp" line="962"/> <source>Cannot write data frame: %1</source> <translation>No se puede escribir trama de datos: %1</translation> </message> <message> <location filename="../serialport-unix.cpp" line="973"/> <source>Cannot write command ACK: %1</source> <translation>No se puede escribir el comando ACK: %1</translation> </message> <message> <location filename="../serialport-unix.cpp" line="983"/> <source>Cannot write command NAK: %1</source> <translation>No se puede escribir el comando NAK: %1</translation> </message> <message> <location filename="../serialport-unix.cpp" line="992"/> <source>Cannot write data ACK: %1</source> <translation>No se puede escribir datos ACK: %1</translation> </message> <message> <location filename="../serialport-unix.cpp" line="1001"/> <source>Cannot write data NAK: %1</source> <translation>No se puede escribir datos de NAK: %1</translation> </message> <message> <location filename="../serialport-unix.cpp" line="1010"/> <source>Cannot write COMPLETE byte: %1</source> <translation>No se puede escribir, byte COMPLETO: %1</translation> </message> <message> <location filename="../serialport-unix.cpp" line="1019"/> <source>Cannot write ERROR byte: %1</source> <translation>No se puede escribir, byte ERROR : %1</translation> </message> <message> <location filename="../serialport-unix.cpp" line="1033"/> <source>Cannot write raw frame: %1</source> <translation>No se puede escribir a marco bruto: %1</translation> </message> <message> <location filename="../serialport-unix.cpp" line="1044"/> <source>Block too long.</source> <translation>Bloque demasiado largo.</translation> </message> <message> <location filename="../serialport-unix.cpp" line="1047"/> <source>Command not acknowledged.</source> <translation>Comando no reconocido.</translation> </message> <message> <location filename="../serialport-unix.cpp" line="1050"/> <source>Command timeout.</source> <translation>Tiempo de espera de comando.</translation> </message> <message> <location filename="../serialport-unix.cpp" line="1053"/> <source>Checksum error.</source> <translation>Checksum error.</translation> </message> <message> <location filename="../serialport-unix.cpp" line="1056"/> <source>Device error.</source> <translation>Error en dispositivo.</translation> </message> <message> <location filename="../serialport-unix.cpp" line="1059"/> <source>Data frame not acknowledged.</source> <translation>No reconoció trama de datos.</translation> </message> <message> <location filename="../serialport-unix.cpp" line="1062"/> <source>Unknown AtariSio driver error.</source> <translation>Error desconocido con AtariSio.</translation> </message> <message> <location filename="../serialport-win32.cpp" line="751"/> <source>AtariSIO is only available under Linux.</source> <translation>AtariSIO sólo está disponible en Linux.</translation> </message> </context> <context> <name>AutoBoot</name> <message> <location filename="../autoboot.cpp" line="28"/> <source>[%1] command: $%2, aux: $%3 NAKed.</source> <translation>[%1] comando: $%2, aux: $%3 NAKed.</translation> </message> <message> <location filename="../autoboot.cpp" line="48"/> <source>[%1] Speed poll.</source> <translation>[%1] Velocidad de sondeo.</translation> </message> <message> <location filename="../autoboot.cpp" line="69"/> <source>[%1] Read sector %2 (%3 bytes).</source> <translation>[%1] Leyendo sector %2 (%3 bytes).</translation> </message> <message> <location filename="../autoboot.cpp" line="75"/> <source>[%1] Read sector %2 failed.</source> <translation>[%1] Leyendo sector %2 malo.</translation> </message> <message> <location filename="../autoboot.cpp" line="99"/> <source>[%1] Get status.</source> <translation>[%1] Obtener el estado.</translation> </message> <message> <location filename="../autoboot.cpp" line="108"/> <source>[%1] Atari is jumping to %2.</source> <translation>[%1] Atari está saltando a %2.</translation> </message> <message> <location filename="../autoboot.cpp" line="118"/> <source>[%1] Invalid chunk in get chunk: aux = %2</source> <translation>[%1] Parte inválida en obtener: aux = %2</translation> </message> <message> <location filename="../autoboot.cpp" line="127"/> <source>[%1] Get chunk %2 (%3 bytes).</source> <translation>[%1] Obtener trozo %2 (%3 bytes).</translation> </message> <message> <location filename="../autoboot.cpp" line="139"/> <source>[%1] Invalid chunk in get chunk info: aux = %2</source> <translation>[%1] Información no válida en obtener información de la parte: aux = %2</translation> </message> <message> <location filename="../autoboot.cpp" line="159"/> <source>[%1] Get chunk info %2 (%3 bytes at %4).</source> <translation>[%1] Obtén información del trozo %2 (%3 bytes en %4).</translation> </message> <message> <location filename="../autoboot.cpp" line="180"/> <source>Cannot open file &apos;%1&apos;: %2</source> <translation>No se puede abrir el archivo &apos;%1&apos;: %2</translation> </message> <message> <location filename="../autoboot.cpp" line="195"/> <location filename="../autoboot.cpp" line="218"/> <source>Unexpected end of file, needed %1 more</source> <translation>Fin de archivo inesperado, necesitaba un %1 más</translation> </message> <message> <location filename="../autoboot.cpp" line="199"/> <location filename="../autoboot.cpp" line="222"/> <location filename="../autoboot.cpp" line="243"/> <location filename="../autoboot.cpp" line="268"/> <location filename="../autoboot.cpp" line="298"/> <location filename="../autoboot.cpp" line="316"/> <source>Cannot read from file &apos;%1&apos;: %2.</source> <translation>No se puede leer el archivo &apos;%1&apos;: %2.</translation> </message> <message> <location filename="../autoboot.cpp" line="207"/> <source>Cannot load file &apos;%1&apos;: The file doesn&apos;t seem to be an Atari DOS executable.</source> <translation>No se puede cargar el archivo &apos;%1&apos;: El archivo no parece ser un archivo ejecutable de Atari DOS.</translation> </message> <message> <location filename="../autoboot.cpp" line="234"/> <location filename="../autoboot.cpp" line="264"/> <location filename="../autoboot.cpp" line="293"/> <location filename="../autoboot.cpp" line="311"/> <source>The executable &apos;%1&apos; is broken: Unexpected end of file, needed %2 more.</source> <translation>El ejecutable &apos;%1&apos; está roto: fin de archivo inesperado, necesitaba un %2 más.</translation> </message> <message> <location filename="../autoboot.cpp" line="254"/> <source>The executable &apos;%1&apos; is broken: The end address is less than the start address.</source> <translation>El ejecutable &apos;%1&apos; está roto: La dirección final es menor que la dirección de inicio.</translation> </message> <message> <location filename="../autoboot.cpp" line="340"/> <source>Cannot open the boot loader: %1</source> <translation>No se puede abrir el gestor de arranque: %1</translation> </message> </context> <context> <name>AutoBootDialog</name> <message> <location filename="../autobootdialog.ui" line="26"/> <source>Boot executable</source> <translation>Inicio archivo ejecutable</translation> </message> <message> <location filename="../autobootdialog.ui" line="87"/> <source>Please reboot your Atari. Don&apos;t forget to remove any cartridges and disable BASIC by holding down the Atari Option button if necessary.</source> <translation>Por favor reinicie su Atari. No olvide retirar los cartuchos y deshabilitar BASIC manteniendo presionado el botón de Opción Atari si es necesario.</translation> </message> <message> <location filename="../autobootdialog.ui" line="117"/> <source>Use this button to re-load the executable if it has been changed since the last re-boot of your Atari computer - Useful for developers </source> <translation>Utilice este botón para volver a cargar el ejecutable si se ha cambiado desde el último reinicio de su computadora Atari - Útil para desarrolladores </translation> </message> <message> <location filename="../autobootdialog.ui" line="122"/> <source>Reload</source> <translation>Recargar</translation> </message> <message> <location filename="../autobootdialog.cpp" line="56"/> <source>Atari is loading the booter.</source> <translation>Atari está cargando el gestor de arranque.</translation> </message> <message> <location filename="../autobootdialog.cpp" line="61"/> <source>Atari is loading the program. For some programs you may have to close this dialog manually when the program starts.</source> <translation>Atari está cargando el programa. En algunos programas es posible que tenga que cerrar este diálogo manualmente cuando se inicia el programa.</translation> </message> </context> <context> <name>BootOptionsDialog</name> <message> <location filename="../bootoptionsdialog.ui" line="26"/> <source>Folder Boot Options</source> <translation>Selecciona carpeta de boteo</translation> </message> <message> <location filename="../bootoptionsdialog.ui" line="60"/> <source>Folder Image Boot Options</source> <translation>Selecciona Imagen de boteo desde carpeta</translation> </message> <message> <location filename="../bootoptionsdialog.ui" line="150"/> <source>Select the DOS you want to boot your Atari with</source> <translation>Seleccione algun DOS que desea arrancar con el ATARI</translation> </message> <message> <location filename="../bootoptionsdialog.ui" line="69"/> <source>SmartDOS 6.1D</source> <translation></translation> </message> <message> <location filename="../bootoptionsdialog.ui" line="85"/> <source>SpartaDOS 3.2G</source> <translation></translation> </message> <message> <location filename="../bootoptionsdialog.ui" line="99"/> <source>(Check if you&apos;re already using a high-speed OS)</source> <translation>(Compruebe si ya está utilizando un sistema operativo de alta velocidad)</translation> </message> <message> <location filename="../bootoptionsdialog.ui" line="115"/> <source>MyDOS 4.x</source> <translation></translation> </message> <message> <location filename="../bootoptionsdialog.ui" line="131"/> <source>AtariDOS 2.x</source> <translation></translation> </message> <message> <location filename="../bootoptionsdialog.ui" line="166"/> <source>MyPicoDOS 4.05 (Standard)</source> <translation></translation> </message> <message> <location filename="../bootoptionsdialog.ui" line="176"/> <source>DosXL 2.x</source> <translation></translation> </message> <message> <location filename="../bootoptionsdialog.ui" line="192"/> <source>Disable high speed SIO</source> <translation>Desactivar SIO de alta velocidad</translation> </message> </context> <context> <name>CassetteDialog</name> <message> <location filename="../cassettedialog.ui" line="23"/> <source>Cassette image playback</source> <translation>Cassette de reproducción de imágenes</translation> </message> <message> <location filename="../cassettedialog.ui" line="35"/> <source>Do whatever is necessary in your Atari to load this cassette image like rebooting while holding Option and Start buttons or entering &quot;CLOAD&quot; in the BASIC prompt. When you hear the beep sound, push the OK button below and press a key on your Atari at about the same time.</source> <translation>Haga lo que sea necesario en su Atari para cargar esta imagen como reiniciar casete mientras se mantiene la opción y botones de arranque o la introducción de &quot;CLOAD&quot; en el símbolo del sistema BASIC. Cuando oiga el pitido, pulse el botón OK y presione una tecla en el Atari al mismo tiempo.</translation> </message> <message> <location filename="../cassettedialog.cpp" line="36"/> <source>RespeQt is ready to playback the cassette image file &apos;%1&apos;. The estimated playback duration is: %2:%3 Do whatever is necessary in your Atari to load this cassette image like rebooting while holding Option and Start buttons or entering &quot;CLOAD&quot; in the BASIC prompt. When you hear the beep sound, push the OK button below and press a key on your Atari at about the same time.</source> <translation>RespeQt está listo para reproducir el archivo de imagen de casete &apos;%1&apos;. La duración de reproducción estimada es: %2:%3 Cuando oiga el pitido, pulse el botón OK y presione una tecla en el Atari al mismo tiempo.</translation> </message> <message> <location filename="../cassettedialog.cpp" line="93"/> <location filename="../cassettedialog.cpp" line="108"/> <source>Playing back cassette image. Estimated time left: %1:%2</source> <translation>Reproducción de imagen cassette.. Tiempo restante estimado: %1:%2</translation> </message> </context> <context> <name>CassetteWorker</name> <message> <location filename="../sioworker.cpp" line="532"/> <source>Cannot open &apos;%1&apos;: %2</source> <translation>No se puede abrir &apos;%1&apos;: %2</translation> </message> <message> <location filename="../sioworker.cpp" line="543"/> <location filename="../sioworker.cpp" line="554"/> <location filename="../sioworker.cpp" line="576"/> <location filename="../sioworker.cpp" line="586"/> <source>Cannot read &apos;%1&apos;: %2</source> <translation>No se puede leer &apos;%1&apos;: %2</translation> </message> <message> <location filename="../sioworker.cpp" line="560"/> <source>Cannot open &apos;%1&apos;: The header does not match.</source> <translation>No se puede abrir &apos;%1&apos;: El encabezado no coincide.</translation> </message> <message> <location filename="../sioworker.cpp" line="565"/> <source>[Cassette]: File description &apos;%2&apos;.</source> <translation>[Casete]: Descripción del archivo &apos;%2&apos;.</translation> </message> <message> <location filename="../sioworker.cpp" line="606"/> <source>Cannot open &apos;%1&apos;: Unknown chunk header %2.</source> <translation>No se puede abrir &apos;%1&apos;: Encabezado mal formado %2.</translation> </message> <message> <location filename="../sioworker.cpp" line="655"/> <source>[Cassette] Playing record %1 of %2 (%3 ms of gap + %4 bytes of data)</source> <translation>[Casete] Reproducción de registro %1 de %2 (%3 ms de gap + %4 bytes de datos)</translation> </message> </context> <context> <name>CreateImageDialog</name> <message> <location filename="../createimagedialog.ui" line="23"/> <source>Create a disk image</source> <translation>Crear una imagen de disco</translation> </message> <message> <location filename="../createimagedialog.ui" line="53"/> <source>Standard single density</source> <translation>Densidad Individual estandard</translation> </message> <message> <location filename="../createimagedialog.ui" line="63"/> <source>Standard enhanced (also called medium or dual) density</source> <translation>Estándar mejorada (también llamado medio o doble) Densidad</translation> </message> <message> <location filename="../createimagedialog.ui" line="70"/> <source>Standard double density</source> <translation>Densidad doble estándar</translation> </message> <message> <location filename="../createimagedialog.ui" line="77"/> <source>Double sided double density</source> <translation>Doble densidad de doble cara</translation> </message> <message> <location filename="../createimagedialog.ui" line="84"/> <source>Double density hard disk</source> <translation>Disco duro de doble densidad</translation> </message> <message> <location filename="../createimagedialog.ui" line="91"/> <source>Custom</source> <translation>A la medida</translation> </message> <message> <location filename="../createimagedialog.ui" line="118"/> <source>Number of sectors:</source> <translation>Número de sectores:</translation> </message> <message> <location filename="../createimagedialog.ui" line="142"/> <source>Sector density:</source> <translation>Sector densidad:</translation> </message> <message> <location filename="../createimagedialog.ui" line="150"/> <source>Single (128 bytes per sector)</source> <translation>Normal (128 bytes por sector)</translation> </message> <message> <location filename="../createimagedialog.ui" line="155"/> <source>Double (256 bytes per sector)</source> <translation>Doble (256 bytes por sector)</translation> </message> <message> <location filename="../createimagedialog.ui" line="160"/> <source>512 bytes per sector</source> <translation>512 bytes por sector</translation> </message> <message> <location filename="../createimagedialog.ui" line="165"/> <source>8192 bytes per sector</source> <translation>8192 bytes por sector</translation> </message> <message> <location filename="../createimagedialog.ui" line="181"/> <source>Total image capacity: 92160 bytes (90 K)</source> <translation>Capacidad de imagen Total: 92160 bytes (90 KB)</translation> </message> <message> <location filename="../createimagedialog.cpp" line="87"/> <source>Total image capacity: %1 bytes (%2 K)</source> <translation>Capacidad de imagen total: %1 bytes (%2 K)</translation> </message> </context> <context> <name>DiskEditDialog</name> <message> <location filename="../diskeditdialog.ui" line="23"/> <source>MainWindow</source> <translation>Ventana Principal</translation> </message> <message> <location filename="../diskeditdialog.ui" line="92"/> <source>Stay on Top</source> <translation>Permanecer encima</translation> </message> <message> <location filename="../diskeditdialog.ui" line="111"/> <source>toolBar</source> <translation>Barra de Herramientas</translation> </message> <message> <location filename="../diskeditdialog.ui" line="150"/> <location filename="../diskeditdialog.ui" line="153"/> <location filename="../diskeditdialog.ui" line="156"/> <source>Go to the parent directory</source> <translation>Vaya al directorio padre</translation> </message> <message> <location filename="../diskeditdialog.ui" line="165"/> <source>Add files...</source> <translation>Agregar archivos...</translation> </message> <message> <location filename="../diskeditdialog.ui" line="168"/> <location filename="../diskeditdialog.ui" line="171"/> <source>Add files to this directory</source> <translation>Agregar archivos a este directorio</translation> </message> <message> <location filename="../diskeditdialog.ui" line="183"/> <source>Extract files...</source> <translation>Extraer archivos...</translation> </message> <message> <location filename="../diskeditdialog.ui" line="186"/> <location filename="../diskeditdialog.ui" line="189"/> <source>Extract selected files</source> <translation>Extrae los archivos seleccionados</translation> </message> <message> <location filename="../diskeditdialog.ui" line="201"/> <source>Text conversion</source> <translation>Conversión de Texto</translation> </message> <message> <location filename="../diskeditdialog.ui" line="204"/> <location filename="../diskeditdialog.ui" line="207"/> <location filename="../diskeditdialog.cpp" line="638"/> <location filename="../diskeditdialog.cpp" line="639"/> <source>Text conversion is off</source> <translation>Conversión de texto desactivado</translation> </message> <message> <location filename="../diskeditdialog.ui" line="219"/> <source>Delete</source> <translation>Borrar</translation> </message> <message> <location filename="../diskeditdialog.ui" line="222"/> <location filename="../diskeditdialog.ui" line="225"/> <source>Delete selected files</source> <translation>Eliminar archivos seleccionados</translation> </message> <message> <location filename="../diskeditdialog.ui" line="228"/> <source>Del</source> <translation>Eliminar</translation> </message> <message> <location filename="../diskeditdialog.ui" line="237"/> <source>Print</source> <translation>Imprimir</translation> </message> <message> <location filename="../diskeditdialog.ui" line="240"/> <source>Print Directory Listing</source> <translation>Imprimir lista de directorio</translation> </message> <message> <location filename="../diskeditdialog.cpp" line="462"/> <source>No file system</source> <translation>No existe un sistema de archivos</translation> </message> <message> <location filename="../diskeditdialog.cpp" line="463"/> <source>Atari Dos 1.0</source> <translation></translation> </message> <message> <location filename="../diskeditdialog.cpp" line="464"/> <source>Atari Dos 2.0</source> <translation></translation> </message> <message> <location filename="../diskeditdialog.cpp" line="465"/> <source>Atari Dos 2.5</source> <translation></translation> </message> <message> <location filename="../diskeditdialog.cpp" line="466"/> <source>MyDos</source> <translation></translation> </message> <message> <location filename="../diskeditdialog.cpp" line="467"/> <source>SpartaDos</source> <translation></translation> </message> <message> <location filename="../diskeditdialog.cpp" line="568"/> <location filename="../diskeditdialog.cpp" line="589"/> <location filename="../diskeditdialog.cpp" line="603"/> <source>RespeQt - Exploring %1</source> <translation>RespeQt - Exploración %1</translation> </message> <message> <location filename="../diskeditdialog.cpp" line="614"/> <source>Extract files</source> <translation>Extraer archivos</translation> </message> <message> <location filename="../diskeditdialog.cpp" line="634"/> <location filename="../diskeditdialog.cpp" line="635"/> <source>Text conversion is on</source> <translation>Conversión de texto activado</translation> </message> <message> <location filename="../diskeditdialog.cpp" line="646"/> <source>Confirmation</source> <translation>Confirmación</translation> </message> <message> <location filename="../diskeditdialog.cpp" line="646"/> <source>Are you sure you want to delete selected files?</source> <translation>¿Está seguro que desea eliminar los archivos seleccionados?</translation> </message> <message> <location filename="../diskeditdialog.cpp" line="656"/> <source>Add files</source> <translation>Agregar archivos</translation> </message> </context> <context> <name>DiskGeometry</name> <message> <location filename="../diskimage.cpp" line="449"/> <source>SD Diskette</source> <translation>Diskette SD</translation> </message> <message> <location filename="../diskimage.cpp" line="451"/> <source>ED Diskette</source> <translation>Diskette ED</translation> </message> <message> <location filename="../diskimage.cpp" line="453"/> <source>DD Diskette</source> <translation>Diskette DD</translation> </message> <message> <location filename="../diskimage.cpp" line="455"/> <location filename="../diskimage.cpp" line="457"/> <source>DS/DD Diskette</source> <translation>Diskette DS/DD</translation> </message> <message> <location filename="../diskimage.cpp" line="460"/> <source>%1 sector SD hard disk</source> <translation>%1 sector SD disco duro</translation> </message> <message> <location filename="../diskimage.cpp" line="462"/> <source>%1 sector DD hard disk</source> <translation>%1 sector DD disco duro</translation> </message> <message> <location filename="../diskimage.cpp" line="464"/> <source>%1 sector, %2 bytes/sector hard disk</source> <translation>%1 sector, %2 bytes/sector del disco duro</translation> </message> <message> <location filename="../diskimage.cpp" line="467"/> <source>%1 %2 tracks/side, %3 sectors/track, %4 bytes/sector diskette</source> <translation>%1 %2 tracks/side, %3 sectors/track, %4 bytes/sector disco</translation> </message> <message> <location filename="../diskimage.cpp" line="468"/> <source>DS</source> <translation></translation> </message> <message> <location filename="../diskimage.cpp" line="468"/> <source>SS</source> <translation></translation> </message> <message> <location filename="../diskimage.cpp" line="474"/> <source>%1 (%2k)</source> <translation></translation> </message> </context> <context> <name>DocDisplayWindow</name> <message> <location filename="../docdisplaywindow.ui" line="17"/> <source>RespeQt User Manual</source> <translation>Manual de uso Respeqt</translation> </message> <message> <location filename="../docdisplaywindow.ui" line="35"/> <source>qrc:/documentation/RespeQt User Manual-English.html</source> <translation>qrc:/documentation/RespeQt User Manual-Spanish.html</translation> </message> <message> <location filename="../docdisplaywindow.ui" line="48"/> <source>toolBar</source> <translation>Barra de Herramientas</translation> </message> <message> <location filename="../docdisplaywindow.ui" line="76"/> <source>Print</source> <translation>Imprimir</translation> </message> <message> <location filename="../docdisplaywindow.ui" line="79"/> <location filename="../docdisplaywindow.ui" line="82"/> <source>Print User Manual</source> <translation>Imprimir manual de uso</translation> </message> <message> <location filename="../docdisplaywindow.ui" line="85"/> <source>Ctrl+P</source> <translation></translation> </message> </context> <context> <name>Dos10FileSystem</name> <message> <location filename="../atarifilesystem.cpp" line="483"/> <location filename="../atarifilesystem.cpp" line="491"/> <location filename="../atarifilesystem.cpp" line="497"/> <location filename="../atarifilesystem.cpp" line="551"/> <location filename="../atarifilesystem.cpp" line="564"/> <location filename="../atarifilesystem.cpp" line="569"/> <location filename="../atarifilesystem.cpp" line="586"/> <location filename="../atarifilesystem.cpp" line="591"/> <location filename="../atarifilesystem.cpp" line="604"/> <location filename="../atarifilesystem.cpp" line="666"/> <location filename="../atarifilesystem.cpp" line="676"/> <location filename="../atarifilesystem.cpp" line="699"/> <location filename="../atarifilesystem.cpp" line="714"/> <location filename="../atarifilesystem.cpp" line="719"/> <location filename="../atarifilesystem.cpp" line="730"/> <location filename="../atarifilesystem.cpp" line="749"/> <location filename="../atarifilesystem.cpp" line="758"/> <location filename="../atarifilesystem.cpp" line="770"/> <location filename="../atarifilesystem.cpp" line="777"/> <location filename="../atarifilesystem.cpp" line="793"/> <location filename="../atarifilesystem.cpp" line="798"/> <location filename="../atarifilesystem.cpp" line="807"/> <location filename="../atarifilesystem.cpp" line="813"/> <location filename="../atarifilesystem.cpp" line="823"/> <location filename="../atarifilesystem.cpp" line="901"/> <location filename="../atarifilesystem.cpp" line="906"/> <location filename="../atarifilesystem.cpp" line="915"/> <source>Atari file system error</source> <translation>Error en archivo de sistema</translation> </message> <message> <location filename="../atarifilesystem.cpp" line="483"/> <source>Cannot create file &apos;%1&apos;.</source> <translation>No se puede crear el archivo &apos;%1&apos;.</translation> </message> <message> <location filename="../atarifilesystem.cpp" line="491"/> <location filename="../atarifilesystem.cpp" line="497"/> <source>Cannot read &apos;%1&apos;: %2</source> <translation>No se puede abrir &apos;%1&apos;: %2</translation> </message> <message> <location filename="../atarifilesystem.cpp" line="491"/> <location filename="../atarifilesystem.cpp" line="676"/> <location filename="../atarifilesystem.cpp" line="770"/> <location filename="../atarifilesystem.cpp" line="793"/> <location filename="../atarifilesystem.cpp" line="807"/> <location filename="../atarifilesystem.cpp" line="901"/> <source>Sector read failed.</source> <translation>Sector de lectura ha fallado.</translation> </message> <message> <location filename="../atarifilesystem.cpp" line="497"/> <location filename="../atarifilesystem.cpp" line="813"/> <source>File number mismatch.</source> <translation>Número de archivo no coincide.</translation> </message> <message> <location filename="../atarifilesystem.cpp" line="551"/> <source>Cannot write to &apos;%1&apos;: %2</source> <translation>No se puede escribir &apos;%1&apos;: %2</translation> </message> <message> <location filename="../atarifilesystem.cpp" line="564"/> <location filename="../atarifilesystem.cpp" line="569"/> <location filename="../atarifilesystem.cpp" line="591"/> <location filename="../atarifilesystem.cpp" line="604"/> <location filename="../atarifilesystem.cpp" line="666"/> <location filename="../atarifilesystem.cpp" line="676"/> <location filename="../atarifilesystem.cpp" line="699"/> <location filename="../atarifilesystem.cpp" line="714"/> <location filename="../atarifilesystem.cpp" line="719"/> <location filename="../atarifilesystem.cpp" line="730"/> <location filename="../atarifilesystem.cpp" line="749"/> <location filename="../atarifilesystem.cpp" line="758"/> <location filename="../atarifilesystem.cpp" line="770"/> <location filename="../atarifilesystem.cpp" line="777"/> <source>Cannot insert &apos;%1&apos;: %2</source> <translation>No se puede insertar &apos;%1&apos;: %2</translation> </message> <message> <location filename="../atarifilesystem.cpp" line="564"/> <location filename="../atarifilesystem.cpp" line="714"/> <source>Cannot find a suitable file name.</source> <translation>No se puede encontrar un nombre de archivo adecuado.</translation> </message> <message> <location filename="../atarifilesystem.cpp" line="569"/> <location filename="../atarifilesystem.cpp" line="719"/> <source>Directory is full.</source> <translation>El disco está lleno.</translation> </message> <message> <location filename="../atarifilesystem.cpp" line="586"/> <source>Cannot open &apos;%1&apos;: %2</source> <translation>No se puede abrir &apos;%1&apos;: %2</translation> </message> <message> <location filename="../atarifilesystem.cpp" line="591"/> <location filename="../atarifilesystem.cpp" line="604"/> <location filename="../atarifilesystem.cpp" line="730"/> <location filename="../atarifilesystem.cpp" line="749"/> <source>Disk is full.</source> <translation>El disco está lleno.</translation> </message> <message> <location filename="../atarifilesystem.cpp" line="628"/> <source>File system error</source> <translation>Error del sistema de archivos</translation> </message> <message> <location filename="../atarifilesystem.cpp" line="628"/> <source>Number of bytes (%1) read from &apos;%2&apos; is not equal to expected data size of (%3)</source> <translation>Número de bytes (%1) Leer &apos;%2&apos; No es igual al tamaño de los datos de (%3)</translation> </message> <message> <location filename="../atarifilesystem.cpp" line="666"/> <location filename="../atarifilesystem.cpp" line="699"/> <location filename="../atarifilesystem.cpp" line="758"/> <location filename="../atarifilesystem.cpp" line="777"/> <location filename="../atarifilesystem.cpp" line="798"/> <location filename="../atarifilesystem.cpp" line="906"/> <source>Sector write failed.</source> <translation>Sector de escritura ha fallado.</translation> </message> <message> <location filename="../atarifilesystem.cpp" line="793"/> <location filename="../atarifilesystem.cpp" line="798"/> <location filename="../atarifilesystem.cpp" line="807"/> <location filename="../atarifilesystem.cpp" line="813"/> <location filename="../atarifilesystem.cpp" line="823"/> <location filename="../atarifilesystem.cpp" line="901"/> <location filename="../atarifilesystem.cpp" line="906"/> <location filename="../atarifilesystem.cpp" line="915"/> <source>Cannot delete &apos;%1&apos;: %2</source> <translation>No se puede eliminar &apos;%1&apos;: %2</translation> </message> <message> <location filename="../atarifilesystem.cpp" line="823"/> <location filename="../atarifilesystem.cpp" line="915"/> <source>Bitmap write failed.</source> <translation>No se puede eliminar.</translation> </message> </context> <context> <name>DriveWidget</name> <message> <location filename="../drivewidget.ui" line="29"/> <source>Frame</source> <translation>Cuadro</translation> </message> <message> <location filename="../drivewidget.ui" line="144"/> <source>1:</source> <translation></translation> </message> <message> <location filename="../drivewidget.ui" line="560"/> <source>Mount disk image...</source> <translation>Montar imagen de disco...</translation> </message> <message> <location filename="../drivewidget.ui" line="563"/> <source>Mount a disk image</source> <translation>Montar una imagen de disco</translation> </message> <message> <location filename="../drivewidget.ui" line="566"/> <source>Mount a disk image to D%1</source> <translation>Montar una imagen de disco en D%1</translation> </message> <message> <location filename="../drivewidget.ui" line="575"/> <source>Mount folder image...</source> <translation>Montar carpeta de imagen...</translation> </message> <message> <location filename="../drivewidget.ui" line="578"/> <source>Mount a folder image</source> <translation>Montar una imagen de carpeta</translation> </message> <message> <location filename="../drivewidget.ui" line="581"/> <source>Mount a folder image to D%1</source> <translation>Montar una imagen de carpeta para D%1</translation> </message> <message> <location filename="../drivewidget.ui" line="593"/> <location filename="../drivewidget.ui" line="596"/> <source>Unmount</source> <translation>Desmontar</translation> </message> <message> <location filename="../drivewidget.ui" line="599"/> <source>Unmount D%1</source> <translation>Desmontar D%1</translation> </message> <message> <location filename="../drivewidget.ui" line="615"/> <source>Write protected</source> <translation>Escritura protegida</translation> </message> <message> <location filename="../drivewidget.ui" line="618"/> <source>Toggle write protection</source> <translation>Alternar protección contra escritura</translation> </message> <message> <location filename="../drivewidget.ui" line="621"/> <source>Toggle write protection for D%1</source> <translation>Alternar protección de escritura para D%1</translation> </message> <message> <location filename="../drivewidget.ui" line="636"/> <source>Explore..</source> <translation>Explorar..</translation> </message> <message> <location filename="../drivewidget.ui" line="639"/> <source>Show properties</source> <translation>Mostrar propiedades</translation> </message> <message> <location filename="../drivewidget.ui" line="642"/> <source>Show D%1&apos;s properties</source> <translation>Mostrar las propiedades de D%1&apos;s</translation> </message> <message> <location filename="../drivewidget.ui" line="654"/> <source>Save</source> <translation>Guardar</translation> </message> <message> <location filename="../drivewidget.ui" line="657"/> <source>Save image</source> <translation>Guardar imagen</translation> </message> <message> <location filename="../drivewidget.ui" line="660"/> <source>Save D%1</source> <translation>Guardar D%1</translation> </message> <message> <location filename="../drivewidget.ui" line="672"/> <source>Revert to original</source> <translation>Volver al original</translation> </message> <message> <location filename="../drivewidget.ui" line="675"/> <source>Revert image to its last saved state</source> <translation>Revertir imagen a su último estado guardado</translation> </message> <message> <location filename="../drivewidget.ui" line="678"/> <source>Revert D%1 to its last saved state</source> <translation>Revertir D%1 a su último estado guardado</translation> </message> <message> <location filename="../drivewidget.ui" line="690"/> <source>Save as...</source> <translation>Guardar como...</translation> </message> <message> <location filename="../drivewidget.ui" line="693"/> <source>Save to a file</source> <translation>Guardar en un archivo</translation> </message> <message> <location filename="../drivewidget.ui" line="696"/> <source>Save D%1 to a file</source> <translation>Guardar D%1 en un archivo</translation> </message> <message> <location filename="../drivewidget.ui" line="714"/> <source>Auto save</source> <translation>Guardar automáticamente</translation> </message> <message> <location filename="../drivewidget.ui" line="717"/> <source>Commit changes to this disk automatically</source> <translation>Confirmar cambios en este disco automáticamente</translation> </message> <message> <location filename="../drivewidget.ui" line="720"/> <source>Toggle Auto Commit ON/OFF</source> <translation>Activar/Desactivar la activación automática</translation> </message> <message> <location filename="../drivewidget.ui" line="732"/> <source>Folder Boot Options</source> <translation>Opciones de arranque de carpeta</translation> </message> <message> <location filename="../drivewidget.ui" line="735"/> <source>Change Boot Options</source> <translation>Cambiar las opciones de arranque</translation> </message> <message> <location filename="../drivewidget.ui" line="751"/> <source>Toggle Chip/Super Archiver compatibility</source> <translation>Alternar compatibilidad Chip/Super Archiver</translation> </message> <message> <location filename="../drivewidget.ui" line="754"/> <source>Enable or disable Chip/Super Archiver compatibility. When enabled, the Chip is open</source> <translation>Habilite o deshabilite la compatibilidad Chip/Super Archiver. Cuando está habilitado, el Chip está abierto</translation> </message> <message> <location filename="../drivewidget.ui" line="770"/> <source>Toggle Happy compatibility</source> <translation>Alternar compatibilidad Happy</translation> </message> <message> <location filename="../drivewidget.ui" line="773"/> <source>Enable or disable Happy compatibility. When enabled, the drive is in Happy mode</source> <translation>Habilita o deshabilita la compatibilidad Happy. Cuando está habilitado, la unidad está en modo Happy</translation> </message> <message> <location filename="../drivewidget.ui" line="788"/> <location filename="../drivewidget.ui" line="791"/> <source>Load next software disk or side</source> <translation>Cargue el siguiente disco de software o sid</translation> </message> <message> <location filename="../drivewidget.ui" line="807"/> <source>Boot tool disk image</source> <translation>Imagen de disco de la herramienta de arranque</translation> </message> <message> <location filename="../drivewidget.ui" line="810"/> <source>Boot tool disk image the next time the Atari is powered on</source> <translation>Imagen de disco de la herramienta de arranque la próxima vez que se encienda el Atari</translation> </message> <message> <location filename="../drivewidget.ui" line="825"/> <source>Boot translator disk image</source> <translation>Imagen de disco del traductor de arranque</translation> </message> <message> <location filename="../drivewidget.ui" line="828"/> <source>Boot translator disk image the next time the Atari is powered on</source> <translation>Arrancar la imagen del disco del traductor la próxima vez que se encienda el Atari</translation> </message> </context> <context> <name>FileModel</name> <message> <location filename="../diskeditdialog.cpp" line="243"/> <source>No</source> <translation></translation> </message> <message> <location filename="../diskeditdialog.cpp" line="246"/> <source>Name</source> <translation>Nombre</translation> </message> <message> <location filename="../diskeditdialog.cpp" line="249"/> <source>Extension</source> <translation>Extensión</translation> </message> <message> <location filename="../diskeditdialog.cpp" line="252"/> <source>Size</source> <translation>Tamaño</translation> </message> <message> <location filename="../diskeditdialog.cpp" line="255"/> <source>Time</source> <translation>Hora</translation> </message> <message> <location filename="../diskeditdialog.cpp" line="258"/> <source>Notes</source> <translation>Notas</translation> </message> </context> <context> <name>FileTypes</name> <message> <location filename="../miscutils.cpp" line="111"/> <source>ATR disk image</source> <translation>Imagen de disco ATR</translation> </message> <message> <location filename="../miscutils.cpp" line="113"/> <source>gzipped ATR disk image</source> <translation>imagen de disco ATR comprimida con gzip</translation> </message> <message> <location filename="../miscutils.cpp" line="115"/> <source>XFD disk image</source> <translation>Imagen de disco XFD</translation> </message> <message> <location filename="../miscutils.cpp" line="117"/> <source>gziped XFD disk image</source> <translation>imagen de disco XFD gziped</translation> </message> <message> <location filename="../miscutils.cpp" line="119"/> <source>DCM disk image</source> <translation>Imagen de disco de DCM</translation> </message> <message> <location filename="../miscutils.cpp" line="121"/> <source>gzipped DCM disk image</source> <translation>imagen de disco de DCM comprimida con gzip</translation> </message> <message> <location filename="../miscutils.cpp" line="123"/> <source>DI disk image</source> <translation>Imagen de disco DI</translation> </message> <message> <location filename="../miscutils.cpp" line="125"/> <source>gzipped DI disk image</source> <translation>imagen de disco DI comprimida con gzip</translation> </message> <message> <location filename="../miscutils.cpp" line="127"/> <source>PRO disk image</source> <translation>Imagen de disco PRO</translation> </message> <message> <location filename="../miscutils.cpp" line="129"/> <source>gzipped PRO disk image</source> <translation>Imagen de disco PRO comprimida con gzip</translation> </message> <message> <location filename="../miscutils.cpp" line="131"/> <source>VAPI (ATX) disk image</source> <translation>Imagen de disco VAPI (ATX)</translation> </message> <message> <location filename="../miscutils.cpp" line="133"/> <source>gzipped VAPI (ATX) disk image</source> <translation>Imagen de disco VAPI (ATX) comprimida con gzip</translation> </message> <message> <location filename="../miscutils.cpp" line="135"/> <source>CAS cassette image</source> <translation>Imagen de casete CAS</translation> </message> <message> <location filename="../miscutils.cpp" line="137"/> <source>gzipped CAS cassette image</source> <translation>Imagen de casete CAS comprimida con gzip</translation> </message> <message> <location filename="../miscutils.cpp" line="139"/> <source>Atari executable</source> <translation>Ejecutable de Atari</translation> </message> <message> <location filename="../miscutils.cpp" line="141"/> <source>gzipped Atari executable</source> <translation>ejecutable de Atari comprimido con gzip</translation> </message> <message> <location filename="../miscutils.cpp" line="143"/> <source>unknown file type</source> <translation>Tipo de archivo desconocido</translation> </message> </context> <context> <name>FolderImage</name> <message> <location filename="../folderimage.cpp" line="122"/> <source>Cannot mirror &apos;%1&apos; in &apos;%2&apos;: No suitable Atari name can be found.</source> <translation>No se puede &apos;%1&apos; espejo de &apos;%2&apos;: No existe el nombre.</translation> </message> <message> <location filename="../folderimage.cpp" line="144"/> <source>Cannot mirror %1 of %2 files in &apos;%3&apos;: Atari directory is full.</source> <translation>No se puede reflejar %1 de %2 archivos en &apos;%3&apos;: Directorio está lleno.</translation> </message> <message> <location filename="../folderimage.h" line="53"/> <source>Folder image</source> <translation>Carpeta de imágenes</translation> </message> </context> <context> <name>GzFile</name> <message> <location filename="../miscutils.cpp" line="173"/> <source>gzdopen() failed.</source> <translation>gzdopen () falló.</translation> </message> <message> <location filename="../miscutils.cpp" line="200"/> <source>gzseek() failed.</source> <translation>gzseek() falló.</translation> </message> </context> <context> <name>InfoWidget</name> <message> <location filename="../infowidget.ui" line="26"/> <source>Form</source> <translation>Información</translation> </message> </context> <context> <name>LogDisplayDialog</name> <message> <location filename="../logdisplaydialog.ui" line="14"/> <source>RespeQt Log View</source> <translation>RespeQt Registro de Log</translation> </message> <message> <location filename="../logdisplaydialog.ui" line="42"/> <source>Filter log by:</source> <translation>Filtrar el registro por:</translation> </message> <message> <location filename="../logdisplaydialog.ui" line="58"/> <source>ALL</source> <translation>Todos</translation> </message> <message> <location filename="../logdisplaydialog.ui" line="63"/> <source>Disk 1</source> <translation>Disco 1</translation> </message> <message> <location filename="../logdisplaydialog.ui" line="68"/> <source>Disk 2</source> <translation>Disco 2</translation> </message> <message> <location filename="../logdisplaydialog.ui" line="73"/> <source>Disk 3</source> <translation>Disco 3</translation> </message> <message> <location filename="../logdisplaydialog.ui" line="78"/> <source>Disk 4</source> <translation>Disco 4</translation> </message> <message> <location filename="../logdisplaydialog.ui" line="83"/> <source>Disk 5</source> <translation>Disco 5</translation> </message> <message> <location filename="../logdisplaydialog.ui" line="88"/> <source>Disk 6</source> <translation>Disco 6</translation> </message> <message> <location filename="../logdisplaydialog.ui" line="93"/> <source>Disk 7</source> <translation>Disco 7</translation> </message> <message> <location filename="../logdisplaydialog.ui" line="98"/> <source>Disk 8</source> <translation>Disco 8</translation> </message> <message> <location filename="../logdisplaydialog.ui" line="103"/> <source>Disk 9</source> <translation>Disco 9</translation> </message> <message> <location filename="../logdisplaydialog.ui" line="108"/> <source>Disk 10</source> <translation>Disco 10</translation> </message> <message> <location filename="../logdisplaydialog.ui" line="113"/> <source>Disk 11</source> <translation>Disco 11</translation> </message> <message> <location filename="../logdisplaydialog.ui" line="118"/> <source>Disk 12</source> <translation>Disco 12</translation> </message> <message> <location filename="../logdisplaydialog.ui" line="123"/> <source>Disk 13</source> <translation>Disco 13</translation> </message> <message> <location filename="../logdisplaydialog.ui" line="128"/> <source>Disk 14</source> <translation>Disco 14</translation> </message> <message> <location filename="../logdisplaydialog.ui" line="133"/> <source>Disk 15</source> <translation>Disco 15</translation> </message> </context> <context> <name>MainWindow</name> <message> <location filename="../mainwindow.ui" line="169"/> <source>&amp;Disk</source> <translation>&amp;Disco</translation> </message> <message> <location filename="../mainwindow.ui" line="180"/> <source>&amp;File</source> <translation>&amp;Archivo</translation> </message> <message> <location filename="../mainwindow.ui" line="195"/> <source>&amp;Tools</source> <translation>&amp;Herramientas</translation> </message> <message> <location filename="../mainwindow.ui" line="201"/> <source>&amp;Help</source> <translation>A&amp;yuda</translation> </message> <message> <location filename="../mainwindow.ui" line="211"/> <source>Window</source> <translation>Ventana</translation> </message> <message> <location filename="../mainwindow.ui" line="236"/> <source>Unmount &amp;all</source> <translation>Desmontar &amp;todos</translation> </message> <message> <location filename="../mainwindow.ui" line="239"/> <source>Unmount all</source> <translation>Desmontar todos</translation> </message> <message> <location filename="../mainwindow.ui" line="242"/> <source>Ctrl+U</source> <translation></translation> </message> <message> <location filename="../mainwindow.ui" line="254"/> <source>&amp;Options...</source> <translation>&amp;Opciones...</translation> </message> <message> <location filename="../mainwindow.ui" line="257"/> <location filename="../mainwindow.ui" line="260"/> <source>Open options dialog</source> <translation>Abrir diálogo de opciones</translation> </message> <message> <location filename="../mainwindow.ui" line="263"/> <source>Ctrl+O</source> <translation></translation> </message> <message> <location filename="../mainwindow.ui" line="279"/> <location filename="../mainwindow.cpp" line="938"/> <source>&amp;Start emulation</source> <translation>&amp;Iniciar emulación</translation> </message> <message> <location filename="../mainwindow.ui" line="282"/> <location filename="../mainwindow.ui" line="285"/> <location filename="../mainwindow.cpp" line="939"/> <location filename="../mainwindow.cpp" line="940"/> <source>Start SIO peripheral emulation</source> <translation>Iniciar emulación periférica SIO</translation> </message> <message> <location filename="../mainwindow.ui" line="288"/> <source>Alt+E</source> <translation></translation> </message> <message> <location filename="../mainwindow.ui" line="299"/> <location filename="../mainwindow.ui" line="302"/> <source>Mount to the first available slot</source> <translation>Monte en la primera ranura disponible</translation> </message> <message> <location filename="../mainwindow.ui" line="311"/> <source>Mount &amp;disk image...</source> <translation>Montaje &amp;imagen de disco...</translation> </message> <message> <location filename="../mainwindow.ui" line="314"/> <location filename="../mainwindow.ui" line="317"/> <source>Mount a disk image to the first available slot</source> <translation>Monte una imagen de disco en la primera ranura disponible</translation> </message> <message> <location filename="../mainwindow.ui" line="320"/> <source>Ctrl+D</source> <translation></translation> </message> <message> <location filename="../mainwindow.ui" line="329"/> <source>Mount &amp;folder image...</source> <translation>Montar &amp;imagen de carpeta...</translation> </message> <message> <location filename="../mainwindow.ui" line="332"/> <location filename="../mainwindow.ui" line="335"/> <source>Mount a folder image to the first available slot</source> <translation>Monte una imagen de carpeta en la primera ranura disponible</translation> </message> <message> <location filename="../mainwindow.ui" line="338"/> <source>Ctrl+F</source> <translation></translation> </message> <message> <location filename="../mainwindow.ui" line="347"/> <source>New disk image...</source> <translation>Nueva imagen de disco...</translation> </message> <message> <location filename="../mainwindow.ui" line="350"/> <location filename="../mainwindow.ui" line="353"/> <source>Create a new disk image file and mount it to the first available slot</source> <translation>Cree un nuevo archivo de imagen de disco y móntelo en la primera ranura disponible</translation> </message> <message> <location filename="../mainwindow.ui" line="356"/> <source>Ctrl+N</source> <translation></translation> </message> <message> <location filename="../mainwindow.ui" line="368"/> <source>&amp;Save session</source> <translation>&amp;Guardar la sesión</translation> </message> <message> <location filename="../mainwindow.ui" line="371"/> <source>Save current session to a file</source> <translation>Guardar la sesión actual en un archivo</translation> </message> <message> <location filename="../mainwindow.ui" line="374"/> <source>Save current session</source> <translation>Guardar sesión actual</translation> </message> <message> <location filename="../mainwindow.ui" line="377"/> <source>Alt+S</source> <translation></translation> </message> <message> <location filename="../mainwindow.ui" line="386"/> <source>&amp;Open session...</source> <translation>&amp;Abrir Sesión...</translation> </message> <message> <location filename="../mainwindow.ui" line="389"/> <location filename="../mainwindow.ui" line="392"/> <source>Open a previously saved session</source> <translation>Abre una sesión guardada previamente</translation> </message> <message> <location filename="../mainwindow.ui" line="395"/> <source>Alt+O</source> <translation></translation> </message> <message> <location filename="../mainwindow.ui" line="404"/> <source>&amp;Boot Atari executable...</source> <translation>&amp;Inicia ejecutable Atari...</translation> </message> <message> <location filename="../mainwindow.ui" line="407"/> <location filename="../mainwindow.ui" line="410"/> <source>Boot an Atari executable</source> <translation>Inicia un ejecutable Atari</translation> </message> <message> <location filename="../mainwindow.ui" line="413"/> <source>Alt+B</source> <translation></translation> </message> <message> <location filename="../mainwindow.ui" line="431"/> <source>Save</source> <translation>Salvar</translation> </message> <message> <location filename="../mainwindow.ui" line="434"/> <location filename="../mainwindow.ui" line="437"/> <source>Save D1</source> <translation>Salvar D1</translation> </message> <message> <location filename="../mainwindow.ui" line="449"/> <location filename="../mainwindow.ui" line="452"/> <location filename="../mainwindow.ui" line="455"/> <source>Show printer text output</source> <translation>Mostrar salida de texto de impresora</translation> </message> <message> <location filename="../mainwindow.ui" line="458"/> <source>Alt+Shift+T</source> <translation></translation> </message> <message> <location filename="../mainwindow.ui" line="467"/> <source>Playback cassette image...</source> <translation>Reproducción de imagen de cassette...</translation> </message> <message> <location filename="../mainwindow.ui" line="470"/> <location filename="../mainwindow.ui" line="473"/> <source>Playback a cassette image</source> <translation>Reproducción de una imagen de cassette</translation> </message> <message> <location filename="../mainwindow.ui" line="476"/> <source>Alt+C</source> <translation></translation> </message> <message> <location filename="../mainwindow.ui" line="485"/> <source>&amp;Quit</source> <translation>&amp;Salir</translation> </message> <message> <location filename="../mainwindow.ui" line="488"/> <source>Quit RespeQt</source> <translation>Salir de RespeQt</translation> </message> <message> <location filename="../mainwindow.ui" line="491"/> <source>Alt+Q</source> <translation></translation> </message> <message> <location filename="../mainwindow.ui" line="500"/> <source>&amp;About RespeQt</source> <translation>&amp;Acerca de RespeQt</translation> </message> <message> <location filename="../mainwindow.ui" line="503"/> <source>Ctrl+A</source> <translation></translation> </message> <message> <location filename="../mainwindow.ui" line="508"/> <source>Help</source> <translation>Ayuda</translation> </message> <message> <location filename="../mainwindow.ui" line="516"/> <source>Contents</source> <translation>Contenido</translation> </message> <message> <location filename="../mainwindow.ui" line="521"/> <source>Index</source> <translation>Índice</translation> </message> <message> <location filename="../mainwindow.ui" line="533"/> <location filename="../mainwindow.ui" line="536"/> <location filename="../mainwindow.ui" line="539"/> <source>User Manual</source> <translation>Manual de usuario</translation> </message> <message> <location filename="../mainwindow.ui" line="542"/> <source>Ctrl+Shift+U</source> <translation></translation> </message> <message> <location filename="../mainwindow.ui" line="551"/> <source>Save mounted image group as default</source> <translation>Guardar el grupo de imágenes montadas como predeterminado</translation> </message> <message> <location filename="../mainwindow.ui" line="566"/> <location filename="../mainwindow.ui" line="569"/> <location filename="../mainwindow.cpp" line="895"/> <location filename="../mainwindow.cpp" line="896"/> <source>Stop printer emulation</source> <translation>Detener la emulación de la impresora</translation> </message> <message> <location filename="../mainwindow.ui" line="572"/> <source>Alt+P</source> <translation></translation> </message> <message> <location filename="../mainwindow.ui" line="581"/> <location filename="../mainwindow.cpp" line="854"/> <location filename="../mainwindow.cpp" line="855"/> <source>Hide drives D9-DO</source> <translation>Ocultar unidades de disco D9-DO</translation> </message> <message> <location filename="../mainwindow.ui" line="584"/> <source>Alt+H</source> <translation></translation> </message> <message> <location filename="../mainwindow.ui" line="593"/> <source>Toggle mini mode</source> <translation>Modo mini de ventana</translation> </message> <message> <location filename="../mainwindow.ui" line="596"/> <source>Ctrl+M</source> <translation></translation> </message> <message> <location filename="../mainwindow.ui" line="608"/> <source>Toggle shade mode</source> <translation>Cambiar modo de sombra</translation> </message> <message> <location filename="../mainwindow.ui" line="611"/> <source>Ctrl+S</source> <translation></translation> </message> <message> <location filename="../mainwindow.ui" line="620"/> <location filename="../mainwindow.ui" line="623"/> <location filename="../mainwindow.ui" line="626"/> <source>Open log window</source> <translation>Abrir ventana de log</translation> </message> <message> <location filename="../mainwindow.ui" line="629"/> <source>Ctrl+L</source> <translation></translation> </message> <message> <location filename="../mainwindow.cpp" line="149"/> <source>RespeQt started at %1.</source> <translation>RespeQt comenzó en %1.</translation> </message> <message> <location filename="../mainwindow.cpp" line="228"/> <location filename="../mainwindow.cpp" line="238"/> <source>Session file error</source> <translation>Error de archivo de sesión</translation> </message> <message> <location filename="../mainwindow.cpp" line="229"/> <source>Requested session file not found in the given directory path or the path is incorrect. RespeQt will continue with default session configuration.</source> <translation>El archivo de sesión solicitado no se encuentra en la ruta del directorio dado o la ruta es incorrecta. RespeQt continuará con la configuración de sesión predeterminada.</translation> </message> <message> <location filename="../mainwindow.cpp" line="239"/> <source>Requested session file not found in the application&apos;s current directory path (No path was specified). RespeQt will continue with default session configuration.</source> <translation>El archivo de sesión solicitado no se encuentra en la ruta del directorio actual de la aplicación (No se especificó ninguna ruta). RespeQt continuará con la configuración de sesión predeterminada.</translation> </message> <message> <location filename="../mainwindow.cpp" line="250"/> <source>RespeQt - Atari Serial Peripheral Emulator for Qt</source> <translation>RespeQt - Atari Serial Peripheral Emulator para Qt</translation> </message> <message> <location filename="../mainwindow.cpp" line="252"/> <location filename="../mainwindow.cpp" line="1897"/> <source> -- Session: </source> <translation> -- Sesión: </translation> </message> <message> <location filename="../mainwindow.cpp" line="265"/> <source>19200 bits/sec</source> <translation></translation> </message> <message> <location filename="../mainwindow.cpp" line="272"/> <source>Clear messages</source> <translation>Eliminar mensajes</translation> </message> <message> <location filename="../mainwindow.cpp" line="291"/> <source>Record SIO traffic</source> <translation>Registro de tráfico SIO</translation> </message> <message> <location filename="../mainwindow.cpp" line="301"/> <source>Connected to the network via: </source> <translation>Conectado a la red a través de: </translation> </message> <message> <location filename="../mainwindow.cpp" line="305"/> <source>No network connection</source> <translation>No hay conexion de red</translation> </message> <message> <location filename="../mainwindow.cpp" line="373"/> <source>RespeQt stopped at %1.</source> <translation>RespeQt se detuvo en %1.</translation> </message> <message> <location filename="../mainwindow.cpp" line="543"/> <source>Swapped disk %1 with disk %2.</source> <translation>Disco intercambiado %1 con disco %2.</translation> </message> <message> <location filename="../mainwindow.cpp" line="597"/> <source>Cannot mount &apos;%1&apos;: No empty disk slots.</source> <translation>No puede montar &apos;%1&apos;: No hay ranuras de disco vacías.</translation> </message> <message> <location filename="../mainwindow.cpp" line="693"/> <source>First run</source> <translation>Primer intento</translation> </message> <message> <location filename="../mainwindow.cpp" line="694"/> <source>You are running RespeQt for the first time. Do you want to open the options dialog?</source> <translation>Está ejecutando RespeQt por primera vez. ṡQuieres abrir el diálogo de opciones?</translation> </message> <message> <location filename="../mainwindow.cpp" line="859"/> <location filename="../mainwindow.cpp" line="860"/> <source>Show drives D9-DO</source> <translation>Mostrar unidades D9-DO</translation> </message> <message> <location filename="../mainwindow.cpp" line="884"/> <source>Printer emulation stopped.</source> <translation>La emulación de la impresora se detuvo.</translation> </message> <message> <location filename="../mainwindow.cpp" line="888"/> <source>Printer emulation started.</source> <translation>Emulación de la impresora iniciada.</translation> </message> <message> <location filename="../mainwindow.cpp" line="900"/> <location filename="../mainwindow.cpp" line="901"/> <source>Start printer emulation</source> <translation>Iniciar la emulación de la impresora</translation> </message> <message> <location filename="../mainwindow.cpp" line="922"/> <source>&amp;Stop emulation</source> <translation>&amp;Detener la emulación</translation> </message> <message> <location filename="../mainwindow.cpp" line="923"/> <location filename="../mainwindow.cpp" line="924"/> <source>Stop SIO peripheral emulation</source> <translation>Detener la emulación periférica SIO</translation> </message> <message> <location filename="../mainwindow.cpp" line="950"/> <source>Emulation stopped.</source> <translation>La emulación se detuvo.</translation> </message> <message> <location filename="../mainwindow.cpp" line="973"/> <location filename="../mainwindow.cpp" line="993"/> <source>Folder image</source> <translation>Imagen de carpeta</translation> </message> <message> <location filename="../mainwindow.cpp" line="1006"/> <location filename="../mainwindow.cpp" line="1620"/> <location filename="../mainwindow.cpp" line="1683"/> <location filename="../mainwindow.cpp" line="1722"/> <source>Save failed</source> <translation>Error al guardar</translation> </message> <message> <location filename="../mainwindow.cpp" line="1007"/> <location filename="../mainwindow.cpp" line="1620"/> <location filename="../mainwindow.cpp" line="1683"/> <location filename="../mainwindow.cpp" line="1722"/> <source>&apos;%1&apos; cannot be saved, do you want to save the image with another name?</source> <translation>&apos;%1&apos; no se puede guardar, ṡdesea guardar la imagen con otro nombre?</translation> </message> <message> <location filename="../mainwindow.cpp" line="1267"/> <source>Unmounted disk %1</source> <translation>Disco %1 desmontado</translation> </message> <message> <location filename="../mainwindow.cpp" line="1435"/> <source>Bad cast for PCLINK</source> <translation>Cast incorrecto para PCLINK</translation> </message> <message> <location filename="../mainwindow.cpp" line="1453"/> <location filename="../mainwindow.cpp" line="1867"/> <source>[%1] Mounted &apos;%2&apos; as &apos;%3&apos;.</source> <translation>[%1] Montado &apos;%2&apos; como &apos;%3&apos;.</translation> </message> <message> <location filename="../mainwindow.cpp" line="1487"/> <source>Open a disk image</source> <translation>Abrir una imagen de disco</translation> </message> <message> <location filename="../mainwindow.cpp" line="1489"/> <location filename="../mainwindow.cpp" line="1706"/> <source>All Atari disk images (*.atr *.xfd *.atx *.pro);;SIO2PC ATR images (*.atr);;XFormer XFD images (*.xfd);;ATX images (*.atx);;Pro images (*.pro);;All files (*)</source> <translation>Todas las imágenes de disco de Atari (*.atr *.xfd *.pro);;Imágenes de SIO2PC ATR (*.atr);;Imágenes de XFormer XFD (*.xfd);;Imágenes PRO (*.pro);;Todos los archivos (*)</translation> </message> <message> <location filename="../mainwindow.cpp" line="1508"/> <source>Open a folder image</source> <translation>Abrir una imagen de carpeta</translation> </message> <message> <location filename="../mainwindow.cpp" line="1579"/> <source>Image file unsaved</source> <translation>Archivo de imagen no guardado</translation> </message> <message> <location filename="../mainwindow.cpp" line="1579"/> <source>&apos;%1&apos; has unsaved changes, do you want to save it?</source> <translation>&apos;%1&apos; tiene cambios no guardados, ṡquieres guardarlo?</translation> </message> <message> <location filename="../mainwindow.cpp" line="1672"/> <source>[Disk %1] Auto-commit ON.</source> <translation>[Disco %1] Activar automáticamente.</translation> </message> <message> <location filename="../mainwindow.cpp" line="1674"/> <source>[Disk %1] Auto-commit OFF.</source> <translation>[Disco %1] Desactivada automáticamente.</translation> </message> <message> <location filename="../mainwindow.cpp" line="1704"/> <source>Save image as</source> <translation>Guardar imagen como</translation> </message> <message> <location filename="../mainwindow.cpp" line="1740"/> <source>Revert to last saved</source> <translation>Volver al último guardado</translation> </message> <message> <location filename="../mainwindow.cpp" line="1741"/> <source>Do you really want to revert &apos;%1&apos; to its last saved state? You will lose the changes that has been made.</source> <translation>ṡRealmente desea revertir &apos;%1&apos; a su ultimo estado guardado? Perderás los cambios que se hayan realizado.</translation> </message> <message> <location filename="../mainwindow.cpp" line="1876"/> <source>Open session</source> <translation>Abrir session</translation> </message> <message> <location filename="../mainwindow.cpp" line="1878"/> <location filename="../mainwindow.cpp" line="1914"/> <source>RespeQt sessions (*.respeqt);;All files (*)</source> <translation>Sesiones de RespeQt (*.respeqt);;Todos los archivos (*)</translation> </message> <message> <location filename="../mainwindow.cpp" line="1912"/> <source>Save session as</source> <translation>Guardar sesión como</translation> </message> <message> <location filename="../mainwindow.cpp" line="1935"/> <source>Open executable</source> <translation>Abrir Ejecutable</translation> </message> <message> <location filename="../mainwindow.cpp" line="1937"/> <source>Atari executables (*.xex *.com *.exe);;All files (*)</source> <translation>Ejecutables Atari (*.xex *.com *.exe);;Todos los archivos (*)</translation> </message> <message> <location filename="../mainwindow.cpp" line="1955"/> <source>Open a cassette image</source> <translation>Abrir una imagen de cassette</translation> </message> <message> <location filename="../mainwindow.cpp" line="1957"/> <source>CAS images (*.cas);;All files (*)</source> <translation>Imágenes CAS (*.cas);;Todos los archivos (*)</translation> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../optionsdialog.ui" line="23"/> <source>Options</source> <translation>Opciones</translation> </message> <message> <location filename="../optionsdialog.ui" line="51"/> <source>1</source> <translation></translation> </message> <message> <location filename="../optionsdialog.ui" line="56"/> <source>Serial I/O backends</source> <translation>Serial E/S backends</translation> </message> <message> <location filename="../optionsdialog.ui" line="63"/> <source>Standard serial port</source> <translation>Puerto serial estandar</translation> </message> <message> <location filename="../optionsdialog.ui" line="71"/> <source>AtariSIO</source> <translation></translation> </message> <message> <location filename="../optionsdialog.ui" line="79"/> <source>Test Backend</source> <translation>Probar backend</translation> </message> <message> <location filename="../optionsdialog.ui" line="88"/> <location filename="../optionsdialog.ui" line="674"/> <source>Emulation</source> <translation>Emulación</translation> </message> <message> <location filename="../optionsdialog.ui" line="93"/> <source>Disk images</source> <translation>Imágenes de disco</translation> </message> <message> <location filename="../optionsdialog.ui" line="100"/> <location filename="../optionsdialog.ui" line="980"/> <source>Image options</source> <translation>Opciones de imagen</translation> </message> <message> <location filename="../optionsdialog.ui" line="105"/> <location filename="../optionsdialog.ui" line="2130"/> <source>OS-B emulation</source> <translation>Emulación OS-B</translation> </message> <message> <location filename="../optionsdialog.ui" line="110"/> <source>Icon visibility</source> <translation>Visibilidad del icono</translation> </message> <message> <location filename="../optionsdialog.ui" line="115"/> <location filename="../optionsdialog.ui" line="2344"/> <source>Favorite tool disk</source> <translation>Disco de herramientas favorito</translation> </message> <message> <location filename="../optionsdialog.ui" line="121"/> <source>User interface</source> <translation>Interfaz de usuario</translation> </message> <message> <location filename="../optionsdialog.ui" line="126"/> <source>Printer emulation</source> <translation>Emulación de impresora</translation> </message> <message> <location filename="../optionsdialog.ui" line="133"/> <location filename="../optionsdialog.ui" line="1192"/> <source>Printer fixed width font</source> <translation>Fuente de ancho fijo para impresora</translation> </message> <message> <location filename="../optionsdialog.ui" line="138"/> <location filename="../optionsdialog.ui" line="1261"/> <source>Passthrough settings</source> <translation>Configuración de paso a través</translation> </message> <message> <location filename="../optionsdialog.ui" line="143"/> <location filename="../optionsdialog.ui" line="2480"/> <source>Printer protocol</source> <translation>Protocolo de impresora</translation> </message> <message> <location filename="../optionsdialog.ui" line="148"/> <source>1020 emulation options</source> <translation>1020 opciones de emulación</translation> </message> <message> <location filename="../optionsdialog.ui" line="191"/> <source>Standard serial port backend options</source> <translation>Opciones de backend de puerto serie estándar</translation> </message> <message> <location filename="../optionsdialog.ui" line="200"/> <location filename="../optionsdialog.ui" line="487"/> <location filename="../optionsdialog.ui" line="593"/> <source>Use this backend</source> <translation>Usa este backend</translation> </message> <message> <location filename="../optionsdialog.ui" line="219"/> <source>Port name:</source> <translation>Nombre del puerto:</translation> </message> <message> <location filename="../optionsdialog.ui" line="235"/> <location filename="../optionsdialog.ui" line="520"/> <source>Handshake method:</source> <translation>Método Handshake:</translation> </message> <message> <location filename="../optionsdialog.ui" line="243"/> <location filename="../optionsdialog.ui" line="528"/> <source>RI</source> <translation></translation> </message> <message> <location filename="../optionsdialog.ui" line="248"/> <location filename="../optionsdialog.ui" line="533"/> <source>DSR</source> <translation></translation> </message> <message> <location filename="../optionsdialog.ui" line="253"/> <location filename="../optionsdialog.ui" line="538"/> <source>CTS</source> <translation></translation> </message> <message> <location filename="../optionsdialog.ui" line="258"/> <source>NONE</source> <translation>Ninguna</translation> </message> <message> <location filename="../optionsdialog.ui" line="263"/> <source>SOFTWARE (SIO2BT)</source> <translation>Porgrama (SIO2BT)</translation> </message> <message> <location filename="../optionsdialog.ui" line="271"/> <source>Trigger on falling edge</source> <translation>Gatillo en el borde de caída</translation> </message> <message> <location filename="../optionsdialog.ui" line="278"/> <source>DTR Control Enable</source> <translation>Habilitar control DTR</translation> </message> <message> <location filename="../optionsdialog.ui" line="294"/> <source>Write delay [ms]:</source> <translation>Retraso de escritura [ms]:</translation> </message> <message> <location filename="../optionsdialog.ui" line="308"/> <source>0</source> <translation></translation> </message> <message> <location filename="../optionsdialog.ui" line="313"/> <source>10</source> <translation></translation> </message> <message> <location filename="../optionsdialog.ui" line="318"/> <source>20</source> <translation></translation> </message> <message> <location filename="../optionsdialog.ui" line="323"/> <source>30</source> <translation></translation> </message> <message> <location filename="../optionsdialog.ui" line="328"/> <source>40</source> <translation></translation> </message> <message> <location filename="../optionsdialog.ui" line="333"/> <source>50</source> <translation></translation> </message> <message> <location filename="../optionsdialog.ui" line="338"/> <source>60</source> <translation></translation> </message> <message> <location filename="../optionsdialog.ui" line="352"/> <source>High speed mode baud rate:</source> <translation>Velocidad de transmisión en modo de alta velocidad:</translation> </message> <message> <location filename="../optionsdialog.ui" line="363"/> <source>19200 (1x)</source> <translation></translation> </message> <message> <location filename="../optionsdialog.ui" line="368"/> <source>38400 (2x)</source> <translation></translation> </message> <message> <location filename="../optionsdialog.ui" line="373"/> <source>57600 (3x)</source> <translation></translation> </message> <message> <location filename="../optionsdialog.ui" line="381"/> <source>Use non-standard speeds</source> <translation>Utilice velocidades no estándar</translation> </message> <message> <location filename="../optionsdialog.ui" line="397"/> <source>High speed mode POKEY divisor:</source> <translation>Modo de alta velocidad divisor POKEY:</translation> </message> <message> <location filename="../optionsdialog.ui" line="417"/> <source>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;Complete/Error response delay (μs)&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</source> <translation>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;Retraso de respuesta completo/error (μs)&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</translation> </message> <message> <location filename="../optionsdialog.ui" line="424"/> <source>μs</source> <translation></translation> </message> <message> <location filename="../optionsdialog.ui" line="478"/> <source>AtariSIO backend options</source> <translation>Opciones de backend AtariSIO</translation> </message> <message> <location filename="../optionsdialog.ui" line="500"/> <source>Device name:</source> <translation>Nombre del dispositivo:</translation> </message> <message> <location filename="../optionsdialog.ui" line="507"/> <source>/dev/atarisio0</source> <translation></translation> </message> <message> <location filename="../optionsdialog.ui" line="584"/> <source>Test backend options</source> <translation>Prueba las opciones de backend</translation> </message> <message> <location filename="../optionsdialog.ui" line="605"/> <source>File</source> <translation>Archivo</translation> </message> <message> <location filename="../optionsdialog.ui" line="618"/> <source>Select test file</source> <translation>Seleccionar archivo de prueba</translation> </message> <message> <location filename="../optionsdialog.ui" line="702"/> <source>CAPITAL letters in file names</source> <translation>Letras mayúsculas en nombres de archivos</translation> </message> <message> <location filename="../optionsdialog.ui" line="721"/> <source>Filter out underscore character from file names</source> <translation>Filtrar el carácter de subrayado de los nombres de archivo</translation> </message> <message> <location filename="../optionsdialog.ui" line="742"/> <source> (Required for AtariDOS compatibility)</source> <translation> (Requerido para compatibilidad con AtariDOS)</translation> </message> <message> <location filename="../optionsdialog.ui" line="765"/> <source>PCLINK:</source> <translation></translation> </message> <message> <location filename="../optionsdialog.ui" line="783"/> <source>Folder Images:</source> <translation>Imágenes de carpeta:</translation> </message> <message> <location filename="../optionsdialog.ui" line="802"/> <source>Use custom baud rate for cassette emulation</source> <translation>Utilice la velocidad de transmisión personalizada para la emulación de cassette</translation> </message> <message> <location filename="../optionsdialog.ui" line="809"/> <source>Smart Device:</source> <translation>Dispositivo inteligente:</translation> </message> <message> <location filename="../optionsdialog.ui" line="832"/> <source>URL Submit</source> <translation>Enviar URL</translation> </message> <message> <location filename="../optionsdialog.ui" line="845"/> <source>Use high speed executable loader</source> <translation>Utilice un cargador ejecutable de alta velocidad</translation> </message> <message> <location filename="../optionsdialog.ui" line="894"/> <source>RCL client local path</source> <translation>Ruta local del cliente RCL</translation> </message> <message> <location filename="../optionsdialog.ui" line="942"/> <source>Try to restart emulation when SIO connection is lost</source> <translation>Intente reiniciar la emulación cuando se pierda la conexión SIO</translation> </message> <message> <location filename="../optionsdialog.ui" line="986"/> <source>Display SIO protocol (ACK, NAK,...)</source> <translation>Mostrar el protocolo SIO (ACK, NAK, ...)</translation> </message> <message> <location filename="../optionsdialog.ui" line="993"/> <location filename="../optionsdialog.ui" line="2499"/> <source>Display data frames (spy mode)</source> <translation>Mostrar marcos de datos (modo espía)</translation> </message> <message> <location filename="../optionsdialog.ui" line="1000"/> <source>Display uploaded code disassembly</source> <translation>Mostrar el desmontaje del código cargado</translation> </message> <message> <location filename="../optionsdialog.ui" line="1007"/> <source>Display track layout of protected disks</source> <translation>Mostrar diseño de pista de discos protegidos</translation> </message> <message> <location filename="../optionsdialog.ui" line="1027"/> <source>Display command name of empty drive slots</source> <translation>Mostrar nombre de comando de ranuras de unidad vacías</translation> </message> <message> <location filename="../optionsdialog.ui" line="1062"/> <source>User inteface</source> <translation>Interfaz de usuario</translation> </message> <message> <location filename="../optionsdialog.ui" line="1068"/> <source>Language:</source> <translation>Idioma:</translation> </message> <message> <location filename="../optionsdialog.ui" line="1078"/> <source>Minimize to system tray</source> <translation>Minimizar a la bandeja del sistema</translation> </message> <message> <location filename="../optionsdialog.ui" line="1085"/> <source>Save window positions and sizes</source> <translation>Guardar posiciones y tamaños de ventanas</translation> </message> <message> <location filename="../optionsdialog.ui" line="1124"/> <source>Save D9-DO drive visibility status</source> <translation>Guardar el estado de visibilidad de la unidad D9-DO</translation> </message> <message> <location filename="../optionsdialog.ui" line="1137"/> <source>Use larger font in drive slot descriptions</source> <translation>Utilice una fuente más grande en las descripciones de las ranuras de la unidad</translation> </message> <message> <location filename="../optionsdialog.ui" line="1147"/> <source>Enable Shade in Mini Mode by default</source> <translation>Habilitar sombra en modo mini de forma predeterminada</translation> </message> <message> <location filename="../optionsdialog.ui" line="1160"/> <source>Use native menu bar</source> <translation>Usar la barra de menú nativa</translation> </message> <message> <location filename="../optionsdialog.ui" line="1212"/> <source>Font selection</source> <translation>Selección de fuentes</translation> </message> <message> <location filename="../optionsdialog.ui" line="1225"/> <source>TextLabel</source> <translation></translation> </message> <message> <location filename="../optionsdialog.ui" line="1240"/> <source>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. </source> <translation></translation> </message> <message> <location filename="../optionsdialog.ui" line="1267"/> <source>Raw output device</source> <translation>Dispositivo de salida sin procesar</translation> </message> <message> <location filename="../optionsdialog.ui" line="1307"/> <source>810 firmware path</source> <translation>810 ruta de firmware</translation> </message> <message> <location filename="../optionsdialog.ui" line="1313"/> <source>Atari 810 Happy firmware path:</source> <translation>Ruta del firmware Atari 810 Happy:</translation> </message> <message> <location filename="../optionsdialog.ui" line="1334"/> <source>Atari 810 Chip firmware path:</source> <translation>Ruta del firmware del chip Atari 810:</translation> </message> <message> <location filename="../optionsdialog.ui" line="1361"/> <source>Atari 810 firmware path:</source> <translation>Ruta del firmware del Atari 810:</translation> </message> <message> <location filename="../optionsdialog.ui" line="1442"/> <source>1050 firmware path</source> <translation>1050 ruta de firmware</translation> </message> <message> <location filename="../optionsdialog.ui" line="1448"/> <source>Atari 1050 Turbo firmware path:</source> <translation>Ruta del firmware de Atari 1050 Turbo:</translation> </message> <message> <location filename="../optionsdialog.ui" line="1455"/> <source>Atari 1050 Duplicator firmware path:</source> <translation>Ruta del firmware de la duplicadora Atari 1050:</translation> </message> <message> <location filename="../optionsdialog.ui" line="1495"/> <source>Atari 1050 firmware path:</source> <translation>Ruta del firmware de Atari 1050:</translation> </message> <message> <location filename="../optionsdialog.ui" line="1509"/> <source>Atari 1050 Archiver firmware path:</source> <translation>Ruta del firmware del archivador Atari 1050:</translation> </message> <message> <location filename="../optionsdialog.ui" line="1523"/> <source>Atari 1050 Happy firmware path:</source> <translation>Ruta del firmware Atari 1050 Happy:</translation> </message> <message> <location filename="../optionsdialog.ui" line="1530"/> <source>Atari 1050 Speedy firmware path:</source> <translation>Ruta del firmware Atari 1050 Speedy:</translation> </message> <message> <location filename="../optionsdialog.ui" line="1676"/> <source>Firmware emulation</source> <translation>Emulación de firmware</translation> </message> <message> <location filename="../optionsdialog.ui" line="1682"/> <source>Modifications in this panel are applied when a</source> <translation>Las modificaciones en este panel se aplican cuando un</translation> </message> <message> <location filename="../optionsdialog.ui" line="1689"/> <source>disk image is loaded in one of the first 4 drives</source> <translation>La imagen del disco se carga en una de las primeras 4 unidades</translation> </message> <message> <location filename="../optionsdialog.ui" line="1697"/> <location filename="../optionsdialog.ui" line="1785"/> <location filename="../optionsdialog.ui" line="1839"/> <location filename="../optionsdialog.ui" line="1893"/> <source>SIO command emulation (default)</source> <translation>Emulación de comando SIO (predeterminada)</translation> </message> <message> <location filename="../optionsdialog.ui" line="1702"/> <location filename="../optionsdialog.ui" line="1790"/> <location filename="../optionsdialog.ui" line="1844"/> <location filename="../optionsdialog.ui" line="1898"/> <source>Atari 810 firmware</source> <translation>Firmware del Atari 810</translation> </message> <message> <location filename="../optionsdialog.ui" line="1707"/> <location filename="../optionsdialog.ui" line="1795"/> <location filename="../optionsdialog.ui" line="1849"/> <location filename="../optionsdialog.ui" line="1903"/> <source>Atari 810 with the Chip firmware</source> <translation>Atari 810 con el firmware de chip</translation> </message> <message> <location filename="../optionsdialog.ui" line="1712"/> <location filename="../optionsdialog.ui" line="1800"/> <location filename="../optionsdialog.ui" line="1854"/> <location filename="../optionsdialog.ui" line="1908"/> <source>Atari 810 with Happy firmware</source> <translation>Atari 810 con firmware Happy</translation> </message> <message> <location filename="../optionsdialog.ui" line="1717"/> <location filename="../optionsdialog.ui" line="1805"/> <location filename="../optionsdialog.ui" line="1859"/> <location filename="../optionsdialog.ui" line="1913"/> <source>Atari 1050 firmware</source> <translation>Firmware de Atari 1050</translation> </message> <message> <location filename="../optionsdialog.ui" line="1722"/> <location filename="../optionsdialog.ui" line="1810"/> <location filename="../optionsdialog.ui" line="1864"/> <location filename="../optionsdialog.ui" line="1918"/> <source>Atari 1050 with the Archiver firmware</source> <translation>Atari 1050 con el firmware Archiver</translation> </message> <message> <location filename="../optionsdialog.ui" line="1727"/> <location filename="../optionsdialog.ui" line="1815"/> <location filename="../optionsdialog.ui" line="1869"/> <location filename="../optionsdialog.ui" line="1923"/> <source>Atari 1050 with Happy firmware</source> <translation>Atari 1050 con firmware Happy</translation> </message> <message> <location filename="../optionsdialog.ui" line="1732"/> <location filename="../optionsdialog.ui" line="1820"/> <location filename="../optionsdialog.ui" line="1874"/> <location filename="../optionsdialog.ui" line="1928"/> <source>Atari 1050 with Speedy firmware</source> <translation>Atari 1050 con firmware Speedy</translation> </message> <message> <location filename="../optionsdialog.ui" line="1737"/> <location filename="../optionsdialog.ui" line="1825"/> <location filename="../optionsdialog.ui" line="1879"/> <location filename="../optionsdialog.ui" line="1933"/> <source>Atari 1050 with Turbo firmware</source> <translation>Atari 1050 con firmware Turbo</translation> </message> <message> <location filename="../optionsdialog.ui" line="1742"/> <location filename="../optionsdialog.ui" line="1830"/> <location filename="../optionsdialog.ui" line="1884"/> <location filename="../optionsdialog.ui" line="1938"/> <source>Atari 1050 with Duplicator firmware</source> <translation>Atari 1050 con firmware duplicador</translation> </message> <message> <location filename="../optionsdialog.ui" line="1750"/> <source>Power on D3 with disk inserted</source> <translation>Encienda D3 con el disco insertado</translation> </message> <message> <location filename="../optionsdialog.ui" line="1757"/> <source>Power on D2 with disk inserted</source> <translation>Encienda D2 con el disco insertado</translation> </message> <message> <location filename="../optionsdialog.ui" line="1764"/> <source>Power on D4 with disk inserted</source> <translation>Encienda D4 con el disco insertado</translation> </message> <message> <location filename="../optionsdialog.ui" line="1777"/> <source>D2:</source> <translation></translation> </message> <message> <location filename="../optionsdialog.ui" line="1952"/> <source>D3:</source> <translation></translation> </message> <message> <location filename="../optionsdialog.ui" line="1978"/> <source>D1:</source> <translation></translation> </message> <message> <location filename="../optionsdialog.ui" line="1991"/> <source>D4</source> <translation></translation> </message> <message> <location filename="../optionsdialog.ui" line="1998"/> <source>Power on D1 with disk inserted</source> <translation>Encienda D1 con el disco insertado</translation> </message> <message> <location filename="../optionsdialog.ui" line="2038"/> <source>Trace options</source> <translation>Opciones de seguimiento</translation> </message> <message> <location filename="../optionsdialog.ui" line="2044"/> <source>Display ID addess marks</source> <translation>Marcas de dirección de ID de pantalla</translation> </message> <message> <location filename="../optionsdialog.ui" line="2064"/> <source>Trace CPU execution in this file:</source> <translation>Rastree la ejecución de la CPU en este archivo:</translation> </message> <message> <location filename="../optionsdialog.ui" line="2071"/> <source>Display drive head position</source> <translation>Mostrar la posición del cabezal de accionamiento</translation> </message> <message> <location filename="../optionsdialog.ui" line="2085"/> <source>Display index pulse</source> <translation>Pulso de índice de visualización</translation> </message> <message> <location filename="../optionsdialog.ui" line="2092"/> <source>Display track information</source> <translation>Mostrar información de la pista</translation> </message> <message> <location filename="../optionsdialog.ui" line="2099"/> <source>Display FDC commands</source> <translation>Mostrar comandos FDC</translation> </message> <message> <location filename="../optionsdialog.ui" line="2106"/> <source>Display motor On/Off</source> <translation>Motor de visualización encendido/apagado</translation> </message> <message> <location filename="../optionsdialog.ui" line="2136"/> <source>Detect [OS-B] and boot the translator disk</source> <translation>Detecta [OS-B] y arranca el disco traductor</translation> </message> <message> <location filename="../optionsdialog.ui" line="2198"/> <source>Translator disk to use with [OS-B] disk images</source> <translation>Disco traductor para usar con imágenes de disco [OS-B]</translation> </message> <message> <location filename="../optionsdialog.ui" line="2205"/> <source>With this option active, RespeQt will detect [OS-B] in</source> <translation>Con esta opción activa, RespeQt detectará [OS-B] en</translation> </message> <message> <location filename="../optionsdialog.ui" line="2212"/> <source>a disk image filename and will automatically boot a</source> <translation>Un nombre de archivo de imagen de disco y automáticamente arrancará un</translation> </message> <message> <location filename="../optionsdialog.ui" line="2219"/> <source>translator disk before booting the chosen disk image.</source> <translation>Disco traductor antes de iniciar la imagen de disco elegida.</translation> </message> <message> <location filename="../optionsdialog.ui" line="2226"/> <source>NOTE: this option applies only to slot D1:</source> <translation>NOTA: esta opción se aplica solo a la ranura D1:</translation> </message> <message> <location filename="../optionsdialog.ui" line="2250"/> <source>Icon visibility in drive slots</source> <translation>Visibilidad de iconos en las ranuras de disco</translation> </message> <message> <location filename="../optionsdialog.ui" line="2256"/> <source>Hide Next image icon</source> <translation>Ocultar icono de imagen siguiente</translation> </message> <message> <location filename="../optionsdialog.ui" line="2263"/> <source>Hide OS-B mode icon</source> <translation>Ocultar el icono del modo OS-B</translation> </message> <message> <location filename="../optionsdialog.ui" line="2270"/> <source>Hide Chip mode icon</source> <translation>Ocultar icono del modo Chip</translation> </message> <message> <location filename="../optionsdialog.ui" line="2277"/> <source>Hide Happy mode icon</source> <translation>Ocultar icono del modo Happy</translation> </message> <message> <location filename="../optionsdialog.ui" line="2284"/> <source>Hide Tool disk icon</source> <translation>Ocultar icono de disco de herramientas</translation> </message> <message> <location filename="../optionsdialog.ui" line="2320"/> <source>These features can still be toggled with contextual menu.</source> <translation>Estas funciones aún se pueden alternar con el menú contextual.</translation> </message> <message> <location filename="../optionsdialog.ui" line="2366"/> <source>Tool disk image to boot when the favorite icon is active</source> <translation>Imagen del disco de la herramienta para arrancar cuando el icono de favorito está activo</translation> </message> <message> <location filename="../optionsdialog.ui" line="2389"/> <source>The favorite tool disk is a disk image to boot before the</source> <translation>El disco de herramientas favorito es una imagen de disco para arrancar antes de</translation> </message> <message> <location filename="../optionsdialog.ui" line="2396"/> <source>selected disk image in slot D1:. For example, you can</source> <translation>imagen de disco seleccionada en la ranura D1 :. Por ejemplo, puedes</translation> </message> <message> <location filename="../optionsdialog.ui" line="2429"/> <source>have your favorite copier always ready with this option.</source> <translation>ten siempre lista tu copiador favorito con esta opción.</translation> </message> <message> <location filename="../optionsdialog.ui" line="2449"/> <source>Activate Happy mode when booting this disk</source> <translation>Activa el modo Happy al arrancar este disco</translation> </message> <message> <location filename="../optionsdialog.ui" line="2456"/> <source>Activate Chip mode when booting this disk</source> <translation>Active el modo Chip al arrancar este disco</translation> </message> <message> <location filename="../optionsdialog.ui" line="2523"/> <source>1020 Options</source> <translation>1020 Opciones</translation> </message> <message> <location filename="../optionsdialog.ui" line="2529"/> <source>Clear Graphics when a STATUS command is received</source> <translation>Gráficos claros cuando se recibe un comando STATUS</translation> </message> <message> <location filename="../optionsdialog.ui" line="2549"/> <source>Display the Graphics instructions in the log window</source> <translation>Mostrar las instrucciones gráficas en la ventana de registro</translation> </message> <message> <location filename="../optionsdialog.ui" line="2567"/> <source>Save/Commit or Cancel/Ignore changes made to the settings</source> <translation>Guardar/Confirmar o Cancelar/Ignorar los cambios realizados en la configuración</translation> </message> <message> <location filename="../optionsdialog.ui" line="2585"/> <source>Select Atari 810 firmware...</source> <translation>Seleccione el firmware Atari 810...</translation> </message> <message> <location filename="../optionsdialog.ui" line="2588"/> <location filename="../optionsdialog.cpp" line="436"/> <source>Select Atari 810 firmware</source> <translation>Seleccione el firmware Atari 810</translation> </message> <message> <location filename="../optionsdialog.ui" line="2591"/> <location filename="../optionsdialog.ui" line="2606"/> <location filename="../optionsdialog.ui" line="2621"/> <location filename="../optionsdialog.ui" line="2636"/> <location filename="../optionsdialog.ui" line="2651"/> <location filename="../optionsdialog.ui" line="2666"/> <location filename="../optionsdialog.ui" line="2681"/> <location filename="../optionsdialog.ui" line="2696"/> <location filename="../optionsdialog.ui" line="2711"/> <source>Mount a folder image to D%1</source> <translation>Montar una imagen de carpeta para D%1</translation> </message> <message> <location filename="../optionsdialog.ui" line="2600"/> <source>Select Atari 810 Chip firmware...</source> <translation>Seleccione el firmware del chip Atari 810...</translation> </message> <message> <location filename="../optionsdialog.ui" line="2603"/> <location filename="../optionsdialog.cpp" line="441"/> <source>Select Atari 810 Chip firmware</source> <translation>Seleccione el firmware del chip Atari 810</translation> </message> <message> <location filename="../optionsdialog.ui" line="2615"/> <source>Select Atari 810 Happy firmware...</source> <translation>Seleccione el firmware Atari 810 Happy...</translation> </message> <message> <location filename="../optionsdialog.ui" line="2618"/> <location filename="../optionsdialog.cpp" line="446"/> <source>Select Atari 810 Happy firmware</source> <translation>Seleccione el firmware Atari 810 Happy</translation> </message> <message> <location filename="../optionsdialog.ui" line="2630"/> <source>Select Atari 1050 firmware...</source> <translation>Seleccione el firmware Atari 1050...</translation> </message> <message> <location filename="../optionsdialog.ui" line="2633"/> <location filename="../optionsdialog.cpp" line="451"/> <source>Select Atari 1050 firmware</source> <translation>Seleccione el firmware Atari 1050</translation> </message> <message> <location filename="../optionsdialog.ui" line="2645"/> <source>Select Atari 1050 Archiver firmware...</source> <translation>Seleccione el firmware del archivador Atari 1050...</translation> </message> <message> <location filename="../optionsdialog.ui" line="2648"/> <location filename="../optionsdialog.cpp" line="456"/> <source>Select Atari 1050 Archiver firmware</source> <translation>Seleccione el firmware del archivador Atari 1050</translation> </message> <message> <location filename="../optionsdialog.ui" line="2660"/> <source>Select Atari 1050 Happy firmware...</source> <translation>Seleccione el firmware Atari 1050 Happy...</translation> </message> <message> <location filename="../optionsdialog.ui" line="2663"/> <location filename="../optionsdialog.cpp" line="461"/> <source>Select Atari 1050 Happy firmware</source> <translation>Seleccione el firmware Atari 1050 Happy</translation> </message> <message> <location filename="../optionsdialog.ui" line="2675"/> <source>Select Atari 1050 Speedy firmware...</source> <translation>Seleccione el firmware Atari 1050 Speedy...</translation> </message> <message> <location filename="../optionsdialog.ui" line="2678"/> <location filename="../optionsdialog.cpp" line="466"/> <source>Select Atari 1050 Speedy firmware</source> <translation>Seleccione el firmware Atari 1050 Speedy</translation> </message> <message> <location filename="../optionsdialog.ui" line="2690"/> <source>Select Atari 1050 Turbo firmware...</source> <translation>Seleccione el firmware Atari 1050 Turbo...</translation> </message> <message> <location filename="../optionsdialog.ui" line="2693"/> <location filename="../optionsdialog.cpp" line="471"/> <source>Select Atari 1050 Turbo firmware</source> <translation>Seleccione el firmware Atari 1050 Turbo</translation> </message> <message> <location filename="../optionsdialog.ui" line="2705"/> <source>Select Atari 1050 Duplicator firmware...</source> <translation>Seleccione el firmware de la duplicadora Atari 1050...</translation> </message> <message> <location filename="../optionsdialog.ui" line="2708"/> <location filename="../optionsdialog.cpp" line="476"/> <source>Select Atari 1050 Duplicator firmware</source> <translation>Seleccione el firmware de la duplicadora Atari 1050</translation> </message> <message> <location filename="../optionsdialog.ui" line="2720"/> <location filename="../optionsdialog.ui" line="2723"/> <location filename="../optionsdialog.cpp" line="481"/> <source>Select translator disk image</source> <translation>Seleccione la imagen del disco del traductor</translation> </message> <message> <location filename="../optionsdialog.ui" line="2726"/> <source>Select translator disk image to D%1</source> <translation>Seleccione la imagen del disco del traductor a D%1</translation> </message> <message> <location filename="../optionsdialog.ui" line="2735"/> <location filename="../optionsdialog.ui" line="2738"/> <location filename="../optionsdialog.cpp" line="486"/> <source>Select tool disk image</source> <translation>Seleccionar imagen de disco de herramientas</translation> </message> <message> <location filename="../optionsdialog.ui" line="2741"/> <source>Select tool disk image to D%1</source> <translation>Seleccione la imagen del disco de la herramienta en D%1</translation> </message> <message> <location filename="../optionsdialog.cpp" line="77"/> <source>Custom</source> <translation>Personalizado</translation> </message> <message> <location filename="../optionsdialog.cpp" line="151"/> <source>Automatic</source> <translation>Automático</translation> </message> <message> <location filename="../optionsdialog.cpp" line="154"/> <location filename="../optionsdialog.cpp" line="163"/> <source>English</source> <translation>Inglés</translation> </message> <message> <location filename="../optionsdialog.cpp" line="436"/> <location filename="../optionsdialog.cpp" line="441"/> <location filename="../optionsdialog.cpp" line="446"/> <location filename="../optionsdialog.cpp" line="451"/> <location filename="../optionsdialog.cpp" line="456"/> <location filename="../optionsdialog.cpp" line="461"/> <location filename="../optionsdialog.cpp" line="466"/> <location filename="../optionsdialog.cpp" line="471"/> <location filename="../optionsdialog.cpp" line="476"/> <source>Atari drive firmware (*.rom);;All files (*)</source> <translation>Firmware de la unidad Atari (*.rom);;Todos los archivos (*)</translation> </message> <message> <location filename="../optionsdialog.cpp" line="481"/> <location filename="../optionsdialog.cpp" line="486"/> <source>Atari disk image (*.atr);;All files (*)</source> <translation>Imagen de disco de Atari (*.atr);;Todos los archivos (*)</translation> </message> <message> <location filename="../optionsdialog.cpp" line="493"/> <source>Open test XML File</source> <translation>Abrir archivo XML de prueba</translation> </message> <message> <location filename="../optionsdialog.cpp" line="493"/> <source>XML Files (*.xml)</source> <translation>Archivos XML (*.xml)</translation> </message> <message> <location filename="../optionsdialog.cpp" line="505"/> <source>Select Atari fixed width font</source> <translation>Seleccione la fuente de ancho fijo Atari</translation> </message> <message> <location filename="../optionsdialog.cpp" line="519"/> <source>Selec RCL image folder</source> <translation>Seleccionar carpeta de imágenes RCL</translation> </message> </context> <context> <name>PCLINK</name> <message> <location filename="../pclink.cpp" line="181"/> <source>PCLINK Command=[$%1] aux1=$%2 aux2=$%3 cunit=$%4</source> <translation>PCLINK Comando=[$%1] aux1=$%2 aux2=$%3 cunit=$%4</translation> </message> <message> <location filename="../pclink.cpp" line="193"/> <source>[%1] P</source> <translation></translation> </message> <message> <location filename="../pclink.cpp" line="200"/> <source>[%1] R</source> <translation></translation> </message> <message> <location filename="../pclink.cpp" line="218"/> <source>[%1] Get status for [%2]</source> <translation>[%1] Obtener estado para [%2]</translation> </message> <message> <location filename="../pclink.cpp" line="229"/> <source>[%1] Speed poll</source> <translation>[%1] Encuesta de velocidad</translation> </message> <message> <location filename="../pclink.cpp" line="236"/> <source>[%1] command: $%2, aux: $%3 NAKed.</source> <translation>[%1] comando: $%2, aux: $%3 NAKed.</translation> </message> <message> <location filename="../pclink.cpp" line="269"/> <source>PCLINK[%1] Mount %2</source> <translation>PCLINK[%1] Montar %2</translation> </message> <message> <location filename="../pclink.cpp" line="311"/> <source>PCLINK[%1] Unmount</source> <translation>PCLINK[%1] Desmontar</translation> </message> <message> <location filename="../pclink.cpp" line="464"/> <source>match: %1%2%3%4%5%6%7%8%9%10%11 with %12%13%14%15%16%17%18%19%20%21%22: </source> <translation>Coincidencia: %1%2%3%4%5%6%7%8%9%10%11 con %12%13%14%15%16%17%18%19%20%21%22: </translation> </message> <message> <location filename="../pclink.cpp" line="477"/> <source>no match</source> <translation>Sin coincidencia</translation> </message> <message> <location filename="../pclink.cpp" line="488"/> <source>atr mismatch: not HIDDEN or ARCHIVED</source> <translation>Desajuste ATR: no OCULTO o ARCHIVADO</translation> </message> <message> <location filename="../pclink.cpp" line="496"/> <source>atr mismatch: not PROTECTED</source> <translation>No coincidencia ATR: no está PROTEGIDO</translation> </message> <message> <location filename="../pclink.cpp" line="505"/> <source>atr mismatch: not UNPROTECTED</source> <translation>Desajuste ATR: no DESPROTECTADO</translation> </message> <message> <location filename="../pclink.cpp" line="514"/> <source>atr mismatch: not SUBDIR</source> <translation>No coincidencia ATR: no SUBDIR</translation> </message> <message> <location filename="../pclink.cpp" line="523"/> <source>atr mismatch: not FILE</source> <translation>No coincidencia ATR: no archivo</translation> </message> <message> <location filename="../pclink.cpp" line="528"/> <source>match</source> <translation>Coincidencia</translation> </message> <message> <location filename="../pclink.cpp" line="593"/> <source>%1: got fname &apos;%2&apos;</source> <translation>%1: tiene nombre &apos;%2&apos;</translation> </message> <message> <location filename="../pclink.cpp" line="601"/> <source>%1: stat &apos;%2&apos;</source> <translation>%1: estado &apos;%2&apos;</translation> </message> <message> <location filename="../pclink.cpp" line="611"/> <source>&apos;%1&apos;: is a symlink</source> <translation>&apos;%1&apos;: es un enlace simbólico</translation> </message> <message> <location filename="../pclink.cpp" line="615"/> <source>&apos;%1&apos;: can&apos;t be accessed</source> <translation>&apos;%1&apos;: no se puede acceder</translation> </message> <message> <location filename="../pclink.cpp" line="616"/> <source>access error code %1</source> <translation>Código de error de acceso %1</translation> </message> <message> <location filename="../pclink.cpp" line="713"/> <source>Internal error: dir_cache should be nullptr!</source> <translation>Error interno: dir_cache debe ser NULL!</translation> </message> <message> <location filename="../pclink.cpp" line="844"/> <source>closing all files</source> <translation>Cerrando todos los archivos</translation> </message> <message> <location filename="../pclink.cpp" line="1120"/> <source>&apos;P&apos; WRONG DATA FRAME, expected size %1 got %2</source> <translation>&apos;P&apos; MARCO DE DATOS INCORRECTO, tamaño esperado %1 obtenido %2</translation> </message> <message> <location filename="../pclink.cpp" line="1138"/> <source>PARBLK retry, ignored</source> <translation>Reintento de PARBLK, ignorado</translation> </message> <message> <location filename="../pclink.cpp" line="1152"/> <source>%1 (fno $%02)</source> <translation></translation> </message> <message> <location filename="../pclink.cpp" line="1166"/> <source>bad handle 1 %1</source> <translation>Mal manejo 1 %1</translation> </message> <message> <location filename="../pclink.cpp" line="1173"/> <location filename="../pclink.cpp" line="1308"/> <source>bad size $0000 (0)</source> <translation>Mal tamaño $ 0000 (0)</translation> </message> <message> <location filename="../pclink.cpp" line="1193"/> <source>size $%1 (%2), buffer $%3 (%4)</source> <translation>tamaño $%1 (%2), buffer $%3 (%4)</translation> </message> <message> <location filename="../pclink.cpp" line="1204"/> <location filename="../pclink.cpp" line="1324"/> <location filename="../pclink.cpp" line="1481"/> <location filename="../pclink.cpp" line="1641"/> <source>serial communication error, abort</source> <translation>error de comunicación serie, abortar</translation> </message> <message> <location filename="../pclink.cpp" line="1210"/> <location filename="../pclink.cpp" line="1330"/> <location filename="../pclink.cpp" line="1498"/> <location filename="../pclink.cpp" line="1576"/> <source>handle %1</source> <translation>encargarse de %1</translation> </message> <message> <location filename="../pclink.cpp" line="1227"/> <source>FREAD: cannot read %1 bytes from dir</source> <translation>FREAD: no puede leer %1 bytes de dir</translation> </message> <message> <location filename="../pclink.cpp" line="1244"/> <source>FREAD: cannot seek to $%1 (%2)</source> <translation>FREAD: no se puede buscar a $%1 (%2)</translation> </message> <message> <location filename="../pclink.cpp" line="1253"/> <source>FREAD: cannot read %1 bytes from file</source> <translation>FREAD: no puede leer %1 bytes del archivo</translation> </message> <message> <location filename="../pclink.cpp" line="1281"/> <source>FREAD: send $%1 (%2), status $%3</source> <translation>FREAD: enviar $%1 (%2), estado $%3</translation> </message> <message> <location filename="../pclink.cpp" line="1301"/> <source>bad handle 2 %1</source><|fim▁hole|> <message> <location filename="../pclink.cpp" line="1316"/> <source>size $%1 (%2)</source> <translation>Tamaño $%1 (%2)</translation> </message> <message> <location filename="../pclink.cpp" line="1336"/> <source>FWRITE: cannot seek to $%1 (%2)</source> <translation>FWRITE: no se puede buscar %1 (%2)</translation> </message> <message> <location filename="../pclink.cpp" line="1349"/> <source>FWRITE: block CRC mismatch</source> <translation>FWRITE: bloque CRC no coinciden</translation> </message> <message> <location filename="../pclink.cpp" line="1375"/> <source>FWRITE: cannot write %1 bytes to file</source> <translation>FWRITE: no se pueden escribir %1 bytes en el archivo</translation> </message> <message> <location filename="../pclink.cpp" line="1386"/> <source>FWRITE: received $%1 (%2), status $%3</source> <translation>FWRITE: recibió $%1 (%2), estado $%3</translation> </message> <message> <location filename="../pclink.cpp" line="1398"/> <source>bad handle 3 %1</source> <translation>handle malo 3 %1</translation> </message> <message> <location filename="../pclink.cpp" line="1406"/> <location filename="../pclink.cpp" line="1565"/> <location filename="../pclink.cpp" line="1603"/> <location filename="../pclink.cpp" line="1946"/> <location filename="../pclink.cpp" line="2055"/> <location filename="../pclink.cpp" line="2134"/> <location filename="../pclink.cpp" line="2224"/> <location filename="../pclink.cpp" line="2298"/> <location filename="../pclink.cpp" line="2382"/> <location filename="../pclink.cpp" line="2579"/> <source>bad exec</source> <translation>Mala ejecución</translation> </message> <message> <location filename="../pclink.cpp" line="1413"/> <source>handle %1, newpos $%2 (%3)</source> <translation></translation> </message> <message> <location filename="../pclink.cpp" line="1437"/> <source>bad handle 4 %1</source> <translation>handle malo 4 %1</translation> </message> <message> <location filename="../pclink.cpp" line="1444"/> <location filename="../pclink.cpp" line="1474"/> <location filename="../pclink.cpp" line="2509"/> <source>device $%1</source> <translation>Dispositivo $%1</translation> </message> <message> <location filename="../pclink.cpp" line="1455"/> <source>handle %1, send $%2 (%3)</source> <translation>handle %1, enviar $%2 (%3)</translation> </message> <message> <location filename="../pclink.cpp" line="1491"/> <source>bad handle 5 %1</source> <translation>handle malo 5 %1</translation> </message> <message> <location filename="../pclink.cpp" line="1508"/> <source>eof_flg %1</source> <translation></translation> </message> <message> <location filename="../pclink.cpp" line="1527"/> <source>FNEXT: EOF</source> <translation></translation> </message> <message> <location filename="../pclink.cpp" line="1537"/> <source>FNEXT: status %1, send $%2 $%3%4 $%5%6%7 %8%9%10%11%12%13%14%15%16%17%18 %19-%20-%21 %22:%23:%24</source> <translation>FNEXT: estado %1, enviar $%2 $%3%4 $%5%6%7 %8%9%10%11%12%13%14%15%16%17%18 %19-%20-%21 %22:%23:%24</translation> </message> <message> <location filename="../pclink.cpp" line="1571"/> <source>bad handle 6 %1</source> <translation>handle malo 6 %1</translation> </message> <message> <location filename="../pclink.cpp" line="1619"/> <source>mode: $%1, atr1: $%2, atr2: $%3, path: &apos;%4&apos;, name: &apos;%5&apos;</source> <translation>Modo: $%1, atr1: $%2, atr2: $%3, ruta: &apos;%4&apos;, nombre: &apos;%5&apos;</translation> </message> <message> <location filename="../pclink.cpp" line="1653"/> <source>unsupported fmode ($%1)</source> <translation>Modo no compatible ($%1)</translation> </message> <message> <location filename="../pclink.cpp" line="1662"/> <source>invalid path 1 &apos;%1&apos;</source> <translation>Ruta no válida 1 &apos;%1&apos;</translation> </message> <message> <location filename="../pclink.cpp" line="1667"/> <location filename="../pclink.cpp" line="2068"/> <source>local path &apos;%1&apos;</source> <translation>Ruta de acceso local &apos;%1&apos;</translation> </message> <message> <location filename="../pclink.cpp" line="1676"/> <source>FOPEN: too many channels open</source> <translation>FOPEN: Demasiados canales abiertos</translation> </message> <message> <location filename="../pclink.cpp" line="1683"/> <location filename="../pclink.cpp" line="1779"/> <source>FOPEN: cannot stat &apos;%1&apos;</source> <translation>FOPEN: No se puede iniciar &apos;%1&apos;</translation> </message> <message> <location filename="../pclink.cpp" line="1697"/> <source> ! fmode &amp; 0x10</source> <translation></translation> </message> <message> <location filename="../pclink.cpp" line="1736"/> <source>FOPEN: file not found</source> <translation>FOPEN: Archivo no encontrado</translation> </message> <message> <location filename="../pclink.cpp" line="1746"/> <source>FOPEN: creating file</source> <translation>FOPEN: Creando archivo</translation> </message> <message> <location filename="../pclink.cpp" line="1753"/> <source>FOPEN: bad filename &apos;%1&apos;</source> <translation>FOPEN: Mal nombre de archivo &apos;%1&apos;</translation> </message> <message> <location filename="../pclink.cpp" line="1773"/> <source>FOPEN: full local path &apos;%1&apos;</source> <translation>FOPEN: Ruta de acceso local completa &apos;%1&apos;</translation> </message> <message> <location filename="../pclink.cpp" line="1790"/> <source>FOPEN: &apos;%1&apos; is read-only</source> <translation>FOPEN: &apos;%1&apos; es de solo lectura</translation> </message> <message> <location filename="../pclink.cpp" line="1820"/> <source>FOPEN: cannot open &apos;%1&apos;, %2 (%3)</source> <translation>FOPEN: No se puede abrir &apos;%1&apos;, %2 (%3)</translation> </message> <message> <location filename="../pclink.cpp" line="1859"/> <source>FOPEN: bad handle 7 %1</source> <translation>FOPEN: Mal handle 7 %1</translation> </message> <message> <location filename="../pclink.cpp" line="1869"/> <source>FOPEN: %1 handle %2</source> <translation>FOPEN: %1 encargarse de %2</translation> </message> <message> <location filename="../pclink.cpp" line="1882"/> <source>FOPEN: dir EOF?</source> <translation>FOPEN: Final de directorio?</translation> </message> <message> <location filename="../pclink.cpp" line="1914"/> <source>FOPEN: send %1, send $%2 $%3%4 $%5%6%7 %8%9%10%11%12%13%14%15%16%17%18 %19-%20-%21 %22:%23:%24</source> <translation>FOPEN: enviar %1, enviar $%2 $%3%4 $%5%6%7 %8%9%10%11%12%13%14%15%16%17%18 %19-%20-%21 %22:%23:%24</translation> </message> <message> <location filename="../pclink.cpp" line="1954"/> <source>invalid path 2 &apos;%1&apos;</source> <translation>Ruta inválida 2 &apos;%1&apos;</translation> </message> <message> <location filename="../pclink.cpp" line="1963"/> <location filename="../pclink.cpp" line="2074"/> <source>cannot open dir &apos;%1&apos;</source> <translation>No se puede abrir el directorio &apos;%1&apos;</translation> </message> <message> <location filename="../pclink.cpp" line="1968"/> <source>local path &apos;%1&apos;, fatr1 $%2</source> <translation>Ruta de acceso local &apos;%1&apos;, fatr1 $%2</translation> </message> <message> <location filename="../pclink.cpp" line="2021"/> <source>RENAME: renaming &apos;%1&apos; -&gt; &apos;%2&apos;</source> <translation>RENAME: Cambio de nombre &apos;%1&apos; -&gt; &apos;%2&apos;</translation> </message> <message> <location filename="../pclink.cpp" line="2025"/> <source>RENAME: &apos;%1&apos; already exists</source> <translation>RENAME: &apos;%1&apos; Ya existe</translation> </message> <message> <location filename="../pclink.cpp" line="2032"/> <source>RENAME: %1</source> <translation>RENAME: %1</translation> </message> <message> <location filename="../pclink.cpp" line="2063"/> <source>invalid path 3 &apos;%1&apos;</source> <translation>Ruta inválida 3 &apos;%1&apos;</translation> </message> <message> <location filename="../pclink.cpp" line="2107"/> <source>REMOVE: delete &apos;%1&apos;</source> <translation>REMOVE: Borrar &apos;%1&apos;</translation> </message> <message> <location filename="../pclink.cpp" line="2110"/> <source>REMOVE: cannot delete &apos;%1&apos;</source> <translation>REMOVE: No se puede borrar &apos;%1&apos;</translation> </message> <message> <location filename="../pclink.cpp" line="2140"/> <source>illegal fatr2 $%1</source> <translation>fatr2 ilegal $%1</translation> </message> <message> <location filename="../pclink.cpp" line="2149"/> <source>invalid path 4 &apos;%1&apos;</source> <translation>Ruta inválida 4 &apos;%1&apos;</translation> </message> <message> <location filename="../pclink.cpp" line="2154"/> <source>local path &apos;%1&apos;, fatr1 $%2 fatr2 $%3</source> <translation>Ruta de acceso local &apos;%1&apos;, fatr1 $%2 fatr2 $%3</translation> </message> <message> <location filename="../pclink.cpp" line="2161"/> <source>CHMOD: cannot open dir &apos;%1&apos;</source> <translation>CHMOD: No se puede abrir el directorio &apos;%1&apos;</translation> </message> <message> <location filename="../pclink.cpp" line="2193"/> <source>CHMOD: change atrs in &apos;%1&apos;</source> <translation>CHMOD: Cambiar permiso en &apos;%1&apos;</translation> </message> <message> <location filename="../pclink.cpp" line="2202"/> <source>CHMOD: failed on &apos;%1&apos;</source> <translation>CHMOD: falla en &apos;%1&apos;</translation> </message> <message> <location filename="../pclink.cpp" line="2232"/> <source>invalid path 5 &apos;%1&apos;</source> <translation>ruta inválida 5 apos;%1&apos;</translation> </message> <message> <location filename="../pclink.cpp" line="2242"/> <location filename="../pclink.cpp" line="2316"/> <source>bad dir name &apos;%1&apos;</source> <translation>Mal nombre de directorio &apos;%1&apos;</translation> </message> <message> <location filename="../pclink.cpp" line="2256"/> <source>making dir &apos;%1&apos;, time %2-%3-%4 %5:%6:%7</source> <translation>Haciendo directorio &apos;%1&apos;, fecha %2-%3-%4 %5:%6:%7</translation> </message> <message> <location filename="../pclink.cpp" line="2261"/> <source>MKDIR: &apos;%1&apos; already exists</source> <translation>MKDIR: &apos;%1&apos; Ya existe</translation> </message> <message> <location filename="../pclink.cpp" line="2272"/> <source>MKDIR: cannot make dir &apos;%1&apos;</source> <translation>MKDIR: No se puede hacer el directorio &apos;%1&apos;</translation> </message> <message> <location filename="../pclink.cpp" line="2306"/> <source>invalid path 6 &apos;%1&apos;</source> <translation>ruta no válida 6 &apos;%1&apos;</translation> </message> <message> <location filename="../pclink.cpp" line="2330"/> <source>cannot stat &apos;%1&apos;</source> <translation>No se puede empezar &apos;%1&apos;</translation> </message> <message> <location filename="../pclink.cpp" line="2338"/> <source>&apos;%1&apos; can&apos;t be accessed</source> <translation>&apos;%1&apos; No se puede acceder</translation> </message> <message> <location filename="../pclink.cpp" line="2346"/> <source>&apos;%1&apos; is not a directory</source> <translation>&apos;%1&apos; No es un directorio</translation> </message> <message> <location filename="../pclink.cpp" line="2353"/> <source>dir &apos;%1&apos; is write-protected</source> <translation>Directorio &apos;%1&apos; protegido contra escritura</translation> </message> <message> <location filename="../pclink.cpp" line="2358"/> <source>delete dir &apos;%1&apos;</source> <translation>Eliminar directorio &apos;%1&apos;</translation> </message> <message> <location filename="../pclink.cpp" line="2364"/> <source>RMDIR: cannot del &apos;%1&apos;, %2 (%3)</source> <translation>RMDIR: No se puede borrar &apos;%1&apos;, %2 (%3)</translation> </message> <message> <location filename="../pclink.cpp" line="2390"/> <source>invalid path 7 &apos;%1&apos;</source> <translation>Ruta no válida 7 &apos;%1&apos;</translation> </message> <message> <location filename="../pclink.cpp" line="2399"/> <source>cannot access &apos;%1&apos;, %2</source> <translation>No puede acceder apos;%1&apos;, %2</translation> </message> <message> <location filename="../pclink.cpp" line="2424"/> <source>new current dir &apos;%1&apos;</source> <translation>Nuevo directorio actual &apos;%1&apos;</translation> </message> <message> <location filename="../pclink.cpp" line="2442"/> <source>device $1</source> <translation>Dispositivo $1</translation> </message> <message> <location filename="../pclink.cpp" line="2462"/> <source>send &apos;%1&apos;</source> <translation>Enviando &apos;%1&apos;</translation> </message> <message> <location filename="../pclink.cpp" line="2523"/> <source>reading &apos;%1&apos;</source> <translation>Leyendo &apos;%1&apos;</translation> </message> <message> <location filename="../pclink.cpp" line="2558"/> <source>DFREE: send info (%1 bytes)</source> <translation>DFREE: Enviar información (%1 bytes)</translation> </message> <message> <location filename="../pclink.cpp" line="2587"/> <source>invalid name</source> <translation>Nombre inválido</translation> </message> <message> <location filename="../pclink.cpp" line="2596"/> <source>writing &apos;%1&apos;</source> <translation>Escritura &apos;%1&apos;</translation> </message> <message> <location filename="../pclink.cpp" line="2616"/> <source>CHVOL: %1</source> <translation></translation> </message> <message> <location filename="../pclink.cpp" line="2622"/> <source>fno $%1 not implemented</source> <translation>fno $%1 no se ha implementado</translation> </message> </context> <context> <name>PrinterWidget</name> <message> <location filename="../printerwidget.ui" line="29"/> <source>Frame</source> <translation>Cuadro</translation> </message> <message> <location filename="../printerwidget.ui" line="144"/> <source>1:</source> <translation></translation> </message> <message> <location filename="../printerwidget.ui" line="239"/> <source>Disconnect</source> <translation>Desconectar</translation> </message> <message> <location filename="../printerwidget.ui" line="242"/> <source>Disconnect Printer</source> <translation>Desconecte la impresora</translation> </message> <message> <location filename="../printerwidget.ui" line="245"/> <source>Unmount D%1</source> <translation>Desmontar D%1</translation> </message> <message> <location filename="../printerwidget.ui" line="254"/> <source>Connect</source> <translation>Conectar</translation> </message> <message> <location filename="../printerwidget.ui" line="257"/> <source>Connect Printer</source> <translation>Conectar impresora</translation> </message> <message> <location filename="../printerwidget.cpp" line="54"/> <location filename="../printerwidget.cpp" line="75"/> <location filename="../printerwidget.cpp" line="110"/> <location filename="../printerwidget.cpp" line="134"/> <source>None</source> <translation>Ninguna</translation> </message> <message> <location filename="../printerwidget.cpp" line="168"/> <source>Printers</source> <translation>Impresoras</translation> </message> <message> <location filename="../printerwidget.cpp" line="168"/> <source>Please select an output device as well as a printer emulation.</source> <translation>Seleccione un dispositivo de salida y una emulación de impresora.</translation> </message> <message> <location filename="../printerwidget.cpp" line="185"/> <source>Printer emulation</source> <translation>Emulación de impresora</translation> </message> <message> <location filename="../printerwidget.cpp" line="185"/> <source>You are not allowed to use the passthrough emulation without an raw output.</source> <translation>No se le permite utilizar la emulación de paso a través sin una salida sin procesar.</translation> </message> <message> <location filename="../printerwidget.cpp" line="196"/> <source>Beginning output</source> <translation>Salida inicial</translation> </message> <message> <location filename="../printerwidget.cpp" line="196"/> <source>The output device couldn&apos;t start.</source> <translation>No se pudo iniciar el dispositivo de salida.</translation> </message> </context> <context> <name>Printers::Atari1020</name> <message> <location filename="../printers/atari1020.cpp" line="92"/> <source>[%1] Get status: $%2</source> <translation>[%1] Obtener el estado: $%2</translation> </message> <message> <location filename="../printers/atari1020.cpp" line="127"/> <source>[%1] Print: data frame failed</source> <translation>[%1] Imprimir: el marco de datos falló</translation> </message> <message> <location filename="../printers/atari1020.cpp" line="137"/> <source>[%1] Print (%2 chars)</source> <translation>[%1] Imprimir (%2 caracteres)</translation> </message> <message> <location filename="../printers/atari1020.cpp" line="146"/> <source>[%1] command: $%2, aux: $%3 NAKed.</source> <translation>[%1] commando: $%2, aux: $%3 NAKed.</translation> </message> <message> <location filename="../printers/atari1020.cpp" line="152"/> <source>[%1] ignored</source> <translation>[%1] ignorado</translation> </message> <message> <location filename="../printers/atari1020.cpp" line="241"/> <source>[%1] Escape character repeated</source> <translation>[%1] Carácter de escape repetido</translation> </message> <message> <location filename="../printers/atari1020.cpp" line="249"/> <source>[%1] Entering international mode</source> <translation>[%1] Entrar en modo internacional</translation> </message> <message> <location filename="../printers/atari1020.cpp" line="257"/> <source>[%1] Exiting international mode</source> <translation>[%1] Saliendo del modo internacional</translation> </message> <message> <location filename="../printers/atari1020.cpp" line="274"/> <source>[%1] Escape character not on start of line</source> <translation>[%1] El carácter de escape no está al principio de la línea</translation> </message> <message> <location filename="../printers/atari1020.cpp" line="282"/> <source>[%1] Enter Graphics mode</source> <translation>[%1] Entrar en el modo de gráficos</translation> </message> <message> <location filename="../printers/atari1020.cpp" line="292"/> <source>[%1] Switch to 40 columns</source> <translation>[%1] Cambiar a 40 columnas</translation> </message> <message> <location filename="../printers/atari1020.cpp" line="300"/> <source>[%1] Switch to 20 columns</source> <translation>[%1] Cambiar a 20 columnas</translation> </message> <message> <location filename="../printers/atari1020.cpp" line="308"/> <source>[%1] Switch to 80 columns</source> <translation>[%1] Cambiar a 80 columnas</translation> </message> <message> <location filename="../printers/atari1020.cpp" line="316"/> <source>[%1] Enter international mode</source> <translation>[%1] Entrar en modo internacional</translation> </message> <message> <location filename="../printers/atari1020.cpp" line="324"/> <source>[%1] Exit international mode</source> <translation>[%1] Salir del modo internacional</translation> </message> <message> <location filename="../printers/atari1020.cpp" line="332"/> <source>[%1] Unknown control code $%2</source> <translation>[%1] Código de control desconocido $%2</translation> </message> <message> <location filename="../printers/atari1020.cpp" line="410"/> <source>[%1] Unknown Graphics command $%2</source> <translation>[%1] Comando de gráficos desconocido $%2</translation> </message> <message> <location filename="../printers/atari1020.cpp" line="548"/> <source>[%1] Exit Graphics mode</source> <translation>[%1] Salir del modo de gráficos</translation> </message> <message> <location filename="../printers/atari1020.cpp" line="555"/> <source>[%1] Move to Home</source> <translation>[%1] Mover al inicio</translation> </message> <message> <location filename="../printers/atari1020.cpp" line="569"/> <source>[%1] Scale characters to %2</source> <translation>[%1] Escalar caracteres a%2</translation> </message> <message> <location filename="../printers/atari1020.cpp" line="575"/> <source>[%1] Scale command ignored (%2 should be in range 0-63)</source> <translation>[%1] Comando de escala ignorado (%2 debe estar en el rango 0-63)</translation> </message> <message> <location filename="../printers/atari1020.cpp" line="608"/> <source>[%1] Set color to %2</source> <translation>[%1] Establecer el color en %2</translation> </message> <message> <location filename="../printers/atari1020.cpp" line="615"/> <source>[%1] Set color command ignored (%2 should be in range 0-3)</source> <translation>[%1] Se ignora el comando establecer color (%2 debe estar en el rango 0-3)</translation> </message> <message> <location filename="../printers/atari1020.cpp" line="628"/> <source>[%1] Set line mode to %2</source> <translation>[%1] Establecer el modo de línea en %2</translation> </message> <message> <location filename="../printers/atari1020.cpp" line="630"/> <source>solid</source> <translation>sólida</translation> </message> <message> <location filename="../printers/atari1020.cpp" line="630"/> <source>dashed %1</source> <translation>punteado %1</translation> </message> <message> <location filename="../printers/atari1020.cpp" line="642"/> <source>[%1] Set line mode command ignored (%2 should be in range 0-15)</source> <translation>[%1] Se ignora el comando de modo de línea de configuración (%2 debe estar en el rango 0-15)</translation> </message> <message> <location filename="../printers/atari1020.cpp" line="652"/> <source>[%1] Initialize plotter</source> <translation>[%1] Inicializar trazador</translation> </message> <message> <location filename="../printers/atari1020.cpp" line="679"/> <source>[%1] Draw to point (%2,%3)</source> <translation>[%1] Dibujar al punto (%2,%3)</translation> </message> <message> <location filename="../printers/atari1020.cpp" line="691"/> <source>[%1] Draw relative to point (%2,%3)</source> <translation>[%1] Dibujar en relación con el punto (%2,%3)</translation> </message> <message> <location filename="../printers/atari1020.cpp" line="701"/> <source>[%1] Move to point (%2,%3)</source> <translation>[%1] Mover al punto (%2,%3)</translation> </message> <message> <location filename="../printers/atari1020.cpp" line="711"/> <source>[%1] Move relative to point (%2,%3)</source> <translation>[%1] Mover en relación con el punto (%2,%3)</translation> </message> <message> <location filename="../printers/atari1020.cpp" line="731"/> <source>[%1] Draw X-axis with size %2 and %3 marks</source> <translation>[%1] Dibujar el eje X con marcas de tamaño %2 y %3</translation> </message> <message> <location filename="../printers/atari1020.cpp" line="738"/> <source>[%1] Draw Y-axis with size %2 and %3 marks</source> <translation>[%1] Dibujar el eje Y con marcas de tamaño %2 y %3</translation> </message> <message> <location filename="../printers/atari1020.cpp" line="755"/> <source>[%1] Set text orientation to %2°</source> <translation>[%1] Establecer la orientación del texto en %2°</translation> </message> <message> <location filename="../printers/atari1020.cpp" line="761"/> <source>[%1] Set text orientation command ignored (%2 should be in range 0-3)</source> <translation>[%1] Se ignora el comando de configuración de la orientación del texto (%2 debe estar en el rango 0-3)</translation> </message> <message> <location filename="../printers/atari1020.cpp" line="772"/> <source>[%1] Print &apos;%2&apos; in Graphics mode</source> <translation>[%1] Impresión &apos;%2&apos; en modo Gráficos</translation> </message> </context> <context> <name>Printers::BasePrinter</name> <message> <location filename="../printers/baseprinter.cpp" line="43"/> <source>[%1] Get status: $%2</source> <translation>[%1] Obtener estado: $%2</translation> </message> <message> <location filename="../printers/baseprinter.cpp" line="70"/> <source>[%1] Command: $%2, aux: $%3 NAKed because aux2 is not supported</source> <translation>[%1] Comando: $%2, aux: $%3 NAKed porque aux2 no es compatible</translation> </message> <message> <location filename="../printers/baseprinter.cpp" line="82"/> <source>[%1] Print: data frame failed</source> <translation>[%1] Impresión: error en el marco de datos</translation> </message> <message> <location filename="../printers/baseprinter.cpp" line="92"/> <source>[%1] Print (%2 chars)</source> <translation>[%1] Imprimir (%2 caracteres)</translation> </message> <message> <location filename="../printers/baseprinter.cpp" line="98"/> <source>[%1] command: $%2, aux: $%3 NAKed.</source> <translation>[%1] comando: $%2, aux: $%3 NAKed.</translation> </message> <message> <location filename="../printers/baseprinter.cpp" line="104"/> <source>[%1] ignored</source> <translation>[%1] ignorado</translation> </message> <message> <location filename="../printers/baseprinter.cpp" line="130"/> <source>[%1] Receiving %2 bytes from Atari</source> <translation>[%1] Recibiendo %2 bytes de Atari</translation> </message> <message> <location filename="../printers/baseprinter.cpp" line="139"/> <source>[%1] Sending %2 bytes to Atari</source> <translation>[%1] Enviando%2 bytes a Atari</translation> </message> <message> <location filename="../printers/baseprinter.cpp" line="151"/> <source>[%1] §%2</source> <translation></translation> </message> </context> <context> <name>Printers::Passthrough</name> <message> <location filename="../printers/passthrough.h" line="20"/> <source>Passthrough</source> <translation>Pasar por</translation> </message> </context> <context> <name>Printers::TextPrinterWindow</name> <message> <location filename="../printers/textprinterwindow.cpp" line="255"/> <source>Save printer text output</source> <translation>Guardar texto impresora salida</translation> </message> <message> <location filename="../printers/textprinterwindow.cpp" line="256"/> <source>Text files (*.txt);;All files (*)</source> <translation>Archivos de texto (* txt.);;Todos los archivos (*)</translation> </message> <message> <location filename="../printers/textprinterwindow.cpp" line="284"/> <source>Stripping Line Numbers..</source> <translation>Excluyendo números de línea..</translation> </message> <message> <location filename="../printers/textprinterwindow.cpp" line="284"/> <source>The text does not seem to contain any line numbers!</source> <translation>El texto no parece contener ningún número de línea!</translation> </message> </context> <context> <name>QObject</name> <message> <location filename="../printers/rawoutput.h" line="32"/> <source>Raw output</source> <translation>Salida sin procesar</translation> </message> <message> <location filename="../printers/rawoutput_cups.cpp" line="127"/> <location filename="../printers/rawoutput_win.cpp" line="88"/> <source>Select raw printer</source> <translation>Seleccionar impresora sin formato</translation> </message> <message> <location filename="../printers/svgoutput.cpp" line="32"/> <source>Save SVG</source> <translation>Guardar SVG</translation> </message> <message> <location filename="../printers/svgoutput.cpp" line="32"/> <source>SVG (*.svg)</source> <translation></translation> </message> <message> <location filename="../printers/textprinterwindow.h" line="51"/> <source>Text printer</source> <translation>Impresora de texto</translation> </message> </context> <context> <name>RCl</name> <message> <location filename="../rcl.cpp" line="53"/> <location filename="../rcl.cpp" line="299"/> <location filename="../rcl.cpp" line="543"/> <source>[%1] Read data frame failed</source> <translation>[%1] Error al leer el marco de datos</translation> </message> <message> <location filename="../rcl.cpp" line="63"/> <source>[%1] List filter set: [%2]</source> <translation>[%1] Conjunto de filtros de lista: [%2]</translation> </message> <message> <location filename="../rcl.cpp" line="160"/> <source>[%1] Date/time sent to client (%2).</source> <translation>[%1] Fecha/hora enviada al cliente (%2).</translation> </message> <message> <location filename="../rcl.cpp" line="186"/> <source>[%1] Swapped disk %2 with disk %3.</source> <translation>[%1] Disco intercambiado %2 con disco %3.</translation> </message> <message> <location filename="../rcl.cpp" line="193"/> <source>[%1] Invalid swap request for drives: (%2)-(%3).</source> <translation>[%1] Solicitud de intercambio no válida para unidades: (%2)-(%3).</translation> </message> <message> <location filename="../rcl.cpp" line="228"/> <source>[%1] Unmounted disk %2</source> <translation>[%1] Disco sin montar %2</translation> </message> <message> <location filename="../rcl.cpp" line="232"/> <source>[%1] ALL images were remotely unmounted</source> <translation>[%1] TODAS las imágenes fueron desmontadas remotamente</translation> </message> <message> <location filename="../rcl.cpp" line="237"/> <source>[%1] Can not remotely unmount ALL images due to pending changes.</source> <translation>[%1] No se puede desmontar remotamente TODAS las imágenes debido a cambios pendientes.</translation> </message> <message> <location filename="../rcl.cpp" line="247"/> <source>[%1] Can not remotely unmount disk %2 due to pending changes.</source> <translation>[%1] No se puede desmontar remotamente el disco %2 debido a cambios pendientes.</translation> </message> <message> <location filename="../rcl.cpp" line="254"/> <source>[%1] Remotely unmounted disk %2</source> <translation>[%1] Disco desmontado remotamente %2</translation> </message> <message> <location filename="../rcl.cpp" line="262"/> <location filename="../rcl.cpp" line="509"/> <source>[%1] Invalid drive number: %2 for remote unmount</source> <translation>[%1] Número de unidad no válido: %2 para desmontaje remoto</translation> </message> <message> <location filename="../rcl.cpp" line="279"/> <location filename="../rcl.cpp" line="529"/> <source>[%1] RespeQt can&apos;t determine the folder where the image file must be created/mounted!</source> <translation>[%1] RespeQt no puede determinar la carpeta donde se debe crear/montar el archivo de imagen!</translation> </message> <message> <location filename="../rcl.cpp" line="281"/> <location filename="../rcl.cpp" line="531"/> <source>[%1] Mount a Folder Image at least once before issuing a remote mount command.</source> <translation>[%1] Monte una imagen de carpeta al menos una vez antes de emitir un comando de montaje remoto.</translation> </message> <message> <location filename="../rcl.cpp" line="313"/> <source>[%1] Invalid image file attribute: %2</source> <translation>[%1] Atributo de archivo de imagen no válido: %2</translation> </message> <message> <location filename="../rcl.cpp" line="323"/> <source>[%1] Can not create PC File: %2</source> <translation>[%1] No se puede crear un archivo de PC: %2</translation> </message> <message> <location filename="../rcl.cpp" line="485"/> <location filename="../rcl.cpp" line="498"/> <source>[%1] Saved disk %2</source> <translation>[%1] Disco guardado %2</translation> </message> <message> <location filename="../rcl.cpp" line="635"/> <source>[%1] command: $%2, aux: $%3 NAKed.</source> <translation>[%1] comando: $%2, aux: $%3 NAKed.</translation> </message> <message> <location filename="../rcl.cpp" line="657"/> <source>[%1] Image %2 mounted</source> <translation>[%1] Imagen %2 montada</translation> </message> </context> <context> <name>SimpleDiskImage</name> <message> <location filename="../diskimage.cpp" line="604"/> <location filename="../diskimage.cpp" line="607"/> <location filename="../diskimage.cpp" line="610"/> <source>Favorite tool disk</source> <translation>Disco de herramientas favorito</translation> </message> <message> <location filename="../diskimage.cpp" line="604"/> <location filename="../diskimage.cpp" line="618"/> <source>CHIP mode</source> <translation>Modo CHIP</translation> </message> <message> <location filename="../diskimage.cpp" line="607"/> <location filename="../diskimage.cpp" line="621"/> <source>HAPPY mode</source> <translation>Modo HAPPY</translation> </message> <message> <location filename="../diskimage.cpp" line="615"/> <source>Image %1/%2</source> <translation>Imagen %1/%2</translation> </message> <message> <location filename="../diskimage.cpp" line="634"/> <source>Load image %1 of %2:%3</source> <translation>Cargar imagen %1 de %2:%3</translation> </message> <message> <location filename="../diskimage.cpp" line="707"/> <source>[%1] No Translator disk image defined. Please, check settings in menu Disk images&gt;OS-B emulation.</source> <translation>[%1] No se ha definido ninguna imagen de disco de traductor. Por favor, verifique la configuración en el menú Imágenes de disco Emulación OS-B.</translation> </message> <message> <location filename="../diskimage.cpp" line="714"/> <source>[%1] Translator &apos;%2&apos; not found. Please, check settings in menu Disk images&gt;OS-B emulation.</source> <translation>[%1] Traductor &apos;%2&apos; extraviado. Por favor, compruebe la configuración en el menú Imágenes de disco Emulación OS-B.</translation> </message> <message> <location filename="../diskimage.cpp" line="752"/> <source>[%1] No tool disk image defined. Please, check settings in menu Disk images&gt;Favorite tool disk.</source> <translation>[%1] No se ha definido ninguna imagen de disco de herramientas. Por favor, compruebe la configuración en el menú Imágenes de disco Disco de herramientas favorito.</translation> </message> <message> <location filename="../diskimage.cpp" line="759"/> <source>[%1] Tool disk &apos;%2&apos; not found. Please, check settings in menu Disk images&gt;Favorite tool disk.</source> <translation>[%1] Disco de herramientas &apos;%2&apos; extraviado. Por favor, verifique la configuración en el menú Imágenes de disco Disco de herramientas favorito.</translation> </message> <message> <location filename="../diskimage.cpp" line="821"/> <source>[%1] Drive door lever open. Drive is no longer ready</source> <translation>[%1] Palanca de la puerta de accionamiento abierta. Drive ya no está listo</translation> </message> <message> <location filename="../diskimage.cpp" line="824"/> <source>[%1] Drive door lever closed. Drive is now ready</source> <translation>[%1] Palanca de la puerta de transmisión cerrada. Drive ya está listo</translation> </message> <message> <location filename="../diskimage.cpp" line="831"/> <location filename="../diskimage.cpp" line="837"/> <location filename="../diskimage.cpp" line="874"/> <location filename="../diskimageatr.cpp" line="41"/> <location filename="../diskimageatr.cpp" line="50"/> <location filename="../diskimageatr.cpp" line="61"/> <location filename="../diskimageatr.cpp" line="76"/> <location filename="../diskimageatr.cpp" line="89"/> <location filename="../diskimageatr.cpp" line="98"/> <location filename="../diskimageatr.cpp" line="123"/> <location filename="../diskimageatr.cpp" line="169"/> <location filename="../diskimageatr.cpp" line="182"/> <location filename="../diskimageatr.cpp" line="198"/> <location filename="../diskimageatr.cpp" line="234"/> <location filename="../diskimageatr.cpp" line="241"/> <location filename="../diskimageatr.cpp" line="253"/> <location filename="../diskimageatr.cpp" line="262"/> <location filename="../diskimageatr.cpp" line="275"/> <location filename="../diskimageatx.cpp" line="35"/> <location filename="../diskimageatx.cpp" line="44"/> <location filename="../diskimageatx.cpp" line="55"/> <location filename="../diskimagepro.cpp" line="38"/> <location filename="../diskimagepro.cpp" line="47"/> <location filename="../diskimagepro.cpp" line="57"/> <location filename="../diskimagepro.cpp" line="63"/> <location filename="../diskimagepro.cpp" line="72"/> <location filename="../diskimagepro.cpp" line="79"/> <location filename="../diskimagepro.cpp" line="2372"/> <location filename="../diskimagepro.cpp" line="2408"/> <source>Cannot open &apos;%1&apos;: %2</source> <translation>No se puede abrir &apos;%1&apos;: %2</translation> </message> <message> <location filename="../diskimage.cpp" line="831"/> <source>DCM images are not supported yet.</source> <translation>Las imágenes de DCM aún no son compatibles.</translation> </message> <message> <location filename="../diskimage.cpp" line="837"/> <source>DI images are not supported yet.</source> <translation>Las imágenes DI aún no son compatibles.</translation> </message> <message> <location filename="../diskimage.cpp" line="874"/> <location filename="../diskimage.cpp" line="1007"/> <source>Unknown file type.</source> <translation>Tipo de archivo desconocido.</translation> </message> <message> <location filename="../diskimage.cpp" line="881"/> <source>Translator &apos;%1&apos; activated</source> <translation>Traductor &apos;%1&apos; activado</translation> </message> <message> <location filename="../diskimage.cpp" line="914"/> <source>Image is %1 of %2. Next image will be %3</source> <translation>La imagen es %1 de %2. La siguiente imagen será %3</translation> </message> <message> <location filename="../diskimage.cpp" line="969"/> <location filename="../diskimage.cpp" line="975"/> <location filename="../diskimage.cpp" line="1007"/> <location filename="../diskimage.cpp" line="1088"/> <location filename="../diskimageatr.cpp" line="327"/> <location filename="../diskimageatr.cpp" line="337"/> <location filename="../diskimageatr.cpp" line="347"/> <location filename="../diskimageatr.cpp" line="362"/> <location filename="../diskimageatr.cpp" line="370"/> <location filename="../diskimageatr.cpp" line="421"/> <location filename="../diskimageatr.cpp" line="429"/> <location filename="../diskimageatr.cpp" line="443"/> <location filename="../diskimageatr.cpp" line="450"/> <location filename="../diskimageatr.cpp" line="473"/> <location filename="../diskimageatr.cpp" line="503"/> <location filename="../diskimageatr.cpp" line="512"/> <location filename="../diskimageatr.cpp" line="536"/> <location filename="../diskimageatx.cpp" line="276"/> <location filename="../diskimageatx.cpp" line="286"/> <location filename="../diskimageatx.cpp" line="318"/> <location filename="../diskimageatx.cpp" line="347"/> <location filename="../diskimageatx.cpp" line="359"/> <location filename="../diskimageatx.cpp" line="373"/> <location filename="../diskimageatx.cpp" line="394"/> <location filename="../diskimageatx.cpp" line="408"/> <location filename="../diskimageatx.cpp" line="423"/> <location filename="../diskimageatx.cpp" line="446"/> <location filename="../diskimagepro.cpp" line="219"/> <location filename="../diskimagepro.cpp" line="228"/> <location filename="../diskimagepro.cpp" line="253"/> <location filename="../diskimagepro.cpp" line="265"/> <location filename="../diskimagepro.cpp" line="287"/> <location filename="../diskimagepro.cpp" line="299"/> <location filename="../diskimagepro.cpp" line="324"/> <source>Cannot save &apos;%1&apos;: %2</source> <translation>No se puede guardar &apos;%1&apos;:%2</translation> </message> <message> <location filename="../diskimage.cpp" line="969"/> <source>Saving DCM images is not supported yet.</source> <translation>Aún no se admite guardar imágenes de DCM.</translation> </message> <message> <location filename="../diskimage.cpp" line="975"/> <source>Saving DI images is not supported yet.</source> <translation>Aún no se admite guardar imágenes DI.</translation> </message> <message> <location filename="../diskimage.cpp" line="1088"/> <source>Unknown file extension.</source> <translation>Extensión de archivo desconocida.</translation> </message> <message> <location filename="../diskimage.cpp" line="1136"/> <source>[%1] Uploaded code is: Check if drive is a Super Archiver</source> <translation>[%1] El código subido es: compruebe si la unidad es un superarchivador</translation> </message> <message> <location filename="../diskimage.cpp" line="1157"/> <source>[%1] Uploaded code is: Speed check</source> <translation>[%1] El código subido es: verificación de velocidad</translation> </message> <message> <location filename="../diskimage.cpp" line="1161"/> <source>[%1] Uploaded code is: Diagnostic</source> <translation>[%1] El código subido es: diagnóstico</translation> </message> <message> <location filename="../diskimage.cpp" line="1165"/> <source>[%1] Uploaded code is: End of diagnostic</source> <translation>[%1] El código subido es: fin del diagnóstico</translation> </message> <message> <location filename="../diskimage.cpp" line="1169"/> <source>[%1] Uploaded code is: Read address marks for track $%2</source> <translation>[%1] El código subido es: leer las marcas de dirección de la pista $%2</translation> </message> <message> <location filename="../diskimage.cpp" line="1174"/> <source>[%1] Uploaded code is: BitWriter clear memory</source> <translation>[%1] El código cargado es: BitWriter borrar memoria</translation> </message> <message> <location filename="../diskimage.cpp" line="1178"/> <source>[%1] Uploaded code is: BitWriter read track $%2</source> <translation>[%1] El código cargado es: BitWriter leyó la pista $%2</translation> </message> <message> <location filename="../diskimage.cpp" line="1187"/> <source>[%1] Uploaded code is: Prepare track data at offset $%2</source> <translation>[%1] El código subido es: preparar los datos de la pista en el desplazamiento $%2</translation> </message> <message> <location filename="../diskimage.cpp" line="1192"/> <source>[%1] Uploaded code is: Super Archiver open Chip</source> <translation>[%1] El código subido es: chip abierto de Super Archiver</translation> </message> <message> <location filename="../diskimage.cpp" line="1196"/> <source>[%1] Uploaded code is: BitWriter open Chip</source> <translation>[%1] El código cargado es: BitWriter open Chip</translation> </message> <message> <location filename="../diskimage.cpp" line="1200"/> <source>[%1] Uploaded code is: Super Archiver clear memory</source> <translation>[%1] El código subido es: Super Archiver borrar memoria</translation> </message> <message> <location filename="../diskimage.cpp" line="1216"/> <source>[%1] Uploaded code is: Skew alignment of track $%2 sector $%3 with track $%4 sector $%5</source> <translation>[%1] El código cargado es: Alineación sesgada de la pista $%2 sector $%3 con la pista $%4 sector $%5</translation> </message> <message> <location filename="../diskimage.cpp" line="1224"/> <source>[%1] Uploaded code is: Skew alignment of track $%2 (%3 sectors) with track $%4 (%5 sectors)</source> <translation>[%1] El código cargado es: Alineación sesgada de la pista $%2 (%3 sectores) con la pista $%4 (%5 sectores)</translation> </message> <message> <location filename="../diskimage.cpp" line="1237"/> <source>[%1] Uploaded code is: Format track $%2 with skew alignment $%3 with track $%4</source> <translation>[%1] El código subido es: Formatee la pista $%2 con alineación sesgada $%3 con la pista $%4</translation> </message> <message> <location filename="../diskimage.cpp" line="1244"/> <source>[%1] Uploaded code is: Format track $%2 with skew alignment with track $%3</source> <translation>[%1] El código subido es: Formatee la pista $%2 con alineación sesgada con la pista $%3</translation> </message> <message> <location filename="../diskimage.cpp" line="1252"/> <source>[%1] Data Crc16 is $%2. Command ignored</source> <translation>[%1] Los datos Crc16 son $%2. Comando ignorado</translation> </message> <message> <location filename="../diskimage.cpp" line="1630"/> <source>[%1] command: $%2, aux: $%3 ignored because the drive is not ready.</source> <translation>[%1] comando: $%2, aux: $%3 ignorado porque la unidad no está lista.</translation> </message> <message> <location filename="../diskimage.cpp" line="1662"/> <source>[%1] Booting Translator &apos;%2&apos; first</source> <translation>[%1] Iniciando Traductor &apos;%2&apos; primero</translation> </message> <message> <location filename="../diskimage.cpp" line="1671"/> <source>[%1] Removing Translator to boot on &apos;%2&apos;</source> <translation>[%1] Eliminando el Traductor para arrancar en &apos;%2&apos;</translation> </message> <message> <location filename="../diskimage.cpp" line="1708"/> <source>[%1] Booting tool disk &apos;%2&apos; first</source> <translation>[%1] Disco de la herramienta de arranque &apos;%2&apos; primero</translation> </message> <message> <location filename="../diskimage.cpp" line="1730"/> <source>[%1] Format.</source> <translation>[%1] Formato.</translation> </message> <message> <location filename="../diskimage.cpp" line="1736"/> <source>[%1] Format failed.</source> <translation>[%1] Error de formato.</translation> </message> <message> <location filename="../diskimage.cpp" line="1741"/> <source>[%1] Format denied.</source> <translation>[%1] Formato denegado.</translation> </message> <message> <location filename="../diskimage.cpp" line="1757"/> <source>[%1] Format ED denied.</source> <translation>[%1] Formato ED denegado.</translation> </message> <message> <location filename="../diskimage.cpp" line="1764"/> <source>[%1] Format ED.</source> <translation>[%1] Formatear ED.</translation> </message> <message> <location filename="../diskimage.cpp" line="1770"/> <source>[%1] Format ED failed.</source> <translation>[%1] Error en el formato ED.</translation> </message> <message> <location filename="../diskimage.cpp" line="1782"/> <source>[%1] Run Speed Diagnostic with AUX1=$%2 and AUX2=$%3</source> <translation>[%1] Ejecutar diagnóstico de velocidad con AUX1=$%2 y AUX2=$%3</translation> </message> <message> <location filename="../diskimage.cpp" line="1800"/> <source>[%1] Run Diagnostic with AUX1=$%2 and AUX2=$%3</source> <translation>[%1] Ejecutar diagnóstico con AUX1=$%2 y AUX2=$%3</translation> </message> <message> <location filename="../diskimage.cpp" line="1841"/> <source>[%1] Speed poll: %2</source> <translation>[%1] Encuesta rápida: %2</translation> </message> <message> <location filename="../diskimage.cpp" line="1856"/> <location filename="../diskimage.cpp" line="2697"/> <source>[%1] Happy Read Track %2 ($%3)</source> <translation>[%1] Pista de lectura Happy %2 ($%3)</translation> </message> <message> <location filename="../diskimage.cpp" line="1867"/> <location filename="../diskimage.cpp" line="1915"/> <location filename="../diskimage.cpp" line="1985"/> <location filename="../diskimage.cpp" line="2057"/> <location filename="../diskimage.cpp" line="2121"/> <location filename="../diskimage.cpp" line="2209"/> <location filename="../diskimage.cpp" line="2292"/> <location filename="../diskimage.cpp" line="2321"/> <location filename="../diskimage.cpp" line="2723"/> <location filename="../diskimage.cpp" line="2741"/> <location filename="../diskimage.cpp" line="3194"/> <source>[%1] Happy Execute custom code $%2 with AUX $%3 and CRC16 $%4. Ignored</source> <translation>[%1] Happy Execute código personalizado $%2 con AUX $%3 y CRC16 $%4. Ignorado</translation> </message> <message> <location filename="../diskimage.cpp" line="1876"/> <source>[%1] Command $41 NAKed (HAPPY is not enabled).</source> <translation>[%1] Comando $41 NAKed (HAPPY no está habilitado).</translation> </message> <message> <location filename="../diskimage.cpp" line="1893"/> <location filename="../diskimage.cpp" line="3109"/> <source>[%1] Happy Read Sectors of track %2 ($%3)</source> <translation>[%1] Sectores de lectura Happy de la pista %2 ($%3)</translation> </message> <message> <location filename="../diskimage.cpp" line="1899"/> <location filename="../diskimage.cpp" line="3115"/> <source>[%1] Happy Read Sectors of track %2 ($%3) starting after sector %4 ($%5)</source> <translation>[%1] Sectores de lectura feliz de la pista %2 ($%3) a partir del sector %4 ($%5)</translation> </message> <message> <location filename="../diskimage.cpp" line="1925"/> <source>[%1] Super Archiver Write Sector using Index denied (CHIP is not open)</source> <translation>[%1] Sector de escritura de Super Archiver que usa índice denegado (CHIP no está abierto)</translation> </message> <message> <location filename="../diskimage.cpp" line="1933"/> <source>[%1] Super Archiver Write Sector using Index with AUX1=$%2 and AUX2=$%3</source> <translation>[%1] Sector de escritura del súper archivador usando índice con AUX1=$%2 y AUX2=$%3</translation> </message> <message> <location filename="../diskimage.cpp" line="1944"/> <source>[%1] Super Archiver Write Sector using Index denied.</source> <translation>[%1] Sector de escritura de Super Archiver que usa índice denegado.</translation> </message> <message> <location filename="../diskimage.cpp" line="1952"/> <source>[%1] Super Archiver Write Sector using Index failed.</source> <translation>[%1] Error en el sector de escritura del Super Archiver al utilizar el índice.</translation> </message> <message> <location filename="../diskimage.cpp" line="1956"/> <source>[%1] Super Archiver Write Sector using Index data frame failed.</source> <translation>[%1] Error en el sector de escritura del Super Archiver utilizando el marco de datos de índice.</translation> </message> <message> <location filename="../diskimage.cpp" line="1974"/> <source>[%1] Happy Set Skew Alignment track %2 ($%3) and sector %4 ($%5)</source> <translation>[%1] Happy Establecer pista de alineación sesgada %2 ($%3) y sector %4 ($%5)</translation> </message> <message> <location filename="../diskimage.cpp" line="1995"/> <source>[%1] Super Archiver Read all Sector Statuses denied (CHIP is not open)</source> <translation>[%1] Super Archiver Lee todos los estados de sector denegados (CHIP no está abierto)</translation> </message> <message> <location filename="../diskimage.cpp" line="2003"/> <source>[%1] Super Archiver Read All Sector Statuses</source> <translation>[%1] Super Archiver lee todos los estados del sector</translation> </message> <message> <location filename="../diskimage.cpp" line="2011"/> <source>[%1] Super Archiver Read All Sector Statuses failed.</source> <translation>[%1] Error en la lectura de todos los estados del sector de Super Archiver.</translation> </message> <message> <location filename="../diskimage.cpp" line="2030"/> <location filename="../diskimage.cpp" line="3079"/> <source>[%1] Happy Read Skew alignment of track %2 ($%3) sector %4 ($%5) with track %6 ($%7) sector %8 ($%9)</source> <translation>[%1] Lectura Happy Alineación sesgada de la pista %2 ($%3) sector %4 ($%5) con la pista %6 ($%7) sector %8 ($%9)</translation> </message> <message> <location filename="../diskimage.cpp" line="2047"/> <location filename="../diskimage.cpp" line="3095"/> <source>[%1] Happy Read Skew alignment failed.</source> <translation>[%1] Error en la alineación del sesgo de lectura Happy.</translation> </message> <message> <location filename="../diskimage.cpp" line="2067"/> <source>[%1] Super Archiver Read Sector using Index denied (CHIP is not open)</source> <translation>[%1] Sector de lectura de Super Archiver que usa índice denegado (CHIP no está abierto)</translation> </message> <message> <location filename="../diskimage.cpp" line="2075"/> <source>[%1] Super Archiver Read Sector using Index with AUX1=$%2 and AUX2=$%3</source> <translation>[%1] Sector de lectura de Super Archiver usando índice con AUX1=$%2 y AUX2=$%3</translation> </message> <message> <location filename="../diskimage.cpp" line="2086"/> <source>[%1] Super Archiver Read sector using Index with AUX1=$%2 and AUX2=$%3 failed.</source> <translation>[%1] Error en el sector de lectura de Super Archiver que usaba el índice con AUX1=$%2 y AUX2=$%3.</translation> </message> <message> <location filename="../diskimage.cpp" line="2106"/> <location filename="../diskimage.cpp" line="2983"/> <source>[%1] Happy Write track %2 ($%3)</source> <translation>[%1] Happy Escribir track %2 ($%3)</translation> </message> <message> <location filename="../diskimage.cpp" line="2116"/> <location filename="../diskimage.cpp" line="2286"/> <location filename="../diskimage.cpp" line="2991"/> <location filename="../diskimage.cpp" line="3177"/> <source>[%1] Happy Write track failed.</source> <translation>[%1] Error en la pista de escritura Happy.</translation> </message> <message> <location filename="../diskimage.cpp" line="2131"/> <source>[%1] Super Archiver Write Track denied (CHIP is not open)</source> <translation>[%1] Seguimiento de escritura de Super Archiver denegado (CHIP no está abierto)</translation> </message> <message> <location filename="../diskimage.cpp" line="2139"/> <source>[%1] Super Archiver Write Track with AUX1=$%2 and AUX2=$%3</source> <translation>[%1] Pista de escritura de Super Archiver con AUX1=$%2 y AUX2=$%3</translation> </message> <message> <location filename="../diskimage.cpp" line="2150"/> <source>[%1] Super Archiver Write Track denied.</source> <translation>[%1] Se rechazó la pista de escritura de Super Archiver.</translation> </message> <message> <location filename="../diskimage.cpp" line="2158"/> <source>[%1] Super Archiver Write track failed.</source> <translation>[%1] Error en la pista de escritura de Super Archiver.</translation> </message> <message> <location filename="../diskimage.cpp" line="2162"/> <source>[%1] Super Archiver Write track data frame failed.</source> <translation>[%1] Error en el marco de datos de la pista de escritura de Super Archiver.</translation> </message> <message> <location filename="../diskimage.cpp" line="2179"/> <location filename="../diskimage.cpp" line="3133"/> <source>[%1] Happy Write Sectors of track %2 ($%3)</source> <translation>[%1] Sectores de escritura Happy de la pista %2 ($%3)</translation> </message> <message> <location filename="../diskimage.cpp" line="2185"/> <location filename="../diskimage.cpp" line="3139"/> <source>[%1] Happy Write Sectors of track %2 ($%3) starting after sector %4 ($%5)</source> <translation>[%1] Happy Write Sectores de la pista %2 ($%3) que comienzan después del sector %4 ($%5)</translation> </message> <message> <location filename="../diskimage.cpp" line="2199"/> <location filename="../diskimage.cpp" line="3152"/> <source>[%1] Happy Write Sectors failed.</source> <translation>[%1] Falló el sector de escritura Happy.</translation> </message> <message> <location filename="../diskimage.cpp" line="2219"/> <source>[%1] Super Archiver Read Track (128 bytes) denied (CHIP is not open)</source> <translation>[%1] Super Archiver Read Track (128 bytes) denegado (CHIP no está abierto)</translation> </message> <message> <location filename="../diskimage.cpp" line="2227"/> <source>[%1] Super Archiver Read Track (128 bytes) with AUX1=$%2 and AUX2=$%3</source> <translation>[%1] Pista de lectura del superarchivador (128 bytes) con AUX1=$%2 y AUX2=$%3</translation> </message> <message> <location filename="../diskimage.cpp" line="2245"/> <source>[%1] Happy Configure drive with AUX $%2</source> <translation>[%1] Unidad Happy configurada con AUX $%2</translation> </message> <message> <location filename="../diskimage.cpp" line="2258"/> <source>[%1] Happy Configure drive NAKed (HAPPY is not enabled).</source> <translation>[%1] Unidad Happy configurada NAKed (HAPPY no está habilitado).</translation> </message> <message> <location filename="../diskimage.cpp" line="2271"/> <source>[%1] Happy Write track using skew alignment of track %2 ($%3) with track %4 ($%5) sector %6 ($%7)</source> <translation>[%1] Pista de escritura Happy usando alineación sesgada de la pista %2 ($%3) con la pista %4 ($%5) sector %6 ($%7)</translation> </message> <message> <location filename="../diskimage.cpp" line="2301"/> <source>[%1] Command $49 NAKed (HAPPY is not enabled).</source> <translation>[%1] Comando $49 NAKed (HAPPY no está habilitado).</translation> </message> <message> <location filename="../diskimage.cpp" line="2314"/> <source>[%1] Happy Init Skew alignment</source> <translation>[%1] Alineación sesgada inicial Happy</translation> </message> <message> <location filename="../diskimage.cpp" line="2330"/> <source>[%1] Command $4A NAKed (HAPPY is not enabled).</source> <translation>[%1] Comando $4A NAKed (HAPPY no está habilitado).</translation> </message> <message> <location filename="../diskimage.cpp" line="2342"/> <source>[%1] Happy Prepare backup with AUX $%2</source> <translation>[%1] Happy preparación de copia de seguridad con AUX $%2</translation> </message> <message> <location filename="../diskimage.cpp" line="2352"/> <source>[%1] Happy Prepare backup NAKed (HAPPY is not enabled).</source> <translation>[%1] Happy Prepare copia de seguridad NAKed (HAPPY no está habilitado).</translation> </message> <message> <location filename="../diskimage.cpp" line="2360"/> <source>[%1] Super Archiver Set RAM Buffer denied (CHIP is not open)</source> <translation>[%1] Super Archiver establecido buffer RAM denegado (CHIP no está abierto)</translation> </message> <message> <location filename="../diskimage.cpp" line="2368"/> <source>[%1] Super Archiver Set RAM Buffer</source> <translation>[%1] Super Archiver establecido buffer RAM</translation> </message> <message> <location filename="../diskimage.cpp" line="2380"/> <source>[%1] Super Archiver Set RAM Buffer data frame failed.</source> <translation>[%1] Error en la trama de datos del buffer RAM del conjunto de Super Archiver.</translation> </message> <message> <location filename="../diskimage.cpp" line="2390"/> <source>[%1] Chip Execute code denied (CHIP is not open)</source> <translation>[%1] Código de ejecución de chip denegado (CHIP no está abierto)</translation> </message> <message> <location filename="../diskimage.cpp" line="2398"/> <source>[%1] Chip Execute code (ignored)</source> <translation>[%1] Código de ejecución de chip (ignorado)</translation> </message> <message> <location filename="../diskimage.cpp" line="2414"/> <source>[%1] Chip Execute code data frame failed.</source> <translation>[%1] Error en la trama de datos del código de ejecución de chip.</translation> </message> <message> <location filename="../diskimage.cpp" line="2426"/> <source>[%1] Get PERCOM block (%2).</source> <translation>[%1] Obtener bloque PERCOM (%2).</translation> </message> <message> <location filename="../diskimage.cpp" line="2443"/> <source>[%1] Open CHIP with code %2</source> <translation>[%1] Abra CHIP con el código %2</translation> </message> <message> <location filename="../diskimage.cpp" line="2448"/> <source>[%1] Open CHIP denied on disk %2</source> <translation>[%1] CHIP abierto denegado en el disco %2</translation> </message> <message> <location filename="../diskimage.cpp" line="2455"/> <source>[%1] Set PERCOM block (%2).</source> <translation>[%1] Establecer bloque PERCOM (%2).</translation> </message> <message> <location filename="../diskimage.cpp" line="2483"/> <source>[%1] BitWriter read memory with AUX=$%2</source> <translation>[%1] BitWriter leyó memoria con AUX=$%2</translation> </message> <message> <location filename="../diskimage.cpp" line="2498"/> <source>[%1] Happy Write memory at $%2</source> <translation>[%1] Memoria de escritura Happy en $%2</translation> </message> <message> <location filename="../diskimage.cpp" line="2537"/> <source>[%1] Happy %2Write memory at $%3</source> <translation>[%1] Happy %2 Escribe memoria a $%3</translation> </message> <message> <location filename="../diskimage.cpp" line="2539"/> <location filename="../diskimage.cpp" line="2783"/> <source>High Speed </source> <translation>Alta velocidad </translation> </message> <message> <location filename="../diskimage.cpp" line="2577"/> <source>[%1] Write memory at $%2 NAKed (Address out of range).</source> <translation>[%1] Escribir memoria en $%2 NAKed (Dirección fuera de rango).</translation> </message> <message> <location filename="../diskimage.cpp" line="2589"/> <source>[%1] %2Write Sector %3 ($%4) #%5 in track %6 ($%7) with AUX=$%8</source> <translation>[%1] %2 Sector de escritura %3 ($%4) #%5 en la pista %6 ($%7) con AUX=$%8</translation> </message> <message> <location filename="../diskimage.cpp" line="2591"/> <location filename="../diskimage.cpp" line="2602"/> <location filename="../diskimage.cpp" line="2805"/> <location filename="../diskimage.cpp" line="2816"/> <source>Happy High Speed </source> <translation>Happy alta velocidad </translation> </message> <message> <location filename="../diskimage.cpp" line="2600"/> <source>[%1] %2Write Sector %3 ($%4) #%5 in track %6 ($%7)</source> <translation>[%1] %2 Sector de escritura %3 ($%4) #%5 en la pista %6 ($%7)</translation> </message> <message> <location filename="../diskimage.cpp" line="2619"/> <source>[%1] Write sector denied.</source> <translation>[%1] Sector de escritura denegado.</translation> </message> <message> <location filename="../diskimage.cpp" line="2628"/> <source>[%1] Write sector failed.</source> <translation>[%1] Error en el sector de escritura.</translation> </message> <message> <location filename="../diskimage.cpp" line="2632"/> <source>[%1] Write sector data frame failed.</source> <translation>[%1] Error en la trama de datos del sector de escritura.</translation> </message> <message> <location filename="../diskimage.cpp" line="2639"/> <source>[%1] Write sector %2 ($%3) NAKed.</source> <translation>[%1] Sector de escritura %2 ($%3) NAKed.</translation> </message> <message> <location filename="../diskimage.cpp" line="2654"/> <source>[%1] Happy Ram check</source> <translation>[%1] Happy cheque de Ram</translation> </message> <message> <location filename="../diskimage.cpp" line="2659"/> <source>[%1] Happy Rom 810 test</source> <translation>[%1] Prueba Happy Rom 810</translation> </message> <message> <location filename="../diskimage.cpp" line="2664"/> <source>[%1] Happy Extended ram check</source> <translation>[%1] Happy verificación de RAM extendida</translation> </message> <message> <location filename="../diskimage.cpp" line="2669"/> <source>[%1] Happy Run diagnostic</source> <translation>[%1] Diagnóstico de Happy Run</translation> </message> <message> <location filename="../diskimage.cpp" line="2674"/> <source>[%1] Happy Speed check</source> <translation>[%1] Comprobación de velocidad Happy</translation> </message> <message> <location filename="../diskimage.cpp" line="2680"/> <location filename="../diskimage.cpp" line="3189"/> <source>[%1] Happy Step-in / Step-out</source> <translation>[%1] Happy paso adentro/afuera</translation> </message> <message> <location filename="../diskimage.cpp" line="2684"/> <source>[%1] Happy Read/Write check</source> <translation>[%1] Happy comprobación de lectura/escritura</translation> </message> <message> <location filename="../diskimage.cpp" line="2689"/> <source>[%1] Happy Set unhappy mode</source> <translation>[%1] Happy Establecer modo no Happy</translation> </message> <message> <location filename="../diskimage.cpp" line="2705"/> <source>[%1] Happy init backup 1</source> <translation>[%1] Happy copia de seguridad de inicio 1</translation> </message> <message> <location filename="../diskimage.cpp" line="2710"/> <source>[%1] Happy init backup 2</source> <translation>[%1] Happy copia de seguridad de inicio 2</translation> </message> <message> <location filename="../diskimage.cpp" line="2718"/> <source>[%1] Happy Clear buffer</source> <translation>[%1] Happy borrar buffer</translation> </message> <message> <location filename="../diskimage.cpp" line="2736"/> <source>[%1] Happy init backup</source> <translation>[%1] Happy copia de seguridad de inicio</translation> </message> <message> <location filename="../diskimage.cpp" line="2750"/> <source>[%1] Command $51 NAKed (HAPPY is not enabled).</source> <translation>[%1] Comando $51 NAKed (HAPPY no está habilitado).</translation> </message> <message> <location filename="../diskimage.cpp" line="2768"/> <source>[%1] Happy Read memory at $%2</source> <translation>[%1] Memoria de lectura Happy en $%2</translation> </message> <message> <location filename="../diskimage.cpp" line="2781"/> <source>[%1] Happy %2Read memory at $%3</source> <translation>[%1] Feliz %2 Read memoria en $%3</translation> </message> <message> <location filename="../diskimage.cpp" line="2803"/> <source>[%1]%2 Read Sector %3 ($%4) #%5 in track %6 ($%7) with AUX=$%8</source> <translation>[%1] %2 Sector de lectura %3 ($%4) #%5 en la pista %6 ($%7) con AUX=$%8</translation> </message> <message> <location filename="../diskimage.cpp" line="2814"/> <source>[%1] %2Read Sector %3 ($%4) #%5 in track %6 ($%7)</source> <translation>[%1] %2 Read Sector %3 ($%4) #%5 en la pista %6 ($%7)</translation> </message> <message> <location filename="../diskimage.cpp" line="2852"/> <source>[%1] Happy Warp Speed Software V7.1 patched on the fly to be compatible with RespeQt</source> <translation>[%1] Happy Warp Speed Software V7.1 parcheado sobre la marcha para que sea compatible con RespeQt</translation> </message> <message> <location filename="../diskimage.cpp" line="2874"/> <source>[%1] Happy Warp Speed Software V5.3 patched on the fly to be compatible with RespeQt</source> <translation>[%1] Happy Warp Speed Software V5.3 parcheado sobre la marcha para ser compatible con RespeQt</translation> </message> <message> <location filename="../diskimage.cpp" line="2893"/> <source>[%1] Read sector failed.</source> <translation>[%1] Error de lectura del sector.</translation> </message> <message> <location filename="../diskimage.cpp" line="2903"/> <source>[%1] Read sector $%2 NAKed.</source> <translation>[%1] Leer sector $%2 NAKed.</translation> </message> <message> <location filename="../diskimage.cpp" line="2919"/> <source>[%1] RespeQt version inquiry: $%2</source> <translation>[%1] Consulta sobre la versión de RespeQt: $%2</translation> </message> <message> <location filename="../diskimage.cpp" line="2924"/> <source>[%1] Get status: $%2</source> <translation>[%1] Obtener estado: $%2</translation> </message> <message> <location filename="../diskimage.cpp" line="2943"/> <source>[%1] Happy High Speed Write Sector %2 ($%3) #%4 in track %5 ($%6)</source> <translation>[%1] Happy sector de escritura de alta velocidad %2 ($%3) #%4 en la pista %5 ($%6)</translation> </message> <message> <location filename="../diskimage.cpp" line="2960"/> <source>[%1] Happy Write sector denied.</source> <translation>[%1] Sector de escritura Happy denegado.</translation> </message> <message> <location filename="../diskimage.cpp" line="2968"/> <source>[%1] Happy Write sector failed.</source> <translation>[%1] Falló el sector de escritura Happy.</translation> </message> <message> <location filename="../diskimage.cpp" line="2972"/> <source>[%1] Happy Write sector data frame failed.</source> <translation>[%1] Error en el marco de datos del sector de escritura Happy.</translation> </message> <message> <location filename="../diskimage.cpp" line="3012"/> <source>[%1] Happy Rom 1050 test</source> <translation>[%1] Prueba Happy Rom 1050</translation> </message> <message> <location filename="../diskimage.cpp" line="3020"/> <source>[%1] Get RAM Buffer denied (CHIP is not open)</source> <translation>[%1] Obtener buffer de RAM denegado (CHIP no está abierto)</translation> </message> <message> <location filename="../diskimage.cpp" line="3028"/> <source>[%1] Get RAM Buffer</source> <translation>[%1] Obtener buffer de RAM</translation> </message> <message> <location filename="../diskimage.cpp" line="3050"/> <source>[%1] Happy High Speed Read Sector %2 ($%3) in track %4 ($%5)</source> <translation>[%1] Happy sector de lectura de alta velocidad %2 ($%3) en la pista %4 ($%5)</translation> </message> <message> <location filename="../diskimage.cpp" line="3071"/> <source>[%1] Happy Read Sector failed.</source> <translation>[%1] Falló el sector de lectura Happy.</translation> </message> <message> <location filename="../diskimage.cpp" line="3164"/> <source>[%1] Happy Write track %2 ($%3) skew aligned with track %4 ($%5) sector %6 ($%7)</source> <translation>[%1] Happy Write track %2 ($%3) sesgo alineado con track %4 ($%5) sector %6 ($%7)</translation> </message> <message> <location filename="../diskimage.cpp" line="3183"/> <source>[%1] Happy init sector copy</source> <translation>[%1] Happy copia del sector de inicio</translation> </message> <message> <location filename="../diskimage.cpp" line="3205"/> <source>[%1] Command $%2 NAKed (HAPPY is not enabled).</source> <translation>[%1] Commando $%2 NAKed (HAPPY no esta habilitado).</translation> </message> <message> <location filename="../diskimage.cpp" line="3214"/> <source>[%1] Super Archiver Write Fuzzy Sector using Index denied (CHIP is not open)</source> <translation>[%1] Super Archiver escribir Fuzzy sector usando índice denegado (CHIP no está abierto)</translation> </message> <message> <location filename="../diskimage.cpp" line="3222"/> <source>[%1] Super Archiver Write Fuzzy Sector using Index with AUX1=$%2 and AUX2=$%3</source> <translation>[%1] Super Archiver escribe un sector difuso con índice con AUX1=$%2 y AUX2=$%3</translation> </message> <message> <location filename="../diskimage.cpp" line="3233"/> <source>[%1] Super Archiver Write Fuzzy Sector using Index denied.</source> <translation>[%1] Super Archiver escribe Fuzzy Sector usando índice denegado.</translation> </message> <message> <location filename="../diskimage.cpp" line="3241"/> <source>[%1] Super Archiver Write Fuzzy Sector using Index failed.</source> <translation>[%1] Error en el sector difuso de escritura del Super Archiver al utilizar el índice.</translation> </message> <message> <location filename="../diskimage.cpp" line="3245"/> <source>[%1] Super Archiver Write Fuzzy Sector using Index data frame failed.</source> <translation>[%1] Error en el sector difuso de escritura del Super Archiver utilizando el marco de datos del índice.</translation> </message> <message> <location filename="../diskimage.cpp" line="3256"/> <source>[%1] Format with custom sector skewing.</source> <translation>[%1] Formato con sesgo de sector personalizado.</translation> </message> <message> <location filename="../diskimage.cpp" line="3267"/> <source>[%1] Format with custom sector skewing failed.</source> <translation>[%1] Error en el formato con sesgo de sector personalizado.</translation> </message> <message> <location filename="../diskimage.cpp" line="3274"/> <source>[%1] Format with custom sector skewing denied.</source> <translation>[%1] Formato con sesgo de sector personalizado denegado.</translation> </message> <message> <location filename="../diskimage.cpp" line="3282"/> <source>[%1] Super Archiver Read Track (256 bytes) denied (CHIP is not open)</source> <translation>[%1] Super Archiver Read Track (256 bytes) denegado (CHIP no está abierto)</translation> </message> <message> <location filename="../diskimage.cpp" line="3290"/> <source>[%1] Super Archiver Read Track (256 bytes) with AUX1=$%2 and AUX2=$%3</source> <translation>[%1] Super Archiver leyendo pista (256 bytes) con AUX1=$%2 y AUX2=$%3</translation> </message> <message> <location filename="../diskimage.cpp" line="3305"/> <source>[%1] Super Archiver Write Fuzzy sector denied (CHIP is not open)</source> <translation>[%1] Super Archiver escribiendo Fuzzy sector denegado (CHIP no está abierto)</translation> </message> <message> <location filename="../diskimage.cpp" line="3315"/> <source>[%1] Super Archiver Write Fuzzy Sector %2 ($%3) in track %4 ($%5) with AUX=$%6</source> <translation>[%1] Super Archiver escribe sector difuso %2 ($%3) en la pista %4 ($%5) con AUX=$%6</translation> </message> <message> <location filename="../diskimage.cpp" line="3329"/> <source>[%1] Super Archiver Write Fuzzy sector denied.</source> <translation>[%1] Se rechazó el sector difuso de escritura del Super Archiver.</translation> </message> <message> <location filename="../diskimage.cpp" line="3337"/> <source>[%1] Super Archiver Write Fuzzy sector failed.</source> <translation>[%1] Error en el sector difuso de escritura del Super Archiver.</translation> </message> <message> <location filename="../diskimage.cpp" line="3341"/> <source>[%1] Super Archiver Write Fuzzy sector data frame failed.</source> <translation>[%1] Error en la trama de datos del sector difuso de escritura de Super Archiver.</translation> </message> <message> <location filename="../diskimage.cpp" line="3347"/> <source>[%1] Super Archiver Write Fuzzy sector $%2 NAKed.</source> <translation>[%1] Super Archiver escribir sector difuso $%2 NAKed.</translation> </message> <message> <location filename="../diskimage.cpp" line="3356"/> <source>[%1] Super Archiver Set Speed denied (CHIP is not open)</source> <translation>[%1] Super Archiver Set Speed denegada (CHIP no está abierto)</translation> </message> <message> <location filename="../diskimage.cpp" line="3364"/> <source>[%1] Super Archiver Set Speed %2</source> <translation>[%1] Super Archiver Velocidad fijada %2</translation> </message> <message> <location filename="../diskimage.cpp" line="3376"/> <source>[%1] Super Archiver Read Memory denied (CHIP is not open)</source> <translation>[%1] Memoria de lectura del Super Archiver denegada (CHIP no está abierto)</translation> </message> <message> <location filename="../diskimage.cpp" line="3388"/> <source>[%1] Super Archiver Read memory (Speed check)</source> <translation>[%1] Memoria de lectura de Super Archiver (comprobación de velocidad)</translation> </message> <message> <location filename="../diskimage.cpp" line="3396"/> <source>[%1] Super Archiver Read memory (Diagnostic)</source> <translation>[%1] Memoria de lectura del Super Archiver (diagnóstico)</translation> </message> <message> <location filename="../diskimage.cpp" line="3402"/> <source>[%1] Super Archiver Read memory (Address marks)</source> <translation>[%1] Memoria de lectura de Super Archiver (marcas de dirección)</translation> </message> <message> <location filename="../diskimage.cpp" line="3422"/> <source>[%1] Super Archiver Read Memory (Skew alignment of $%2)</source> <translation>[%1] Memoria de lectura del Super Archiver (alineación sesgada de $%2)</translation> </message> <message> <location filename="../diskimage.cpp" line="3427"/> <source>[%1] Super Archiver Read Memory (Skew alignment)</source> <translation>[%1] Memoria de lectura del Super Archiver (alineación sesgada)</translation> </message> <message> <location filename="../diskimage.cpp" line="3433"/> <source>[%1] Super Archiver Read Memory</source> <translation>[%1] Memoria de lectura del Super Archiver</translation> </message> <message> <location filename="../diskimage.cpp" line="3443"/> <source>[%1] Super Archiver Upload and execute code denied (CHIP is not open)</source> <translation>[%1] Super Archiver Subir y ejecutar código denegado (CHIP no está abierto)</translation> </message> <message> <location filename="../diskimage.cpp" line="3452"/> <source>[%1] Super Archiver Upload and Execute Code</source> <translation>[%1] Código de carga y ejecución de Super Archiver</translation> </message> <message> <location filename="../diskimage.cpp" line="3473"/> <source>[%1] Super Archiver Upload and Execute Code data frame failed.</source> <translation>[%1] Error en el marco de datos de carga y ejecución de código de Super Archiver.</translation> </message> <message> <location filename="../diskimage.cpp" line="3482"/> <source>[%1] command: $%2, aux: $%3 NAKed.</source> <translation>[%1] commando: $%2, aux: $%3 NAKed.</translation> </message> <message> <location filename="../diskimage.cpp" line="3583"/> <source>[%1] Sending [COMMAND ACK] to Atari</source> <translation>[%1] Enviando [COMMAND ACK] al Atari</translation> </message> <message> <location filename="../diskimage.cpp" line="3591"/> <source>[%1] Sending [DATA ACK] to Atari</source> <translation>[%1] Enviando [DATA ACK] al Atari</translation> </message> <message> <location filename="../diskimage.cpp" line="3598"/> <source>[%1] Sending [COMMAND NAK] to Atari</source> <translation>[%1] Enviando [COMMAND NAK] al Atari</translation> </message> <message> <location filename="../diskimage.cpp" line="3604"/> <source>[%1] Sending [DATA NAK] to Atari</source> <translation>[%1] Enviando [DATA NAK] al Atari</translation> </message> <message> <location filename="../diskimage.cpp" line="3611"/> <source>[%1] Sending [COMPLETE] to Atari</source> <translation>[%1] Enviando [COMPLETE] al Atari</translation> </message> <message> <location filename="../diskimage.cpp" line="3618"/> <source>[%1] Sending [ERROR] to Atari</source> <translation>[%1] Enviando [ERROR] al Atari</translation> </message> <message> <location filename="../diskimage.cpp" line="3626"/> <source>[%1] Receiving %2 bytes from Atari</source> <translation>[%1] Recepción %2 bytes desde Atari</translation> </message> <message> <location filename="../diskimage.cpp" line="3635"/> <source>[%1] Sending %2 bytes to Atari</source> <translation>[%1] Enviando %2 bytes al Atari</translation> </message> <message> <location filename="../diskimage.cpp" line="3738"/> <location filename="../diskimage.cpp" line="3835"/> <source>[%1] §%2</source> <translation></translation> </message> <message> <location filename="../diskimage.cpp" line="3780"/> <source>[%1] Disassembly of %2 bytes at $%3 with CRC $%4</source> <translation>[%1] Desmontaje de %2 bytes en $%3 con CRC $%4</translation> </message> <message> <location filename="../diskimage.cpp" line="3791"/> <source>[%1] §$%2: %3 %4 %5 ; Happy signature</source> <translation>[%1] §$%2: %3 %4 %5 ; firma de Happy</translation> </message> <message> <location filename="../diskimage.cpp" line="3801"/> <source>[%1] §$%2: %3 %4 %5 JMP $%6 ; Command $%7</source> <translation>[%1] §$%2: %3 %4 %5 JMP $%6 ; Commando $%7</translation> </message> <message> <location filename="../diskimageatr.cpp" line="52"/> <location filename="../diskimageatx.cpp" line="46"/> <location filename="../diskimagepro.cpp" line="49"/> <source>Cannot read the header: %1.</source> <translation>No se puede leer el encabezado: %1.</translation> </message> <message> <location filename="../diskimageatr.cpp" line="61"/> <source>Not a valid ATR file.</source> <translation>No es un archivo ATR válido.</translation> </message> <message> <location filename="../diskimageatr.cpp" line="78"/> <location filename="../diskimageatr.cpp" line="243"/> <source>Cannot create temporary file &apos;%1&apos;: %2</source> <translation>No se puede crear un archivo temporal &apos;%1&apos;: %2</translation> </message> <message> <location filename="../diskimageatr.cpp" line="91"/> <location filename="../diskimageatr.cpp" line="255"/> <location filename="../diskimagepro.cpp" line="2374"/> <location filename="../diskimagepro.cpp" line="2410"/> <source>Cannot read from file: %1.</source> <translation>No se puede leer del archivo: %1.</translation> </message> <message> <location filename="../diskimageatr.cpp" line="100"/> <location filename="../diskimageatr.cpp" line="264"/> <source>Cannot write to temporary file &apos;%1&apos;: %2</source> <translation>No se puede escribir en el archivo temporal &apos;%1&apos;:%2</translation> </message> <message> <location filename="../diskimageatr.cpp" line="113"/> <source>Image size of &apos;%1&apos; is reported as %2 bytes in the header but it&apos;s actually %3.</source> <translation>Tamaño de imagen de &apos;%1&apos; se informa como %2 bytes en el encabezado, pero en realidad es %3.</translation> </message> <message> <location filename="../diskimageatr.cpp" line="123"/> <source>Unknown sector size (%1).</source> <translation>Tamaño de sector desconocido (%1).</translation> </message> <message> <location filename="../diskimageatr.cpp" line="171"/> <location filename="../diskimageatr.cpp" line="277"/> <source>Invalid image size (%1).</source> <translation>Tamaño de imagen no válido (%1).</translation> </message> <message> <location filename="../diskimageatr.cpp" line="184"/> <source>Too many sectors in the image (%1).</source> <translation>Demasiados sectores en la imagen (%1).</translation> </message> <message> <location filename="../diskimageatr.cpp" line="193"/> <source>The file &apos;%1&apos; has some unrecognized fields in its header.</source> <translation>El &apos;%1&apos; archivo tiene algunos campos no reconocidos en su encabezado.</translation> </message> <message> <location filename="../diskimageatr.cpp" line="200"/> <source>Cannot resize temporary file &apos;%1&apos;: %2</source> <translation>No se puede cambiar el tamaño del archivo temporal &apos;%1&apos;: %2</translation> </message> <message> <location filename="../diskimageatr.cpp" line="349"/> <location filename="../diskimageatr.cpp" line="431"/> <source>Cannot rewind temporary file &apos;%1&apos;: %2</source> <translation>No se puede rebobinar el archivo temporal &apos;%1&apos;: %2</translation> </message> <message> <location filename="../diskimageatr.cpp" line="364"/> <location filename="../diskimageatr.cpp" line="445"/> <source>Cannot read from temporary file %1: %2</source> <translation>No se puede leer del archivo temporal %1: %2</translation> </message> <message> <location filename="../diskimageatr.cpp" line="383"/> <location filename="../diskimageatr.cpp" line="548"/> <source>Detailed geometry information will be lost when reopening &apos;%1&apos; due to ATR file format limitations.</source> <translation>La información detallada de la geometría se perderá al reabrir &apos;%1&apos; debido a las limitaciones del formato de archivo ATR.</translation> </message> <message> <location filename="../diskimageatr.cpp" line="403"/> <source>Detailed disk geometry information will be lost when reopening &apos;%1&apos; due to XFD file format limitations.</source> <translation>La información detallada de la geometría del disco se perderá al volver a abrir &apos;%1&apos; debido a las limitaciones del formato de archivo XFD.</translation> </message> <message> <location filename="../diskimageatr.cpp" line="406"/> <source>XFD file format cannot handle this disk geometry. Try saving &apos;%1&apos; as ATR.</source> <translation>El formato de archivo XFD no puede manejar esta geometría de disco. Intenta guardar &apos;%1&apos; con ATR.</translation> </message> <message> <location filename="../diskimageatr.cpp" line="473"/> <source>Saving Atr images from the current format is not supported yet.</source> <translation>Aún no se admite guardar imágenes Atr del formato actual.</translation> </message> <message> <location filename="../diskimageatr.cpp" line="531"/> <source>Some sector information is lost due to destination file format limitations.</source> <translation>Parte de la información del sector se pierde debido a limitaciones de formato de archivo de destino.</translation> </message> <message> <location filename="../diskimageatr.cpp" line="565"/> <source>Cannot create new image: Cannot create temporary file &apos;%2&apos;: %3.</source> <translation>No se puede crear una nueva imagen: no se puede crear un archivo temporal &apos;%2&apos;: %3.</translation> </message> <message> <location filename="../diskimageatr.cpp" line="575"/> <location filename="../diskimageatx.cpp" line="513"/> <location filename="../diskimagepro.cpp" line="475"/> <source>Untitled image %1</source> <translation>Imagen sin título %1</translation> </message> <message> <location filename="../diskimageatr.cpp" line="602"/> <location filename="../diskimageatx.cpp" line="584"/> <location filename="../diskimagepro.cpp" line="566"/> <source>[%1] Invalid previous track number %2 ($%3) for skew alignment</source> <translation>[%1] Número de pista anterior %2 ($%3) no válido para alineación sesgada</translation> </message> <message> <location filename="../diskimageatr.cpp" line="610"/> <location filename="../diskimageatx.cpp" line="592"/> <location filename="../diskimagepro.cpp" line="574"/> <source>[%1] Invalid current track number %2 ($%3) for skew alignment</source> <translation>[%1] Número de pista actual no válido %2 ($%3) para alineación sesgada</translation> </message> <message> <location filename="../diskimageatr.cpp" line="621"/> <location filename="../diskimageatr.cpp" line="635"/> <location filename="../diskimageatx.cpp" line="601"/> <location filename="../diskimageatx.cpp" line="612"/> <location filename="../diskimagepro.cpp" line="613"/> <location filename="../diskimagepro.cpp" line="641"/> <source>[%1] Sector %2 ($%3) not found in track %4 ($%5)</source> <translation>[%1] El sector %2 ($%3) no se encuentra en la pista %4 ($%5)</translation> </message> <message> <location filename="../diskimageatr.cpp" line="736"/> <location filename="../diskimageatr.cpp" line="1073"/> <source>[%1] Write track can not write a non standard track with this kind of image.</source> <translation>[%1] Escribir pista no puede escribir una pista no estándar con este tipo de imagen.</translation> </message> <message> <location filename="../diskimageatr.cpp" line="760"/> <source>[%1] command $%2 not supported for sector %3 ($%4) with this kind of image. Ignored.</source> <translation>El comando [%1] $%2 no es compatible con el sector %3 ($%4) con este tipo de imagen. Ignorado.</translation> </message> <message> <location filename="../diskimageatr.cpp" line="768"/> <location filename="../diskimageatx.cpp" line="786"/> <location filename="../diskimagepro.cpp" line="866"/> <source>[%1] write unused sector %2 ($%3). Ignored.</source> <translation>[%1] escribe el sector %2 no utilizado ($%3). Ignorado.</translation> </message> <message> <location filename="../diskimageatr.cpp" line="792"/> <source>[%1] Cannot format: %2</source> <translation>[%1] No se puede formatear :%2</translation> </message> <message> <location filename="../diskimageatr.cpp" line="807"/> <location filename="../diskimageatr.cpp" line="823"/> <source>[%1] Cannot seek to sector %2: %3</source> <translation>[%1] No puede buscar el sector %2: %3</translation> </message> <message> <location filename="../diskimageatr.cpp" line="810"/> <source>Sector number is out of bounds.</source> <translation>Número sector está fuera del límite.</translation> </message> <message> <location filename="../diskimageatr.cpp" line="908"/> <source>[%1] readSectorStatuses return -1</source> <translation>[%1] leer estados del sector devolvió -1</translation> </message> <message> <location filename="../diskimageatr.cpp" line="949"/> <source>[%1] Cannot read from sector %2: %3.</source> <translation>[%1] No se puede leer del sector %2: %3.</translation> </message> <message> <location filename="../diskimageatr.cpp" line="1097"/> <source>[%1] Fuzzy sectors are not supported with Atr/Xfd file format</source> <translation>[%1] Los sectores Fuzzy no son compatibles con el formato de archivo ATR/XFD</translation> </message> <message> <location filename="../diskimageatr.cpp" line="1112"/> <source>[%1] Cannot write to sector %2: %3.</source> <translation>[%1] No se puede escribir sector %2: %3.</translation> </message> <message> <location filename="../diskimageatx.cpp" line="55"/> <source>Not a valid ATX file.</source> <translation>No es un archivo ATX válido.</translation> </message> <message> <location filename="../diskimageatx.cpp" line="67"/> <source>Single</source> <translation>Simple</translation> </message> <message> <location filename="../diskimageatx.cpp" line="70"/> <source>Enhanced</source> <translation>Mejorada</translation> </message> <message> <location filename="../diskimageatx.cpp" line="73"/> <source>Double</source> <translation>Doble</translation> </message> <message> <location filename="../diskimageatx.cpp" line="76"/> <source>Unknown (%1)</source> <translation>Desconocido (%1)</translation> </message> <message> <location filename="../diskimageatx.cpp" line="79"/> <source>Track layout for %1. Density is %2</source> <translation>Diseño de pista para %1. La densidad es %2</translation> </message> <message> <location filename="../diskimageatx.cpp" line="88"/> <source>[%1] Cannot seek to track header #%2: %3</source> <translation>[%1] No se puede buscar para rastrear el encabezado #%2: %3</translation> </message> <message> <location filename="../diskimageatx.cpp" line="95"/> <source>[%1] Track #%2 header could not be read</source> <translation>[%1] No se pudo leer el encabezado de la pista #%2</translation> </message> <message> <location filename="../diskimageatx.cpp" line="101"/> <source>[%1] Track header #%2 has an unknown type $%3</source> <translation>[%1] El encabezado de la pista #%2 tiene un tipo desconocido $%3</translation> </message> <message> <location filename="../diskimageatx.cpp" line="116"/> <source>[%1] Cannot seek to sector list of track $%2: %3</source> <translation>[%1] No se puede buscar la lista de sectores de la pista $%2: %3</translation> </message> <message> <location filename="../diskimageatx.cpp" line="124"/> <source>[%1] Sector List header of track $%2 could not be read</source> <translation>[%1] No se pudo leer el encabezado de la lista de sectores de la pista $%2</translation> </message> <message> <location filename="../diskimageatx.cpp" line="130"/> <source>[%1] Sector List header of track $%2 has an unknown type $%3</source> <translation>[%1] El encabezado de la lista de sectores de la pista $%2 tiene un tipo desconocido $%3</translation> </message> <message> <location filename="../diskimageatx.cpp" line="149"/> <location filename="../diskimagepro.cpp" line="149"/> <source>%1</source> <translation></translation> </message> <message> <location filename="../diskimageatx.cpp" line="179"/> <source>[%1] Cannot seek to sector data of track $%2, sector $%3: %4</source> <translation>[%1] No se pueden buscar datos de sector de la pista $%2, sector $%3: %4</translation> </message> <message> <location filename="../diskimageatx.cpp" line="186"/> <source>[%1] Cannot read sector data of track $%2, sector $%3: %4</source> <translation>[%1] No se pueden leer los datos del sector de la pista $%2, sector $%3: %4</translation> </message> <message> <location filename="../diskimageatx.cpp" line="196"/> <source>track $%1 (%2): %3</source> <translation>pista $%1 (%2): %3</translation> </message> <message> <location filename="../diskimageatx.cpp" line="203"/> <source>[%1] Cannot seek to extended sector data of track $%2: %3</source> <translation>[%1] No se pueden buscar datos del sector ampliado de la pista $%2: %3</translation> </message> <message> <location filename="../diskimageatx.cpp" line="210"/> <source>[%1] Extended sector data of track $%2 could not be read</source> <translation>[%1] No se pudieron leer los datos del sector extendido de la pista $%2</translation> </message> <message> <location filename="../diskimageatx.cpp" line="218"/> <source>[%1] Extended sector data of track $%2 references an out of bound sector %3</source> <translation>[%1] Datos del sector ampliado de la pista $%2 hace referencia a un sector fuera del límite %3</translation> </message> <message> <location filename="../diskimageatx.cpp" line="446"/> <source>Saving Atx images from the current format is not supported yet.</source> <translation>Aún no se admite guardar imágenes Atx del formato actual.</translation> </message> <message> <location filename="../diskimageatx.cpp" line="561"/> <source>[%1] Sector %2 ($%3) not found starting at index %4</source> <translation>[%1] El sector %2 ($%3) no se encuentra a partir del índice %4</translation> </message> <message> <location filename="../diskimageatx.cpp" line="709"/> <source>[%1] Too many sectors in this track. Ignored.</source> <translation>[%1] Demasiados sectores en esta pista. Ignorado.</translation> </message> <message> <location filename="../diskimageatx.cpp" line="715"/> <source>[%1] Special sync header at position %2. Ignored.</source> <translation>[%1] Encabezado de sincronización especial en la posición %2. Ignorado.</translation> </message> <message> <location filename="../diskimageatx.cpp" line="723"/> <source>[%1] Header has out of range values: Track=$%2 Sector=$%3. Ignored.</source> <translation>[%1] El encabezado tiene valores fuera de rango: Track=$%2 Sector=$%3. Ignorado.</translation> </message> <message> <location filename="../diskimageatx.cpp" line="779"/> <location filename="../diskimagepro.cpp" line="859"/> <source>[%1] sector %2 ($%3) not found. Ignored.</source> <translation>[%1] sector %2 ($%3) no encontrado. Ignorado.</translation> </message> <message> <location filename="../diskimageatx.cpp" line="814"/> <location filename="../diskimageatx.cpp" line="819"/> <source>Can not format ATX image: %1</source> <translation>No se puede formatear la imagen ATX: %1</translation> </message> <message> <location filename="../diskimageatx.cpp" line="815"/> <location filename="../diskimagepro.cpp" line="895"/> <source>Sector size (%1) not supported (should be 128)</source> <translation>Tamaño del sector (%1) no admitido (debería ser 128)</translation> </message> <message> <location filename="../diskimageatx.cpp" line="820"/> <location filename="../diskimagepro.cpp" line="81"/> <location filename="../diskimagepro.cpp" line="900"/> <source>Number of sectors (%1) not supported (max 1040)</source> <translation>Número de sectores (%1) no admitidos (máx. 1040)</translation> </message> <message> <location filename="../diskimageatx.cpp" line="934"/> <location filename="../diskimageatx.cpp" line="963"/> <location filename="../diskimageatx.cpp" line="1648"/> <location filename="../diskimagepro.cpp" line="1206"/> <location filename="../diskimagepro.cpp" line="1235"/> <location filename="../diskimagepro.cpp" line="1966"/> <source>[%1] sector layout does not map to track layout</source> <translation>[%1] el diseño del sector no se asigna al diseño de la pista</translation> </message> <message> <location filename="../diskimageatx.cpp" line="973"/> <location filename="../diskimageatx.cpp" line="1657"/> <source>[%1] no sector found at index %2 in track %3</source> <translation>[%1] no se encontró ningún sector en el índice %2 en la pista %3</translation> </message> <message> <location filename="../diskimageatx.cpp" line="1083"/> <location filename="../diskimagepro.cpp" line="1371"/> <source>[%1] Bad sector (status $%2) Grrr Grrr !</source> <translation>[%1] Sector defectuoso (estado $%2) ¡Grrr Grrr!</translation> </message> <message> <location filename="../diskimageatx.cpp" line="1092"/> <source>[%1] Deleted sector (status $%2)</source> <translation>[%1] Sector eliminado (estado $%2)</translation> </message> <message> <location filename="../diskimageatx.cpp" line="1137"/> <location filename="../diskimagepro.cpp" line="1386"/> <source>[%1] Weak sector at offset %2</source> <translation>[%1] Sector débil en compensación %2</translation> </message> <message> <location filename="../diskimageatx.cpp" line="1143"/> <location filename="../diskimagepro.cpp" line="1396"/> <source>[%1] CRC error (status $%2) on sector index #%3 among %4 phantom sectors</source> <translation>[%1] Error de CRC (estado $%2) en el índice de sector #%3 entre %4 sectores fantasmas</translation> </message> <message> <location filename="../diskimageatx.cpp" line="1150"/> <location filename="../diskimageatx.cpp" line="1173"/> <location filename="../diskimagepro.cpp" line="1424"/> <source>[%1] Read sector index #%2 among %3 phantom sectors</source> <translation>[%1] Leer índice de sector #%2 entre %3 sectores fantasmas</translation> </message> <message> <location filename="../diskimageatx.cpp" line="1157"/> <location filename="../diskimagepro.cpp" line="1408"/> <source>[%1] CRC error (status $%2)</source> <translation>[%1] Error de CRC (estado $%2)</translation> </message> <message> <location filename="../diskimageatx.cpp" line="1165"/> <location filename="../diskimagepro.cpp" line="1416"/> <source>[%1] Read status $%2</source> <translation>[%1] Leer estado $%2</translation> </message> <message> <location filename="../diskimageatx.cpp" line="1665"/> <source>[%1] sector %2 does not match sector number at index %3 in track %4</source> <translation>[%1] el sector %2 no coincide con el número de sector en el índice %3 en la pista %4</translation> </message> <message> <location filename="../diskimageatx.cpp" line="1686"/> <source>[%1] Fuzzy sector starting at byte %2</source> <translation>[%1] Sector difuso que comienza en el byte %2</translation> </message> <message> <location filename="../diskimageatx.cpp" line="1692"/> <location filename="../diskimageatx.cpp" line="1774"/> <location filename="../diskimageatx.cpp" line="1856"/> <location filename="../diskimagepro.cpp" line="2002"/> <location filename="../diskimagepro.cpp" line="2099"/> <location filename="../diskimagepro.cpp" line="2221"/> <source>[%1] Short sector: %2 bytes</source> <translation>[%1] Sector corto: %2 bytes</translation> </message> <message> <location filename="../diskimageatx.cpp" line="1697"/> <location filename="../diskimageatx.cpp" line="1779"/> <location filename="../diskimageatx.cpp" line="1861"/> <location filename="../diskimagepro.cpp" line="2007"/> <location filename="../diskimagepro.cpp" line="2104"/> <location filename="../diskimagepro.cpp" line="2226"/> <source>[%1] CRC error (type $%2)</source> <translation>[%1] Error CRC (tipo $%2)</translation> </message> <message> <location filename="../diskimageatx.cpp" line="1752"/> <location filename="../diskimageatx.cpp" line="1832"/> <source>[%1] Sector %2 does not exist in ATX file</source> <translation>[%1] El sector %2 no existe en el archivo ATX</translation> </message> <message> <location filename="../diskimagepro.cpp" line="57"/> <source>Not a valid PRO file.</source> <translation>No es un archivo válido PRO.</translation> </message> <message> <location filename="../diskimagepro.cpp" line="63"/> <source>Unsupported PRO file version</source> <translation>Versión de archivo PRO no compatible</translation> </message> <message> <location filename="../diskimagepro.cpp" line="72"/> <source>Unsupported PRO file size</source> <translation>Tamaño de archivo PRO no admitido</translation> </message> <message> <location filename="../diskimagepro.cpp" line="136"/> <source>Track layout for %1</source> <translation>Diseño de pista para %1</translation> </message> <message> <location filename="../diskimagepro.cpp" line="165"/> <source>track $%1: %2</source> <translation>pista $%1: %2</translation> </message> <message> <location filename="../diskimagepro.cpp" line="324"/> <source>Saving Pro images from the current format is not supported yet.</source> <translation>Aún no se admite guardar imágenes Pro del formato actual.</translation> </message> <message> <location filename="../diskimagepro.cpp" line="403"/> <source>The number of duplicate sectors exceeds the Pro file capacity.</source> <translation>El número de sectores duplicados supera la capacidad del archivo Pro.</translation> </message> <message> <location filename="../diskimagepro.cpp" line="544"/> <source>[%1] sector %2 ($%3) not found starting at index %4</source> <translation>[%1] sector %2 ($%3) que no se encuentran comenzando en el índice %4</translation> </message> <message> <location filename="../diskimagepro.cpp" line="750"/> <location filename="../diskimagepro.cpp" line="1746"/> <source>[%1] More than 255 phantom sectors (unsupported with PRO format)</source> <translation>[%1] Más de 255 sectores fantasmas (no compatibles con el formato PRO)</translation> </message> <message> <location filename="../diskimagepro.cpp" line="765"/> <location filename="../diskimagepro.cpp" line="1761"/> <source>[%1] More than 6 phantom sectors for a given sector number (unsupported with PRO format)</source> <translation>[%1] Más de 6 sectores fantasmas para un número de sector determinado (no compatible con el formato PRO)</translation> </message> <message> <location filename="../diskimagepro.cpp" line="894"/> <location filename="../diskimagepro.cpp" line="899"/> <source>Can not format PRO image: %1</source> <translation>No se puede formatear la imagen PRO: %1</translation> </message> <message> <location filename="../diskimagepro.cpp" line="1246"/> <location filename="../diskimagepro.cpp" line="1976"/> <source>[%1] sector %2 does not match sector number at index %3</source> <translation>[%1] el sector %2 no coincide con el número de sector en el índice %3</translation> </message> <message> <location filename="../diskimagepro.cpp" line="1333"/> <location filename="../diskimagepro.cpp" line="2186"/> <source>[%1] Sector %2 (phantom %3) does not exist in PRO file</source> <translation>[%1] El sector %2 (phantom %3) no existe en el archivo PRO</translation> </message> <message> <location filename="../diskimagepro.cpp" line="1996"/> <source>[%1] Fuzzy sector among phantom sectors (unsupported with PRO format)</source> <translation>[%1] Sector Fuzzy entre sectores phantom (no compatible con el formato PRO)</translation> </message> <message> <location filename="../diskimagepro.cpp" line="2048"/> <location filename="../diskimagepro.cpp" line="2173"/> <source>[%1] Sector %2 does not exist in PRO file</source> <translation>[%1] El sector %2 no existe en el archivo PRO</translation> </message> <message> <location filename="../diskimagepro.cpp" line="2077"/> <source>[%1] Sector can not be fuzzed because all duplicate sector slots are already used</source> <translation>[%1] El sector no se puede desviar porque ya se utilizan todos los espacios de sectores duplicados</translation> </message> <message> <location filename="../diskimagepro.cpp" line="2130"/> <location filename="../diskimagepro.cpp" line="2272"/> <location filename="../diskimagepro.cpp" line="2296"/> <source>[%1] Empty duplicate sector slot not found in Pro file</source> <translation>[%1] No se encontró el espacio vacío del sector duplicado en el archivo PRO</translation> </message> <message> <location filename="../diskimagepro.cpp" line="2180"/> <source>[%1] Duplicate sector $%2: writing number %3</source> <translation>[%1] Sector duplicado $%2: número de escritura %3</translation> </message> <message> <location filename="../diskimagepro.cpp" line="2393"/> <source>[%1] Invalid number of phantom sectors (%2) for sector %3</source> <translation>[%1] Número no válido de sectores fantasmas (%2) para el sector %3</translation> </message> <message> <location filename="../diskimagepro.cpp" line="2446"/> <source>[%1] Sector %2 has an invalid phantom index %3.</source> <translation>[%1] El sector %2 tiene un índice phantom %3 no válido.</translation> </message> </context> <context> <name>SioWorker</name> <message> <location filename="../sioworker.cpp" line="140"/> <source>Cannot read command frame.</source> <translation>No se puede leer trama de comando.</translation> </message> <message> <location filename="../sioworker.cpp" line="142"/> <source>Trying to reconnect SIO port...</source> <translation>Intentando volver a conectar el puerto SIO...</translation> </message> <message> <location filename="../sioworker.cpp" line="170"/> <source>[%1] command: $%2, aux: $%3 ignored because the image explorer is open.</source> <translation>[%1] comando: $%2, aux: $%3 ignorado porque el explorador de imagen está abierta.</translation> </message> <message> <location filename="../sioworker.cpp" line="177"/> <source>[%1] command: $%2, aux: $%3 ignored: %4</source> <translation>[%1] comando: $%2, aux: $%3 ignorado: %4</translation> </message> <message> <location filename="../sioworker.cpp" line="184"/> <source>[%1] command: $%2, aux: $%3 ignored.</source> <translation>[%1] comando: $%2, aux: $%3 ignorado.</translation> </message> <message> <location filename="../sioworker.cpp" line="201"/> <source>[810 Rev. E] Upload and Execute Code or [Speedy 1050] Format Disk Asynchronously</source> <translation>[810 Rev. E] Cargar y ejecutar código o [Speedy 1050] Formatear disco de forma asincrónica</translation> </message> <message> <location filename="../sioworker.cpp" line="202"/> <location filename="../sioworker.cpp" line="266"/> <source>Format Single Density Disk</source> <translation>Formatear disco de densidad única</translation> </message> <message> <location filename="../sioworker.cpp" line="203"/> <location filename="../sioworker.cpp" line="267"/> <source>Format Enhanced Density Disk</source> <translation>Formatear disco de densidad mejorada</translation> </message> <message> <location filename="../sioworker.cpp" line="204"/> <source>[1050, Happy 1050] Run Speed Diagnostic or [Turbo 1050] Service Put</source> <translation>[1050, Happy 1050] Ejecutar diagnóstico de velocidad o [Turbo 1050] Puesta en servicio</translation> </message> <message> <location filename="../sioworker.cpp" line="205"/> <source>[1050, Happy 1050] Run Diagnostic or [Turbo 1050] Service Get</source> <translation>[1050, Happy 1050] Ejecutar diagnóstico o [Turbo 1050] Obtener servicio</translation> </message> <message> <location filename="../sioworker.cpp" line="206"/> <source>[Happy 1050 Rev. 7] Clear Sector Flags (Broadcast)</source> <translation>[Happy 1050 Rev. 7] Borrar las banderas del sector (transmisión)</translation> </message> <message> <location filename="../sioworker.cpp" line="207"/> <source>[Happy 1050 Rev. 7] Get Sector Flags (Broadcast)</source> <translation>[Happy 1050 Rev. 7] Obtener indicadores de sector (transmisión)</translation> </message> <message> <location filename="../sioworker.cpp" line="208"/> <source>[Happy 1050 Rev. 7] Send Sector (Broadcast)</source> <translation>[Happy 1050 Rev. 7] Sector de envío (transmisión)</translation> </message> <message> <location filename="../sioworker.cpp" line="209"/> <source>[Super Archiver 1050, Happy 1050, Speedy 1050, Duplicator 1050] Poll Speed</source> <translation>[Super Archiver 1050, Happy 1050, Speedy 1050, Duplicator 1050] Velocidad de encuesta</translation> </message> <message> <location filename="../sioworker.cpp" line="210"/> <source>[Happy 810/1050 Rev. 7] Read Track or [Speedy 1050] Add or Delete a Command</source> <translation>[Happy 810/1050 Rev. 7] Leer pista o [Speedy 1050] Agregar o eliminar un comando</translation> </message> <message> <location filename="../sioworker.cpp" line="211"/> <source>[Chip 810, Super Archiver 1050] Write Sector using Index or [Happy 810/1050 Rev. 7] Read All Sectors</source> <translation>[Chip 810, Super Archiver 1050] Escribir sector usando índice o [Happy 810/1050 Rev. 7] Leer todos los sectores</translation> </message> <message> <location filename="../sioworker.cpp" line="212"/> <source>[Chip 810, Super Archiver 1050] Read All Sector Statuses or [Happy 810/1050 Rev. 7] Set Skew Alignment</source> <translation>[Chip 810, Super Archiver 1050] Leer todos los estados de sector o [Happy 810/1050 Rev. 7] Establecer alineación sesgada</translation> </message> <message> <location filename="../sioworker.cpp" line="213"/> <source>[Chip 810, Super Archiver 1050] Read Sector using Index or [Happy 810/1050 Rev. 7] Read Skew Alignment or [Speedy 1050] Configure Drive and Display</source> <translation>[Chip 810, Super Archiver 1050] Leer sector usando índice o [Happy 810/1050 Rev. 7] Leer alineación sesgada o [Speedy 1050] Configurar unidad y visualización</translation> </message> <message> <location filename="../sioworker.cpp" line="214"/> <source>[Chip 810, Super Archiver 1050] Write Track</source> <translation>[Chip 810, Super Archiver 1050] Pista de escritura</translation> </message> <message> <location filename="../sioworker.cpp" line="215"/> <source>[Chip 810, Super Archiver 1050] Read Track (128 bytes)</source> <translation>[Chip 810, Super Archiver 1050] Leer pista (128 bytes)</translation> </message> <message> <location filename="../sioworker.cpp" line="218"/> <source>[Happy 810/1050 Rev. 7] Set Idle Timeout</source> <translation>[Happy 810/1050 Rev. 7] Establecer tiempo de espera inactivo</translation> </message> <message> <location filename="../sioworker.cpp" line="220"/> <source>[Happy 810/1050 Rev. 7] Set Alternate Device ID</source> <translation>[Happy 810/1050 Rev. 7] Establecer ID de dispositivo alternativo</translation> </message> <message> <location filename="../sioworker.cpp" line="222"/> <source>[Happy 810/1050 Rev. 7] Reinitialize Drive</source> <translation>[Happy 810/1050 Rev. 7] Reinicializar Drive</translation> </message> <message> <location filename="../sioworker.cpp" line="223"/> <source>[Happy 810/1050 Rev. 7] Configure Drive</source> <translation>[Happy 810/1050 Rev. 7] Configurar unidad</translation> </message> <message> <location filename="../sioworker.cpp" line="224"/> <source>[Happy 810/1050 Rev. 7] Write Track with Skew Alignment</source> <translation>[Happy 810/1050 Rev. 7] Escribir pista con alineación sesgada</translation> </message> <message> <location filename="../sioworker.cpp" line="225"/> <source>[Happy 810/1050 Rev. 7] Init Skew Alignment</source> <translation>[Happy 810/1050 Rev. 7] Alineación sesgada inicial</translation> </message> <message> <location filename="../sioworker.cpp" line="226"/> <source>[Happy 810/1050 Rev. 7] Prepare backup or [Speedy 1050] Configure Slow/Fast Speed</source> <translation>[Happy 810/1050 Rev. 7] Prepare una copia de seguridad o [Speedy 1050] Configure la velocidad lenta/rápida</translation> </message> <message> <location filename="../sioworker.cpp" line="227"/> <source>[Chip 810, Super Archiver 1050] Set RAM Buffer or [Speedy 1050] Jump to Address</source> <translation>[Chip 810, Super Archiver 1050] Establecer buffer RAM o [Speedy 1050] Saltar a dirección</translation> </message> <message> <location filename="../sioworker.cpp" line="228"/> <source>[Chip 810] Upload and Execute Code or [Speedy 1050] Jump to Address with Acknowledge</source> <translation>[Chip 810] Cargar y ejecutar código o [Speedy 1050] Saltar a la dirección con reconocimiento</translation> </message> <message> <location filename="../sioworker.cpp" line="229"/> <source>[Super Archiver 1050, Speedy 1050, Turbo 1050, Duplicator 1050] Get PERCOM Block or [Chip 810] Set Shutdown Delay</source> <translation>[Super Archiver 1050, Speedy 1050, Turbo 1050, Duplicator 1050] Obtener bloque PERCOM o [Chip 810] Establecer retardo de apagado</translation> </message> <message> <location filename="../sioworker.cpp" line="230"/> <source>[Speedy 1050, Turbo 1050, Duplicator 1050] Set PERCOM Block or [Chip 810, Super Archiver 1050] Open CHIP</source> <translation>[Speedy 1050, Turbo 1050, Duplicator 1050] Establecer bloque PERCOM o [Chip 810, Super Archiver 1050] Abrir CHIP</translation> </message> <message> <location filename="../sioworker.cpp" line="231"/> <location filename="../sioworker.cpp" line="295"/> <source>Put Sector (no verify)</source> <translation>Poner sector (no verificar)</translation> </message> <message> <location filename="../sioworker.cpp" line="232"/> <source>[Happy 810] Execute code or [Speedy 1050] Flush Write</source> <translation>[Happy 810] Ejecutar código o [Speedy 1050] Escritura al ras</translation> </message> <message> <location filename="../sioworker.cpp" line="233"/> <location filename="../sioworker.cpp" line="297"/> <source>Read Sector</source> <translation>Leer sector</translation> </message> <message> <location filename="../sioworker.cpp" line="234"/> <location filename="../sioworker.cpp" line="298"/> <source>Get Status</source> <translation>Obtener el estado</translation> </message> <message> <location filename="../sioworker.cpp" line="235"/> <source>[Chip 810, Super Archiver 1050, 810 Rev. E] Get RAM Buffer</source> <translation>[Chip 810, Super Archiver 1050, 810 Rev. E] Obtener buffer RAM</translation> </message> <message> <location filename="../sioworker.cpp" line="236"/> <location filename="../sioworker.cpp" line="237"/> <source>[Happy 810] Execute code</source> <translation>[Happy 810] Ejecutar código</translation> </message> <message> <location filename="../sioworker.cpp" line="238"/> <location filename="../sioworker.cpp" line="302"/> <source>Write Sector (with verify)</source> <translation>Escribir sector (con verificar)</translation> </message> <message> <location filename="../sioworker.cpp" line="239"/> <source>[Chip 810, Super Archiver 1050] Set Trace On/Off</source> <translation>[Chip 810, Super Archiver 1050] Activar/desactivar el seguimiento</translation> </message> <message> <location filename="../sioworker.cpp" line="240"/> <source>[Speedy 1050] Write Track at Address</source> <translation>[Speedy 1050] Escribir pista en la dirección</translation> </message> <message> <location filename="../sioworker.cpp" line="241"/> <source>[Duplicator 1050] Analyze Track</source> <translation>[Duplicator 1050] Analizar pista</translation> </message> <message> <location filename="../sioworker.cpp" line="242"/> <source>[Super Archiver 1050] Write Fuzzy Sector using Index or [Speedy 1050] Read Track at Address or [Duplicator 1050] Set Drive buffer Mode</source> <translation>[Super Archiver 1050] Escribir sector difuso usando índice o [Speedy 1050] Leer pista en dirección o [Duplicador 1050] Establecer modo de buffer de unidad</translation> </message> <message> <location filename="../sioworker.cpp" line="243"/> <source>[Duplicator 1050] Custom Track Format</source> <translation>[Duplicator 1050] Formato de pista personalizado</translation> </message> <message> <location filename="../sioworker.cpp" line="244"/> <source>[Duplicator 1050] Set Density Sensing</source> <translation>[Duplicator 1050] Establecer detección de densidad</translation> </message> <message> <location filename="../sioworker.cpp" line="245"/> <source>[Super Archiver 1050, Duplicator 1050] Format with Custom Sector Skewing</source> <translation>[Super Archiver 1050, Duplicator 1050] Formato con sesgo de sector personalizado</translation> </message> <message> <location filename="../sioworker.cpp" line="246"/> <source>[Super Archiver 1050] Read Track (256 bytes) or [Duplicator 1050] Seek to Track</source> <translation>[Super Archiver 1050] Leer pista (256 bytes) o [Duplicador 1050] Buscar pista</translation> </message> <message> <location filename="../sioworker.cpp" line="247"/> <source>[Speedy 1050] Get SIO Routine size or [Duplicator 1050] Change Drive Hold on Time</source> <translation>[Speedy 1050] Obtener el tamaño de la rutina SIO o [Duplicator 1050] Cambiar el tiempo de espera de la unidad</translation> </message> <message> <location filename="../sioworker.cpp" line="248"/> <source>[Speedy 1050] Get SIO Routine relocated at Address</source> <translation>[Speedy 1050] Reubicar la rutina SIO en la dirección</translation> </message> <message> <location filename="../sioworker.cpp" line="249"/> <source>[Duplicator 1050] Change Drive RPM</source> <translation>[Duplicator 1050] Cambiar las RPM de la unidad</translation> </message> <message> <location filename="../sioworker.cpp" line="250"/> <source>[Duplicator 1050] Upload Sector Pattern and Read Track</source> <translation>[Duplicator 1050] Cargar patrón de sector y leer pista</translation> </message> <message> <location filename="../sioworker.cpp" line="251"/> <source>[Duplicator 1050] Upload Sector Pattern and Write Buffer to Disk</source> <translation>[Duplicator 1050] Cargar patrón de sector y escribir buffer en disco</translation> </message> <message> <location filename="../sioworker.cpp" line="252"/> <source>[Happy 810/1050 Rev. 7] High Speed Put Sector (no verify)</source> <translation>[Happy 810/1050 Rev. 7] Sector Put de alta velocidad (sin verificación)</translation> </message> <message> <location filename="../sioworker.cpp" line="253"/> <source>[Super Archiver 1050] Write Fuzzy Sector</source> <translation>[Super Archiver 1050] Escribir sector difuso</translation> </message> <message> <location filename="../sioworker.cpp" line="254"/> <source>[Happy 810/1050 Rev. 7] High Speed Read Sector or [Duplicator 1050] Run Uploaded Program at Address</source> <translation>[Happy 810/1050 Rev. 7] Sector de lectura de alta velocidad o [Duplicator 1050] Ejecutar programa cargado en la dirección</translation> </message> <message> <location filename="../sioworker.cpp" line="255"/> <source>[Super Archiver 1050] Set Speed or [Duplicator 1050] Set Load Address</source> <translation>[Super Archiver 1050] Establecer velocidad o [Duplicator 1050] Establecer dirección de carga</translation> </message> <message> <location filename="../sioworker.cpp" line="256"/> <source>[Super Archiver 1050] Read Memory or [Duplicator 1050] Get Sector Data</source> <translation>[Super Archiver 1050] Leer memoria o [Duplicator 1050] Obtener datos del sector</translation> </message> <message> <location filename="../sioworker.cpp" line="257"/> <source>[Super Archiver 1050] Upload and Execute Code or [Duplicator 1050] Upload Data to Drive</source> <translation>[Super Archiver 1050] Cargar y ejecutar código o [Duplicator 1050] Cargar datos a Drive</translation> </message> <message> <location filename="../sioworker.cpp" line="258"/> <source>[Duplicator 1050] Upload Sector Data in Buffer</source> <translation>[Duplicator 1050] Cargar datos del sector en buffer</translation> </message> <message> <location filename="../sioworker.cpp" line="259"/> <source>[Happy 810/1050 Rev. 7] High Speed Write Sector (with verify) or [Duplicator 1050] Write Sector with Deleted Data</source> <translation>[Happy 810/1050 Rev. 7] Sector de escritura de alta velocidad (con verificación) o [Duplicator 1050] Sector de escritura con datos eliminados</translation> </message> <message> <location filename="../sioworker.cpp" line="260"/> <source>[810 Rev. E] Execute Code</source> <translation>[810 Rev. E] Código de ejecución</translation> </message> <message> <location filename="../sioworker.cpp" line="261"/> <location filename="../sioworker.cpp" line="314"/> <source>Unknown</source> <translation>Desconocido</translation> </message> <message> <location filename="../sioworker.cpp" line="268"/> <source>Run Speed Diagnostic</source> <translation>Ejecutar diagnóstico de velocidad</translation> </message> <message> <location filename="../sioworker.cpp" line="269"/> <source>Run Diagnostic</source> <translation>Ejecutar diagnóstico</translation> </message> <message> <location filename="../sioworker.cpp" line="270"/> <source>Happy Clear Sector Flags (Broadcast)</source> <translation>Borrar indicadores de sector Happy (difusión)</translation> </message> <message> <location filename="../sioworker.cpp" line="271"/> <source>Happy Get Sector Flags (Broadcast)</source> <translation>Obtener banderas de sector Happy (difusión)</translation> </message> <message> <location filename="../sioworker.cpp" line="272"/> <source>Happy Send Sector (Broadcast)</source> <translation>Sector de envío Happy (difusión)</translation> </message> <message> <location filename="../sioworker.cpp" line="273"/> <source>Poll Speed</source> <translation>Velocidad de encuesta</translation> </message> <message> <location filename="../sioworker.cpp" line="274"/> <source>Happy Read Track</source> <translation>Leyendo pista Happy</translation> </message> <message> <location filename="../sioworker.cpp" line="275"/> <source>Super Archiver Write Sector using Index or Happy Read All Sectors</source> <translation>Super Archiver escribiendo sector usando en índice o Happy leyendo en todos los sectores</translation> </message> <message> <location filename="../sioworker.cpp" line="276"/> <source>Super Archiver Read All Sector Statuses or Happy Set Skew Alignment</source> <translation>Super Archiver lee todos los estados del sector o alineación de sesgo Happy</translation> </message> <message> <location filename="../sioworker.cpp" line="277"/> <source>Super Archiver Read Sector using Index or Happy Read Skew Alignment</source> <translation>Super Archiver leyendo Sector usando de índice o Happy leyendo alineación sesgada</translation> </message> <message> <location filename="../sioworker.cpp" line="278"/> <source>Super Archiver Write Track or Happy Write Track</source> <translation>Super Archiver escribir Track o Happy escribir Track</translation> </message> <message> <location filename="../sioworker.cpp" line="279"/> <source>Super Archiver Read Track (128 bytes) or Happy Write All Sectors</source> <translation>Super Archiver leer pista (128 bytes) o Happy escritura en todos los sectores</translation> </message> <message> <location filename="../sioworker.cpp" line="282"/> <source>Happy Set Idle Timeout</source> <translation>Establecer tiempo de espera inactivo de Happy</translation> </message> <message> <location filename="../sioworker.cpp" line="284"/> <source>Happy Set Alternate Device ID</source> <translation>Happy Set ID de dispositivo alternativo</translation> </message> <message> <location filename="../sioworker.cpp" line="286"/> <source>Happy Reinitialize Drive</source> <translation>Reinicio de unidad Happy</translation> </message> <message> <location filename="../sioworker.cpp" line="287"/> <source>Happy Configure Drive</source> <translation>Configurar unidad Happy</translation> </message> <message> <location filename="../sioworker.cpp" line="288"/> <source>Happy Write Track with Skew Alignment</source> <translation>Pista de escritura Happy con alineación sesgada</translation> </message> <message> <location filename="../sioworker.cpp" line="289"/> <source>Happy Init Skew Alignment</source> <translation>Happy Init Skew Alignment</translation> </message> <message> <location filename="../sioworker.cpp" line="290"/> <source>Happy Prepare backup</source> <translation>Happy Prepare copia de seguridad</translation> </message> <message> <location filename="../sioworker.cpp" line="291"/> <source>Super Archiver Set RAM Buffer</source> <translation>Super Archiver Set RAM Buffer</translation> </message> <message> <location filename="../sioworker.cpp" line="292"/> <source>Chip 810 Upload and Execute Code</source> <translation>Código de carga y ejecución del chip 810</translation> </message> <message> <location filename="../sioworker.cpp" line="293"/> <source>Get PERCOM Block</source> <translation>Obtener bloque PERCOM</translation> </message> <message> <location filename="../sioworker.cpp" line="294"/> <source>Set PERCOM Block or Super Archiver Open CHIP</source> <translation>Establecer bloque PERCOM o CHIP abierto de Super Archiver</translation> </message> <message> <location filename="../sioworker.cpp" line="296"/> <location filename="../sioworker.cpp" line="300"/> <location filename="../sioworker.cpp" line="301"/> <source>Happy Execute code</source> <translation>Código de ejecución Happy</translation> </message> <message> <location filename="../sioworker.cpp" line="299"/> <source>Super Archiver Get RAM Buffer</source> <translation>Super Archiver Obtener buffer RAM</translation> </message> <message> <location filename="../sioworker.cpp" line="303"/> <source>Super Archiver Set Trace On/Off</source> <translation>Super Archiver Establecer seguimiento de encendido/apagado</translation> </message> <message> <location filename="../sioworker.cpp" line="304"/> <source>Super Archiver Write Fuzzy Sector using Index</source> <translation>Super Archiver escribir sector difuso usando índice</translation> </message> <message> <location filename="../sioworker.cpp" line="305"/> <source>Super Archiver Format with Custom Sector Skewing</source> <translation>Formato de Super Archiver con sesgo de sector personalizado</translation> </message> <message> <location filename="../sioworker.cpp" line="306"/> <source>Super Archiver Read Track (256 bytes)</source> <translation>Super Archiver Leer Track (256 bytes)</translation> </message> <message> <location filename="../sioworker.cpp" line="307"/> <source>Happy High Speed Put Sector (no verify)</source> <translation>Happy aplicar el sector Put de alta velocidad (sin verificar)</translation> </message> <message> <location filename="../sioworker.cpp" line="308"/> <source>Super Archiver Write Fuzzy Sector</source> <translation>Super Archiver escribe sector borroso</translation> </message> <message> <location filename="../sioworker.cpp" line="309"/> <source>Happy High Speed Read Sector</source> <translation>Happy sector de lectura de alta velocidad</translation> </message> <message> <location filename="../sioworker.cpp" line="310"/> <source>Super Archiver Set Speed</source> <translation>Super Archiver velocidad fijada</translation> </message> <message> <location filename="../sioworker.cpp" line="311"/> <source>Super Archiver Read Memory</source> <translation>Memoria de lectura de Super Archiver</translation> </message> <message> <location filename="../sioworker.cpp" line="312"/> <source>Super Archiver Upload and Execute Code</source> <translation>Código de carga y ejecución de Super Archiver</translation> </message> <message> <location filename="../sioworker.cpp" line="313"/> <source>Happy High Speed Write Sector (with verify)</source> <translation>Sector de escritura de alta velocidad Happy (con verificación)</translation> </message> <message> <location filename="../sioworker.cpp" line="397"/> <source>Disk 1 (below autoboot)</source> <translation>Disco 1 (con autoboot)</translation> </message> <message> <location filename="../sioworker.cpp" line="414"/> <source>Disk %1</source> <translation>Disco %1</translation> </message> <message> <location filename="../sioworker.cpp" line="420"/> <source>Printer %1</source> <translation>Impresora %1</translation> </message> <message> <location filename="../sioworker.cpp" line="423"/> <source>Smart device (APE time + URL)</source> <translation>Dispositivo inteligente (hora APE + URL)</translation> </message> <message> <location filename="../sioworker.cpp" line="426"/> <source>RespeQt Client</source> <translation>AspeQt Cliente</translation> </message> <message> <location filename="../sioworker.cpp" line="432"/> <source>RS232 %1</source> <translation></translation> </message> <message> <location filename="../sioworker.cpp" line="435"/> <source>PCLINK</source> <translation></translation> </message> <message> <location filename="../sioworker.cpp" line="438"/> <source>Device $%1</source> <translation>Unidad $%1</translation> </message> <message> <location filename="../sioworker.cpp" line="448"/> <source>Save test XML File</source> <translation>Guardar archivo XML de prueba</translation> </message> <message> <location filename="../sioworker.cpp" line="448"/> <source>XML Files (*.xml)</source> <translation>Archivos XML (*.xml)</translation> </message> </context> <context> <name>SmartDevice</name> <message> <location filename="../smartdevice.cpp" line="53"/> <source>[%1] Read date/time (%2).</source> <translation>[%1] Fecha/hora de lectura (%2).</translation> </message> <message> <location filename="../smartdevice.cpp" line="73"/> <source>[%1] Read data frame failed</source> <translation>[%1] Falló el marco de datos</translation> </message> <message> <location filename="../smartdevice.cpp" line="84"/> <source>URL [%1] submitted</source> <translation>URL [%1] enviada</translation> </message> <message> <location filename="../smartdevice.cpp" line="89"/> <location filename="../smartdevice.cpp" line="101"/> <source>[%1] command: $%2, aux: $%3 NAKed.</source> <translation>[%1] comando: $%2, aux: $%3 NAKed.</translation> </message> </context> <context> <name>SpartaDosFileSystem</name> <message> <location filename="../atarifilesystem.cpp" line="1260"/> <location filename="../atarifilesystem.cpp" line="1289"/> <source>Atari file system error</source> <translation>Error en archivo de sistema</translation> </message> <message> <location filename="../atarifilesystem.cpp" line="1260"/> <source>Cannot create file &apos;%1&apos;.</source> <translation>No se puede crear el archivo &apos;%1&apos;.</translation> </message> <message> <location filename="../atarifilesystem.cpp" line="1289"/> <source>Cannot write to &apos;%1&apos;.</source> <translation>No se puede escribir &apos;%1&apos;.</translation> </message> </context> <context> <name>StandardSerialPortBackend</name> <message> <location filename="../serialport-unix.cpp" line="93"/> <location filename="../serialport-win32.cpp" line="78"/> <location filename="../serialport-win32.cpp" line="94"/> <source>Cannot open serial port &apos;%1&apos;: %2</source> <translation>No se puede abrir puerto serial &apos;%1&apos;: %2</translation> </message> <message> <location filename="../serialport-unix.cpp" line="102"/> <source>Cannot get serial port status</source> <translation>No se puede obtener el estado del puerto serie</translation> </message> <message> <location filename="../serialport-unix.cpp" line="107"/> <source>Cannot set DTR and RTS lines in serial port &apos;%1&apos;: %2</source> <translation>No se pueden establecer líneas DTR y RTS en serie &apos;%1&apos;: %2</translation> </message> <message> <location filename="../serialport-unix.cpp" line="139"/> <source>Emulation started through standard serial port backend on &apos;%1&apos; with %2 handshaking.</source> <translation>Emulación inicia a través de back-end estándar de puerto serial de &apos;%1&apos; con %2 handshaking.</translation> </message> <message> <location filename="../serialport-unix.cpp" line="154"/> <location filename="../serialport-win32.cpp" line="154"/> <source>Cannot close serial port: %1</source> <translation>No se puede cerrar el puerto serial: %1</translation> </message> <message> <location filename="../serialport-unix.cpp" line="264"/> <location filename="../serialport-unix.cpp" line="277"/> <location filename="../serialport-unix.cpp" line="310"/> <location filename="../serialport-win32.cpp" line="281"/> <source>Cannot set serial port speed to %1: %2</source> <translation>No se puede establecer la velocidad del puerto serial para %1: %2</translation> </message> <message> <location filename="../serialport-unix.cpp" line="264"/> <source>Closest possible speed is %2.</source> <translation>La velocidad posible más cercana es %2.</translation> </message> <message> <location filename="../serialport-unix.cpp" line="283"/> <location filename="../serialport-unix.cpp" line="323"/> <location filename="../serialport-win32.cpp" line="311"/> <source>%1 bits/sec</source> <translation>%1 bits/segundo</translation> </message> <message> <location filename="../serialport-unix.cpp" line="284"/> <location filename="../serialport-unix.cpp" line="324"/> <location filename="../serialport-win32.cpp" line="312"/> <source>Serial port speed set to %1.</source> <translation>Velocidad del puerto serial configurado para %1.</translation> </message> <message> <location filename="../serialport-unix.cpp" line="319"/> <source>Failed to set serial port speed to %1</source> <translation>Error al establecer la velocidad del puerto serie a %1</translation> </message> <message> <location filename="../serialport-unix.cpp" line="343"/> <location filename="../serialport-unix.cpp" line="471"/> <location filename="../serialport-win32.cpp" line="331"/> <location filename="../serialport-win32.cpp" line="464"/> <source>Cannot clear serial port read buffer: %1</source> <translation>No se puede borrar el buffer de lectura del puerto serie: %1</translation> </message> <message> <location filename="../serialport-unix.cpp" line="440"/> <location filename="../serialport-unix.cpp" line="456"/> <location filename="../serialport-unix.cpp" line="489"/> <source>Cannot retrieve serial port status: %1</source> <translation>No se puede recuperar el estado del puerto serie: %1</translation> </message> <message> <location filename="../serialport-unix.cpp" line="545"/> <location filename="../serialport-win32.cpp" line="534"/> <source>Data frame checksum error, expected: %1, got: %2. (%3)</source> <translation>Los datos de suma de comprobación de errores de trama, que se espera: %1, obtuvo: %2. (%3)</translation> </message> <message> <location filename="../serialport-unix.cpp" line="636"/> <location filename="../serialport-unix.cpp" line="677"/> <location filename="../serialport-win32.cpp" line="650"/> <location filename="../serialport-win32.cpp" line="656"/> <source>Cannot read from serial port: %1</source> <translation>No se puede leer desde el puerto serial: %1</translation> </message> <message> <location filename="../serialport-unix.cpp" line="651"/> <source>Serial port read timeout. %1 of %2 read in %3 ms</source> <translation>Tiempo de espera de lectura de puerto serie. %1 de %2 leído en %3 ms</translation> </message> <message> <location filename="../serialport-unix.cpp" line="691"/> <source>Serial port write timeout. %1 of %2 written in %3 ms</source> <translation>Tiempo de espera de escritura de puerto serie. %1 de %2 escrito en %3 ms</translation> </message> <message> <location filename="../serialport-unix.cpp" line="696"/> <source>Cannot flush serial port write buffer: %1</source> <translation>No se puede vaciar buffer de escritura del puerto serial: %1</translation> </message> <message> <location filename="../serialport-win32.cpp" line="98"/> <source>Cannot clear DTR line in serial port &apos;%1&apos;: %2</source> <translation>No se puede borrar la línea DTR en el puerto serie &apos;%1&apos;: %2</translation> </message> <message> <location filename="../serialport-win32.cpp" line="102"/> <source>Cannot clear RTS line in serial port &apos;%1&apos;: %2</source> <translation>No se puede borrar la línea RTS en el puerto serie &apos;%1&apos;: %2</translation> </message> <message> <location filename="../serialport-win32.cpp" line="137"/> <source>Emulation started through standard serial port backend on &apos;%1&apos; with %2 handshaking</source> <translation>Emulación de iniciado a través de puerto serial estándar backend en &apos;%1&apos; con handshaking de %2</translation> </message> <message> <location filename="../serialport-win32.cpp" line="307"/> <source>Cannot set serial port timeouts: %1</source> <translation>No se puede establecer tiempos de espera del puerto serial: %1</translation> </message> <message> <location filename="../serialport-win32.cpp" line="405"/> <source>Cannot set serial port event mask: %1</source> <translation>No se puede establecer la máscara de evento puerto serial: %1</translation> </message> <message> <location filename="../serialport-win32.cpp" line="430"/> <location filename="../serialport-win32.cpp" line="436"/> <source>Cannot wait for serial port event: %1</source> <translation>No puedo esperar para el evento del puerto serial: %1</translation> </message> <message> <location filename="../serialport-win32.cpp" line="642"/> <source>Cannot create event: %1</source> <translation>No se puede crear el evento: %1</translation> </message> <message> <location filename="../serialport-win32.cpp" line="667"/> <source>Serial port read timeout.</source> <translation>Tiempo de espera de lectura de puerto serie.</translation> </message> <message> <location filename="../serialport-win32.cpp" line="683"/> <source>Cannot clear serial port write buffer: %1</source> <translation>No se puede borrar el buffer de escritura del puerto serial: %1</translation> </message> <message> <location filename="../serialport-win32.cpp" line="701"/> <location filename="../serialport-win32.cpp" line="706"/> <source>Cannot write to serial port: %1</source> <translation>No se puede escribir en el puerto serial: %1</translation> </message> <message> <location filename="../serialport-win32.cpp" line="714"/> <source>Serial port write timeout.</source> <translation>Tiempo de espera de escritura de puerto serie.</translation> </message> </context> <context> <name>TestSerialPortBackend</name> <message> <location filename="../serialport-test.cpp" line="108"/> <source>Sleeping %1 seconds</source> <translation>Durmiendo %1 segundos</translation> </message> <message> <location filename="../serialport-test.cpp" line="114"/> <source>Sleeping %1 milliseconds</source> <translation>Durmiendo %1 milisegundos</translation> </message> <message> <location filename="../serialport-test.cpp" line="229"/> <source>Data frame contents: %1</source> <translation>Contenido del marco de datos: %1</translation> </message> <message> <location filename="../serialport-test.cpp" line="232"/> <source>Read error: got %1 bytes, expected %2 bytes</source> <translation>Error de lectura: obtuvo %1 bytes, se esperaba %2 bytes</translation> </message> </context> <context> <name>TextPrinterWindow</name> <message> <location filename="../printers/textprinterwindow.ui" line="14"/> <source>RespeQt - Printer text output</source> <translation>RespeQt - Salida de texto por impresora</translation> </message> <message> <location filename="../printers/textprinterwindow.ui" line="47"/> <location filename="../printers/textprinterwindow.ui" line="50"/> <source>Atari Output (Atascii)</source> <translation>Salida Atari (Atascii)</translation> </message> <message> <location filename="../printers/textprinterwindow.ui" line="69"/> <location filename="../printers/textprinterwindow.ui" line="72"/> <source>Atari Output (Ascii)</source> <translation>Salida Atari (Ascii)</translation> </message> <message> <location filename="../printers/textprinterwindow.ui" line="85"/> <location filename="../printers/textprinterwindow.ui" line="88"/> <source>Atari Output (Graphics)</source> <translation>Salida Atari (gráficos)</translation> </message> <message> <location filename="../printers/textprinterwindow.ui" line="137"/> <source>toolBar</source> <translation>Barra de Herramientas</translation> </message> <message> <location filename="../printers/textprinterwindow.ui" line="173"/> <source>Save to a file...</source> <translation>Guardar en un archivo...</translation> </message> <message> <location filename="../printers/textprinterwindow.ui" line="176"/> <source>Save contents to a file (Ctrl+S)</source> <translation>Guardar contenido en un archivo (Ctrl+S)</translation> </message> <message> <location filename="../printers/textprinterwindow.ui" line="179"/> <source>Save contents to a file</source> <translation>Guardar contenido en un archivo</translation> </message> <message> <location filename="../printers/textprinterwindow.ui" line="182"/> <location filename="../printers/textprinterwindow.ui" line="369"/> <source>Ctrl+S</source> <translation></translation> </message> <message> <location filename="../printers/textprinterwindow.ui" line="191"/> <source>Clear</source> <translation>Borrar</translation> </message> <message> <location filename="../printers/textprinterwindow.ui" line="194"/> <source>Clear contents (Ctrl+C)</source> <translation>Borrar el contenido (Ctrl+C)</translation> </message> <message> <location filename="../printers/textprinterwindow.ui" line="197"/> <source>Clear contents</source> <translation>Borrar el contenido</translation> </message> <message> <location filename="../printers/textprinterwindow.ui" line="200"/> <source>Ctrl+C</source> <translation></translation> </message> <message> <location filename="../printers/textprinterwindow.ui" line="215"/> <source>Word wrap</source> <translation>Ajuste de línea</translation> </message> <message> <location filename="../printers/textprinterwindow.ui" line="218"/> <source>Toggle word wrapping (Ctrl+W)</source> <translation>Activar ajuste de texto (Ctrl+W)</translation> </message> <message> <location filename="../printers/textprinterwindow.ui" line="221"/> <source>Toggle word wrapping</source> <translation>Activar ajuste de texto</translation> </message> <message> <location filename="../printers/textprinterwindow.ui" line="224"/> <source>Ctrl+W</source> <translation></translation> </message> <message> <location filename="../printers/textprinterwindow.ui" line="233"/> <source>Print</source> <translation>Imprimir</translation> </message> <message> <location filename="../printers/textprinterwindow.ui" line="236"/> <source>Send contents to printer (Ctrl+P)</source> <translation>Enviar contenido a la impresora (Ctrl+P)</translation> </message> <message> <location filename="../printers/textprinterwindow.ui" line="239"/> <source>Send contents to printer</source> <translation>Enviar contenido a la impresora</translation> </message> <message> <location filename="../printers/textprinterwindow.ui" line="242"/> <source>Ctrl+P</source> <translation></translation> </message> <message> <location filename="../printers/textprinterwindow.ui" line="252"/> <source>Atascii Font</source> <translation>Fuente Atascii</translation> </message> <message> <location filename="../printers/textprinterwindow.ui" line="255"/> <source>Toggle ATASCII fonts (Alt+F)</source> <translation>Alternar las fuentes ATASCII (Alt+F)</translation> </message> <message> <location filename="../printers/textprinterwindow.ui" line="258"/> <source>Toggle ATASCII fonts</source> <translation>Alternar las fuentes ATASCII</translation> </message> <message> <location filename="../printers/textprinterwindow.ui" line="261"/> <source>Alt+F</source> <translation></translation> </message> <message> <location filename="../printers/textprinterwindow.ui" line="277"/> <source>Font Size</source> <translation>Tamaño de la Fuente</translation> </message> <message> <location filename="../printers/textprinterwindow.ui" line="280"/> <source>Toggle Font Size (6, 9, 12 pt) (Alt+Shift+F)</source> <translation>Cambiar tamaño de la fuente (6, 9, 12 pt) (Alt+Shift+F)</translation> </message> <message> <location filename="../printers/textprinterwindow.ui" line="283"/> <source>Toggle Font Size (6, 9, 12 pt)</source> <translation>Cambiar tamaño de la fuente (6, 9, 12 pt)</translation> </message> <message> <location filename="../printers/textprinterwindow.ui" line="286"/> <source>Alt+Shift+F</source> <translation></translation> </message> <message> <location filename="../printers/textprinterwindow.ui" line="305"/> <source>Hide/Show Ascii</source> <translation>Mostrar/Ocultar Ascii</translation> </message> <message> <location filename="../printers/textprinterwindow.ui" line="308"/> <source>Hide/Show Ascii Printer Output (Alt+Shift+H)</source> <translation>Ocultar/mostrar la salida por impresora Ascii (Alt+Shift+H)</translation> </message> <message> <location filename="../printers/textprinterwindow.ui" line="311"/> <source>Hide/Show Ascii Printer Output</source> <translation>Ocultar/mostrar la salida por impresora Ascii</translation> </message> <message> <location filename="../printers/textprinterwindow.ui" line="314"/> <source>Alt+Shift+H</source> <translation></translation> </message> <message> <location filename="../printers/textprinterwindow.ui" line="336"/> <source>HideShow_Atascii</source> <translation>Mostrar/Ocultar Ascii</translation> </message> <message> <location filename="../printers/textprinterwindow.ui" line="339"/> <source> Hide/Show Atascii Printer Output (Alt+H)</source> <translation> Ocultar/Mostrar salida de impresora Atascii (Alt+H)</translation> </message> <message> <location filename="../printers/textprinterwindow.ui" line="342"/> <source>Hide/Show Atascii Printer Output</source> <translation>Ocultar/Mostrar la salida por impresora Ascii</translation> </message> <message> <location filename="../printers/textprinterwindow.ui" line="345"/> <source>Alt+H</source> <translation></translation> </message> <message> <location filename="../printers/textprinterwindow.ui" line="360"/> <source>Strip Line Numbers</source> <translation>Tira números de línea</translation> </message> <message> <location filename="../printers/textprinterwindow.ui" line="363"/> <source>Strip Line numbers from the text output (Ctrl-S)</source> <translation>Tira números de línea de la salida de texto (Ctrl-S)</translation> </message> <message> <location filename="../printers/textprinterwindow.ui" line="366"/> <source>Strip Line numbers from the text output</source> <translation>Eliminar números de línea de la salida de texto</translation> </message> </context> </TS><|fim▁end|>
<translation>Mango malo 2 %1</translation> </message>
<|file_name|>FetchWeatherTask.java<|end_file_name|><|fim▁begin|>/* * Copyright (C) 2014 The Android Open Source Project * * 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 com.example.android.sunshine.app; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.os.AsyncTask; import android.text.format.Time; import android.util.Log; import com.example.android.sunshine.app.data.WeatherContract; import com.example.android.sunshine.app.data.WeatherContract.WeatherEntry; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.Vector; public class FetchWeatherTask extends AsyncTask<String, Void, Void> { private final String LOG_TAG = FetchWeatherTask.class.getSimpleName(); private final Context mContext; public FetchWeatherTask (Context context) { mContext = context; } private boolean DEBUG = true; /** * Helper method to handle insertion of a new location in the weather database. * * @param locationSetting The location string used to request updates from the server. * @param cityName A human-readable city name, e.g "Mountain View" * @param lat the latitude of the city * @param lon the longitude of the city * @return the row ID of the added location. */ long addLocation (String locationSetting, String cityName, double lat, double lon) { long locationId; // First, check if the location with this city name exists in the db Cursor locationCursor = mContext.getContentResolver().query( WeatherContract.LocationEntry.CONTENT_URI, new String[] {WeatherContract.LocationEntry._ID}, WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " = ?", new String[] {locationSetting}, null); if (locationCursor.moveToFirst()) { int locationIdIndex = locationCursor.getColumnIndex(WeatherContract.LocationEntry._ID); locationId = locationCursor.getLong(locationIdIndex); } else { // Now that the content provider is set up, inserting rows of data is pretty simple. // First create a ContentValues object to hold the data you want to insert. ContentValues locationValues = new ContentValues(); // Then add the data, along with the corresponding name of the data type, // so the content provider knows what kind of value is being inserted. locationValues.put(WeatherContract.LocationEntry.COLUMN_CITY_NAME, cityName); locationValues.put(WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING, locationSetting);<|fim▁hole|> // Finally, insert location data into the database. Uri insertedUri = mContext.getContentResolver().insert( WeatherContract.LocationEntry.CONTENT_URI, locationValues ); // The resulting URI contains the ID for the row. Extract the locationId from the Uri. locationId = ContentUris.parseId(insertedUri); } locationCursor.close(); // Wait, that worked? Yes! return locationId; } /** * Take the String representing the complete forecast in JSON Format and * pull out the data we need to construct the Strings needed for the wireframes. * <p> * Fortunately parsing is easy: constructor takes the JSON string and converts it * into an Object hierarchy for us. */ private void getWeatherDataFromJson (String forecastJsonStr, String locationSetting) throws JSONException { // Now we have a String representing the complete forecast in JSON Format. // Fortunately parsing is easy: constructor takes the JSON string and converts it // into an Object hierarchy for us. // These are the names of the JSON objects that need to be extracted. // Location information final String OWM_CITY = "city"; final String OWM_CITY_NAME = "name"; final String OWM_COORD = "coord"; // Location coordinate final String OWM_LATITUDE = "lat"; final String OWM_LONGITUDE = "lon"; // Weather information. Each day's forecast info is an element of the "list" array. final String OWM_LIST = "list"; final String OWM_PRESSURE = "pressure"; final String OWM_HUMIDITY = "humidity"; final String OWM_WINDSPEED = "speed"; final String OWM_WIND_DIRECTION = "deg"; // All temperatures are children of the "temp" object. final String OWM_TEMPERATURE = "temp"; final String OWM_MAX = "max"; final String OWM_MIN = "min"; final String OWM_WEATHER = "weather"; final String OWM_DESCRIPTION = "main"; final String OWM_WEATHER_ID = "id"; try { JSONObject forecastJson = new JSONObject(forecastJsonStr); JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST); JSONObject cityJson = forecastJson.getJSONObject(OWM_CITY); String cityName = cityJson.getString(OWM_CITY_NAME); JSONObject cityCoord = cityJson.getJSONObject(OWM_COORD); double cityLatitude = cityCoord.getDouble(OWM_LATITUDE); double cityLongitude = cityCoord.getDouble(OWM_LONGITUDE); long locationId = addLocation(locationSetting, cityName, cityLatitude, cityLongitude); // Insert the new weather information into the database Vector<ContentValues> cVVector = new Vector<>(weatherArray.length()); // OWM returns daily forecasts based upon the local time of the city that is being // asked for, which means that we need to know the GMT offset to translate this data // properly. // Since this data is also sent in-order and the first day is always the // current day, we're going to take advantage of that to get a nice // normalized UTC date for all of our weather. Time dayTime = new Time(); dayTime.setToNow(); // we start at the day returned by local time. Otherwise this is a mess. int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff); // now we work exclusively in UTC dayTime = new Time(); for (int i = 0; i < weatherArray.length(); i++) { // These are the values that will be collected. long dateTime; double pressure; int humidity; double windSpeed; double windDirection; double high; double low; String description; int weatherId; // Get the JSON object representing the day JSONObject dayForecast = weatherArray.getJSONObject(i); // Cheating to convert this to UTC time, which is what we want anyhow dateTime = dayTime.setJulianDay(julianStartDay + i); pressure = dayForecast.getDouble(OWM_PRESSURE); humidity = dayForecast.getInt(OWM_HUMIDITY); windSpeed = dayForecast.getDouble(OWM_WINDSPEED); windDirection = dayForecast.getDouble(OWM_WIND_DIRECTION); // Description is in a child array called "weather", which is 1 element long. // That element also contains a weather code. JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0); description = weatherObject.getString(OWM_DESCRIPTION); weatherId = weatherObject.getInt(OWM_WEATHER_ID); // Temperatures are in a child object called "temp". Try not to name variables // "temp" when working with temperature. It confuses everybody. JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE); high = temperatureObject.getDouble(OWM_MAX); low = temperatureObject.getDouble(OWM_MIN); ContentValues weatherValues = new ContentValues(); weatherValues.put(WeatherEntry.COLUMN_LOC_KEY, locationId); weatherValues.put(WeatherEntry.COLUMN_DATE, dateTime); weatherValues.put(WeatherEntry.COLUMN_HUMIDITY, humidity); weatherValues.put(WeatherEntry.COLUMN_PRESSURE, pressure); weatherValues.put(WeatherEntry.COLUMN_WIND_SPEED, windSpeed); weatherValues.put(WeatherEntry.COLUMN_DEGREES, windDirection); weatherValues.put(WeatherEntry.COLUMN_MAX_TEMP, high); weatherValues.put(WeatherEntry.COLUMN_MIN_TEMP, low); weatherValues.put(WeatherEntry.COLUMN_SHORT_DESC, description); weatherValues.put(WeatherEntry.COLUMN_WEATHER_ID, weatherId); cVVector.add(weatherValues); } int inserted = 0; // add to database if (cVVector.size() > 0) { ContentValues[] cvArray = new ContentValues[cVVector.size()]; cVVector.toArray(cvArray); inserted = mContext.getContentResolver().bulkInsert(WeatherEntry.CONTENT_URI, cvArray); } Log.d(LOG_TAG, "FetchWeatherTask Complete. " + inserted + " Inserted"); } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); } } @Override protected Void doInBackground (String... params) { // If there's no zip code, there's nothing to look up. Verify size of params. if (params.length == 0) { return null; } String locationQuery = params[0]; // These two need to be declared outside the try/catch // so that they can be closed in the finally block. HttpURLConnection urlConnection = null; BufferedReader reader = null; // Will contain the raw JSON response as a string. String forecastJsonStr = null; String format = "json"; String units = "metric"; int numDays = 14; try { // Construct the URL for the OpenWeatherMap query // Possible parameters are avaiable at OWM's forecast API page, at // http://openweathermap.org/API#forecast final String FORECAST_BASE_URL = "http://api.openweathermap.org/data/2.5/forecast/daily?"; final String ZIP_CODE_PARAM = "zip"; final String FORMAT_PARAM = "mode"; final String UNITS_PARAM = "units"; final String DAYS_PARAM = "cnt"; final String APP_ID_PARAM = "appid"; Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon() .appendQueryParameter(APP_ID_PARAM, BuildConfig.OPEN_WEATHER_MAP_API_KEY) .appendQueryParameter(ZIP_CODE_PARAM, params[0]) .appendQueryParameter(FORMAT_PARAM, format) .appendQueryParameter(UNITS_PARAM, units) .appendQueryParameter(DAYS_PARAM, Integer.toString(numDays)) .build(); URL url = new URL(builtUri.toString()); // Create the request to OpenWeatherMap, and open the connection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); // Read the input stream into a String InputStream inputStream = urlConnection.getInputStream(); StringBuffer buffer = new StringBuffer(); if (inputStream == null) { // Nothing to do. return null; } reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { // Since it's JSON, adding a newline isn't necessary (it won't affect parsing) // But it does make debugging a *lot* easier if you print out the completed // buffer for debugging. buffer.append(line + "\n"); } if (buffer.length() == 0) { // Stream was empty. No point in parsing. return null; } forecastJsonStr = buffer.toString(); getWeatherDataFromJson(forecastJsonStr, locationQuery); } catch (IOException e) { Log.e(LOG_TAG, "Error ", e); // If the code didn't successfully get the weather data, there's no point in attemping // to parse it. return null; } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); } finally { if (urlConnection != null) { urlConnection.disconnect(); } if (reader != null) { try { reader.close(); } catch (final IOException e) { Log.e(LOG_TAG, "Error closing stream", e); } } } return null; } }<|fim▁end|>
locationValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LAT, lat); locationValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LONG, lon);
<|file_name|>FontWarnings.js<|end_file_name|><|fim▁begin|><|fim▁hole|> * Copyright (c) 2009-2018 The MathJax Consortium * * 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. * */ MathJax.Localization.addTranslation("br","FontWarnings",{ version: "2.7.3", isLoaded: true, strings: { webFont: "MathJax a implij ar fonto\u00F9 web evit diskwel ar jedado\u00F9 war ar bajenn-ma\u00F1. Pell eo ar re-se o pellgarga\u00F1 ha diskwelet e vefe buanoc'h ma stailhfec'h fonto\u00F9 jedoniezh war-eeun e teuliad fonto\u00F9 ho reizhiad.", noFonts: "N'hall ket MathJax lec'hia\u00F1 ur polis evit diskwel e jedado\u00F9, ha dihegerz eo ar fonto\u00F9 skeudenn. Ret eo implijout arouezenno\u00F9 Unicode neuze. Emicha\u00F1s e c'hallo ho merdeer diskwel anezho. Ne c'hallo ket arouezenno\u00F9 zo beza\u00F1 diskwelet mat, tamm ebet zoken.", webFonts: "GAnt an darn vrasa\u00F1 eus ar merdeerio\u00F9 arnevez e c'haller pellgarga\u00F1 fonto\u00F9 adalek ar web. Hizivaat ho merdeer (pe che\u00F1ch merdeer) a c'hallfe gwellaat kalite ar jedado\u00F9 war ar bajenn-ma\u00F1.", fonts: "Gallout a ra MathJax implijout pe ar fonto\u00F9 [STIX](%1) pe ar fonto\u00F9 [MathJax TeX](%2); Pellgargit ha stailhit unan eus fonto\u00F9-se evit gwellaat ho skiant-prenet gant MathJax.", STIXPage: "Krouet eo bet ar bajenn-ma\u00F1 evit implijout ar fonto\u00F9 [STIX ](%1). Pellgargit ha stailhit ar fonto\u00F9-se evit gwellaat ho skiant-penet gant MathJax.", TeXPage: "Krouet eo bet ar bajenn-ma\u00F1 evit implijout ar fonto\u00F9 [MathJax TeX](%1). Pellgargit ha stailhit ar fonto\u00F9-se evit gwellaat ho skiant-prenet gant MathJax.", imageFonts: "Ober a ra MathJax gant skeudenno\u00F9 font kentoc'h eget gant fonto\u00F9 web pe fonto\u00F9 lec'hel. Gant se e teu an trao\u00F9 gorrekoc'h war-wel ha marteze ne vo ket ar jedado\u00F9 evit beza\u00F1 moullet diouzh pizhder kloka\u00F1 ho moullerez." } }); MathJax.Ajax.loadComplete("[MathJax]/localization/br/FontWarnings.js");<|fim▁end|>
/************************************************************* * * MathJax/localization/br/FontWarnings.js *
<|file_name|>upsertMany.js<|end_file_name|><|fim▁begin|>'use strict' const MongoClient = require('mongodb').MongoClient const muri = require('muri') const chai = require('chai') const expect = chai.expect const assert = chai.assert const chaiSubset = require('chai-subset') chai.use(chaiSubset) chai.should() const stringConnection = 'mongodb://localhost:27017/lambda-mongo-crud-test' const tableName = 'posts' const Crud = require('./../lib/crud') const PERMISSION = { list: 'posts:list', get: 'posts:get', save: 'posts:save', delete: 'posts:delete' } const ROLES = {<|fim▁hole|> admin: { can: [PERMISSION.save, PERMISSION.delete, PERMISSION.list, PERMISSION.get] } } describe('MANY', () => { before(async () => { const { db: dbName } = muri(stringConnection) const client = await MongoClient.connect(stringConnection, { useUnifiedTopology: true }) const collection = client.db(dbName).collection(tableName) await collection.insertMany([{ title: "Title 1", code: 1 }, { title: "Title 2", code: 2 }, { title: "Title 3", code: 3 }]) await client.close() }) after(async () => { const { db: dbName } = muri(stringConnection) const client = await MongoClient.connect(stringConnection, { useUnifiedTopology: true }) const collection = client.db(dbName).collection(tableName) await collection.deleteMany() await client.close() }) const crud = new Crud(stringConnection, tableName, { role: 'admin', _id: 123 }, ROLES) describe('list()', () => { it('should return an array', (done) => { crud.list({}, PERMISSION.list, {}, (err, docs) => { expect(docs.length).to.be.equal(3) done() }) }) it('should return an array', (done) => { const data = [ { title: "Title 2", code: 2 }, { title: "Title 3bis", code: 3 }, { title: "Title 4", code: 4 }, { title: "Title 5", code: 5 } ] crud.upsertMany(data, "code", PERMISSION.save, {}, (err, result) => { expect(result.nMatched).to.be.equal(2) expect(result.nUpserted).to.be.equal(2) crud.list({}, PERMISSION.list, {}, (err, docs) => { expect(docs.length).to.be.equal(5) done() }) }) }) }) })<|fim▁end|>
<|file_name|>btqlistdelegate.cpp<|end_file_name|><|fim▁begin|>#include <QtGui> #include "btglobal.h" #include "btqlistdelegate.h" //#include <QMetaType> btQListDeletgate::btQListDeletgate(QObject *parent) : QItemDelegate(parent) { } QWidget *btQListDeletgate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const { //qRegisterMetaType<btChildWeights>("btChildWeights"); //qRegisterMetaType<btParallelConditions>("btParallelConditions"); QComboBox *comboBox = new QComboBox(parent); comboBox->addItem("int", QVariant("int")); comboBox->addItem("QString", QVariant("QString")); comboBox->addItem("double", QVariant("double")); comboBox->addItem("QVariantList", QVariant("QVariantList")); //comboBox->addItem("btChildWeights", QVariant("btChildWeights")); comboBox->setCurrentIndex(comboBox->findData(index.data())); return comboBox; } void btQListDeletgate::setEditorData(QWidget *editor, const QModelIndex &index) const { QString value = index.model()->data(index, Qt::EditRole).toString(); QComboBox *comboBox = static_cast<QComboBox*>(editor); comboBox->setCurrentIndex(comboBox->findText(value));//comboBox->findData(value)); } void btQListDeletgate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const { QComboBox *comboBox = static_cast<QComboBox*>(editor); QString value = comboBox->currentText(); model->setData(index, value, Qt::EditRole); } void btQListDeletgate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &/* index */) const { editor->setGeometry(option.rect);<|fim▁hole|><|fim▁end|>
} #include "btqlistdelegate.moc"
<|file_name|>setup.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup from djangocms_carousel import __version__ INSTALL_REQUIRES = [ ] CLASSIFIERS = [ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Communications', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content',<|fim▁hole|> 'Topic :: Internet :: WWW/HTTP :: Dynamic Content :: Message Boards', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', ] setup( name='djangocms-carousel', version=__version__, description='Slider Plugin for django CMS', author='Andrew Mirsky', author_email='[email protected]', url='https://git.mirsky.net/mirskyconsulting/djangocms-carousel', packages=['djangocms_carousel', 'djangocms_carousel.migrations'], install_requires=INSTALL_REQUIRES, license='LICENSE.txt', platforms=['OS Independent'], classifiers=CLASSIFIERS, long_description=open('README.md').read(), include_package_data=True, zip_safe=False )<|fim▁end|>
<|file_name|>task_manager.js<|end_file_name|><|fim▁begin|>mf.include("chat_commands.js"); mf.include("assert.js"); mf.include("arrays.js"); /** * Example: * var id; * var count = 0; * task_manager.doLater(new task_manager.Task(function start() { * id = mf.setInterval(function() { * mf.debug("hello"); * if (++count === 10) { * task_manager.done(); * } * }, 1000); * }, function stop() { * mf.clearInterval(id); * }, "saying hello 10 times"); */ var task_manager = {}; (function() { /** * Constructor. * @param start_func() called when the job starts or resumes * @param stop_func() called when the job should pause or abort * @param string either a toString function or a string used to display the task in a list */ task_manager.Task = function(start_func, stop_func, string, resume_func) { assert.isFunction(start_func); this.start = start_func; assert.isFunction(stop_func); this.stop = stop_func; if (typeof string === "string") { var old_string = string; string = function() { return old_string; }; } assert.isFunction(string); this.toString = string; if (resume_func !== undefined) { assert.isFunction(resume_func); this.resume = resume_func; } this.started = false; }; var tasks = []; function runNextCommand() { if (tasks.length === 0) { return; } if (tasks[0].started && tasks[0].resume !== undefined) { tasks[0].resume(); } else { tasks[0].started = true; tasks[0].begin_time = new Date().getTime(); tasks[0].start(); } }; task_manager.doLater = function(task) { tasks.push(task); task.started = false; if (tasks.length === 1) { runNextCommand(); } }; task_manager.doNow = function(task) { if (tasks.length !== 0) { tasks[0].stop(); } tasks.remove(task); tasks.unshift(task); runNextCommand(); }; task_manager.done = function() { assert.isTrue(tasks.length !== 0); var length = tasks.length; tasks[0].started = false; tasks.shift(); assert.isTrue(length !== tasks.length); runNextCommand(); }; task_manager.postpone = function(min_timeout) { var task = tasks[0]; tasks.remove(task); if (min_timeout > 0) { task.postponed = mf.setTimeout(function resume() { task.postponed = undefined; tasks.push(task); if (tasks.length === 1) { runNextCommand(); } }, min_timeout); } else { tasks.push(task); } runNextCommand(); }; task_manager.remove = function(task) { if (task === tasks[0]) { task.stop(); tasks.remove(task); runNextCommand(); } else { tasks.remove(task); if (task.postponed !== undefined) { mf.clearTimeout(task.postponed); task.postponed = undefined; task.stop(); } } } chat_commands.registerCommand("stop", function() { if (tasks.length === 0) { return; } tasks[0].stop(); tasks = []; }); chat_commands.registerCommand("tasks",function(speaker,args,responder_fun) { responder_fun("Tasks: " + tasks.join(", ")); }); chat_commands.registerCommand("reboot", function(speaker, args, responder_fun) { if (tasks.length === 0) { responder_fun("no tasks"); return;<|fim▁hole|> }), })();<|fim▁end|>
} tasks[0].stop(); tasks[0].start();
<|file_name|>custom.time.pipe.ts<|end_file_name|><|fim▁begin|>import { Pipe,PipeTransform } from '@angular/core' @Pipe({ name: 'customTime' }) export class CustomTimePipe implements PipeTransform { minuteTime: number = 60 * 1000 hourTime: number = 60 * this.minuteTime dayTime: number = 24 * this.hourTime monthTime: number = this.dayTime * 30 yearTime: number = this.monthTime * 12 nowTime:number = new Date().getTime() transform(item: string): string { let publishTime:number = new Date(item).getTime(); let historyTime:number = this.nowTime - publishTime let descTime:string<|fim▁hole|> if(historyTime >= this.yearTime){ //按年算 descTime = Math.floor(historyTime / this.yearTime) + '年前' }else if(historyTime< this.yearTime && historyTime >= this.monthTime){ //按月算 descTime = Math.floor(historyTime / this.monthTime) + '月前' }else if(historyTime< this.monthTime && historyTime>= this.dayTime){ //按天算 descTime = Math.floor(historyTime / this.dayTime) + '天前' }else if(historyTime< this.dayTime && historyTime>= this.hourTime){ //按小时算 descTime = Math.floor(historyTime / this.hourTime) + '小时前' }else if(historyTime< this.hourTime && historyTime>= this.minuteTime){ //按分钟算 descTime = Math.floor(historyTime / this.minuteTime) + '分钟前' }else{ descTime = '刚刚' } return descTime } }<|fim▁end|>
<|file_name|>color.mako.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% data.new_style_struct("Color", inherited=True) %> <% from data import to_rust_ident %> ${helpers.predefined_type( "color", "ColorPropertyValue", "::cssparser::RGBA::new(0, 0, 0, 255)", animation_value_type="AnimatedRGBA", flags="APPLIES_TO_FIRST_LETTER APPLIES_TO_FIRST_LINE APPLIES_TO_PLACEHOLDER", ignored_when_colors_disabled="True", spec="https://drafts.csswg.org/css-color/#color" )} // FIXME(#15973): Add servo support for system colors // // FIXME(emilio): Move outside of mako. % if product == "gecko": pub mod system_colors { <% # These are actually parsed. See nsCSSProps::kColorKTable system_colors = """activeborder activecaption appworkspace background buttonface<|fim▁hole|> highlighttext inactiveborder inactivecaption inactivecaptiontext infobackground infotext menu menutext scrollbar threeddarkshadow threedface threedhighlight threedlightshadow threedshadow window windowframe windowtext -moz-buttondefault -moz-buttonhoverface -moz-buttonhovertext -moz-cellhighlight -moz-cellhighlighttext -moz-eventreerow -moz-field -moz-fieldtext -moz-dialog -moz-dialogtext -moz-dragtargetzone -moz-gtk-info-bar-text -moz-html-cellhighlight -moz-html-cellhighlighttext -moz-mac-buttonactivetext -moz-mac-chrome-active -moz-mac-chrome-inactive -moz-mac-defaultbuttontext -moz-mac-focusring -moz-mac-menuselect -moz-mac-menushadow -moz-mac-menutextdisable -moz-mac-menutextselect -moz-mac-disabledtoolbartext -moz-mac-secondaryhighlight -moz-mac-vibrancy-light -moz-mac-vibrancy-dark -moz-mac-vibrant-titlebar-light -moz-mac-vibrant-titlebar-dark -moz-mac-menupopup -moz-mac-menuitem -moz-mac-active-menuitem -moz-mac-source-list -moz-mac-source-list-selection -moz-mac-active-source-list-selection -moz-mac-tooltip -moz-menuhover -moz-menuhovertext -moz-menubartext -moz-menubarhovertext -moz-oddtreerow -moz-win-mediatext -moz-win-communicationstext -moz-win-accentcolor -moz-win-accentcolortext -moz-nativehyperlinktext -moz-comboboxtext -moz-combobox""".split() # These are not parsed but must be serialized # They are only ever set directly by Gecko extra_colors = """WindowBackground WindowForeground WidgetBackground WidgetForeground WidgetSelectBackground WidgetSelectForeground Widget3DHighlight Widget3DShadow TextBackground TextForeground TextSelectBackground TextSelectForeground TextSelectForegroundCustom TextSelectBackgroundDisabled TextSelectBackgroundAttention TextHighlightBackground TextHighlightForeground IMERawInputBackground IMERawInputForeground IMERawInputUnderline IMESelectedRawTextBackground IMESelectedRawTextForeground IMESelectedRawTextUnderline IMEConvertedTextBackground IMEConvertedTextForeground IMEConvertedTextUnderline IMESelectedConvertedTextBackground IMESelectedConvertedTextForeground IMESelectedConvertedTextUnderline SpellCheckerUnderline""".split() %> use cssparser::Parser; use gecko_bindings::bindings::Gecko_GetLookAndFeelSystemColor; use gecko_bindings::structs::root::mozilla::LookAndFeel_ColorID; use std::fmt::{self, Write}; use style_traits::{CssWriter, ToCss}; use values::computed::{Context, ToComputedValue}; pub type SystemColor = LookAndFeel_ColorID; // It's hard to implement MallocSizeOf for LookAndFeel_ColorID because it // is a bindgen type. So we implement it on the typedef instead. malloc_size_of_is_0!(SystemColor); impl ToCss for SystemColor { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write, { let s = match *self { % for color in system_colors + extra_colors: LookAndFeel_ColorID::eColorID_${to_rust_ident(color)} => "${color}", % endfor LookAndFeel_ColorID::eColorID_LAST_COLOR => unreachable!(), }; dest.write_str(s) } } impl ToComputedValue for SystemColor { type ComputedValue = u32; // nscolor #[inline] fn to_computed_value(&self, cx: &Context) -> Self::ComputedValue { unsafe { Gecko_GetLookAndFeelSystemColor(*self as i32, cx.device().pres_context()) } } #[inline] fn from_computed_value(_: &Self::ComputedValue) -> Self { unreachable!() } } impl SystemColor { pub fn parse<'i, 't>(input: &mut Parser<'i, 't>,) -> Result<Self, ()> { ascii_case_insensitive_phf_map! { color_name -> SystemColor = { % for color in system_colors: "${color}" => LookAndFeel_ColorID::eColorID_${to_rust_ident(color)}, % endfor } } let ident = input.expect_ident().map_err(|_| ())?; color_name(ident).cloned().ok_or(()) } } } % endif<|fim▁end|>
buttonhighlight buttonshadow buttontext captiontext graytext highlight
<|file_name|>flags.rs<|end_file_name|><|fim▁begin|>// This file is part of Grust, GObject introspection bindings for Rust // // Copyright (C) 2015 Mikhail Zabaluev <[email protected]> // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA use gtype::GType; use types::guint; use std::error::Error as ErrorTrait; use std::fmt; pub trait IntrospectedFlags : Sized { fn from_uint(v: guint) -> Result<Self, UnknownFlags>; fn to_uint(&self) -> guint; } pub trait FlagsType : IntrospectedFlags { fn get_type() -> GType; } #[derive(Copy, Clone)] pub struct UnknownFlags { actual: guint, known_mask: guint } impl UnknownFlags { pub fn new(flags: guint, known_mask: guint) -> UnknownFlags { UnknownFlags { actual: flags, known_mask: known_mask } } pub fn actual(&self) -> guint { self.actual } pub fn unknown(&self) -> guint { self.actual & !self.known_mask } pub fn known(&self) -> guint { self.actual & self.known_mask } }<|fim▁hole|>pub mod prelude { pub use super::{IntrospectedFlags, FlagsType, UnknownFlags}; pub use gtype::GType; pub use types::guint; } impl ErrorTrait for UnknownFlags { fn description(&self) -> &str { "unknown bit flags encountered" } } impl fmt::Display for UnknownFlags { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "unsupported bit flag value 0b{:b} (unknown flags: 0b{:b})", self.actual(), self.unknown()) } } impl fmt::Debug for UnknownFlags { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "UnknownFlags {{ actual: 0b{:b}, known_mask: 0b{:b} }}", self.actual, self.known_mask) } } pub fn from_uint<F>(v: guint) -> Result<F, UnknownFlags> where F: IntrospectedFlags { IntrospectedFlags::from_uint(v) } pub fn type_of<F>() -> GType where F: FlagsType { <F as FlagsType>::get_type() }<|fim▁end|>
<|file_name|>settings.py<|end_file_name|><|fim▁begin|>""" Django settings for jstest project. Generated by 'django-admin startproject' using Django 1.10.4. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '(n=5&yvpo-9!=db58cbix!za-$30^osiq1i42o42xh8)9j81i1' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'samplepage', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'jstest.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth',<|fim▁hole|> 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'jstest.wsgi.application' # Database # https://docs.djangoproject.com/en/1.10/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.10/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Seoul' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.10/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'samplepage/statics'), )<|fim▁end|>
<|file_name|>test_website.py<|end_file_name|><|fim▁begin|>from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import os import StringIO from pytest import raises from aspen.website import Website from aspen.http.response import Response from aspen.exceptions import BadLocation simple_error_spt = """ [---] [---] text/plain via stdlib_format {response.body} """ # Tests # ===== def test_basic(): website = Website() expected = os.getcwd() actual = website.www_root assert actual == expected def test_normal_response_is_returned(harness): harness.fs.www.mk(('index.html', "Greetings, program!")) expected = '\r\n'.join("""\ HTTP/1.1 Content-Type: text/html Greetings, program! """.splitlines()) actual = harness.client.GET()._to_http('1.1') assert actual == expected def test_fatal_error_response_is_returned(harness): harness.fs.www.mk(('index.html.spt', "[---]\nraise heck\n[---]\n")) expected = 500 actual = harness.client.GET(raise_immediately=False).code assert actual == expected def test_redirect_has_only_location(harness): harness.fs.www.mk(('index.html.spt', """ from aspen import Response [---] website.redirect('http://elsewhere', code=304) [---]""")) actual = harness.client.GET(raise_immediately=False) assert actual.code == 304 headers = actual.headers assert headers.keys() == ['Location'] def test_nice_error_response_is_returned(harness): harness.short_circuit = False harness.fs.www.mk(('index.html.spt', """ from aspen import Response [---] raise Response(500) [---]""")) assert harness.client.GET(raise_immediately=False).code == 500 def test_nice_error_response_is_returned_for_404(harness): harness.fs.www.mk(('index.html.spt', """ from aspen import Response [---] raise Response(404) [---]""")) assert harness.client.GET(raise_immediately=False).code == 404 def test_response_body_doesnt_expose_traceback_by_default(harness): harness.fs.project.mk(('error.spt', simple_error_spt)) harness.fs.www.mk(('index.html.spt', """ [---] raise Exception("Can I haz traceback ?") [---]""")) response = harness.client.GET(raise_immediately=False) assert response.code == 500 assert "Can I haz traceback ?" not in response.body def test_response_body_exposes_traceback_for_show_tracebacks(harness): harness.client.website.show_tracebacks = True harness.fs.project.mk(('error.spt', simple_error_spt)) harness.fs.www.mk(('index.html.spt', """ [---] raise Exception("Can I haz traceback ?") [---]""")) response = harness.client.GET(raise_immediately=False) assert response.code == 500 assert "Can I haz traceback ?" in response.body def test_default_error_simplate_doesnt_expose_raised_body_by_default(harness): harness.fs.www.mk(('index.html.spt', """ from aspen import Response [---] raise Response(404, "Um, yeah.") [---]""")) response = harness.client.GET(raise_immediately=False) assert response.code == 404 assert "Um, yeah." not in response.body def test_default_error_simplate_exposes_raised_body_for_show_tracebacks(harness): harness.client.website.show_tracebacks = True harness.fs.www.mk(('index.html.spt', """ from aspen import Response [---] raise Response(404, "Um, yeah.") [---]""")) response = harness.client.GET(raise_immediately=False) assert response.code == 404 assert "Um, yeah." in response.body def test_nice_error_response_can_come_from_user_error_spt(harness): harness.fs.project.mk(('error.spt', '[---]\n[---] text/plain\nTold ya.')) harness.fs.www.mk(('index.html.spt', """ from aspen import Response [---] raise Response(420) [---]""")) response = harness.client.GET(raise_immediately=False) assert response.code == 420 assert response.body == 'Told ya.' def test_nice_error_response_can_come_from_user_420_spt(harness): harness.fs.project.mk(('420.spt', """ [---] msg = "Enhance your calm." if response.code == 420 else "Ok." [---] text/plain %(msg)s""")) harness.fs.www.mk(('index.html.spt', """ from aspen import Response [---] raise Response(420) [---]""")) response = harness.client.GET(raise_immediately=False) assert response.code == 420 assert response.body == 'Enhance your calm.' def test_delegate_error_to_simplate_respects_original_accept_header(harness): harness.fs.project.mk(('error.spt', """[---] [---] text/fake Lorem ipsum [---] text/html <p>Error</p> [---] text/plain Error """)) harness.fs.www.mk(('foo.spt',""" from aspen import Response [---] raise Response(404) [---] text/plain """)) response = harness.client.GET('/foo', raise_immediately=False, HTTP_ACCEPT=b'text/fake') assert response.code == 404 assert 'text/fake' in response.headers['Content-Type'] def test_default_error_spt_handles_text_html(harness): harness.fs.www.mk(('foo.html.spt',""" from aspen import Response [---] raise Response(404) [---] """)) response = harness.client.GET('/foo.html', raise_immediately=False) assert response.code == 404 assert 'text/html' in response.headers['Content-Type'] def test_default_error_spt_handles_application_json(harness): harness.fs.www.mk(('foo.json.spt',""" from aspen import Response [---] raise Response(404) [---] """)) response = harness.client.GET('/foo.json', raise_immediately=False) assert response.code == 404<|fim▁hole|> assert response.headers['Content-Type'] == 'application/json' assert response.body == '''\ { "error_code": 404 , "error_message_short": "Not Found" , "error_message_long": "" } ''' def test_default_error_spt_application_json_includes_msg_for_show_tracebacks(harness): harness.client.website.show_tracebacks = True harness.fs.www.mk(('foo.json.spt',""" from aspen import Response [---] raise Response(404, "Right, sooo...") [---] """)) response = harness.client.GET('/foo.json', raise_immediately=False) assert response.code == 404 assert response.headers['Content-Type'] == 'application/json' assert response.body == '''\ { "error_code": 404 , "error_message_short": "Not Found" , "error_message_long": "Right, sooo..." } ''' def test_default_error_spt_falls_through_to_text_plain(harness): harness.fs.www.mk(('foo.xml.spt',""" from aspen import Response [---] raise Response(404) [---] """)) response = harness.client.GET('/foo.xml', raise_immediately=False) assert response.code == 404 assert response.headers['Content-Type'] == 'text/plain; charset=UTF-8' assert response.body == "Not found, program!\n\n" def test_default_error_spt_fall_through_includes_msg_for_show_tracebacks(harness): harness.client.website.show_tracebacks = True harness.fs.www.mk(('foo.xml.spt',""" from aspen import Response [---] raise Response(404, "Try again!") [---] """)) response = harness.client.GET('/foo.xml', raise_immediately=False) assert response.code == 404 assert response.headers['Content-Type'] == 'text/plain; charset=UTF-8' assert response.body == "Not found, program!\nTry again!\n" def test_custom_error_spt_without_text_plain_results_in_406(harness): harness.fs.project.mk(('error.spt', """ [---] [---] text/html <h1>Oh no!</h1> """)) harness.fs.www.mk(('foo.xml.spt',""" from aspen import Response [---] raise Response(404) [---] """)) response = harness.client.GET('/foo.xml', raise_immediately=False) assert response.code == 406 def test_custom_error_spt_with_text_plain_works(harness): harness.fs.project.mk(('error.spt', """ [---] [---] text/plain Oh no! """)) harness.fs.www.mk(('foo.xml.spt',""" from aspen import Response [---] raise Response(404) [---] """)) response = harness.client.GET('/foo.xml', raise_immediately=False) assert response.code == 404 assert response.headers['Content-Type'] == 'text/plain; charset=UTF-8' assert response.body == "Oh no!\n" def test_autoindex_response_is_404_by_default(harness): harness.fs.www.mk(('README', "Greetings, program!")) assert harness.client.GET(raise_immediately=False).code == 404 def test_autoindex_response_is_returned(harness): harness.fs.www.mk(('README', "Greetings, program!")) harness.client.website.list_directories = True body = harness.client.GET(raise_immediately=False).body assert 'README' in body def test_resources_can_import_from_project_root(harness): harness.fs.project.mk(('foo.py', 'bar = "baz"')) harness.fs.www.mk(('index.html.spt', "from foo import bar\n[---]\n[---]\nGreetings, %(bar)s!")) assert harness.client.GET(raise_immediately=False).body == "Greetings, baz!" def test_non_500_response_exceptions_dont_get_folded_to_500(harness): harness.fs.www.mk(('index.html.spt', ''' from aspen import Response [---] raise Response(400) [---] ''')) response = harness.client.GET(raise_immediately=False) assert response.code == 400 def test_errors_show_tracebacks(harness): harness.fs.www.mk(('index.html.spt', ''' from aspen import Response [---] website.show_tracebacks = 1 raise Response(400,1,2,3,4,5,6,7,8,9) [---] ''')) response = harness.client.GET(raise_immediately=False) assert response.code == 500 assert 'Response(400,1,2,3,4,5,6,7,8,9)' in response.body class TestMiddleware(object): """Simple WSGI middleware for testing.""" def __init__(self, app): self.app = app def __call__(self, environ, start_response): if environ['PATH_INFO'] == '/middleware': start_response('200 OK', [('Content-Type', 'text/plain')]) return ['TestMiddleware'] return self.app(environ, start_response) def build_environ(path): """Build WSGI environ for testing.""" return { 'REQUEST_METHOD': b'GET', 'PATH_INFO': path, 'QUERY_STRING': b'', 'SERVER_SOFTWARE': b'build_environ/1.0', 'SERVER_PROTOCOL': b'HTTP/1.1', 'wsgi.input': StringIO.StringIO() } def test_call_wraps_wsgi_middleware(client): client.website.algorithm.default_short_circuit = False client.website.wsgi_app = TestMiddleware(client.website.wsgi_app) respond = [False, False] def start_response_should_404(status, headers): assert status.lower().strip() == '404 not found' respond[0] = True client.website(build_environ('/'), start_response_should_404) assert respond[0] def start_response_should_200(status, headers): assert status.lower().strip() == '200 ok' respond[1] = True client.website(build_environ('/middleware'), start_response_should_200) assert respond[1] # redirect def test_redirect_redirects(website): assert raises(Response, website.redirect, '/').value.code == 302 def test_redirect_code_is_settable(website): assert raises(Response, website.redirect, '/', code=8675309).value.code == 8675309 def test_redirect_permanent_is_301(website): assert raises(Response, website.redirect, '/', permanent=True).value.code == 301 def test_redirect_without_website_base_url_is_fine(website): assert raises(Response, website.redirect, '/').value.headers['Location'] == '/' def test_redirect_honors_website_base_url(website): website.base_url = 'foo' assert raises(Response, website.redirect, '/').value.headers['Location'] == 'foo/' def test_redirect_can_override_base_url_per_call(website): website.base_url = 'foo' assert raises(Response, website.redirect, '/', base_url='b').value.headers['Location'] == 'b/' def test_redirect_declines_to_construct_bad_urls(website): raised = raises(BadLocation, website.redirect, '../foo', base_url='http://www.example.com') assert raised.value.body == 'Bad redirect location: http://www.example.com../foo' def test_redirect_declines_to_construct_more_bad_urls(website): raised = raises(BadLocation, website.redirect, 'http://www.example.org/foo', base_url='http://www.example.com') assert raised.value.body == 'Bad redirect location: '\ 'http://www.example.comhttp://www.example.org/foo' def test_redirect_will_construct_a_good_absolute_url(website): response = raises(Response, website.redirect, '/foo', base_url='http://www.example.com').value assert response.headers['Location'] == 'http://www.example.com/foo' def test_redirect_will_allow_a_relative_path(website): response = raises(Response, website.redirect, '../foo', base_url='').value assert response.headers['Location'] == '../foo' def test_redirect_will_allow_an_absolute_url(website): response = raises(Response, website.redirect, 'http://www.example.org/foo', base_url='').value assert response.headers['Location'] == 'http://www.example.org/foo' def test_redirect_can_use_given_response(website): response = Response(65, 'Greetings, program!', {'Location': 'A Town'}) response = raises(Response, website.redirect, '/flah', response=response).value assert response.code == 302 # gets clobbered assert response.headers['Location'] == '/flah' # gets clobbered assert response.body == 'Greetings, program!' # not clobbered # canonicalize_base_url def test_canonicalize_base_url_canonicalizes_base_url(harness): harness.fs.www.mk(('index.html', 'Greetings, program!')) harness.client.hydrate_website(base_url='http://example.com') response = harness.client.GxT() assert response.code == 302 assert response.headers['Location'] == 'http://example.com/' def test_canonicalize_base_url_includes_path_and_qs_for_GET(harness): harness.fs.www.mk(('index.html', 'Greetings, program!')) harness.client.hydrate_website(base_url='http://example.com') response = harness.client.GxT('/foo/bar?baz=buz') assert response.code == 302 assert response.headers['Location'] == 'http://example.com/foo/bar?baz=buz' def test_canonicalize_base_url_redirects_to_homepage_for_POST(harness): harness.fs.www.mk(('index.html', 'Greetings, program!')) harness.client.hydrate_website(base_url='http://example.com') response = harness.client.PxST('/foo/bar?baz=buz') assert response.code == 302 assert response.headers['Location'] == 'http://example.com/' def test_canonicalize_base_url_allows_good_base_url(harness): harness.fs.www.mk(('index.html', 'Greetings, program!')) harness.client.hydrate_website(base_url='http://localhost') response = harness.client.GET() assert response.code == 200 assert response.body == 'Greetings, program!' def test_canonicalize_base_url_is_noop_without_base_url(harness): harness.fs.www.mk(('index.html', 'Greetings, program!')) harness.client.hydrate_website() response = harness.client.GET() assert response.code == 200 assert response.body == 'Greetings, program!'<|fim▁end|>
<|file_name|>unmarshal.go<|end_file_name|><|fim▁begin|>package rest import ( "encoding/base64" "fmt" "io/ioutil" "net/http" "reflect" "strconv" "strings" "time" "github.com/revinate/etcd2s3/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws"<|fim▁hole|> // Unmarshal unmarshals the REST component of a response in a REST service. func Unmarshal(r *request.Request) { if r.DataFilled() { v := reflect.Indirect(reflect.ValueOf(r.Data)) unmarshalBody(r, v) } } // UnmarshalMeta unmarshals the REST metadata of a response in a REST service func UnmarshalMeta(r *request.Request) { r.RequestID = r.HTTPResponse.Header.Get("X-Amzn-Requestid") if r.DataFilled() { v := reflect.Indirect(reflect.ValueOf(r.Data)) unmarshalLocationElements(r, v) } } func unmarshalBody(r *request.Request, v reflect.Value) { if field, ok := v.Type().FieldByName("_"); ok { if payloadName := field.Tag.Get("payload"); payloadName != "" { pfield, _ := v.Type().FieldByName(payloadName) if ptag := pfield.Tag.Get("type"); ptag != "" && ptag != "structure" { payload := v.FieldByName(payloadName) if payload.IsValid() { switch payload.Interface().(type) { case []byte: b, err := ioutil.ReadAll(r.HTTPResponse.Body) if err != nil { r.Error = awserr.New("SerializationError", "failed to decode REST response", err) } else { payload.Set(reflect.ValueOf(b)) } case *string: b, err := ioutil.ReadAll(r.HTTPResponse.Body) if err != nil { r.Error = awserr.New("SerializationError", "failed to decode REST response", err) } else { str := string(b) payload.Set(reflect.ValueOf(&str)) } default: switch payload.Type().String() { case "io.ReadSeeker": payload.Set(reflect.ValueOf(aws.ReadSeekCloser(r.HTTPResponse.Body))) case "aws.ReadSeekCloser", "io.ReadCloser": payload.Set(reflect.ValueOf(r.HTTPResponse.Body)) default: r.Error = awserr.New("SerializationError", "failed to decode REST response", fmt.Errorf("unknown payload type %s", payload.Type())) } } } } } } } func unmarshalLocationElements(r *request.Request, v reflect.Value) { for i := 0; i < v.NumField(); i++ { m, field := v.Field(i), v.Type().Field(i) if n := field.Name; n[0:1] == strings.ToLower(n[0:1]) { continue } if m.IsValid() { name := field.Tag.Get("locationName") if name == "" { name = field.Name } switch field.Tag.Get("location") { case "statusCode": unmarshalStatusCode(m, r.HTTPResponse.StatusCode) case "header": err := unmarshalHeader(m, r.HTTPResponse.Header.Get(name)) if err != nil { r.Error = awserr.New("SerializationError", "failed to decode REST response", err) break } case "headers": prefix := field.Tag.Get("locationName") err := unmarshalHeaderMap(m, r.HTTPResponse.Header, prefix) if err != nil { r.Error = awserr.New("SerializationError", "failed to decode REST response", err) break } } } if r.Error != nil { return } } } func unmarshalStatusCode(v reflect.Value, statusCode int) { if !v.IsValid() { return } switch v.Interface().(type) { case *int64: s := int64(statusCode) v.Set(reflect.ValueOf(&s)) } } func unmarshalHeaderMap(r reflect.Value, headers http.Header, prefix string) error { switch r.Interface().(type) { case map[string]*string: // we only support string map value types out := map[string]*string{} for k, v := range headers { k = http.CanonicalHeaderKey(k) if strings.HasPrefix(strings.ToLower(k), strings.ToLower(prefix)) { out[k[len(prefix):]] = &v[0] } } r.Set(reflect.ValueOf(out)) } return nil } func unmarshalHeader(v reflect.Value, header string) error { if !v.IsValid() || (header == "" && v.Elem().Kind() != reflect.String) { return nil } switch v.Interface().(type) { case *string: v.Set(reflect.ValueOf(&header)) case []byte: b, err := base64.StdEncoding.DecodeString(header) if err != nil { return err } v.Set(reflect.ValueOf(&b)) case *bool: b, err := strconv.ParseBool(header) if err != nil { return err } v.Set(reflect.ValueOf(&b)) case *int64: i, err := strconv.ParseInt(header, 10, 64) if err != nil { return err } v.Set(reflect.ValueOf(&i)) case *float64: f, err := strconv.ParseFloat(header, 64) if err != nil { return err } v.Set(reflect.ValueOf(&f)) case *time.Time: t, err := time.Parse(RFC822, header) if err != nil { return err } v.Set(reflect.ValueOf(&t)) default: err := fmt.Errorf("Unsupported value for param %v (%s)", v.Interface(), v.Type()) return err } return nil }<|fim▁end|>
"github.com/revinate/etcd2s3/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/awserr" "github.com/revinate/etcd2s3/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/request" )
<|file_name|>add_o32_rAX_Id.java<|end_file_name|><|fim▁begin|>/* JPC: An x86 PC Hardware Emulator for a pure Java Virtual Machine Copyright (C) 2012-2013 Ian Preston 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. <|fim▁hole|> 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. Details (including contact information) can be found at: jpc.sourceforge.net or the developer website sourceforge.net/projects/jpc/ End of licence header */ package org.jpc.emulator.execution.opcodes.vm; import org.jpc.emulator.execution.*; import org.jpc.emulator.execution.decoder.*; import org.jpc.emulator.processor.*; import org.jpc.emulator.processor.fpu64.*; import static org.jpc.emulator.processor.Processor.*; public class add_o32_rAX_Id extends Executable { final int immd; public add_o32_rAX_Id(int blockStart, int eip, int prefices, PeekableInputStream input) { super(blockStart, eip); immd = Modrm.Id(input); } public Branch execute(Processor cpu) { cpu.flagOp1 = cpu.r_eax.get32(); cpu.flagOp2 = immd; cpu.flagResult = (cpu.flagOp1 + cpu.flagOp2); cpu.r_eax.set32(cpu.flagResult); cpu.flagIns = UCodes.ADD32; cpu.flagStatus = OSZAPC; return Branch.None; } public boolean isBranch() { return false; } public String toString() { return this.getClass().getName(); } }<|fim▁end|>
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
<|file_name|>jquery.flot.resize.min.js<|end_file_name|><|fim▁begin|>/* Flot plugin for automatically redrawing plots as the placeholder resizes. Copyright (c) 2007-2013 IOLA and Ole Laursen. Licensed under the MIT license. <|fim▁hole|>There are no options. If you need to disable the plugin for some plots, you can just fix the size of their placeholders. */ /* Inline dependency: * jQuery resize event - v1.1 - 3/14/2010 * http://benalman.com/projects/jquery-resize-plugin/ * * Copyright (c) 2010 "Cowboy" Ben Alman * Dual licensed under the MIT and GPL licenses. * http://benalman.com/about/license/ */(function($,h,c){var a=$([]),e=$.resize=$.extend($.resize,{}),i,k="setTimeout",j="resize",d=j+"-special-event",b="delay",f="throttleWindow";e[b]=250;e[f]=true;$.event.special[j]={setup:function(){if(!e[f]&&this[k]){return false}var l=$(this);a=a.add(l);$.data(this,d,{w:l.width(),h:l.height()});if(a.length===1){g()}},teardown:function(){if(!e[f]&&this[k]){return false}var l=$(this);a=a.not(l);l.removeData(d);if(!a.length){clearTimeout(i)}},add:function(l){if(!e[f]&&this[k]){return false}var n;function m(s,o,p){var q=$(this),r=$.data(this,d);r.w=o!==c?o:q.width();r.h=p!==c?p:q.height();n.apply(this,arguments)}if($.isFunction(l)){n=l;return m}else{n=l.handler;l.handler=m}}};function g(){i=h[k](function(){a.each(function(){var n=$(this),m=n.width(),l=n.height(),o=$.data(this,d);if(m!==o.w||l!==o.h){n.trigger(j,[o.w=m,o.h=l])}});g()},e[b])}})(jQuery,this); (function(e){function n(e){function t(){var t=e.getPlaceholder();if(t.width()==0||t.height()==0)return;e.resize(),e.setupGrid(),e.draw()}function n(e,n){e.getPlaceholder().resize(t)}function r(e,n){e.getPlaceholder().unbind("resize",t)}e.hooks.bindEvents.push(n),e.hooks.shutdown.push(r)}var t={};e.plot.plugins.push({init:n,options:t,name:"resize",version:"1.0"})})(jQuery);<|fim▁end|>
It works by listening for changes on the placeholder div (through the jQuery resize event plugin) - if the size changes, it will redraw the plot.
<|file_name|>google-maps.js<|end_file_name|><|fim▁begin|>'use strict'; angular.module('mean.system').directive('googleMaps', ['GoogleMaps', 'Global', function(GoogleMaps, Global) { return { restrict: 'E', template: '<div id="map" style="height: 600px; width: 100%;"></div>',<|fim▁hole|> center: new GoogleMaps.LatLng(-34.397, 150.644), zoom: 14, mapTypeId: GoogleMaps.MapTypeId.ROADMAP }; Global.map = new GoogleMaps.Map(document.getElementById('map'), mapOptions); } } }; }]);<|fim▁end|>
controller: function() { var mapOptions; if ( GoogleMaps ) { mapOptions = {
<|file_name|>test_call.py<|end_file_name|><|fim▁begin|>import py from rpython.flowspace.model import SpaceOperation, Constant, Variable from rpython.rtyper.lltypesystem import lltype, llmemory, rffi from rpython.translator.unsimplify import varoftype<|fim▁hole|>from rpython.rlib import jit from rpython.jit.codewriter import support, call from rpython.jit.codewriter.call import CallControl from rpython.jit.codewriter.effectinfo import EffectInfo class FakePolicy: def look_inside_graph(self, graph): return True def test_graphs_from_direct_call(): cc = CallControl() F = lltype.FuncType([], lltype.Signed) f = lltype.functionptr(F, 'f', graph='fgraph') v = varoftype(lltype.Signed) op = SpaceOperation('direct_call', [Constant(f, lltype.Ptr(F))], v) # lst = cc.graphs_from(op, {}.__contains__) assert lst is None # residual call # lst = cc.graphs_from(op, {'fgraph': True}.__contains__) assert lst == ['fgraph'] # normal call def test_graphs_from_indirect_call(): cc = CallControl() F = lltype.FuncType([], lltype.Signed) v = varoftype(lltype.Signed) graphlst = ['f1graph', 'f2graph'] op = SpaceOperation('indirect_call', [varoftype(lltype.Ptr(F)), Constant(graphlst, lltype.Void)], v) # lst = cc.graphs_from(op, {'f1graph': True, 'f2graph': True}.__contains__) assert lst == ['f1graph', 'f2graph'] # normal indirect call # lst = cc.graphs_from(op, {'f1graph': True}.__contains__) assert lst == ['f1graph'] # indirect call, look only inside some graphs # lst = cc.graphs_from(op, {}.__contains__) assert lst is None # indirect call, don't look inside any graph def test_graphs_from_no_target(): cc = CallControl() F = lltype.FuncType([], lltype.Signed) v = varoftype(lltype.Signed) op = SpaceOperation('indirect_call', [varoftype(lltype.Ptr(F)), Constant(None, lltype.Void)], v) lst = cc.graphs_from(op, {}.__contains__) assert lst is None # ____________________________________________________________ class FakeJitDriverSD: def __init__(self, portal_graph): self.portal_graph = portal_graph self.portal_runner_ptr = "???" def test_find_all_graphs(): def g(x): return x + 2 def f(x): return g(x) + 1 rtyper = support.annotate(f, [7]) jitdriver_sd = FakeJitDriverSD(rtyper.annotator.translator.graphs[0]) cc = CallControl(jitdrivers_sd=[jitdriver_sd]) res = cc.find_all_graphs(FakePolicy()) funcs = set([graph.func for graph in res]) assert funcs == set([f, g]) def test_find_all_graphs_without_g(): def g(x): return x + 2 def f(x): return g(x) + 1 rtyper = support.annotate(f, [7]) jitdriver_sd = FakeJitDriverSD(rtyper.annotator.translator.graphs[0]) cc = CallControl(jitdrivers_sd=[jitdriver_sd]) class CustomFakePolicy: def look_inside_graph(self, graph): assert graph.name == 'g' return False res = cc.find_all_graphs(CustomFakePolicy()) funcs = [graph.func for graph in res] assert funcs == [f] # ____________________________________________________________ def test_guess_call_kind_and_calls_from_graphs(): class portal_runner_obj: graph = object() class FakeJitDriverSD: portal_runner_ptr = portal_runner_obj g = object() g1 = object() cc = CallControl(jitdrivers_sd=[FakeJitDriverSD()]) cc.candidate_graphs = [g, g1] op = SpaceOperation('direct_call', [Constant(portal_runner_obj)], Variable()) assert cc.guess_call_kind(op) == 'recursive' class fakeresidual: _obj = object() op = SpaceOperation('direct_call', [Constant(fakeresidual)], Variable()) assert cc.guess_call_kind(op) == 'residual' class funcptr: class _obj: class graph: class func: oopspec = "spec" op = SpaceOperation('direct_call', [Constant(funcptr)], Variable()) assert cc.guess_call_kind(op) == 'builtin' class funcptr: class _obj: graph = g op = SpaceOperation('direct_call', [Constant(funcptr)], Variable()) res = cc.graphs_from(op) assert res == [g] assert cc.guess_call_kind(op) == 'regular' class funcptr: class _obj: graph = object() op = SpaceOperation('direct_call', [Constant(funcptr)], Variable()) res = cc.graphs_from(op) assert res is None assert cc.guess_call_kind(op) == 'residual' h = object() op = SpaceOperation('indirect_call', [Variable(), Constant([g, g1, h])], Variable()) res = cc.graphs_from(op) assert res == [g, g1] assert cc.guess_call_kind(op) == 'regular' op = SpaceOperation('indirect_call', [Variable(), Constant([h])], Variable()) res = cc.graphs_from(op) assert res is None assert cc.guess_call_kind(op) == 'residual' # ____________________________________________________________ def test_get_jitcode(monkeypatch): from rpython.jit.codewriter.test.test_flatten import FakeCPU class FakeRTyper: class annotator: translator = None def getfunctionptr(graph): F = lltype.FuncType([], lltype.Signed) return lltype.functionptr(F, 'bar') monkeypatch.setattr(call, 'getfunctionptr', getfunctionptr) cc = CallControl(FakeCPU(FakeRTyper())) class somegraph: name = "foo" jitcode = cc.get_jitcode(somegraph) assert jitcode is cc.get_jitcode(somegraph) # caching assert jitcode.name == "foo" pending = list(cc.enum_pending_graphs()) assert pending == [(somegraph, jitcode)] # ____________________________________________________________ def test_jit_force_virtualizable_effectinfo(): py.test.skip("XXX add a test for CallControl.getcalldescr() -> EF_xxx") def test_releases_gil_analyzer(): from rpython.jit.backend.llgraph.runner import LLGraphCPU T = rffi.CArrayPtr(rffi.TIME_T) external = rffi.llexternal("time", [T], rffi.TIME_T, releasegil=True) @jit.dont_look_inside def f(): return external(lltype.nullptr(T.TO)) rtyper = support.annotate(f, []) jitdriver_sd = FakeJitDriverSD(rtyper.annotator.translator.graphs[0]) cc = CallControl(LLGraphCPU(rtyper), jitdrivers_sd=[jitdriver_sd]) res = cc.find_all_graphs(FakePolicy()) [f_graph] = [x for x in res if x.func is f] [block, _] = list(f_graph.iterblocks()) [op] = block.operations call_descr = cc.getcalldescr(op) assert call_descr.extrainfo.has_random_effects() assert call_descr.extrainfo.is_call_release_gil() is False def test_call_release_gil(): from rpython.jit.backend.llgraph.runner import LLGraphCPU T = rffi.CArrayPtr(rffi.TIME_T) external = rffi.llexternal("time", [T], rffi.TIME_T, releasegil=True, save_err=rffi.RFFI_SAVE_ERRNO) # no jit.dont_look_inside in this test def f(): return external(lltype.nullptr(T.TO)) rtyper = support.annotate(f, []) jitdriver_sd = FakeJitDriverSD(rtyper.annotator.translator.graphs[0]) cc = CallControl(LLGraphCPU(rtyper), jitdrivers_sd=[jitdriver_sd]) res = cc.find_all_graphs(FakePolicy()) [llext_graph] = [x for x in res if x.func is external] [block, _] = list(llext_graph.iterblocks()) [op] = block.operations tgt_tuple = op.args[0].value._obj.graph.func._call_aroundstate_target_ assert type(tgt_tuple) is tuple and len(tgt_tuple) == 2 call_target, saveerr = tgt_tuple assert saveerr == rffi.RFFI_SAVE_ERRNO call_target = llmemory.cast_ptr_to_adr(call_target) call_descr = cc.getcalldescr(op) assert call_descr.extrainfo.has_random_effects() assert call_descr.extrainfo.is_call_release_gil() is True assert call_descr.extrainfo.call_release_gil_target == ( call_target, rffi.RFFI_SAVE_ERRNO) def test_random_effects_on_stacklet_switch(): from rpython.jit.backend.llgraph.runner import LLGraphCPU from rpython.translator.platform import CompilationError try: from rpython.rlib._rffi_stacklet import switch, handle except CompilationError as e: if "Unsupported platform!" in e.out: py.test.skip("Unsupported platform!") else: raise e @jit.dont_look_inside def f(): switch(rffi.cast(handle, 0)) rtyper = support.annotate(f, []) jitdriver_sd = FakeJitDriverSD(rtyper.annotator.translator.graphs[0]) cc = CallControl(LLGraphCPU(rtyper), jitdrivers_sd=[jitdriver_sd]) res = cc.find_all_graphs(FakePolicy()) [f_graph] = [x for x in res if x.func is f] [block, _] = list(f_graph.iterblocks()) op = block.operations[-1] call_descr = cc.getcalldescr(op) assert call_descr.extrainfo.has_random_effects() def test_no_random_effects_for_rotateLeft(): from rpython.jit.backend.llgraph.runner import LLGraphCPU from rpython.rlib.rarithmetic import r_uint if r_uint.BITS == 32: py.test.skip("64-bit only") from rpython.rlib.rmd5 import _rotateLeft def f(n, m): return _rotateLeft(r_uint(n), m) rtyper = support.annotate(f, [7, 9]) jitdriver_sd = FakeJitDriverSD(rtyper.annotator.translator.graphs[0]) cc = CallControl(LLGraphCPU(rtyper), jitdrivers_sd=[jitdriver_sd]) res = cc.find_all_graphs(FakePolicy()) [f_graph] = [x for x in res if x.func is f] [block, _] = list(f_graph.iterblocks()) op = block.operations[-1] call_descr = cc.getcalldescr(op) assert not call_descr.extrainfo.has_random_effects() assert call_descr.extrainfo.check_is_elidable() def test_elidable_kinds(): from rpython.jit.backend.llgraph.runner import LLGraphCPU @jit.elidable def f1(n, m): return n + m @jit.elidable def f2(n, m): return [n, m] # may raise MemoryError @jit.elidable def f3(n, m): if n > m: raise ValueError return n + m def f(n, m): a = f1(n, m) b = f2(n, m) c = f3(n, m) return a + len(b) + c rtyper = support.annotate(f, [7, 9]) jitdriver_sd = FakeJitDriverSD(rtyper.annotator.translator.graphs[0]) cc = CallControl(LLGraphCPU(rtyper), jitdrivers_sd=[jitdriver_sd]) res = cc.find_all_graphs(FakePolicy()) [f_graph] = [x for x in res if x.func is f] for index, expected in [ (0, EffectInfo.EF_ELIDABLE_CANNOT_RAISE), (1, EffectInfo.EF_ELIDABLE_OR_MEMORYERROR), (2, EffectInfo.EF_ELIDABLE_CAN_RAISE)]: call_op = f_graph.startblock.operations[index] assert call_op.opname == 'direct_call' call_descr = cc.getcalldescr(call_op) assert call_descr.extrainfo.extraeffect == expected def test_raise_elidable_no_result(): from rpython.jit.backend.llgraph.runner import LLGraphCPU l = [] @jit.elidable def f1(n, m): l.append(n) def f(n, m): f1(n, m) return n + m rtyper = support.annotate(f, [7, 9]) jitdriver_sd = FakeJitDriverSD(rtyper.annotator.translator.graphs[0]) cc = CallControl(LLGraphCPU(rtyper), jitdrivers_sd=[jitdriver_sd]) res = cc.find_all_graphs(FakePolicy()) [f_graph] = [x for x in res if x.func is f] call_op = f_graph.startblock.operations[0] assert call_op.opname == 'direct_call' with py.test.raises(Exception): call_descr = cc.getcalldescr(call_op)<|fim▁end|>
<|file_name|>temp_dir.py<|end_file_name|><|fim▁begin|>"""TempDir module."""<|fim▁hole|>import shutil class TempDir: """Class creating and managing the temporary directories.""" def __init__(self, directory: str): self.temp_dir = directory @classmethod def create(cls) -> "TempDir": """Initializes a TempDir object.""" temp_dir = tempfile.mkdtemp(prefix="exonum_test_suite_") return cls(temp_dir) def path(self) -> str: """Returns the path of the temporary dir.""" return self.temp_dir def remove(self) -> None: """Removes created temporary directory.""" shutil.rmtree(self.temp_dir)<|fim▁end|>
import tempfile
<|file_name|>TableLog.rs<|end_file_name|><|fim▁begin|>outputserver.TableLog$2 outputserver.TableLog$3<|fim▁hole|>outputserver.TableLog$7 outputserver.TableLog$6 outputserver.TableLog$5 outputserver.TableLog$4 outputserver.TableLog$CenterTableCellRenderer outputserver.TableLog outputserver.TableLog$8<|fim▁end|>
outputserver.TableLog$1
<|file_name|>DummyClass.java<|end_file_name|><|fim▁begin|>/* * * Copyright 2015 the original author or 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 springfox.documentation.spring.web.dummy; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import io.swagger.annotations.Authorization; import io.swagger.annotations.AuthorizationScope; import io.swagger.annotations.Extension; import io.swagger.annotations.ExtensionProperty; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.multipart.MultipartFile; import springfox.documentation.annotations.ApiIgnore; import springfox.documentation.spring.web.dummy.DummyModels.Ignorable; import springfox.documentation.spring.web.dummy.models.EnumType; import springfox.documentation.spring.web.dummy.models.Example; import springfox.documentation.spring.web.dummy.models.FoobarDto; import springfox.documentation.spring.web.dummy.models.Treeish; import javax.servlet.ServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Date; import java.util.List; import java.util.Map; @RequestMapping(produces = {"application/json"}, consumes = {"application/json", "application/xml"}) public class DummyClass { @ApiParam public void annotatedWithApiParam() { } public void dummyMethod() { } public void methodWithOneArgs(int a) { } public void methodWithTwoArgs(int a, String b) { } public void methodWithNoArgs() { } @ApiOperation(value = "description", httpMethod = "GET") public void methodWithHttpGETMethod() { } @ApiOperation(value = "description", nickname = "unique") public void methodWithNickName() { } @ApiOperation(value = "description", httpMethod = "GET", hidden = true) public void methodThatIsHidden() { } @ApiOperation(value = "description", httpMethod = "RUBBISH") public void methodWithInvalidHttpMethod() { } @ApiOperation(value = "summary", httpMethod = "RUBBISH") public void methodWithSummary() { } @ApiOperation(value = "", notes = "some notes") public void methodWithNotes() { } @ApiOperation(value = "", nickname = "a nickname") public void methodWithNickname() { } @ApiOperation(value = "", position = 5) public void methodWithPosition() { } @ApiOperation(value = "", consumes = "application/xml") public void methodWithXmlConsumes() { } @ApiOperation(value = "", produces = "application/xml") public void methodWithXmlProduces() { } @ApiOperation(value = "", produces = "application/xml, application/json", consumes = "application/xml, " + "application/json") public void methodWithMultipleMediaTypes() { } @ApiOperation(value = "", produces = "application/xml", consumes = "application/xml") public void methodWithBothXmlMediaTypes() { } @ApiOperation(value = "", produces = "application/json", consumes = "application/xml") public void methodWithMediaTypeAndFile(MultipartFile multipartFile) { } @ApiOperation(value = "", response = DummyModels.FunkyBusiness.class) public void methodApiResponseClass() { } @ApiResponses({ @ApiResponse(code = 201, response = Void.class, message = "Rule Scheduled successfuly"), @ApiResponse(code = 500, response = RestError.class, message = "Internal Server Error"), @ApiResponse(code = 406, response = RestError.class, message = "Not acceptable")}) public void methodAnnotatedWithApiResponse() { } @ApiOperation(value = "methodWithExtensions", extensions = { @Extension(properties = @ExtensionProperty(name="x-test1", value="value1")), @Extension(name="test2", properties = @ExtensionProperty(name="name2", value="value2")) } ) public void methodWithExtensions() { } @ApiOperation(value = "SomeVal", authorizations = @Authorization(value = "oauth2", scopes = {@AuthorizationScope(scope = "scope", description = "scope description") })) public void methodWithAuth() { } @ApiOperation(value = "") public DummyModels.FunkyBusiness methodWithAPiAnnotationButWithoutResponseClass() { return null; } @ApiOperation(value = "") public DummyModels.Paginated<BusinessType> methodWithGenericType() { return null; } public ResponseEntity<byte[]> methodWithGenericPrimitiveArray() { return null; } public ResponseEntity<DummyClass[]> methodWithGenericComplexArray() { return null; } public ResponseEntity<EnumType> methodWithEnumResponse() { return null; } @Deprecated public void methodWithDeprecated() { } public void methodWithServletRequest(ServletRequest req) { } public void methodWithBindingResult(BindingResult res) { } public void methodWithInteger(Integer integer) { } public void methodWithAnnotatedInteger(@Ignorable Integer integer) { } public void methodWithModelAttribute(@ModelAttribute Example example) { } public void methodWithoutModelAttribute(Example example) { } public void methodWithTreeishModelAttribute(@ModelAttribute Treeish example) { } @RequestMapping("/businesses/{businessId}") public void methodWithSinglePathVariable(@PathVariable String businessId) { } @RequestMapping("/businesses/{businessId}") public void methodWithSingleEnum(BusinessType businessType) { } @RequestMapping("/businesses/{businessId}") public void methodWithSingleEnumArray(BusinessType[] businessTypes) { } @RequestMapping("/businesses/{businessId}/employees/{employeeId}/salary") public void methodWithRatherLongRequestPath() { } @RequestMapping(value = "/parameter-conditions", params = "test=testValue") public void methodWithParameterRequestCondition() { } @ApiImplicitParam(name = "Authentication", dataType = "string", required = true, paramType = "header", value = "Authentication token") public void methodWithApiImplicitParam() { } @ApiImplicitParam(name = "Authentication", dataType = "string", required = true, paramType = "header", value = "Authentication token") public void methodWithApiImplicitParamAndInteger(Integer integer) { } @ApiImplicitParams({ @ApiImplicitParam(name = "lang", dataType = "string", required = true, paramType = "query", value = "Language", defaultValue = "EN", allowableValues = "EN,FR"), @ApiImplicitParam(name = "Authentication", dataType = "string", required = true, paramType = "header", value = "Authentication token") }) public void methodWithApiImplicitParams(Integer integer) { } public interface ApiImplicitParamsInterface { @ApiImplicitParams({ @ApiImplicitParam(name = "lang", dataType = "string", required = true, paramType = "query", value = "Language", defaultValue = "EN", allowableValues = "EN,FR") }) @ApiImplicitParam(name = "Authentication", dataType = "string", required = true, paramType = "header", value = "Authentication token") void methodWithApiImplicitParam(); } public static class ApiImplicitParamsClass implements ApiImplicitParamsInterface { @Override public void methodWithApiImplicitParam() { } } @ResponseBody public DummyModels.BusinessModel methodWithConcreteResponseBody() { return null; } @ResponseBody public Map<String, DummyModels.BusinessModel> methodWithMapReturn() { return null; } @ResponseBody @ResponseStatus(value = HttpStatus.ACCEPTED, reason = "Accepted request") public DummyModels.BusinessModel methodWithResponseStatusAnnotation() { return null; } @ResponseBody @ResponseStatus(value = HttpStatus.NO_CONTENT) public void methodWithResponseStatusAnnotationAndEmptyReason() { } @ResponseBody public DummyModels.AnnotatedBusinessModel methodWithModelPropertyAnnotations() { return null; } @ResponseBody public DummyModels.NamedBusinessModel methodWithModelAnnotations() { return null; } @ResponseBody public List<DummyModels.BusinessModel> methodWithListOfBusinesses() { return null; } @ResponseBody public DummyModels.CorporationModel methodWithConcreteCorporationModel() { return null; } @ResponseBody public Date methodWithDateResponseBody() { return null; } public void methodParameterWithRequestBodyAnnotation( @RequestBody DummyModels.BusinessModel model, HttpServletResponse response, DummyModels.AnnotatedBusinessModel annotatedBusinessModel) { } public void methodParameterWithRequestPartAnnotation( @RequestPart DummyModels.BusinessModel model, HttpServletResponse response, DummyModels.AnnotatedBusinessModel annotatedBusinessModel) { } public void methodParameterWithRequestPartAnnotationOnSimpleType( @RequestPart String model, HttpServletResponse response, DummyModels.AnnotatedBusinessModel annotatedBusinessModel) { } @ResponseBody public DummyModels.AnnotatedBusinessModel methodWithSameAnnotatedModelInReturnAndRequestBodyParam( @RequestBody DummyModels.AnnotatedBusinessModel model) { return null; } @ApiResponses({@ApiResponse(code = 413, message = "a message")}) public void methodWithApiResponses() { } @ApiIgnore public static class ApiIgnorableClass { @ApiIgnore public void dummyMethod() { } } @ResponseBody public DummyModels.ModelWithSerializeOnlyProperty methodWithSerializeOnlyPropInReturnAndRequestBodyParam( @RequestBody DummyModels.ModelWithSerializeOnlyProperty model) { return null; } @ResponseBody<|fim▁hole|> public enum BusinessType { PRODUCT(1), SERVICE(2); private int value; private BusinessType(int value) { this.value = value; } public int getValue() { return value; } } public class CustomClass { } public class MethodsWithSameName { public ResponseEntity methodToTest(Integer integer, Parent child) { return null; } public void methodToTest(Integer integer, Child child) { } } class Parent { } class Child extends Parent { } }<|fim▁end|>
public FoobarDto methodToTestFoobarDto(@RequestBody FoobarDto model) { return null; }
<|file_name|>trie.rs<|end_file_name|><|fim▁begin|>// Copyright 2013 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. //! Ordered containers with integer keys, implemented as radix tries (`TrieSet` and `TrieMap` types) use prelude::*; use mem; use uint; use util::replace; use unstable::intrinsics::init; use vec; // FIXME: #5244: need to manually update the TrieNode constructor static SHIFT: uint = 4; static SIZE: uint = 1 << SHIFT; static MASK: uint = SIZE - 1; static NUM_CHUNKS: uint = uint::bits / SHIFT; enum Child<T> { Internal(~TrieNode<T>), External(uint, T), Nothing } #[allow(missing_doc)] pub struct TrieMap<T> { priv root: TrieNode<T>, priv length: uint } impl<T> Container for TrieMap<T> { /// Return the number of elements in the map #[inline] fn len(&self) -> uint { self.length } } impl<T> Mutable for TrieMap<T> { /// Clear the map, removing all values. #[inline] fn clear(&mut self) { self.root = TrieNode::new(); self.length = 0; } } impl<T> Map<uint, T> for TrieMap<T> { /// Return a reference to the value corresponding to the key #[inline] fn find<'a>(&'a self, key: &uint) -> Option<&'a T> { let mut node: &'a TrieNode<T> = &self.root; let mut idx = 0; loop { match node.children[chunk(*key, idx)] { Internal(ref x) => node = &**x, External(stored, ref value) => { if stored == *key { return Some(value) } else { return None } } Nothing => return None } idx += 1; } } } impl<T> MutableMap<uint, T> for TrieMap<T> { /// Return a mutable reference to the value corresponding to the key #[inline] fn find_mut<'a>(&'a mut self, key: &uint) -> Option<&'a mut T> { find_mut(&mut self.root.children[chunk(*key, 0)], *key, 1) } /// Insert a key-value pair from the map. If the key already had a value /// present in the map, that value is returned. Otherwise None is returned. fn swap(&mut self, key: uint, value: T) -> Option<T> { let ret = insert(&mut self.root.count, &mut self.root.children[chunk(key, 0)], key, value, 1); if ret.is_none() { self.length += 1 } ret } /// Removes a key from the map, returning the value at the key if the key /// was previously in the map. fn pop(&mut self, key: &uint) -> Option<T> { let ret = remove(&mut self.root.count, &mut self.root.children[chunk(*key, 0)], *key, 1); if ret.is_some() { self.length -= 1 } ret } } impl<T> TrieMap<T> {<|fim▁hole|> TrieMap{root: TrieNode::new(), length: 0} } /// Visit all key-value pairs in reverse order #[inline] pub fn each_reverse<'a>(&'a self, f: |&uint, &'a T| -> bool) -> bool { self.root.each_reverse(f) } /// Get an iterator over the key-value pairs in the map pub fn iter<'a>(&'a self) -> Entries<'a, T> { let mut iter = unsafe {Entries::new()}; iter.stack[0] = self.root.children.iter(); iter.length = 1; iter.remaining_min = self.length; iter.remaining_max = self.length; iter } /// Get an iterator over the key-value pairs in the map, with the /// ability to mutate the values. pub fn mut_iter<'a>(&'a mut self) -> MutEntries<'a, T> { let mut iter = unsafe {MutEntries::new()}; iter.stack[0] = self.root.children.mut_iter(); iter.length = 1; iter.remaining_min = self.length; iter.remaining_max = self.length; iter } } // FIXME #5846 we want to be able to choose between &x and &mut x // (with many different `x`) below, so we need to optionally pass mut // as a tt, but the only thing we can do with a `tt` is pass them to // other macros, so this takes the `& <mutability> <operand>` token // sequence and forces their evalutation as an expression. (see also // `item!` below.) macro_rules! addr { ($e:expr) => { $e } } macro_rules! bound { ($iterator_name:ident, // the current treemap self = $this:expr, // the key to look for key = $key:expr, // are we looking at the upper bound? is_upper = $upper:expr, // method names for slicing/iterating. slice_from = $slice_from:ident, iter = $iter:ident, // see the comment on `addr!`, this is just an optional mut, but // there's no 0-or-1 repeats yet. mutability = $($mut_:tt)*) => { { // # For `mut` // We need an unsafe pointer here because we are borrowing // mutable references to the internals of each of these // mutable nodes, while still using the outer node. // // However, we're allowed to flaunt rustc like this because we // never actually modify the "shape" of the nodes. The only // place that mutation is can actually occur is of the actual // values of the TrieMap (as the return value of the // iterator), i.e. we can never cause a deallocation of any // TrieNodes so the raw pointer is always valid. // // # For non-`mut` // We like sharing code so much that even a little unsafe won't // stop us. let this = $this; let mut node = addr!(& $($mut_)* this.root as * $($mut_)* TrieNode<T>); let key = $key; let mut it = unsafe {$iterator_name::new()}; // everything else is zero'd, as we want. it.remaining_max = this.length; // this addr is necessary for the `Internal` pattern. addr!(loop { let children = unsafe {addr!(& $($mut_)* (*node).children)}; // it.length is the current depth in the iterator and the // current depth through the `uint` key we've traversed. let child_id = chunk(key, it.length); let (slice_idx, ret) = match children[child_id] { Internal(ref $($mut_)* n) => { node = addr!(& $($mut_)* **n as * $($mut_)* TrieNode<T>); (child_id + 1, false) } External(stored, _) => { (if stored < key || ($upper && stored == key) { child_id + 1 } else { child_id }, true) } Nothing => { (child_id + 1, true) } }; // push to the stack. it.stack[it.length] = children.$slice_from(slice_idx).$iter(); it.length += 1; if ret { return it } }) } } } impl<T> TrieMap<T> { // If `upper` is true then returns upper_bound else returns lower_bound. #[inline] fn bound<'a>(&'a self, key: uint, upper: bool) -> Entries<'a, T> { bound!(Entries, self = self, key = key, is_upper = upper, slice_from = slice_from, iter = iter, mutability = ) } /// Get an iterator pointing to the first key-value pair whose key is not less than `key`. /// If all keys in the map are less than `key` an empty iterator is returned. pub fn lower_bound<'a>(&'a self, key: uint) -> Entries<'a, T> { self.bound(key, false) } /// Get an iterator pointing to the first key-value pair whose key is greater than `key`. /// If all keys in the map are not greater than `key` an empty iterator is returned. pub fn upper_bound<'a>(&'a self, key: uint) -> Entries<'a, T> { self.bound(key, true) } // If `upper` is true then returns upper_bound else returns lower_bound. #[inline] fn mut_bound<'a>(&'a mut self, key: uint, upper: bool) -> MutEntries<'a, T> { bound!(MutEntries, self = self, key = key, is_upper = upper, slice_from = mut_slice_from, iter = mut_iter, mutability = mut) } /// Get an iterator pointing to the first key-value pair whose key is not less than `key`. /// If all keys in the map are less than `key` an empty iterator is returned. pub fn mut_lower_bound<'a>(&'a mut self, key: uint) -> MutEntries<'a, T> { self.mut_bound(key, false) } /// Get an iterator pointing to the first key-value pair whose key is greater than `key`. /// If all keys in the map are not greater than `key` an empty iterator is returned. pub fn mut_upper_bound<'a>(&'a mut self, key: uint) -> MutEntries<'a, T> { self.mut_bound(key, true) } } impl<T> FromIterator<(uint, T)> for TrieMap<T> { fn from_iterator<Iter: Iterator<(uint, T)>>(iter: &mut Iter) -> TrieMap<T> { let mut map = TrieMap::new(); map.extend(iter); map } } impl<T> Extendable<(uint, T)> for TrieMap<T> { fn extend<Iter: Iterator<(uint, T)>>(&mut self, iter: &mut Iter) { for (k, v) in *iter { self.insert(k, v); } } } #[allow(missing_doc)] pub struct TrieSet { priv map: TrieMap<()> } impl Container for TrieSet { /// Return the number of elements in the set #[inline] fn len(&self) -> uint { self.map.len() } } impl Mutable for TrieSet { /// Clear the set, removing all values. #[inline] fn clear(&mut self) { self.map.clear() } } impl TrieSet { /// Create an empty TrieSet #[inline] pub fn new() -> TrieSet { TrieSet{map: TrieMap::new()} } /// Return true if the set contains a value #[inline] pub fn contains(&self, value: &uint) -> bool { self.map.contains_key(value) } /// Add a value to the set. Return true if the value was not already /// present in the set. #[inline] pub fn insert(&mut self, value: uint) -> bool { self.map.insert(value, ()) } /// Remove a value from the set. Return true if the value was /// present in the set. #[inline] pub fn remove(&mut self, value: &uint) -> bool { self.map.remove(value) } /// Visit all values in reverse order #[inline] pub fn each_reverse(&self, f: |&uint| -> bool) -> bool { self.map.each_reverse(|k, _| f(k)) } /// Get an iterator over the values in the set #[inline] pub fn iter<'a>(&'a self) -> SetItems<'a> { SetItems{iter: self.map.iter()} } /// Get an iterator pointing to the first value that is not less than `val`. /// If all values in the set are less than `val` an empty iterator is returned. pub fn lower_bound<'a>(&'a self, val: uint) -> SetItems<'a> { SetItems{iter: self.map.lower_bound(val)} } /// Get an iterator pointing to the first value that key is greater than `val`. /// If all values in the set are not greater than `val` an empty iterator is returned. pub fn upper_bound<'a>(&'a self, val: uint) -> SetItems<'a> { SetItems{iter: self.map.upper_bound(val)} } } impl FromIterator<uint> for TrieSet { fn from_iterator<Iter: Iterator<uint>>(iter: &mut Iter) -> TrieSet { let mut set = TrieSet::new(); set.extend(iter); set } } impl Extendable<uint> for TrieSet { fn extend<Iter: Iterator<uint>>(&mut self, iter: &mut Iter) { for elem in *iter { self.insert(elem); } } } struct TrieNode<T> { count: uint, children: [Child<T>, ..SIZE] } impl<T> TrieNode<T> { #[inline] fn new() -> TrieNode<T> { // FIXME: #5244: [Nothing, ..SIZE] should be possible without implicit // copyability TrieNode{count: 0, children: [Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing]} } } impl<T> TrieNode<T> { fn each_reverse<'a>(&'a self, f: |&uint, &'a T| -> bool) -> bool { for elt in self.children.rev_iter() { match *elt { Internal(ref x) => if !x.each_reverse(|i,t| f(i,t)) { return false }, External(k, ref v) => if !f(&k, v) { return false }, Nothing => () } } true } } // if this was done via a trait, the key could be generic #[inline] fn chunk(n: uint, idx: uint) -> uint { let sh = uint::bits - (SHIFT * (idx + 1)); (n >> sh) & MASK } fn find_mut<'r, T>(child: &'r mut Child<T>, key: uint, idx: uint) -> Option<&'r mut T> { match *child { External(stored, ref mut value) if stored == key => Some(value), External(..) => None, Internal(ref mut x) => find_mut(&mut x.children[chunk(key, idx)], key, idx + 1), Nothing => None } } fn insert<T>(count: &mut uint, child: &mut Child<T>, key: uint, value: T, idx: uint) -> Option<T> { // we branch twice to avoid having to do the `replace` when we // don't need to; this is much faster, especially for keys that // have long shared prefixes. match *child { Nothing => { *count += 1; *child = External(key, value); return None; } Internal(ref mut x) => { return insert(&mut x.count, &mut x.children[chunk(key, idx)], key, value, idx + 1); } External(stored_key, ref mut stored_value) if stored_key == key => { // swap in the new value and return the old. return Some(replace(stored_value, value)); } _ => {} } // conflict, an external node with differing keys: we have to // split the node, so we need the old value by value; hence we // have to move out of `child`. match replace(child, Nothing) { External(stored_key, stored_value) => { let mut new = ~TrieNode::new(); insert(&mut new.count, &mut new.children[chunk(stored_key, idx)], stored_key, stored_value, idx + 1); let ret = insert(&mut new.count, &mut new.children[chunk(key, idx)], key, value, idx + 1); *child = Internal(new); return ret; } _ => unreachable!() } } fn remove<T>(count: &mut uint, child: &mut Child<T>, key: uint, idx: uint) -> Option<T> { let (ret, this) = match *child { External(stored, _) if stored == key => { match replace(child, Nothing) { External(_, value) => (Some(value), true), _ => fail!() } } External(..) => (None, false), Internal(ref mut x) => { let ret = remove(&mut x.count, &mut x.children[chunk(key, idx)], key, idx + 1); (ret, x.count == 0) } Nothing => (None, false) }; if this { *child = Nothing; *count -= 1; } return ret; } /// Forward iterator over a map pub struct Entries<'a, T> { priv stack: [vec::Items<'a, Child<T>>, .. NUM_CHUNKS], priv length: uint, priv remaining_min: uint, priv remaining_max: uint } /// Forward iterator over the key-value pairs of a map, with the /// values being mutable. pub struct MutEntries<'a, T> { priv stack: [vec::MutItems<'a, Child<T>>, .. NUM_CHUNKS], priv length: uint, priv remaining_min: uint, priv remaining_max: uint } // FIXME #5846: see `addr!` above. macro_rules! item { ($i:item) => {$i}} macro_rules! iterator_impl { ($name:ident, iter = $iter:ident, mutability = $($mut_:tt)*) => { impl<'a, T> $name<'a, T> { // Create new zero'd iterator. We have a thin gilding of safety by // using init rather than uninit, so that the worst that can happen // from failing to initialise correctly after calling these is a // segfault. #[cfg(target_word_size="32")] unsafe fn new() -> $name<'a, T> { $name { remaining_min: 0, remaining_max: 0, length: 0, // ick :( ... at least the compiler will tell us if we screwed up. stack: [init(), init(), init(), init(), init(), init(), init(), init()] } } #[cfg(target_word_size="64")] unsafe fn new() -> $name<'a, T> { $name { remaining_min: 0, remaining_max: 0, length: 0, stack: [init(), init(), init(), init(), init(), init(), init(), init(), init(), init(), init(), init(), init(), init(), init(), init()] } } } item!(impl<'a, T> Iterator<(uint, &'a $($mut_)* T)> for $name<'a, T> { // you might wonder why we're not even trying to act within the // rules, and are just manipulating raw pointers like there's no // such thing as invalid pointers and memory unsafety. The // reason is performance, without doing this we can get the // bench_iter_large microbenchmark down to about 30000 ns/iter // (using .unsafe_ref to index self.stack directly, 38000 // ns/iter with [] checked indexing), but this smashes that down // to 13500 ns/iter. // // Fortunately, it's still safe... // // We have an invariant that every Internal node // corresponds to one push to self.stack, and one pop, // nested appropriately. self.stack has enough storage // to store the maximum depth of Internal nodes in the // trie (8 on 32-bit platforms, 16 on 64-bit). fn next(&mut self) -> Option<(uint, &'a $($mut_)* T)> { let start_ptr = self.stack.as_mut_ptr(); unsafe { // write_ptr is the next place to write to the stack. // invariant: start_ptr <= write_ptr < end of the // vector. let mut write_ptr = start_ptr.offset(self.length as int); while write_ptr != start_ptr { // indexing back one is safe, since write_ptr > // start_ptr now. match (*write_ptr.offset(-1)).next() { // exhausted this iterator (i.e. finished this // Internal node), so pop from the stack. // // don't bother clearing the memory, because the // next time we use it we'll've written to it // first. None => write_ptr = write_ptr.offset(-1), Some(child) => { addr!(match *child { Internal(ref $($mut_)* node) => { // going down a level, so push // to the stack (this is the // write referenced above) *write_ptr = node.children.$iter(); write_ptr = write_ptr.offset(1); } External(key, ref $($mut_)* value) => { self.remaining_max -= 1; if self.remaining_min > 0 { self.remaining_min -= 1; } // store the new length of the // stack, based on our current // position. self.length = (write_ptr as uint - start_ptr as uint) / mem::size_of_val(&*write_ptr); return Some((key, value)); } Nothing => {} }) } } } } return None; } #[inline] fn size_hint(&self) -> (uint, Option<uint>) { (self.remaining_min, Some(self.remaining_max)) } }) } } iterator_impl! { Entries, iter = iter, mutability = } iterator_impl! { MutEntries, iter = mut_iter, mutability = mut } /// Forward iterator over a set pub struct SetItems<'a> { priv iter: Entries<'a, ()> } impl<'a> Iterator<uint> for SetItems<'a> { fn next(&mut self) -> Option<uint> { self.iter.next().map(|(key, _)| key) } fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() } } #[cfg(test)] pub fn check_integrity<T>(trie: &TrieNode<T>) { assert!(trie.count != 0); let mut sum = 0; for x in trie.children.iter() { match *x { Nothing => (), Internal(ref y) => { check_integrity(&**y); sum += 1 } External(_, _) => { sum += 1 } } } assert_eq!(sum, trie.count); } #[cfg(test)] mod test_map { use super::*; use prelude::*; use iter::range_step; use uint; #[test] fn test_find_mut() { let mut m = TrieMap::new(); assert!(m.insert(1, 12)); assert!(m.insert(2, 8)); assert!(m.insert(5, 14)); let new = 100; match m.find_mut(&5) { None => fail!(), Some(x) => *x = new } assert_eq!(m.find(&5), Some(&new)); } #[test] fn test_find_mut_missing() { let mut m = TrieMap::new(); assert!(m.find_mut(&0).is_none()); assert!(m.insert(1, 12)); assert!(m.find_mut(&0).is_none()); assert!(m.insert(2, 8)); assert!(m.find_mut(&0).is_none()); } #[test] fn test_step() { let mut trie = TrieMap::new(); let n = 300u; for x in range_step(1u, n, 2) { assert!(trie.insert(x, x + 1)); assert!(trie.contains_key(&x)); check_integrity(&trie.root); } for x in range_step(0u, n, 2) { assert!(!trie.contains_key(&x)); assert!(trie.insert(x, x + 1)); check_integrity(&trie.root); } for x in range(0u, n) { assert!(trie.contains_key(&x)); assert!(!trie.insert(x, x + 1)); check_integrity(&trie.root); } for x in range_step(1u, n, 2) { assert!(trie.remove(&x)); assert!(!trie.contains_key(&x)); check_integrity(&trie.root); } for x in range_step(0u, n, 2) { assert!(trie.contains_key(&x)); assert!(!trie.insert(x, x + 1)); check_integrity(&trie.root); } } #[test] fn test_each_reverse() { let mut m = TrieMap::new(); assert!(m.insert(3, 6)); assert!(m.insert(0, 0)); assert!(m.insert(4, 8)); assert!(m.insert(2, 4)); assert!(m.insert(1, 2)); let mut n = 4; m.each_reverse(|k, v| { assert_eq!(*k, n); assert_eq!(*v, n * 2); n -= 1; true }); } #[test] fn test_each_reverse_break() { let mut m = TrieMap::new(); for x in range(uint::max_value - 10000, uint::max_value).invert() { m.insert(x, x / 2); } let mut n = uint::max_value - 1; m.each_reverse(|k, v| { if n == uint::max_value - 5000 { false } else { assert!(n > uint::max_value - 5000); assert_eq!(*k, n); assert_eq!(*v, n / 2); n -= 1; true } }); } #[test] fn test_swap() { let mut m = TrieMap::new(); assert_eq!(m.swap(1, 2), None); assert_eq!(m.swap(1, 3), Some(2)); assert_eq!(m.swap(1, 4), Some(3)); } #[test] fn test_pop() { let mut m = TrieMap::new(); m.insert(1, 2); assert_eq!(m.pop(&1), Some(2)); assert_eq!(m.pop(&1), None); } #[test] fn test_from_iter() { let xs = ~[(1u, 1i), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)]; let map: TrieMap<int> = xs.iter().map(|&x| x).collect(); for &(k, v) in xs.iter() { assert_eq!(map.find(&k), Some(&v)); } } #[test] fn test_iteration() { let empty_map : TrieMap<uint> = TrieMap::new(); assert_eq!(empty_map.iter().next(), None); let first = uint::max_value - 10000; let last = uint::max_value; let mut map = TrieMap::new(); for x in range(first, last).invert() { map.insert(x, x / 2); } let mut i = 0; for (k, &v) in map.iter() { assert_eq!(k, first + i); assert_eq!(v, k / 2); i += 1; } assert_eq!(i, last - first); } #[test] fn test_mut_iter() { let mut empty_map : TrieMap<uint> = TrieMap::new(); assert!(empty_map.mut_iter().next().is_none()); let first = uint::max_value - 10000; let last = uint::max_value; let mut map = TrieMap::new(); for x in range(first, last).invert() { map.insert(x, x / 2); } let mut i = 0; for (k, v) in map.mut_iter() { assert_eq!(k, first + i); *v -= k / 2; i += 1; } assert_eq!(i, last - first); assert!(map.iter().all(|(_, &v)| v == 0)); } #[test] fn test_bound() { let empty_map : TrieMap<uint> = TrieMap::new(); assert_eq!(empty_map.lower_bound(0).next(), None); assert_eq!(empty_map.upper_bound(0).next(), None); let last = 999u; let step = 3u; let value = 42u; let mut map : TrieMap<uint> = TrieMap::new(); for x in range_step(0u, last, step) { assert!(x % step == 0); map.insert(x, value); } for i in range(0u, last - step) { let mut lb = map.lower_bound(i); let mut ub = map.upper_bound(i); let next_key = i - i % step + step; let next_pair = (next_key, &value); if i % step == 0 { assert_eq!(lb.next(), Some((i, &value))); } else { assert_eq!(lb.next(), Some(next_pair)); } assert_eq!(ub.next(), Some(next_pair)); } let mut lb = map.lower_bound(last - step); assert_eq!(lb.next(), Some((last - step, &value))); let mut ub = map.upper_bound(last - step); assert_eq!(ub.next(), None); for i in range(last - step + 1, last) { let mut lb = map.lower_bound(i); assert_eq!(lb.next(), None); let mut ub = map.upper_bound(i); assert_eq!(ub.next(), None); } } #[test] fn test_mut_bound() { let empty_map : TrieMap<uint> = TrieMap::new(); assert_eq!(empty_map.lower_bound(0).next(), None); assert_eq!(empty_map.upper_bound(0).next(), None); let mut m_lower = TrieMap::new(); let mut m_upper = TrieMap::new(); for i in range(0u, 100) { m_lower.insert(2 * i, 4 * i); m_upper.insert(2 * i, 4 * i); } for i in range(0u, 199) { let mut lb_it = m_lower.mut_lower_bound(i); let (k, v) = lb_it.next().unwrap(); let lb = i + i % 2; assert_eq!(lb, k); *v -= k; } for i in range(0u, 198) { let mut ub_it = m_upper.mut_upper_bound(i); let (k, v) = ub_it.next().unwrap(); let ub = i + 2 - i % 2; assert_eq!(ub, k); *v -= k; } assert!(m_lower.mut_lower_bound(199).next().is_none()); assert!(m_upper.mut_upper_bound(198).next().is_none()); assert!(m_lower.iter().all(|(_, &x)| x == 0)); assert!(m_upper.iter().all(|(_, &x)| x == 0)); } } #[cfg(test)] mod bench_map { use super::*; use prelude::*; use rand::{weak_rng, Rng}; use extra::test::BenchHarness; #[bench] fn bench_iter_small(bh: &mut BenchHarness) { let mut m = TrieMap::<uint>::new(); let mut rng = weak_rng(); for _ in range(0, 20) { m.insert(rng.gen(), rng.gen()); } bh.iter(|| for _ in m.iter() {}) } #[bench] fn bench_iter_large(bh: &mut BenchHarness) { let mut m = TrieMap::<uint>::new(); let mut rng = weak_rng(); for _ in range(0, 1000) { m.insert(rng.gen(), rng.gen()); } bh.iter(|| for _ in m.iter() {}) } #[bench] fn bench_lower_bound(bh: &mut BenchHarness) { let mut m = TrieMap::<uint>::new(); let mut rng = weak_rng(); for _ in range(0, 1000) { m.insert(rng.gen(), rng.gen()); } bh.iter(|| { for _ in range(0, 10) { m.lower_bound(rng.gen()); } }); } #[bench] fn bench_upper_bound(bh: &mut BenchHarness) { let mut m = TrieMap::<uint>::new(); let mut rng = weak_rng(); for _ in range(0, 1000) { m.insert(rng.gen(), rng.gen()); } bh.iter(|| { for _ in range(0, 10) { m.upper_bound(rng.gen()); } }); } #[bench] fn bench_insert_large(bh: &mut BenchHarness) { let mut m = TrieMap::<[uint, .. 10]>::new(); let mut rng = weak_rng(); bh.iter(|| { for _ in range(0, 1000) { m.insert(rng.gen(), [1, .. 10]); } }) } #[bench] fn bench_insert_large_low_bits(bh: &mut BenchHarness) { let mut m = TrieMap::<[uint, .. 10]>::new(); let mut rng = weak_rng(); bh.iter(|| { for _ in range(0, 1000) { // only have the last few bits set. m.insert(rng.gen::<uint>() & 0xff_ff, [1, .. 10]); } }) } #[bench] fn bench_insert_small(bh: &mut BenchHarness) { let mut m = TrieMap::<()>::new(); let mut rng = weak_rng(); bh.iter(|| { for _ in range(0, 1000) { m.insert(rng.gen(), ()); } }) } #[bench] fn bench_insert_small_low_bits(bh: &mut BenchHarness) { let mut m = TrieMap::<()>::new(); let mut rng = weak_rng(); bh.iter(|| { for _ in range(0, 1000) { // only have the last few bits set. m.insert(rng.gen::<uint>() & 0xff_ff, ()); } }) } } #[cfg(test)] mod test_set { use super::*; use prelude::*; use uint; #[test] fn test_sane_chunk() { let x = 1; let y = 1 << (uint::bits - 1); let mut trie = TrieSet::new(); assert!(trie.insert(x)); assert!(trie.insert(y)); assert_eq!(trie.len(), 2); let expected = [x, y]; for (i, x) in trie.iter().enumerate() { assert_eq!(expected[i], x); } } #[test] fn test_from_iter() { let xs = ~[9u, 8, 7, 6, 5, 4, 3, 2, 1]; let set: TrieSet = xs.iter().map(|&x| x).collect(); for x in xs.iter() { assert!(set.contains(x)); } } }<|fim▁end|>
/// Create an empty TrieMap #[inline] pub fn new() -> TrieMap<T> {
<|file_name|>editor.js<|end_file_name|><|fim▁begin|>/* This file is part of Booktype. Copyright (c) 2012 Aleksandar Erkalovic <[email protected]> Booktype 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. Booktype 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 Booktype. If not, see <http://www.gnu.org/licenses/>. */ (function (win, jquery, _) { 'use strict'; jquery.namespace('win.booktype.editor'); /* Hold some basic variables and functions that are needed on global level and almost in all situations. */ win.booktype.editor = (function () { // Default settings var DEFAULTS = { panels: { 'edit': 'win.booktype.editor.edit', 'toc' : 'win.booktype.editor.toc', 'media' : 'win.booktype.editor.media' }, styles: { 'style1': '/static/edit/css/style1.css', 'style2': '/static/edit/css/style2.css', 'style3': '/static/edit/css/style3.css' }, tabs: { 'icon_generator': function (tb) { var tl = ''; if (!_.isUndefined(tb.title)) { if (tb.isLeft) { tl = 'rel="tooltip" data-placement="right" data-original-title="' + tb.title + '"'; } else { tl = 'rel="tooltip" data-placement="left" data-original-title="' + tb.title + '"'; } } return '<a href="#" id="' + tb.tabID + '"' + tl + '><i class="' + tb.iconID + '"></i></a>'; } }, config: { 'global': { 'tabs': ['online-users', 'chat'] }, 'edit': { 'tabs': ['chapters', 'attachments', 'notes', 'history', 'style'], 'toolbar': { 'H': ['table-dropdown', 'unorderedList', 'orderedList'], 'TABLE': ['unorderedList', 'orderedList', 'indent-left', 'indent-right'], 'PRE': ['table-dropdown', 'alignLeft', 'alignRight', 'indent-left', 'indent-right', 'alignCenter', 'alignJustify', 'unorderedList', 'orderedList'], 'ALL': ['table-dropdown', 'alignLeft', 'alignRight', 'indent-left', 'indent-right', 'alignCenter', 'alignJustify', 'unorderedList', 'orderedList', 'currentHeading', 'heading-dropdown'] }, 'menu': { 'H': ['insertImage', 'insertLink', 'horizontalline', 'pbreak'], 'TABLE': ['horizontalline', 'pbreak', 'indent-left', 'indent-right'], 'PRE': ['insertImage', 'insertLink', 'horizontalline', 'pbreak', 'indent-left', 'indent-right'], 'ALL': ['insertImage', 'insertLink', 'horizontalline', 'pbreak', 'indent-left', 'indent-right'] } }, 'media': { 'allowUpload': ['.jpe?g$', '.png$'] }, 'toc': { 'tabs': ['hold'], 'sortable': {'is_allowed': function (placeholder, parent, item) { return true; } } } } }; // Our global data var data = { 'chapters': null, 'holdChapters': null, 'statuses': null, 'activeStyle': 'style1', 'activePanel': null, 'panels': null, 'settings': {} }; var EditorRouter = Backbone.Router.extend({ routes: { 'edit/:id': 'edit' }, edit: function (id) { _editChapter(id); } }); var router = new EditorRouter(); // ID of the chapter which is being edited var currentEdit = null; // TABS var tabs = []; var Tab = function (tabID, iconID) { this.tabID = tabID; this.iconID = iconID; this.domID = ''; this.isLeft = false; this.isOnTop = false; this.title = ''; }; Tab.prototype.onActivate = function () {}; Tab.prototype.onDeactivate = function () {}; var hideAllTabs = function () { jquery('.right-tabpane').removeClass('open hold'); jquery('body').removeClass('opentabpane-right'); jquery('.right-tablist li').removeClass('active'); jquery('.left-tabpane').removeClass('open hold'); jquery('body').removeClass('opentabpane-left'); jquery('.left-tablist li').removeClass('active'); }; // Right tab var createRightTab = function (tabID, iconID, title) { var tb = new Tab(tabID, iconID); tb.isLeft = false; tb.domID = '.right-tablist li #' + tabID; if (!_.isUndefined(title)) { tb.title = title; } return tb; }; // Left tab var createLeftTab = function (tabID, iconID, title) { var tb = new Tab(tabID, iconID); tb.isLeft = true; tb.domID = '.left-tablist li #' + tabID; if (!_.isUndefined(title)) { tb.title = title; } return tb; }; // Initialise all tabs var activateTabs = function (tabList) { var _gen = data.settings.tabs['icon_generator']; jquery.each(tabList, function (i, v) { if (!v.isLeft) { if (v.isOnTop && jquery('DIV.right-tablist UL.navigation-tabs li').length > 0) { jquery('DIV.right-tablist UL.navigation-tabs li:eq(0)').before('<li>' + _gen(v) + '</li>'); } else { jquery('DIV.right-tablist UL.navigation-tabs').append('<li>' + _gen(v) + '</li>'); } jquery(v.domID).click(function () { //close left side jquery('.left-tabpane').removeClass('open hold'); jquery('body').removeClass('opentabpane-left'); jquery('.left-tablist li').removeClass('active'); // check if the tab is open if (jquery('#right-tabpane').hasClass('open')) { // if clicked on active tab, close tab if (jquery(this).closest('li').hasClass('active')) { jquery('.right-tabpane').toggleClass('open'); jquery('.right-tabpane').removeClass('hold'); jquery('.right-tabpane section').hide(); jquery('body').toggleClass('opentabpane-right'); jquery(this).closest('li').toggleClass('active'); } else { // open but not active, switching content jquery(this).closest('ul').find('li').removeClass('active'); jquery(this).parent().toggleClass('active'); jquery('.right-tabpane').removeClass('hold'); var target = jquery(this).attr('id'); jquery('.right-tabpane section').hide(); jquery('.right-tabpane section[source_id="' + target + '"]').show(); var isHold = jquery(this).attr('id'); if (isHold === 'hold-tab') { jquery('.right-tabpane').addClass('hold'); } v.onActivate(); } } else { // if closed, open tab jquery('body').toggleClass('opentabpane-right'); jquery(this).parent().toggleClass('active'); jquery('.right-tabpane').toggleClass('open'); var target = jquery(this).attr('id'); jquery('.right-tabpane section').hide(); jquery('.right-tabpane section[source_id="' + target + '"]').show(); var isHold = jquery(this).attr('id'); if (isHold === 'hold-tab') { jquery('.right-tabpane').addClass('hold'); } v.onActivate(); } return false; }); } else { if (v.isOnTop && jquery('DIV.left-tablist UL.navigation-tabs li').length > 0) { jquery('DIV.left-tablist UL.navigation-tabs li:eq(0)').before('<li>' + _gen(v) + '</li>'); } else { jquery('DIV.left-tablist UL.navigation-tabs').append('<li>' + _gen(v) + '</li>'); } jquery(v.domID).click(function () { //close right side jquery('.right-tabpane').removeClass('open hold'); jquery('body').removeClass('opentabpane-right'); jquery('.right-tablist li').removeClass('active'); // check if the tab is open if (jquery('#left-tabpane').hasClass('open')) { // if clicked on active tab, close tab if (jquery(this).closest('li').hasClass('active')) { jquery('.left-tabpane').toggleClass('open'); jquery('.left-tabpane').removeClass('hold'); jquery('.left-tabpane section').hide(); jquery('body').toggleClass('opentabpane-left'); jquery(this).closest('li').toggleClass('active');<|fim▁hole|> jquery('.left-tabpane').removeClass('hold'); var target = jquery(this).attr('id'); jquery('.left-tabpane section').hide(); jquery('.left-tabpane section[source_id="' + target + '"]').show(); var isHold = jquery(this).attr('id'); if (isHold === 'hold-tab') { jquery('.left-tabpane').addClass('hold'); } v.onActivate(); } } else { // if closed, open tab jquery('body').toggleClass('opentabpane-left'); jquery(this).parent().toggleClass('active'); jquery('.left-tabpane').toggleClass('open'); //jquery('.right-tabpane').removeClass('open'); var target = jquery(this).attr('id'); jquery('.left-tabpane section').hide(); jquery('.left-tabpane section[source_id="' + target + '"]').show(); var isHold = jquery(this).attr('id'); if (isHold === 'hold-tab') { jquery('.left-tabpane').addClass('hold'); } v.onActivate(); } return false; }); } }); jquery('DIV.left-tablist [rel=tooltip]').tooltip({container: 'body'}); jquery('DIV.right-tablist [rel=tooltip]').tooltip({container: 'body'}); }; var deactivateTabs = function (tabList) { jquery('DIV.left-tablist [rel=tooltip]').tooltip('destroy'); jquery('DIV.right-tablist [rel=tooltip]').tooltip('destroy'); jquery.each(tabList, function (i, v) { if (v.isLeft) { jquery('DIV.left-tablist UL.navigation-tabs #' + v.tabID).remove(); } else { jquery('DIV.right-tablist UL.navigation-tabs #' + v.tabID).remove(); } }); }; // UTIL FUNCTIONS var _editChapter = function (id) { win.booktype.ui.notify(win.booktype._('loading_chapter', 'Loading chapter.')); win.booktype.sendToCurrentBook({ 'command': 'get_chapter', 'chapterID': id }, function (dta) { currentEdit = id; var activePanel = win.booktype.editor.getActivePanel(); activePanel.hide(function () { data.activePanel = data.panels['edit']; data.activePanel.setChapterID(id); jquery('#contenteditor').html(dta.content); data.activePanel.show(); win.booktype.ui.notify(); // Trigger events var doc = win.booktype.editor.getChapterWithID(id); jquery(document).trigger('booktype-document-loaded', [doc]); }); } ); }; // Init UI var _initUI = function () { win.booktype.ui.notify(); // History Backbone.history.start({pushState: false, root: '/' + win.booktype.currentBookURL + '/_edit/', hashChange: true}); // This is a default route. Instead of doing it from the Router we do it this way so user could easily // change his default route from the booktype events. // This should probably be some kind of default callback. var match = win.location.href.match(/#(.*)$/); if (!match) { data.activePanel = data.panels['toc']; data.activePanel.show(); } // Check configuration for this. Do not show it if it is not enabled. // ONLINE USERS TAB if (isEnabledTab('global', 'online-users')) { var t1 = createLeftTab('online-users-tab', 'big-icon-online-users'); t1.onActivate = function () { }; tabs.push(t1); } // CHAT TAB // Only activate if it is enabled. if (isEnabledTab('global', 'chat')) { var t2 = createLeftTab('chat-tab', 'big-icon-chat'); t2.draw = function () { var $this = this; var $container = jquery('section[source_id=chat-tab]'); var scrollBottom = function () { var scrollHeight = jquery('.content', $container)[0].scrollHeight; jquery('.content', $container).scrollTop(scrollHeight); }; $this.formatString = function (frm, args) { return frm.replace(/\{\{|\}\}|\{(\d+)\}/g, function (m, n) { if (m === '{{') { return '{'; } if (m === '}}') { return '}'; } return win.booktype.utils.escapeJS(args[n]); } ); }; $this.showJoined = function (notice) { var msg = win.booktype.ui.getTemplate('joinMsg'); msg.find('.notice').html(win.booktype.utils.escapeJS(notice)); jquery('.content', $container).append(msg.clone()); scrollBottom(); }; $this.showInfo = function (notice) { var msg = win.booktype.ui.getTemplate('infoMsg'); if (typeof notice['message_id'] !== 'undefined') { msg.find('.notice').html($this.formatString(win.booktype._('message_info_' + notice['message_id'], ''), notice['message_args'])); } jquery('.content', $container).append(msg.clone()); scrollBottom(); }; $this.formatMessage = function (from, message) { return $('<p><b>' + from + '</b>: ' + win.booktype.utils.escapeJS(message) + '</p>'); }; $this.showMessage = function (from, message) { jquery('.content', $container).append($this.formatMessage(from, message)); scrollBottom(); }; jquery('FORM', $container).submit(function () { var msg = jquery.trim(jquery('INPUT[name=message]', $container).val()); if (msg !== '') { $this.showMessage(win.booktype.username, msg); jquery('INPUT', $container).val(''); win.booktype.sendToChannel('/chat/' + win.booktype.currentBookID + '/', { 'command': 'message_send', 'message': msg }, function () { } ); } return false; }); }; t2.onActivate = function () {}; t2.draw(); tabs.push(t2); } activateTabs(tabs); jquery(document).trigger('booktype-ui-finished'); }; var _loadInitialData = function () { win.booktype.ui.notify(win.booktype._('loading_data', 'Loading data.')); win.booktype.sendToCurrentBook({'command': 'init_editor'}, function (dta) { // Put this in the TOC data.chapters.clear(); data.chapters.loadFromArray(dta.chapters); data.holdChapters.clear(); data.holdChapters.loadFromArray(dta.hold); // Attachments are not really needed //attachments = dta.attachments; data.statuses = dta.statuses; // Initislize rest of the interface _initUI(); } ); }; var _reloadEditor = function () { var $d = jquery.Deferred(); win.booktype.ui.notify('Loading data.'); win.booktype.sendToCurrentBook({'command': 'init_editor'}, function (dta) { // Put this in the TOC data.chapters.clear(); data.chapters.loadFromArray(dta.chapters); data.holdChapters.clear(); data.holdChapters.loadFromArray(dta.hold); // Attachments are not really needed //attachments = dta.attachments; data.statuses = dta.statuses; // if activePanel == toc then redraw() if (win.booktype.editor.getActivePanel().name === 'toc') { win.booktype.editor.getActivePanel().redraw(); } else { Backbone.history.navigate('toc', true); } win.booktype.ui.notify(); $d.resolve(); } ); return $d.promise(); }; var _disableUnsaved = function () { jquery(win).bind('beforeunload', function (e) { // CHECK TO SEE IF WE ARE CURRENTLY EDITING SOMETHING return 'not saved'; }); }; var _fillSettings = function (sett, opts) { if (!_.isObject(opts)) { return opts; } _.each(_.pairs(opts), function (item) { var key = item[0], value = item[1]; if (_.isObject(value) && !_.isArray(value)) { if (_.isFunction(value)) { sett[key] = value; } else { sett[key] = _fillSettings(sett[key], value); } } else { sett[key] = value; } }); return sett; }; var _initEditor = function (settings) { // Settings data.settings = _fillSettings(_.clone(DEFAULTS), settings); // Initialize Panels data.panels = {}; _.each(settings.panels, function (pan, name) { data.panels[name] = eval(pan); }); jquery.each(data.panels, function (i, v) { v.init(); }); // initialize chapters data.chapters = new win.booktype.editor.toc.TOC(); data.holdChapters = new win.booktype.editor.toc.TOC(); //_disableUnsaved(); // Subscribe to the book channel win.booktype.subscribeToChannel('/booktype/book/' + win.booktype.currentBookID + '/' + win.booktype.currentVersion + '/', function (message) { var funcs = { 'user_status_changed': function () { jquery('#users .user' + message.from + ' SPAN').html(message.message); jquery('#users .user' + message.from).animate({backgroundColor: 'yellow'}, 'fast', function () { jquery(this).animate({backgroundColor: 'white'}, 3000); }); }, 'user_add': function () { jquery('#users').append('<li class="user' + message.username + '"><div style="width: 24px; height: 24px; float: left; margin-right: 5px;background-image: url(' + jquery.booki.profileThumbnailViewUrlTemplate.replace('XXX', message.username) + ');"></div><b>' + message.username + '</b><br/><span>' + message.mood + '</span></li>'); }, 'user_remove': function () { jquery('#users .user' + message.username).css('background-color', 'yellow').slideUp(1000, function () { jquery(this).remove(); }); } }; if (funcs[message.command]) { funcs[message.command](); } } ); // Do not subscribe to the chat channel if chat is not enabled win.booktype.subscribeToChannel('/chat/' + win.booktype.currentBookID + '/', function (message) { if (message.command === 'user_joined') { if (tabs[1]) { tabs[1].showJoined(message['user_joined']); } } if (message.command === 'message_info') { if (tabs[1]) { tabs[1].showInfo(message); } } if (message.command === 'message_received') { if (tabs[1]) { tabs[1].showMessage(message.from, message.message); } } } ); _loadInitialData(); jquery('#button-toc').parent().addClass('active'); }; var embedActiveStyle = function () { var styleURL = data.settings.styles[data.activeStyle]; jquery('#aloha-embeded-style').attr('href', styleURL); }; var setStyle = function (sid) { data.activeStyle = sid; embedActiveStyle(); jquery(document).trigger('booktype-style-changed', [sid]); }; var isEnabledTab = function (panelName, tabName) { return _.contains(data.settings.config[panelName]['tabs'], tabName); }; return { data: data, editChapter: function (id) { Backbone.history.navigate('edit/' + id, true); }, getCurrentChapterID: function () { return currentEdit; }, getChapterWithID: function (cid) { var d = data.chapters.getChapterWithID(cid); if (_.isUndefined(d)) { d = data.holdChapters.getChapterWithID(cid); } return d; }, setStyle: setStyle, embedActiveStyle: embedActiveStyle, isEnabledTab: isEnabledTab, initEditor: _initEditor, reloadEditor: _reloadEditor, getActivePanel: function () { if (data.activePanel) { return data.activePanel; } return {'name': 'unknown', 'hide': function (c) { c(); }}; }, hideAllTabs: hideAllTabs, activateTabs: activateTabs, deactivateTabs: deactivateTabs, createLeftTab: createLeftTab, createRightTab: createRightTab }; })(); })(window, jQuery, _);<|fim▁end|>
} else { // open but not active, switching content jquery(this).closest('ul').find('li').removeClass('active'); jquery(this).parent().toggleClass('active');
<|file_name|>normal.rs<|end_file_name|><|fim▁begin|>// Copyright 2013 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. //! The normal and derived distributions. use {Rng, Rand, Open01}; use distributions::{ziggurat, ziggurat_tables, Sample, IndependentSample}; /// A wrapper around an `f64` to generate N(0, 1) random numbers /// (a.k.a. a standard normal, or Gaussian). /// /// See `Normal` for the general normal distribution. /// /// Implemented via the ZIGNOR variant[1] of the Ziggurat method. /// /// [1]: Jurgen A. Doornik (2005). [*An Improved Ziggurat Method to /// Generate Normal Random /// Samples*](http://www.doornik.com/research/ziggurat.pdf). Nuffield /// College, Oxford /// /// # Example /// /// ```rust /// use rand::distributions::normal::StandardNormal; /// /// let StandardNormal(x) = rand::random(); /// println!("{}", x); /// ``` #[derive(Clone, Copy)] pub struct StandardNormal(pub f64); impl Rand for StandardNormal { fn rand<R:Rng>(rng: &mut R) -> StandardNormal { #[inline] fn pdf(x: f64) -> f64 { (-x*x/2.0).exp() } #[inline] fn zero_case<R:Rng>(rng: &mut R, u: f64) -> f64 { // compute a random number in the tail by hand // strange initial conditions, because the loop is not // do-while, so the condition should be true on the first // run, they get overwritten anyway (0 < 1, so these are // good). let mut x = 1.0f64; let mut y = 0.0f64; while -2.0 * y < x * x { let Open01(x_) = rng.gen::<Open01<f64>>(); let Open01(y_) = rng.gen::<Open01<f64>>(); x = x_.ln() / ziggurat_tables::ZIG_NORM_R; y = y_.ln(); } if u < 0.0 { x - ziggurat_tables::ZIG_NORM_R } else { ziggurat_tables::ZIG_NORM_R - x } } StandardNormal(ziggurat( rng, true, // this is symmetric &ziggurat_tables::ZIG_NORM_X, &ziggurat_tables::ZIG_NORM_F, pdf, zero_case)) } } /// The normal distribution `N(mean, std_dev**2)`. /// /// This uses the ZIGNOR variant of the Ziggurat method, see /// `StandardNormal` for more details. /// /// # Example /// /// ```rust /// use rand::distributions::{Normal, IndependentSample}; /// /// // mean 2, standard deviation 3 /// let normal = Normal::new(2.0, 3.0); /// let v = normal.ind_sample(&mut rand::thread_rng()); /// println!("{} is from a N(2, 9) distribution", v) /// ``` #[derive(Clone, Copy)] pub struct Normal { mean: f64, std_dev: f64, } impl Normal { /// Construct a new `Normal` distribution with the given mean and /// standard deviation. /// /// # Panics /// /// Panics if `std_dev < 0`.<|fim▁hole|> #[inline] pub fn new(mean: f64, std_dev: f64) -> Normal { assert!(std_dev >= 0.0, "Normal::new called with `std_dev` < 0"); Normal { mean: mean, std_dev: std_dev } } } impl Sample<f64> for Normal { fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } } impl IndependentSample<f64> for Normal { fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 { let StandardNormal(n) = rng.gen::<StandardNormal>(); self.mean + self.std_dev * n } } /// The log-normal distribution `ln N(mean, std_dev**2)`. /// /// If `X` is log-normal distributed, then `ln(X)` is `N(mean, /// std_dev**2)` distributed. /// /// # Example /// /// ```rust /// use rand::distributions::{LogNormal, IndependentSample}; /// /// // mean 2, standard deviation 3 /// let log_normal = LogNormal::new(2.0, 3.0); /// let v = log_normal.ind_sample(&mut rand::thread_rng()); /// println!("{} is from an ln N(2, 9) distribution", v) /// ``` #[derive(Clone, Copy)] pub struct LogNormal { norm: Normal } impl LogNormal { /// Construct a new `LogNormal` distribution with the given mean /// and standard deviation. /// /// # Panics /// /// Panics if `std_dev < 0`. #[inline] pub fn new(mean: f64, std_dev: f64) -> LogNormal { assert!(std_dev >= 0.0, "LogNormal::new called with `std_dev` < 0"); LogNormal { norm: Normal::new(mean, std_dev) } } } impl Sample<f64> for LogNormal { fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } } impl IndependentSample<f64> for LogNormal { fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 { self.norm.ind_sample(rng).exp() } } #[cfg(test)] mod tests { use distributions::{Sample, IndependentSample}; use super::{Normal, LogNormal}; #[test] fn test_normal() { let mut norm = Normal::new(10.0, 10.0); let mut rng = ::test::rng(); for _ in 0..1000 { norm.sample(&mut rng); norm.ind_sample(&mut rng); } } #[test] #[should_panic] fn test_normal_invalid_sd() { Normal::new(10.0, -1.0); } #[test] fn test_log_normal() { let mut lnorm = LogNormal::new(10.0, 10.0); let mut rng = ::test::rng(); for _ in 0..1000 { lnorm.sample(&mut rng); lnorm.ind_sample(&mut rng); } } #[test] #[should_panic] fn test_log_normal_invalid_sd() { LogNormal::new(10.0, -1.0); } }<|fim▁end|>
<|file_name|>no-use-before-define.js<|end_file_name|><|fim▁begin|>"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", { value: true }); const experimental_utils_1 = require("@typescript-eslint/experimental-utils"); const scope_manager_1 = require("@typescript-eslint/scope-manager"); const util = __importStar(require("../util")); const SENTINEL_TYPE = /^(?:(?:Function|Class)(?:Declaration|Expression)|ArrowFunctionExpression|CatchClause|ImportDeclaration|ExportNamedDeclaration)$/; /** * Parses a given value as options. */ function parseOptions(options) { let functions = true; let classes = true; let enums = true; let variables = true; let typedefs = true; let ignoreTypeReferences = true; if (typeof options === 'string') { functions = options !== 'nofunc'; } else if (typeof options === 'object' && options !== null) { functions = options.functions !== false; classes = options.classes !== false; enums = options.enums !== false; variables = options.variables !== false; typedefs = options.typedefs !== false; ignoreTypeReferences = options.ignoreTypeReferences !== false; } return { functions, classes, enums, variables, typedefs, ignoreTypeReferences, }; } /** * Checks whether or not a given variable is a function declaration. */ function isFunction(variable) { return variable.defs[0].type === scope_manager_1.DefinitionType.FunctionName; } /** * Checks whether or not a given variable is a type declaration. */ function isTypedef(variable) { return variable.defs[0].type === scope_manager_1.DefinitionType.Type; } /** * Checks whether or not a given variable is a enum declaration. */ function isOuterEnum(variable, reference) { return (variable.defs[0].type == scope_manager_1.DefinitionType.TSEnumName && variable.scope.variableScope !== reference.from.variableScope); } /** * Checks whether or not a given variable is a class declaration in an upper function scope. */ function isOuterClass(variable, reference) { return (variable.defs[0].type === scope_manager_1.DefinitionType.ClassName && variable.scope.variableScope !== reference.from.variableScope); } /** * Checks whether or not a given variable is a variable declaration in an upper function scope. */ function isOuterVariable(variable, reference) { return (variable.defs[0].type === scope_manager_1.DefinitionType.Variable && variable.scope.variableScope !== reference.from.variableScope); } /** * Recursively checks whether or not a given reference has a type query declaration among it's parents */ function referenceContainsTypeQuery(node) { switch (node.type) { case experimental_utils_1.AST_NODE_TYPES.TSTypeQuery: return true; case experimental_utils_1.AST_NODE_TYPES.TSQualifiedName: case experimental_utils_1.AST_NODE_TYPES.Identifier: if (!node.parent) { return false; } return referenceContainsTypeQuery(node.parent); default: // if we find a different node, there's no chance that we're in a TSTypeQuery return false; } } /** * Checks whether or not a given reference is a type reference. */ function isTypeReference(reference) { return (reference.isTypeReference || referenceContainsTypeQuery(reference.identifier)); } /** * Checks whether or not a given location is inside of the range of a given node. */ function isInRange(node, location) { return !!node && node.range[0] <= location && location <= node.range[1]; } /** * Decorators are transpiled such that the decorator is placed after the class declaration * So it is considered safe */ function isClassRefInClassDecorator(variable, reference) { if (variable.defs[0].type !== scope_manager_1.DefinitionType.ClassName) { return false; } if (!variable.defs[0].node.decorators || variable.defs[0].node.decorators.length === 0) { return false; } for (const deco of variable.defs[0].node.decorators) { if (reference.identifier.range[0] >= deco.range[0] && reference.identifier.range[1] <= deco.range[1]) { return true; } } return false; }<|fim▁hole|> * - var a = a * - var [a = a] = list * - var {a = a} = obj * - for (var a in a) {} * - for (var a of a) {} */ function isInInitializer(variable, reference) { var _a; if (variable.scope !== reference.from) { return false; } let node = variable.identifiers[0].parent; const location = reference.identifier.range[1]; while (node) { if (node.type === experimental_utils_1.AST_NODE_TYPES.VariableDeclarator) { if (isInRange(node.init, location)) { return true; } if (((_a = node.parent) === null || _a === void 0 ? void 0 : _a.parent) && (node.parent.parent.type === experimental_utils_1.AST_NODE_TYPES.ForInStatement || node.parent.parent.type === experimental_utils_1.AST_NODE_TYPES.ForOfStatement) && isInRange(node.parent.parent.right, location)) { return true; } break; } else if (node.type === experimental_utils_1.AST_NODE_TYPES.AssignmentPattern) { if (isInRange(node.right, location)) { return true; } } else if (SENTINEL_TYPE.test(node.type)) { break; } node = node.parent; } return false; } exports.default = util.createRule({ name: 'no-use-before-define', meta: { type: 'problem', docs: { description: 'Disallow the use of variables before they are defined', recommended: false, extendsBaseRule: true, }, messages: { noUseBeforeDefine: "'{{name}}' was used before it was defined.", }, schema: [ { oneOf: [ { enum: ['nofunc'], }, { type: 'object', properties: { functions: { type: 'boolean' }, classes: { type: 'boolean' }, enums: { type: 'boolean' }, variables: { type: 'boolean' }, typedefs: { type: 'boolean' }, ignoreTypeReferences: { type: 'boolean' }, }, additionalProperties: false, }, ], }, ], }, defaultOptions: [ { functions: true, classes: true, enums: true, variables: true, typedefs: true, ignoreTypeReferences: true, }, ], create(context, optionsWithDefault) { const options = parseOptions(optionsWithDefault[0]); /** * Determines whether a given use-before-define case should be reported according to the options. * @param variable The variable that gets used before being defined * @param reference The reference to the variable */ function isForbidden(variable, reference) { if (options.ignoreTypeReferences && isTypeReference(reference)) { return false; } if (isFunction(variable)) { return options.functions; } if (isOuterClass(variable, reference)) { return options.classes; } if (isOuterVariable(variable, reference)) { return options.variables; } if (isOuterEnum(variable, reference)) { return options.enums; } if (isTypedef(variable)) { return options.typedefs; } return true; } /** * Finds and validates all variables in a given scope. */ function findVariablesInScope(scope) { scope.references.forEach(reference => { const variable = reference.resolved; // Skips when the reference is: // - initializations. // - referring to an undefined variable. // - referring to a global environment variable (there're no identifiers). // - located preceded by the variable (except in initializers). // - allowed by options. if (reference.init || !variable || variable.identifiers.length === 0 || (variable.identifiers[0].range[1] <= reference.identifier.range[1] && !isInInitializer(variable, reference)) || !isForbidden(variable, reference) || isClassRefInClassDecorator(variable, reference) || reference.from.type === experimental_utils_1.TSESLint.Scope.ScopeType.functionType) { return; } // Reports. context.report({ node: reference.identifier, messageId: 'noUseBeforeDefine', data: { name: reference.identifier.name, }, }); }); scope.childScopes.forEach(findVariablesInScope); } return { Program() { findVariablesInScope(context.getScope()); }, }; }, }); //# sourceMappingURL=no-use-before-define.js.map<|fim▁end|>
/** * Checks whether or not a given reference is inside of the initializers of a given variable. * * @returns `true` in the following cases:
<|file_name|>path.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. // // 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. //! Cross-platform path manipulation. //! //! This module provides two types, `PathBuf` and `Path` (akin to `String` and //! `str`), for working with paths abstractly. These types are thin wrappers //! around `OsString` and `OsStr` respectively, meaning that they work directly //! on strings according to the local platform's path syntax. //! //! ## Simple usage //! //! Path manipulation involves both parsing components from slices and building //! new owned paths. //! //! To parse a path, you can create a `Path` slice from a `str` //! slice and start asking questions: //! //! ```rust //! use std::path::Path; //! //! let path = Path::new("/tmp/foo/bar.txt"); //! let file = path.file_name(); //! let extension = path.extension(); //! let parent_dir = path.parent(); //! ``` //! //! To build or modify paths, use `PathBuf`: //! //! ```rust //! use std::path::PathBuf; //! //! let mut path = PathBuf::new("c:\\"); //! path.push("windows"); //! path.push("system32"); //! path.set_extension("dll"); //! ``` //! //! ## Path components and normalization //! //! The path APIs are built around the notion of "components", which roughly //! correspond to the substrings between path separators (`/` and, on Windows, //! `\`). The APIs for path parsing are largely specified in terms of the path's //! components, so it's important to clearly understand how those are determined. //! //! A path can always be reconstructed into an equivalent path by putting //! together its components via `push`. Syntactically, the paths may differ by //! the normalization described below. //! //! ### Component types //! //! Components come in several types: //! //! * Normal components are the default: standard references to files or //! directories. The path `a/b` has two normal components, `a` and `b`. //! //! * Current directory components represent the `.` character. For example, //! `a/.` has a normal component `a` and a current directory component. //! //! * The root directory component represents a separator that designates //! starting from root. For example, `/a/b` has a root directory component //! followed by normal components `a` and `b`. //! //! On Windows, two additional component types come into play: //! //! * Prefix components, of which there is a large variety. For example, `C:` //! and `\\server\share` are prefixes. The path `C:windows` has a prefix //! component `C:` and a normal component `windows`; the path `C:\windows` has a //! prefix component `C:`, a root directory component, and a normal component //! `windows`. //! //! * Empty components, a special case for so-called "verbatim" paths where very //! little normalization is allowed. For example, `\\?\C:\` has a "verbatim" //! prefix `\\?\C:`, a root component, and an empty component (as a way of //! representing the trailing `\`. Such a trailing `\` is in fact the only //! situation in which an empty component is produced. //! //! ### Normalization //! //! Aside from splitting on the separator(s), there is a small amount of //! "normalization": //! //! * Repeated separators are ignored: `a/b` and `a//b` both have components `a` //! and `b`. //! //! * Paths ending in a separator are treated as if they has a current directory //! component at the end (or, in verbatim paths, an empty component). For //! example, while `a/b` has components `a` and `b`, the paths `a/b/` and //! `a/b/.` both have components `a`, `b`, and `.` (current directory). The //! reason for this normalization is that `a/b` and `a/b/` are treated //! differently in some contexts, but `a/b/` and `a/b/.` are always treated //! the same. //! //! No other normalization takes place by default. In particular, `a/./b/` and //! `a/b` are treated distinctly in terms of components, as are `a/c` and //! `a/b/../c`. Further normalization is possible to build on top of the //! components APIs, and will be included in this library very soon. #![unstable(feature = "path")] use core::prelude::*; use ascii::*; use borrow::BorrowFrom; use cmp; use iter; use mem; use ops::{self, Deref}; use string::CowString; use vec::Vec; use fmt; use ffi::{OsStr, OsString, AsOsStr}; use self::platform::{is_sep_byte, is_verbatim_sep, MAIN_SEP_STR, parse_prefix}; //////////////////////////////////////////////////////////////////////////////// // GENERAL NOTES //////////////////////////////////////////////////////////////////////////////// // // Parsing in this module is done by directly transmuting OsStr to [u8] slices, // taking advantage of the fact that OsStr always encodes ASCII characters // as-is. Eventually, this transmutation should be replaced by direct uses of // OsStr APIs for parsing, but it will take a while for those to become // available. //////////////////////////////////////////////////////////////////////////////// // Platform-specific definitions //////////////////////////////////////////////////////////////////////////////// // The following modules give the most basic tools for parsing paths on various // platforms. The bulk of the code is devoted to parsing prefixes on Windows. #[cfg(unix)] mod platform { use super::Prefix; use core::prelude::*; use ffi::OsStr; #[inline] pub fn is_sep_byte(b: u8) -> bool { b == b'/' } #[inline] pub fn is_verbatim_sep(b: u8) -> bool { b == b'/' } pub fn parse_prefix(_: &OsStr) -> Option<Prefix> { None } pub const MAIN_SEP_STR: &'static str = "/"; pub const MAIN_SEP: char = '/'; } #[cfg(windows)] mod platform { use core::prelude::*; use ascii::*; use char::CharExt as UnicodeCharExt; use super::{os_str_as_u8_slice, u8_slice_as_os_str, Prefix}; use ffi::OsStr; #[inline] pub fn is_sep_byte(b: u8) -> bool { b == b'/' || b == b'\\' } #[inline] pub fn is_verbatim_sep(b: u8) -> bool { b == b'\\' } pub fn parse_prefix<'a>(path: &'a OsStr) -> Option<Prefix> { use super::Prefix::*; unsafe { // The unsafety here stems from converting between &OsStr and &[u8] // and back. This is safe to do because (1) we only look at ASCII // contents of the encoding and (2) new &OsStr values are produced // only from ASCII-bounded slices of existing &OsStr values. let mut path = os_str_as_u8_slice(path); if path.starts_with(br"\\") { // \\ path = &path[2..]; if path.starts_with(br"?\") { // \\?\ path = &path[2..]; if path.starts_with(br"UNC\") { // \\?\UNC\server\share path = &path[4..]; let (server, share) = match parse_two_comps(path, is_verbatim_sep) { Some((server, share)) => (u8_slice_as_os_str(server), u8_slice_as_os_str(share)), None => (u8_slice_as_os_str(path), u8_slice_as_os_str(&[])), }; return Some(VerbatimUNC(server, share)); } else { // \\?\path let idx = path.position_elem(&b'\\'); if idx == Some(2) && path[1] == b':' { let c = path[0]; if c.is_ascii() && (c as char).is_alphabetic() { // \\?\C:\ path return Some(VerbatimDisk(c.to_ascii_uppercase())); } } let slice = &path[.. idx.unwrap_or(path.len())]; return Some(Verbatim(u8_slice_as_os_str(slice))); } } else if path.starts_with(b".\\") { // \\.\path path = &path[2..]; let slice = &path[.. path.position_elem(&b'\\').unwrap_or(path.len())]; return Some(DeviceNS(u8_slice_as_os_str(slice))); } match parse_two_comps(path, is_sep_byte) { Some((server, share)) if server.len() > 0 && share.len() > 0 => { // \\server\share return Some(UNC(u8_slice_as_os_str(server), u8_slice_as_os_str(share))); } _ => () } } else if path.len() > 1 && path[1] == b':' { // C: let c = path[0]; if c.is_ascii() && (c as char).is_alphabetic() { return Some(Disk(c.to_ascii_uppercase())); } } return None; } fn parse_two_comps(mut path: &[u8], f: fn(u8) -> bool) -> Option<(&[u8], &[u8])> { let first = match path.iter().position(|x| f(*x)) { None => return None, Some(x) => &path[.. x] }; path = &path[(first.len()+1)..]; let idx = path.iter().position(|x| f(*x)); let second = &path[.. idx.unwrap_or(path.len())]; Some((first, second)) } } pub const MAIN_SEP_STR: &'static str = "\\"; pub const MAIN_SEP: char = '\\'; } //////////////////////////////////////////////////////////////////////////////// // Windows Prefixes //////////////////////////////////////////////////////////////////////////////// /// Path prefixes (Windows only). /// /// Windows uses a variety of path styles, including references to drive /// volumes (like `C:`), network shared (like `\\server\share`) and /// others. In addition, some path prefixes are "verbatim", in which case /// `/` is *not* treated as a separator and essentially no normalization is /// performed. #[derive(Copy, Clone, Debug, Hash, PartialOrd, Ord, PartialEq, Eq)] pub enum Prefix<'a> { /// Prefix `\\?\`, together with the given component immediately following it. Verbatim(&'a OsStr), /// Prefix `\\?\UNC\`, with the "server" and "share" components following it. VerbatimUNC(&'a OsStr, &'a OsStr), /// Prefix like `\\?\C:\`, for the given drive letter VerbatimDisk(u8), /// Prefix `\\.\`, together with the given component immediately following it. DeviceNS(&'a OsStr), /// Prefix `\\server\share`, with the given "server" and "share" components. UNC(&'a OsStr, &'a OsStr), /// Prefix `C:` for the given disk drive. Disk(u8), } impl<'a> Prefix<'a> { #[inline] fn len(&self) -> usize { use self::Prefix::*; fn os_str_len(s: &OsStr) -> usize { os_str_as_u8_slice(s).len() } match *self { Verbatim(x) => 4 + os_str_len(x), VerbatimUNC(x,y) => 8 + os_str_len(x) + if os_str_len(y) > 0 { 1 + os_str_len(y) } else { 0 }, VerbatimDisk(_) => 6, UNC(x,y) => 2 + os_str_len(x) + if os_str_len(y) > 0 { 1 + os_str_len(y) } else { 0 }, DeviceNS(x) => 4 + os_str_len(x), Disk(_) => 2 } } /// Determine if the prefix is verbatim, i.e. begins `\\?\`. #[inline] pub fn is_verbatim(&self) -> bool { use self::Prefix::*; match *self { Verbatim(_) | VerbatimDisk(_) | VerbatimUNC(_, _) => true, _ => false } } #[inline] fn is_drive(&self) -> bool { match *self { Prefix::Disk(_) => true, _ => false, } } #[inline] fn has_implicit_root(&self) -> bool { !self.is_drive() } } //////////////////////////////////////////////////////////////////////////////// // Exposed parsing helpers //////////////////////////////////////////////////////////////////////////////// /// Determine whether the character is one of the permitted path /// separators for the current platform. pub fn is_separator(c: char) -> bool { use ascii::*; c.is_ascii() && is_sep_byte(c as u8) } /// The primary sperator for the current platform pub const MAIN_SEPARATOR: char = platform::MAIN_SEP; //////////////////////////////////////////////////////////////////////////////// // Misc helpers //////////////////////////////////////////////////////////////////////////////// // Iterate through `iter` while it matches `prefix`; return `None` if `prefix` // is not a prefix of `iter`, otherwise return `Some(iter_after_prefix)` giving // `iter` after having exhausted `prefix`. fn iter_after<A, I, J>(mut iter: I, mut prefix: J) -> Option<I> where I: Iterator<Item=A> + Clone, J: Iterator<Item=A>, A: PartialEq { loop { let mut iter_next = iter.clone(); match (iter_next.next(), prefix.next()) { (Some(x), Some(y)) => { if x != y { return None } } (Some(_), None) => return Some(iter), (None, None) => return Some(iter), (None, Some(_)) => return None, } iter = iter_next; } } // See note at the top of this module to understand why these are used: fn os_str_as_u8_slice(s: &OsStr) -> &[u8] { unsafe { mem::transmute(s) } } unsafe fn u8_slice_as_os_str(s: &[u8]) -> &OsStr { mem::transmute(s) } //////////////////////////////////////////////////////////////////////////////// // Cross-platform parsing //////////////////////////////////////////////////////////////////////////////// /// Says whether the path ends in a separator character and therefore needs to /// be treated as if it ended with an additional `.` fn has_suffix(s: &[u8], prefix: Option<Prefix>) -> bool { let (prefix_len, verbatim) = if let Some(p) = prefix { (p.len(), p.is_verbatim()) } else { (0, false) }; if prefix_len > 0 && prefix_len == s.len() && !verbatim { return true; } let mut splits = s[prefix_len..].split(|b| is_sep_byte(*b)); let last = splits.next_back().unwrap(); let more = splits.next_back().is_some(); more && last == b"" } /// Says whether the first byte after the prefix is a separator. fn has_physical_root(s: &[u8], prefix: Option<Prefix>) -> bool { let path = if let Some(p) = prefix { &s[p.len()..] } else { s }; path.len() > 0 && is_sep_byte(path[0]) } fn parse_single_component(comp: &[u8]) -> Option<Component> { match comp { b"." => Some(Component::CurDir), b".." => Some(Component::ParentDir), b"" => None, _ => Some(Component::Normal(unsafe { u8_slice_as_os_str(comp) })) } } // basic workhorse for splitting stem and extension #[allow(unused_unsafe)] // FIXME fn split_file_at_dot(file: &OsStr) -> (Option<&OsStr>, Option<&OsStr>) { unsafe { if os_str_as_u8_slice(file) == b".." { return (Some(file), None) } // The unsafety here stems from converting between &OsStr and &[u8] // and back. This is safe to do because (1) we only look at ASCII // contents of the encoding and (2) new &OsStr values are produced // only from ASCII-bounded slices of existing &OsStr values. let mut iter = os_str_as_u8_slice(file).rsplitn(1, |b| *b == b'.'); let after = iter.next(); let before = iter.next(); if before == Some(b"") { (Some(file), None) } else { (before.map(|s| u8_slice_as_os_str(s)), after.map(|s| u8_slice_as_os_str(s))) } } } //////////////////////////////////////////////////////////////////////////////// // The core iterators //////////////////////////////////////////////////////////////////////////////// /// Component parsing works by a double-ended state machine; the cursors at the /// front and back of the path each keep track of what parts of the path have /// been consumed so far. /// /// Going front to back, a path is made up of a prefix, a root component, a body /// (of normal components), and a suffix/emptycomponent (normalized `.` or `` /// for a path ending with the separator) #[derive(Copy, Clone, PartialEq, PartialOrd, Debug)] enum State { Prefix = 0, // c: Root = 1, // / Body = 2, // foo/bar/baz Suffix = 3, // . Done = 4, } /// A single component of a path. /// /// See the module documentation for an in-depth explanation of components and /// their role in the API. #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] pub enum Component<'a> { /// A Windows path prefix, e.g. `C:` or `\server\share`. /// /// Does not occur on Unix. Prefix { /// The prefix as an unparsed `OsStr` slice. raw: &'a OsStr, /// The parsed prefix data. parsed: Prefix<'a> }, /// An empty component. Only used on Windows for the last component of /// verbatim paths ending with a separator (e.g. the last component of /// `\\?\C:\windows\` but not `\\?\C:\windows` or `C:\windows`). Empty, /// The root directory component, appears after any prefix and before anything else RootDir, /// A reference to the current directory, i.e. `.` CurDir, /// A reference to the parent directory, i.e. `..` ParentDir, /// A normal component, i.e. `a` and `b` in `a/b` Normal(&'a OsStr), } impl<'a> Component<'a> { /// Extract the underlying `OsStr` slice pub fn as_os_str(self) -> &'a OsStr { match self { Component::Prefix { raw, .. } => &raw, Component::Empty => OsStr::from_str(""), Component::RootDir => OsStr::from_str(MAIN_SEP_STR), Component::CurDir => OsStr::from_str("."), Component::ParentDir => OsStr::from_str(".."), Component::Normal(path) => path, } } } /// The core iterator giving the components of a path. /// /// See the module documentation for an in-depth explanation of components and /// their role in the API. #[derive(Clone)] pub struct Components<'a> { // The path left to parse components from path: &'a [u8], // The prefix as it was originally parsed, if any prefix: Option<Prefix<'a>>, // true if path *physically* has a root separator; for most Windows // prefixes, it may have a "logical" rootseparator for the purposes of // normalization, e.g. \\server\share == \\server\share\. has_physical_root: bool, // The iterator is double-ended, and these two states keep track of what has // been produced from either end front: State, back: State, } /// An iterator over the components of a path, as `OsStr` slices. #[derive(Clone)] pub struct Iter<'a> { inner: Components<'a> } impl<'a> Components<'a> { // how long is the prefix, if any? #[inline] fn prefix_len(&self) -> usize { self.prefix.as_ref().map(Prefix::len).unwrap_or(0) } #[inline] fn prefix_verbatim(&self) -> bool { self.prefix.as_ref().map(Prefix::is_verbatim).unwrap_or(false) } /// how much of the prefix is left from the point of view of iteration? #[inline] fn prefix_remaining(&self) -> usize { if self.front == State::Prefix { self.prefix_len() } else { 0 } } fn prefix_and_root(&self) -> usize { let root = if self.front <= State::Root && self.has_physical_root { 1 } else { 0 }; self.prefix_remaining() + root } // is the iteration complete? #[inline] fn finished(&self) -> bool { self.front == State::Done || self.back == State::Done || self.front > self.back } #[inline] fn is_sep_byte(&self, b: u8) -> bool { if self.prefix_verbatim() { is_verbatim_sep(b) } else { is_sep_byte(b) } } /// Extract a slice corresponding to the portion of the path remaining for iteration. pub fn as_path(&self) -> &'a Path { let mut comps = self.clone(); if comps.front == State::Body { comps.trim_left(); } if comps.back == State::Body { comps.trim_right(); } if comps.path.is_empty() && comps.front < comps.back && comps.back == State::Suffix { Path::new(".") } else { unsafe { Path::from_u8_slice(comps.path) } } } /// Is the *original* path rooted? fn has_root(&self) -> bool { if self.has_physical_root { return true } if let Some(p) = self.prefix { if p.has_implicit_root() { return true } } false } // parse a component from the left, saying how many bytes to consume to // remove the component fn parse_next_component(&self) -> (usize, Option<Component<'a>>) { debug_assert!(self.front == State::Body); let (extra, comp) = match self.path.iter().position(|b| self.is_sep_byte(*b)) { None => (0, self.path), Some(i) => (1, &self.path[.. i]), }; (comp.len() + extra, parse_single_component(comp)) } // parse a component from the right, saying how many bytes to consume to // remove the component fn parse_next_component_back(&self) -> (usize, Option<Component<'a>>) { debug_assert!(self.back == State::Body); let start = self.prefix_and_root(); let (extra, comp) = match self.path[start..].iter().rposition(|b| self.is_sep_byte(*b)) { None => (0, &self.path[start ..]), Some(i) => (1, &self.path[start + i + 1 ..]), }; (comp.len() + extra, parse_single_component(comp)) } // trim away repeated separators (i.e. emtpy components) on the left fn trim_left(&mut self) { while !self.path.is_empty() { let (size, comp) = self.parse_next_component(); if comp.is_some() { return; } else { self.path = &self.path[size ..]; } } } // trim away repeated separators (i.e. emtpy components) on the right fn trim_right(&mut self) { while self.path.len() > self.prefix_and_root() { let (size, comp) = self.parse_next_component_back(); if comp.is_some() { return; } else { self.path = &self.path[.. self.path.len() - size]; } } } /// Examine the next component without consuming it. pub fn peek(&self) -> Option<Component<'a>> { self.clone().next() } } impl<'a> Iter<'a> { /// Extract a slice corresponding to the portion of the path remaining for iteration. pub fn as_path(&self) -> &'a Path { self.inner.as_path() } } impl<'a> Iterator for Iter<'a> { type Item = &'a OsStr; fn next(&mut self) -> Option<&'a OsStr> { self.inner.next().map(Component::as_os_str) } } impl<'a> DoubleEndedIterator for Iter<'a> { fn next_back(&mut self) -> Option<&'a OsStr> { self.inner.next_back().map(Component::as_os_str) } } impl<'a> Iterator for Components<'a> { type Item = Component<'a>; fn next(&mut self) -> Option<Component<'a>> { while !self.finished() { match self.front { State::Prefix if self.prefix_len() > 0 => { self.front = State::Root; debug_assert!(self.prefix_len() <= self.path.len()); let raw = &self.path[.. self.prefix_len()]; self.path = &self.path[self.prefix_len() .. ]; return Some(Component::Prefix { raw: unsafe { u8_slice_as_os_str(raw) }, parsed: self.prefix.unwrap() }) } State::Prefix => { self.front = State::Root; } State::Root => { self.front = State::Body; if self.has_physical_root { debug_assert!(self.path.len() > 0); self.path = &self.path[1..]; return Some(Component::RootDir) } else if let Some(p) = self.prefix { if p.has_implicit_root() && !p.is_verbatim() { return Some(Component::RootDir) } } } State::Body if !self.path.is_empty() => { let (size, comp) = self.parse_next_component(); self.path = &self.path[size ..]; if comp.is_some() { return comp } } State::Body => { self.front = State::Suffix; } State::Suffix => { self.front = State::Done; if self.prefix_verbatim() { return Some(Component::Empty) } else { return Some(Component::CurDir) } } State::Done => unreachable!() } } None } } impl<'a> DoubleEndedIterator for Components<'a> { fn next_back(&mut self) -> Option<Component<'a>> { while !self.finished() { match self.back { State::Suffix => { self.back = State::Body; if self.prefix_verbatim() { return Some(Component::Empty) } else { return Some(Component::CurDir) } } State::Body if self.path.len() > self.prefix_and_root() => { let (size, comp) = self.parse_next_component_back(); self.path = &self.path[.. self.path.len() - size]; if comp.is_some() { return comp } } State::Body => { self.back = State::Root; } State::Root => { self.back = State::Prefix; if self.has_physical_root { self.path = &self.path[.. self.path.len() - 1]; return Some(Component::RootDir) } else if let Some(p) = self.prefix { if p.has_implicit_root() && !p.is_verbatim() { return Some(Component::RootDir) } } } State::Prefix if self.prefix_len() > 0 => { self.back = State::Done; return Some(Component::Prefix { raw: unsafe { u8_slice_as_os_str(self.path) }, parsed: self.prefix.unwrap() }) } State::Prefix => { self.back = State::Done; return None } State::Done => unreachable!() } } None } } fn optional_path(path: &Path) -> Option<&Path> { if path.as_u8_slice().is_empty() { None } else { Some(path) } } impl<'a> cmp::PartialEq for Components<'a> { fn eq(&self, other: &Components<'a>) -> bool { iter::order::eq(self.clone(), other.clone()) } } impl<'a> cmp::Eq for Components<'a> {} impl<'a> cmp::PartialOrd for Components<'a> { fn partial_cmp(&self, other: &Components<'a>) -> Option<cmp::Ordering> { iter::order::partial_cmp(self.clone(), other.clone()) } } impl<'a> cmp::Ord for Components<'a> { fn cmp(&self, other: &Components<'a>) -> cmp::Ordering { iter::order::cmp(self.clone(), other.clone()) } } //////////////////////////////////////////////////////////////////////////////// // Basic types and traits //////////////////////////////////////////////////////////////////////////////// /// An owned, mutable path (akin to `String`). /// /// This type provides methods like `push` and `set_extension` that mutate the /// path in place. It also implements `Deref` to `Path`, meaning that all /// methods on `Path` slices are available on `PathBuf` values as well. /// /// More details about the overall approach can be found in /// the module documentation. /// /// # Example /// /// ```rust /// use std::path::PathBuf; /// /// let mut path = PathBuf::new("c:\\"); /// path.push("windows"); /// path.push("system32"); /// path.set_extension("dll"); /// ``` #[derive(Clone, Hash)] pub struct PathBuf { inner: OsString } impl PathBuf { fn as_mut_vec(&mut self) -> &mut Vec<u8> { unsafe { mem::transmute(self) } } /// Allocate a `PathBuf` with initial contents given by the /// argument. pub fn new<S: ?Sized + AsOsStr>(s: &S) -> PathBuf { PathBuf { inner: s.as_os_str().to_os_string() } } /// Extend `self` with `path`. /// /// If `path` is absolute, it replaces the current path. /// /// On Windows: /// /// * if `path` has a root but no prefix (e.g. `\windows`), it /// replaces everything except for the prefix (if any) of `self`. /// * if `path` has a prefix but no root, it replaces `self. pub fn push<P: ?Sized>(&mut self, path: &P) where P: AsPath { // in general, a separator is needed if the rightmost byte is not a separator let mut need_sep = self.as_mut_vec().last().map(|c| !is_sep_byte(*c)).unwrap_or(false); // in the special case of `C:` on Windows, do *not* add a separator { let comps = self.components(); if comps.prefix_len() > 0 && comps.prefix_len() == comps.path.len() && comps.prefix.unwrap().is_drive() { need_sep = false } } let path = path.as_path(); // absolute `path` replaces `self` if path.is_absolute() || path.prefix().is_some() { self.as_mut_vec().truncate(0); // `path` has a root but no prefix, e.g. `\windows` (Windows only) } else if path.has_root() { let prefix_len = self.components().prefix_remaining(); self.as_mut_vec().truncate(prefix_len); // `path` is a pure relative path } else if need_sep { self.inner.push_os_str(OsStr::from_str(MAIN_SEP_STR)); } self.inner.push_os_str(path.as_os_str()); } /// Truncate `self` to `self.parent()`. /// /// Returns `false` and does nothing if `self.parent()` is `None`. /// Otherwise, returns `true`. pub fn pop(&mut self) -> bool { match self.parent().map(|p| p.as_u8_slice().len()) { Some(len) => { self.as_mut_vec().truncate(len); true } None => false } } /// Updates `self.file_name()` to `file_name`. /// /// If `self.file_name()` was `None`, this is equivalent to pushing /// `file_name`. /// /// # Examples /// /// ```rust /// use std::path::{Path, PathBuf}; /// /// let mut buf = PathBuf::new("/foo/"); /// assert!(buf.file_name() == None); /// buf.set_file_name("bar"); /// assert!(buf == PathBuf::new("/foo/bar")); /// assert!(buf.file_name().is_some()); /// buf.set_file_name("baz.txt"); /// assert!(buf == PathBuf::new("/foo/baz.txt")); /// ``` pub fn set_file_name<S: ?Sized>(&mut self, file_name: &S) where S: AsOsStr { if self.file_name().is_some() && !self.pop() { // Given that there is a file name, this is reachable only for // Windows paths like c:file or paths like `foo`, but not `c:\` or // `/`. let prefix_len = self.components().prefix_remaining(); self.as_mut_vec().truncate(prefix_len); } self.push(file_name.as_os_str()); } /// Updates `self.extension()` to `extension`. /// /// If `self.file_name()` is `None`, does nothing and returns `false`. /// /// Otherwise, returns `true`; if `self.extension()` is `None`, the extension /// is added; otherwise it is replaced. pub fn set_extension<S: ?Sized + AsOsStr>(&mut self, extension: &S) -> bool { if self.file_name().is_none() { return false; } let mut stem = match self.file_stem() { Some(stem) => stem.to_os_string(), None => OsString::from_str(""), }; let extension = extension.as_os_str(); if os_str_as_u8_slice(extension).len() > 0 { stem.push_os_str(OsStr::from_str(".")); stem.push_os_str(extension.as_os_str()); } self.set_file_name(&stem); true } /// Consume the `PathBuf`, yielding its internal `OsString` storage pub fn into_os_string(self) -> OsString { self.inner } } impl<'a, P: ?Sized + 'a> iter::FromIterator<&'a P> for PathBuf where P: AsPath { fn from_iter<I: Iterator<Item = &'a P>>(iter: I) -> PathBuf { let mut buf = PathBuf::new(""); buf.extend(iter); buf } } impl<'a, P: ?Sized + 'a> iter::Extend<&'a P> for PathBuf where P: AsPath { fn extend<I: Iterator<Item = &'a P>>(&mut self, iter: I) { for p in iter { self.push(p) } } } impl fmt::Debug for PathBuf { fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { fmt::Debug::fmt(&**self, formatter) } } impl ops::Deref for PathBuf { type Target = Path; fn deref(&self) -> &Path { unsafe { mem::transmute(&self.inner[]) } } } impl BorrowFrom<PathBuf> for Path { fn borrow_from(owned: &PathBuf) -> &Path { owned.deref() } } impl cmp::PartialEq for PathBuf { fn eq(&self, other: &PathBuf) -> bool { self.components() == other.components() } } impl cmp::Eq for PathBuf {} impl cmp::PartialOrd for PathBuf { fn partial_cmp(&self, other: &PathBuf) -> Option<cmp::Ordering> { self.components().partial_cmp(&other.components()) } } impl cmp::Ord for PathBuf { fn cmp(&self, other: &PathBuf) -> cmp::Ordering { self.components().cmp(&other.components()) } } impl AsOsStr for PathBuf { fn as_os_str(&self) -> &OsStr { &self.inner[] } } /// A slice of a path (akin to `str`). /// /// This type supports a number of operations for inspecting a path, including /// breaking the path into its components (separated by `/` or `\`, depending on /// the platform), extracting the file name, determining whether the path is /// absolute, and so on. More details about the overall approach can be found in /// the module documentation. /// /// This is an *unsized* type, meaning that it must always be used with behind a /// pointer like `&` or `Box`. /// /// # Example /// /// ```rust /// use std::path::Path; /// /// let path = Path::new("/tmp/foo/bar.txt"); /// let file = path.file_name(); /// let extension = path.extension(); /// let parent_dir = path.parent(); /// ``` /// #[derive(Hash)] pub struct Path { inner: OsStr } impl Path { // The following (private!) function allows construction of a path from a u8 // slice, which is only safe when it is known to follow the OsStr encoding. unsafe fn from_u8_slice(s: &[u8]) -> &Path { mem::transmute(s) } // The following (private!) function reveals the byte encoding used for OsStr. fn as_u8_slice(&self) -> &[u8] { unsafe { mem::transmute(self) } } /// Directly wrap a string slice as a `Path` slice. /// /// This is a cost-free conversion. pub fn new<S: ?Sized + AsOsStr>(s: &S) -> &Path { unsafe { mem::transmute(s.as_os_str()) } } /// Yield a `&str` slice if the `Path` is valid unicode. /// /// This conversion may entail doing a check for UTF-8 validity. pub fn to_str(&self) -> Option<&str> { self.inner.to_str() } /// Convert a `Path` to a `CowString`. /// /// Any non-Unicode sequences are replaced with U+FFFD REPLACEMENT CHARACTER. pub fn to_string_lossy(&self) -> CowString { self.inner.to_string_lossy() } /// Convert a `Path` to an owned `PathBuf`. pub fn to_path_buf(&self) -> PathBuf { PathBuf::new(self) } /// A path is *absolute* if it is independent of the current directory. /// /// * On Unix, a path is absolute if it starts with the root, so /// `is_absolute` and `has_root` are equivalent. /// /// * On Windows, a path is absolute if it has a prefix and starts with the /// root: `c:\windows` is absolute, while `c:temp` and `\temp` are not. In /// other words, `path.is_absolute() == path.prefix().is_some() && path.has_root()`. pub fn is_absolute(&self) -> bool { self.has_root() && (cfg!(unix) || self.prefix().is_some()) } /// A path is *relative* if it is not absolute. pub fn is_relative(&self) -> bool { !self.is_absolute() } /// Returns the *prefix* of a path, if any. /// /// Prefixes are relevant only for Windows paths, and consist of volumes /// like `C:`, UNC prefixes like `\\server`, and others described in more /// detail in `std::os::windows::PathExt`. pub fn prefix(&self) -> Option<&Path> { let iter = self.components(); optional_path(unsafe { Path::from_u8_slice( &self.as_u8_slice()[.. iter.prefix_remaining()]) }) } /// A path has a root if the body of the path begins with the directory separator. /// /// * On Unix, a path has a root if it begins with `/`. /// /// * On Windows, a path has a root if it: /// * has no prefix and begins with a separator, e.g. `\\windows` /// * has a prefix followed by a separator, e.g. `c:\windows` but not `c:windows` /// * has any non-disk prefix, e.g. `\\server\share` pub fn has_root(&self) -> bool { self.components().has_root() } /// The path without its final component. /// /// Does nothing, returning `None` if the path consists of just a prefix /// and/or root directory reference. /// /// # Examples /// /// ```rust /// use std::path::Path; /// /// let path = Path::new("/foo/bar"); /// let foo = path.parent().unwrap(); /// assert!(foo == Path::new("/foo")); /// let root = foo.parent().unwrap(); /// assert!(root == Path::new("/")); /// assert!(root.parent() == None); /// ``` pub fn parent(&self) -> Option<&Path> { let mut comps = self.components(); let comp = comps.next_back(); let rest = optional_path(comps.as_path()); match (comp, comps.next_back()) { (Some(Component::CurDir), Some(Component::RootDir)) => None, (Some(Component::CurDir), Some(Component::Prefix { .. })) => None, (Some(Component::Empty), Some(Component::RootDir)) => None, (Some(Component::Empty), Some(Component::Prefix { .. })) => None, (Some(Component::Prefix { .. }), None) => None, (Some(Component::RootDir), Some(Component::Prefix { .. })) => None, _ => rest } } /// The final component of the path, if it is a normal file. /// /// If the path terminates in `.`, `..`, or consists solely or a root of /// prefix, `file` will return `None`. pub fn file_name(&self) -> Option<&OsStr> { self.components().next_back().and_then(|p| match p { Component::Normal(p) => Some(p.as_os_str()), _ => None }) } /// Returns a path that, when joined onto `base`, yields `self`. pub fn relative_from<'a, P: ?Sized>(&'a self, base: &'a P) -> Option<&Path> where P: AsPath { iter_after(self.components(), base.as_path().components()).map(|c| c.as_path()) } /// Determines whether `base` is a prefix of `self`. pub fn starts_with<P: ?Sized>(&self, base: &P) -> bool where P: AsPath { iter_after(self.components(), base.as_path().components()).is_some() } /// Determines whether `base` is a suffix of `self`. pub fn ends_with<P: ?Sized>(&self, child: &P) -> bool where P: AsPath { iter_after(self.components().rev(), child.as_path().components().rev()).is_some() } /// Extract the stem (non-extension) portion of `self.file()`. /// /// The stem is: /// /// * None, if there is no file name; /// * The entire file name if there is no embedded `.`; /// * The entire file name if the file name begins with `.` and has no other `.`s within; /// * Otherwise, the portion of the file name before the final `.` pub fn file_stem(&self) -> Option<&OsStr> { self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.or(after)) } /// Extract the extension of `self.file()`, if possible. /// /// The extension is: /// /// * None, if there is no file name; /// * None, if there is no embedded `.`; /// * None, if the file name begins with `.` and has no other `.`s within; /// * Otherwise, the portion of the file name after the final `.` pub fn extension(&self) -> Option<&OsStr> { self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.and(after)) } /// Creates an owned `PathBuf` with `path` adjoined to `self`. /// /// See `PathBuf::push` for more details on what it means to adjoin a path. pub fn join<P: ?Sized>(&self, path: &P) -> PathBuf where P: AsPath { let mut buf = self.to_path_buf(); buf.push(path); buf } /// Creates an owned `PathBuf` like `self` but with the given file name. /// /// See `PathBuf::set_file_name` for more details. pub fn with_file_name<S: ?Sized>(&self, file_name: &S) -> PathBuf where S: AsOsStr { let mut buf = self.to_path_buf(); buf.set_file_name(file_name); buf } /// Creates an owned `PathBuf` like `self` but with the given extension. /// /// See `PathBuf::set_extension` for more details. pub fn with_extension<S: ?Sized>(&self, extension: &S) -> PathBuf where S: AsOsStr { let mut buf = self.to_path_buf(); buf.set_extension(extension); buf } /// Produce an iterator over the components of the path. pub fn components(&self) -> Components { let prefix = parse_prefix(self.as_os_str()); Components { path: self.as_u8_slice(), prefix: prefix, has_physical_root: has_physical_root(self.as_u8_slice(), prefix), front: State::Prefix, back: if has_suffix(self.as_u8_slice(), prefix) { State::Suffix } else { State::Body }, } } /// Produce an iterator over the path's components viewed as `OsStr` slices. pub fn iter(&self) -> Iter { Iter { inner: self.components() } } /// Returns an object that implements `Display` for safely printing paths /// that may contain non-Unicode data. pub fn display(&self) -> Display { Display { path: self } } } impl AsOsStr for Path { fn as_os_str(&self) -> &OsStr { &self.inner } } impl fmt::Debug for Path { fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { self.inner.fmt(formatter) } } /// Helper struct for safely printing paths with `format!()` and `{}` pub struct Display<'a> { path: &'a Path } impl<'a> fmt::Debug for Display<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(&self.path.to_string_lossy(), f) } } impl<'a> fmt::Display for Display<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&self.path.to_string_lossy(), f) } } impl cmp::PartialEq for Path { fn eq(&self, other: &Path) -> bool { iter::order::eq(self.components(), other.components()) } } impl cmp::Eq for Path {} impl cmp::PartialOrd for Path { fn partial_cmp(&self, other: &Path) -> Option<cmp::Ordering> { self.components().partial_cmp(&other.components()) } } impl cmp::Ord for Path { fn cmp(&self, other: &Path) -> cmp::Ordering { self.components().cmp(&other.components()) } } /// Freely convertible to a `Path`. pub trait AsPath { /// Convert to a `Path`. fn as_path(&self) -> &Path; } impl<T: AsOsStr + ?Sized> AsPath for T { fn as_path(&self) -> &Path { Path::new(self.as_os_str()) } } #[cfg(test)] mod tests { use super::*; use ffi::OsStr; use core::prelude::*; use string::{ToString, String}; use vec::Vec; macro_rules! t( ($path:expr, iter: $iter:expr) => ( { let path = Path::new($path); // Forward iteration let comps = path.iter() .map(|p| p.to_string_lossy().into_owned()) .collect::<Vec<String>>(); let exp: &[&str] = &$iter; let exps = exp.iter().map(|s| s.to_string()).collect::<Vec<String>>(); assert!(comps == exps, "iter: Expected {:?}, found {:?}", exps, comps); // Reverse iteration let comps = Path::new($path).iter().rev() .map(|p| p.to_string_lossy().into_owned()) .collect::<Vec<String>>(); let exps = exps.into_iter().rev().collect::<Vec<String>>(); assert!(comps == exps, "iter().rev(): Expected {:?}, found {:?}", exps, comps); } ); ($path:expr, has_root: $has_root:expr, is_absolute: $is_absolute:expr) => ( { let path = Path::new($path); let act_root = path.has_root(); assert!(act_root == $has_root, "has_root: Expected {:?}, found {:?}", $has_root, act_root); let act_abs = path.is_absolute(); assert!(act_abs == $is_absolute, "is_absolute: Expected {:?}, found {:?}", $is_absolute, act_abs); } ); ($path:expr, parent: $parent:expr, file_name: $file:expr) => ( { let path = Path::new($path); let parent = path.parent().map(|p| p.to_str().unwrap()); let exp_parent: Option<&str> = $parent; assert!(parent == exp_parent, "parent: Expected {:?}, found {:?}", exp_parent, parent); let file = path.file_name().map(|p| p.to_str().unwrap()); let exp_file: Option<&str> = $file; assert!(file == exp_file, "file_name: Expected {:?}, found {:?}", exp_file, file); } ); ($path:expr, file_stem: $file_stem:expr, extension: $extension:expr) => ( { let path = Path::new($path); let stem = path.file_stem().map(|p| p.to_str().unwrap()); let exp_stem: Option<&str> = $file_stem; assert!(stem == exp_stem, "file_stem: Expected {:?}, found {:?}", exp_stem, stem); let ext = path.extension().map(|p| p.to_str().unwrap()); let exp_ext: Option<&str> = $extension; assert!(ext == exp_ext, "extension: Expected {:?}, found {:?}", exp_ext, ext); } ); ($path:expr, iter: $iter:expr, has_root: $has_root:expr, is_absolute: $is_absolute:expr, parent: $parent:expr, file_name: $file:expr, file_stem: $file_stem:expr, extension: $extension:expr) => ( { t!($path, iter: $iter); t!($path, has_root: $has_root, is_absolute: $is_absolute); t!($path, parent: $parent, file_name: $file); t!($path, file_stem: $file_stem, extension: $extension); } ); ); #[test] #[cfg(unix)] pub fn test_decompositions_unix() { t!("", iter: [], has_root: false, is_absolute: false, parent: None, file_name: None, file_stem: None, extension: None ); t!("foo", iter: ["foo"], has_root: false, is_absolute: false, parent: None, file_name: Some("foo"), file_stem: Some("foo"), extension: None ); t!("/", iter: ["/", "."], has_root: true, is_absolute: true, parent: None, file_name: None, file_stem: None, extension: None ); t!("/foo", iter: ["/", "foo"], has_root: true, is_absolute: true, parent: Some("/"), file_name: Some("foo"), file_stem: Some("foo"), extension: None ); t!("foo/", iter: ["foo", "."], has_root: false, is_absolute: false, parent: Some("foo"), file_name: None, file_stem: None, extension: None ); t!("/foo/", iter: ["/", "foo", "."], has_root: true, is_absolute: true, parent: Some("/foo"), file_name: None, file_stem: None, extension: None ); t!("foo/bar", iter: ["foo", "bar"], has_root: false, is_absolute: false, parent: Some("foo"), file_name: Some("bar"), file_stem: Some("bar"),<|fim▁hole|> t!("/foo/bar", iter: ["/", "foo", "bar"], has_root: true, is_absolute: true, parent: Some("/foo"), file_name: Some("bar"), file_stem: Some("bar"), extension: None ); t!("///foo///", iter: ["/", "foo", "."], has_root: true, is_absolute: true, parent: Some("///foo"), file_name: None, file_stem: None, extension: None ); t!("///foo///bar", iter: ["/", "foo", "bar"], has_root: true, is_absolute: true, parent: Some("///foo"), file_name: Some("bar"), file_stem: Some("bar"), extension: None ); t!("./.", iter: [".", "."], has_root: false, is_absolute: false, parent: Some("."), file_name: None, file_stem: None, extension: None ); t!("./.", iter: [".", "."], has_root: false, is_absolute: false, parent: Some("."), file_name: None, file_stem: None, extension: None ); t!("/..", iter: ["/", ".."], has_root: true, is_absolute: true, parent: Some("/"), file_name: None, file_stem: None, extension: None ); t!("../", iter: ["..", "."], has_root: false, is_absolute: false, parent: Some(".."), file_name: None, file_stem: None, extension: None ); t!("foo/.", iter: ["foo", "."], has_root: false, is_absolute: false, parent: Some("foo"), file_name: None, file_stem: None, extension: None ); t!("foo/..", iter: ["foo", ".."], has_root: false, is_absolute: false, parent: Some("foo"), file_name: None, file_stem: None, extension: None ); t!("foo/./", iter: ["foo", ".", "."], has_root: false, is_absolute: false, parent: Some("foo/."), file_name: None, file_stem: None, extension: None ); t!("foo/./bar", iter: ["foo", ".", "bar"], has_root: false, is_absolute: false, parent: Some("foo/."), file_name: Some("bar"), file_stem: Some("bar"), extension: None ); t!("foo/../", iter: ["foo", "..", "."], has_root: false, is_absolute: false, parent: Some("foo/.."), file_name: None, file_stem: None, extension: None ); t!("foo/../bar", iter: ["foo", "..", "bar"], has_root: false, is_absolute: false, parent: Some("foo/.."), file_name: Some("bar"), file_stem: Some("bar"), extension: None ); t!("./a", iter: [".", "a"], has_root: false, is_absolute: false, parent: Some("."), file_name: Some("a"), file_stem: Some("a"), extension: None ); t!(".", iter: ["."], has_root: false, is_absolute: false, parent: None, file_name: None, file_stem: None, extension: None ); t!("./", iter: [".", "."], has_root: false, is_absolute: false, parent: Some("."), file_name: None, file_stem: None, extension: None ); t!("a/b", iter: ["a", "b"], has_root: false, is_absolute: false, parent: Some("a"), file_name: Some("b"), file_stem: Some("b"), extension: None ); t!("a//b", iter: ["a", "b"], has_root: false, is_absolute: false, parent: Some("a"), file_name: Some("b"), file_stem: Some("b"), extension: None ); t!("a/./b", iter: ["a", ".", "b"], has_root: false, is_absolute: false, parent: Some("a/."), file_name: Some("b"), file_stem: Some("b"), extension: None ); t!("a/b/c", iter: ["a", "b", "c"], has_root: false, is_absolute: false, parent: Some("a/b"), file_name: Some("c"), file_stem: Some("c"), extension: None ); } #[test] #[cfg(windows)] pub fn test_decompositions_windows() { t!("", iter: [], has_root: false, is_absolute: false, parent: None, file_name: None, file_stem: None, extension: None ); t!("foo", iter: ["foo"], has_root: false, is_absolute: false, parent: None, file_name: Some("foo"), file_stem: Some("foo"), extension: None ); t!("/", iter: ["\\", "."], has_root: true, is_absolute: false, parent: None, file_name: None, file_stem: None, extension: None ); t!("\\", iter: ["\\", "."], has_root: true, is_absolute: false, parent: None, file_name: None, file_stem: None, extension: None ); t!("c:", iter: ["c:", "."], has_root: false, is_absolute: false, parent: None, file_name: None, file_stem: None, extension: None ); t!("c:\\", iter: ["c:", "\\", "."], has_root: true, is_absolute: true, parent: None, file_name: None, file_stem: None, extension: None ); t!("c:\\", iter: ["c:", "\\", "."], has_root: true, is_absolute: true, parent: None, file_name: None, file_stem: None, extension: None ); t!("c:/", iter: ["c:", "\\", "."], has_root: true, is_absolute: true, parent: None, file_name: None, file_stem: None, extension: None ); t!("/foo", iter: ["\\", "foo"], has_root: true, is_absolute: false, parent: Some("/"), file_name: Some("foo"), file_stem: Some("foo"), extension: None ); t!("foo/", iter: ["foo", "."], has_root: false, is_absolute: false, parent: Some("foo"), file_name: None, file_stem: None, extension: None ); t!("/foo/", iter: ["\\", "foo", "."], has_root: true, is_absolute: false, parent: Some("/foo"), file_name: None, file_stem: None, extension: None ); t!("foo/bar", iter: ["foo", "bar"], has_root: false, is_absolute: false, parent: Some("foo"), file_name: Some("bar"), file_stem: Some("bar"), extension: None ); t!("/foo/bar", iter: ["\\", "foo", "bar"], has_root: true, is_absolute: false, parent: Some("/foo"), file_name: Some("bar"), file_stem: Some("bar"), extension: None ); t!("///foo///", iter: ["\\", "foo", "."], has_root: true, is_absolute: false, parent: Some("///foo"), file_name: None, file_stem: None, extension: None ); t!("///foo///bar", iter: ["\\", "foo", "bar"], has_root: true, is_absolute: false, parent: Some("///foo"), file_name: Some("bar"), file_stem: Some("bar"), extension: None ); t!("./.", iter: [".", "."], has_root: false, is_absolute: false, parent: Some("."), file_name: None, file_stem: None, extension: None ); t!("./.", iter: [".", "."], has_root: false, is_absolute: false, parent: Some("."), file_name: None, file_stem: None, extension: None ); t!("/..", iter: ["\\", ".."], has_root: true, is_absolute: false, parent: Some("/"), file_name: None, file_stem: None, extension: None ); t!("../", iter: ["..", "."], has_root: false, is_absolute: false, parent: Some(".."), file_name: None, file_stem: None, extension: None ); t!("foo/.", iter: ["foo", "."], has_root: false, is_absolute: false, parent: Some("foo"), file_name: None, file_stem: None, extension: None ); t!("foo/..", iter: ["foo", ".."], has_root: false, is_absolute: false, parent: Some("foo"), file_name: None, file_stem: None, extension: None ); t!("foo/./", iter: ["foo", ".", "."], has_root: false, is_absolute: false, parent: Some("foo/."), file_name: None, file_stem: None, extension: None ); t!("foo/./bar", iter: ["foo", ".", "bar"], has_root: false, is_absolute: false, parent: Some("foo/."), file_name: Some("bar"), file_stem: Some("bar"), extension: None ); t!("foo/../", iter: ["foo", "..", "."], has_root: false, is_absolute: false, parent: Some("foo/.."), file_name: None, file_stem: None, extension: None ); t!("foo/../bar", iter: ["foo", "..", "bar"], has_root: false, is_absolute: false, parent: Some("foo/.."), file_name: Some("bar"), file_stem: Some("bar"), extension: None ); t!("./a", iter: [".", "a"], has_root: false, is_absolute: false, parent: Some("."), file_name: Some("a"), file_stem: Some("a"), extension: None ); t!(".", iter: ["."], has_root: false, is_absolute: false, parent: None, file_name: None, file_stem: None, extension: None ); t!("./", iter: [".", "."], has_root: false, is_absolute: false, parent: Some("."), file_name: None, file_stem: None, extension: None ); t!("a/b", iter: ["a", "b"], has_root: false, is_absolute: false, parent: Some("a"), file_name: Some("b"), file_stem: Some("b"), extension: None ); t!("a//b", iter: ["a", "b"], has_root: false, is_absolute: false, parent: Some("a"), file_name: Some("b"), file_stem: Some("b"), extension: None ); t!("a/./b", iter: ["a", ".", "b"], has_root: false, is_absolute: false, parent: Some("a/."), file_name: Some("b"), file_stem: Some("b"), extension: None ); t!("a/b/c", iter: ["a", "b", "c"], has_root: false, is_absolute: false, parent: Some("a/b"), file_name: Some("c"), file_stem: Some("c"), extension: None); t!("a\\b\\c", iter: ["a", "b", "c"], has_root: false, is_absolute: false, parent: Some("a\\b"), file_name: Some("c"), file_stem: Some("c"), extension: None ); t!("\\a", iter: ["\\", "a"], has_root: true, is_absolute: false, parent: Some("\\"), file_name: Some("a"), file_stem: Some("a"), extension: None ); t!("c:\\foo.txt", iter: ["c:", "\\", "foo.txt"], has_root: true, is_absolute: true, parent: Some("c:\\"), file_name: Some("foo.txt"), file_stem: Some("foo"), extension: Some("txt") ); t!("\\\\server\\share\\foo.txt", iter: ["\\\\server\\share", "\\", "foo.txt"], has_root: true, is_absolute: true, parent: Some("\\\\server\\share\\"), file_name: Some("foo.txt"), file_stem: Some("foo"), extension: Some("txt") ); t!("\\\\server\\share", iter: ["\\\\server\\share", "\\", "."], has_root: true, is_absolute: true, parent: None, file_name: None, file_stem: None, extension: None ); t!("\\\\server", iter: ["\\", "server"], has_root: true, is_absolute: false, parent: Some("\\"), file_name: Some("server"), file_stem: Some("server"), extension: None ); t!("\\\\?\\bar\\foo.txt", iter: ["\\\\?\\bar", "\\", "foo.txt"], has_root: true, is_absolute: true, parent: Some("\\\\?\\bar\\"), file_name: Some("foo.txt"), file_stem: Some("foo"), extension: Some("txt") ); t!("\\\\?\\bar", iter: ["\\\\?\\bar"], has_root: true, is_absolute: true, parent: None, file_name: None, file_stem: None, extension: None ); t!("\\\\?\\", iter: ["\\\\?\\"], has_root: true, is_absolute: true, parent: None, file_name: None, file_stem: None, extension: None ); t!("\\\\?\\UNC\\server\\share\\foo.txt", iter: ["\\\\?\\UNC\\server\\share", "\\", "foo.txt"], has_root: true, is_absolute: true, parent: Some("\\\\?\\UNC\\server\\share\\"), file_name: Some("foo.txt"), file_stem: Some("foo"), extension: Some("txt") ); t!("\\\\?\\UNC\\server", iter: ["\\\\?\\UNC\\server"], has_root: true, is_absolute: true, parent: None, file_name: None, file_stem: None, extension: None ); t!("\\\\?\\UNC\\", iter: ["\\\\?\\UNC\\"], has_root: true, is_absolute: true, parent: None, file_name: None, file_stem: None, extension: None ); t!("\\\\?\\C:\\foo.txt", iter: ["\\\\?\\C:", "\\", "foo.txt"], has_root: true, is_absolute: true, parent: Some("\\\\?\\C:\\"), file_name: Some("foo.txt"), file_stem: Some("foo"), extension: Some("txt") ); t!("\\\\?\\C:\\", iter: ["\\\\?\\C:", "\\", ""], has_root: true, is_absolute: true, parent: None, file_name: None, file_stem: None, extension: None ); t!("\\\\?\\C:", iter: ["\\\\?\\C:"], has_root: true, is_absolute: true, parent: None, file_name: None, file_stem: None, extension: None ); t!("\\\\?\\foo/bar", iter: ["\\\\?\\foo/bar"], has_root: true, is_absolute: true, parent: None, file_name: None, file_stem: None, extension: None ); t!("\\\\?\\C:/foo", iter: ["\\\\?\\C:/foo"], has_root: true, is_absolute: true, parent: None, file_name: None, file_stem: None, extension: None ); t!("\\\\.\\foo\\bar", iter: ["\\\\.\\foo", "\\", "bar"], has_root: true, is_absolute: true, parent: Some("\\\\.\\foo\\"), file_name: Some("bar"), file_stem: Some("bar"), extension: None ); t!("\\\\.\\foo", iter: ["\\\\.\\foo", "\\", "."], has_root: true, is_absolute: true, parent: None, file_name: None, file_stem: None, extension: None ); t!("\\\\.\\foo/bar", iter: ["\\\\.\\foo/bar", "\\", "."], has_root: true, is_absolute: true, parent: None, file_name: None, file_stem: None, extension: None ); t!("\\\\.\\foo\\bar/baz", iter: ["\\\\.\\foo", "\\", "bar", "baz"], has_root: true, is_absolute: true, parent: Some("\\\\.\\foo\\bar"), file_name: Some("baz"), file_stem: Some("baz"), extension: None ); t!("\\\\.\\", iter: ["\\\\.\\", "\\", "."], has_root: true, is_absolute: true, parent: None, file_name: None, file_stem: None, extension: None ); t!("\\\\?\\a\\b\\", iter: ["\\\\?\\a", "\\", "b", ""], has_root: true, is_absolute: true, parent: Some("\\\\?\\a\\b"), file_name: None, file_stem: None, extension: None ); } #[test] pub fn test_stem_ext() { t!("foo", file_stem: Some("foo"), extension: None ); t!("foo.", file_stem: Some("foo"), extension: Some("") ); t!(".foo", file_stem: Some(".foo"), extension: None ); t!("foo.txt", file_stem: Some("foo"), extension: Some("txt") ); t!("foo.bar.txt", file_stem: Some("foo.bar"), extension: Some("txt") ); t!("foo.bar.", file_stem: Some("foo.bar"), extension: Some("") ); t!(".", file_stem: None, extension: None ); t!("..", file_stem: None, extension: None ); t!("", file_stem: None, extension: None ); } #[test] pub fn test_push() { macro_rules! tp( ($path:expr, $push:expr, $expected:expr) => ( { let mut actual = PathBuf::new($path); actual.push($push); assert!(actual.to_str() == Some($expected), "pushing {:?} onto {:?}: Expected {:?}, got {:?}", $push, $path, $expected, actual.to_str().unwrap()); }); ); if cfg!(unix) { tp!("", "foo", "foo"); tp!("foo", "bar", "foo/bar"); tp!("foo/", "bar", "foo/bar"); tp!("foo//", "bar", "foo//bar"); tp!("foo/.", "bar", "foo/./bar"); tp!("foo./.", "bar", "foo././bar"); tp!("foo", "", "foo/"); tp!("foo", ".", "foo/."); tp!("foo", "..", "foo/.."); tp!("foo", "/", "/"); tp!("/foo/bar", "/", "/"); tp!("/foo/bar", "/baz", "/baz"); tp!("/foo/bar", "./baz", "/foo/bar/./baz"); } else { tp!("", "foo", "foo"); tp!("foo", "bar", r"foo\bar"); tp!("foo/", "bar", r"foo/bar"); tp!(r"foo\", "bar", r"foo\bar"); tp!("foo//", "bar", r"foo//bar"); tp!(r"foo\\", "bar", r"foo\\bar"); tp!("foo/.", "bar", r"foo/.\bar"); tp!("foo./.", "bar", r"foo./.\bar"); tp!(r"foo\.", "bar", r"foo\.\bar"); tp!(r"foo.\.", "bar", r"foo.\.\bar"); tp!("foo", "", "foo\\"); tp!("foo", ".", r"foo\."); tp!("foo", "..", r"foo\.."); tp!("foo", "/", "/"); tp!("foo", r"\", r"\"); tp!("/foo/bar", "/", "/"); tp!(r"\foo\bar", r"\", r"\"); tp!("/foo/bar", "/baz", "/baz"); tp!("/foo/bar", r"\baz", r"\baz"); tp!("/foo/bar", "./baz", r"/foo/bar\./baz"); tp!("/foo/bar", r".\baz", r"/foo/bar\.\baz"); tp!("c:\\", "windows", "c:\\windows"); tp!("c:", "windows", "c:windows"); tp!("a\\b\\c", "d", "a\\b\\c\\d"); tp!("\\a\\b\\c", "d", "\\a\\b\\c\\d"); tp!("a\\b", "c\\d", "a\\b\\c\\d"); tp!("a\\b", "\\c\\d", "\\c\\d"); tp!("a\\b", ".", "a\\b\\."); tp!("a\\b", "..\\c", "a\\b\\..\\c"); tp!("a\\b", "C:a.txt", "C:a.txt"); tp!("a\\b", "C:\\a.txt", "C:\\a.txt"); tp!("C:\\a", "C:\\b.txt", "C:\\b.txt"); tp!("C:\\a\\b\\c", "C:d", "C:d"); tp!("C:a\\b\\c", "C:d", "C:d"); tp!("C:", r"a\b\c", r"C:a\b\c"); tp!("C:", r"..\a", r"C:..\a"); tp!("\\\\server\\share\\foo", "bar", "\\\\server\\share\\foo\\bar"); tp!("\\\\server\\share\\foo", "C:baz", "C:baz"); tp!("\\\\?\\C:\\a\\b", "C:c\\d", "C:c\\d"); tp!("\\\\?\\C:a\\b", "C:c\\d", "C:c\\d"); tp!("\\\\?\\C:\\a\\b", "C:\\c\\d", "C:\\c\\d"); tp!("\\\\?\\foo\\bar", "baz", "\\\\?\\foo\\bar\\baz"); tp!("\\\\?\\UNC\\server\\share\\foo", "bar", "\\\\?\\UNC\\server\\share\\foo\\bar"); tp!("\\\\?\\UNC\\server\\share", "C:\\a", "C:\\a"); tp!("\\\\?\\UNC\\server\\share", "C:a", "C:a"); // Note: modified from old path API tp!("\\\\?\\UNC\\server", "foo", "\\\\?\\UNC\\server\\foo"); tp!("C:\\a", "\\\\?\\UNC\\server\\share", "\\\\?\\UNC\\server\\share"); tp!("\\\\.\\foo\\bar", "baz", "\\\\.\\foo\\bar\\baz"); tp!("\\\\.\\foo\\bar", "C:a", "C:a"); // again, not sure about the following, but I'm assuming \\.\ should be verbatim tp!("\\\\.\\foo", "..\\bar", "\\\\.\\foo\\..\\bar"); tp!("\\\\?\\C:", "foo", "\\\\?\\C:\\foo"); // this is a weird one } } #[test] pub fn test_pop() { macro_rules! tp( ($path:expr, $expected:expr, $output:expr) => ( { let mut actual = PathBuf::new($path); let output = actual.pop(); assert!(actual.to_str() == Some($expected) && output == $output, "popping from {:?}: Expected {:?}/{:?}, got {:?}/{:?}", $path, $expected, $output, actual.to_str().unwrap(), output); }); ); tp!("", "", false); tp!("/", "/", false); tp!("foo", "foo", false); tp!(".", ".", false); tp!("/foo", "/", true); tp!("/foo/bar", "/foo", true); tp!("foo/bar", "foo", true); tp!("foo/.", "foo", true); tp!("foo//bar", "foo", true); if cfg!(windows) { tp!("a\\b\\c", "a\\b", true); tp!("\\a", "\\", true); tp!("\\", "\\", false); tp!("C:\\a\\b", "C:\\a", true); tp!("C:\\a", "C:\\", true); tp!("C:\\", "C:\\", false); tp!("C:a\\b", "C:a", true); tp!("C:a", "C:", true); tp!("C:", "C:", false); tp!("\\\\server\\share\\a\\b", "\\\\server\\share\\a", true); tp!("\\\\server\\share\\a", "\\\\server\\share\\", true); tp!("\\\\server\\share", "\\\\server\\share", false); tp!("\\\\?\\a\\b\\c", "\\\\?\\a\\b", true); tp!("\\\\?\\a\\b", "\\\\?\\a\\", true); tp!("\\\\?\\a", "\\\\?\\a", false); tp!("\\\\?\\C:\\a\\b", "\\\\?\\C:\\a", true); tp!("\\\\?\\C:\\a", "\\\\?\\C:\\", true); tp!("\\\\?\\C:\\", "\\\\?\\C:\\", false); tp!("\\\\?\\UNC\\server\\share\\a\\b", "\\\\?\\UNC\\server\\share\\a", true); tp!("\\\\?\\UNC\\server\\share\\a", "\\\\?\\UNC\\server\\share\\", true); tp!("\\\\?\\UNC\\server\\share", "\\\\?\\UNC\\server\\share", false); tp!("\\\\.\\a\\b\\c", "\\\\.\\a\\b", true); tp!("\\\\.\\a\\b", "\\\\.\\a\\", true); tp!("\\\\.\\a", "\\\\.\\a", false); tp!("\\\\?\\a\\b\\", "\\\\?\\a\\b", true); } } #[test] pub fn test_set_file_name() { macro_rules! tfn( ($path:expr, $file:expr, $expected:expr) => ( { let mut p = PathBuf::new($path); p.set_file_name($file); assert!(p.to_str() == Some($expected), "setting file name of {:?} to {:?}: Expected {:?}, got {:?}", $path, $file, $expected, p.to_str().unwrap()); }); ); tfn!("foo", "foo", "foo"); tfn!("foo", "bar", "bar"); tfn!("foo", "", ""); tfn!("", "foo", "foo"); if cfg!(unix) { tfn!(".", "foo", "./foo"); tfn!("foo/", "bar", "foo/bar"); tfn!("foo/.", "bar", "foo/./bar"); tfn!("..", "foo", "../foo"); tfn!("foo/..", "bar", "foo/../bar"); tfn!("/", "foo", "/foo"); } else { tfn!(".", "foo", r".\foo"); tfn!(r"foo\", "bar", r"foo\bar"); tfn!(r"foo\.", "bar", r"foo\.\bar"); tfn!("..", "foo", r"..\foo"); tfn!(r"foo\..", "bar", r"foo\..\bar"); tfn!(r"\", "foo", r"\foo"); } } #[test] pub fn test_set_extension() { macro_rules! tfe( ($path:expr, $ext:expr, $expected:expr, $output:expr) => ( { let mut p = PathBuf::new($path); let output = p.set_extension($ext); assert!(p.to_str() == Some($expected) && output == $output, "setting extension of {:?} to {:?}: Expected {:?}/{:?}, got {:?}/{:?}", $path, $ext, $expected, $output, p.to_str().unwrap(), output); }); ); tfe!("foo", "txt", "foo.txt", true); tfe!("foo.bar", "txt", "foo.txt", true); tfe!("foo.bar.baz", "txt", "foo.bar.txt", true); tfe!(".test", "txt", ".test.txt", true); tfe!("foo.txt", "", "foo", true); tfe!("foo", "", "foo", true); tfe!("", "foo", "", false); tfe!(".", "foo", ".", false); tfe!("foo/", "bar", "foo/", false); tfe!("foo/.", "bar", "foo/.", false); tfe!("..", "foo", "..", false); tfe!("foo/..", "bar", "foo/..", false); tfe!("/", "foo", "/", false); } #[test] pub fn test_compare() { macro_rules! tc( ($path1:expr, $path2:expr, eq: $eq:expr, starts_with: $starts_with:expr, ends_with: $ends_with:expr, relative_from: $relative_from:expr) => ({ let path1 = Path::new($path1); let path2 = Path::new($path2); let eq = path1 == path2; assert!(eq == $eq, "{:?} == {:?}, expected {:?}, got {:?}", $path1, $path2, $eq, eq); let starts_with = path1.starts_with(path2); assert!(starts_with == $starts_with, "{:?}.starts_with({:?}), expected {:?}, got {:?}", $path1, $path2, $starts_with, starts_with); let ends_with = path1.ends_with(path2); assert!(ends_with == $ends_with, "{:?}.ends_with({:?}), expected {:?}, got {:?}", $path1, $path2, $ends_with, ends_with); let relative_from = path1.relative_from(path2).map(|p| p.to_str().unwrap()); let exp: Option<&str> = $relative_from; assert!(relative_from == exp, "{:?}.relative_from({:?}), expected {:?}, got {:?}", $path1, $path2, exp, relative_from); }); ); tc!("", "", eq: true, starts_with: true, ends_with: true, relative_from: Some("") ); tc!("foo", "", eq: false, starts_with: true, ends_with: true, relative_from: Some("foo") ); tc!("", "foo", eq: false, starts_with: false, ends_with: false, relative_from: None ); tc!("foo", "foo", eq: true, starts_with: true, ends_with: true, relative_from: Some("") ); tc!("foo/", "foo", eq: false, starts_with: true, ends_with: false, relative_from: Some(".") ); tc!("foo/bar", "foo", eq: false, starts_with: true, ends_with: false, relative_from: Some("bar") ); tc!("foo/bar/baz", "foo/bar", eq: false, starts_with: true, ends_with: false, relative_from: Some("baz") ); tc!("foo/bar", "foo/bar/baz", eq: false, starts_with: false, ends_with: false, relative_from: None ); tc!("./foo/bar/", ".", eq: false, starts_with: true, ends_with: true, relative_from: Some("foo/bar/") ); } }<|fim▁end|>
extension: None );
<|file_name|>usgs_eddn_test.py<|end_file_name|><|fim▁begin|>from datetime import datetime import pandas as pd from pandas.util.testing import assert_frame_equal import ulmo import ulmo.usgs.eddn.parsers as parsers import test_util fmt = '%y%j%H%M%S' message_test_sets = [ { 'dcp_address': 'C5149430', 'number_of_lines': 4, 'parser': 'twdb_stevens', 'first_row_message_timestamp_utc': datetime.strptime('13305152818', fmt), }, { 'dcp_address': 'C514D73A', 'number_of_lines': 4, 'parser': 'twdb_sutron', 'first_row_message_timestamp_utc': datetime.strptime('13305072816', fmt), }, { 'dcp_address': 'C516C1B8', 'number_of_lines': 28, 'parser': 'stevens', 'first_row_message_timestamp_utc': datetime.strptime('13305134352', fmt), } ] def test_parse_dcp_message_number_of_lines(): for test_set in message_test_sets: dcp_data_file = 'usgs/eddn/' + test_set['dcp_address'] + '.txt' with test_util.mocked_urls(dcp_data_file): data = ulmo.usgs.eddn.get_data(test_set['dcp_address']) assert len(data) == test_set['number_of_lines'] def test_parse_dcp_message_timestamp(): for test_set in message_test_sets: dcp_data_file = 'usgs/eddn/' + test_set['dcp_address'] + '.txt' with test_util.mocked_urls(dcp_data_file): data = ulmo.usgs.eddn.get_data(test_set['dcp_address']) assert data['message_timestamp_utc'][-1] == test_set['first_row_message_timestamp_utc'] multi_message_test_sets = [ { 'dcp_address': 'C5149430', 'data_files': { '.*DRS_UNTIL=now.*':'usgs/eddn/C5149430_file1.txt', '.*DRS_UNTIL=2013%2F294.*':'usgs/eddn/C5149430_file2.txt', '.*DRS_UNTIL=2013%2F207.*':'usgs/eddn/C5149430_file3.txt' }, 'first_row_message_timestamp_utc': datetime.strptime('14016152818', fmt), 'last_row_message_timestamp_utc': datetime.strptime('13202032818', fmt), 'number_of_lines': 360, 'start': 'P365D' } ] def test_multi_message_download(): for test_set in multi_message_test_sets: with test_util.mocked_urls(test_set['data_files']): data = ulmo.usgs.eddn.get_data(test_set['dcp_address'], start=test_set['start']) assert data['message_timestamp_utc'][-1] == test_set['first_row_message_timestamp_utc'] assert data['message_timestamp_utc'][0] == test_set['last_row_message_timestamp_utc'] assert len(data) == test_set['number_of_lines'] twdb_stevens_test_sets = [ { 'message_timestamp_utc': datetime(2013,10,30,15,28,18), 'dcp_message': '"BV:11.9 193.76$ 193.70$ 193.62$ 193.54$ 193.49$ 193.43$ 193.37$ 199.62$ 200.51$ 200.98$ 195.00$ 194.33$ ', 'return_value': [ ['2013-10-30 04:00:00', pd.np.nan, 193.76], ['2013-10-30 05:00:00', pd.np.nan, 193.70], ['2013-10-30 06:00:00', pd.np.nan, 193.62], ['2013-10-30 07:00:00', pd.np.nan, 193.54], ['2013-10-30 08:00:00', pd.np.nan, 193.49], ['2013-10-30 09:00:00', pd.np.nan, 193.43], ['2013-10-30 10:00:00', pd.np.nan, 193.37], ['2013-10-30 11:00:00', pd.np.nan, 199.62], ['2013-10-30 12:00:00', pd.np.nan, 200.51], ['2013-10-30 13:00:00', pd.np.nan, 200.98], ['2013-10-30 14:00:00', pd.np.nan, 195.00], ['2013-10-30 15:00:00', 11.9, 194.33], ], }, { 'message_timestamp_utc': datetime(2013,10,30,15,28,18), 'dcp_message': '"BV:12.6 Channel:5 Time:28 +304.63 +304.63 +304.63 +304.56 +304.63 +304.63 +304.63 +304.63 +304.63 +304.63 +304.63 +304.71 Channel:6 Time:28 +310.51 +310.66 +310.59 +310.51 +310.51 +310.59 +310.59 +310.51 +310.66 +310.51 +310.66 +310.59 ', 'return_value': [ ['2013-10-30 04:00:00', '5', '28', pd.np.nan, 304.63], ['2013-10-30 05:00:00', '5', '28', pd.np.nan, 304.63], ['2013-10-30 06:00:00', '5', '28', pd.np.nan, 304.63], ['2013-10-30 07:00:00', '5', '28', pd.np.nan, 304.56], ['2013-10-30 08:00:00', '5', '28', pd.np.nan, 304.63], ['2013-10-30 09:00:00', '5', '28', pd.np.nan, 304.63], ['2013-10-30 10:00:00', '5', '28', pd.np.nan, 304.63], ['2013-10-30 11:00:00', '5', '28', pd.np.nan, 304.63], ['2013-10-30 12:00:00', '5', '28', pd.np.nan, 304.63], ['2013-10-30 13:00:00', '5', '28', pd.np.nan, 304.63], ['2013-10-30 14:00:00', '5', '28', pd.np.nan, 304.63], ['2013-10-30 15:00:00', '5', '28', 12.6, 304.71], ['2013-10-30 04:00:00', '6', '28', pd.np.nan, 310.51], ['2013-10-30 05:00:00', '6', '28', pd.np.nan, 310.66], ['2013-10-30 06:00:00', '6', '28', pd.np.nan, 310.59], ['2013-10-30 07:00:00', '6', '28', pd.np.nan, 310.51], ['2013-10-30 08:00:00', '6', '28', pd.np.nan, 310.51], ['2013-10-30 09:00:00', '6', '28', pd.np.nan, 310.59], ['2013-10-30 10:00:00', '6', '28', pd.np.nan, 310.59], ['2013-10-30 11:00:00', '6', '28', pd.np.nan, 310.51], ['2013-10-30 12:00:00', '6', '28', pd.np.nan, 310.66], ['2013-10-30 13:00:00', '6', '28', pd.np.nan, 310.51], ['2013-10-30 14:00:00', '6', '28', pd.np.nan, 310.66], ['2013-10-30 15:00:00', '6', '28', 12.6, 310.59], ] }, { 'message_timestamp_utc': datetime(2013,10,30,15,28,18), 'dcp_message': '"BV:12.6 ', 'return_value': pd.DataFrame() }, { 'message_timestamp_utc': datetime(2013,10,30,15,28,18), 'dcp_message': """ 79."$}X^pZBF8iB~i>>Xmj[bvr^Zv%JXl,DU=l{uu[ t( |@2q^sjS! """, 'return_value': pd.DataFrame() }, ] def test_parser_twdb_stevens(): for test_set in twdb_stevens_test_sets: print 'testing twdb_stevens parser' if isinstance(test_set['return_value'], pd.DataFrame): parser = getattr(parsers, 'twdb_stevens') assert_frame_equal(pd.DataFrame(), parser(test_set)) return if len(test_set['return_value'][0]) == 3: columns = ['timestamp_utc', 'battery_voltage', 'water_level'] else: columns = ['timestamp_utc', 'channel', 'time', 'battery_voltage', 'water_level'] _assert(test_set, columns, 'twdb_stevens') twdb_sutron_test_sets = [ { 'message_timestamp_utc': datetime(2013,10,30,15,28,18), 'dcp_message': '":Sense01 60 #60 -67.84 -66.15 -67.73 -67.81 -66.42 -68.45 -68.04 -67.87 -71.53 -73.29 -70.55 -72.71 :BL 13.29', 'return_value': [ ['2013-10-30 04:00:00', 'sense01', pd.np.nan, 72.71], ['2013-10-30 05:00:00', 'sense01', pd.np.nan, 70.55], ['2013-10-30 06:00:00', 'sense01', pd.np.nan, 73.29], ['2013-10-30 07:00:00', 'sense01', pd.np.nan, 71.53], ['2013-10-30 08:00:00', 'sense01', pd.np.nan, 67.87], ['2013-10-30 09:00:00', 'sense01', pd.np.nan, 68.04], ['2013-10-30 10:00:00', 'sense01', pd.np.nan, 68.45], ['2013-10-30 11:00:00', 'sense01', pd.np.nan, 66.42], ['2013-10-30 12:00:00', 'sense01', pd.np.nan, 67.81], ['2013-10-30 13:00:00', 'sense01', pd.np.nan, 67.73], ['2013-10-30 14:00:00', 'sense01', pd.np.nan, 66.15], ['2013-10-30 15:00:00', 'sense01', 13.29, 67.84], ], }, { 'message_timestamp_utc': datetime(2013,10,30,15,28,18), 'dcp_message': '":OTT 703 60 #60 -231.47 -231.45 -231.44 -231.45 -231.47 -231.50 -231.51 -231.55 -231.56 -231.57 -231.55 -231.53 :6910704 60 #60 -261.85 -261.83 -261.81 -261.80 -261.81 -261.83 -261.85 -261.87 -261.89 -261.88 -261.86 -261.83 :BL 13.21', 'return_value': [ ['2013-10-30 04:00:00', 'ott 703', pd.np.nan, 231.53], ['2013-10-30 05:00:00', 'ott 703', pd.np.nan, 231.55], ['2013-10-30 06:00:00', 'ott 703', pd.np.nan, 231.57], ['2013-10-30 07:00:00', 'ott 703', pd.np.nan, 231.56], ['2013-10-30 08:00:00', 'ott 703', pd.np.nan, 231.55], ['2013-10-30 09:00:00', 'ott 703', pd.np.nan, 231.51], ['2013-10-30 10:00:00', 'ott 703', pd.np.nan, 231.50], ['2013-10-30 11:00:00', 'ott 703', pd.np.nan, 231.47], ['2013-10-30 12:00:00', 'ott 703', pd.np.nan, 231.45], ['2013-10-30 13:00:00', 'ott 703', pd.np.nan, 231.44], ['2013-10-30 14:00:00', 'ott 703', pd.np.nan, 231.45], ['2013-10-30 15:00:00', 'ott 703', 13.21, 231.47], ['2013-10-30 04:00:00', '6910704', pd.np.nan, 261.83], ['2013-10-30 05:00:00', '6910704', pd.np.nan, 261.86], ['2013-10-30 06:00:00', '6910704', pd.np.nan, 261.88], ['2013-10-30 07:00:00', '6910704', pd.np.nan, 261.89], ['2013-10-30 08:00:00', '6910704', pd.np.nan, 261.87], ['2013-10-30 09:00:00', '6910704', pd.np.nan, 261.85], ['2013-10-30 10:00:00', '6910704', pd.np.nan, 261.83], ['2013-10-30 11:00:00', '6910704', pd.np.nan, 261.81], ['2013-10-30 12:00:00', '6910704', pd.np.nan, 261.80], ['2013-10-30 13:00:00', '6910704', pd.np.nan, 261.81], ['2013-10-30 14:00:00', '6910704', pd.np.nan, 261.83], ['2013-10-30 15:00:00', '6910704', 13.21, 261.85], ] }, { 'message_timestamp_utc': datetime(2013,10,30,15,28,18), 'dcp_message': '"\r\n// \r\n// \r\n// \r\n// \r\n// \r\n-199.88 \r\n-199.92 \r\n-199.96 \r\n-199.98 \r\n-200.05 \r\n-200.09 \r\n-200.15', 'return_value': [ ['2013-10-30 04:00:00', pd.np.nan, 200.15], ['2013-10-30 05:00:00', pd.np.nan, 200.09], ['2013-10-30 06:00:00', pd.np.nan, 200.05], ['2013-10-30 07:00:00', pd.np.nan, 199.98], ['2013-10-30 08:00:00', pd.np.nan, 199.96], ['2013-10-30 09:00:00', pd.np.nan, 199.92], ['2013-10-30 10:00:00', pd.np.nan, 199.88], ['2013-10-30 11:00:00', pd.np.nan, pd.np.nan], ['2013-10-30 12:00:00', pd.np.nan, pd.np.nan], ['2013-10-30 13:00:00', pd.np.nan, pd.np.nan], ['2013-10-30 14:00:00', pd.np.nan, pd.np.nan], ['2013-10-30 15:00:00', pd.np.nan, pd.np.nan], ], }, ] def test_parser_twdb_sutron(): for test_set in twdb_sutron_test_sets: print 'testing twdb_sutron parser' if len(test_set['return_value'][0]) == 3: columns = ['timestamp_utc', 'battery_voltage', 'water_level'] else: columns = ['timestamp_utc', 'channel', 'battery_voltage', 'water_level'] _assert(test_set, columns, 'twdb_sutron') twdb_texuni_test_sets = [ { 'message_timestamp_utc': datetime(2013,10,30,15,28,18), 'dcp_message': ' \r\n+0.000,-109.8,\r\n+0.000,-109.8,\r\n+0.000,-109.8,\r\n+0.000,-109.8,\r\n+0.000,-109.8,\r\n+0.000,-109.9,\r\n+0.000,-109.9,\r\n+0.000,-109.9,\r\n+0.000,-109.9,\r\n+0.000,-109.9,\r\n+0.000,-110.0,\r\n+0.000,-110.0,\r\n+0.000,-109.9,\r\n+0.000,-109.9,\r\n+0.000,-109.9,\r\n+0.000,-109.9,\r\n+0.000,-110.0,\r\n+0.000,-110.0,\r\n+0.000,-110.0,\r\n+0.000,-110.1,\r\n+0.000,-110.1,\r\n+0.000,-110.1,\r\n+0.000,-110.1,\r\n+0.000,-110.1,\r\n+340.0,+2013.,+307.0,+1400.,+12.07,+0.000,-109.9,-109.8,-110.1,+30.57,', 'return_value': [ ['2013-10-29 16:00:00', pd.np.nan, 109.8], ['2013-10-29 17:00:00', pd.np.nan, 109.8], ['2013-10-29 18:00:00', pd.np.nan, 109.8], ['2013-10-29 19:00:00', pd.np.nan, 109.8], ['2013-10-29 20:00:00', pd.np.nan, 109.8], ['2013-10-29 21:00:00', pd.np.nan, 109.9], ['2013-10-29 22:00:00', pd.np.nan, 109.9], ['2013-10-29 23:00:00', pd.np.nan, 109.9], ['2013-10-30 00:00:00', pd.np.nan, 109.9], ['2013-10-30 01:00:00', pd.np.nan, 109.9], ['2013-10-30 02:00:00', pd.np.nan, 110.0], ['2013-10-30 03:00:00', pd.np.nan, 110.0], ['2013-10-30 04:00:00', pd.np.nan, 109.9], ['2013-10-30 05:00:00', pd.np.nan, 109.9], ['2013-10-30 06:00:00', pd.np.nan, 109.9],<|fim▁hole|> ['2013-10-30 11:00:00', pd.np.nan, 110.1], ['2013-10-30 12:00:00', pd.np.nan, 110.1], ['2013-10-30 13:00:00', pd.np.nan, 110.1], ['2013-10-30 14:00:00', pd.np.nan, 110.1], ['2013-10-30 15:00:00', pd.np.nan, 110.1], ] }, ] def test_parser_twdb_texuni(): for test_set in twdb_texuni_test_sets: print 'testing twdb_texuni parser' columns = ['timestamp_utc', 'battery_voltage', 'water_level'] _assert(test_set, columns, 'twdb_texuni') def _assert(test_set, columns, parser): expected = pd.DataFrame(test_set['return_value'], columns=columns) expected.index = pd.to_datetime(expected['timestamp_utc']) del expected['timestamp_utc'] parser = getattr(parsers, parser) df = parser(test_set) # to compare pandas dataframes, columns must be in same order if 'channel' in df.columns: for channel in pd.np.unique(df['channel']): df_c = df[df['channel']==channel] expected_c = expected[expected['channel']==channel] assert_frame_equal(df_c.sort(axis=1).sort(axis=0), expected_c.sort(axis=1).sort(axis=0)) else: assert_frame_equal(df.sort(axis=1).sort(axis=0), expected.sort(axis=1).sort(axis=0))<|fim▁end|>
['2013-10-30 07:00:00', pd.np.nan, 109.9], ['2013-10-30 08:00:00', pd.np.nan, 110.0], ['2013-10-30 09:00:00', pd.np.nan, 110.0], ['2013-10-30 10:00:00', pd.np.nan, 110.0],
<|file_name|>test-zlib-brotli-kmaxlength-rangeerror.js<|end_file_name|><|fim▁begin|>'use strict'; require('../common'); // This test ensures that zlib throws a RangeError if the final buffer needs to // be larger than kMaxLength and concatenation fails. // https://github.com/nodejs/node/pull/1811 const assert = require('assert'); // Change kMaxLength for zlib to trigger the error without having to allocate // large Buffers. const buffer = require('buffer'); const oldkMaxLength = buffer.kMaxLength; buffer.kMaxLength = 64; const zlib = require('zlib');<|fim▁hole|>// Async zlib.brotliDecompress(encoded, function(err) { assert.ok(err instanceof RangeError); }); // Sync assert.throws(function() { zlib.brotliDecompressSync(encoded); }, RangeError);<|fim▁end|>
buffer.kMaxLength = oldkMaxLength; const encoded = Buffer.from('G38A+CXCIrFAIAM=', 'base64');
<|file_name|>MySQLPreTableImportManager.java<|end_file_name|><|fim▁begin|>package org.dbflute.erflute.db.impl.mysql; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.dbflute.erflute.editor.model.dbimport.DBObject; import org.dbflute.erflute.editor.model.dbimport.PreImportFromDBManager; public class MySQLPreTableImportManager extends PreImportFromDBManager { @Override protected List<DBObject> importObjects(String[] types, String dbObjectType) throws SQLException { final List<DBObject> list = new ArrayList<>(); ResultSet resultSet = null; if (schemaList.isEmpty()) { schemaList.add(null); } final String catalog = (8 <= metaData.getDriverMajorVersion()) ? dbSetting.getDatabase() : null; for (final String schemaPattern : schemaList) { try { resultSet = metaData.getTables(catalog, schemaPattern, null, types); while (resultSet.next()) { final String schema = resultSet.getString("TABLE_SCHEM"); final String name = resultSet.getString("TABLE_NAME"); if (DBObject.TYPE_TABLE.equals(dbObjectType)) { try { getAutoIncrementColumnName(con, schema, name); } catch (final SQLException e) { e.printStackTrace(); // テーブル情報が取得できない場合(他のユーザの所有物などの場合)、<|fim▁hole|> continue; } } final DBObject dbObject = new DBObject(schema, name, dbObjectType); list.add(dbObject); } } finally { if (resultSet != null) { resultSet.close(); resultSet = null; } } } return list; } }<|fim▁end|>
// このテーブルは使用しない。
<|file_name|>normalizeOptions.js<|end_file_name|><|fim▁begin|>'use strict'; // Adapted from https://github.com/tleunen/babel-plugin-module-resolver/blob/master/src/normalizeOptions.js const path = require('path'); const { createSelector } = require('reselect'); const defaultExtensions = ['.js']; const normalizeRoots = (optsRoot, cwd) => { return Object.keys(optsRoot).reduce((acc, current) => { const dirPath = path.resolve(cwd, optsRoot[current]); acc[current] = dirPath; return acc; }, {}); }; const normalizeOptions = createSelector( // TODO check if needed currentFile => (currentFile.includes('.') ? path.dirname(currentFile) : currentFile), (_, opts) => opts, (_, opts) => { const cwd = process.cwd(); const roots = normalizeRoots(opts.roots, cwd); return { cwd, roots, extensions: defaultExtensions,<|fim▁hole|>module.exports = normalizeOptions;<|fim▁end|>
}; } );
<|file_name|>pouchdb.js<|end_file_name|><|fim▁begin|>const url = require('url'); const _ = require('lodash'); const fetch = require('node-fetch'); const PouchDB = require('pouchdb'); const logout = require('../../logout')(); PouchDB.plugin(require('pouchdb-adapter-node-websql')); PouchDB.plugin(require('pouchdb-find')); module.exports = { createPouchDB: _.memoize(createPouchDB), sync: _.memoize(sync), }; function createPouchDB(environment){ return new PouchDB(`${environment}.db`, {adapter: 'websql', auto_compaction: true}); } function sync(environment, syncDbUrl, continuous_sync){ if(!environment) return; if(!syncDbUrl) return; const syncDbUri = url.parse(syncDbUrl); const syncDbNamedUrl = ((!syncDbUri.path) || (syncDbUri.path === '/')) ? url.resolve(syncDbUrl, environment) : url.resolve(syncDbUrl.replace(syncDbUri.path, ''), `${syncDbUri.path.replace(/\//g, '')}-${environment}`); return fetch(syncDbNamedUrl, {method: 'PUT'}) .catch(error => error) .then(data => data.json()) .then(data => {<|fim▁hole|> return createPouchDB(environment) .sync(syncDbNamedUrl, { live: continuous_sync, retry: continuous_sync, }) .on('change', info => logout.log(`Change - ${syncDbUri.host} - ${environment}`)) .on('paused', () => logout.log(`Paused - ${syncDbUri.host} - ${environment}`)) .on('active', () => logout.log(`Active - ${syncDbUri.host} - ${environment}`)) .on('denied', info => logout.error(`Denied - ${syncDbUri.host} - ${environment}`)) .on('complete', info => logout.log(`Complete - ${syncDbUri.host} - ${environment}`)) .on('error', error => logout.error(`Error - ${syncDbUri.host} - ${environment}`)); }) .catch(error => logout.error(error)); }<|fim▁end|>
<|file_name|>issue-15167.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|>// <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 f should not be able to inject a reference to 'n'. // // Ignored because `for` loops are not hygienic yet; they will require special // handling since they introduce a new pattern binding position. // ignore-test macro_rules! f { () => (n) } fn main() -> (){ for n in 0..1 { println!("{}", f!()); //~ ERROR unresolved name `n` } }<|fim▁end|>
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
<|file_name|>validate.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # # http://www.privacyidea.org # (c) cornelius kölbel, privacyidea.org # # 2020-01-30 Jean-Pierre Höhmann <[email protected]> # Add WebAuthn token # 2018-01-22 Cornelius Kölbel <[email protected]> # Add offline refill # 2016-12-20 Cornelius Kölbel <[email protected]> # Add triggerchallenge endpoint # 2016-10-23 Cornelius Kölbel <[email protected]> # Add subscription decorator # 2016-09-05 Cornelius Kölbel <[email protected]> # SAML attributes on fail # 2016-08-30 Cornelius Kölbel <[email protected]> # save client application type to database # 2016-08-09 Cornelius Kölbel <[email protected]> # Add possibility to check OTP only # 2015-11-19 Cornelius Kölbel <[email protected]> # Add support for transaction_id to saml_check # 2015-06-17 Cornelius Kölbel <[email protected]> # Add policy decorator for API key requirement # 2014-12-08 Cornelius Kölbel, <[email protected]> # Complete rewrite during flask migration # Try to provide REST API # # This code is free software; you can redistribute it and/or # modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE # License as published by the Free Software Foundation; either # version 3 of the License, or any later version. # # This code 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/>. # __doc__ = """This module contains the REST API for doing authentication. The methods are tested in the file tests/test_api_validate.py Authentication is either done by providing a username and a password or a serial number and a password. **Authentication workflow** Authentication workflow is like this: In case of authenticating a user: * :func:`privacyidea.lib.token.check_user_pass` * :func:`privacyidea.lib.token.check_token_list` * :func:`privacyidea.lib.tokenclass.TokenClass.authenticate` * :func:`privacyidea.lib.tokenclass.TokenClass.check_pin` * :func:`privacyidea.lib.tokenclass.TokenClass.check_otp` In case if authenticating a serial number: * :func:`privacyidea.lib.token.check_serial_pass` * :func:`privacyidea.lib.token.check_token_list` * :func:`privacyidea.lib.tokenclass.TokenClass.authenticate` * :func:`privacyidea.lib.tokenclass.TokenClass.check_pin` * :func:`privacyidea.lib.tokenclass.TokenClass.check_otp` """ from flask import (Blueprint, request, g, current_app) from privacyidea.lib.user import get_user_from_param, log_used_user from .lib.utils import send_result, getParam from ..lib.decorators import (check_user_or_serial_in_request) from .lib.utils import required from privacyidea.lib.error import ParameterError from privacyidea.lib.token import (check_user_pass, check_serial_pass, check_otp, create_challenges_from_tokens, get_one_token) from privacyidea.api.lib.utils import get_all_params from privacyidea.lib.config import (return_saml_attributes, get_from_config, return_saml_attributes_on_fail, SYSCONF, ensure_no_config_object) from privacyidea.lib.audit import getAudit from privacyidea.api.lib.decorators import add_serial_from_response_to_g from privacyidea.api.lib.prepolicy import (prepolicy, set_realm, api_key_required, mangle, save_client_application_type, check_base_action, pushtoken_wait, webauthntoken_auth, webauthntoken_authz, webauthntoken_request, check_application_tokentype) from privacyidea.api.lib.postpolicy import (postpolicy, check_tokentype, check_serial, check_tokeninfo, no_detail_on_fail, no_detail_on_success, autoassign, offline_info, add_user_detail_to_response, construct_radius_response, mangle_challenge_response, is_authorized) from privacyidea.lib.policy import PolicyClass from privacyidea.lib.event import EventConfiguration import logging from privacyidea.api.register import register_blueprint from privacyidea.api.recover import recover_blueprint from privacyidea.lib.utils import get_client_ip from privacyidea.lib.event import event from privacyidea.lib.challenge import get_challenges, extract_answered_challenges from privacyidea.lib.subscriptions import CheckSubscription from privacyidea.api.auth import admin_required from privacyidea.lib.policy import ACTION from privacyidea.lib.token import get_tokens from privacyidea.lib.machine import list_machine_tokens from privacyidea.lib.applications.offline import MachineApplication import json log = logging.getLogger(__name__) validate_blueprint = Blueprint('validate_blueprint', __name__) @validate_blueprint.before_request @register_blueprint.before_request @recover_blueprint.before_request def before_request(): """ This is executed before the request """ ensure_no_config_object() request.all_data = get_all_params(request) request.User = get_user_from_param(request.all_data) privacyidea_server = current_app.config.get("PI_AUDIT_SERVERNAME") or \ request.host # Create a policy_object, that reads the database audit settings # and contains the complete policy definition during the request. # This audit_object can be used in the postpolicy and prepolicy and it # can be passed to the innerpolicies. g.policy_object = PolicyClass() g.audit_object = getAudit(current_app.config, g.startdate) g.event_config = EventConfiguration() # access_route contains the ip addresses of all clients, hops and proxies. g.client_ip = get_client_ip(request, get_from_config(SYSCONF.OVERRIDECLIENT)) # Save the HTTP header in the localproxy object g.request_headers = request.headers g.serial = getParam(request.all_data, "serial", default=None) g.audit_object.log({"success": False, "action_detail": "", "client": g.client_ip, "client_user_agent": request.user_agent.browser, "privacyidea_server": privacyidea_server, "action": "{0!s} {1!s}".format(request.method, request.url_rule), "info": ""}) @validate_blueprint.route('/offlinerefill', methods=['POST']) @check_user_or_serial_in_request(request) @event("validate_offlinerefill", request, g) def offlinerefill(): """ This endpoint allows to fetch new offline OTP values for a token, that is already offline. According to the definition it will send the missing OTP values, so that the client will have as much otp values as defined. :param serial: The serial number of the token, that should be refilled. :param refilltoken: The authorization token, that allows refilling. :param pass: the last password (maybe password+OTP) entered by the user :return: """ serial = getParam(request.all_data, "serial", required) refilltoken = getParam(request.all_data, "refilltoken", required) password = getParam(request.all_data, "pass", required) tokenobj_list = get_tokens(serial=serial) if len(tokenobj_list) != 1: raise ParameterError("The token does not exist") else: tokenobj = tokenobj_list[0] tokenattachments = list_machine_tokens(serial=serial, application="offline") if tokenattachments: # TODO: Currently we do not distinguish, if a token had more than one offline attachment # We need the options to pass the count and the rounds for the next offline OTP values, # which could have changed in the meantime. options = tokenattachments[0].get("options") # check refill token: if tokenobj.get_tokeninfo("refilltoken") == refilltoken: # refill otps = MachineApplication.get_refill(tokenobj, password, options) refilltoken = MachineApplication.generate_new_refilltoken(tokenobj) response = send_result(True) content = response.json content["auth_items"] = {"offline": [{"refilltoken": refilltoken, "response": otps}]} response.set_data(json.dumps(content)) return response raise ParameterError("Token is not an offline token or refill token is incorrect") @validate_blueprint.route('/check', methods=['POST', 'GET']) @validate_blueprint.route('/radiuscheck', methods=['POST', 'GET']) @validate_blueprint.route('/samlcheck', methods=['POST', 'GET']) @postpolicy(is_authorized, request=request) @postpolicy(mangle_challenge_response, request=request) @postpolicy(construct_radius_response, request=request) @postpolicy(no_detail_on_fail, request=request) @postpolicy(no_detail_on_success, request=request) @postpolicy(add_user_detail_to_response, request=request) @postpolicy(offline_info, request=request) @postpolicy(check_tokeninfo, request=request) @postpolicy(check_tokentype, request=request) @postpolicy(check_serial, request=request) @postpolicy(autoassign, request=request) @add_serial_from_response_to_g @prepolicy(check_application_tokentype, request=request) @prepolicy(pushtoken_wait, request=request) @prepolicy(set_realm, request=request) @prepolicy(mangle, request=request) @prepolicy(save_client_application_type, request=request) @prepolicy(webauthntoken_request, request=request) @prepolicy(webauthntoken_authz, request=request) @prepolicy(webauthntoken_auth, request=request) @check_user_or_serial_in_request(request) @CheckSubscription(request) @prepolicy(api_key_required, request=request) @event("validate_check", request, g) def check(): """ check the authentication for a user or a serial number. Either a ``serial`` or a ``user`` is required to authenticate. The PIN and OTP value is sent in the parameter ``pass``. In case of successful authentication it returns ``result->value: true``. In case of a challenge response authentication a parameter ``exception=1`` can be passed. This would result in a HTTP 500 Server Error response if an error occurred during sending of SMS or Email. In case ``/validate/radiuscheck`` is requested, the responses are modified as follows: A successful authentication returns an empty ``HTTP 204`` response. An unsuccessful authentication returns an empty ``HTTP 400`` response. Error responses are the same responses as for the ``/validate/check`` endpoint. :param serial: The serial number of the token, that tries to authenticate. :param user: The loginname/username of the user, who tries to authenticate. :param realm: The realm of the user, who tries to authenticate. If the realm is omitted, the user is looked up in the default realm. :param type: The tokentype of the tokens, that are taken into account during authentication. Requires the *authz* policy :ref:`application_tokentype_policy`. It is ignored when a distinct serial is given. :param pass: The password, that consists of the OTP PIN and the OTP value. :param otponly: If set to 1, only the OTP value is verified. This is used in the management UI. Only used with the parameter serial. :param transaction_id: The transaction ID for a response to a challenge request :param state: The state ID for a response to a challenge request :return: a json result with a boolean "result": true **Example Validation Request**: .. sourcecode:: http POST /validate/check HTTP/1.1 Host: example.com Accept: application/json user=user realm=realm1 pass=s3cret123456 **Example response** for a successful authentication: .. sourcecode:: http HTTP/1.1 200 OK Content-Type: application/json { "detail": { "message": "matching 1 tokens", "serial": "PISP0000AB00", "type": "spass" }, "id": 1, "jsonrpc": "2.0", "result": { "status": true, "value": true }, "version": "privacyIDEA unknown" } **Example response** for this first part of a challenge response authentication: .. sourcecode:: http HTTP/1.1 200 OK Content-Type: application/json { "detail": { "serial": "PIEM0000AB00", "type": "email", "transaction_id": "12345678901234567890", "multi_challenge: [ {"serial": "PIEM0000AB00", "transaction_id": "12345678901234567890", "message": "Please enter otp from your email", "client_mode": "interactive"}, {"serial": "PISM12345678", "transaction_id": "12345678901234567890", "message": "Please enter otp from your SMS", "client_mode": "interactive"} ] }, "id": 2, "jsonrpc": "2.0", "result": { "status": true, "value": false }, "version": "privacyIDEA unknown" } In this example two challenges are triggered, one with an email and one with an SMS. The application and thus the user has to decide, which one to use. They can use either. The challenges also contain the information of the "client_mode". This tells the plugin, whether it should display an input field to ask for the OTP value or e.g. to poll for an answered authentication. Read more at :ref:`client_modes`. .. note:: All challenge response tokens have the same ``transaction_id`` in this case. **Example response** for a successful authentication with ``/samlcheck``: .. sourcecode:: http HTTP/1.1 200 OK Content-Type: application/json { "detail": { "message": "matching 1 tokens", "serial": "PISP0000AB00", "type": "spass" }, "id": 1, "jsonrpc": "2.0", "result": { "status": true, "value": {"attributes": { "username": "koelbel", "realm": "themis", "mobile": null, "phone": null, "myOwn": "/data/file/home/koelbel", "resolver": "themis", "surname": "Kölbel", "givenname": "Cornelius", "email": null}, "auth": true} }, "version": "privacyIDEA unknown" } The response in ``value->attributes`` can contain additional attributes (like "myOwn") which you can define in the LDAP resolver in the attribute mapping. """ user = request.User serial = getParam(request.all_data, "serial") password = getParam(request.all_data, "pass", required) otp_only = getParam(request.all_data, "otponly") token_type = getParam(request.all_data, "type") options = {"g": g, "clientip": g.client_ip, "user": user} # Add all params to the options for key, value in request.all_data.items(): if value and key not in ["g", "clientip", "user"]: options[key] = value g.audit_object.log({"user": user.login, "resolver": user.resolver, "realm": user.realm}) if serial: if user: # check if the given token belongs to the user if not get_tokens(user=user, serial=serial, count=True): raise ParameterError('Given serial does not belong to given user!') if not otp_only: success, details = check_serial_pass(serial, password, options=options) else: success, details = check_otp(serial, password) result = success else: options["token_type"] = token_type success, details = check_user_pass(user, password, options=options) result = success if request.path.endswith("samlcheck"): ui = user.info result = {"auth": success, "attributes": {}} if return_saml_attributes(): if success or return_saml_attributes_on_fail(): # privacyIDEA's own attribute map result["attributes"] = {"username": ui.get("username"), "realm": user.realm, "resolver": user.resolver, "email": ui.get("email"), "surname": ui.get("surname"), "givenname": ui.get("givenname"), "mobile": ui.get("mobile"), "phone": ui.get("phone")} # additional attributes for k, v in ui.items(): result["attributes"][k] = v g.audit_object.log({"info": log_used_user(user, details.get("message")), "success": success, "serial": serial or details.get("serial"), "token_type": details.get("type")}) return send_result(result, rid=2, details=details) @validate_blueprint.route('/triggerchallenge', methods=['POST', 'GET']) @admin_required @postpolicy(is_authorized, request=request) @postpolicy(mangle_challenge_response, request=request) @add_serial_from_response_to_g @check_user_or_serial_in_request(request) @prepolicy(check_application_tokentype, request=request) @prepolicy(check_base_action, request, action=ACTION.TRIGGERCHALLENGE) @prepolicy(webauthntoken_request, request=request) @prepolicy(webauthntoken_auth, request=request) @event("validate_triggerchallenge", request, g) def trigger_challenge(): """ An administrator can call this endpoint if he has the right of ``triggerchallenge`` (scope: admin). He can pass a ``user`` name and or a ``serial`` number. privacyIDEA will trigger challenges for all native challenges response tokens, possessed by this user or only for the given serial number. The request needs to contain a valid PI-Authorization header. :param user: The loginname/username of the user, who tries to authenticate. :param realm: The realm of the user, who tries to authenticate. If the realm is omitted, the user is looked up in the default realm. :param serial: The serial number of the token. :param type: The tokentype of the tokens, that are taken into account during authentication. Requires authz policy application_tokentype. Is ignored when a distinct serial is given. :return: a json result with a "result" of the number of matching challenge response tokens **Example response** for a successful triggering of challenge: .. sourcecode:: http HTTP/1.1 200 OK Content-Type: application/json { "detail": { "client_mode": "interactive", "message": "please enter otp: , please enter otp: ", "messages": [ "please enter otp: ", "please enter otp: " ], "multi_challenge": [ { "client_mode": "interactive", "message": "please enter otp: ", "serial": "TOTP000026CB", "transaction_id": "11451135673179897001", "type": "totp" }, { "client_mode": "interactive", "message": "please enter otp: ", "serial": "OATH0062752C", "transaction_id": "11451135673179897001", "type": "hotp" } ], "serial": "OATH0062752C", "threadid": 140329819764480, "transaction_id": "11451135673179897001", "transaction_ids": [ "11451135673179897001", "11451135673179897001" ], "type": "hotp" }, "id": 2, "jsonrpc": "2.0", "result": { "status": true, "value": 2 } **Example response** for response, if the user has no challenge token: .. sourcecode:: http HTTP/1.1 200 OK Content-Type: application/json { "detail": {"messages": [], "threadid": 140031212377856, "transaction_ids": []}, "id": 1, "jsonrpc": "2.0", "result": {"status": true, "value": 0}, "signature": "205530282...54508", "time": 1484303812.346576, "version": "privacyIDEA 2.17", "versionnumber": "2.17" } **Example response** for a failed triggering of a challenge. In this case the ``status`` will be ``false``. .. sourcecode:: http HTTP/1.1 200 OK Content-Type: application/json { "detail": null, "id": 1, "jsonrpc": "2.0", "result": {"error": {"code": 905, "message": "ERR905: The user can not be found in any resolver in this realm!"}, "status": false}, "signature": "14468...081555", "time": 1484303933.72481, "version": "privacyIDEA 2.17" } """<|fim▁hole|> user = request.User serial = getParam(request.all_data, "serial") token_type = getParam(request.all_data, "type") details = {"messages": [], "transaction_ids": []} options = {"g": g, "clientip": g.client_ip, "user": user} # Add all params to the options for key, value in request.all_data.items(): if value and key not in ["g", "clientip", "user"]: options[key] = value token_objs = get_tokens(serial=serial, user=user, active=True, revoked=False, locked=False, tokentype=token_type) # Only use the tokens, that are allowed to do challenge response chal_resp_tokens = [token_obj for token_obj in token_objs if "challenge" in token_obj.mode] create_challenges_from_tokens(chal_resp_tokens, details, options) result_obj = len(details.get("multi_challenge")) challenge_serials = [challenge_info["serial"] for challenge_info in details["multi_challenge"]] g.audit_object.log({ "user": user.login, "resolver": user.resolver, "realm": user.realm, "success": result_obj > 0, "info": log_used_user(user, "triggered {0!s} challenges".format(result_obj)), "serial": ",".join(challenge_serials), }) return send_result(result_obj, rid=2, details=details) @validate_blueprint.route('/polltransaction', methods=['GET']) @validate_blueprint.route('/polltransaction/<transaction_id>', methods=['GET']) @prepolicy(mangle, request=request) @CheckSubscription(request) @prepolicy(api_key_required, request=request) def poll_transaction(transaction_id=None): """ Given a mandatory transaction ID, check if any non-expired challenge for this transaction ID has been answered. In this case, return true. If this is not the case, return false. This endpoint also returns false if no challenge with the given transaction ID exists. This is mostly useful for out-of-band tokens that should poll this endpoint to determine when to send an authentication request to ``/validate/check``. :jsonparam transaction_id: a transaction ID """ if transaction_id is None: transaction_id = getParam(request.all_data, "transaction_id", required) # Fetch a list of non-exired challenges with the given transaction ID # and determine whether it contains at least one non-expired answered challenge. matching_challenges = [challenge for challenge in get_challenges(transaction_id=transaction_id) if challenge.is_valid()] answered_challenges = extract_answered_challenges(matching_challenges) if answered_challenges: result = True log_challenges = answered_challenges else: result = False log_challenges = matching_challenges # We now determine the information that should be written to the audit log: # * If there are no answered valid challenges, we log all token serials of challenges matching # the transaction ID and the corresponding token owner # * If there are any answered valid challenges, we log their token serials and the corresponding user if log_challenges: g.audit_object.log({ "serial": ",".join(challenge.serial for challenge in log_challenges), }) # The token owner should be the same for all matching transactions user = get_one_token(serial=log_challenges[0].serial).user if user: g.audit_object.log({ "user": user.login, "resolver": user.resolver, "realm": user.realm, }) # In any case, we log the transaction ID g.audit_object.log({ "info": u"transaction_id: {}".format(transaction_id), "success": result }) return send_result(result)<|fim▁end|>
<|file_name|>request_test.go<|end_file_name|><|fim▁begin|>package sarama import ( "bytes" "reflect" "testing" "github.com/davecgh/go-spew/spew" ) type testRequestBody struct { } func (s *testRequestBody) key() int16 { return 0x666 } func (s *testRequestBody) version() int16 { return 0xD2 } func (s *testRequestBody) encode(pe packetEncoder) error { return pe.putString("abc") } // not specific to request tests, just helper functions for testing structures that // implement the encoder or decoder interfaces that needed somewhere to live func testEncodable(t *testing.T, name string, in encoder, expect []byte) { packet, err := encode(in, nil) if err != nil { t.Error(err) } else if !bytes.Equal(packet, expect) { t.Error("Encoding", name, "failed\ngot ", packet, "\nwant", expect) } } func testDecodable(t *testing.T, name string, out decoder, in []byte) { err := decode(in, out)<|fim▁hole|> if err != nil { t.Error("Decoding", name, "failed:", err) } } func testVersionDecodable(t *testing.T, name string, out versionedDecoder, in []byte, version int16) { err := versionedDecode(in, out, version) if err != nil { t.Error("Decoding", name, "version", version, "failed:", err) } } func testRequest(t *testing.T, name string, rb protocolBody, expected []byte) { packet := testRequestEncode(t, name, rb, expected) testRequestDecode(t, name, rb, packet) } func testRequestEncode(t *testing.T, name string, rb protocolBody, expected []byte) []byte { req := &request{correlationID: 123, clientID: "foo", body: rb} packet, err := encode(req, nil) headerSize := 14 + len("foo") if err != nil { t.Error(err) } else if !bytes.Equal(packet[headerSize:], expected) { t.Error("Encoding", name, "failed\ngot ", packet[headerSize:], "\nwant", expected) } return packet } func testRequestDecode(t *testing.T, name string, rb protocolBody, packet []byte) { decoded, n, err := decodeRequest(bytes.NewReader(packet)) if err != nil { t.Error("Failed to decode request", err) } else if decoded.correlationID != 123 || decoded.clientID != "foo" { t.Errorf("Decoded header %q is not valid: %+v", name, decoded) } else if !reflect.DeepEqual(rb, decoded.body) { t.Error(spew.Sprintf("Decoded request %q does not match the encoded one\nencoded: %+v\ndecoded: %+v", name, rb, decoded.body)) } else if n != len(packet) { t.Errorf("Decoded request %q bytes: %d does not match the encoded one: %d\n", name, n, len(packet)) } } func testResponse(t *testing.T, name string, res protocolBody, expected []byte) { encoded, err := encode(res, nil) if err != nil { t.Error(err) } else if expected != nil && !bytes.Equal(encoded, expected) { t.Error("Encoding", name, "failed\ngot ", encoded, "\nwant", expected) } decoded := reflect.New(reflect.TypeOf(res).Elem()).Interface().(versionedDecoder) if err := versionedDecode(encoded, decoded, res.version()); err != nil { t.Error("Decoding", name, "failed:", err) } if !reflect.DeepEqual(decoded, res) { t.Errorf("Decoded response does not match the encoded one\nencoded: %#v\ndecoded: %#v", res, decoded) } } func nullString(s string) *string { return &s }<|fim▁end|>
<|file_name|>package.py<|end_file_name|><|fim▁begin|># Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details.<|fim▁hole|># # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class RTriebeard(RPackage): """triebeard: 'Radix' Trees in 'Rcpp'""" homepage = "https://github.com/Ironholds/triebeard/" url = "https://cloud.r-project.org/src/contrib/triebeard_0.3.0.tar.gz" list_url = "https://cloud.r-project.org/src/contrib/Archive/triebeard" version('0.3.0', sha256='bf1dd6209cea1aab24e21a85375ca473ad11c2eff400d65c6202c0fb4ef91ec3') depends_on('r-rcpp', type=('build', 'run'))<|fim▁end|>
<|file_name|>OldUnAveragedSystemData.py<|end_file_name|><|fim▁begin|>#### import the simple module from the paraview from paraview.simple import * import glob, re, os, numpy, csv def CreatePointSelection(ids): source = IDSelectionSource() source.FieldType = "POINT" sids = [] for i in ids: sids.append(0) #proc-id sids.append(i) #cell-id source.IDs = sids return source def selectElectrodeData(data, voi): dataOverTime = PlotSelectionOverTime(Input=data, Selection=selection) dataOverTime.OnlyReportSelectionStatistics = 0 dataOverTimeT = TransposeTable(Input=dataOverTime, VariablesofInterest=voi) dataOverTimeT.UpdatePipeline() dataOverTimeTT = TransposeTable(Input=dataOverTimeT) dataOverTimeTT.Usethecolumnwithoriginalcolumnsname = 1 dataOverTimeTT.Addacolumnwithoriginalcolumnsname = 0 dataOverTimeTT.UpdatePipeline() return dataOverTimeTT path = os.getcwd() + "/" #path = "C:\\Users\\John\\Desktop\\" fileBase = "SteadyState_out" #fileBase = "Ar_phi_2.5_eV_tOn_2_ns_tOff_100_ns_d_10_um_VHigh_45.6_V_VLow_1.0_V" ## Define selection ## selection = CreatePointSelection(ids=[0]) ## Get reader data ## reader = ExodusIIReader(FileName=path+fileBase + '.e') reader.GenerateObjectIdCellArray = 1 reader.GenerateGlobalElementIdArray = 1 reader.ElementVariables = reader.ElementVariables.Available reader.PointVariables = reader.PointVariables.Available reader.ElementBlocks = reader.ElementBlocks.Available reader.ApplyDisplacements = 1 reader.DisplacementMagnitude = 1.0 ## Get cathode and anode coordinates calc = Calculator(Input=reader) calc.ResultArrayName = 'coords' calc.Function = 'coords' calc.UpdatePipeline() coordRange = calc.PointData['coords'].GetRange() minX = coordRange[0] maxX = coordRange[1] Delete(calc) del calc ## Prepare to extract electrode data ## electrodeData = [] VariablesofInterest = ['Time', 'Voltage', 'Current_Arp', 'Current_em', 'tot_gas_current', 'Emission_energy_flux'] ## Extract cathode data ## cathodeValues = ExtractLocation(Input=reader) cathodeValues.Location = [minX,0,0] cathodeValues.Mode = 'Interpolate At Location' electrodeData.append(selectElectrodeData(cathodeValues, VariablesofInterest)) ## Extract anode data ## anodeValues = ExtractLocation(Input=reader) anodeValues.Location = [maxX,0,0] anodeValues.Mode = 'Interpolate At Location' electrodeData.append(selectElectrodeData(anodeValues, VariablesofInterest)) electrodeData.append(reader) ## Calculate average powers and efficiency ## PowerAndEfficiency = ProgrammableFilter(Input=electrodeData) PowerAndEfficiency.Script = """ from numpy import trapz import numpy as np for c, a, r, outTable in zip(inputs[0], inputs[1], inputs[2], output): voltageDelta = 1E-1 # (V) timeUnits = 1E-9 # (s/ns) potential = c.RowData['Voltage'] - a.RowData['Voltage'] # (V) loadVoltage = max( potential ) * np.ones(len(c.RowData['Voltage'])) # (V) workFunctionDelta = 1 workFunctionDeltaVector = workFunctionDelta * np.ones(len(c.RowData['Voltage'])) # (eV) appliedVoltage = numpy.round( potential - loadVoltage , 4 ) # (V) ind = np.where( max( potential ) - voltageDelta < np.array(potential)) # (V) time = c.RowData['Time'] - min(c.RowData['Time']) # (ns) period = max(time) - min(time) # (ns) offTime = max(time[ind]) - min(time[ind]) # (ns) onTime = period - offTime # (ns) # current density j = a.RowData['tot_gas_current'] # The units stay the same because it is being integrated over ns, then divided by ns # Time (ns) outTable.RowData.append(time, 'time') # Total current density leaving at the boundaries (A/m^2) outTable.RowData.append(j, 'CurrentDensity') # Cathode anode potential difference (V) outTable.RowData.append(potential, 'CathodeAnodePotentialDifference') # Output voltage (V) outTable.RowData.append(workFunctionDeltaVector + potential, 'OutputVoltage') # Production voltage (V) outTable.RowData.append(workFunctionDeltaVector + loadVoltage, 'ProductionVoltage') # Applied voltage (V) outTable.RowData.append(appliedVoltage, 'AppliedVoltage') # Net power (W/m^2) outTable.RowData.append(j * (workFunctionDeltaVector + potential), 'NetPower') # Power produced (W/m^2) outTable.RowData.append(j * (workFunctionDeltaVector + loadVoltage), 'PowerProduced') # Power power consumed (W/m^2) <|fim▁hole|> outTable.RowData.append(c.RowData['Emission_energy_flux'], 'ElectronCooling') # Total current density leaving at the boundaries (A/m^2) outTable.RowData.append(r.FieldData['Full_EmissionCurrent'], 'EmittedCurrentDensity') # Emitted current density (A/m^2) outTable.RowData.append(r.FieldData['Thermionic_EmissionCurrent'], 'ThermionicEmissionCurrent') # Thermionic emitted current density (A/m^2) outTable.RowData.append(r.FieldData['Native_EmissionCurrent'], 'NativeCurrentDensity') # Native emitted current density (A/m^2) """ PowerAndEfficiency.UpdatePipeline() fname = glob.glob(path + 'TimeDependentData*.csv') for f in fname: os.remove(f) writer = CreateWriter(path + 'TimeDependentData.csv', PowerAndEfficiency, Precision=13, UseScientificNotation=1) writer.UpdatePipeline() fname = glob.glob(path + 'TimeDependentData*.csv') os.rename(fname[0] , path + 'TimeDependentData.csv') for f in GetSources().values(): Delete(f) del f<|fim▁end|>
outTable.RowData.append(j * appliedVoltage, 'PowerConsumed') # ElectronCooling (W/m^2)
<|file_name|>objectconsole.py<|end_file_name|><|fim▁begin|># Written by Ingar Arntzen # see LICENSE.txt for license information """ This module implements a generic console interface that can be attached to any runnable python object. """ import code import __builtin__ import threading import exceptions ############################################## # OBJECT CONSOLE ##############################################<|fim▁hole|> class ConsoleError(exceptions.Exception): """Error associated with the console.""" pass class ObjectConsole: """ This class runs a python console in the main thread, and starts a given Object in a second thread. The Object is assumed to implement at least two methods, run() and stop(). - The run() method is the entry point for the thread. - The stop() method is used by the main thread to request that the object thread does a controlled shutdown and returns from the run method. If the worker thread does not return from run() within 2 seconds after stop() has been invoked, the console terminates the object thread more aggressively. AttributeNames of Object listed in the provided namespace will be included in the console namespace. """ TIMEOUT = 2 def __init__(self, object_, name_space=None, run='run', stop='stop', name=""): self._object = object_ self._object_run = getattr(object_, run) self._object_stop = getattr(object_, stop) self._thread = threading.Thread(group=None, target=self._object_run, name="ObjectThread") # Configure Console Namespace self._name_space = {} self._name_space['__builtiname_space__'] = __builtin__ self._name_space['__name__'] = __name__ self._name_space['__doc__'] = __doc__ self._name_space['help'] = self._usage if name_space and isinstance(name_space, type({})): self._name_space.update(name_space) self._app_name_space = name_space self._app_name = name self._usage() def _usage(self): """Print usage information.""" print "\nConsole:", self._app_name for key in self._app_name_space.keys(): print "- ", key print "- help" def run(self): """Starts the given runnable object in a thread and then starts the console.""" self._thread.start() try: code.interact("", None, self._name_space) except KeyboardInterrupt: pass self._object_stop() self._thread.join(ObjectConsole.TIMEOUT) if self._thread.isAlive(): raise ConsoleError, "Worker Thread still alive"<|fim▁end|>
<|file_name|>9120015.js<|end_file_name|><|fim▁begin|>/* This file is part of the OdinMS Maple Story Server Copyright (C) 2008 Patrick Huy <[email protected]> Matthias Butz <[email protected]> Jan Christian Meyer <[email protected]> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License version 3 as published by the Free Software Foundation. You may not use, modify or distribute this program under any other version of the GNU Affero General Public License. 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/>. */ /** -- Odin JavaScript -------------------------------------------------------------------------------- Konpei - Showa Town(801000000) -- By --------------------------------------------------------------------------------------------- Information -- Version Info ----------------------------------------------------------------------------------- 1.1 - Fixed by Moogra 1.0 - First Version by Information --------------------------------------------------------------------------------------------------- **/ function start() { cm.sendSimple ("What do you want from me?\r #L0##bGather up some information on the hideout.#l\r\n#L1#Take me to the hideout#l\r\n#L2#Nothing#l#k"); } function action(mode, type, selection) { if (mode < 1) { cm.dispose(); } else { status++; if (status == 1) { if (selection == 0) { cm.sendNext("I can take you to the hideout, but the place is infested with thugs looking for trouble. You'll need to be both incredibly strong and brave to enter the premise. At the hideaway, you'll find the Boss that controls all the other bosses around this area. It's easy to get to the hideout, but the room on the top floor of the place can only be entered ONCE a day. The Boss's Room is not a place to mess around. I suggest you don't stay there for too long; you'll need to swiftly take care of the business once inside. The boss himself is a difficult foe, but you'll run into some incredibly powerful enemies on you way to meeting the boss! It ain't going to be easy."); cm.dispose(); } else if (selection == 1) cm.sendNext("Oh, the brave one. I've been awaiting your arrival. If these\r\nthugs are left unchecked, there's no telling what going to\r\nhappen in this neighborhood. Before that happens, I hope\r\nyou take care of all them and beat the boss, who resides\r\non the 5th floor. You'll need to be on alert at all times, since\r\nthe boss is too tough for even wisemen to handle.\r\nLooking at your eyes, however, I can see that eye of the\r\ntiger, the eyes that tell me you can do this. Let's go!"); else { cm.sendOk("I'm a busy person! Leave me alone if that's all you need!"); cm.dispose(); }<|fim▁hole|> } } }<|fim▁end|>
} else { cm.warp(801040000); cm.dispose();
<|file_name|>test_insert.py<|end_file_name|><|fim▁begin|>import pytest from etcdb import OperationalError from etcdb.lock import WriteLock def test_insert(cursor): cursor.execute('CREATE TABLE t1(id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, name VARCHAR(255))') cursor.execute("INSERT INTO t1(id, name) VALUES (1, 'aaa')") cursor.execute("INSERT INTO t1(id, name) VALUES (2, 'bbb')") cursor.execute("INSERT INTO t1(id, name) VALUES (3, 'ccc')") cursor.execute("SELECT id, name FROM t1") assert cursor.fetchall() == ( ('1', 'aaa'), ('2', 'bbb'), ('3', 'ccc'), ) def test_insert_wrong_lock_raises(cursor):<|fim▁hole|> with pytest.raises(OperationalError): cursor.execute("INSERT INTO t1(id, name) VALUES (2, 'bbb') USE LOCK 'foo'") def test_insert_with_lock(cursor, etcdb_connection): cursor.execute('CREATE TABLE t1(id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, name VARCHAR(255))') cursor.execute("INSERT INTO t1(id, name) VALUES (1, 'aaa')") lock = WriteLock(etcdb_connection.client, 'foo', 't1') lock.acquire() cursor.execute("INSERT INTO t1(id, name) VALUES (2, 'bbb') USE LOCK '%s'" % lock.id) lock.release() cursor.execute("SELECT id, name FROM t1 WHERE id = 2") assert cursor.fetchall() == ( ('2', 'bbb'), ) def test_insert_doesnt_release_lock(cursor, etcdb_connection): cursor.execute('CREATE TABLE t1(id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, name VARCHAR(255))') cursor.execute("INSERT INTO t1(id, name) VALUES (1, 'aaa')") lock = WriteLock(etcdb_connection.client, 'foo', 't1') lock.acquire(ttl=0) cursor.execute("UPDATE t1 SET name = 'bbb' WHERE id = 1 USE LOCK '%s'" % lock.id) with pytest.raises(OperationalError): cursor.execute("UPDATE t1 SET name = 'bbb' WHERE id = 1")<|fim▁end|>
cursor.execute('CREATE TABLE t1(id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, name VARCHAR(255))') cursor.execute("INSERT INTO t1(id, name) VALUES (1, 'aaa')")
<|file_name|>search-result-by-id.js<|end_file_name|><|fim▁begin|>import { LOAD_SEARCH_RESULT_SUCCESS, CLEAR_SEARCH_RESULTS, } from 'actions/search';<|fim▁hole|>import { createActionHandlers } from 'utils/reducer/actions-handlers'; const actionHandlers = {}; export function loadSearchResultSuccess(state, searchResultsList) { return searchResultsList.reduce((acc, result) => { return { ...acc, [result.id]: result, }; }, {}); } export function clearSearchResult() { return {}; } actionHandlers[LOAD_SEARCH_RESULT_SUCCESS] = loadSearchResultSuccess; actionHandlers[CLEAR_SEARCH_RESULTS] = clearSearchResult; export default createActionHandlers(actionHandlers);<|fim▁end|>
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from io import BytesIO from django import forms from django.http import HttpResponse from django.template import Context, Template from braces.views import LoginRequiredMixin from django.views.generic import DetailView, ListView from django.views.decorators.http import require_http_methods from django.contrib import messages from django.shortcuts import render, redirect from django.conf import settings from reportlab.pdfgen.canvas import Canvas from reportlab.lib.units import inch from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib.pagesizes import letter, landscape from reportlab.platypus import Spacer from reportlab.platypus import Frame from reportlab.platypus import Paragraph from reportlab.platypus import PageTemplate from reportlab.platypus import BaseDocTemplate from environ import Env from members.models import Member @require_http_methods(['GET', 'POST']) def member_list(request): env = Env() MEMBERS_PASSWORD = env('MEMBERS_PASSWORD') # handle form submission if request.POST: pw_form = PasswordForm(request.POST) if pw_form.is_valid() and pw_form.cleaned_data['password'] == MEMBERS_PASSWORD: request.session['password'] = pw_form.cleaned_data['password'] return redirect('members:member_list') messages.error(request, "The password you entered was incorrect, please try again.") # form not being submitted, check password if (request.session.get('password') and request.session['password'] == MEMBERS_PASSWORD): member_list = Member.objects.all() return render(request, 'members/member_list.html', { 'member_list': member_list, }) # password is wrong, render form pw_form = PasswordForm() return render(request, 'members/members_password_form.html', { 'pw_form': pw_form, }) class PasswordForm(forms.Form): password = forms.CharField(max_length=20, widget=forms.PasswordInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter Password', })) def build_frames(pwidth, pheight, ncols): frames = [] for i in range(ncols): f = Frame(x1=(i*((pwidth-30) / ncols)+15), y1=0, width=((pwidth-30) / ncols), height=pheight+2, leftPadding=15, rightPadding=15, topPadding=15, bottomPadding=15, showBoundary=True) frames.append(f) frames[0].showBoundary=False frames[3].showBoundary=False return frames def member_list_pdf(request): response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="memberlist.pdf"' buffer = BytesIO() NCOLUMNS = 4 PAGE_WIDTH, PAGE_HEIGHT = landscape(letter)<|fim▁hole|> ptemplate = PageTemplate(frames=build_frames(PAGE_WIDTH, PAGE_HEIGHT, NCOLUMNS)) doc = BaseDocTemplate( filename=buffer, pagesize=landscape(letter), pageTemplates=[ptemplate], showBoundary=0, leftMargin=inch, rightMargin=inch, topMargin=inch, bottomMargin=inch, allowSplitting=0, title='SSIP209 Members Listing', author='Max Shkurygin', _pageBreakQuick=1, encrypt=None) template = Template(""" <font size="14"><strong>{{ member.last_name }}, {{ member.first_name }}</strong></font> <br/> {% if member.address or member.town %} {{ member.address }}<br/> {% if member.town %} {{ member.town }} NY <br/>{% endif %} {% endif %} {% if member.homephone %} (Home) {{ member.homephone }} <br/> {% endif %} {% if member.cellphone %} (Cell) {{ member.cellphone }} <br/> {% endif %} {% if member.email %} Email: {{ member.email }} <br/> {% endif %} {% if member.hobbies %} <strong>My Hobbies</strong>: {{ member.hobbies }} <br/> {% endif %} {% if member.canhelp %} <strong>I can help with</strong>: {{ member.canhelp }} <br/> {% endif %} {% if member.needhelp %} <strong>I could use help with</strong>: {{ member.needhelp }} <br/> {% endif %} """) content = [] for member in Member.objects.all(): context = Context({"member": member}) p = Paragraph(template.render(context), styles["Normal"]) content.append(p) content.append(Spacer(1, 0.3*inch)) doc.build(content) pdf = buffer.getvalue() buffer.close() response.write(pdf) return response<|fim▁end|>
styles = getSampleStyleSheet()
<|file_name|>memprof.py<|end_file_name|><|fim▁begin|>from __future__ import print_function, division, unicode_literals from pprint import pprint from itertools import groupby from functools import wraps from collections import namedtuple, deque # OrderedDict was added in 2.7. ibm6 still uses python2.6 try: from collections import OrderedDict except ImportError: from .ordereddict import OrderedDict def group_entries_bylocus(entries): d = {} for e in entries: if e.locus not in d: d[e.locus] = [e] else: d[e.locus].append(e) return d class Entry(namedtuple("Entry", "vname, ptr, action, size, file, func, line, tot_memory, sidx")): @classmethod def from_line(cls, line, sidx): args = line.split() args.append(sidx) return cls(*args) def __new__(cls, *args): """Extends the base class adding type conversion of arguments.""" # write(logunt,'(a,t60,a,1x,2(i0,1x),2(a,1x),2(i0,1x))')& # trim(vname), trim(act), addr, isize, trim(basename(file)), trim(func), line, memtot_abi%memory return super(cls, Entry).__new__(cls, vname=args[0], action=args[1], ptr=int(args[2]), size=int(args[3]), file=args[4], func=args[5], line=int(args[6]),<|fim▁hole|> def __repr__(self): return self.as_repr(with_addr=True) def as_repr(self, with_addr=True): if with_addr: return "<var=%s, %s@%s:%s:%s, addr=%s, size=%d, idx=%d>" % ( self.vname, self.action, self.file, self.func, self.line, hex(self.ptr), self.size, self.sidx) else: return "<var=%s, %s@%s:%s:%s, size=%d, idx=%d>" % ( self.vname, self.action, self.file, self.func, self.line, self.size, self.sidx) @property def basename(self): return self.vname.split("%")[-1] @property def isalloc(self): """True if entry represents an allocation.""" return self.action == "A" @property def isfree(self): """True if entry represents a deallocation.""" return self.action == "D" @property def iszerosized(self): """True if this is a zero-sized alloc/free.""" return self.size == 0 @property def locus(self): """This is almost unique""" return self.func + "@" + self.file def frees_onheap(self, other): if (not self.isfree) or other.isalloc: return False if self.size + other.size != 0: return False return True def frees_onstack(self, other): if (not self.isfree) or other.isalloc: return False if self.size + other.size != 0: return False if self.locus != other.locus: return False return True class Heap(dict): def show(self): print("=== HEAP OF LEN %s ===" % len(self)) if not self: return # for p, elist in self.items(): pprint(self, indent=4) print("") def pop_alloc(self, entry): if not entry.isfree: return 0 elist = self.get[entry.ptr] if elist is None: return 0 for i, olde in elist: if entry.size + olde.size != 0: elist.pop(i) return 1 return 0 class Stack(dict): def show(self): print("=== STACK OF LEN %s ===)" % len(self)) if not self: return pprint(self) print("") def catchall(method): @wraps(method) def wrapper(*args, **kwargs): self = args[0] try: return method(*args, **kwargs) except Exception as exc: # Add info on file and re-raise. msg = "Exception while parsing file: %s\n" % self.path raise exc.__class__(msg + str(exc)) return wrapper class AbimemParser(object): def __init__(self, path): self.path = path #def __str__(self): # lines = [] # app = lines.append # return "\n".join(lines) @catchall def summarize(self): with open(self.path, "rt") as fh: l = fh.read() print(l) @catchall def find_small_allocs(self, nbytes=160): """Zero sized allocations are not counted.""" smalles = [] with open(self.path, "rt") as fh: for lineno, line in enumerate(fh): if lineno == 0: continue e = Entry.from_line(line, lineno) if not e.isalloc: continue if 0 < e.size <= nbytes: smalles.append(e) pprint(smalles) return smalles @catchall def find_intensive(self, threshold=2000): d = {} with open(self.path, "rt") as fh: for lineno, line in enumerate(fh): if lineno == 0: continue e = Entry.from_line(line, lineno) loc = e.locus if loc not in d: d[loc] = [e] else: d[loc].append(e) # Remove entries below the threshold and perform DSU sort dsu_list = [(elist, len(elist)) for _, elist in d.items() if len(elist) >= threshold] intensive = [t[0] for t in sorted(dsu_list, key=lambda x: x[1], reverse=True)] for elist in intensive: loc = elist[0].locus # assert all(e.locus == loc for e in elist) print("[%s] has %s allocations/frees" % (loc, len(elist))) return intensive #def show_peaks(self): @catchall def find_zerosized(self): elist = [] eapp = elist.append for e in self.yield_all_entries(): if e.size == 0: eapp(e) if elist: print("Found %d zero-sized entries:" % len(elist)) pprint(elist) else: print("No zero-sized found") return elist @catchall def find_weird_ptrs(self): elist = [] eapp = elist.append for e in self.yield_all_entries(): if e.ptr <= 0: eapp(e) if elist: print("Found %d weird entries:" % len(elist)) pprint(elist) else: print("No weird entries found") return elist def yield_all_entries(self): with open(self.path, "rt") as fh: for lineno, line in enumerate(fh): if lineno == 0: continue yield Entry.from_line(line, lineno) @catchall def find_peaks(self, maxlen=20): # the deque is bounded to the specified maximum length. Once a bounded length deque is full, # when new items are added, a corresponding number of items are discarded from the opposite end. peaks = deque(maxlen=maxlen) for e in self.yield_all_entries(): size = e.size if size == 0 or not e.isalloc: continue if len(peaks) == 0: peaks.append(e); continue # TODO: Should remove redondant entries. if size > peaks[0].size: peaks.append(e) peaks = deque(sorted(peaks, key=lambda x: x.size), maxlen=maxlen) peaks = deque(sorted(peaks, key=lambda x: x.size, reverse=True), maxlen=maxlen) for peak in peaks: print(peak) return peaks @catchall def plot_memory_usage(self, show=True): memory = [e.tot_memory for e in self.yield_all_entries()] import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(1,1,1) ax.plot(memory) if show: plt.show() return fig #def get_dataframe(self): # import pandas as pd # frame = pd.DataFrame() # return frame @catchall def find_memleaks(self): heap, stack = Heap(), Stack() reallocs = [] with open(self.path, "rt") as fh: for lineno, line in enumerate(fh): if lineno == 0: continue newe = Entry.from_line(line, lineno) p = newe.ptr if newe.size == 0: continue # Store new entry in list if the ptr is not in d # else we check if there's an allocation that matches a previous allocation # (zero-sized arrays are not included) # else there's a possible memory leak or some undected problems. if p not in heap: if newe.isalloc: heap[p] = [newe] else: # Likely reallocation reallocs.append(newe) else: if newe.isfree and len(heap[p]) == 1 and heap[p][0].size + newe.size == 0: heap.pop(p) else: # In principle this should never happen but there are exceptions: # # 1) The compiler could decide to put the allocatable on the stack # In this case the ptr reported by gfortran is 0. # # 2) The allocatable variable is "reallocated" by the compiler (F2003). # Example: # # allocate(foo(2,1)) ! p0 = &foo # foo = reshape([0,0], [2,1]) ! p1 = &foo. Reallocation of the LHS. # ! Use foo(:) to avoid that # deallocate(foo) ! p2 = &foo # # In this case, p2 != p0 #print("WARN:", newe.ptr, newe, "ptr already on the heap") #print("HEAP:", heap[newe.ptr]) locus = newe.locus if locus not in stack: stack[locus] = [newe] else: #if newe.ptr != 0: print(newe) stack_loc = stack[locus] ifind = -1 for i, olde in enumerate(stack_loc): if newe.frees_onstack(olde): ifind = i break if ifind != -1: stack_loc.pop(ifind) #else: # print(newe) #if p == 0: # stack[p] = newe #else: # print("varname", newe.vname, "in heap with size ",newe.size) # for weirde in heap[p]: # print("\tweird entry:", weirde) # heap[p].append(newe) if False and heap: # Possible memory leaks. count = -1 keyfunc = lambda e: abs(e.size) for a, entries in heap.items(): count += 1 entries = [e for e in entries if e.size != 0] entries = sorted(entries, key=keyfunc) #if any(int(e.size) != 0 for e in l): #msizes = [] for key, group in groupby(entries, keyfunc): group = list(group) #print([e.name for e in g]) pos_size = [e for e in group if e.size >0] neg_size = [e for e in group if e.size <0] if len(pos_size) != len(neg_size): print("key", key) for e in group: print(e) #print(list(g)) #for i, e in enumerate(entries): # print("\t[%d]" % i, e) #print("Count=%d" % count, 60 * "=") if heap: heap.show() if stack: stack.show() if reallocs: print("Possible reallocations:") pprint(reallocs) return len(heap) + len(stack) + len(reallocs)<|fim▁end|>
tot_memory=int(args[7]), sidx=args[8], )
<|file_name|>blink.py<|end_file_name|><|fim▁begin|>import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) <|fim▁hole|> try: while True: GPIO.output(ledpin, 1) time.sleep(0.5) GPIO.output(ledpin, 0) time.sleep(0.5) except KeyboardInterrupt: GPIO.cleanup()<|fim▁end|>
ledpin = 18 GPIO.setup(ledpin, GPIO.OUT)
<|file_name|>rgstry_test.cpp<|end_file_name|><|fim▁begin|>/* Copyright (C) 1999 Claude SIMON (http://q37.info/contact/). This file is part of the Epeios framework. The Epeios framework 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. The Epeios framework 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 the Epeios framework. If not, see <http://www.gnu.org/licenses/><|fim▁hole|>#include <string.h> #include "rgstry.h" #include "err.h" #include "cio.h" using cio::CIn; using cio::COut; using cio::CErr; void Generic( int argc, char *argv[] ) { qRH qRB qRR qRT qRE } int main( int argc, char *argv[] ) { qRFH qRFB COut << "Test of library " << RGSTRY_NAME << ' ' << __DATE__" "__TIME__"\n"; qRFR qRFT qRFE return ERRExitValue; }<|fim▁end|>
*/ #include <stdio.h> #include <stdlib.h>
<|file_name|>configuration.js<|end_file_name|><|fim▁begin|>'use strict'; angular.module('springangularwayApp') .config(function ($stateProvider) { $stateProvider .state('configuration', { parent: 'admin', url: '/configuration', data: { roles: ['ROLE_ADMIN'],<|fim▁hole|> views: { 'content@': { templateUrl: 'scripts/app/admin/configuration/configuration.html', controller: 'ConfigurationController' } }, resolve: { translatePartialLoader: ['$translate', '$translatePartialLoader', function ($translate, $translatePartialLoader) { $translatePartialLoader.addPart('configuration'); return $translate.refresh(); }] } }); });<|fim▁end|>
pageTitle: 'configuration.title' },
<|file_name|>commit_pending.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # # Copyright © 2012 - 2014 Michal Čihař <[email protected]> # # This file is part of Weblate <http://weblate.org/> # # 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/>. # from weblate.trans.management.commands import WeblateLangCommand from django.utils import timezone from datetime import timedelta from optparse import make_option <|fim▁hole|> option_list = WeblateLangCommand.option_list + ( make_option( '--age', action='store', type='int', dest='age', default=24, help='Age of changes to commit in hours (default is 24 hours)' ), ) def handle(self, *args, **options): age = timezone.now() - timedelta(hours=options['age']) for translation in self.get_translations(*args, **options): if not translation.git_needs_commit(): continue last_change = translation.get_last_change() if last_change is None: continue if last_change > age: continue if int(options['verbosity']) >= 1: print 'Committing %s' % translation translation.commit_pending(None)<|fim▁end|>
class Command(WeblateLangCommand): help = 'commits pending changes older than given age'
<|file_name|>api.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2017 CERN. # # Invenio 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. # # Invenio 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 Invenio; if not, write to the # Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307, USA. # # In applying this license, CERN does not # waive the privileges and immunities granted to it by virtue of its status # as an Intergovernmental Organization or submit itself to any jurisdiction. """Record API.""" from __future__ import absolute_import, print_function import uuid import os from invenio_records.api import Record from invenio_jsonschemas import current_jsonschemas from .minters import kwid_minter class Keyword(Record): """Define API for a keywords.""" _schema = 'keywords/keyword-v1.0.0.json' @classmethod<|fim▁hole|> """Create a keyword.""" data['$schema'] = current_jsonschemas.path_to_url(cls._schema) key_id = data.get('key_id', None) name = data.get('name', None) data.setdefault('deleted', False) if not id_: id_ = uuid.uuid4() kwid_minter(id_, data) data['suggest_name'] = { 'input': name, 'payload': { 'key_id': key_id, 'name': name }, } return super(Keyword, cls).create(data=data, id_=id_, **kwargs) @property def ref(self): """Get the url.""" return Keyword.get_ref(self['key_id']) @classmethod def get_id(cls, ref): """Get the ID from the reference.""" return os.path.basename(ref) @classmethod def get_ref(cls, id_): """Get reference from an ID.""" return 'https://cds.cern.ch/api/keywords/{0}'.format(str(id_)) class Category(Record): """Define API for a category.""" _schema = 'categories/category-v1.0.0.json' @classmethod def create(cls, data, id_=None, **kwargs): """Create a category.""" data['$schema'] = current_jsonschemas.path_to_url(cls._schema) data['suggest_name'] = { 'input': data.get('name', None), 'payload': { 'types': data.get('types', []) } } return super(Category, cls).create(data=data, id_=id_, **kwargs)<|fim▁end|>
def create(cls, data, id_=None, **kwargs):
<|file_name|>test.js<|end_file_name|><|fim▁begin|>import test from 'ava'; import escapeStringRegexp from './index.js'; test('main', t => { t.is( escapeStringRegexp('\\ ^ $ * + ? . ( ) | { } [ ]'), '\\\\ \\^ \\$ \\* \\+ \\? \\. \\( \\) \\| \\{ \\} \\[ \\]' ); }); test('escapes `-` in a way compatible with PCRE', t => {<|fim▁hole|> ); }); test('escapes `-` in a way compatible with the Unicode flag', t => { t.regex( '-', new RegExp(escapeStringRegexp('-'), 'u') ); });<|fim▁end|>
t.is( escapeStringRegexp('foo - bar'), 'foo \\x2d bar'
<|file_name|>field_of_vision.cpp<|end_file_name|><|fim▁begin|>#include "field_of_vision.hpp" using namespace engine; FieldOfVision::FieldOfVision(double x, double y, int size, double angle){ range = size; total_angle = angle; catch_effect = new Audio("assets/sounds/GUARDAVIU.wav", "EFFECT", 128); active = true; //not including centerLine number_of_lines = 10; createLines(x,y,range); } int FieldOfVision::getAngle(){ return center_line->getAngle(); } void FieldOfVision::resetLines(){ //free(centerLine); for(auto line: lines){ free(line); } lines.clear(); } void FieldOfVision::deactivate(){ active = false; } bool FieldOfVision::isActive(){ return active; } void FieldOfVision::createLines(double x, double y, int size){ resetLines(); center_line = new Line(x,y,size, 0); double angle_inc = ((double)total_angle/2.0)/((double)number_of_lines/2.0); for(double i = 0, line_angle = angle_inc; i<number_of_lines/2; i+=1, line_angle += angle_inc) { Line* new_upper_line = new Line(center_line); new_upper_line->rotateLine(line_angle); lines.push_back(new_upper_line); Line* new_lower_line = new Line(center_line); new_lower_line->rotateLine(-line_angle); lines.push_back(new_lower_line); } } void FieldOfVision::updateCenter(double inc_x, double inc_y){ center_line->updatePosition(inc_x,inc_y); for(auto line: lines){ line->updatePosition(inc_x,inc_y); } } void FieldOfVision::draw(){ if(active){ AnimationManager::instance.addFieldOfVision(this); } } void FieldOfVision::incrementAngle(double angle){ center_line->rotateLine(angle); for(auto line:lines){ line->rotateLine(angle); } } void FieldOfVision::setAngle(double angle){ center_line->changeAngleTo(angle); double angle_inc = ((double)total_angle/2.0)/((double)number_of_lines/2.0); double line_angle = angle; int i = 0; bool inverteu = false; for(auto line:lines){ if(i >= number_of_lines/2 && !inverteu){ line_angle = angle; angle_inc *= (-1);<|fim▁hole|> line->changeAngleTo(line_angle); i++; } } std::vector<Line*> FieldOfVision::getLines(){ std::vector<Line*> lines_return; lines_return.push_back(center_line); for(auto line:lines){ lines_return.push_back(line); } return lines_return; } int FieldOfVision::getRange(){ return range; } void FieldOfVision::playEffect(){ catch_effect->play(0); }<|fim▁end|>
inverteu = true; } line_angle -= angle_inc;
<|file_name|>bubble_sort.rs<|end_file_name|><|fim▁begin|>//! Module contains pure implementations of bubble sort algorithm. //! //! * `sort` - is non distructive function (does not affects on input sequence) //! * `mut_sort` - function with side effects (modify input sequence) //! //! It's better to use first one in functional style, second - in OOP-style /// Pure implementation of Bubble sort algorithm /// /// # Examples /// /// ``` /// use algorithms::sorts::bubble_sort::sort; /// use algorithms::sorts::utils::is_sorted; /// /// assert!(is_sorted(&sort(&[0, 5, 3, 2, 2]))); /// assert!(is_sorted(&sort(&[-1, -5, -10, 105]))); /// ``` pub fn sort<T: Ord + Clone>(list: &[T]) -> Vec<T> { let mut sorted_list = list.clone().to_vec(); let length = sorted_list.len(); for i in 0..length { let mut swapped = false; for j in 0..length - i - 1 { if sorted_list[j] > sorted_list[j + 1] { sorted_list.swap(j, j + 1); swapped = true; } } if swapped == false {<|fim▁hole|> return sorted_list; } /// Pure implementation of bubble sort algorithm. Side-effects version /// Modifies input sequense /// /// # Examples /// /// ``` /// use algorithms::sorts::bubble_sort::mut_sort; /// use algorithms::sorts::utils::is_sorted; /// /// let mut test_sequence = [0, 5, 3, 2, 2]; /// mut_sort(&mut test_sequence); /// assert!(is_sorted(&test_sequence)); /// /// let mut test_sequence = [0, 5, 3, 2, 2]; /// mut_sort(&mut test_sequence); /// assert!(is_sorted(&test_sequence)); /// ``` pub fn mut_sort<T: Ord>(list: &mut [T]) { for n in (0..(list.len() as isize + 1)).rev() { for m in 1..(n as usize) { if list[m] < list[m - 1] { list.swap(m, m - 1); } } } } #[cfg(test)] mod tests { use super::*; use super::super::utils::is_sorted; #[test] fn sort_numbers() { let empty_vec: Vec<i32> = Vec::new(); assert!(is_sorted(&sort(&[0, 5, 3, 2, 2]))); assert!(is_sorted(&sort(&empty_vec))); assert!(is_sorted(&sort(&[-1, -5, -10, 105]))); } #[test] fn sort_chars() { assert!(is_sorted(&sort(&['a', 'r', 'b']))) } #[test] fn mut_sort_numbers() { let mut test_vector = vec![0, 5, 2, 3, 2]; mut_sort(&mut test_vector); assert!(is_sorted(&test_vector)); let mut test_vector: Vec<i32> = Vec::new(); mut_sort(&mut test_vector); assert!(is_sorted(&test_vector)); } #[test] fn mut_sort_chars() { let mut test_vector = vec!['a', 'r', 'b']; mut_sort(&mut test_vector); assert!(is_sorted(&test_vector)); } }<|fim▁end|>
break; } }
<|file_name|>io.rs<|end_file_name|><|fim▁begin|>/*! # Input and Output This module holds a single struct (`FC`) that keeps what would otherwise be global state of the running process. All the open file handles and sockets are stored here as well as helper functions to properly initialize the program and all the necessary packing and work to receive, log, and send any data. In many ways this is the guts of the flight computer. */ extern crate byteorder; use std::net::UdpSocket; use std::net::SocketAddrV4; use std::net::Ipv4Addr; use std::io::Error; use std::io::Cursor; use std::fs::File; use std::io::Write; use std::time; use self::byteorder::{ReadBytesExt, WriteBytesExt, BigEndian}; /// Ports for data const PSAS_LISTEN_UDP_PORT: u16 = 36000; /// Port for outgoing telemetry const PSAS_TELEMETRY_UDP_PORT: u16 = 35001; /// Expected port for ADIS messages pub const PSAS_ADIS_PORT: u16 = 35020; /// Maximum size of single telemetry packet const P_LIMIT: usize = 1432; /// Size of PSAS Packet header const HEADER_SIZE: usize = 12; /// Message name (ASCII: SEQN) const SEQN_NAME: [u8;4] = [83, 69, 81, 78]; /// Sequence Error message size (bytes) pub const SIZE_OF_SEQE: usize = 10; /// Sequence Error message name (ASCII: SEQE) pub const SEQE_NAME: [u8;4] = [83, 69, 81, 69]; /// Flight Computer IO. /// /// Internally holds state for this implementation of the flight computer. /// This includes time (nanosecond counter from startup), a socket for /// listening for incoming data, a socket for sending data over the telemetry /// link, a log file, a running count of telemetry messages sent and a buffer /// for partly built telemetry messages. /// /// To initialize use the Default trait: /// /// # Example /// /// ```no_run /// use rust_fc::io; /// /// let mut flight_computer: io::FC = Default::default(); /// ``` pub struct FC { /// Instant we started boot_time: time::Instant, /// Socket to listen on for messages. fc_listen_socket: UdpSocket, /// Socket to send telemetry. telemetry_socket: UdpSocket, /// File to write data to. fc_log_file: File, /// Current count of telemetry messages sent. sequence_number: u32, /// Buffer of messages to build a telemetry Packet. telemetry_buffer: Vec<u8>, } // Reusable code for packing header into bytes fn pack_header(name: [u8; 4], time: time::Duration, message_size: usize) -> [u8; HEADER_SIZE] { let mut buffer = [0u8; HEADER_SIZE]; { let mut header = Cursor::<&mut [u8]>::new(&mut buffer); // Fields: // ID (Four character code) header.write(&name).unwrap(); // Timestamp, 6 bytes nanoseconds from boot let nanos: u64 = (time.as_secs() * 1000000000) + time.subsec_nanos() as u64; let mut time_buffer = [0u8; 8]; { let mut t = Cursor::<&mut [u8]>::new(&mut time_buffer);<|fim▁hole|> header.write(&time_buffer[2..8]).unwrap(); // Size: header.write_u16::<BigEndian>(message_size as u16).unwrap(); } buffer } impl Default for FC { fn default () -> FC { // Boot time let boot_time = time::Instant::now(); let fc_listen_socket: UdpSocket; let telemetry_socket: UdpSocket; let fc_log_file: File; // Try and open listen socket match UdpSocket::bind(("0.0.0.0", PSAS_LISTEN_UDP_PORT)) { Ok(socket) => { fc_listen_socket = socket; }, Err(e) => { panic!(e) }, } // Try and open telemetry socket match UdpSocket::bind("0.0.0.0:0") { Ok(socket) => { telemetry_socket = socket; }, Err(e) => { panic!(e) }, } // Try and open log file, loop until we find a name that's not taken let mut newfilenum = 0; loop { let filename = format!("logfile-{:03}", newfilenum); match File::open(filename) { // If this works, keep going Ok(_) => { newfilenum += 1; }, // If this fails, make a new file Err(_) => { break; } } } // We got here, so open the file match File::create(format!("logfile-{:03}", newfilenum)) { Ok(file) => { fc_log_file = file; }, Err(e) => { panic!(e) }, } // Put first sequence number (always 0) in the telemetry buffer. let mut telemetry_buffer = Vec::with_capacity(P_LIMIT); telemetry_buffer.extend_from_slice(&[0, 0, 0, 0]); // Initialise let mut fc = FC { boot_time: boot_time, fc_listen_socket: fc_listen_socket, telemetry_socket: telemetry_socket, fc_log_file: fc_log_file, sequence_number: 0, telemetry_buffer: telemetry_buffer, }; // Write log header fc.log_message(&[0, 0, 0, 0], SEQN_NAME, time::Duration::new(0, 0), 4).unwrap(); fc } } impl FC { /// Listen for messages from the network. /// /// This makes a blocking `read` call on the `fc_listen_socket`, waiting /// for any message from the outside world. Once received, it will deal /// with the sequence numbers in the header of the data and write the raw /// message to the passed in buffer. /// /// # Returns: /// /// An Option containing a tuple of data from the socket. The tuple /// contains: /// /// - **Sequence Number**: Sequence number from the header of the data packet /// - **Port**: Which port the data was sent _from_ /// - **Time**: The time that the message was received /// - **Message**: A message buffer that has raw bytes off the wire /// /// # Example /// /// ```no_run /// use rust_fc::io; /// /// let mut flight_computer: io::FC = Default::default(); /// /// if let Some((seqn, recv_port, recv_time, message)) = flight_computer.listen() { /// // Do something here with received data /// } /// ``` pub fn listen(&self) -> Option<(u32, u16, time::Duration, [u8; P_LIMIT - 4])> { // A buffer to put data in from the port. // Should at least be the size of telemetry message. let mut message_buffer = [0u8; P_LIMIT]; // Read from the socket (blocking!) // message_buffer gets filled and we get the number of bytes read // along with and address that the message came from match self.fc_listen_socket.recv_from(&mut message_buffer) { Ok((_, recv_addr)) => { // Get time for incoming data let recv_time = time::Instant::now().duration_since(self.boot_time); // First 4 bytes are the sequence number let mut buf = Cursor::new(&message_buffer[..4]); let seqn = buf.read_u32::<BigEndian>().unwrap(); // Rest of the bytes may be part of a message let mut message = [0u8; P_LIMIT - 4]; message.clone_from_slice(&message_buffer[4..P_LIMIT]); Some((seqn, recv_addr.port(), recv_time, message)) }, Err(_) => { None }, // continue } } /// Log a message to disk. /// /// All data we care about can be encoded as a "message". The original code /// defined messages as packed structs in C. The reasoning was to be as /// space-efficient as reasonably possible given that we are both disk-size /// and bandwidth constrained. /// /// This function takes a message (as an array of bytes) and writes it to /// disk. /// /// ## Parameters: /// /// - **message**: Byte array containing packed message /// - **name**: Byte array of the name for this message /// - **time**: Time of message /// - **message_size**: How many bytes to copy from the message array /// /// ## Returns: /// /// A Result with any errors. But we hope to never deal with a failure here /// (Greater care was taken in the original flight computer to not crash /// because of disk errors). pub fn log_message(&mut self, message: &[u8], name: [u8; 4], time: time::Duration, message_size: usize) -> Result<(), Error> { // Header: let header = pack_header(name, time, message_size); try!(self.fc_log_file.write(&header)); // message: try!(self.fc_log_file.write(&message[0..message_size])); Ok(()) } /// Send a message to the ground. /// /// All data we care about can be encoded as a "message". The original code /// defined messages as packed structs in C. The reasoning was to be as /// space-efficient as reasonably possible given that we are both disk-size /// and bandwidth constrained. /// /// This function takes a message (as an array of bytes) and queues it to /// be send out over the network once will fill the maximum size of a UDP /// packet. /// /// ## Parameters /// /// - **message**: Byte array containing packed message /// - **name**: Byte array of the name for this message /// - **time**: Time of message /// - **message_size**: How many bytes to copy from the message array /// pub fn telemetry(&mut self, message: &[u8], name: [u8; 4], time: time::Duration, message_size: usize) { // If we won't have room in the current packet, flush if (self.telemetry_buffer.len() + HEADER_SIZE + message_size) > P_LIMIT { self.flush_telemetry(); } // Header: let header = pack_header(name, time, message_size); self.telemetry_buffer.extend_from_slice(&header); // Message: self.telemetry_buffer.extend_from_slice(&message[0..message_size]); } /// This will actually send the now full and packed telemetry packet, /// and set us up for the next one. fn flush_telemetry(&mut self) { // Push out the door let telemetry_addr: SocketAddrV4 = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), PSAS_TELEMETRY_UDP_PORT); // When did we send this packet let send_time = time::Instant::now().duration_since(self.boot_time); self.telemetry_socket.send_to(&self.telemetry_buffer, telemetry_addr).unwrap(); // Increment SEQN self.sequence_number += 1; // Start telemetry buffer over self.telemetry_buffer.clear(); // Prepend with next sequence number let mut seqn = Vec::with_capacity(4); seqn.write_u32::<BigEndian>(self.sequence_number).unwrap(); self.telemetry_buffer.extend_from_slice(&mut seqn); // Keep track of sequence numbers in the flight computer log too self.log_message(&seqn, SEQN_NAME, send_time, 4).unwrap(); } } /// A sequence error message. /// /// When we miss a packet or get an out of order packet we should log that /// for future analysis. This stores a error and builds a log-able message. /// /// # Example /// /// ``` /// use rust_fc::io; /// /// let seqerror = io::SequenceError { /// port: 35020, /// expected: 12345, /// received: 12349, /// }; /// /// // Now you can log or send the message somewhere /// ``` pub struct SequenceError { /// Which port the packet error is from pub port: u16, /// Expected packet sequence number pub expected: u32, /// Actual received packet sequence number pub received: u32, } impl SequenceError { /// Return a copy of this struct as a byte array. /// /// The PSAS file and message type is always a byte array with big-endian /// representation of fields in a struct. pub fn as_message(&self) -> [u8; SIZE_OF_SEQE] { let mut buffer = [0u8; SIZE_OF_SEQE]; { let mut message = Cursor::<&mut [u8]>::new(&mut buffer); // Struct Fields: message.write_u16::<BigEndian>(self.port).unwrap(); message.write_u32::<BigEndian>(self.expected).unwrap(); message.write_u32::<BigEndian>(self.received).unwrap(); } buffer } }<|fim▁end|>
t.write_u64::<BigEndian>(nanos).unwrap(); } // Truncate to 6 least significant bytes
<|file_name|>CollinearOverlap.java<|end_file_name|><|fim▁begin|>/* * Copyright (c) 2008, Keith Woodward * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of Keith Woodward nor the names * of its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ package straightedge.geom.vision; import straightedge.geom.*; public class CollinearOverlap{ public KPolygon polygon; public int pointIndex; public int nextPointIndex; public KPolygon polygon2; public int point2Index; public CollinearOverlap(KPolygon polygon, int pointIndex, int nextPointIndex, KPolygon polygon2, int point2Index){ this.polygon = polygon; this.pointIndex = pointIndex; this.nextPointIndex = nextPointIndex; this.polygon2 = polygon2; this.point2Index = point2Index; } public KPolygon getPolygon() { return polygon; } public int getPointIndex() {<|fim▁hole|> return pointIndex; } public int getNextPointIndex() { return nextPointIndex; } public KPolygon getPolygon2() { return polygon2; } public int getPoint2Index() { return point2Index; } }<|fim▁end|>
<|file_name|>index.js<|end_file_name|><|fim▁begin|>/** * Created by ff on 2016/10/25. */ require('./style.css');<|fim▁hole|>}) module.exports = vm;<|fim▁end|>
var vm = avalon.define({ $id:'map'
<|file_name|>pixel_buffer.rs<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|>
//! Moved to the `texture` module. #![deprecated(note = "Moved to the `texture` module")] pub use texture::pixel_buffer::*;
<|file_name|>search_screen.py<|end_file_name|><|fim▁begin|>from base_screen import BaseScreen import pygame from ..graphic_utils import ListView,\ ScreenObjectsManager, TouchAndTextItem from ..input import InputManager from play_options import PlayOptions mode_track_name = 0 mode_album_name = 1 mode_artist_name = 2 class SearchScreen(BaseScreen): def __init__(self, size, base_size, manager, fonts, playqueues=None): BaseScreen.__init__(self, size, base_size, manager, fonts) self.list_view = ListView((0, self.base_size*2), ( self.size[0], self.size[1] - 3*self.base_size), self.base_size, manager.fonts['base']) self.results_strings = [] self.results = [] self.screen_objects = ScreenObjectsManager() self.query = "" self.playqueues = playqueues # Search button<|fim▁hole|> button = TouchAndTextItem(self.fonts['icon'], u" \ue986", (0, self.base_size), None, center=True) self.screen_objects.set_touch_object( "search", button) x = button.get_right_pos() # Query text text = TouchAndTextItem(self.fonts['base'], self.query, (0, 0), (self.size[0], self.base_size), center=True) self.screen_objects.set_touch_object("query", text) # Mode buttons button_size = ((self.size[0]-x)/3, self.base_size) self.mode_objects_keys = ["mode_track", "mode_album", "mode_artist"] # Track button button = TouchAndTextItem(self.fonts['base'], "Track", (x, self.base_size), (button_size[0], self.base_size), center=True) self.screen_objects.set_touch_object( self.mode_objects_keys[0], button) # Album button button = TouchAndTextItem(self.fonts['base'], "Album", (button_size[0]+x, self.base_size), button_size, center=True) self.screen_objects.set_touch_object( self.mode_objects_keys[1], button) # Artist button button = TouchAndTextItem(self.fonts['base'], "Artist", (button_size[0]*2+x, self.base_size), button_size, center=True) self.screen_objects.set_touch_object( self.mode_objects_keys[2], button) # Top Bar self.top_bar = pygame.Surface( (self.size[0], self.base_size * 2), pygame.SRCALPHA) self.top_bar.fill((38, 38, 38, 128)) self.mode = -1 self.set_mode(mode=mode_track_name) self.set_query("Search") self.play_options_dialog = None def should_update(self): return self.list_view.should_update() def update(self, screen, update_type, rects): screen.blit(self.top_bar, (0, 0)) self.screen_objects.render(screen) update_all = (update_type == BaseScreen.update_all) self.list_view.render(screen, update_all, rects) if self.play_options_dialog != None : self.play_options_dialog.render(screen, update_all, rects) def set_mode(self, mode=mode_track_name): if mode is not self.mode: self.mode = mode for key in self.mode_objects_keys: self.screen_objects.get_touch_object(key).\ set_active(False) self.screen_objects.get_touch_object( self.mode_objects_keys[self.mode]).set_active(True) def set_query(self, query=""): self.query = query self.screen_objects.get_touch_object("query").set_text( self.query, False) def search(self, query=None, mode=None): if query is not None: self.set_query(query) if mode is not None: self.set_mode(mode) if self.mode == mode_track_name: search_query = {'any': [self.query]} elif self.mode == mode_album_name: search_query = {'album': [self.query]} else: search_query = {'artist': [self.query]} if len(self.query) > 0: current_results = self.manager.core.library.search( search_query).get() self.results = [] self.results_strings = [] for backend in current_results: if mode == mode_track_name: iterable = backend.tracks elif mode == mode_album_name: iterable = backend.albums else: iterable = backend.artists for result in iterable: self.results.append(result) self.results_strings.append(result.name) self.list_view.set_list(self.results_strings) def touch_event(self, touch_event): if touch_event.type == InputManager.click: # check if user clicked in play options dialog if ((self.play_options_dialog != None) and (self.play_options_dialog.is_position_in_dialog(touch_event.current_pos))): # TODO the user clicked in the play options dialog, now do something with it (i.e. play song, add to queue, etc.) self.play_options_dialog.touch_event(touch_event) self.play_options_dialog = None #self.list_view.scroll_text(True) else: self.play_options_dialog = None clicked = self.list_view.touch_event(touch_event) if clicked is not None: #self.list_view.scroll_text(False) self.play_options_dialog = PlayOptions(self.size, self.base_size, self.manager, self.fonts, self.results[clicked].uri, self.playqueues) #self.manager.core.tracklist.clear() #self.manager.core.tracklist.add( # uri=self.results[clicked].uri) # javey: pull up play options dialog #self.manager.core.playback.play() else: clicked = self.screen_objects.get_touch_objects_in_pos( touch_event.down_pos) if len(clicked) > 0: clicked = clicked[0] if clicked == self.mode_objects_keys[0]: self.search(mode=0) if clicked == self.mode_objects_keys[1]: self.search(mode=1) if clicked == self.mode_objects_keys[2]: self.search(mode=2) if clicked == "query" or clicked == "search": self.manager.open_keyboard(self) elif touch_event.type == InputManager.long_click: # javey: TODO do something on long click if needed x = 0 else: pos = self.list_view.touch_event(touch_event) if pos is not None: self.screen_objects.get_touch_object(pos).set_selected() self.manager.core.tracklist.clear() self.manager.core.tracklist.add( uri=self.results[pos].uri) # self.manager.core.playback.play() def change_screen(self, direction): if direction == InputManager.right: if self.mode < 2: self.set_mode(self.mode+1) return True elif direction == InputManager.left: if self.mode > 0: self.set_mode(self.mode-1) return True else: self.manager.open_keyboard(self) return False def text_input(self, text): self.search(text, self.mode)<|fim▁end|>
<|file_name|>test_qwificlient.py<|end_file_name|><|fim▁begin|>from hearinglosssimulator.gui.wifidevice.wifidevicewidget import WifiDeviceWidget from hearinglosssimulator.gui.wifidevice.qwificlient import QWifiClient, ThreadAudioStream from hearinglosssimulator.gui.wifidevice.gui_debug_wifidevice import WindowDebugWifiDevice udp_ip = "192.168.1.1" udp_port = 6666 def test_qwificlient(): import pyqtgraph as pg client = QWifiClient(udp_ip=udp_ip, udp_port=udp_port) app = pg.mkQApp() win = WindowDebugWifiDevice(client=client) win.show()<|fim▁hole|> app.exec_() if __name__ =='__main__': test_qwificlient()<|fim▁end|>
<|file_name|>interfaces.py<|end_file_name|><|fim▁begin|># sqlalchemy/interfaces.py # Copyright (C) 2007-2013 the SQLAlchemy authors and contributors <see AUTHORS file> # Copyright (C) 2007 Jason Kirtland [email protected] # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """Deprecated core event interfaces. This module is **deprecated** and is superseded by the event system. """ from . import event, util class PoolListener(object): """Hooks into the lifecycle of connections in a :class:`.Pool`. .. note:: :class:`.PoolListener` is deprecated. Please refer to :class:`.PoolEvents`. Usage:: class MyListener(PoolListener): def connect(self, dbapi_con, con_record): '''perform connect operations''' # etc. # create a new pool with a listener p = QueuePool(..., listeners=[MyListener()]) # add a listener after the fact p.add_listener(MyListener()) # usage with create_engine() e = create_engine("url://", listeners=[MyListener()]) All of the standard connection :class:`~sqlalchemy.pool.Pool` types can accept event listeners for key connection lifecycle events: creation, pool check-out and check-in. There are no events fired when a connection closes. For any given DB-API connection, there will be one ``connect`` event, `n` number of ``checkout`` events, and either `n` or `n - 1` ``checkin`` events. (If a ``Connection`` is detached from its pool via the ``detach()`` method, it won't be checked back in.) These are low-level events for low-level objects: raw Python DB-API connections, without the conveniences of the SQLAlchemy ``Connection`` wrapper, ``Dialect`` services or ``ClauseElement`` execution. If you execute SQL through the connection, explicitly closing all cursors and other resources is recommended. Events also receive a ``_ConnectionRecord``, a long-lived internal ``Pool`` object that basically represents a "slot" in the connection pool. ``_ConnectionRecord`` objects have one public attribute of note: ``info``, a dictionary whose contents are scoped to the lifetime of the DB-API connection managed by the record. You can use this shared storage area however you like. There is no need to subclass ``PoolListener`` to handle events. Any class that implements one or more of these methods can be used as a pool listener. The ``Pool`` will inspect the methods provided by a listener object and add the listener to one or more internal event queues based on its capabilities. In terms of efficiency and function call overhead, you're much better off only providing implementations for the hooks you'll be using. """ @classmethod def _adapt_listener(cls, self, listener): """Adapt a :class:`.PoolListener` to individual :class:`event.Dispatch` events. """ listener = util.as_interface(listener, methods=('connect', 'first_connect', 'checkout', 'checkin')) if hasattr(listener, 'connect'): event.listen(self, 'connect', listener.connect) if hasattr(listener, 'first_connect'): event.listen(self, 'first_connect', listener.first_connect) if hasattr(listener, 'checkout'): event.listen(self, 'checkout', listener.checkout) if hasattr(listener, 'checkin'): event.listen(self, 'checkin', listener.checkin) def connect(self, dbapi_con, con_record): """Called once for each new DB-API connection or Pool's ``creator()``. dbapi_con A newly connected raw DB-API connection (not a SQLAlchemy ``Connection`` wrapper). con_record The ``_ConnectionRecord`` that persistently manages the connection """ def first_connect(self, dbapi_con, con_record): """Called exactly once for the first DB-API connection. dbapi_con A newly connected raw DB-API connection (not a SQLAlchemy ``Connection`` wrapper). con_record The ``_ConnectionRecord`` that persistently manages the connection """ def checkout(self, dbapi_con, con_record, con_proxy): """Called when a connection is retrieved from the Pool. dbapi_con A raw DB-API connection con_record The ``_ConnectionRecord`` that persistently manages the connection con_proxy The ``_ConnectionFairy`` which manages the connection for the span of the current checkout. If you raise an ``exc.DisconnectionError``, the current connection will be disposed and a fresh connection retrieved. Processing of all checkout listeners will abort and restart using the new connection. """ def checkin(self, dbapi_con, con_record): """Called when a connection returns to the pool. Note that the connection may be closed, and may be None if the connection has been invalidated. ``checkin`` will not be called for detached connections. (They do not return to the pool.) dbapi_con A raw DB-API connection con_record The ``_ConnectionRecord`` that persistently manages the connection """ class ConnectionProxy(object): """Allows interception of statement execution by Connections. .. note:: :class:`.ConnectionProxy` is deprecated. Please refer to :class:`.ConnectionEvents`. Either or both of the ``execute()`` and ``cursor_execute()`` may be implemented to intercept compiled statement and cursor level executions, e.g.:: class MyProxy(ConnectionProxy): def execute(self, conn, execute, clauseelement, *multiparams, **params): print "compiled statement:", clauseelement return execute(clauseelement, *multiparams, **params) def cursor_execute(self, execute, cursor, statement, parameters, context, executemany): print "raw statement:", statement return execute(cursor, statement, parameters, context) The ``execute`` argument is a function that will fulfill the default execution behavior for the operation. The signature illustrated in the example should be used. The proxy is installed into an :class:`~sqlalchemy.engine.Engine` via the ``proxy`` argument:: e = create_engine('someurl://', proxy=MyProxy()) """ @classmethod def _adapt_listener(cls, self, listener): def adapt_execute(conn, clauseelement, multiparams, params): def execute_wrapper(clauseelement, *multiparams, **params): return clauseelement, multiparams, params return listener.execute(conn, execute_wrapper, clauseelement, *multiparams, **params) event.listen(self, 'before_execute', adapt_execute) def adapt_cursor_execute(conn, cursor, statement, parameters, context, executemany): def execute_wrapper( cursor, statement, parameters, context, ): return statement, parameters return listener.cursor_execute( execute_wrapper, cursor, statement, parameters, context, executemany, ) event.listen(self, 'before_cursor_execute', adapt_cursor_execute) def do_nothing_callback(*arg, **kw): pass def adapt_listener(fn): def go(conn, *arg, **kw): fn(conn, do_nothing_callback, *arg, **kw) return util.update_wrapper(go, fn) event.listen(self, 'begin', adapt_listener(listener.begin)) event.listen(self, 'rollback', adapt_listener(listener.rollback)) event.listen(self, 'commit', adapt_listener(listener.commit)) event.listen(self, 'savepoint', adapt_listener(listener.savepoint)) event.listen(self, 'rollback_savepoint', adapt_listener(listener.rollback_savepoint)) event.listen(self, 'release_savepoint', adapt_listener(listener.release_savepoint)) event.listen(self, 'begin_twophase', adapt_listener(listener.begin_twophase)) event.listen(self, 'prepare_twophase', adapt_listener(listener.prepare_twophase)) event.listen(self, 'rollback_twophase', adapt_listener(listener.rollback_twophase)) event.listen(self, 'commit_twophase', adapt_listener(listener.commit_twophase)) <|fim▁hole|> def cursor_execute(self, execute, cursor, statement, parameters, context, executemany): """Intercept low-level cursor execute() events.""" return execute(cursor, statement, parameters, context) def begin(self, conn, begin): """Intercept begin() events.""" return begin() def rollback(self, conn, rollback): """Intercept rollback() events.""" return rollback() def commit(self, conn, commit): """Intercept commit() events.""" return commit() def savepoint(self, conn, savepoint, name=None): """Intercept savepoint() events.""" return savepoint(name=name) def rollback_savepoint(self, conn, rollback_savepoint, name, context): """Intercept rollback_savepoint() events.""" return rollback_savepoint(name, context) def release_savepoint(self, conn, release_savepoint, name, context): """Intercept release_savepoint() events.""" return release_savepoint(name, context) def begin_twophase(self, conn, begin_twophase, xid): """Intercept begin_twophase() events.""" return begin_twophase(xid) def prepare_twophase(self, conn, prepare_twophase, xid): """Intercept prepare_twophase() events.""" return prepare_twophase(xid) def rollback_twophase(self, conn, rollback_twophase, xid, is_prepared): """Intercept rollback_twophase() events.""" return rollback_twophase(xid, is_prepared) def commit_twophase(self, conn, commit_twophase, xid, is_prepared): """Intercept commit_twophase() events.""" return commit_twophase(xid, is_prepared)<|fim▁end|>
def execute(self, conn, execute, clauseelement, *multiparams, **params): """Intercept high level execute() events.""" return execute(clauseelement, *multiparams, **params)
<|file_name|>LabelPopup.java<|end_file_name|><|fim▁begin|>/* * Copyright 2013-2020 consulo.io * * 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.<|fim▁hole|>import com.intellij.icons.AllIcons; import com.intellij.ide.DataManager; import com.intellij.openapi.actionSystem.ActionGroup; import com.intellij.openapi.ui.popup.JBPopupFactory; import com.intellij.ui.ClickListener; import com.intellij.util.ui.JBUI; import com.intellij.util.ui.UIUtil; import consulo.awt.TargetAWT; import consulo.localize.LocalizeValue; import javax.annotation.Nonnull; import javax.swing.*; import java.awt.event.MouseEvent; import java.util.function.Function; /** * @author VISTALL * @since 03/12/2020 */ public class LabelPopup extends JLabel { private final LocalizeValue myPrefix; public LabelPopup(LocalizeValue prefix, Function<LabelPopup, ? extends ActionGroup> groupBuilder) { myPrefix = prefix; setForeground(UIUtil.getLabelDisabledForeground()); setBorder(JBUI.Borders.empty(1, 1, 1, 5)); setIcon(TargetAWT.to(AllIcons.General.ComboArrow)); setHorizontalTextPosition(SwingConstants.LEADING); new ClickListener() { @Override public boolean onClick(@Nonnull MouseEvent event, int clickCount) { LabelPopup component = LabelPopup.this; JBPopupFactory.getInstance() .createActionGroupPopup(myPrefix.get(), groupBuilder.apply(component), DataManager.getInstance().getDataContext(component), JBPopupFactory.ActionSelectionAid.SPEEDSEARCH, true) .showUnderneathOf(component); return true; } }.installOn(this); } public void setPrefixedText(LocalizeValue tagValue) { setText(LocalizeValue.join(myPrefix, LocalizeValue.space(), tagValue).get()); } }<|fim▁end|>
*/ package com.intellij.ide.plugins;
<|file_name|>TestOrcLargeStripe.java<|end_file_name|><|fim▁begin|>/* * Copyright 2015 The Apache Software Foundation. * * 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 org.apache.orc.impl; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.anyBoolean; import static org.mockito.Mockito.anyInt; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.Random; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hive.ql.exec.vector.BytesColumnVector; import org.apache.hadoop.hive.ql.exec.vector.VectorizedRowBatch; import org.apache.orc.CompressionKind; import org.apache.orc.OrcConf; import org.apache.orc.OrcFile; import org.apache.orc.Reader; import org.apache.orc.RecordReader; import org.apache.orc.TypeDescription; import org.apache.orc.Writer; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestName; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class TestOrcLargeStripe { private Path workDir = new Path(System.getProperty("test.tmp.dir", "target" + File.separator + "test" + File.separator + "tmp")); Configuration conf; FileSystem fs; private Path testFilePath; @Rule public TestName testCaseName = new TestName(); @Before public void openFileSystem() throws Exception { conf = new Configuration(); fs = FileSystem.getLocal(conf); testFilePath = new Path(workDir, "TestOrcFile." + testCaseName.getMethodName() + ".orc"); fs.delete(testFilePath, false); } @Mock private FSDataInputStream mockDataInput; static class RangeBuilder { BufferChunkList result = new BufferChunkList(); RangeBuilder range(long offset, int length) { result.add(new BufferChunk(offset, length)); return this; } BufferChunkList build() { return result; } } @Test public void testZeroCopy() throws Exception { BufferChunkList ranges = new RangeBuilder().range(1000, 3000).build(); HadoopShims.ZeroCopyReaderShim mockZcr = mock(HadoopShims.ZeroCopyReaderShim.class); when(mockZcr.readBuffer(anyInt(), anyBoolean())) .thenAnswer(invocation -> ByteBuffer.allocate(1000)); RecordReaderUtils.readDiskRanges(mockDataInput, mockZcr, ranges, true); verify(mockDataInput).seek(1000); verify(mockZcr).readBuffer(3000, false); verify(mockZcr).readBuffer(2000, false); verify(mockZcr).readBuffer(1000, false); } @Test public void testRangeMerge() throws Exception { BufferChunkList rangeList = new RangeBuilder() .range(100, 1000) .range(1000, 10000) .range(3000, 30000).build(); RecordReaderUtils.readDiskRanges(mockDataInput, null, rangeList, false); verify(mockDataInput).readFully(eq(100L), any(), eq(0), eq(32900));<|fim▁hole|> } @Test public void testRangeSkip() throws Exception { BufferChunkList rangeList = new RangeBuilder() .range(1000, 1000) .range(2000, 1000) .range(4000, 1000) .range(4100, 100) .range(8000, 1000).build(); RecordReaderUtils.readDiskRanges(mockDataInput, null, rangeList, false); verify(mockDataInput).readFully(eq(1000L), any(), eq(0), eq(2000)); verify(mockDataInput).readFully(eq(4000L), any(), eq(0), eq(1000)); verify(mockDataInput).readFully(eq(8000L), any(), eq(0), eq(1000)); } @Test public void testEmpty() throws Exception { BufferChunkList rangeList = new RangeBuilder().build(); RecordReaderUtils.readDiskRanges(mockDataInput, null, rangeList, false); verify(mockDataInput, never()).readFully(anyLong(), any(), anyInt(), anyInt()); } @Test public void testConfigMaxChunkLimit() throws IOException { Configuration conf = new Configuration(); FileSystem fs = FileSystem.getLocal(conf); TypeDescription schema = TypeDescription.createTimestamp(); testFilePath = new Path(workDir, "TestOrcLargeStripe." + testCaseName.getMethodName() + ".orc"); fs.delete(testFilePath, false); Writer writer = OrcFile.createWriter(testFilePath, OrcFile.writerOptions(conf).setSchema(schema).stripeSize(100000).bufferSize(10000) .version(OrcFile.Version.V_0_11).fileSystem(fs)); writer.close(); OrcFile.ReaderOptions opts = OrcFile.readerOptions(conf); Reader reader = OrcFile.createReader(testFilePath, opts); RecordReader recordReader = reader.rows(new Reader.Options().range(0L, Long.MAX_VALUE)); assertTrue(recordReader instanceof RecordReaderImpl); assertEquals(Integer.MAX_VALUE - 1024, ((RecordReaderImpl) recordReader).getMaxDiskRangeChunkLimit()); conf = new Configuration(); conf.setInt(OrcConf.ORC_MAX_DISK_RANGE_CHUNK_LIMIT.getHiveConfName(), 1000); opts = OrcFile.readerOptions(conf); reader = OrcFile.createReader(testFilePath, opts); recordReader = reader.rows(new Reader.Options().range(0L, Long.MAX_VALUE)); assertTrue(recordReader instanceof RecordReaderImpl); assertEquals(1000, ((RecordReaderImpl) recordReader).getMaxDiskRangeChunkLimit()); } @Test public void testStringDirectGreaterThan2GB() throws IOException { final Runtime rt = Runtime.getRuntime(); assumeTrue(rt.maxMemory() > 4_000_000_000L); TypeDescription schema = TypeDescription.createString(); conf.setDouble("hive.exec.orc.dictionary.key.size.threshold", 0.0); Writer writer = OrcFile.createWriter( testFilePath, OrcFile.writerOptions(conf).setSchema(schema) .compress(CompressionKind.NONE)); // 5000 is the lower bound for a stripe int size = 5000; int width = 500_000; // generate a random string that is width characters long Random random = new Random(123); char[] randomChars= new char[width]; int posn = 0; for(int length = 0; length < width && posn < randomChars.length; ++posn) { char cp = (char) random.nextInt(Character.MIN_SUPPLEMENTARY_CODE_POINT); // make sure we get a valid, non-surrogate while (Character.isSurrogate(cp)) { cp = (char) random.nextInt(Character.MIN_SUPPLEMENTARY_CODE_POINT); } // compute the length of the utf8 length += cp < 0x80 ? 1 : (cp < 0x800 ? 2 : 3); randomChars[posn] = cp; } // put the random characters in as a repeating value. VectorizedRowBatch batch = schema.createRowBatch(); BytesColumnVector string = (BytesColumnVector) batch.cols[0]; string.setVal(0, new String(randomChars, 0, posn).getBytes(StandardCharsets.UTF_8)); string.isRepeating = true; for(int rows=size; rows > 0; rows -= batch.size) { batch.size = Math.min(rows, batch.getMaxSize()); writer.addRowBatch(batch); } writer.close(); try { Reader reader = OrcFile.createReader(testFilePath, OrcFile.readerOptions(conf).filesystem(fs)); RecordReader rows = reader.rows(); batch = reader.getSchema().createRowBatch(); int rowsRead = 0; while (rows.nextBatch(batch)) { rowsRead += batch.size; } assertEquals(size, rowsRead); } finally { fs.delete(testFilePath, false); } } }<|fim▁end|>
<|file_name|>setup.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python from distutils.core import setup import strfrag setup( name='Strfrag', version=strfrag.__version__, description=('StringFragment type to represent parts of str objects; ' 'used to avoid copying strings during processing'), url="https://github.com/ludios/Strfrag", author="Ivan Kozik", author_email="[email protected]", classifiers=[ 'Programming Language :: Python :: 2',<|fim▁hole|> ], py_modules=['strfrag', 'test_strfrag'], )<|fim▁end|>
'Development Status :: 3 - Alpha', 'Operating System :: OS Independent', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License',
<|file_name|>test_cc2_tensor.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # ---------------------------------------------------------------------------- # Copyright 2014 Nervana Systems 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. # ---------------------------------------------------------------------------- from nose.plugins.attrib import attr from nose.tools import nottest import numpy as np from neon.util.testing import assert_tensor_equal @attr('cuda') class TestGPUTensor(object): def setup(self): from neon.backends.cc2 import GPUTensor self.gpt = GPUTensor def test_empty_creation(self): tns = self.gpt([]) expected_shape = (0, ) while len(expected_shape) < tns._min_dims: expected_shape += (1, ) assert tns.shape == expected_shape def test_1d_creation(self): tns = self.gpt([1, 2, 3, 4]) expected_shape = (4, ) while len(expected_shape) < tns._min_dims: expected_shape += (1, ) assert tns.shape == expected_shape def test_2d_creation(self): tns = self.gpt([[1, 2], [3, 4]]) expected_shape = (2, 2) while len(expected_shape) < tns._min_dims: expected_shape += (1, ) assert tns.shape == expected_shape def test_2d_ndarray_creation(self): tns = self.gpt(np.array([[1.5, 2.5], [3.3, 9.2], [0.111111, 5]])) assert tns.shape == (3, 2) @nottest # TODO: add >2 dimension support to cudanet def test_higher_dim_creation(self): shapes = ((1, 1, 1), (1, 2, 3, 4), (1, 2, 3, 4, 5, 6, 7)) for shape in shapes: tns = self.gpt(np.empty(shape))<|fim▁hole|> def test_str(self): tns = self.gpt([[1, 2], [3, 4]]) assert str(tns) == "[[ 1. 2.]\n [ 3. 4.]]" def test_scalar_slicing(self): tns = self.gpt([[1, 2], [3, 4]]) res = tns[1, 0] assert res.shape == (1, 1) assert_tensor_equal(res, self.gpt([[3]])) def test_range_slicing(self): tns = self.gpt([[1, 2], [3, 4]]) res = tns[0:2, 0] assert res.shape == (2, 1) assert_tensor_equal(res, self.gpt([1, 3])) @nottest # TODO: add scalar assignment to self.gpt class def test_scalar_slice_assignment(self): tns = self.gpt([[1, 2], [3, 4]]) tns[1, 0] = 9 assert_tensor_equal(tns, self.gpt([[1, 2], [9, 4]])) def test_asnumpyarray(self): tns = self.gpt([[1, 2], [3, 4]]) res = tns.asnumpyarray() assert isinstance(res, np.ndarray) assert_tensor_equal(res, np.array([[1, 2], [3, 4]])) @nottest # TODO: fix this for self.gpt def test_transpose(self): tns = self.gpt([[1, 2], [3, 4]]) res = tns.transpose() assert_tensor_equal(res, self.gpt([[1, 3], [2, 4]])) def test_fill(self): tns = self.gpt([[1, 2], [3, 4]]) tns.fill(-9.5) assert_tensor_equal(tns, self.gpt([[-9.5, -9.5], [-9.5, -9.5]]))<|fim▁end|>
assert tns.shape == shape
<|file_name|>DTStructuredMesh2D.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # This software is under a BSD license. See LICENSE.txt for details. from datatank_py.DTStructuredGrid2D import DTStructuredGrid2D, _squeeze2d import numpy as np class DTStructuredMesh2D(object): """2D structured mesh object. This class corresponds to DataTank's DTStructuredMesh2D. """ dt_type = ("2D Structured Mesh",) """Type strings allowed by DataTank""" def __init__(self, values, grid=None): """ :param values: 2D array of values :param grid: DTStructuredGrid2D object (defaults to unit grid) or the name of a previously saved grid Note that the values array must be ordered as (y, x) for compatibility with the grid and DataTank. """ super(DTStructuredMesh2D, self).__init__() values = _squeeze2d(values) shape = np.shape(values) assert len(shape) == 2, "values array must be 2D" if isinstance(grid, basestring) == False: if grid == None: grid = DTStructuredGrid2D(range(shape[1]), range(shape[0])) assert shape == grid.shape(), "grid shape %s != value shape %s" % (grid.shape(), shape) self._grid = grid self._values = values def grid(self): """:returns: a :class:`datatank_py.DTStructuredGrid2D.DTStructuredGrid2D` instance""" return self._grid def values(self): """:returns: a 2D numpy array of values at each grid node""" return self._values def __dt_type__(self): return "2D Structured Mesh" def __str__(self): return self.__dt_type__() + ":\n " + str(self._grid) + "\n" + " Values:\n " + str(self._values) def __dt_write__(self, datafile, name): datafile.write_anonymous(self._grid, name) datafile.write_anonymous(self._values, name + "_V") def write_with_shared_grid(self, datafile, name, grid_name, time, time_index): """Allows saving a single grid and sharing it amongst different time values of a variable. :param datafile: a :class:`datatank_py.DTDataFile.DTDataFile` open for writing :param name: the mesh variable's name :param grid_name: the grid name to be shared (will not be visible in DataTank) :param time: the time value for this step (DataTank's ``t`` variable) :param time_index: the corresponding integer index of this time step This is an advanced technique, but it can give a significant space savings in a data file. It's not widely implemented, since it's not clear yet if this is the best API. """ if grid_name not in datafile: datafile.write_anonymous(self._grid, grid_name) datafile.write_anonymous(self.__dt_type__(), "Seq_" + name) varname = "%s_%d" % (name, time_index) datafile.write_anonymous(grid_name, varname) datafile.write_anonymous(self._values, varname + "_V") datafile.write_anonymous(np.array((time,)), varname + "_time") @classmethod def from_data_file(self, datafile, name): grid = DTStructuredGrid2D.from_data_file(datafile, name) values = datafile[name + "_V"] return DTStructuredMesh2D(values, grid=grid) if __name__ == '__main__': from DTDataFile import DTDataFile with DTDataFile("test/structured_mesh2D.dtbin", truncate=True) as df: xvals = np.exp(np.array(range(18), dtype=np.float) / 5) yvals = np.exp(np.array(range(20), dtype=np.float) / 5) grid = DTStructuredGrid2D(xvals, yvals) values = np.zeros(len(xvals) * len(yvals)) for i in xrange(len(values)): values[i] = i # DataTank indexes differently from numpy; the grid is z,y,x ordered values = values.reshape(grid.shape()) <|fim▁hole|><|fim▁end|>
mesh = DTStructuredMesh2D(values, grid=grid) df["2D mesh"] = mesh
<|file_name|>DynamicJAXBFromXSDTestCases.java<|end_file_name|><|fim▁begin|>/******************************************************************************* * Copyright (c) 2011, 2012 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * rbarkhouse - 2.1 - initial implementation ******************************************************************************/ package org.eclipse.persistence.testing.jaxb.dynamic; import java.io.File; import java.io.InputStream; import java.lang.reflect.UndeclaredThrowableException; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.datatype.DatatypeConstants; import javax.xml.datatype.DatatypeFactory; import javax.xml.namespace.QName; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.Source; import javax.xml.transform.stream.StreamSource; import junit.framework.TestCase; import org.eclipse.persistence.dynamic.DynamicEntity; import org.eclipse.persistence.internal.helper.ClassConstants; import org.eclipse.persistence.jaxb.JAXBContextFactory; import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext; import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContextFactory; import org.eclipse.persistence.testing.jaxb.dynamic.util.NoExtensionEntityResolver; import org.w3c.dom.Document; import org.w3c.dom.Node; public class DynamicJAXBFromXSDTestCases extends TestCase { DynamicJAXBContext jaxbContext; static { try { // Disable XJC's schema correctness check. XSD imports do not seem to work if this is left on. System.setProperty("com.sun.tools.xjc.api.impl.s2j.SchemaCompilerImpl.noCorrectnessCheck", "true"); } catch (Exception e) { // Ignore } } public DynamicJAXBFromXSDTestCases(String name) throws Exception { super(name); } public String getName() { return "Dynamic JAXB: XSD: " + super.getName(); } public void testEclipseLinkSchema() throws Exception { // Bootstrapping from eclipselink_oxm_2_4.xsd will trigger a JAXB 2.2 API (javax.xml.bind.annotation.XmlElementRef.required()) // so only run this test in Java 7 if (System.getProperty("java.version").contains("1.7")) { InputStream inputStream = ClassLoader.getSystemResourceAsStream(ECLIPSELINK_SCHEMA); jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null); } } // ==================================================================== public void testXmlSchemaQualified() throws Exception { // <xs:schema targetNamespace="myNamespace" xmlns:xs="http://www.w3.org/2001/XMLSchema" // attributeFormDefault="qualified" elementFormDefault="qualified"> InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLSCHEMA_QUALIFIED); jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null); DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON); assertNotNull("Could not create Dynamic Entity.", person); person.set("id", 456); person.set("name", "Bob Dobbs"); Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); jaxbContext.createMarshaller().marshal(person, marshalDoc); // Make sure "targetNamespace" was interpreted properly. Node node = marshalDoc.getChildNodes().item(0); assertEquals("Target Namespace was not set as expected.", "myNamespace", node.getNamespaceURI()); // Make sure "elementFormDefault" was interpreted properly. // elementFormDefault=qualified, so the root node, the // root node's attribute, and the child node should all have a prefix. assertNotNull("Root node did not have namespace prefix as expected.", node.getPrefix()); Node attr = node.getAttributes().item(0); assertNotNull("Attribute did not have namespace prefix as expected.", attr.getPrefix()); Node childNode = node.getChildNodes().item(0); assertNotNull("Child node did not have namespace prefix as expected.", childNode.getPrefix()); } public void testXmlSchemaUnqualified() throws Exception { // <xs:schema targetNamespace="myNamespace" xmlns:xs="http://www.w3.org/2001/XMLSchema" // attributeFormDefault="unqualified" elementFormDefault="unqualified"> InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLSCHEMA_UNQUALIFIED); jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null); DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON); assertNotNull("Could not create Dynamic Entity.", person); person.set("id", 456); person.set("name", "Bob Dobbs"); Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); jaxbContext.createMarshaller().marshal(person, marshalDoc); // Make sure "targetNamespace" was interpreted properly. Node node = marshalDoc.getChildNodes().item(0); assertEquals("Target Namespace was not set as expected.", "myNamespace", node.getNamespaceURI()); // Make sure "elementFormDefault" was interpreted properly. // elementFormDefault=unqualified, so the root node should have a prefix // but the root node's attribute and child node should not. assertNotNull("Root node did not have namespace prefix as expected.", node.getPrefix()); // Do not test attribute prefix with the Oracle xmlparserv2, it qualifies attributes by default. DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); if (builderFactory.getClass().getPackage().getName().contains("oracle")) { return; } else { Node attr = node.getAttributes().item(0); assertNull("Attribute should not have namespace prefix (" + attr.getPrefix() + ").", attr.getPrefix()); } Node childNode = node.getChildNodes().item(0); assertNull("Child node should not have namespace prefix.", childNode.getPrefix()); } public void testXmlSchemaDefaults() throws Exception { // <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLSCHEMA_DEFAULTS); jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null); DynamicEntity person = jaxbContext.newDynamicEntity(DEF_PACKAGE + "." + PERSON); assertNotNull("Could not create Dynamic Entity.", person); person.set("id", 456); person.set("name", "Bob Dobbs"); Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); jaxbContext.createMarshaller().marshal(person, marshalDoc); // "targetNamespace" should be null by default Node node = marshalDoc.getChildNodes().item(0); assertNull("Target Namespace was not null as expected.", node.getNamespaceURI()); // Make sure "elementFormDefault" was interpreted properly. // When unset, no namespace qualification is done. assertNull("Root node should not have namespace prefix.", node.getPrefix()); Node attr = node.getAttributes().item(0); assertNull("Attribute should not have namespace prefix.", attr.getPrefix()); Node childNode = node.getChildNodes().item(0); assertNull("Child node should not have namespace prefix.", childNode.getPrefix()); } public void testXmlSchemaImport() throws Exception { // <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> // <xs:import schemaLocation="xmlschema-currency" namespace="bankNamespace"/> // Do not run this test if we are not using JDK 1.6 String javaVersion = System.getProperty("java.version"); if (!(javaVersion.startsWith("1.6"))) { return; } // Do not run this test with the Oracle xmlparserv2, it will not properly hit the EntityResolver DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); if (builderFactory.getClass().getPackage().getName().contains("oracle")) { return; } InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLSCHEMA_IMPORT); jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, new NoExtensionEntityResolver(), null, null); DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON); assertNotNull("Could not create Dynamic Entity.", person); DynamicEntity salary = jaxbContext.newDynamicEntity(BANK_PACKAGE + "." + CDN_CURRENCY); assertNotNull("Could not create Dynamic Entity.", salary); salary.set("value", new BigDecimal(75425.75)); person.set("name", "Bob Dobbs"); person.set("salary", salary); Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); JAXBElement jbe = new JAXBElement(new QName("person"), DynamicEntity.class, person); jaxbContext.createMarshaller().marshal(jbe, marshalDoc); // Nothing to really test, if the import failed we couldn't have created the salary. } public void testXmlSeeAlso() throws Exception { InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLSEEALSO); jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null); DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + EMPLOYEE); assertNotNull("Could not create Dynamic Entity.", person); person.set("name", "Bob Dobbs"); person.set("employeeId", "CA2472"); Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); jaxbContext.createMarshaller().marshal(person, marshalDoc); // Nothing to really test, XmlSeeAlso isn't represented in an instance doc. } public void testXmlRootElement() throws Exception { InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLROOTELEMENT); jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null); DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + INDIVIDUO); assertNotNull("Could not create Dynamic Entity.", person); person.set("name", "Bob Dobbs"); Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); jaxbContext.createMarshaller().marshal(person, marshalDoc); Node node = marshalDoc.getChildNodes().item(0); assertEquals("Root element was not 'individuo' as expected.", "individuo", node.getLocalName()); } public void testXmlType() throws Exception { InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLTYPE); jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null); DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON); assertNotNull("Could not create Dynamic Entity.", person); person.set("email", "[email protected]"); person.set("lastName", "Dobbs"); person.set("id", 678); person.set("phoneNumber", "212-555-8282"); person.set("firstName", "Bob"); JAXBElement jbe = new JAXBElement(new QName("person"), DynamicEntity.class, person); Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); jaxbContext.createMarshaller().marshal(jbe, marshalDoc); // Test that XmlType.propOrder was interpreted properly Node node = marshalDoc.getDocumentElement().getChildNodes().item(0); assertNotNull("Node was null.", node); assertEquals("Unexpected node.", "id", node.getLocalName()); node = marshalDoc.getDocumentElement().getChildNodes().item(1); assertNotNull("Node was null.", node); assertEquals("Unexpected node.", "first-name", node.getLocalName()); node = marshalDoc.getDocumentElement().getChildNodes().item(2); assertNotNull("Node was null.", node); assertEquals("Unexpected node.", "last-name", node.getLocalName()); node = marshalDoc.getDocumentElement().getChildNodes().item(3); assertNotNull("Node was null.", node); assertEquals("Unexpected node.", "phone-number", node.getLocalName()); node = marshalDoc.getDocumentElement().getChildNodes().item(4); assertNotNull("Node was null.", node); assertEquals("Unexpected node.", "email", node.getLocalName()); } public void testXmlAttribute() throws Exception { InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLATTRIBUTE); jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null); DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON); assertNotNull("Could not create Dynamic Entity.", person); person.set("id", 777); Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); JAXBElement jbe = new JAXBElement(new QName("person"), DynamicEntity.class, person); jaxbContext.createMarshaller().marshal(jbe, marshalDoc); Node node = marshalDoc.getChildNodes().item(0); if (node.getAttributes() == null || node.getAttributes().getNamedItem("id") == null) { fail("Attribute not present."); } } public void testXmlElement() throws Exception { InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLELEMENT); jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null); DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON); assertNotNull("Could not create Dynamic Entity.", person); person.set("type", "O+"); Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); JAXBElement jbe = new JAXBElement(new QName("person"), DynamicEntity.class, person); jaxbContext.createMarshaller().marshal(jbe, marshalDoc); Node node = marshalDoc.getDocumentElement(); assertNotNull("Element not present.", node.getChildNodes()); String elemName = node.getChildNodes().item(0).getNodeName(); assertEquals("Element not present.", "type", elemName); } public void testXmlElementCollection() throws Exception { InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLELEMENTCOLLECTION); jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null); DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON); assertNotNull("Could not create Dynamic Entity.", person); ArrayList nicknames = new ArrayList(); nicknames.add("Bobby"); nicknames.add("Dobsy"); nicknames.add("Big Kahuna"); person.set("nickname", nicknames); Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); JAXBElement jbe = new JAXBElement(new QName("person"), DynamicEntity.class, person); jaxbContext.createMarshaller().marshal(jbe, marshalDoc); <|fim▁hole|> assertNotNull("Element not present.", node.getChildNodes()); assertEquals("Unexpected number of child nodes present.", 3, node.getChildNodes().getLength()); } public void testXmlElementCustomized() throws Exception { // Customize the EclipseLink mapping generation by providing an eclipselink-oxm.xml String metadataFile = RESOURCE_DIR + "eclipselink-oxm.xml"; InputStream iStream = ClassLoader.getSystemResourceAsStream(metadataFile); HashMap<String, Source> metadataSourceMap = new HashMap<String, Source>(); metadataSourceMap.put(CONTEXT_PATH, new StreamSource(iStream)); Map<String, Object> props = new HashMap<String, Object>(); props.put(JAXBContextFactory.ECLIPSELINK_OXM_XML_KEY, metadataSourceMap); InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLELEMENT); jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, props); DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON); assertNotNull("Could not create Dynamic Entity.", person); person.set("type", "O+"); Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); jaxbContext.createMarshaller().marshal(person, marshalDoc); Node node = marshalDoc.getDocumentElement(); assertNotNull("Element not present.", node.getChildNodes()); String elemName = node.getChildNodes().item(0).getNodeName(); // 'type' was renamed to 'bloodType' in the OXM bindings file assertEquals("Element not present.", "bloodType", elemName); } public void testXmlList() throws Exception { InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLLIST); jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null); DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON); assertNotNull("Could not create Dynamic Entity.", person); ArrayList<String> codes = new ArrayList<String>(3); codes.add("D1182"); codes.add("D1716"); codes.add("G7212"); person.set("name", "Bob Dobbs"); person.set("codes", codes); Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); jaxbContext.createMarshaller().marshal(person, marshalDoc); Node node = marshalDoc.getDocumentElement(); assertEquals("Unexpected number of nodes in document.", 2, node.getChildNodes().getLength()); String value = node.getChildNodes().item(1).getTextContent(); assertEquals("Unexpected element contents.", "D1182 D1716 G7212", value); } public void testXmlValue() throws Exception { InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLVALUE); jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null); DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON); assertNotNull("Could not create Dynamic Entity.", person); DynamicEntity salary = jaxbContext.newDynamicEntity(PACKAGE + "." + CDN_CURRENCY); assertNotNull("Could not create Dynamic Entity.", salary); salary.set("value", new BigDecimal(75100)); person.set("name", "Bob Dobbs"); person.set("salary", salary); JAXBElement jbe = new JAXBElement(new QName("person"), DynamicEntity.class, person); Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); jaxbContext.createMarshaller().marshal(jbe, marshalDoc); // Nothing to really test, XmlValue isn't represented in an instance doc. } public void testXmlAnyElement() throws Exception { InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLANYELEMENT); jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null); DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON); assertNotNull("Could not create Dynamic Entity.", person); person.set("name", "Bob Dobbs"); person.set("any", "StringValue"); Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); jaxbContext.createMarshaller().marshal(person, marshalDoc); Node node = marshalDoc.getDocumentElement(); assertTrue("Any element not found.", node.getChildNodes().item(1).getNodeType() == Node.TEXT_NODE); } public void testXmlAnyAttribute() throws Exception { InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLANYATTRIBUTE); jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null); DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON); assertNotNull("Could not create Dynamic Entity.", person); Map<QName, Object> otherAttributes = new HashMap<QName, Object>(); otherAttributes.put(new QName("foo"), new BigDecimal(1234)); otherAttributes.put(new QName("bar"), Boolean.FALSE); person.set("name", "Bob Dobbs"); person.set("otherAttributes", otherAttributes); Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); jaxbContext.createMarshaller().marshal(person, marshalDoc); Node node = marshalDoc.getDocumentElement(); Node otherAttributesNode = node.getAttributes().getNamedItem("foo"); assertNotNull("'foo' attribute not found.", otherAttributesNode); otherAttributesNode = node.getAttributes().getNamedItem("bar"); assertNotNull("'bar' attribute not found.", otherAttributesNode); } public void testXmlMixed() throws Exception { // Also tests XmlElementRef / XmlElementRefs InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLMIXED); try { jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null); } catch (JAXBException e) { // If running in a non-JAXB 2.2 environment, we will get this error because the required() method // on @XmlElementRef is missing. Just ignore this and pass the test. if (e.getLinkedException() instanceof UndeclaredThrowableException) { return; } else { throw e; } } catch (Exception e) { if (e instanceof UndeclaredThrowableException) { return; } else { throw e; } } DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON); assertNotNull("Could not create Dynamic Entity.", person); ArrayList list = new ArrayList(); list.add("Hello"); list.add(new JAXBElement<String>(new QName("myNamespace", "title"), String.class, person.getClass(), "MR")); list.add(new JAXBElement<String>(new QName("myNamespace", "name"), String.class, person.getClass(), "Bob Dobbs")); list.add(", your point balance is"); list.add(new JAXBElement<BigInteger>(new QName("myNamespace", "rewardPoints"), BigInteger.class, person.getClass(), BigInteger.valueOf(175))); list.add("Visit www.rewards.com!"); person.set("content", list); Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); jaxbContext.createMarshaller().marshal(person, marshalDoc); Node node = marshalDoc.getDocumentElement(); assertTrue("Unexpected number of elements.", node.getChildNodes().getLength() == 6); } public void testXmlId() throws Exception { // Tests both XmlId and XmlIdRef InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLID); jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null); DynamicEntity data = jaxbContext.newDynamicEntity(PACKAGE + "." + DATA); assertNotNull("Could not create Dynamic Entity.", data); DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON); assertNotNull("Could not create Dynamic Entity.", person); DynamicEntity company = jaxbContext.newDynamicEntity(PACKAGE + "." + COMPANY); assertNotNull("Could not create Dynamic Entity.", company); company.set("name", "ACME International"); company.set("address", "165 Main St, Anytown US, 93012"); company.set("id", "882"); person.set("name", "Bob Dobbs"); person.set("company", company); data.set("person", person); data.set("company", company); Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); jaxbContext.createMarshaller().marshal(data, marshalDoc); // 'person' node Node pNode = marshalDoc.getDocumentElement().getChildNodes().item(0); // 'company' node Node cNode = pNode.getChildNodes().item(1); // If IDREF worked properly, the company element should only contain the id of the company object assertEquals("'company' has unexpected number of child nodes.", 1, cNode.getChildNodes().getLength()); } public void testXmlElements() throws Exception { InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLELEMENTS); jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null); DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON); assertNotNull("Could not create Dynamic Entity.", person); ArrayList list = new ArrayList(1); list.add("BOB"); person.set("nameOrReferenceNumber", list); Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); jaxbContext.createMarshaller().marshal(person, marshalDoc); Node node = marshalDoc.getDocumentElement().getChildNodes().item(0); assertEquals("Unexpected element name.", "name", node.getNodeName()); person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON); list = new ArrayList(1); list.add(328763); person.set("nameOrReferenceNumber", list); marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); jaxbContext.createMarshaller().marshal(person, marshalDoc); node = marshalDoc.getDocumentElement().getChildNodes().item(0); assertEquals("Unexpected element name.", "reference-number", node.getNodeName()); } public void testXmlElementRef() throws Exception { InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLELEMENTREF); jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null); DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON); assertNotNull("Could not create Dynamic Entity.", person); ArrayList list = new ArrayList(1); list.add("BOB"); person.set("nameOrReferenceNumber", list); Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); jaxbContext.createMarshaller().marshal(person, marshalDoc); Node node = marshalDoc.getDocumentElement().getChildNodes().item(0); assertEquals("Unexpected element name.", "name", node.getNodeName()); person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON); list = new ArrayList(1); list.add(328763); person.set("nameOrReferenceNumber", list); marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); jaxbContext.createMarshaller().marshal(person, marshalDoc); node = marshalDoc.getDocumentElement().getChildNodes().item(0); assertEquals("Unexpected element name.", "reference-number", node.getNodeName()); } public void testXmlSchemaType() throws Exception { InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLSCHEMATYPE); jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null); DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON); assertNotNull("Could not create Dynamic Entity.", person); person.set("dateOfBirth", DatatypeFactory.newInstance().newXMLGregorianCalendarDate(1976, 02, 17, DatatypeConstants.FIELD_UNDEFINED)); Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); jaxbContext.createMarshaller().marshal(person, marshalDoc); Node node = marshalDoc.getDocumentElement().getChildNodes().item(0); assertEquals("Unexpected date value.", "1976-02-17", node.getTextContent()); } public void testXmlEnum() throws Exception { // Tests XmlEnum and XmlEnumValue InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLENUM); jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null); DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON); assertNotNull("Could not create Dynamic Entity.", person); Object NORTH = jaxbContext.getEnumConstant(PACKAGE + "." + COMPASS_DIRECTION, NORTH_CONSTANT); assertNotNull("Could not find enum constant.", NORTH); person.set("quadrant", NORTH); Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); jaxbContext.createMarshaller().marshal(person, marshalDoc); } public void testXmlEnumBig() throws Exception { // Tests XmlEnum and XmlEnumValue // This test schema contains >128 enum values to test an ASM boundary case InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLENUM_BIG); jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null); Object EST = jaxbContext.getEnumConstant(DEF_PACKAGE + "." + TIME_ZONE, EST_CONSTANT); assertNotNull("Could not find enum constant.", EST); } public void testXmlEnumError() throws Exception { // Tests XmlEnum and XmlEnumValue InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLENUM); jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null); Exception caughtException = null; try { Object NORTHWEST = jaxbContext.getEnumConstant(PACKAGE + "." + COMPASS_DIRECTION, "NORTHWEST"); } catch (Exception e) { caughtException = e; } assertNotNull("Expected exception was not thrown.", caughtException); } public void testXmlElementDecl() throws Exception { // Also tests XmlRegistry InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLELEMENTDECL); jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null); DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON); assertNotNull("Could not create Dynamic Entity.", person); person.set("name", "Bob Dobbs"); Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); JAXBElement jbe = new JAXBElement(new QName("individuo"), DynamicEntity.class, person); jaxbContext.createMarshaller().marshal(jbe, marshalDoc); Node node = marshalDoc.getChildNodes().item(0); assertEquals("Root element was not 'individuo' as expected.", "individuo", node.getLocalName()); } public void testSchemaWithJAXBBindings() throws Exception { // jaxbcustom.xsd specifies that the generated package name should be "foo.bar" and // the person type will be named MyPersonType in Java InputStream inputStream = ClassLoader.getSystemResourceAsStream(JAXBCUSTOM); jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null); DynamicEntity person = jaxbContext.newDynamicEntity("foo.bar.MyPersonType"); assertNotNull("Could not create Dynamic Entity.", person); person.set("name", "Bob Dobbs"); Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); jaxbContext.createMarshaller().marshal(person, marshalDoc); } public void testSubstitutionGroupsUnmarshal() throws Exception { try { InputStream xsdStream = ClassLoader.getSystemResourceAsStream(SUBSTITUTION); jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(xsdStream, null, null, null); InputStream xmlStream = ClassLoader.getSystemResourceAsStream(PERSON_XML); JAXBElement person = (JAXBElement) jaxbContext.createUnmarshaller().unmarshal(xmlStream); assertEquals("Element was not substituted properly: ", new QName("myNamespace", "person"), person.getName()); JAXBElement name = (JAXBElement) ((DynamicEntity) person.getValue()).get("name"); assertEquals("Element was not substituted properly: ", new QName("myNamespace", "name"), name.getName()); // ==================================================================== InputStream xmlStream2 = ClassLoader.getSystemResourceAsStream(PERSONNE_XML); JAXBElement person2 = (JAXBElement) jaxbContext.createUnmarshaller().unmarshal(xmlStream2); assertEquals("Element was not substituted properly: ", new QName("myNamespace", "personne"), person2.getName()); JAXBElement name2 = (JAXBElement) ((DynamicEntity) person2.getValue()).get("name"); assertEquals("Element was not substituted properly: ", new QName("myNamespace", "nom"), name2.getName()); } catch (JAXBException e) { // If running in a non-JAXB 2.2 environment, we will get this error because the required() method // on @XmlElementRef is missing. Just ignore this and pass the test. if (e.getLinkedException() instanceof UndeclaredThrowableException) { return; } else { throw e; } } catch (Exception e) { if (e instanceof UndeclaredThrowableException) { return; } else { throw e; } } } public void testSubstitutionGroupsMarshal() throws Exception { try { InputStream inputStream = ClassLoader.getSystemResourceAsStream(SUBSTITUTION); jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null); QName personQName = new QName("myNamespace", "person"); DynamicEntity person = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON); JAXBElement<DynamicEntity> personElement = new JAXBElement<DynamicEntity>(personQName, DynamicEntity.class, person); personElement.setValue(person); QName nameQName = new QName("myNamespace", "name"); JAXBElement<String> nameElement = new JAXBElement<String>(nameQName, String.class, "Marty Friedman"); person.set("name", nameElement); Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); jaxbContext.createMarshaller().marshal(personElement, marshalDoc); Node node1 = marshalDoc.getDocumentElement(); assertEquals("Incorrect element name: ", "person", node1.getLocalName()); Node node2 = node1.getFirstChild(); assertEquals("Incorrect element name: ", "name", node2.getLocalName()); // ==================================================================== QName personneQName = new QName("myNamespace", "personne"); DynamicEntity personne = jaxbContext.newDynamicEntity(PACKAGE + "." + PERSON); JAXBElement<DynamicEntity> personneElement = new JAXBElement<DynamicEntity>(personneQName, DynamicEntity.class, personne); personneElement.setValue(personne); QName nomQName = new QName("myNamespace", "nom"); JAXBElement<String> nomElement = new JAXBElement<String>(nomQName, String.class, "Marty Friedman"); personne.set("name", nomElement); Document marshalDoc2 = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); jaxbContext.createMarshaller().marshal(personneElement, marshalDoc2); Node node3 = marshalDoc2.getDocumentElement(); assertEquals("Incorrect element name: ", "personne", node3.getLocalName()); Node node4 = node3.getFirstChild(); assertEquals("Incorrect element name: ", "nom", node4.getLocalName()); } catch (JAXBException e) { // If running in a non-JAXB 2.2 environment, we will get this error because the required() method // on @XmlElementRef is missing. Just ignore this and pass the test. if (e.getLinkedException() instanceof UndeclaredThrowableException) { return; } else { throw e; } } catch (Exception e) { if (e instanceof UndeclaredThrowableException) { return; } else { throw e; } } } // ==================================================================== public void testTypePreservation() throws Exception { InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLSCHEMA_DEFAULTS); jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null); DynamicEntity person = jaxbContext.newDynamicEntity(DEF_PACKAGE + "." + PERSON); assertNotNull("Could not create Dynamic Entity.", person); person.set("id", 456); person.set("name", "Bob Dobbs"); person.set("salary", 45000.00); Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); jaxbContext.createMarshaller().marshal(person, marshalDoc); DynamicEntity readPerson = (DynamicEntity) jaxbContext.createUnmarshaller().unmarshal(marshalDoc); assertEquals("Property type was not preserved during unmarshal.", Double.class, readPerson.<Object>get("salary").getClass()); assertEquals("Property type was not preserved during unmarshal.", Integer.class, readPerson.<Object>get("id").getClass()); } public void testNestedInnerClasses() throws Exception { // Tests multiple levels of inner classes, eg. mynamespace.Person.RelatedResource.Link InputStream inputStream = ClassLoader.getSystemResourceAsStream(NESTEDINNERCLASSES); jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null); DynamicEntity person = jaxbContext.newDynamicEntity("mynamespace.Person"); DynamicEntity resource = jaxbContext.newDynamicEntity("mynamespace.Person.RelatedResource"); DynamicEntity link = jaxbContext.newDynamicEntity("mynamespace.Person.RelatedResource.Link"); DynamicEntity link2 = jaxbContext.newDynamicEntity("mynamespace.Person.RelatedResource.Link"); link.set("linkName", "LINKFOO"); link2.set("linkName", "LINKFOO2"); resource.set("resourceName", "RESBAR"); ArrayList<DynamicEntity> links = new ArrayList<DynamicEntity>(); links.add(link); links.add(link2); resource.set("link", links); person.set("name", "Bob Smith"); person.set("relatedResource", resource); Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); JAXBElement jbe = new JAXBElement(new QName("person"), DynamicEntity.class, person); jaxbContext.createMarshaller().marshal(jbe, marshalDoc); } public void testBinary() throws Exception { InputStream inputStream = ClassLoader.getSystemResourceAsStream(BINARY); jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null); byte[] byteArray = new byte[] {30,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4}; DynamicEntity person = jaxbContext.newDynamicEntity("mynamespace.Person"); person.set("name", "B. Nary"); person.set("abyte", (byte) 30); person.set("base64", byteArray); person.set("hex", byteArray); Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); jaxbContext.createMarshaller().marshal(person, marshalDoc); } public void testBinaryGlobalType() throws Exception { InputStream inputStream = ClassLoader.getSystemResourceAsStream(BINARY2); jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null); byte[] byteArray = new byte[] {30,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4}; DynamicEntity person = jaxbContext.newDynamicEntity("mynamespace.Person"); person.set("name", "B. Nary"); person.set("abyte", (byte) 30); person.set("base64", byteArray); person.set("hex", byteArray); Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); JAXBElement jbe = new JAXBElement(new QName("person"), DynamicEntity.class, person); jaxbContext.createMarshaller().marshal(jbe, marshalDoc); } public void testXMLSchemaSchema() throws Exception { try { InputStream inputStream = ClassLoader.getSystemResourceAsStream(XMLSCHEMASCHEMA); jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null); DynamicEntity schema = jaxbContext.newDynamicEntity("org.w3._2001.xmlschema.Schema"); schema.set("targetNamespace", "myNamespace"); Object QUALIFIED = jaxbContext.getEnumConstant("org.w3._2001.xmlschema.FormChoice", "QUALIFIED"); schema.set("attributeFormDefault", QUALIFIED); DynamicEntity complexType = jaxbContext.newDynamicEntity("org.w3._2001.xmlschema.TopLevelComplexType"); complexType.set("name", "myComplexType"); List<DynamicEntity> complexTypes = new ArrayList<DynamicEntity>(1); complexTypes.add(complexType); schema.set("simpleTypeOrComplexTypeOrGroup", complexTypes); List<Object> blocks = new ArrayList<Object>(); blocks.add("FOOBAR"); schema.set("blockDefault", blocks); File f = new File("myschema.xsd"); jaxbContext.createMarshaller().marshal(schema, f); } catch (JAXBException e) { // If running in a non-JAXB 2.2 environment, we will get this error because the required() method // on @XmlElementRef is missing. Just ignore this and pass the test. if (e.getLinkedException() instanceof UndeclaredThrowableException) { return; } else { throw e; } } catch (Exception e) { if (e instanceof UndeclaredThrowableException) { return; } else { throw e; } } } public void testGetByXPathPosition() throws Exception { InputStream inputStream = ClassLoader.getSystemResourceAsStream(XPATH_POSITION); jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null); InputStream xmlStream = ClassLoader.getSystemResourceAsStream(XPATH_POSITION_XML); JAXBElement<DynamicEntity> jelem = (JAXBElement<DynamicEntity>) jaxbContext.createUnmarshaller().unmarshal(xmlStream); DynamicEntity testBean = jelem.getValue(); Object o = jaxbContext.getValueByXPath(testBean, "array[1]/text()", null, Object.class); assertNotNull("XPath: 'array[1]/text()' returned null.", o); o = jaxbContext.getValueByXPath(testBean, "array[2]/text()", null, Object.class); assertNull("XPath: 'array[2]/text()' did not return null.", o); o = jaxbContext.getValueByXPath(testBean, "map/entry[1]/value/text()", null, Object.class); assertEquals("foo", o); o = jaxbContext.getValueByXPath(testBean, "sub-bean[1]/map/entry[1]/value/text()", null, Object.class); assertEquals("foo2", o); } public void testDateTimeArray() throws Exception { // Tests to ensure that XSD dateTime is always unmarshalled as XMLGregorianCalendar, and never // as GregorianCalendar. This can fail intermittently so is tested in a loop. HashSet<Class> elemClasses = new HashSet<Class>(); for (int i = 0; i < 50; i++) { InputStream inputStream = ClassLoader.getSystemResourceAsStream(DATETIME_ARRAY); jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(inputStream, null, null, null); InputStream xmlStream = ClassLoader.getSystemResourceAsStream(DATETIME_ARRAY_XML); JAXBElement<DynamicEntity> jelem = (JAXBElement<DynamicEntity>) jaxbContext.createUnmarshaller().unmarshal(xmlStream); DynamicEntity testBean = jelem.getValue(); ArrayList array = testBean.get("array"); elemClasses.add(array.get(0).getClass()); } assertEquals("dateTime was not consistently unmarshalled as XMLGregorianCalendar " + elemClasses, 1, elemClasses.size()); Class elemClass = (Class) elemClasses.toArray()[0]; boolean isXmlGregorianCalendar = ClassConstants.XML_GREGORIAN_CALENDAR.isAssignableFrom(elemClass); assertTrue("dateTime was not unmarshalled as XMLGregorianCalendar", isXmlGregorianCalendar); } // ==================================================================== private void print(Object o) throws Exception { Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); marshaller.marshal(o, System.err); } // ==================================================================== private static final String RESOURCE_DIR = "org/eclipse/persistence/testing/jaxb/dynamic/"; private static final String CONTEXT_PATH = "mynamespace"; // Schema files used to test each annotation private static final String XMLSCHEMA_QUALIFIED = RESOURCE_DIR + "xmlschema-qualified.xsd"; private static final String XMLSCHEMA_UNQUALIFIED = RESOURCE_DIR + "xmlschema-unqualified.xsd"; private static final String XMLSCHEMA_DEFAULTS = RESOURCE_DIR + "xmlschema-defaults.xsd"; private static final String XMLSCHEMA_IMPORT = RESOURCE_DIR + "xmlschema-import.xsd"; private static final String XMLSCHEMA_CURRENCY = RESOURCE_DIR + "xmlschema-currency.xsd"; private static final String XMLSEEALSO = RESOURCE_DIR + "xmlseealso.xsd"; private static final String XMLROOTELEMENT = RESOURCE_DIR + "xmlrootelement.xsd"; private static final String XMLTYPE = RESOURCE_DIR + "xmltype.xsd"; private static final String XMLATTRIBUTE = RESOURCE_DIR + "xmlattribute.xsd"; private static final String XMLELEMENT = RESOURCE_DIR + "xmlelement.xsd"; private static final String XMLLIST = RESOURCE_DIR + "xmllist.xsd"; private static final String XMLVALUE = RESOURCE_DIR + "xmlvalue.xsd"; private static final String XMLANYELEMENT = RESOURCE_DIR + "xmlanyelement.xsd"; private static final String XMLANYATTRIBUTE = RESOURCE_DIR + "xmlanyattribute.xsd"; private static final String XMLMIXED = RESOURCE_DIR + "xmlmixed.xsd"; private static final String XMLID = RESOURCE_DIR + "xmlid.xsd"; private static final String XMLELEMENTS = RESOURCE_DIR + "xmlelements.xsd"; private static final String XMLELEMENTREF = RESOURCE_DIR + "xmlelementref.xsd"; private static final String XMLSCHEMATYPE = RESOURCE_DIR + "xmlschematype.xsd"; private static final String XMLENUM = RESOURCE_DIR + "xmlenum.xsd"; private static final String XMLENUM_BIG = RESOURCE_DIR + "xmlenum-big.xsd"; private static final String XMLELEMENTDECL = RESOURCE_DIR + "xmlelementdecl.xsd"; private static final String XMLELEMENTCOLLECTION = RESOURCE_DIR + "xmlelement-collection.xsd"; private static final String JAXBCUSTOM = RESOURCE_DIR + "jaxbcustom.xsd"; private static final String SUBSTITUTION = RESOURCE_DIR + "substitution.xsd"; private static final String NESTEDINNERCLASSES = RESOURCE_DIR + "nestedinnerclasses.xsd"; private static final String BINARY = RESOURCE_DIR + "binary.xsd"; private static final String BINARY2 = RESOURCE_DIR + "binary2.xsd"; private static final String XMLSCHEMASCHEMA = RESOURCE_DIR + "XMLSchema.xsd"; private static final String XPATH_POSITION = RESOURCE_DIR + "xpathposition.xsd"; private static final String DATETIME_ARRAY = RESOURCE_DIR + "dateTimeArray.xsd"; private static final String ECLIPSELINK_SCHEMA = "org/eclipse/persistence/jaxb/eclipselink_oxm_2_5.xsd"; // Test Instance Docs private static final String PERSON_XML = RESOURCE_DIR + "sub-person-en.xml"; private static final String PERSONNE_XML = RESOURCE_DIR + "sub-personne-fr.xml"; private static final String XPATH_POSITION_XML = RESOURCE_DIR + "xpathposition.xml"; private static final String DATETIME_ARRAY_XML = RESOURCE_DIR + "dateTimeArray.xml"; // Names of types to instantiate private static final String PACKAGE = "mynamespace"; private static final String DEF_PACKAGE = "generated"; private static final String BANK_PACKAGE = "banknamespace"; private static final String PERSON = "Person"; private static final String EMPLOYEE = "Employee"; private static final String INDIVIDUO = "Individuo"; private static final String CDN_CURRENCY = "CdnCurrency"; private static final String DATA = "Data"; private static final String COMPANY = "Company"; private static final String COMPASS_DIRECTION = "CompassDirection"; private static final String TIME_ZONE = "Timezone"; private static final String NORTH_CONSTANT = "NORTH"; private static final String EST_CONSTANT = "EST"; }<|fim▁end|>
Node node = marshalDoc.getDocumentElement();
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|><|fim▁hole|>pub mod vector; pub mod point; pub mod common; pub mod normal; pub mod ray; pub mod matrix;<|fim▁end|>
pub mod scalar;
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|><|fim▁hole|>from . import ir_ui_view<|fim▁end|>
<|file_name|>neo-validator.ts<|end_file_name|><|fim▁begin|>export class NeoValidator { static validateHeight(height: number) {<|fim▁hole|> } } static validateTransactionId(transactionId: string) { // TODO } }<|fim▁end|>
if (height <= 0) { throw new Error(`'height' must be an integer 1 or above.`)
<|file_name|>index.ts<|end_file_name|><|fim▁begin|>import turfbbox from '@turf/bbox'; import booleanPointInPolygon from '@turf/boolean-point-in-polygon'; import rbush from 'rbush'; import { FeatureCollection, Polygon, Feature, Point } from '@turf/helpers'; /** * Merges a specified property from a FeatureCollection of points into a * FeatureCollection of polygons. Given an `inProperty` on points and an `outProperty` * for polygons, this finds every point that lies within each polygon, collects the * `inProperty` values from those points, and adds them as an array to `outProperty` * on the polygon. *<|fim▁hole|> * @param {FeatureCollection<Polygon>} polygons polygons with values on which to aggregate * @param {FeatureCollection<Point>} points points to be aggregated * @param {string} inProperty property to be nested from * @param {string} outProperty property to be nested into * @returns {FeatureCollection<Polygon>} polygons with properties listed based on `outField` * @example * var poly1 = turf.polygon([[[0,0],[10,0],[10,10],[0,10],[0,0]]]); * var poly2 = turf.polygon([[[10,0],[20,10],[20,20],[20,0],[10,0]]]); * var polyFC = turf.featureCollection([poly1, poly2]); * var pt1 = turf.point([5,5], {population: 200}); * var pt2 = turf.point([1,3], {population: 600}); * var pt3 = turf.point([14,2], {population: 100}); * var pt4 = turf.point([13,1], {population: 200}); * var pt5 = turf.point([19,7], {population: 300}); * var pointFC = turf.featureCollection([pt1, pt2, pt3, pt4, pt5]); * var collected = turf.collect(polyFC, pointFC, 'population', 'values'); * var values = collected.features[0].properties.values * //=values => [200, 600] * * //addToMap * var addToMap = [pointFC, collected] */ function collect( polygons: FeatureCollection<Polygon>, points: FeatureCollection<Point>, inProperty: string, outProperty: string ): FeatureCollection<Polygon> { var rtree = rbush(6); var treeItems = points.features.map(function (item) { return { minX: item.geometry.coordinates[0], minY: item.geometry.coordinates[1], maxX: item.geometry.coordinates[0], maxY: item.geometry.coordinates[1], property: item.properties[inProperty] }; }); rtree.load(treeItems); polygons.features.forEach(function (poly) { if (!poly.properties) { poly.properties = {}; } var bbox = turfbbox(poly); var potentialPoints = rtree.search({minX: bbox[0], minY: bbox[1], maxX: bbox[2], maxY: bbox[3]}); var values = []; potentialPoints.forEach(function (pt) { if (booleanPointInPolygon([pt.minX, pt.minY], poly)) { values.push(pt.property); } }); poly.properties[outProperty] = values; }); return polygons; } export default collect;<|fim▁end|>
* @name collect
<|file_name|>test_codestyle.py<|end_file_name|><|fim▁begin|>import unittest import pycodestyle from os.path import exists <|fim▁hole|> def test_conformance(self): """Test that we conform to PEP-8.""" style = pycodestyle.StyleGuide(quiet=False, ignore=['E501', 'W605']) if exists('transitions'): # when run from root directory (e.g. tox) style.input_dir('transitions') style.input_dir('tests') else: # when run from test directory (e.g. pycharm) style.input_dir('../transitions') style.input_dir('.') result = style.check_files() self.assertEqual(result.total_errors, 0, "Found code style errors (and warnings).")<|fim▁end|>
class TestCodeFormat(unittest.TestCase):
<|file_name|>lpfhpfilter.cpp<|end_file_name|><|fim▁begin|>/** * The MIT License (MIT) * * adapted from musicdsp.org-post by [email protected] * * Copyright (c) 2013-2017 Igor Zinken - http://www.igorski.nl * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software.<|fim▁hole|> * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "lpfhpfilter.h" #include "../global.h" #include <math.h> namespace MWEngine { // constructor LPFHPFilter::LPFHPFilter( float aLPCutoff, float aHPCutoff, int amountOfChannels ) { setLPF( aLPCutoff, AudioEngineProps::SAMPLE_RATE ); setHPF( aHPCutoff, AudioEngineProps::SAMPLE_RATE ); outSamples = new SAMPLE_TYPE[ amountOfChannels ]; inSamples = new SAMPLE_TYPE[ amountOfChannels ]; for ( int i = 0; i < amountOfChannels; ++i ) { outSamples[ i ] = 0.0; inSamples[ i ] = 0.0; } } LPFHPFilter::~LPFHPFilter() { delete[] outSamples; delete[] inSamples; } /* public methods */ void LPFHPFilter::setLPF( float aCutOffFrequency, int aSampleRate ) { SAMPLE_TYPE w = 2.0 * aSampleRate; SAMPLE_TYPE Norm; aCutOffFrequency *= TWO_PI; Norm = 1.0 / ( aCutOffFrequency + w ); b1 = ( w - aCutOffFrequency ) * Norm; a0 = a1 = aCutOffFrequency * Norm; } void LPFHPFilter::setHPF( float aCutOffFrequency, int aSampleRate ) { SAMPLE_TYPE w = 2.0 * aSampleRate; SAMPLE_TYPE Norm; aCutOffFrequency *= TWO_PI; Norm = 1.0 / ( aCutOffFrequency + w ); a0 = w * Norm; a1 = -a0; b1 = ( w - aCutOffFrequency ) * Norm; } void LPFHPFilter::process( AudioBuffer* sampleBuffer, bool isMonoSource ) { int bufferSize = sampleBuffer->bufferSize; for ( int c = 0, ca = sampleBuffer->amountOfChannels; c < ca; ++c ) { SAMPLE_TYPE* channelBuffer = sampleBuffer->getBufferForChannel( c ); for ( int i = 0; i < bufferSize; ++i ) { SAMPLE_TYPE sample = channelBuffer[ i ]; channelBuffer[ i ] = sample * a0 + inSamples[ c ] * a1 + outSamples[ c ] * b1; inSamples[ c ] = sample; // store this unprocessed sample for next iteration outSamples[ c ] = channelBuffer[ i ]; // and the processed sample too } // save CPU cycles when source is mono if ( isMonoSource ) { sampleBuffer->applyMonoSource(); break; } } } } // E.O namespace MWEngine<|fim▁end|>
* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
<|file_name|>server.py<|end_file_name|><|fim▁begin|># nxt.server module -- LEGO Mindstorms NXT socket interface module # Copyright (C) 2009 Marcus Wanner # # 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. '''Use for a socket-interface NXT driver. Command and protocol docs at: http://code.google.com/p/nxt-python/wiki/ServerUsage''' import nxt.locator from nxt.motor import * from nxt.sensor import * from nxt.compass import * import socket, string, sys global brick host = '' port = 54174 outport = 54374 def _process_port(nxtport): if nxtport == 'A' or nxtport == 'a': nxtport = PORT_A elif nxtport == 'B' or nxtport == 'b': nxtport = PORT_B elif nxtport == 'C' or nxtport == 'c': nxtport = PORT_C elif nxtport == 'ALL' or nxtport == 'All' or nxtport == 'all': nxtport = PORT_ALL elif nxtport == '1': nxtport = PORT_1 elif nxtport == '2': nxtport = PORT_2 elif nxtport == '3': nxtport = PORT_3 elif nxtport == '4': nxtport = PORT_4 else: raise ValueError, 'Invalid port: '+nxtport return nxtport <|fim▁hole|> global brick retcode = 0 retmsg = '' #act on messages, these conditions can be in no particular order #it should send a return code on port 54374. 0 for success, 1 for failure #then an error message if cmd.startswith('find_brick'): try: brick = nxt.locator.find_one_brick() brick = brick.connect() retmsg = 'Connected to brick.' retcode = 0 except: retcode = 1 retmsg = str(sys.exc_info()[1]) elif cmd.startswith('get_touch_sample'): try: port = string.split(cmd, ':')[1] port = _process_port(port) retmsg = str(TouchSensor(brick, port).get_sample()) retcode = 0 except: retcode = 1 retmsg = str(sys.exc_info()[1]) elif cmd.startswith('get_sound_sample'): try: port = string.split(cmd, ':')[1] port = _process_port(port) retmsg = str(SoundSensor(brick, port).get_sample()) retcode = 0 except: retcode = 1 retmsg = str(sys.exc_info()[1]) elif cmd.startswith('get_light_sample'): try: data = string.split(cmd, ':')[1] data = string.split(data, ',') if len(data) > 1: #there is emit light data port, emit = data else: port, emit = data[0], False port = _process_port(port) light = LightSensor(brick, port) light.set_illuminated(emit) retmsg = str(light.get_sample()) light.set_illuminated(False) retcode = 0 except: retcode = 1 retmsg = str(sys.exc_info()[1]) elif cmd.startswith('get_ultrasonic_sample'): try: port = string.split(cmd, ':')[1] port = _process_port(port) retmsg = str(UltrasonicSensor(brick, port).get_sample()) retcode = 0 except: retcode = 1 retmsg = str(sys.exc_info()[1]) elif cmd.startswith('get_accelerometer_sample'): try: port = string.split(cmd, ':')[1] port = _process_port(port) retmsg = str(AccelerometerSensor(brick, port).get_sample()) retcode = 0 except: retcode = 1 retmsg = str(sys.exc_info()[1]) elif cmd.startswith('get_compass_sample'): try: port = string.split(cmd, ':')[1] port = _process_port(port) retmsg = str(CompassSensor(brick, port).get_sample()) retcode = 0 except: retcode = 1 retmsg = str(sys.exc_info()[1]) elif cmd.startswith('update_motor:'): try: #separate the information from the command keyword info = string.split(cmd, ':')[1] [port, power, tacholim] = string.split(info, ',') portarray = [] if port.count('(') > 0 and port.count(')') > 0: #there are more than 1 ports, separate them port = port.strip('()') #port.strip(')') port.replace(' ', '') for separateport in string.split(port, ';'): portarray.append(separateport) else: #one port, just use that portarray.append(port) #process the port for currentport in portarray: processedport = _process_port(currentport) Motor(brick, processedport).update(int(power), int(tacholim)) retmsg = 'Motor command succeded.' retcode = 0 except: retcode = 1 retmsg = str(sys.exc_info()[1]) elif cmd.startswith('run_motor:'): try: #separate the information from the command keyword info = string.split(cmd, ':')[1] [port, power, regulated] = string.split(info, ',') port = _process_port(port) Motor(brick, port).run(int(power), int(regulated)) retmsg = 'Motor run command succeded.' except: retcode = 1 retmsg = str(sys.exc_info()[1]) elif cmd.startswith('stop_motor:'): try: #separate the information from the command keyword info = string.split(cmd, ':')[1] [port, braking] = string.split(info, ',') port = _process_port(port) Motor(brick, port).stop(int(braking)) retmsg = 'Motor stop command succeded.' except: retcode = 1 retmsg = str(sys.exc_info()[1]) elif cmd.startswith('play_tone:'): try: #separate the information from the command keyword info = string.split(cmd, ':')[1] [freq, dur] = string.split(info, ',') #call the function brick.play_tone_and_wait(int(freq), int(dur)) retmsg = 'Tone command succeded.' retcode = 0 except: retcode = 1 retmsg = str(sys.exc_info()[1]) #close_brick elif cmd == 'close_brick': try: brick.close() retcode = 0 except: retcode = 1 retmsg = str(sys.exc_info()[1]) #command not recognised else: retmsg = 'Command not found.' retcode = 1 #then return 1 or 0 and a message return retcode, retmsg def serve_forever(password=None, authorizedips = []): '''Serve clients until the window is closed or there is an unhandled error. If you supply a password, then any ip that wants to control the NXT will have to send the password once to be authorized before any of the commands it sends will be carried out. authorizedips is a list of the ips that can have access to the NXT without supplying a password. Normally, this is left blank.''' #make sockets outsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) insock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) insock.bind((host, port)) while 1: #get a message from port on any host inmsg, (clientip,assignedport) = insock.recvfrom(100) #no commands can be longer than 100 chars #print a helpful message to the console. print 'Got command '+inmsg+' from '+clientip #process command if password: #password protection enabled try: authorizedips.index(clientip) #ip is authorized, and is therefore in the list of authorized ip code, message = _process_command(inmsg) #process the command as normal except ValueError: #ip not authorized, and therefore cannot be found in the list of authorized ips if inmsg == str(password): #command is the correct password authorizedips.append(clientip) code = 0 message = 'Authorization successful.' else: #command is not the password code = 1 message = 'NXT access on this server is password protected, please send correct password to be authorized.' else: #not password protected code, message = _process_command(inmsg) #send return code to the computer that send the request outsock.sendto(str(code) + message, (clientip, 54374)) #print a summany of the response print 'Sent return code '+str(code)+' with message "'+message+'" to '+clientip print '' #do again #serve automatically if the script is started #by double-clicking or by command line. if __name__ == '__main__': try: password = sys.argv[1] except: password = None serve_forever(password)<|fim▁end|>
def _process_command(cmd):
<|file_name|>Type.java<|end_file_name|><|fim▁begin|>/*The MIT License (MIT) <|fim▁hole|>in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Sogiftware. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.*/ package org.dvare.annotations; import org.dvare.expression.datatype.DataType; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) public @interface Type { DataType dataType(); }<|fim▁end|>
Copyright (c) 2016 Muhammad Hammad Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal
<|file_name|>etcd_node.rs<|end_file_name|><|fim▁begin|>use rustc_serialize::json; //use chrono::datetime::DateTime; //use chrono::offset::fixed::FixedOffset; #[derive(Debug)] pub struct EtcdNode { /// key: the HTTP path to which the request was made. etcd uses a file-system-like structure to represent the /// key-value pairs, therefore all keys start with /. pub key: String, /// createdIndex: an index is a unique, monotonically-incrementing integer created for each change to etcd. This /// specific index reflects the point in the etcd state member at which a given key was created.There are internal /// commands that also change the state behind the scenes, like adding and syncing servers. pub created_index: i64, /// modifiedIndex: like node.createdIndex, this attribute is also an etcd index. Actions that cause the value to /// change include set, delete, update, create, compareAndSwap and compareAndDelete. Since the get and watch /// commands do not change state in the store, they do not change the value of node.modifiedIndex. pub modified_index: i64, /// value: the value of the key after resolving the request. pub value: Option<String>, /// The expiration is the time at which this key will expire and be deleted. pub expiration: Option<String>, /// The ttl is the specified time to live for the key, in seconds. pub ttl: Option<i64>, /// this a directory pub dir: bool, // todo, should this be a map with the key derived from the path of the parent? /// the list of nodes in the directory pub nodes: Option<Vec<EtcdNode>>, } impl EtcdNode { pub fn from_json(obj: &json::Object) -> EtcdNode { return EtcdNode { key: obj.get("key").unwrap().as_string().unwrap().to_string(), created_index: obj.get("createdIndex").unwrap().as_i64().unwrap(), modified_index: obj.get("modifiedIndex").unwrap().as_i64().unwrap(), value: if let Some(j) = obj.get("value") { Some(j.as_string().unwrap().to_string()) } else { None }, expiration: if let Some(j) = obj.get("expiration") { Some(j.as_string().unwrap().to_string()) } else { None }, ttl: if let Some(j) = obj.get("ttl") { j.as_i64() } else { None }, dir: if let Some(j) = obj.get("dir") { j.as_boolean().unwrap() } else { false }, nodes: if let Some(j) = obj.get("nodes") { let arr: &Vec<json::Json> = j.as_array().unwrap(); let mut list: Vec<EtcdNode> = Vec::with_capacity(arr.len()); for n in arr { // these should be node list.push(EtcdNode::from_json(n.as_object().unwrap())); } Some(list) // the value } else { None }, } } } //// "20133-12-04T12:01:21.874888581-08:00" /*fn decode_tm_from_str<D: Decoder>(d: &mut D) -> Result<DateTime<FixedOffset>, D::Error> { let time_str = try!(d.read_str()); let parse_result = DateTime::parse_from_rfc3339(&time_str); println!("parse_result {:?}", parse_result); match parse_result { Ok(t) => return Ok(t), Err(e) => return Err(d.error(e.description())), } }*/ #[cfg(test)] mod tests { use rustc_serialize::json; use super::EtcdNode; static NODE_JSON: &'static str = "{ \"createdIndex\": 2, \"key\": \"/queue/2\", \"modifiedIndex\": 2, \"value\": \"Job1\" }"; static COMPLEX_NODE_JSON: &'static str = "{ \"createdIndex\": 2, \"dir\": true, \"key\": \"/queue\", \"modifiedIndex\": 2, \"nodes\": [ { \"createdIndex\": 2, \"key\": \"/queue/2\", \"modifiedIndex\": 2, \"value\": \"Job1\" }, { \"createdIndex\": 3, \"key\": \"/queue/3\", \"modifiedIndex\": 3, \"value\": \"Job2\" } ] }"; #[test] fn decode_node_json_test() { let json_tree = json::Json::from_str(NODE_JSON).unwrap(); let etcd_node = EtcdNode::from_json(json_tree.as_object().unwrap()); assert_eq!(&etcd_node.key as &str, "/queue/2"); assert_eq!(etcd_node.dir, false); assert_eq!(etcd_node.created_index, 2); assert_eq!(etcd_node.modified_index, 2); assert_eq!(&etcd_node.value.unwrap() as &str, "Job1"); } #[test] fn decode_complex_node_json_test() { let json_tree = json::Json::from_str(COMPLEX_NODE_JSON).unwrap(); let etcd_node = EtcdNode::from_json(json_tree.as_object().unwrap()); assert_eq!(&etcd_node.key as &str, "/queue"); assert_eq!(etcd_node.dir, true); assert_eq!(etcd_node.created_index, 2); assert_eq!(etcd_node.modified_index, 2);<|fim▁hole|> assert_eq!((&nodes[0]).created_index, 2); assert_eq!(&(&nodes[0]).key as &str, "/queue/2"); assert_eq!((&nodes[0]).modified_index, 2); assert_eq!((&nodes[0]).value.as_ref().unwrap() as &str, "Job1"); assert_eq!((&nodes[1]).created_index, 3); assert_eq!((&nodes[1]).key, "/queue/3".to_string()); assert_eq!((&nodes[1]).modified_index, 3); assert_eq!((&nodes[1]).value.as_ref().unwrap()as &str, "Job2"); } }<|fim▁end|>
assert_eq!(etcd_node.value, None); let ref nodes = etcd_node.nodes.unwrap();
<|file_name|>set.js<|end_file_name|><|fim▁begin|>require('ember-runtime/core'); require('ember-runtime/system/core_object'); require('ember-runtime/mixins/mutable_enumerable'); require('ember-runtime/mixins/copyable'); require('ember-runtime/mixins/freezable'); /** @module ember @submodule ember-runtime */ var get = Ember.get, set = Ember.set, guidFor = Ember.guidFor, isNone = Ember.isNone, fmt = Ember.String.fmt; /** An unordered collection of objects. A Set works a bit like an array except that its items are not ordered. You can create a set to efficiently test for membership for an object. You can also iterate through a set just like an array, even accessing objects by index, however there is no guarantee as to their order. All Sets are observable via the Enumerable Observer API - which works on any enumerable object including both Sets and Arrays. ## Creating a Set You can create a set like you would most objects using `new Ember.Set()`. Most new sets you create will be empty, but you can also initialize the set with some content by passing an array or other enumerable of objects to the constructor. Finally, you can pass in an existing set and the set will be copied. You can also create a copy of a set by calling `Ember.Set#copy()`. ```javascript // creates a new empty set var foundNames = new Ember.Set(); // creates a set with four names in it. var names = new Ember.Set(["Charles", "Tom", "Juan", "Alex"]); // :P // creates a copy of the names set. var namesCopy = new Ember.Set(names); // same as above. var anotherNamesCopy = names.copy(); ``` ## Adding/Removing Objects You generally add or remove objects from a set using `add()` or `remove()`. You can add any type of object including primitives such as numbers, strings, and booleans. Unlike arrays, objects can only exist one time in a set. If you call `add()` on a set with the same object multiple times, the object will only be added once. Likewise, calling `remove()` with the same object multiple times will remove the object the first time and have no effect on future calls until you add the object to the set again. NOTE: You cannot add/remove `null` or `undefined` to a set. Any attempt to do so will be ignored. In addition to add/remove you can also call `push()`/`pop()`. Push behaves just like `add()` but `pop()`, unlike `remove()` will pick an arbitrary object, remove it and return it. This is a good way to use a set as a job queue when you don't care which order the jobs are executed in. ## Testing for an Object To test for an object's presence in a set you simply call `Ember.Set#contains()`. ## Observing changes When using `Ember.Set`, you can observe the `"[]"` property to be alerted whenever the content changes. You can also add an enumerable observer to the set to be notified of specific objects that are added and removed from the set. See `Ember.Enumerable` for more information on<|fim▁hole|> it is very inefficient to re-filter all of the items each time the set changes. It would be better if you could just adjust the filtered set based on what was changed on the original set. The same issue applies to merging sets, as well. ## Other Methods `Ember.Set` primary implements other mixin APIs. For a complete reference on the methods you will use with `Ember.Set`, please consult these mixins. The most useful ones will be `Ember.Enumerable` and `Ember.MutableEnumerable` which implement most of the common iterator methods you are used to on Array. Note that you can also use the `Ember.Copyable` and `Ember.Freezable` APIs on `Ember.Set` as well. Once a set is frozen it can no longer be modified. The benefit of this is that when you call `frozenCopy()` on it, Ember will avoid making copies of the set. This allows you to write code that can know with certainty when the underlying set data will or will not be modified. @class Set @namespace Ember @extends Ember.CoreObject @uses Ember.MutableEnumerable @uses Ember.Copyable @uses Ember.Freezable @since Ember 0.9 */ Ember.Set = Ember.CoreObject.extend(Ember.MutableEnumerable, Ember.Copyable, Ember.Freezable, /** @scope Ember.Set.prototype */ { // .......................................................... // IMPLEMENT ENUMERABLE APIS // /** This property will change as the number of objects in the set changes. @property length @type number @default 0 */ length: 0, /** Clears the set. This is useful if you want to reuse an existing set without having to recreate it. ```javascript var colors = new Ember.Set(["red", "green", "blue"]); colors.length; // 3 colors.clear(); colors.length; // 0 ``` @method clear @return {Ember.Set} An empty Set */ clear: function() { if (this.isFrozen) { throw new Error(Ember.FROZEN_ERROR); } var len = get(this, 'length'); if (len === 0) { return this; } var guid; this.enumerableContentWillChange(len, 0); Ember.propertyWillChange(this, 'firstObject'); Ember.propertyWillChange(this, 'lastObject'); for (var i=0; i < len; i++){ guid = guidFor(this[i]); delete this[guid]; delete this[i]; } set(this, 'length', 0); Ember.propertyDidChange(this, 'firstObject'); Ember.propertyDidChange(this, 'lastObject'); this.enumerableContentDidChange(len, 0); return this; }, /** Returns true if the passed object is also an enumerable that contains the same objects as the receiver. ```javascript var colors = ["red", "green", "blue"], same_colors = new Ember.Set(colors); same_colors.isEqual(colors); // true same_colors.isEqual(["purple", "brown"]); // false ``` @method isEqual @param {Ember.Set} obj the other object. @return {Boolean} */ isEqual: function(obj) { // fail fast if (!Ember.Enumerable.detect(obj)) return false; var loc = get(this, 'length'); if (get(obj, 'length') !== loc) return false; while(--loc >= 0) { if (!obj.contains(this[loc])) return false; } return true; }, /** Adds an object to the set. Only non-`null` objects can be added to a set and those can only be added once. If the object is already in the set or the passed value is null this method will have no effect. This is an alias for `Ember.MutableEnumerable.addObject()`. ```javascript var colors = new Ember.Set(); colors.add("blue"); // ["blue"] colors.add("blue"); // ["blue"] colors.add("red"); // ["blue", "red"] colors.add(null); // ["blue", "red"] colors.add(undefined); // ["blue", "red"] ``` @method add @param {Object} obj The object to add. @return {Ember.Set} The set itself. */ add: Ember.aliasMethod('addObject'), /** Removes the object from the set if it is found. If you pass a `null` value or an object that is already not in the set, this method will have no effect. This is an alias for `Ember.MutableEnumerable.removeObject()`. ```javascript var colors = new Ember.Set(["red", "green", "blue"]); colors.remove("red"); // ["blue", "green"] colors.remove("purple"); // ["blue", "green"] colors.remove(null); // ["blue", "green"] ``` @method remove @param {Object} obj The object to remove @return {Ember.Set} The set itself. */ remove: Ember.aliasMethod('removeObject'), /** Removes the last element from the set and returns it, or `null` if it's empty. ```javascript var colors = new Ember.Set(["green", "blue"]); colors.pop(); // "blue" colors.pop(); // "green" colors.pop(); // null ``` @method pop @return {Object} The removed object from the set or null. */ pop: function() { if (get(this, 'isFrozen')) throw new Error(Ember.FROZEN_ERROR); var obj = this.length > 0 ? this[this.length-1] : null; this.remove(obj); return obj; }, /** Inserts the given object on to the end of the set. It returns the set itself. This is an alias for `Ember.MutableEnumerable.addObject()`. ```javascript var colors = new Ember.Set(); colors.push("red"); // ["red"] colors.push("green"); // ["red", "green"] colors.push("blue"); // ["red", "green", "blue"] ``` @method push @return {Ember.Set} The set itself. */ push: Ember.aliasMethod('addObject'), /** Removes the last element from the set and returns it, or `null` if it's empty. This is an alias for `Ember.Set.pop()`. ```javascript var colors = new Ember.Set(["green", "blue"]); colors.shift(); // "blue" colors.shift(); // "green" colors.shift(); // null ``` @method shift @return {Object} The removed object from the set or null. */ shift: Ember.aliasMethod('pop'), /** Inserts the given object on to the end of the set. It returns the set itself. This is an alias of `Ember.Set.push()` ```javascript var colors = new Ember.Set(); colors.unshift("red"); // ["red"] colors.unshift("green"); // ["red", "green"] colors.unshift("blue"); // ["red", "green", "blue"] ``` @method unshift @return {Ember.Set} The set itself. */ unshift: Ember.aliasMethod('push'), /** Adds each object in the passed enumerable to the set. This is an alias of `Ember.MutableEnumerable.addObjects()` ```javascript var colors = new Ember.Set(); colors.addEach(["red", "green", "blue"]); // ["red", "green", "blue"] ``` @method addEach @param {Ember.Enumerable} objects the objects to add. @return {Ember.Set} The set itself. */ addEach: Ember.aliasMethod('addObjects'), /** Removes each object in the passed enumerable to the set. This is an alias of `Ember.MutableEnumerable.removeObjects()` ```javascript var colors = new Ember.Set(["red", "green", "blue"]); colors.removeEach(["red", "blue"]); // ["green"] ``` @method removeEach @param {Ember.Enumerable} objects the objects to remove. @return {Ember.Set} The set itself. */ removeEach: Ember.aliasMethod('removeObjects'), // .......................................................... // PRIVATE ENUMERABLE SUPPORT // init: function(items) { this._super(); if (items) this.addObjects(items); }, // implement Ember.Enumerable nextObject: function(idx) { return this[idx]; }, // more optimized version firstObject: Ember.computed(function() { return this.length > 0 ? this[0] : undefined; }), // more optimized version lastObject: Ember.computed(function() { return this.length > 0 ? this[this.length-1] : undefined; }), // implements Ember.MutableEnumerable addObject: function(obj) { if (get(this, 'isFrozen')) throw new Error(Ember.FROZEN_ERROR); if (isNone(obj)) return this; // nothing to do var guid = guidFor(obj), idx = this[guid], len = get(this, 'length'), added ; if (idx>=0 && idx<len && (this[idx] === obj)) return this; // added added = [obj]; this.enumerableContentWillChange(null, added); Ember.propertyWillChange(this, 'lastObject'); len = get(this, 'length'); this[guid] = len; this[len] = obj; set(this, 'length', len+1); Ember.propertyDidChange(this, 'lastObject'); this.enumerableContentDidChange(null, added); return this; }, // implements Ember.MutableEnumerable removeObject: function(obj) { if (get(this, 'isFrozen')) throw new Error(Ember.FROZEN_ERROR); if (isNone(obj)) return this; // nothing to do var guid = guidFor(obj), idx = this[guid], len = get(this, 'length'), isFirst = idx === 0, isLast = idx === len-1, last, removed; if (idx>=0 && idx<len && (this[idx] === obj)) { removed = [obj]; this.enumerableContentWillChange(removed, null); if (isFirst) { Ember.propertyWillChange(this, 'firstObject'); } if (isLast) { Ember.propertyWillChange(this, 'lastObject'); } // swap items - basically move the item to the end so it can be removed if (idx < len-1) { last = this[len-1]; this[idx] = last; this[guidFor(last)] = idx; } delete this[guid]; delete this[len-1]; set(this, 'length', len-1); if (isFirst) { Ember.propertyDidChange(this, 'firstObject'); } if (isLast) { Ember.propertyDidChange(this, 'lastObject'); } this.enumerableContentDidChange(removed, null); } return this; }, // optimized version contains: function(obj) { return this[guidFor(obj)]>=0; }, copy: function() { var C = this.constructor, ret = new C(), loc = get(this, 'length'); set(ret, 'length', loc); while(--loc>=0) { ret[loc] = this[loc]; ret[guidFor(this[loc])] = loc; } return ret; }, toString: function() { var len = this.length, idx, array = []; for(idx = 0; idx < len; idx++) { array[idx] = this[idx]; } return fmt("Ember.Set<%@>", [array.join(',')]); } });<|fim▁end|>
enumerables. This is often unhelpful. If you are filtering sets of objects, for instance,
<|file_name|>no_0977_squares_of_a_sorted_array.rs<|end_file_name|><|fim▁begin|>struct Solution; impl Solution { // 官方题解中的思路 pub fn sorted_squares(a: Vec<i32>) -> Vec<i32> { let mut ans = vec![0; a.len()]; if a.is_empty() { return ans; } // 这个减少了一半的时间。 if a[0] >= 0 { return a.into_iter().map(|v| v * v).collect(); } let (mut l, mut r) = (0, a.len() - 1); // 选择 l 和 r 中较大的那个,逆序放入 ans 中。 for pos in (0..a.len()).rev() { if a[l].abs() > a[r].abs() { ans[pos] = a[l].pow(2); l += 1; } else { ans[pos] = a[r].pow(2); if r == 0 { break; } r -= 1; } } ans } pub fn sorted_squares1(a: Vec<i32>) -> Vec<i32> { if a.is_empty() { return Vec::new(); } if a[0] >= 0 { return a.into_iter().map(|v| v * v).collect(); } let n = a.len(); // 第一个 >= 0 的索引,或者 a.len() let r = a.iter().position(|&v| v >= 0); let mut r = r.unwrap_or(n); let mut l = r as isize - 1; let mut ans = Vec::with_capacity(n); while l >= 0 && r < a.len() { if a[l as usize].abs() < a[r] { ans.push(a[l as usize].pow(2)); l -= 1; } else { ans.push(a[r].pow(2)); r += 1; } }<|fim▁hole|> } } for i in r..n { ans.push(a[i].pow(2)); } ans } } #[cfg(test)] mod tests { use super::*; #[test] fn test_sorted_squares() { assert_eq!( Solution::sorted_squares(vec![-4, -1, 0, 3, 10]), vec![0, 1, 9, 16, 100] ); assert_eq!( Solution::sorted_squares(vec![-7, -3, 2, 3, 11]), vec![4, 9, 9, 49, 121] ); } }<|fim▁end|>
if l >= 0 { for i in (0..=l as usize).rev() { ans.push(a[i].pow(2));
<|file_name|>settings.py<|end_file_name|><|fim▁begin|>""" Django settings for Outcumbent project. For more information on this file, see https://docs.djangoproject.com/en/1.6/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.6/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) TEMPLATE_DIRS = ('templates') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '3&@zwum@#!0f+g(k-pvlw#9n05t$kuz_5db58-02739t+u*u(r' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True TEMPLATE_DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin', 'outcumbent', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'Outcumbent.urls' WSGI_APPLICATION = 'Outcumbent.wsgi.application' <|fim▁hole|> # Database # https://docs.djangoproject.com/en/1.6/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'outcumbentdb', 'USER': 'root', #'PASSWORD': 'root', 'HOST': '127.0.0.1', 'PORT': '3306' } } # Internationalization # https://docs.djangoproject.com/en/1.6/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.6/howto/static-files/ STATIC_URL = '/static/'<|fim▁end|>
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #![recursion_limit = "128"] mod ext; mod repr; use proc_macro2::Span; use syn::visit::{self, Visit}; use syn::{ parse_quote, punctuated::Punctuated, token::Comma, Data, DataEnum, DataStruct, DeriveInput, Error, GenericParam, Ident, Lifetime, Type, TypePath, }; use synstructure::{decl_derive, quote, Structure}; use ext::*; use repr::*; // TODO(joshlf): Some errors could be made better if we could add multiple lines // of error output like this: // // error: unsupported representation // --> enum.rs:28:8 // | // 28 | #[repr(transparent)] // | // help: required by the derive of FromBytes // // Instead, we have more verbose error messages like "unsupported representation // for deriving FromBytes, AsBytes, or Unaligned on an enum" // // This will probably require Span::error // (https://doc.rust-lang.org/nightly/proc_macro/struct.Span.html#method.error), // which is currently unstable. Revisit this once it's stable. decl_derive!([FromBytes] => derive_from_bytes); decl_derive!([AsBytes] => derive_as_bytes); decl_derive!([Unaligned] => derive_unaligned); fn derive_from_bytes(s: Structure<'_>) -> proc_macro2::TokenStream { match &s.ast().data { Data::Struct(strct) => derive_from_bytes_struct(&s, strct), Data::Enum(enm) => derive_from_bytes_enum(&s, enm), Data::Union(_) => Error::new(Span::call_site(), "unsupported on unions").to_compile_error(), } } fn derive_as_bytes(s: Structure<'_>) -> proc_macro2::TokenStream { match &s.ast().data { Data::Struct(strct) => derive_as_bytes_struct(&s, strct), Data::Enum(enm) => derive_as_bytes_enum(&s, enm), Data::Union(_) => Error::new(Span::call_site(), "unsupported on unions").to_compile_error(), } } fn derive_unaligned(s: Structure<'_>) -> proc_macro2::TokenStream { match &s.ast().data { Data::Struct(strct) => derive_unaligned_struct(&s, strct), Data::Enum(enm) => derive_unaligned_enum(&s, enm), Data::Union(_) => Error::new(Span::call_site(), "unsupported on unions").to_compile_error(), } } // Unwrap a Result<_, Vec<Error>>, converting any Err value into a TokenStream // and returning it. macro_rules! try_or_print { ($e:expr) => { match $e { Ok(x) => x, Err(errors) => return print_all_errors(errors), } }; } // A struct is FromBytes if: // - all fields are FromBytes fn derive_from_bytes_struct(s: &Structure<'_>, strct: &DataStruct) -> proc_macro2::TokenStream { impl_block(s.ast(), strct, "FromBytes", true, false) } // An enum is FromBytes if: // - Every possible bit pattern must be valid, which means that every bit // pattern must correspond to a different enum variant. Thus, for an enum // whose layout takes up N bytes, there must be 2^N variants. // - Since we must know N, only representations which guarantee the layout's // size are allowed. These are repr(uN) and repr(iN) (repr(C) implies an // implementation-defined size). size and isize technically guarantee the // layout's size, but would require us to know how large those are on the // target platform. This isn't terribly difficult - we could emit a const // expression that could call core::mem::size_of in order to determine the // size and check against the number of enum variants, but a) this would be // platform-specific and, b) even on Rust's smallest bit width platform (32), // this would require ~4 billion enum variants, which obviously isn't a thing. fn derive_from_bytes_enum(s: &Structure<'_>, enm: &DataEnum) -> proc_macro2::TokenStream { if !enm.is_c_like() { return Error::new_spanned(s.ast(), "only C-like enums can implement FromBytes") .to_compile_error(); } let reprs = try_or_print!(ENUM_FROM_BYTES_CFG.validate_reprs(s.ast())); let variants_required = match reprs.as_slice() { [EnumRepr::U8] | [EnumRepr::I8] => 1usize << 8, [EnumRepr::U16] | [EnumRepr::I16] => 1usize << 16, // validate_reprs has already validated that it's one of the preceding // patterns _ => unreachable!(), }; if enm.variants.len() != variants_required { return Error::new_spanned( s.ast(), format!( "FromBytes only supported on {} enum with {} variants", reprs[0], variants_required ), ) .to_compile_error(); } impl_block(s.ast(), enm, "FromBytes", true, false) } #[rustfmt::skip] const ENUM_FROM_BYTES_CFG: Config<EnumRepr> = { use EnumRepr::*; Config { allowed_combinations_message: r#"FromBytes requires repr of "u8", "u16", "i8", or "i16""#, derive_unaligned: false, allowed_combinations: &[ &[U8], &[U16], &[I8], &[I16], ], disallowed_but_legal_combinations: &[ &[C], &[U32], &[I32], &[U64], &[I64], &[Usize], &[Isize], ], } };<|fim▁hole|>// - all fields are AsBytes // - repr(C) or repr(transparent) and // - no padding (size of struct equals sum of size of field types) // - repr(packed) fn derive_as_bytes_struct(s: &Structure<'_>, strct: &DataStruct) -> proc_macro2::TokenStream { // TODO(joshlf): Support type parameters. if !s.ast().generics.params.is_empty() { return Error::new(Span::call_site(), "unsupported on types with type parameters") .to_compile_error(); } let reprs = try_or_print!(STRUCT_AS_BYTES_CFG.validate_reprs(s.ast())); let require_size_check = match reprs.as_slice() { [StructRepr::C] | [StructRepr::Transparent] => true, [StructRepr::Packed] | [StructRepr::C, StructRepr::Packed] => false, // validate_reprs has already validated that it's one of the preceding // patterns _ => unreachable!(), }; impl_block(s.ast(), strct, "AsBytes", true, require_size_check) } #[rustfmt::skip] const STRUCT_AS_BYTES_CFG: Config<StructRepr> = { use StructRepr::*; Config { // NOTE: Since disallowed_but_legal_combinations is empty, this message // will never actually be emitted. allowed_combinations_message: r#"AsBytes requires repr of "C", "transparent", or "packed""#, derive_unaligned: false, allowed_combinations: &[ &[C], &[Transparent], &[C, Packed], &[Packed], ], disallowed_but_legal_combinations: &[], } }; // An enum is AsBytes if it is C-like and has a defined repr fn derive_as_bytes_enum(s: &Structure<'_>, enm: &DataEnum) -> proc_macro2::TokenStream { if !enm.is_c_like() { return Error::new_spanned(s.ast(), "only C-like enums can implement AsBytes") .to_compile_error(); } // We don't care what the repr is; we only care that it is one of the // allowed ones. try_or_print!(ENUM_AS_BYTES_CFG.validate_reprs(s.ast())); impl_block(s.ast(), enm, "AsBytes", false, false) } #[rustfmt::skip] const ENUM_AS_BYTES_CFG: Config<EnumRepr> = { use EnumRepr::*; Config { // NOTE: Since disallowed_but_legal_combinations is empty, this message // will never actually be emitted. allowed_combinations_message: r#"AsBytes requires repr of "C", "u8", "u16", "u32", "u64", "usize", "i8", "i16", "i32", "i64", or "isize""#, derive_unaligned: false, allowed_combinations: &[ &[C], &[U8], &[U16], &[I8], &[I16], &[U32], &[I32], &[U64], &[I64], &[Usize], &[Isize], ], disallowed_but_legal_combinations: &[], } }; // A struct is Unaligned if: // - repr(align) is no more than 1 and either // - repr(C) or repr(transparent) and // - all fields Unaligned // - repr(packed) fn derive_unaligned_struct(s: &Structure<'_>, strct: &DataStruct) -> proc_macro2::TokenStream { let reprs = try_or_print!(STRUCT_UNALIGNED_CFG.validate_reprs(s.ast())); let require_trait_bound = match reprs.as_slice() { [StructRepr::C] | [StructRepr::Transparent] => true, [StructRepr::Packed] | [StructRepr::C, StructRepr::Packed] => false, // validate_reprs has already validated that it's one of the preceding // patterns _ => unreachable!(), }; impl_block(s.ast(), strct, "Unaligned", require_trait_bound, false) } #[rustfmt::skip] const STRUCT_UNALIGNED_CFG: Config<StructRepr> = { use StructRepr::*; Config { // NOTE: Since disallowed_but_legal_combinations is empty, this message // will never actually be emitted. allowed_combinations_message: r#"Unaligned requires either a) repr "C" or "transparent" with all fields implementing Unaligned or, b) repr "packed""#, derive_unaligned: true, allowed_combinations: &[ &[C], &[Transparent], &[Packed], &[C, Packed], ], disallowed_but_legal_combinations: &[], } }; // An enum is Unaligned if: // - No repr(align(N > 1)) // - repr(u8) or repr(i8) fn derive_unaligned_enum(s: &Structure<'_>, enm: &DataEnum) -> proc_macro2::TokenStream { if !enm.is_c_like() { return Error::new_spanned(s.ast(), "only C-like enums can implement Unaligned") .to_compile_error(); } // The only valid reprs are u8 and i8, and optionally align(1). We don't // actually care what the reprs are so long as they satisfy that // requirement. try_or_print!(ENUM_UNALIGNED_CFG.validate_reprs(s.ast())); // NOTE: C-like enums cannot currently have type parameters, so this value // of true for require_trait_bounds doesn't really do anything. But it's // marginally more future-proof in case that restriction is lifted in the // future. impl_block(s.ast(), enm, "Unaligned", true, false) } #[rustfmt::skip] const ENUM_UNALIGNED_CFG: Config<EnumRepr> = { use EnumRepr::*; Config { allowed_combinations_message: r#"Unaligned requires repr of "u8" or "i8", and no alignment (i.e., repr(align(N > 1)))"#, derive_unaligned: true, allowed_combinations: &[ &[U8], &[I8], ], disallowed_but_legal_combinations: &[ &[C], &[U16], &[U32], &[U64], &[Usize], &[I16], &[I32], &[I64], &[Isize], ], } }; fn impl_block<D: DataExt>( input: &DeriveInput, data: &D, trait_name: &str, require_trait_bound: bool, require_size_check: bool, ) -> proc_macro2::TokenStream { // In this documentation, we will refer to this hypothetical struct: // // #[derive(FromBytes)] // struct Foo<T, I: Iterator> // where // T: Copy, // I: Clone, // I::Item: Clone, // { // a: u8, // b: T, // c: I::Item, // } // // First, we extract the field types, which in this case are u8, T, and // I::Item. We use the names of the type parameters to split the field types // into two sets - a set of types which are based on the type parameters, // and a set of types which are not. First, we re-use the existing // parameters and where clauses, generating an impl block like: // // impl<T, I: Iterator> FromBytes for Foo<T, I> // where // T: Copy, // I: Clone, // I::Item: Clone, // { // } // // Then, we use the list of types which are based on the type parameters to // generate new entries in the where clause: // // impl<T, I: Iterator> FromBytes for Foo<T, I> // where // T: Copy, // I: Clone, // I::Item: Clone, // T: FromBytes, // I::Item: FromBytes, // { // } // // Finally, we use a different technique to generate the bounds for the types // which are not based on type parameters: // // // fn only_derive_is_allowed_to_implement_this_trait() where Self: Sized { // struct ImplementsFromBytes<F: ?Sized + FromBytes>(PhantomData<F>); // let _: ImplementsFromBytes<u8>; // } // // It would be easier to put all types in the where clause, but that won't // work until the trivial_bounds feature is stabilized (#48214). // // NOTE: It is standard practice to only emit bounds for the type parameters // themselves, not for field types based on those parameters (e.g., `T` vs // `T::Foo`). For a discussion of why this is standard practice, see // https://github.com/rust-lang/rust/issues/26925. // // The reason we diverge from this standard is that doing it that way for us // would be unsound. E.g., consider a type, `T` where `T: FromBytes` but // `T::Foo: !FromBytes`. It would not be sound for us to accept a type with // a `T::Foo` field as `FromBytes` simply because `T: FromBytes`. // // While there's no getting around this requirement for us, it does have // some pretty serious downsides that are worth calling out: // // 1. You lose the ability to have fields of generic type with reduced visibility. // // #[derive(Unaligned)] // #[repr(C)] // pub struct Public<T>(Private<T>); // // #[derive(Unaligned)] // #[repr(C)] // struct Private<T>(T); // // // warning: private type `Private<T>` in public interface (error E0446) // --> src/main.rs:6:10 // | // 6 | #[derive(Unaligned)] // | ^^^^^^^^^ // | // = note: #[warn(private_in_public)] on by default // = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! // = note: for more information, see issue #34537 <https://github.com/rust-lang/rust/issues/34537> // // 2. When lifetimes are involved, the trait solver ties itself in knots. // // #[derive(Unaligned)] // #[repr(C)] // struct Dup<'a, 'b> { // a: PhantomData<&'a u8>, // b: PhantomData<&'b u8>, // } // // // error[E0283]: type annotations required: cannot resolve `core::marker::PhantomData<&'a u8>: zerocopy::Unaligned` // --> src/main.rs:6:10 // | // 6 | #[derive(Unaligned)] // | ^^^^^^^^^ // | // = note: required by `zerocopy::Unaligned` // A visitor which is used to walk a field's type and determine whether any // of its definition is based on the type or lifetime parameters on a type. struct FromTypeParamVisit<'a, 'b>(&'a Punctuated<GenericParam, Comma>, &'b mut bool); impl<'a, 'b> Visit<'a> for FromTypeParamVisit<'a, 'b> { fn visit_type_path(&mut self, i: &'a TypePath) { visit::visit_type_path(self, i); if self.0.iter().any(|param| { if let GenericParam::Type(param) = param { i.path.segments.first().unwrap().ident == param.ident } else { false } }) { *self.1 = true; } } fn visit_lifetime(&mut self, i: &'a Lifetime) { visit::visit_lifetime(self, i); if self.0.iter().any(|param| { if let GenericParam::Lifetime(param) = param { param.lifetime.ident == i.ident } else { false } }) { *self.1 = true; } } } // Whether this type is based on one of the type parameters. E.g., given the // type parameters `<T>`, `T`, `T::Foo`, and `(T::Foo, String)` are all // based on the type parameters, while `String` and `(String, Box<()>)` are // not. let is_from_type_param = |ty: &Type| { let mut ret = false; FromTypeParamVisit(&input.generics.params, &mut ret).visit_type(ty); ret }; let trait_ident = Ident::new(trait_name, Span::call_site()); let field_types = data.nested_types(); let type_param_field_types = field_types.iter().filter(|ty| is_from_type_param(ty)); let non_type_param_field_types = field_types.iter().filter(|ty| !is_from_type_param(ty)); // Add a new set of where clause predicates of the form `T: Trait` for each // of the types of the struct's fields (but only the ones whose types are // based on one of the type parameters). let mut generics = input.generics.clone(); let where_clause = generics.make_where_clause(); if require_trait_bound { for ty in type_param_field_types { let bound = parse_quote!(#ty: zerocopy::#trait_ident); where_clause.predicates.push(bound); } } let type_ident = &input.ident; // The parameters with trait bounds, but without type defaults. let params = input.generics.params.clone().into_iter().map(|mut param| { match &mut param { GenericParam::Type(ty) => ty.default = None, GenericParam::Const(cnst) => cnst.default = None, GenericParam::Lifetime(_) => {} } quote!(#param) }); // The identifiers of the parameters without trait bounds or type defaults. let param_idents = input.generics.params.iter().map(|param| match param { GenericParam::Type(ty) => { let ident = &ty.ident; quote!(#ident) } GenericParam::Lifetime(l) => quote!(#l), GenericParam::Const(cnst) => quote!(#cnst), }); let trait_bound_body = if require_trait_bound { let implements_type_ident = Ident::new(format!("Implements{}", trait_ident).as_str(), Span::call_site()); let implements_type_tokens = quote!(#implements_type_ident); let types = non_type_param_field_types.map(|ty| quote!(#implements_type_tokens<#ty>)); quote!( // A type with a type parameter that must implement #trait_ident struct #implements_type_ident<F: ?Sized + zerocopy::#trait_ident>(::core::marker::PhantomData<F>); // For each field type, an instantiation that won't type check if // that type doesn't implement #trait_ident #(let _: #types;)* ) } else { quote!() }; let size_check_body = if require_size_check && !field_types.is_empty() { quote!( const HAS_PADDING: bool = core::mem::size_of::<#type_ident>() != #(core::mem::size_of::<#field_types>())+*; let _: [(); 1/(1 - HAS_PADDING as usize)]; ) } else { quote!() }; quote! { unsafe impl < #(#params),* > zerocopy::#trait_ident for #type_ident < #(#param_idents),* > #where_clause { fn only_derive_is_allowed_to_implement_this_trait() where Self: Sized { #trait_bound_body #size_check_body } } } } fn print_all_errors(errors: Vec<Error>) -> proc_macro2::TokenStream { errors.iter().map(Error::to_compile_error).collect() } #[cfg(test)] mod tests { use super::*; #[test] fn test_config_repr_orderings() { // Validate that the repr lists in the various configs are in the // canonical order. If they aren't, then our algorithm to look up in // those lists won't work. // TODO(joshlf): Remove once the is_sorted method is stabilized // (issue #53485). fn is_sorted_and_deduped<T: Clone + Ord>(ts: &[T]) -> bool { let mut sorted = ts.to_vec(); sorted.sort(); sorted.dedup(); ts == sorted.as_slice() } fn elements_are_sorted_and_deduped<T: Clone + Ord>(lists: &[&[T]]) -> bool { lists.iter().all(|list| is_sorted_and_deduped(*list)) } fn config_is_sorted<T: KindRepr + Clone>(config: &Config<T>) -> bool { elements_are_sorted_and_deduped(&config.allowed_combinations) && elements_are_sorted_and_deduped(&config.disallowed_but_legal_combinations) } assert!(config_is_sorted(&STRUCT_UNALIGNED_CFG)); assert!(config_is_sorted(&ENUM_FROM_BYTES_CFG)); assert!(config_is_sorted(&ENUM_UNALIGNED_CFG)); } #[test] fn test_config_repr_no_overlap() { // Validate that no set of reprs appears in both th allowed_combinations // and disallowed_but_legal_combinations lists. fn overlap<T: Eq>(a: &[T], b: &[T]) -> bool { a.iter().any(|elem| b.contains(elem)) } fn config_overlaps<T: KindRepr + Eq>(config: &Config<T>) -> bool { overlap(config.allowed_combinations, config.disallowed_but_legal_combinations) } assert!(!config_overlaps(&STRUCT_UNALIGNED_CFG)); assert!(!config_overlaps(&ENUM_FROM_BYTES_CFG)); assert!(!config_overlaps(&ENUM_UNALIGNED_CFG)); } }<|fim▁end|>
// A struct is AsBytes if:
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from __future__ import unicode_literals import logging # Logging configuration log = logging.getLogger(__name__) # noqa log.addHandler(logging.NullHandler()) # noqa from netmiko.ssh_dispatcher import ConnectHandler from netmiko.ssh_dispatcher import ssh_dispatcher from netmiko.ssh_dispatcher import redispatch from netmiko.ssh_dispatcher import platforms from netmiko.ssh_dispatcher import FileTransfer from netmiko.scp_handler import SCPConn from netmiko.cisco.cisco_ios import InLineTransfer from netmiko.ssh_exception import NetMikoTimeoutException from netmiko.ssh_exception import NetMikoAuthenticationException from netmiko.ssh_autodetect import SSHDetect from netmiko.base_connection import BaseConnection # Alternate naming NetmikoTimeoutError = NetMikoTimeoutException NetmikoAuthError = NetMikoAuthenticationException __version__ = '2.0.1' __all__ = ('ConnectHandler', 'ssh_dispatcher', 'platforms', 'SCPConn', 'FileTransfer', 'NetMikoTimeoutException', 'NetMikoAuthenticationException', 'NetmikoTimeoutError', 'NetmikoAuthError', 'InLineTransfer', 'redispatch',<|fim▁hole|><|fim▁end|>
'SSHDetect', 'BaseConnection') # Cisco cntl-shift-six sequence CNTL_SHIFT_6 = chr(30)
<|file_name|>core.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Copyright (c) 2013–2015Molly White # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import codecs, logging, os, util from tokenizer import Tokenizer from tokenparser import Parser from api import Document def setup_logging(): logger=logging.getLogger("W2L") logger.setLevel(logging.DEBUG) console_formatter = logging.Formatter("%(asctime)s - %(levelname)s" ": %(message)s", datefmt="%I:%M:%S %p") consolehandler = logging.StreamHandler() consolehandler.setFormatter(console_formatter) logger.addHandler(consolehandler) return logger if __name__ == "__main__": logger = setup_logging() doc = Document() doc.organize() if not os.path.exists(os.curdir + '/raw'): logger.debug("Getting raw text files.") doc.call() if not os.path.exists(os.curdir + '/text'): logger.debug("Parsing JSON to TXT.") doc.json_to_text() # Open and read files tokenizer = Tokenizer() progress = util.ProgressChecker() parser = Parser(progress) if not os.path.exists(os.curdir + '/latex'): os.mkdir(os.curdir + '/latex') if not os.path.exists(os.curdir + '/latex'):<|fim▁hole|> os.mkdir(os.curdir + '/latex') #folders = sorted(os.listdir(path=(os.curdir + '/text')), key=int) folders = ['0', '1', '2', '3'] for folder in folders: files = sorted(os.listdir(path=(os.curdir + '/text/' + folder)), key=lambda x: int(x[0])) if folder == '3': files = ['0.txt', '1.txt'] with codecs.open(os.curdir + '/latex/' + folder + '.tex', 'w+', 'utf-8') as outputfile: last_open = os.curdir + '/latex/' + folder + '.tex' for file in files: logger.debug("Parsing " + folder + "/" + file + " to " + folder + ".tex.") with codecs.open(os.curdir + '/text/' + folder + '/' + file, 'r', 'utf-8') as f: data = f.read() token_list = tokenizer.analyze(data) parser.begin(outputfile) parser.dispatch(token_list) print("Total number of pages included in main pages: " + str(doc.num_pages)) progress.get_statistics() # with codecs.open(last_open, 'a', 'utf-8') as outputfile: # contributors = doc.attribute() # parser.end_matter(contributors, outputfile) logger.debug("Parsing complete.")<|fim▁end|>
<|file_name|>fileutils.js<|end_file_name|><|fim▁begin|>'use strict'; const fs = require('fs'); const execa = require('execa'); const Bluebird = require('bluebird'); const log = require('npmlog'); const fsStatAsync = Bluebird.promisify(fs.stat); <|fim▁hole|> return fsStatAsync(path).then(stat => stat.isFile()).catchReturn(false); }; exports.executableExists = function executableExists(exe, options) { let cmd = isWin ? 'where' : 'which'; let test = execa(cmd, [exe], options); test.on('error', error => log.error('Error spawning "' + cmd + exe + '"', error)); return test.then(result => result.code === 0, () => false); };<|fim▁end|>
const isWin = require('./utils/is-win')(); exports.fileExists = function fileExists(path) {
<|file_name|>admin.py<|end_file_name|><|fim▁begin|># # Newfies-Dialer License # http://www.newfies-dialer.org # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/. # # Copyright (C) 2011-2013 Star2Billing S.L. # # The Initial Developer of the Original Code is # Arezqui Belaid <[email protected]> # from django.contrib import admin from django.contrib import messages from django.conf.urls import patterns from django.utils.translation import ugettext as _ from django.db.models import Count from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from django.shortcuts import render_to_response from django.template.context import RequestContext from dialer_campaign.models import Campaign, Subscriber from dialer_campaign.function_def import check_dialer_setting, dialer_setting_limit from dialer_campaign.constants import SUBSCRIBER_STATUS, SUBSCRIBER_STATUS_NAME from dialer_campaign.forms import SubscriberReportForm from genericadmin.admin import GenericAdminModelAdmin from common.common_functions import variable_value, ceil_strdate from common.app_label_renamer import AppLabelRenamer from datetime import datetime APP_LABEL = _('Dialer Campaign') AppLabelRenamer(native_app_label=u'dialer_campaign', app_label=APP_LABEL).main() class CampaignAdmin(GenericAdminModelAdmin): """ Allows the administrator to view and modify certain attributes of a Campaign. """ content_type_whitelist = ('survey/survey_template', ) fieldsets = ( (_('standard options').capitalize(), { 'fields': ('campaign_code', 'name', 'description', 'callerid', 'user', 'status', 'startingdate', 'expirationdate', 'aleg_gateway', 'content_type', 'object_id', 'extra_data', 'phonebook', 'voicemail', 'amd_behavior', 'voicemail_audiofile' ), }), (_('advanced options').capitalize(), { 'classes': ('collapse',), 'fields': ('frequency', 'callmaxduration', 'maxretry', 'intervalretry', 'calltimeout', 'imported_phonebook', 'daily_start_time', 'daily_stop_time', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday', 'completion_maxretry', 'completion_intervalretry', 'dnc') }), ) list_display = ('id', 'name', 'content_type', 'campaign_code', 'user', 'startingdate', 'expirationdate', 'frequency', 'callmaxduration', 'maxretry', 'aleg_gateway', 'status', 'update_campaign_status', 'totalcontact', 'completed', 'subscriber_detail', 'progress_bar') list_display_links = ('id', 'name', ) #list_filter doesn't display correctly too many elements in list_display #list_filter = ['user', 'status', 'created_date']<|fim▁hole|> def get_urls(self): urls = super(CampaignAdmin, self).get_urls() my_urls = patterns('', (r'^$', self.admin_site.admin_view(self.changelist_view)), (r'^add/$', self.admin_site.admin_view(self.add_view)), ) return my_urls + urls def add_view(self, request, extra_context=None): """ Override django add_view method for checking the dialer setting limit **Logic Description**: * Before adding campaign, check dialer setting limit if applicable to the user, if matched then the user will be redirected to the campaign list """ # Check dialer setting limit # check Max Number of running campaigns if check_dialer_setting(request, check_for="campaign"): msg = _("you have too many campaigns. max allowed %(limit)s") \ % {'limit': dialer_setting_limit(request, limit_for="campaign")} messages.error(request, msg) return HttpResponseRedirect( reverse("admin:dialer_campaign_campaign_changelist")) ctx = {} return super(CampaignAdmin, self).add_view(request, extra_context=ctx) admin.site.register(Campaign, CampaignAdmin) class SubscriberAdmin(admin.ModelAdmin): """Allows the administrator to view and modify certain attributes of a Subscriber.""" list_display = ('id', 'contact', 'campaign', 'last_attempt', 'count_attempt', 'completion_count_attempt', 'duplicate_contact', 'contact_name', 'status', 'created_date') list_filter = ['campaign', 'status', 'created_date', 'last_attempt'] ordering = ('-id', ) raw_id_fields = ("contact",) def get_urls(self): urls = super(SubscriberAdmin, self).get_urls() my_urls = patterns('', (r'^subscriber_report/$', self.admin_site.admin_view(self.subscriber_report)), ) return my_urls + urls def subscriber_report(self, request): """ Get subscriber report **Attributes**: * ``form`` - SubscriberReportForm * ``template`` - admin/dialer_campaign/subscriber/subscriber_report.html """ opts = Subscriber._meta tday = datetime.today() form = SubscriberReportForm(initial={"from_date": tday.strftime("%Y-%m-%d"), "to_date": tday.strftime("%Y-%m-%d")}) total_subscriber = 0 total_pending = 0 total_pause = 0 total_abort = 0 total_fail = 0 total_sent = 0 total_in_process = 0 total_not_auth = 0 total_completed = 0 if request.method == 'POST': form = SubscriberReportForm(request.POST) if form.is_valid(): start_date = '' end_date = '' if request.POST.get('from_date'): from_date = request.POST.get('from_date') start_date = ceil_strdate(from_date, 'start') if request.POST.get('to_date'): to_date = request.POST.get('to_date') end_date = ceil_strdate(to_date, 'end') campaign_id = variable_value(request, 'campaign_id') kwargs = {} if start_date and end_date: kwargs['updated_date__range'] = (start_date, end_date) if start_date and end_date == '': kwargs['updated_date__gte'] = start_date if start_date == '' and end_date: kwargs['updated_date__lte'] = end_date if campaign_id and campaign_id != '0': kwargs['campaign_id'] = campaign_id select_data = {"updated_date": "SUBSTR(CAST(updated_date as CHAR(30)),1,10)"} subscriber = Subscriber.objects\ .filter(**kwargs)\ .extra(select=select_data)\ .values('updated_date', 'status')\ .annotate(Count('updated_date'))\ .order_by('updated_date') for i in subscriber: total_subscriber += i['updated_date__count'] if i['status'] == SUBSCRIBER_STATUS.PENDING: total_pending += i['updated_date__count'] elif i['status'] == SUBSCRIBER_STATUS.PAUSE: total_pause += i['updated_date__count'] elif i['status'] == SUBSCRIBER_STATUS.ABORT: total_abort += i['updated_date__count'] elif i['status'] == SUBSCRIBER_STATUS.FAIL: total_fail += i['updated_date__count'] elif i['status'] == SUBSCRIBER_STATUS.SENT: total_sent += i['updated_date__count'] elif i['status'] == SUBSCRIBER_STATUS.IN_PROCESS: total_in_process += i['updated_date__count'] elif i['status'] == SUBSCRIBER_STATUS.NOT_AUTHORIZED: total_not_auth += i['updated_date__count'] else: #status COMPLETED total_completed += i['updated_date__count'] ctx = RequestContext(request, { 'form': form, 'opts': opts, 'total_subscriber': total_subscriber, 'total_pending': total_pending, 'total_pause': total_pause, 'total_abort': total_abort, 'total_fail': total_fail, 'total_sent': total_sent, 'total_in_process': total_in_process, 'total_not_auth': total_not_auth, 'total_completed': total_completed, 'SUBSCRIBER_STATUS_NAME': SUBSCRIBER_STATUS_NAME, 'model_name': opts.object_name.lower(), 'app_label': APP_LABEL, 'title': _('subscriber report'), }) return render_to_response('admin/dialer_campaign/subscriber/subscriber_report.html', context_instance=ctx) admin.site.register(Subscriber, SubscriberAdmin)<|fim▁end|>
ordering = ('-id', ) filter_horizontal = ('phonebook',)
<|file_name|>manage.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "web_sheets_django.settings.local") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django<|fim▁hole|> "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv)<|fim▁end|>
except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and "
<|file_name|>apps.py<|end_file_name|><|fim▁begin|>from django.apps import AppConfig<|fim▁hole|> class ContentStoreAppConfig(AppConfig): name = "contentstore" def ready(self): import contentstore.signals contentstore.signals<|fim▁end|>
<|file_name|>gradient_hf_test.py<|end_file_name|><|fim▁begin|>import numpy as np from openfermioncirq.experiments.hfvqe.gradient_hf import (rhf_func_generator, rhf_minimization) from openfermioncirq.experiments.hfvqe.molecular_example import make_h6_1_3 def test_rhf_func_gen(): rhf_objective, molecule, parameters, _, _ = make_h6_1_3() ansatz, energy, _ = rhf_func_generator(rhf_objective) assert np.isclose(molecule.hf_energy, energy(parameters)) ansatz, energy, _, opdm_func = rhf_func_generator( rhf_objective, initial_occ_vec=[1] * 3 + [0] * 3, get_opdm_func=True) assert np.isclose(molecule.hf_energy, energy(parameters))<|fim▁hole|> test_opdm = opdm_func(parameters) u = ansatz(parameters) initial_opdm = np.diag([1] * 3 + [0] * 3) final_odpm = u @ initial_opdm @ u.T assert np.allclose(test_opdm, final_odpm) result = rhf_minimization(rhf_objective, initial_guess=parameters) assert np.allclose(result.x, parameters)<|fim▁end|>
<|file_name|>jsonloader.go<|end_file_name|><|fim▁begin|><|fim▁hole|>package config import "golang.org/x/xerrors" // JSONLoader loads configuration type JSONLoader struct { } // Load load the configuration JSON file specified by path arg. func (c JSONLoader) Load(_, _, _ string) (err error) { return xerrors.New("Not implement yet") }<|fim▁end|>
<|file_name|>dupe-symbols-7.rs<|end_file_name|><|fim▁begin|>// build-fail // // error-pattern: entry symbol `main` declared multiple times // FIXME https://github.com/rust-lang/rust/issues/59774<|fim▁hole|>// normalize-stderr-test "note:.*RUST_BACKTRACE=1.*\n" -> "" #![allow(warnings)] #[no_mangle] fn main(){}<|fim▁end|>
// normalize-stderr-test "thread.*panicked.*Metadata module not compiled.*\n" -> ""
<|file_name|>test_atmosphere.py<|end_file_name|><|fim▁begin|>import itertools import numpy as np import pandas as pd import pytest from numpy.testing import assert_allclose from pvlib import atmosphere from pvlib import solarposition latitude, longitude, tz, altitude = 32.2, -111, 'US/Arizona', 700 times = pd.date_range(start='20140626', end='20140626', freq='6h', tz=tz) ephem_data = solarposition.get_solarposition(times, latitude, longitude) # need to add physical tests instead of just functional tests def test_pres2alt(): atmosphere.pres2alt(100000) def test_alt2press(): atmosphere.pres2alt(1000) @pytest.mark.parametrize("model", ['simple', 'kasten1966', 'youngirvine1967', 'kastenyoung1989', 'gueymard1993', 'young1994', 'pickering2002']) def test_airmass(model): out = atmosphere.relativeairmass(ephem_data['zenith'], model) assert isinstance(out, pd.Series) out = atmosphere.relativeairmass(ephem_data['zenith'].values, model) assert isinstance(out, np.ndarray) def test_airmass_scalar(): assert not np.isnan(atmosphere.relativeairmass(10)) def test_airmass_scalar_nan(): assert np.isnan(atmosphere.relativeairmass(100)) def test_airmass_invalid(): with pytest.raises(ValueError): atmosphere.relativeairmass(ephem_data['zenith'], 'invalid') def test_absoluteairmass(): relative_am = atmosphere.relativeairmass(ephem_data['zenith'], 'simple') atmosphere.absoluteairmass(relative_am) atmosphere.absoluteairmass(relative_am, pressure=100000) def test_absoluteairmass_numeric(): atmosphere.absoluteairmass(2) def test_absoluteairmass_nan(): np.testing.assert_equal(np.nan, atmosphere.absoluteairmass(np.nan)) def test_gueymard94_pw(): temp_air = np.array([0, 20, 40]) relative_humidity = np.array([0, 30, 100]) temps_humids = np.array( list(itertools.product(temp_air, relative_humidity))) pws = atmosphere.gueymard94_pw(temps_humids[:, 0], temps_humids[:, 1]) expected = np.array( [ 0.1 , 0.33702061, 1.12340202, 0.1 , 1.12040963, 3.73469877, 0.1 , 3.44859767, 11.49532557]) assert_allclose(pws, expected, atol=0.01) @pytest.mark.parametrize("module_type,expect", [ ('cdte', np.array( [[ 0.9905102 , 0.9764032 , 0.93975028], [ 1.02928735, 1.01881074, 0.98578821], [ 1.04750335, 1.03814456, 1.00623986]])), ('monosi', np.array( [[ 0.9776977 , 1.02043409, 1.03574032], [ 0.98630905, 1.03055092, 1.04736262], [ 0.98828494, 1.03299036, 1.05026561]])), ('polysi', np.array( [[ 0.9770408 , 1.01705849, 1.02613202], [ 0.98992828, 1.03173953, 1.04260662], [ 0.99352435, 1.03588785, 1.04730718]])), ('cigs', np.array( [[ 0.9745919 , 1.02821696, 1.05067895], [ 0.97529378, 1.02967497, 1.05289307], [ 0.97269159, 1.02730558, 1.05075651]])), ('asi', np.array( [[ 1.0555275 , 0.87707583, 0.72243772], [ 1.11225204, 0.93665901, 0.78487953], [ 1.14555295, 0.97084011, 0.81994083]])) ]) def test_first_solar_spectral_correction(module_type, expect): ams = np.array([1, 3, 5]) pws = np.array([1, 3, 5]) ams, pws = np.meshgrid(ams, pws) out = atmosphere.first_solar_spectral_correction(pws, ams, module_type) assert_allclose(out, expect, atol=0.001) def test_first_solar_spectral_correction_supplied(): # use the cdte coeffs coeffs = (0.87102, -0.040543, -0.00929202, 0.10052, 0.073062, -0.0034187) out = atmosphere.first_solar_spectral_correction(1, 1, coefficients=coeffs) expected = 0.99134828 assert_allclose(out, expected, atol=1e-3) def test_first_solar_spectral_correction_ambiguous(): with pytest.raises(TypeError): atmosphere.first_solar_spectral_correction(1, 1) <|fim▁hole|> """Test Linke turbidity factor calculated from AOD, Pwat and AM""" amp = np.array([1, 3, 5]) pwat = np.array([0, 2.5, 5]) aod_bb = np.array([0, 0.1, 1]) lt_expected = np.array( [[[1.3802, 2.4102, 11.6802], [1.16303976, 2.37303976, 13.26303976], [1.12101907, 2.51101907, 15.02101907]], [[2.95546945, 3.98546945, 13.25546945], [2.17435443, 3.38435443, 14.27435443], [1.99821967, 3.38821967, 15.89821967]], [[3.37410769, 4.40410769, 13.67410769], [2.44311797, 3.65311797, 14.54311797], [2.23134152, 3.62134152, 16.13134152]]] ) lt = atmosphere.kasten96_lt(*np.meshgrid(amp, pwat, aod_bb)) assert np.allclose(lt, lt_expected, 1e-3) return lt def test_angstrom_aod(): """Test Angstrom turbidity model functions.""" aod550 = 0.15 aod1240 = 0.05 alpha = atmosphere.angstrom_alpha(aod550, 550, aod1240, 1240) assert np.isclose(alpha, 1.3513924317859232) aod700 = atmosphere.angstrom_aod_at_lambda(aod550, 550, alpha) assert np.isclose(aod700, 0.10828110997681031) def test_bird_hulstrom80_aod_bb(): """Test Bird_Hulstrom broadband AOD.""" aod380, aod500 = 0.22072480948195175, 0.1614279181106312 bird_hulstrom = atmosphere.bird_hulstrom80_aod_bb(aod380, aod500) assert np.isclose(0.11738229553812768, bird_hulstrom)<|fim▁end|>
def test_kasten96_lt():
<|file_name|>shot.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Created on Wed Nov 25 12:14:03 2015 @author: ktritz """ from __future__ import print_function from builtins import str, range import inspect import types #import numpy as np from collections.abc import MutableMapping from .container import containerClassFactory class Shot(MutableMapping): # _modules = None _logbook = None _machine = None def __init__(self, shot, machine): self.shot = shot # set class attributes if needed cls = self.__class__ if cls._machine is None: cls._machine = machine # if cls._modules is None: # cls._modules = {module: None for module in self._machine._modules} if cls._logbook is None: cls._logbook = self._machine._logbook self._logbook_entries = self._logbook.get_entries(shot=self.shot) self._efits = [] self._modules = {module: None for module in self._machine._modules} self.xp = self._get_xp() self.date = self._get_date() def _get_xp(self): # query logbook for XP, return XP (list if needed) xplist = [] for entry in self._logbook_entries: if entry['xp']: xplist.append(entry['xp']) return list(set(xplist)) def _get_date(self): # query logbook for rundate, return rundate if self._logbook_entries: return self._logbook_entries[0]['rundate'] else: return def __getattr__(self, attr_name): if attr_name in self._modules: if self._modules[attr_name] is None: self._modules[attr_name] = containerClassFactory(attr_name, root=self._machine, shot=self.shot, parent=self) return self._modules[attr_name] else: try: attr = getattr(self._machine, attr_name) except AttributeError as e: # print('{} is not attribute of {}'.format(attr_name, self._machine._name)) raise e if inspect.ismethod(attr): return types.MethodType(attr.__func__, self) else: return attr def __repr__(self): return '<Shot {}>'.format(self.shot) def __str__(self): return 'Shot {}'.format(self.shot) def __iter__(self): # return iter(self._modules.values()) return iter(self._modules) def __contains__(self, key): return key in self._modules def __len__(self): return len(list(self._modules.keys())) def __delitem__(self, item): pass def __getitem__(self, item): return self._modules[item] def __setitem__(self, item, value): pass def __dir__(self): return list(self._modules.keys()) def logbook(self): # show logbook entries if not self._logbook_entries: self._logbook_entries = self._logbook.get_entries(shot=self.shot) if self._logbook_entries: print('Logbook entries for {}'.format(self.shot)) for entry in self._logbook_entries: print('************************************') print(('{shot} on {rundate} in XP {xp}\n' '{username} in topic {topic}\n\n' '{text}').format(**entry)) print('************************************') else: print('No logbook entries for {}'.format(self.shot)) def get_logbook(self): # return a list of logbook entries<|fim▁hole|> def check_efit(self): if len(self._efits): return self._efits trees = ['efit{}'.format(str(index).zfill(2)) for index in range(1, 7)] trees.extend(['lrdfit{}'.format(str(index).zfill(2)) for index in range(1, 13)]) if self.shot == 0: return trees tree_exists = [] for tree in trees: data = None connection = self._get_connection(self.shot, tree) try: data = connection.get('\\{}::userid'.format(tree)).value except: pass if data and data != '*': tree_exists.append(tree) self._efits = tree_exists return self._efits<|fim▁end|>
if not self._logbook_entries: self._logbook_entries = self._logbook.get_entries(shot=self.shot) return self._logbook_entries
<|file_name|>tag-variant-disr-dup.rs<|end_file_name|><|fim▁begin|>// Copyright 2012 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<|fim▁hole|>// except according to those terms. //error-pattern:discriminator value already exists // black and white have the same discriminator value ... enum color { red = 0xff0000, green = 0x00ff00, blue = 0x0000ff, black = 0x000000, white = 0x000000, }<|fim▁end|>
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed
<|file_name|>bench_engine_main.rs<|end_file_name|><|fim▁begin|>#[macro_use] extern crate criterion; extern crate pleco; extern crate pleco_engine; mod eval_benches; mod multimove_benches; mod startpos_benches; trait DepthLimit { fn depth() -> u16; } struct Depth5 {} struct Depth6 {} struct Depth7 {} struct Depth8 {} struct Depth9 {} impl DepthLimit for Depth5 { fn depth() -> u16 {5} } impl DepthLimit for Depth6 { fn depth() -> u16 {6} } impl DepthLimit for Depth7 { fn depth() -> u16 {7} } impl DepthLimit for Depth8 { fn depth() -> u16 {8} } impl DepthLimit for Depth9 { fn depth() -> u16 {9} }<|fim▁hole|> eval_benches::eval_benches, multimove_benches::search_multimove, startpos_benches::search_singular }<|fim▁end|>
criterion_main!{
<|file_name|>index.ts<|end_file_name|><|fim▁begin|>import Message from './Message'; <|fim▁hole|><|fim▁end|>
export default Message; export * from './Message';
<|file_name|>edit.controller.js<|end_file_name|><|fim▁begin|>(function () { 'use strict'; function ContentEditController($rootScope, $scope, $routeParams, $q, $timeout, $window, $location, appState, contentResource, entityResource, navigationService, notificationsService, angularHelper, serverValidationManager, contentEditingHelper, treeService, fileManager, formHelper, umbRequestHelper, keyboardService, umbModelMapper, editorState, $http, eventsService, relationResource) { var evts = []; //setup scope vars $scope.defaultButton = null; $scope.subButtons = []; $scope.page = {}; $scope.page.loading = false; $scope.page.menu = {}; $scope.page.menu.currentNode = null; $scope.page.menu.currentSection = appState.getSectionState("currentSection"); $scope.page.listViewPath = null; $scope.page.isNew = $scope.isNew ? true : false; $scope.page.buttonGroupState = "init"; $scope.allowOpen = true; function init(content) { createButtons(content); editorState.set($scope.content); //We fetch all ancestors of the node to generate the footer breadcrumb navigation if (!$scope.page.isNew) { if (content.parentId && content.parentId !== -1) { entityResource.getAncestors(content.id, "document") .then(function (anc) { $scope.ancestors = anc; }); } } evts.push(eventsService.on("editors.content.changePublishDate", function (event, args) { createButtons(args.node); })); evts.push(eventsService.on("editors.content.changeUnpublishDate", function (event, args) { createButtons(args.node); })); // We don't get the info tab from the server from version 7.8 so we need to manually add it contentEditingHelper.addInfoTab($scope.content.tabs); } function getNode() { $scope.page.loading = true; //we are editing so get the content item from the server $scope.getMethod()($scope.contentId) .then(function (data) { $scope.content = data; if (data.isChildOfListView && data.trashed === false) { $scope.page.listViewPath = ($routeParams.page) ? "/content/content/edit/" + data.parentId + "?page=" + $routeParams.page : "/content/content/edit/" + data.parentId; } init($scope.content); //in one particular special case, after we've created a new item we redirect back to the edit // route but there might be server validation errors in the collection which we need to display // after the redirect, so we will bind all subscriptions which will show the server validation errors // if there are any and then clear them so the collection no longer persists them. serverValidationManager.executeAndClearAllSubscriptions(); syncTreeNode($scope.content, data.path, true); resetLastListPageNumber($scope.content); eventsService.emit("content.loaded", { content: $scope.content }); $scope.page.loading = false; }); } function createButtons(content) { $scope.page.buttonGroupState = "init"; var buttons = contentEditingHelper.configureContentEditorButtons({ create: $scope.page.isNew, content: content, methods: { saveAndPublish: $scope.saveAndPublish, sendToPublish: $scope.sendToPublish, save: $scope.save, unPublish: $scope.unPublish } }); $scope.defaultButton = buttons.defaultButton; $scope.subButtons = buttons.subButtons; } /** Syncs the content item to it's tree node - this occurs on first load and after saving */ function syncTreeNode(content, path, initialLoad) { if (!$scope.content.isChildOfListView) { navigationService.syncTree({ tree: $scope.treeAlias, path: path.split(","), forceReload: initialLoad !== true }).then(function (syncArgs) { $scope.page.menu.currentNode = syncArgs.node; }); } else if (initialLoad === true) { //it's a child item, just sync the ui node to the parent navigationService.syncTree({ tree: $scope.treeAlias, path: path.substring(0, path.lastIndexOf(",")).split(","), forceReload: initialLoad !== true }); //if this is a child of a list view and it's the initial load of the editor, we need to get the tree node // from the server so that we can load in the actions menu. umbRequestHelper.resourcePromise( $http.get(content.treeNodeUrl), 'Failed to retrieve data for child node ' + content.id).then(function (node) { $scope.page.menu.currentNode = node; }); } } // This is a helper method to reduce the amount of code repitition for actions: Save, Publish, SendToPublish function performSave(args) { var deferred = $q.defer(); $scope.page.buttonGroupState = "busy"; eventsService.emit("content.saving", { content: $scope.content, action: args.action }); contentEditingHelper.contentEditorPerformSave({ statusMessage: args.statusMessage, saveMethod: args.saveMethod, scope: $scope, content: $scope.content, action: args.action }).then(function (data) { //success init($scope.content); syncTreeNode($scope.content, data.path); $scope.page.buttonGroupState = "success"; deferred.resolve(data); eventsService.emit("content.saved", { content: $scope.content, action: args.action }); }, function (err) { //error if (err) { editorState.set($scope.content); } $scope.page.buttonGroupState = "error"; deferred.reject(err); }); return deferred.promise; } function resetLastListPageNumber(content) { // We're using rootScope to store the page number for list views, so if returning to the list // we can restore the page. If we've moved on to edit a piece of content that's not the list or it's children // we should remove this so as not to confuse if navigating to a different list if (!content.isChildOfListView && !content.isContainer) { $rootScope.lastListViewPageViewed = null; } } if ($scope.page.isNew) { $scope.page.loading = true; //we are creating so get an empty content item $scope.getScaffoldMethod()() .then(function (data) { $scope.content = data; init($scope.content); resetLastListPageNumber($scope.content); $scope.page.loading = false; eventsService.emit("content.newReady", { content: $scope.content }); }); } else { getNode(); } $scope.unPublish = function () { // raising the event triggers the confirmation dialog if (!notificationsService.hasView()) { notificationsService.add({ view: "confirmunpublish" }); } $scope.page.buttonGroupState = "busy"; // actioning the dialog raises the confirmUnpublish event, act on it here var actioned = $rootScope.$on("content.confirmUnpublish", function(event, confirmed) { if (confirmed && formHelper.submitForm({ scope: $scope, statusMessage: "Unpublishing...", skipValidation: true })) { eventsService.emit("content.unpublishing", { content: $scope.content }); contentResource.unPublish($scope.content.id) .then(function (data) { formHelper.resetForm({ scope: $scope, notifications: data.notifications }); contentEditingHelper.handleSuccessfulSave({ scope: $scope, savedContent: data, rebindCallback: contentEditingHelper.reBindChangedProperties($scope.content, data) }); init($scope.content); syncTreeNode($scope.content, data.path); $scope.page.buttonGroupState = "success"; eventsService.emit("content.unpublished", { content: $scope.content }); }, function(err) { formHelper.showNotifications(err.data); $scope.page.buttonGroupState = 'error'; }); } else { $scope.page.buttonGroupState = "init"; } // unsubscribe to avoid queueing notifications // listener is re-bound when the unpublish button is clicked so it is created just-in-time actioned(); }); }; $scope.sendToPublish = function () { return performSave({ saveMethod: contentResource.sendToPublish, statusMessage: "Sending...", action: "sendToPublish" }); }; $scope.saveAndPublish = function () { return performSave({ saveMethod: contentResource.publish, statusMessage: "Publishing...", action: "publish" }); }; $scope.save = function () { return performSave({ saveMethod: $scope.saveMethod(), statusMessage: "Saving...", action: "save" }); }; $scope.preview = function (content) { if (!$scope.busy) { // Chromes popup blocker will kick in if a window is opened // without the initial scoped request. This trick will fix that. // var previewWindow = $window.open('preview/?init=true&id=' + content.id, 'umbpreview'); // Build the correct path so both /#/ and #/ work. var redirect = Umbraco.Sys.ServerVariables.umbracoSettings.umbracoPath + '/preview/?id=' + content.id; //The user cannot save if they don't have access to do that, in which case we just want to preview //and that's it otherwise they'll get an unauthorized access message if (!_.contains(content.allowedActions, "A")) { previewWindow.location.href = redirect; } else { $scope.save().then(function (data) { previewWindow.location.href = redirect; }); } } }; $scope.restore = function (content) { $scope.page.buttonRestore = "busy"; relationResource.getByChildId(content.id, "relateParentDocumentOnDelete").then(function (data) { var relation = null; var target = null; var error = { headline: "Cannot automatically restore this item", content: "Use the Move menu item to move it manually"}; if (data.length == 0) { notificationsService.error(error.headline, "There is no 'restore' relation found for this node. Use the Move menu item to move it manually."); $scope.page.buttonRestore = "error"; return; } relation = data[0]; if (relation.parentId == -1) { target = { id: -1, name: "Root" }; moveNode(content, target); } else { contentResource.getById(relation.parentId).then(function (data) { target = data; // make sure the target item isn't in the recycle bin if(target.path.indexOf("-20") !== -1) { notificationsService.error(error.headline, "The item you want to restore it under (" + target.name + ") is in the recycle bin. Use the Move menu item to move the item manually."); $scope.page.buttonRestore = "error"; return; } moveNode(content, target); }, function (err) { $scope.page.buttonRestore = "error"; notificationsService.error(error.headline, error.content); }); } }, function (err) { $scope.page.buttonRestore = "error"; notificationsService.error(error.headline, error.content); }); }; function moveNode(node, target) { contentResource.move({ "parentId": target.id, "id": node.id }) .then(function (path) { // remove the node that we're working on if($scope.page.menu.currentNode) { treeService.removeNode($scope.page.menu.currentNode); } // sync the destination node navigationService.syncTree({ tree: "content", path: path, forceReload: true, activate: false }); $scope.page.buttonRestore = "success"; notificationsService.success("Successfully restored " + node.name + " to " + target.name); // reload the node getNode(); }, function (err) { $scope.page.buttonRestore = "error"; notificationsService.error("Cannot automatically restore this item", err); }); } //ensure to unregister from all events! $scope.$on('$destroy', function () { for (var e in evts) { eventsService.unsubscribe(evts[e]); } }); } <|fim▁hole|> function createDirective() { var directive = { restrict: 'E', replace: true, templateUrl: 'views/components/content/edit.html', controller: 'Umbraco.Editors.Content.EditorDirectiveController', scope: { contentId: "=", isNew: "=?", treeAlias: "@", page: "=?", saveMethod: "&", getMethod: "&", getScaffoldMethod: "&?" } }; return directive; } angular.module('umbraco.directives').controller('Umbraco.Editors.Content.EditorDirectiveController', ContentEditController); angular.module('umbraco.directives').directive('contentEditor', createDirective); })();<|fim▁end|>
<|file_name|>wsgi.py<|end_file_name|><|fim▁begin|>from app import setup <|fim▁hole|>app = setup()<|fim▁end|>
<|file_name|>0159_auto__add_field_authidentity_last_verified__add_field_organizationmemb.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'AuthIdentity.last_verified' db.add_column( 'sentry_authidentity', 'last_verified', self.gf('django.db.models.fields.DateTimeField')(default=datetime.datetime.now), keep_default=False ) # Adding field 'OrganizationMember.flags' db.add_column( 'sentry_organizationmember', 'flags', self.gf('django.db.models.fields.BigIntegerField')(default=0), keep_default=False ) def backwards(self, orm): # Deleting field 'AuthIdentity.last_verified' db.delete_column('sentry_authidentity', 'last_verified') # Deleting field 'OrganizationMember.flags' db.delete_column('sentry_organizationmember', 'flags') models = { 'sentry.accessgroup': { 'Meta': { 'unique_together': "(('team', 'name'),)", 'object_name': 'AccessGroup' }, 'data': ( 'sentry.db.models.fields.gzippeddict.GzippedDictField', [], { 'null': 'True', 'blank': 'True' } ), 'date_added': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'managed': ('django.db.models.fields.BooleanField', [], { 'default': 'False' }), 'members': ( 'django.db.models.fields.related.ManyToManyField', [], { 'to': "orm['sentry.User']", 'symmetrical': 'False' } ), 'name': ('django.db.models.fields.CharField', [], { 'max_length': '64' }), 'projects': ( 'django.db.models.fields.related.ManyToManyField', [], { 'to': "orm['sentry.Project']", 'symmetrical': 'False' } ), 'team': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Team']" } ), 'type': ('sentry.db.models.fields.bounded.BoundedIntegerField', [], { 'default': '50' }) }, 'sentry.activity': { 'Meta': { 'object_name': 'Activity' }, 'data': ('sentry.db.models.fields.gzippeddict.GzippedDictField', [], { 'null': 'True' }), 'datetime': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'event': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Event']", 'null': 'True' } ), 'group': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Group']", 'null': 'True' } ), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'ident': ('django.db.models.fields.CharField', [], { 'max_length': '64', 'null': 'True' }), 'project': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Project']" } ), 'type': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {}), 'user': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.User']", 'null': 'True' } ) }, 'sentry.alert': { 'Meta': { 'object_name': 'Alert' }, 'data': ('sentry.db.models.fields.gzippeddict.GzippedDictField', [], { 'null': 'True' }), 'datetime': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'group': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Group']", 'null': 'True' } ), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'message': ('django.db.models.fields.TextField', [], {}), 'project': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Project']" } ), 'related_groups': ( 'django.db.models.fields.related.ManyToManyField', [], { 'related_name': "'related_alerts'", 'symmetrical': 'False', 'through': "orm['sentry.AlertRelatedGroup']", 'to': "orm['sentry.Group']" } ), 'status': ( 'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'default': '0', 'db_index': 'True' } ) }, 'sentry.alertrelatedgroup': { 'Meta': { 'unique_together': "(('group', 'alert'),)", 'object_name': 'AlertRelatedGroup' }, 'alert': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Alert']" } ), 'data': ('sentry.db.models.fields.gzippeddict.GzippedDictField', [], { 'null': 'True' }), 'group': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Group']" } ), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }) }, 'sentry.apikey': { 'Meta': { 'object_name': 'ApiKey' }, 'date_added': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'key': ('django.db.models.fields.CharField', [], { 'unique': 'True', 'max_length': '32' }), 'label': ( 'django.db.models.fields.CharField', [], { 'default': "'Default'", 'max_length': '64', 'blank': 'True' } ), 'organization': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'related_name': "'key_set'", 'to': "orm['sentry.Organization']" } ), 'scopes': ('django.db.models.fields.BigIntegerField', [], { 'default': 'None' }), 'status': ( 'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'default': '0', 'db_index': 'True' } ) }, 'sentry.auditlogentry': { 'Meta': { 'object_name': 'AuditLogEntry' }, 'actor': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'related_name': "'audit_actors'", 'to': "orm['sentry.User']" } ), 'data': ('sentry.db.models.fields.gzippeddict.GzippedDictField', [], {}), 'datetime': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'event': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'ip_address': ( 'django.db.models.fields.GenericIPAddressField', [], { 'max_length': '39', 'null': 'True' } ), 'organization': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Organization']" } ), 'target_object': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'null': 'True' }), 'target_user': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'blank': 'True', 'related_name': "'audit_targets'", 'null': 'True', 'to': "orm['sentry.User']" } ) }, 'sentry.authidentity': { 'Meta': { 'unique_together': "(('auth_provider', 'ident'), ('auth_provider', 'user'))", 'object_name': 'AuthIdentity' }, 'auth_provider': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.AuthProvider']" } ), 'data': ('sentry.db.models.fields.gzippeddict.GzippedDictField', [], {}), 'date_added': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'ident': ('django.db.models.fields.CharField', [], { 'max_length': '128' }), 'last_verified': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'user': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.User']" } ) }, 'sentry.authprovider': { 'Meta': { 'object_name': 'AuthProvider' }, 'config': ('sentry.db.models.fields.gzippeddict.GzippedDictField', [], {}), 'date_added': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'default_role': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'default': '50' }), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'last_sync': ('django.db.models.fields.DateTimeField', [], { 'null': 'True' }), 'organization': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Organization']", 'unique': 'True' } ), 'provider': ('django.db.models.fields.CharField', [], { 'max_length': '128' }), 'sync_time': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'null': 'True' }) }, 'sentry.broadcast': { 'Meta': { 'object_name': 'Broadcast' }, 'badge': ( 'django.db.models.fields.CharField', [], { 'max_length': '32', 'null': 'True', 'blank': 'True' } ), 'date_added': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'is_active': ('django.db.models.fields.BooleanField', [], { 'default': 'True', 'db_index': 'True' }), 'link': ( 'django.db.models.fields.URLField', [], { 'max_length': '200', 'null': 'True', 'blank': 'True' } ), 'message': ('django.db.models.fields.CharField', [], { 'max_length': '256' }) }, 'sentry.event': { 'Meta': { 'unique_together': "(('project', 'event_id'),)", 'object_name': 'Event', 'db_table': "'sentry_message'", 'index_together': "(('group', 'datetime'),)" }, 'checksum': ('django.db.models.fields.CharField', [], { 'max_length': '32', 'db_index': 'True' }), 'data': ('sentry.db.models.fields.node.NodeField', [], { 'null': 'True', 'blank': 'True' }), 'datetime': ( 'django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now', 'db_index': 'True' } ), 'event_id': ( 'django.db.models.fields.CharField', [], { 'max_length': '32', 'null': 'True', 'db_column': "'message_id'" } ), 'group': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'blank': 'True', 'related_name': "'event_set'", 'null': 'True', 'to': "orm['sentry.Group']" } ), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'message': ('django.db.models.fields.TextField', [], {}), 'num_comments': ( 'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'default': '0', 'null': 'True' } ), 'platform': ('django.db.models.fields.CharField', [], { 'max_length': '64', 'null': 'True' }), 'project': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Project']", 'null': 'True' } ), 'time_spent': ('sentry.db.models.fields.bounded.BoundedIntegerField', [], { 'null': 'True' }) }, 'sentry.eventmapping': { 'Meta': { 'unique_together': "(('project', 'event_id'),)", 'object_name': 'EventMapping' }, 'date_added': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'event_id': ('django.db.models.fields.CharField', [], { 'max_length': '32' }), 'group': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Group']" } ), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'project': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Project']" } ) }, 'sentry.file': { 'Meta': { 'unique_together': "(('name', 'checksum'),)", 'object_name': 'File' }, 'checksum': ('django.db.models.fields.CharField', [], { 'max_length': '32', 'null': 'True' }), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'name': ('django.db.models.fields.CharField', [], { 'max_length': '128' }), 'path': ('django.db.models.fields.TextField', [], { 'null': 'True' }), 'size': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'null': 'True' }), 'storage': ('django.db.models.fields.CharField', [], { 'max_length': '128', 'null': 'True' }), 'storage_options': ('sentry.db.models.fields.gzippeddict.GzippedDictField', [], {}), 'timestamp': ( 'django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now', 'db_index': 'True' } ), 'type': ('django.db.models.fields.CharField', [], { 'max_length': '64' }) }, 'sentry.group': { 'Meta': { 'unique_together': "(('project', 'checksum'),)", 'object_name': 'Group', 'db_table': "'sentry_groupedmessage'" }, 'active_at': ('django.db.models.fields.DateTimeField', [], { 'null': 'True', 'db_index': 'True' }), 'checksum': ('django.db.models.fields.CharField', [], { 'max_length': '32', 'db_index': 'True' }), 'culprit': ( 'django.db.models.fields.CharField', [], { 'max_length': '200', 'null': 'True', 'db_column': "'view'", 'blank': 'True' } ), 'data': ( 'sentry.db.models.fields.gzippeddict.GzippedDictField', [], { 'null': 'True', 'blank': 'True' } ), 'first_seen': ( 'django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now', 'db_index': 'True' } ), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'is_public': ( 'django.db.models.fields.NullBooleanField', [], { 'default': 'False', 'null': 'True', 'blank': 'True' } ), 'last_seen': ( 'django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now', 'db_index': 'True' } ), 'level': ( 'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'default': '40', 'db_index': 'True', 'blank': 'True' } ), 'logger': ( 'django.db.models.fields.CharField', [], { 'default': "'root'", 'max_length': '64', 'db_index': 'True', 'blank': 'True' } ), 'message': ('django.db.models.fields.TextField', [], {}), 'num_comments': ( 'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'default': '0', 'null': 'True' } ), 'platform': ('django.db.models.fields.CharField', [], { 'max_length': '64', 'null': 'True' }), 'project': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Project']", 'null': 'True' } ), 'resolved_at': ('django.db.models.fields.DateTimeField', [], { 'null': 'True', 'db_index': 'True' }), 'score': ('sentry.db.models.fields.bounded.BoundedIntegerField', [], { 'default': '0' }), 'status': ( 'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'default': '0', 'db_index': 'True' } ), 'time_spent_count': ('sentry.db.models.fields.bounded.BoundedIntegerField', [], { 'default': '0' }), 'time_spent_total': ('sentry.db.models.fields.bounded.BoundedIntegerField', [], { 'default': '0' }), 'times_seen': ( 'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'default': '1', 'db_index': 'True' } ) }, 'sentry.groupassignee': { 'Meta': { 'object_name': 'GroupAssignee', 'db_table': "'sentry_groupasignee'" }, 'date_added': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'group': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'related_name': "'assignee_set'", 'unique': 'True', 'to': "orm['sentry.Group']" } ), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'project': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'related_name': "'assignee_set'", 'to': "orm['sentry.Project']" } ), 'user': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'related_name': "'sentry_assignee_set'", 'to': "orm['sentry.User']" } ) }, 'sentry.groupbookmark': { 'Meta': { 'unique_together': "(('project', 'user', 'group'),)", 'object_name': 'GroupBookmark' }, 'group': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'related_name': "'bookmark_set'", 'to': "orm['sentry.Group']" } ), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'project': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'related_name': "'bookmark_set'", 'to': "orm['sentry.Project']" } ), 'user': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'related_name': "'sentry_bookmark_set'", 'to': "orm['sentry.User']" } ) }, 'sentry.grouphash': { 'Meta': { 'unique_together': "(('project', 'hash'),)", 'object_name': 'GroupHash' }, 'group': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Group']", 'null': 'True' } ), 'hash': ('django.db.models.fields.CharField', [], { 'max_length': '32', 'db_index': 'True' }), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'project': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Project']", 'null': 'True' } ) }, 'sentry.groupmeta': { 'Meta': { 'unique_together': "(('group', 'key'),)", 'object_name': 'GroupMeta' }, 'group': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Group']" } ), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'key': ('django.db.models.fields.CharField', [], { 'max_length': '64' }), 'value': ('django.db.models.fields.TextField', [], {}) }, 'sentry.grouprulestatus': { 'Meta': { 'unique_together': "(('rule', 'group'),)", 'object_name': 'GroupRuleStatus' }, 'date_added': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'group': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Group']" } ), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'last_active': ('django.db.models.fields.DateTimeField', [], { 'null': 'True' }), 'project': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Project']" } ), 'rule': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Rule']" } ), 'status': ('django.db.models.fields.PositiveSmallIntegerField', [], { 'default': '0' }) }, 'sentry.groupseen': { 'Meta': { 'unique_together': "(('user', 'group'),)", 'object_name': 'GroupSeen' }, 'group': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Group']" } ), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'last_seen': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'project': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Project']" } ), 'user': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.User']", 'db_index': 'False' } ) }, 'sentry.grouptagkey': { 'Meta': { 'unique_together': "(('project', 'group', 'key'),)", 'object_name': 'GroupTagKey' }, 'group': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Group']" } ), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'key': ('django.db.models.fields.CharField', [], { 'max_length': '32' }), 'project': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Project']", 'null': 'True' } ), 'values_seen': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'default': '0' }) }, 'sentry.grouptagvalue': { 'Meta': { 'unique_together': "(('project', 'key', 'value', 'group'),)", 'object_name': 'GroupTagValue', 'db_table': "'sentry_messagefiltervalue'" }, 'first_seen': ( 'django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now', 'null': 'True', 'db_index': 'True' } ), 'group': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'related_name': "'grouptag'", 'to': "orm['sentry.Group']" } ), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'key': ('django.db.models.fields.CharField', [], { 'max_length': '32' }), 'last_seen': ( 'django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now', 'null': 'True', 'db_index': 'True' } ), 'project': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'related_name': "'grouptag'", 'null': 'True', 'to': "orm['sentry.Project']" } ), 'times_seen': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'default': '0' }), 'value': ('django.db.models.fields.CharField', [], { 'max_length': '200' }) }, 'sentry.helppage': { 'Meta': { 'object_name': 'HelpPage' }, 'content': ('django.db.models.fields.TextField', [], {}), 'date_added': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'is_visible': ('django.db.models.fields.BooleanField', [], { 'default': 'True' }), 'key': ( 'django.db.models.fields.CharField', [], { 'max_length': '64', 'unique': 'True', 'null': 'True' } ), 'priority': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'default': '50' }), 'title': ('django.db.models.fields.CharField', [], { 'max_length': '64' }) }, 'sentry.lostpasswordhash': { 'Meta': { 'object_name': 'LostPasswordHash'<|fim▁hole|> }), 'hash': ('django.db.models.fields.CharField', [], { 'max_length': '32' }), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'user': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.User']", 'unique': 'True' } ) }, 'sentry.option': { 'Meta': { 'object_name': 'Option' }, 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'key': ('django.db.models.fields.CharField', [], { 'unique': 'True', 'max_length': '64' }), 'last_updated': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'value': ('sentry.db.models.fields.pickle.UnicodePickledObjectField', [], {}) }, 'sentry.organization': { 'Meta': { 'object_name': 'Organization' }, 'date_added': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'members': ( 'django.db.models.fields.related.ManyToManyField', [], { 'related_name': "'org_memberships'", 'symmetrical': 'False', 'through': "orm['sentry.OrganizationMember']", 'to': "orm['sentry.User']" } ), 'name': ('django.db.models.fields.CharField', [], { 'max_length': '64' }), 'owner': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.User']" } ), 'slug': ('django.db.models.fields.SlugField', [], { 'unique': 'True', 'max_length': '50' }), 'status': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'default': '0' }) }, 'sentry.organizationmember': { 'Meta': { 'unique_together': "(('organization', 'user'), ('organization', 'email'))", 'object_name': 'OrganizationMember' }, 'date_added': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'email': ( 'django.db.models.fields.EmailField', [], { 'max_length': '75', 'null': 'True', 'blank': 'True' } ), 'flags': ('django.db.models.fields.BigIntegerField', [], { 'default': '0' }), 'has_global_access': ('django.db.models.fields.BooleanField', [], { 'default': 'True' }), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'organization': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'related_name': "'member_set'", 'to': "orm['sentry.Organization']" } ), 'teams': ( 'django.db.models.fields.related.ManyToManyField', [], { 'to': "orm['sentry.Team']", 'symmetrical': 'False', 'blank': 'True' } ), 'type': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'default': '50' }), 'user': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'blank': 'True', 'related_name': "'sentry_orgmember_set'", 'null': 'True', 'to': "orm['sentry.User']" } ) }, 'sentry.pendingteammember': { 'Meta': { 'unique_together': "(('team', 'email'),)", 'object_name': 'PendingTeamMember' }, 'date_added': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'email': ('django.db.models.fields.EmailField', [], { 'max_length': '75' }), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'team': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'related_name': "'pending_member_set'", 'to': "orm['sentry.Team']" } ), 'type': ('sentry.db.models.fields.bounded.BoundedIntegerField', [], { 'default': '50' }) }, 'sentry.project': { 'Meta': { 'unique_together': "(('team', 'slug'), ('organization', 'slug'))", 'object_name': 'Project' }, 'date_added': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'name': ('django.db.models.fields.CharField', [], { 'max_length': '200' }), 'organization': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Organization']" } ), 'platform': ('django.db.models.fields.CharField', [], { 'max_length': '32', 'null': 'True' }), 'public': ('django.db.models.fields.BooleanField', [], { 'default': 'False' }), 'slug': ('django.db.models.fields.SlugField', [], { 'max_length': '50', 'null': 'True' }), 'status': ( 'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'default': '0', 'db_index': 'True' } ), 'team': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Team']" } ) }, 'sentry.projectkey': { 'Meta': { 'object_name': 'ProjectKey' }, 'date_added': ( 'django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now', 'null': 'True' } ), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'label': ( 'django.db.models.fields.CharField', [], { 'max_length': '64', 'null': 'True', 'blank': 'True' } ), 'project': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'related_name': "'key_set'", 'to': "orm['sentry.Project']" } ), 'public_key': ( 'django.db.models.fields.CharField', [], { 'max_length': '32', 'unique': 'True', 'null': 'True' } ), 'roles': ('django.db.models.fields.BigIntegerField', [], { 'default': '1' }), 'secret_key': ( 'django.db.models.fields.CharField', [], { 'max_length': '32', 'unique': 'True', 'null': 'True' } ), 'status': ( 'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'default': '0', 'db_index': 'True' } ), 'user': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.User']", 'null': 'True' } ), 'user_added': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'related_name': "'keys_added_set'", 'null': 'True', 'to': "orm['sentry.User']" } ) }, 'sentry.projectoption': { 'Meta': { 'unique_together': "(('project', 'key'),)", 'object_name': 'ProjectOption', 'db_table': "'sentry_projectoptions'" }, 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'key': ('django.db.models.fields.CharField', [], { 'max_length': '64' }), 'project': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Project']" } ), 'value': ('sentry.db.models.fields.pickle.UnicodePickledObjectField', [], {}) }, 'sentry.release': { 'Meta': { 'unique_together': "(('project', 'version'),)", 'object_name': 'Release' }, 'date_added': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'project': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Project']" } ), 'version': ('django.db.models.fields.CharField', [], { 'max_length': '64' }) }, 'sentry.rule': { 'Meta': { 'object_name': 'Rule' }, 'data': ('sentry.db.models.fields.gzippeddict.GzippedDictField', [], {}), 'date_added': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'label': ('django.db.models.fields.CharField', [], { 'max_length': '64' }), 'project': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Project']" } ) }, 'sentry.tagkey': { 'Meta': { 'unique_together': "(('project', 'key'),)", 'object_name': 'TagKey', 'db_table': "'sentry_filterkey'" }, 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'key': ('django.db.models.fields.CharField', [], { 'max_length': '32' }), 'label': ('django.db.models.fields.CharField', [], { 'max_length': '64', 'null': 'True' }), 'project': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Project']" } ), 'status': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'default': '0' }), 'values_seen': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'default': '0' }) }, 'sentry.tagvalue': { 'Meta': { 'unique_together': "(('project', 'key', 'value'),)", 'object_name': 'TagValue', 'db_table': "'sentry_filtervalue'" }, 'data': ( 'sentry.db.models.fields.gzippeddict.GzippedDictField', [], { 'null': 'True', 'blank': 'True' } ), 'first_seen': ( 'django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now', 'null': 'True', 'db_index': 'True' } ), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'key': ('django.db.models.fields.CharField', [], { 'max_length': '32' }), 'last_seen': ( 'django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now', 'null': 'True', 'db_index': 'True' } ), 'project': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Project']", 'null': 'True' } ), 'times_seen': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'default': '0' }), 'value': ('django.db.models.fields.CharField', [], { 'max_length': '200' }) }, 'sentry.team': { 'Meta': { 'unique_together': "(('organization', 'slug'),)", 'object_name': 'Team' }, 'date_added': ( 'django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now', 'null': 'True' } ), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'name': ('django.db.models.fields.CharField', [], { 'max_length': '64' }), 'organization': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Organization']" } ), 'owner': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.User']" } ), 'slug': ('django.db.models.fields.SlugField', [], { 'max_length': '50' }), 'status': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'default': '0' }) }, 'sentry.teammember': { 'Meta': { 'unique_together': "(('team', 'user'),)", 'object_name': 'TeamMember' }, 'date_added': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'team': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Team']" } ), 'type': ('sentry.db.models.fields.bounded.BoundedIntegerField', [], { 'default': '50' }), 'user': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.User']" } ) }, 'sentry.user': { 'Meta': { 'object_name': 'User', 'db_table': "'auth_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' }), 'id': ('django.db.models.fields.AutoField', [], { 'primary_key': 'True' }), 'is_active': ('django.db.models.fields.BooleanField', [], { 'default': 'True' }), 'is_managed': ('django.db.models.fields.BooleanField', [], { 'default': 'False' }), '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' }), 'username': ('django.db.models.fields.CharField', [], { 'unique': 'True', 'max_length': '128' }) }, 'sentry.useroption': { 'Meta': { 'unique_together': "(('user', 'project', 'key'),)", 'object_name': 'UserOption' }, 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'key': ('django.db.models.fields.CharField', [], { 'max_length': '64' }), 'project': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Project']", 'null': 'True' } ), 'user': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.User']" } ), 'value': ('sentry.db.models.fields.pickle.UnicodePickledObjectField', [], {}) } } complete_apps = ['sentry']<|fim▁end|>
}, 'date_added': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now'
<|file_name|>decorator.py<|end_file_name|><|fim▁begin|>""" Time Execution decorator """ import socket import time from fqn_decorators import Decorator from fqn_decorators.asynchronous import AsyncDecorator from pkgsettings import Settings SHORT_HOSTNAME = socket.gethostname() settings = Settings() settings.configure(backends=[], hooks=[], duration_field="value") def write_metric(name, **metric): for backend in settings.backends: backend.write(name, **metric) def _apply_hooks(hooks, response, exception, metric, func, func_args, func_kwargs): metadata = dict() for hook in hooks: hook_result = hook( response=response, exception=exception, metric=metric, func=func, func_args=func_args, func_kwargs=func_kwargs, ) if hook_result: metadata.update(hook_result) return metadata class time_execution(Decorator): def __init__(self, func=None, **params): self.start_time = None super(time_execution, self).__init__(func, **params) def before(self): self.start_time = time.time() def after(self): duration = round(time.time() - self.start_time, 3) * 1000 metric = {"name": self.fqn, settings.duration_field: duration, "hostname": SHORT_HOSTNAME} origin = getattr(settings, "origin", None) if origin: metric["origin"] = origin hooks = self.params.get("extra_hooks", []) disable_default_hooks = self.params.get("disable_default_hooks", False) if not disable_default_hooks: hooks = settings.hooks + hooks # Apply the registered hooks, and collect the metadata they might # return to be stored with the metrics metadata = _apply_hooks( hooks=hooks, response=self.result, exception=self.get_exception(), metric=metric, func=self.func, func_args=self.args, func_kwargs=self.kwargs, ) metric.update(metadata) write_metric(**metric) def get_exception(self): """Retrieve the exception""" if self.exc_info is None: return <|fim▁hole|> exc_type, exc_value, exc_tb = self.exc_info if exc_value is None: exc_value = exc_type() if exc_value.__traceback__ is not exc_tb: return exc_value.with_traceback(exc_tb) return exc_value class time_execution_async(AsyncDecorator, time_execution): pass<|fim▁end|>
<|file_name|>PropertySaver.java<|end_file_name|><|fim▁begin|>/* * PropertySaver.java * * Created on October 9, 2007, 3:13 PM * * Trieda, ktoru nainicializuje objekt PropertyReader, pri starte programu * WebAnalyzer. Tento objekt bude jedinacik a bude poskytovat vlastnosti, ktore * potrebuju jednotlive moduly WebAnalyzatoru. * */ package org.apache.analyzer.config; /** * * @author praso */ public class PropertySaver { public static final PropertySaver INSTANCE = new PropertySaver(); private int crawlerPropertyMaxUrls; private int crawlerPropertyTimeout; /** * Creates a new instance of PropertySaver */ private PropertySaver() { } public int getCrawlerPropertyMaxUrls() { return crawlerPropertyMaxUrls; } public void setCrawlerPropertyMaxUrls(int crawlerPropertyMaxUrls) { this.crawlerPropertyMaxUrls = crawlerPropertyMaxUrls; } <|fim▁hole|> public int getCrawlerPropertyTimeout() { return crawlerPropertyTimeout; } public void setCrawlerPropertyTimeout(int crawlerPropertyTimeout) { this.crawlerPropertyTimeout = crawlerPropertyTimeout; } }<|fim▁end|>
<|file_name|>ewf-param-position.js<|end_file_name|><|fim▁begin|>(function($){ "use strict"; <|fim▁hole|> $('.wpb-element-edit-modal .ewf-position-box div').click(function(){ // e.preventDefault(); $(this).closest('.ewf-position-box').find('div').removeClass('active'); $(this).addClass('active'); console.log('execute param position shit!'); var value = 'none'; if ($(this).hasClass('ewf-pb-top')) { value = 'top'; } if ($(this).hasClass('ewf-pb-top-right')) { value = 'top-right'; } if ($(this).hasClass('ewf-pb-top-left')) { value = 'top-left'; } if ($(this).hasClass('ewf-pb-bottom')) { value = 'bottom'; } if ($(this).hasClass('ewf-pb-bottom-right')) { value = 'bottom-right'; } if ($(this).hasClass('ewf-pb-bottom-left')) { value = 'bottom-left'; } if ($(this).hasClass('ewf-pb-left')) { value = 'left'; } if ($(this).hasClass('ewf-pb-right')) { value = 'right'; } $(this).closest('.edit_form_line').find('input.wpb_vc_param_value').val(value); }); })(window.jQuery);<|fim▁end|>
// wpb_el_type_position
<|file_name|>FixedBinaryString.hpp<|end_file_name|><|fim▁begin|>// C/C++ File // Author: Alexandre Tea <[email protected]> // File: /Users/alexandretea/Work/gachc-steinerproblem/srcs/ga/FixedBinaryString.hpp // Purpose: TODO (a one-line explanation) // Created: 2017-01-15 20:57:05 // Modified: 2017-03-15 17:31:42 #ifndef FIXEDBINARYSTRING_H #define FIXEDBINARYSTRING_H #include <cstddef> #include <vector> #include <utility> #include "utils/random.hpp" #include "utils/IStringRepresentation.hpp" namespace ga { // TODO assert _rep_size is the same when operations between two instances class FixedBinaryString : public utils::IStringRepresentation { public: using DynamicBitset = std::vector<bool>; // will store values as bits using ChildPair = std::pair<FixedBinaryString, FixedBinaryString>; public: FixedBinaryString(); FixedBinaryString(size_t s); FixedBinaryString(DynamicBitset const& bitset); virtual ~FixedBinaryString(); FixedBinaryString(FixedBinaryString const& o); FixedBinaryString& operator=(FixedBinaryString const& o); public:<|fim▁hole|> // Reproduction operators ChildPair crossover_singlepoint(FixedBinaryString const& rhs) const; ChildPair crossover_twopoint(FixedBinaryString const& rhs) const; // Mutation operators void flip_all(); void flip_random(); // Iterators DynamicBitset::const_iterator begin() const; DynamicBitset::const_iterator end() const; DynamicBitset::iterator begin(); DynamicBitset::iterator end(); public: virtual std::string to_string() const; static FixedBinaryString random(size_t size); protected: size_t _rep_size; DynamicBitset _rep; }; std::ostream& operator<<(std::ostream& s, utils::IStringRepresentation const& o); } #endif /* end of include guard: FIXEDBINARYSTRING_H */<|fim▁end|>
void flip(unsigned int index); bool test(unsigned int index) const; bool operator[](unsigned int index) const; size_t size() const;
<|file_name|>PermMissingElem.java<|end_file_name|><|fim▁begin|>class Solution { public int solution(int[] A) {<|fim▁hole|> int[] temArray = new int[A.length + 2]; for (int i = 0; i < A.length; i++) { temArray[A[i]] = 1; } for (int i = 1; i < temArray.length + 1; i++) { if(temArray[i] == 0){ return i; } } return A[A.length - 1] + 1; } }<|fim▁end|>