repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
yogeshsaroya/new-cdnjs
ajax/libs/ammaps/3.10.0/maps/js/irelandLow.min.js
130
version https://git-lfs.github.com/spec/v1 oid sha256:2bdfe5678cd560584ad9cf5e163bac4dcc8b54e7e5efd3369cb30a7f193cfae8 size 78833
mit
project-schumann/vmf-parser
src/test/java/com/drkharma/vmf/KeySignatureTest.java
1403
package com.drkharma.vmf; import org.junit.Test; import static org.junit.Assert.assertEquals; /** * Test class for {@link KeySignature} */ public class KeySignatureTest { /** * Tests the case where a key signature has 0 sharps and 0 * flats. */ @Test public void testGetKeySignatureCode001() { int code = KeySignature.C_MAJOR_A_MINOR.getKeySignatureCode(); assertEquals(0, code); } /** * Tests the case where a key signature has sharps. */ @Test public void testGetKeySignatureCode002() { int code = KeySignature.G_MAJOR_E_MINOR.getKeySignatureCode(); assertEquals(1, code); } /** * Tests the case where a key signature has flats. */ @Test public void testGetKeySignature003() { int code = KeySignature.F_MAJOR_D_MINOR.getKeySignatureCode(); assertEquals(-1, code); } /** * Tests retrieval of a key signature which exists. */ @Test public void testGetKeySignature001() { KeySignature ks = KeySignature.getKeySignature(0); assertEquals(KeySignature.C_MAJOR_A_MINOR, ks); } /** * Tests retrieval of a key signature which does not exist. */ @Test(expected = IllegalArgumentException.class) public void testGetKeySignature002() { KeySignature ks = KeySignature.getKeySignature(100); } }
mit
jordanabrahambaws/DotNetwork
DotNetwork/Oldscape/Network/Protocol/Packet/PacketBuilder.cs
14357
// Copyright(c) 2010-2011 Graham Edgecombe // Copyright(c) 2011-2016 Major<major.emrs@gmail.com> and other apollo contributors // // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS.IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. using DotNetty.Buffers; using DotNetwork.Oldscape.Util.Buf; using System; using System.Text; namespace DotNetwork.Oldscape.Network.Protocol.Packet { /// <summary> /// Assists in creating a packet. /// </summary> sealed class PacketBuilder { /// <summary> /// The buffer. /// </summary> private readonly IByteBuffer buffer; /// <summary> /// The current mode. /// </summary> private AccessMode mode = AccessMode.BYTE_ACCESS; /// <summary> /// The current bit index. /// </summary> private int bitIndex; /// <summary> /// Constructs a new object. /// </summary> public PacketBuilder() : this(Unpooled.Buffer()) { } /// <summary> /// Constructs a new object. /// </summary> /// <param name="buffer"></param> public PacketBuilder(IByteBuffer buffer) { this.buffer = buffer; } /// <summary> /// Checks that this builder is in the bit access mode. /// </summary> private void CheckBitAccess() { if (mode != AccessMode.BIT_ACCESS) throw new Exception("For bit-based calls to work, the mode must be bit access."); } /// <summary> /// Checks that this builder is in the byte access mode. /// </summary> private void CheckByteAccess() { if (mode != AccessMode.BYTE_ACCESS) throw new Exception("For bit-based calls to work, the mode must be byte access."); } /// <summary> /// Gets the current length of the builder's buffer. /// </summary> /// <returns></returns> public int GetLength() { CheckByteAccess(); return buffer.WriterIndex; } /// <summary> /// Puts a standard data type with the specified value, byte order and transformation. /// </summary> /// <param name="type"></param> /// <param name="order"></param> /// <param name="transformation"></param> /// <param name="value"></param> public void Put(DataType type, DataOrder order, DataTransformation transformation, long value) { CheckByteAccess(); int length = (int)type; switch (order) { case DataOrder.BIG: for (int index = length - 1; index >= 0; index--) { if (index == 0 && transformation != DataTransformation.NONE) { if (transformation == DataTransformation.ADD) buffer.WriteByte((byte)(value + 128)); else if (transformation == DataTransformation.NEGATE) buffer.WriteByte((byte)-value); else if (transformation == DataTransformation.SUBTRACT) buffer.WriteByte((byte)(128 - value)); else throw new Exception("Unknown transformation."); } else buffer.WriteByte((byte)(value >> index * 8)); } break; case DataOrder.INVERSED_MIDDLE: if (transformation != DataTransformation.NONE) throw new Exception("Inversed middle endian cannot be transformed."); if (type != DataType.INT) throw new Exception("Inversed middle endian can only be used with an integer."); buffer.WriteByte((byte)(value >> 16)); buffer.WriteByte((byte)(value >> 24)); buffer.WriteByte((byte)value); buffer.WriteByte((byte)(value >> 8)); break; case DataOrder.LITTLE: for (int index = 0; index < length; index++) { if (index == 0 && transformation != DataTransformation.NONE) { if (transformation == DataTransformation.ADD) buffer.WriteByte((byte)(value + 128)); else if (transformation == DataTransformation.NEGATE) buffer.WriteByte((byte)-value); else if (transformation == DataTransformation.SUBTRACT) buffer.WriteByte((byte)(128 - value)); else throw new Exception("Unknown transformation."); } else buffer.WriteByte((byte)(value >> index * 8)); } break; case DataOrder.MIDDLE: if (transformation != DataTransformation.NONE) throw new Exception("Middle endian cannot be transformed."); if (type != DataType.INT) throw new Exception("Middle endian can only be used with an integer."); buffer.WriteByte((byte)(value >> 8)); buffer.WriteByte((byte)value); buffer.WriteByte((byte)(value >> 24)); buffer.WriteByte((byte)(value >> 16)); break; } } /// <summary> /// Puts a standard data type with the specified value and byte order. /// </summary> /// <param name="type"></param> /// <param name="order"></param> /// <param name="value"></param> public void Put(DataType type, DataOrder order, long value) { Put(type, order, DataTransformation.NONE, value); } /// <summary> /// Puts a standard data type with the specified value and transformation. /// </summary> /// <param name="type"></param> /// <param name="transformation"></param> /// <param name="value"></param> public void Put(DataType type, DataTransformation transformation, long value) { Put(type, DataOrder.BIG, transformation, value); } /// <summary> /// Puts a standard data type with the specified value. /// </summary> /// <param name="type"></param> /// <param name="value"></param> public void Put(DataType type, long value) { Put(type, DataOrder.BIG, DataTransformation.NONE, value); } /// <summary> /// Puts a single bit into the buffer. If {@code flag} is {@code true}, the value of the bit is {@code 1}. If {@code flag} is {@code false}, the value of the bit is {@code 0}. /// </summary> /// <param name="flag"></param> public void PutBit(bool flag) { PutBit(flag ? 1 : 0); } /// <summary> /// Puts a single bit into the buffer with the value {@code value}. /// </summary> /// <param name="value"></param> public void PutBit(int value) { PutBits(1, value); } /// <summary> /// Puts {@code numBits} into the buffer with the value {@code value}. /// </summary> /// <param name="numBits"></param> /// <param name="value"></param> public void PutBits(int numBits, int value) { CheckBitAccess(); int bytePos = bitIndex >> 3; int bitOffset = 8 - (bitIndex & 7); bitIndex += numBits; int requiredSpace = bytePos - buffer.WriterIndex + 1; requiredSpace += (numBits + 7) / 8; buffer.EnsureWritable(requiredSpace); for (; numBits > bitOffset; bitOffset = 8) { int tmp = buffer.GetByte(bytePos); tmp &= ~DataConstants.BIT_MASK[bitOffset]; tmp |= value >> numBits - bitOffset & DataConstants.BIT_MASK[bitOffset]; buffer.SetByte(bytePos++, tmp); numBits -= bitOffset; } if (numBits == bitOffset) { int tmp = buffer.GetByte(bytePos); tmp &= ~DataConstants.BIT_MASK[bitOffset]; tmp |= value & DataConstants.BIT_MASK[bitOffset]; buffer.SetByte(bytePos, tmp); } else { int tmp = buffer.GetByte(bytePos); tmp &= ~(DataConstants.BIT_MASK[numBits] << bitOffset - numBits); tmp |= (value & DataConstants.BIT_MASK[numBits]) << bitOffset - numBits; buffer.SetByte(bytePos, tmp); } } /// <summary> /// Puts the specified byte array into the buffer. /// </summary> /// <param name="bytes"></param> public void PutBytes(byte[] bytes) { buffer.WriteBytes(bytes); } /// <summary> /// Puts the bytes from the specified buffer into this packet's buffer. /// </summary> /// <param name="buffer"></param> public void PutBytes(IByteBuffer buffer) { byte[] bytes = new byte[buffer.ReadableBytes]; buffer.MarkReaderIndex(); try { buffer.ReadBytes(bytes); } finally { buffer.ResetReaderIndex(); } PutBytes(bytes); } /// <summary> /// Puts the bytes into the buffer with the specified transformation. /// </summary> /// <param name="transformation"></param> /// <param name="bytes"></param> public void PutBytes(DataTransformation transformation, byte[] bytes) { if (transformation == DataTransformation.NONE) PutBytes(bytes); else { foreach (byte b in bytes) Put(DataType.BYTE, transformation, b); } } /// <summary> /// Puts the specified byte array into the buffer in reverse. /// </summary> /// <param name="bytes"></param> public void PutBytesReverse(byte[] bytes) { CheckByteAccess(); for (int index = bytes.Length - 1; index >= 0; index--) buffer.WriteByte(bytes[index]); } /// <summary> /// Puts the bytes from the specified buffer into this packet's buffer, in reverse. /// </summary> /// <param name="buffer"></param> public void PutBytesReverse(IByteBuffer buffer) { byte[] bytes = new byte[buffer.ReadableBytes]; buffer.MarkReaderIndex(); try { buffer.ReadBytes(bytes); } finally { buffer.ResetReaderIndex(); } PutBytesReverse(bytes); } /// <summary> /// Puts the specified byte array into the buffer in reverse with the specified transformation. /// </summary> /// <param name="transformation"></param> /// <param name="bytes"></param> public void PutBytesReverse(DataTransformation transformation, byte[] bytes) { if (transformation == DataTransformation.NONE) PutBytesReverse(bytes); else { for (int index = bytes.Length - 1; index >= 0; index--) Put(DataType.BYTE, transformation, bytes[index]); } } /// <summary> /// Puts a smart into the buffer. /// </summary> /// <param name="value"></param> public void PutSmart(int value) { CheckByteAccess(); if (value < 128) buffer.WriteByte(value); else buffer.WriteShort(value); } /// <summary> /// Puts a string into the buffer. /// </summary> /// <param name="str"></param> public void PutString(string str) { CheckByteAccess(); char[] chars = str.ToCharArray(); foreach (char c in chars) buffer.WriteByte((byte)c); buffer.WriteByte(IByteBufferExtensions.STRING_TERMINATOR); } /// <summary> /// Switches this builder's mode to the bit access mode. /// </summary> public void SwitchToBitAccess() { if (mode == AccessMode.BIT_ACCESS) return; mode = AccessMode.BIT_ACCESS; bitIndex = buffer.WriterIndex * 8; } /// <summary> /// Switches this builder's mode to the byte access mode. /// </summary> public void SwitchToByteAccess() { if (mode == AccessMode.BYTE_ACCESS) return; mode = AccessMode.BYTE_ACCESS; buffer.SetWriterIndex((bitIndex + 7) / 8); } /// <summary> /// Gets the buffer. /// </summary> /// <returns></returns> public IByteBuffer GetBuffer() { return buffer; } } }
mit
CodeLizards/Jobs-Queue
server/models/website.js
236
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var websiteSchema = new Schema({ content: String, id: String, url: String, }); var website = mongoose.model('website', websiteSchema); module.exports = website;
mit
pepinho24/Demos
Design Patterns/Behavioral/ChainOfResponsibility/DeveloperTeams/DeveloperTeamFactory.cs
587
namespace ChainOfResponsibility.DeveloperTeams { internal class DeveloperTeamFactory : IDeveloperTeamFactory { public DeveloperTeam CreateAndAttachDeveloperTeams() { var juniorDeveloperTeam = new JuniorDeveloperTeam(); var regularDeveloperTeam = new RegularDeveloperTeam(); var seniorDeveloperTeam = new SeniorDeveloperTeam(); juniorDeveloperTeam.SetSuccessor(regularDeveloperTeam); regularDeveloperTeam.SetSuccessor(seniorDeveloperTeam); return juniorDeveloperTeam; } } }
mit
Qambar/romanNumerals
test/numerals/NumeralsGeneratorTest.java
1148
package numerals; import static org.junit.Assert.assertEquals; import org.junit.Test; import uk.co.bbc.roman.NumeralGenerator; import uk.co.bbc.roman.NumeralGeneratorInterface; public class NumeralsGeneratorTest { NumeralGeneratorInterface numeralGeneratorTest = new NumeralGenerator(); @Test(expected = IllegalArgumentException.class) public void itThrowsException() { numeralGeneratorTest.generate(-2); } @Test public void itReturnsOne() { assertEquals("Single Digit Test for 1", "I", numeralGeneratorTest.generate(1)); } @Test public void itReturnsTwo() { assertEquals("Single Digit Test for 2", "II", numeralGeneratorTest.generate(2)); } @Test public void itReturns() { assertEquals("Single Digit Test for 3", "III", numeralGeneratorTest.generate(3)); } @Test public void itReturnsTen() { assertEquals("Double Digit Test for 10", "X", numeralGeneratorTest.generate(10)); } @Test public void itReturns3999() { assertEquals("Largest Number Test for 3999", "MMMCMXCIX", numeralGeneratorTest.generate(3999)); } }
mit
aj-michael/raft
src/main/scala/edu/rosehulman/collections/DistributedMap.scala
4221
package edu.rosehulman.collections import akka.actor._ import akka.event.Logging import akka.event.slf4j.Logger import akka.pattern.ask import akka.util.Timeout import edu.rosehulman.raft.messages.{CommandResponse, FailedCommandResponse, CommandRequest} import java.util.concurrent.TimeoutException import scala.concurrent.Await import scala.concurrent.duration._ import scala.util.control.Breaks._ class DistributedMap[T] (raftWorkerPaths: List[String]) extends scala.collection.mutable.Map[String, T] { val system = ActorSystem("raft") val log = Logging.getLogger(system, this) val workers: List[ActorSelection] = raftWorkerPaths.map(system.actorSelection(_)) implicit val timeout = Timeout(10.seconds) override def +=(kv: (String, T)): this.type = { val request = CommandRequest.put(kv._1, kv._2) workers.foreach { a => val future = a ? request try Await.result(future, timeout.duration) match { case FailedCommandResponse(leaderId) => if (leaderId.isDefined) { val ref = system.actorSelection(RootActorPath(leaderId.get) / "user" / "worker") Await.result(ref ? request, timeout.duration) match { case FailedCommandResponse(leaderId) => throw new RuntimeException("Leader is down, all hope is lost: " + leaderId) case CommandResponse(value) => log.info("Command += returned value: " + value) return this } } case CommandResponse(value) => log.info("Command += returned value: " + value) return this } catch { case e: TimeoutException => log.warning("Worker " + a + " is not responding") } } return this } override def -=(key: String) = { val request = CommandRequest.delete(key) breakable { workers.foreach { a => val future = a ? request try Await.result(future, timeout.duration) match { case FailedCommandResponse(leaderId) => if (leaderId.isDefined) { val ref = system.actorSelection(RootActorPath(leaderId.get) / "user" / "worker") Await.result(ref ? request, timeout.duration) match { case FailedCommandResponse(leaderId) => throw new RuntimeException("Leader is down, all hope is lost") case CommandResponse(value) => log.info("Command -= returned value: " + value) break } } case CommandResponse(value) => log.info("Command -= returned value: " + value) break } catch { case e: TimeoutException => log.warning("Worker " + a + " is not responding") } } } this } override def get(key: String) = { val request = CommandRequest.get(key) var returnValue: Option[T] = Option.empty breakable { workers.foreach { a => val future = a ? request try Await.result(future, timeout.duration) match { case FailedCommandResponse(leaderId) => if (leaderId.isDefined) { val ref = system.actorSelection(RootActorPath(leaderId.get) / "user" / "worker") Await.result(ref ? request, timeout.duration) match { case FailedCommandResponse(leaderId) => throw new RuntimeException("Leader is down, all hope is lost") case CommandResponse(value: T) => log.info("Command get returned value: " + value) returnValue = Option(value) break } } case CommandResponse(value: T) => log.info("Command get returned value: " + value) returnValue = Option(value) break } catch { case e: TimeoutException => log.warning("Worker " + a + " is not responding") } } } returnValue } override def iterator = { workers.foreach { a => a ! CommandRequest.iterator } Iterator.empty } }
mit
ThiagoFacchini/3DUX
app/i18n.js
891
// @flow import { addLocaleData } from 'react-intl' import enLocaleData from 'react-intl/locale-data/en' import { DEFAULT_LOCALE } from './structural/LanguageProvider/constants' import enTranslationMessages from './translations/en.json' export const appLocales = [ 'en', ] addLocaleData(enLocaleData) export const formatTranslationMessages = (locale: string, messages: Object) => { const defaultFormattedMessages = locale !== DEFAULT_LOCALE ? formatTranslationMessages(DEFAULT_LOCALE, enTranslationMessages) : {} return Object.keys(messages).reduce((formattedMessages, key) => { let message = messages[key] if (!message && locale !== DEFAULT_LOCALE) { message = defaultFormattedMessages[key] } return Object.assign(formattedMessages, { [key]: message }) }, {}) } export const translationMessages = { en: formatTranslationMessages('en', enTranslationMessages), }
mit
arz-ngs/arz-ngs
ng-service-ui/src/at/arz/ngs/ui/controllers/ServiceInstanceController.java
15093
package at.arz.ngs.ui.controllers; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import javax.enterprise.context.SessionScoped; import javax.faces.context.FacesContext; import javax.inject.Inject; import javax.inject.Named; import at.arz.ngs.search.OrderCondition; import at.arz.ngs.search.PaginationCondition; import at.arz.ngs.serviceinstance.ServiceInstanceAdmin; import at.arz.ngs.serviceinstance.commands.find.ServiceInstanceOverview; import at.arz.ngs.serviceinstance.commands.find.ServiceInstanceOverviewList; import at.arz.ngs.ui.data_collections.ConfirmStopAllCollection; import at.arz.ngs.ui.data_collections.Error; import at.arz.ngs.ui.data_collections.ErrorCollection; import at.arz.ngs.ui.data_collections.OrderImgCollection; import at.arz.ngs.ui.data_collections.OverviewCollection; import at.arz.ngs.ui.data_collections.PaginationCollection; @SessionScoped @Named("serviceinstance") public class ServiceInstanceController implements Serializable { private static final long serialVersionUID = 1L; @Inject private ServiceInstanceAdmin admin; private List<OverviewCollection> instancesCollection; private PaginationCondition pagination; private PaginationCollection paginationCollection; private int numElementsFound; private String serviceRegex; private String envIdRegex; private String hostRegex; private String instanceRegex; private OrderCondition order; private OrderImgCollection orderCollection; private ErrorCollection errorCollection; private ConfirmStopAllCollection confirmCollection; @PostConstruct public void init() { pagination = new PaginationCondition(50, 1); // default is first page with 50 elements order = new OrderCondition(OrderCondition.ORDERBY_SERVICEINSTANCE, OrderCondition.ASCENDING); errorCollection = new ErrorCollection(); try { mapToOverviewCollection(admin.getServiceInstances("*", "*", "*", "*", order, pagination)); } catch (RuntimeException e) { errorCollection.addError(new Error(e)); errorCollection.setShowPopup(true); } paginationCollection = new PaginationCollection(); orderCollection = new OrderImgCollection(); doPaginationValidation(); doSortValidation("instance"); confirmCollection = new ConfirmStopAllCollection(); confirmCollection.setShowPopup(false); } private void mapToOverviewCollection(ServiceInstanceOverviewList list) { numElementsFound = list.getNumElementsFound(); instancesCollection = new ArrayList<>(); for (ServiceInstanceOverview o : list.getServiceInstances()) { instancesCollection.add(new OverviewCollection(o)); } } public String goToOverview() { formSubmit(); return "overview"; } /** * This method should be invoked when someone presses Enter on the overview * (sets the current page to the first one) */ public void enterFormSubmit() { pagination.setCurrentPage(1); formSubmit(); } public void formSubmit() { errorCollection = new ErrorCollection(); try { mapToOverviewCollection(admin.getServiceInstances(cumputeServiceRegex(), cumputeEnvRegex(), cumputeHostRegex(), cumputeInstanceRegex(), order, pagination)); } catch (RuntimeException e) { errorCollection.addError(new Error(e)); errorCollection.setShowPopup(true); } doPaginationValidation(); } public void sortAction(String sortBy) { if (sortBy.equals(orderCollection.getLastSortedBy())) { // turn arrow if (orderCollection.isLastSortedASC()) { // if asc last, now sort desc order.setOrder(OrderCondition.DESCENDING); } else { order.setOrder(OrderCondition.ASCENDING); } } else { order.setOrder(OrderCondition.ASCENDING); } if (sortBy.equals("service")) { order.setOrderByField(OrderCondition.ORDERBY_SERVICE); } else if (sortBy.equals("envId")) { order.setOrderByField(OrderCondition.ORDERBY_ENVIRONMENT); } else if (sortBy.equals("host")) { order.setOrderByField(OrderCondition.ORDERBY_HOST); } else if (sortBy.equals("instance")) { order.setOrderByField(OrderCondition.ORDERBY_SERVICEINSTANCE); } else if (sortBy.equals("status")) { order.setOrderByField(OrderCondition.ORDERBY_STATUS); } errorCollection = new ErrorCollection(); try { mapToOverviewCollection(admin.getServiceInstances(cumputeServiceRegex(), cumputeEnvRegex(), cumputeHostRegex(), cumputeInstanceRegex(), order, pagination)); } catch (RuntimeException e) { errorCollection.addError(new Error(e)); errorCollection.setShowPopup(true); } doSortValidation(sortBy); } private void doSortValidation(String lastSortedBy) { orderCollection.setLastSortedASC(order.getOrder().equals(OrderCondition.ASCENDING)); orderCollection.setLastSortedBy(lastSortedBy); orderCollection.setServiceOrderSRC(resolveOrderImg("service")); orderCollection.setEnvOrderSRC(resolveOrderImg("envId")); orderCollection.setHostOrderSRC(resolveOrderImg("host")); orderCollection.setInstanceOrderSRC(resolveOrderImg("instance")); orderCollection.setStatusOrderSRC(resolveOrderImg("status")); } private String resolveOrderImg(String field) { if (orderCollection.getLastSortedBy().equals(field)) { if (orderCollection.isLastSortedASC()) { return OrderImgCollection.ASC_enabled; } else { return OrderImgCollection.DESC_enabled; } } else { return OrderImgCollection.ASC_disabled; } } public void performPagination(String newPage) { try { int page = new Integer(newPage); pagination.setCurrentPage(page); } catch (Exception e) { if (newPage.equals("_lt")) { pagination.setCurrentPage(pagination.getCurrentPage() - 1); } else if (newPage.equals("_gt")) { pagination.setCurrentPage(pagination.getCurrentPage() + 1); } else { throw e; } } errorCollection = new ErrorCollection(); try { mapToOverviewCollection(admin.getServiceInstances(cumputeServiceRegex(), cumputeEnvRegex(), cumputeHostRegex(), cumputeInstanceRegex(), order, pagination)); } catch (RuntimeException e) { errorCollection.addError(new Error(e)); errorCollection.setShowPopup(true); } doPaginationValidation(); } /** * Computes the fields in the pagination (ui) */ private void doPaginationValidation() { int overallElementCount = numElementsFound; int currentPage = pagination.getCurrentPage(); int elemPerPage = pagination.getElementsPerPage(); int lastPage = 0; if (overallElementCount % elemPerPage == 0) { lastPage = overallElementCount / elemPerPage; } else { lastPage = (overallElementCount / elemPerPage) + 1; } paginationCollection.setLeftCaretClass(currentPage == 1 ? PaginationCollection.DISABLED : null); paginationCollection.setLeftCaretDisabled(currentPage == 1); paginationCollection.setRightCaretClass(currentPage == lastPage ? PaginationCollection.DISABLED : null); paginationCollection.setRightCaretDisabled(currentPage == lastPage); int numPages = lastPage; if (numPages == 1 || numPages == 0) { paginationCollection.setShowSecondElem(false); paginationCollection.setShowThirdElem(false); paginationCollection.setShowFourthElem(false); paginationCollection.setShowFifthElem(false); paginationCollection.setSecondElement("-1"); // not shown here paginationCollection.setThirdElement("-1"); paginationCollection.setFourthElement("-1"); paginationCollection.setFithElement("-1"); } else if (numPages == 2) { paginationCollection.setShowSecondElem(false); paginationCollection.setShowThirdElem(false); paginationCollection.setShowFourthElem(false); paginationCollection.setShowFifthElem(true); paginationCollection.setSecondElement("-1"); paginationCollection.setThirdElement("-1"); paginationCollection.setFourthElement("-1"); } else if (numPages == 3) { paginationCollection.setShowSecondElem(false); paginationCollection.setShowThirdElem(false); paginationCollection.setShowFourthElem(true); paginationCollection.setShowFifthElem(true); paginationCollection.setSecondElement("-1"); paginationCollection.setThirdElement("-1"); paginationCollection.setFourthElement("2"); } else if (numPages == 4) { paginationCollection.setShowSecondElem(false); paginationCollection.setShowThirdElem(true); paginationCollection.setShowFourthElem(true); paginationCollection.setShowFifthElem(true); paginationCollection.setSecondElement("-1"); paginationCollection.setThirdElement("2"); paginationCollection.setFourthElement("3"); } else if (numPages >= 5) { paginationCollection.setShowSecondElem(true); paginationCollection.setShowThirdElem(true); paginationCollection.setShowFourthElem(true); paginationCollection.setShowFifthElem(true); // don't hide anything if (currentPage == 1 || currentPage == 2) { paginationCollection.setSecondElement("2"); paginationCollection.setThirdElement("3"); paginationCollection.setFourthElement("4"); } else if (currentPage == lastPage || currentPage == lastPage - 1) { paginationCollection.setFourthElement((lastPage - 1) + ""); paginationCollection.setThirdElement((lastPage - 2) + ""); paginationCollection.setSecondElement((lastPage - 3) + ""); } else { // if the current page is somewhere in the middle paginationCollection.setSecondElement((currentPage - 1) + ""); paginationCollection.setThirdElement(currentPage + ""); paginationCollection.setFourthElement((currentPage + 1) + ""); } } paginationCollection.setFithElement(lastPage + ""); // now highlight current page to be active if (paginationCollection.getFirstElement().equals(currentPage + "")) { paginationCollection.setFirstElementClass(PaginationCollection.ACTIVE); paginationCollection.setSecondElementClass(null); paginationCollection.setThirdElementClass(null); paginationCollection.setFourthElementClass(null); paginationCollection.setFifthElementClass(null); } else if (paginationCollection.getFithElement().equals(currentPage + "")) { paginationCollection.setFirstElementClass(null); paginationCollection.setSecondElementClass(null); paginationCollection.setThirdElementClass(null); paginationCollection.setFourthElementClass(null); paginationCollection.setFifthElementClass(PaginationCollection.ACTIVE); } else if (paginationCollection.getSecondElement().equals(currentPage + "")) { paginationCollection.setFirstElementClass(null); paginationCollection.setSecondElementClass(PaginationCollection.ACTIVE); paginationCollection.setThirdElementClass(null); paginationCollection.setFourthElementClass(null); paginationCollection.setFifthElementClass(null); } else if (paginationCollection.getThirdElement().equals(currentPage + "")) { paginationCollection.setFirstElementClass(null); paginationCollection.setSecondElementClass(null); paginationCollection.setThirdElementClass(PaginationCollection.ACTIVE); paginationCollection.setFourthElementClass(null); paginationCollection.setFifthElementClass(null); } else if (paginationCollection.getFourthElement().equals(currentPage + "")) { paginationCollection.setFirstElementClass(null); paginationCollection.setSecondElementClass(null); paginationCollection.setThirdElementClass(null); paginationCollection.setFourthElementClass(PaginationCollection.ACTIVE); paginationCollection.setFifthElementClass(null); } } public String cancelPendingJob() { confirmCollection.dispose(); formSubmit(); return "overview"; } public void cancelPendingSingleJob() { try { FacesContext.getCurrentInstance().getExternalContext() .redirect("detailview.xhtml?instance=" + confirmCollection.getInstance() + "&service=" + confirmCollection.getService() + "&env=" + confirmCollection.getEnvironment() + "&host=" + confirmCollection.getHost()); } catch (IOException e) { e.printStackTrace(); } confirmCollection.dispose(); } private String cumputeServiceRegex() { if (serviceRegex == null) { return "*"; } return serviceRegex + "*"; } private String cumputeEnvRegex() { if (envIdRegex == null) { return "*"; } return envIdRegex + "*"; } private String cumputeHostRegex() { if (hostRegex == null) { return "*"; } return hostRegex + "*"; } private String cumputeInstanceRegex() { if (instanceRegex == null) { return "*"; } return instanceRegex + "*"; } public PaginationCollection getPaginationCollection() { return paginationCollection; } public PaginationCondition getPagination() { return pagination; } public ServiceInstanceAdmin getService() { return admin; } public void setService(ServiceInstanceAdmin service) { this.admin = service; } public OrderCondition getOrder() { return order; } public void setOrder(OrderCondition order) { this.order = order; } public String getServiceRegex() { return serviceRegex; } public void setServiceRegex(String serviceRegex) { this.serviceRegex = serviceRegex; } public String getEnvIdRegex() { return envIdRegex; } public void setEnvIdRegex(String envIdRegex) { this.envIdRegex = envIdRegex; } public String getHostRegex() { return hostRegex; } public void setHostRegex(String hostRegex) { this.hostRegex = hostRegex; } public String getInstanceRegex() { return instanceRegex; } public void setInstanceRegex(String instanceRegex) { this.instanceRegex = instanceRegex; } public void setPagination(PaginationCondition pagination) { this.pagination = pagination; } public void setPaginationCollection(PaginationCollection paginationCollection) { this.paginationCollection = paginationCollection; } public OrderImgCollection getOrderCollection() { return orderCollection; } public void setOrderCollection(OrderImgCollection orderCollection) { this.orderCollection = orderCollection; } public List<OverviewCollection> getInstancesCollection() { return instancesCollection; } public void setInstancesCollection(List<OverviewCollection> instancesCollection) { this.instancesCollection = instancesCollection; } public ErrorCollection getErrorCollection() { return errorCollection; } public void setErrorCollection(ErrorCollection errorCollection) { this.errorCollection = errorCollection; } public ConfirmStopAllCollection getConfirmCollection() { return confirmCollection; } public void setConfirmCollection(ConfirmStopAllCollection confirmCollection) { this.confirmCollection = confirmCollection; } }
mit
catedrasaes-umu/NoSQLDataEngineering
projects/es.um.nosql.s13e.datavisualization/NoSQLDataIndex/Movies/js/gen/_OBJ_E_Movies.js
34373
var DiffMethodsExclusive = { isOfExactType_Actor_1: function (obj) { if (!("Name" in obj) || !(typeof obj.Name === "string")) return false; if (!("Age" in obj) || !(typeof obj.Age === "number") || !(obj.Age % 1 === 0)) return false; if (!("Birthday" in obj) || !(typeof obj.Birthday === "string")) return false; if (!("type" in obj) || !(typeof obj.type === "string") || (obj.type !== "Actor")) return false; if ("Nationality" in obj && !(!(obj.Nationality.constructor === Array) || (!checkAllOf(obj.Nationality, "String")))) return false; if ("Debut_year" in obj && !(!(typeof obj.Debut_year === "number") || !(obj.Debut_year % 1 === 0))) return false; if ("hasAwards" in obj && !((typeof obj.hasAwards === "object" && !(obj.hasAwards instanceof Array) && (!this.isOfExactType_Award_1(obj.hasAwards))) || (obj.hasAwards.constructor === Array && (0 > obj.hasAwards.size || !checkAllOf(obj.hasAwards, "object") || obj.hasAwards[0] == null || !this.isOfExactType_Award_1(obj.hasAwards[0]) )) || (typeof obj.hasAwards !== "object" && obj.hasAwards.constructor !== Array))) return false; if ("Website" in obj && !(!(typeof obj.Website === "string"))) return false; return true; }, isOfExactType_Actor_2: function (obj) { if (!("Name" in obj) || !(typeof obj.Name === "string")) return false; if (!("Age" in obj) || !(typeof obj.Age === "number") || !(obj.Age % 1 === 0)) return false; if (!("Birthday" in obj) || !(typeof obj.Birthday === "string")) return false; if (!("Nationality" in obj) || !(obj.Nationality.constructor === Array) || (!checkAllOf(obj.Nationality, "String"))) return false; if (!("hasAwards" in obj) || (typeof obj.hasAwards === "object" && !(obj.hasAwards instanceof Array) && (!this.isOfExactType_Award_1(obj.hasAwards))) || (obj.hasAwards.constructor === Array && (0 > obj.hasAwards.size || !checkAllOf(obj.hasAwards, "object") || obj.hasAwards[0] == null || !this.isOfExactType_Award_1(obj.hasAwards[0]) )) || (typeof obj.hasAwards !== "object" && obj.hasAwards.constructor !== Array)) return false; if (!("type" in obj) || !(typeof obj.type === "string") || (obj.type !== "Actor")) return false; if ("Debut_year" in obj && !(!(typeof obj.Debut_year === "number") || !(obj.Debut_year % 1 === 0))) return false; if ("Website" in obj && !(!(typeof obj.Website === "string"))) return false; return true; }, isOfExactType_Actor_3: function (obj) { if (!("Name" in obj) || !(typeof obj.Name === "string")) return false; if (!("Age" in obj) || !(typeof obj.Age === "number") || !(obj.Age % 1 === 0)) return false; if (!("Birthday" in obj) || !(typeof obj.Birthday === "string")) return false; if (!("Nationality" in obj) || !(obj.Nationality.constructor === Array) || (!checkAllOf(obj.Nationality, "String"))) return false; if (!("Debut_year" in obj) || !(typeof obj.Debut_year === "number") || !(obj.Debut_year % 1 === 0)) return false; if (!("hasAwards" in obj) || (typeof obj.hasAwards === "object" && !(obj.hasAwards instanceof Array) && (!this.isOfExactType_Award_1(obj.hasAwards))) || (obj.hasAwards.constructor === Array && (0 > obj.hasAwards.size || !checkAllOf(obj.hasAwards, "object") || obj.hasAwards[0] == null || !this.isOfExactType_Award_1(obj.hasAwards[0]) )) || (typeof obj.hasAwards !== "object" && obj.hasAwards.constructor !== Array)) return false; if (!("type" in obj) || !(typeof obj.type === "string") || (obj.type !== "Actor")) return false; if ("Website" in obj && !(!(typeof obj.Website === "string"))) return false; return true; }, isOfExactType_Actor_4: function (obj) { if (!("Name" in obj) || !(typeof obj.Name === "string")) return false; if (!("Age" in obj) || !(typeof obj.Age === "number") || !(obj.Age % 1 === 0)) return false; if (!("Birthday" in obj) || !(typeof obj.Birthday === "string")) return false; if (!("Nationality" in obj) || !(obj.Nationality.constructor === Array) || (!checkAllOf(obj.Nationality, "String"))) return false; if (!("Debut_year" in obj) || !(typeof obj.Debut_year === "number") || !(obj.Debut_year % 1 === 0)) return false; if (!("Website" in obj) || !(typeof obj.Website === "string")) return false; if (!("hasAwards" in obj) || (typeof obj.hasAwards === "object" && !(obj.hasAwards instanceof Array) && (!this.isOfExactType_Award_1(obj.hasAwards))) || (obj.hasAwards.constructor === Array && (0 > obj.hasAwards.size || !checkAllOf(obj.hasAwards, "object") || obj.hasAwards[0] == null || !this.isOfExactType_Award_1(obj.hasAwards[0]) )) || (typeof obj.hasAwards !== "object" && obj.hasAwards.constructor !== Array)) return false; if (!("type" in obj) || !(typeof obj.type === "string") || (obj.type !== "Actor")) return false; return true; }, isOfExactType_Award_1: function (obj) { if (!("Name" in obj) || !(typeof obj.Name === "string")) return false; if (!("Institution" in obj) || !(typeof obj.Institution === "string")) return false; if (!("Year" in obj) || !(typeof obj.Year === "number") || !(obj.Year % 1 === 0)) return false; if (!("type" in obj) || !(typeof obj.type === "string") || (obj.type !== "Award")) return false; return true; }, isOfExactType_Director_1: function (obj) { if (!("Name" in obj) || !(typeof obj.Name === "string")) return false; if (!("Age" in obj) || !(typeof obj.Age === "string")) return false; if (!("type" in obj) || !(typeof obj.type === "string") || (obj.type !== "Director")) return false; if ("Age" in obj && !(!(typeof obj.Age === "number") || !(obj.Age % 1 === 0))) return false; if ("hasAwards" in obj && !((typeof obj.hasAwards === "object" && !(obj.hasAwards instanceof Array) && (!this.isOfExactType_Award_1(obj.hasAwards))) || (obj.hasAwards.constructor === Array && (0 > obj.hasAwards.size || !checkAllOf(obj.hasAwards, "object") || obj.hasAwards[0] == null || !this.isOfExactType_Award_1(obj.hasAwards[0]) )) || (typeof obj.hasAwards !== "object" && obj.hasAwards.constructor !== Array))) return false; if ("Oscars" in obj && !(!(typeof obj.Oscars === "number") || !(obj.Oscars % 1 === 0))) return false; return true; }, isOfExactType_Director_2: function (obj) { if (!("Name" in obj) || !(typeof obj.Name === "string")) return false; if (!("Age" in obj) || !(typeof obj.Age === "number") || !(obj.Age % 1 === 0)) return false; if (!("Oscars" in obj) || !(typeof obj.Oscars === "number") || !(obj.Oscars % 1 === 0)) return false; if (!("type" in obj) || !(typeof obj.type === "string") || (obj.type !== "Director")) return false; if ("hasAwards" in obj && !((typeof obj.hasAwards === "object" && !(obj.hasAwards instanceof Array) && (!this.isOfExactType_Award_1(obj.hasAwards))) || (obj.hasAwards.constructor === Array && (0 > obj.hasAwards.size || !checkAllOf(obj.hasAwards, "object") || obj.hasAwards[0] == null || !this.isOfExactType_Award_1(obj.hasAwards[0]) )) || (typeof obj.hasAwards !== "object" && obj.hasAwards.constructor !== Array))) return false; if ("Age" in obj && !(!(typeof obj.Age === "string"))) return false; return true; }, isOfExactType_Director_3: function (obj) { if (!("Name" in obj) || !(typeof obj.Name === "string")) return false; if (!("Age" in obj) || !(typeof obj.Age === "number") || !(obj.Age % 1 === 0)) return false; if (!("hasAwards" in obj) || (typeof obj.hasAwards === "object" && !(obj.hasAwards instanceof Array) && (!this.isOfExactType_Award_1(obj.hasAwards))) || (obj.hasAwards.constructor === Array && (0 > obj.hasAwards.size || !checkAllOf(obj.hasAwards, "object") || obj.hasAwards[0] == null || !this.isOfExactType_Award_1(obj.hasAwards[0]) )) || (typeof obj.hasAwards !== "object" && obj.hasAwards.constructor !== Array)) return false; if (!("type" in obj) || !(typeof obj.type === "string") || (obj.type !== "Director")) return false; if ("Age" in obj && !(!(typeof obj.Age === "string"))) return false; if ("Oscars" in obj && !(!(typeof obj.Oscars === "number") || !(obj.Oscars % 1 === 0))) return false; return true; }, isOfExactType_Movie_1: function (obj) { if (!("Name" in obj) || !(typeof obj.Name === "string")) return false; if (!("Director" in obj) || !(typeof obj.Director === "string")) return false; if (!("Year" in obj) || !(typeof obj.Year === "number") || !(obj.Year % 1 === 0)) return false; if (!("Rating" in obj) || !(typeof obj.Rating === "number") || (obj.Rating % 1 === 0)) return false; if (!("Genre" in obj) || !(obj.Genre.constructor === Array) || (!checkAllOf(obj.Genre, "String"))) return false; if (!("type" in obj) || !(typeof obj.type === "string") || (obj.type !== "Movie")) return false; if ("Oscars" in obj && !(!(typeof obj.Oscars === "number") || !(obj.Oscars % 1 === 0))) return false; if ("hasDirector" in obj && !((typeof obj.hasDirector === "string" && false) || (obj.hasDirector.constructor === Array && (1 > obj.hasDirector.size || 1 < obj.hasDirector.size || !checkAllOf(obj.hasDirector, "string")) || (typeof obj.hasDirector !== "string" && obj.hasDirector.constructor !== Array)))) return false; if ("hasProducers" in obj && !((typeof obj.hasProducers === "string" && false) || (obj.hasProducers.constructor === Array && (1 > obj.hasProducers.size || !checkAllOf(obj.hasProducers, "string")) || (typeof obj.hasProducers !== "string" && obj.hasProducers.constructor !== Array)))) return false; if ("hasActors" in obj && !((typeof obj.hasActors === "string" && false) || (obj.hasActors.constructor === Array && (0 > obj.hasActors.size || !checkAllOf(obj.hasActors, "string")) || (typeof obj.hasActors !== "string" && obj.hasActors.constructor !== Array)))) return false; if ("Awards" in obj && !(!(typeof obj.Awards === "number") || !(obj.Awards % 1 === 0))) return false; if ("hasRating" in obj && !((typeof obj.hasRating === "object" && !(obj.hasRating instanceof Array) && (!this.isOfExactType_Rating_1(obj.hasRating))) || (obj.hasRating.constructor === Array && (1 > obj.hasRating.size || 1 < obj.hasRating.size || !checkAllOf(obj.hasRating, "object") || obj.hasRating[0] == null || !this.isOfExactType_Rating_1(obj.hasRating[0]) )) || (typeof obj.hasRating !== "object" && obj.hasRating.constructor !== Array))) return false; if ("hasRating" in obj && !((typeof obj.hasRating === "object" && !(obj.hasRating instanceof Array) && (!this.isOfExactType_Rating_2(obj.hasRating))) || (obj.hasRating.constructor === Array && (1 > obj.hasRating.size || 1 < obj.hasRating.size || !checkAllOf(obj.hasRating, "object") || obj.hasRating[0] == null || !this.isOfExactType_Rating_2(obj.hasRating[0]) )) || (typeof obj.hasRating !== "object" && obj.hasRating.constructor !== Array))) return false; if ("hasAwards" in obj && !((typeof obj.hasAwards === "object" && !(obj.hasAwards instanceof Array) && (!this.isOfExactType_Award_1(obj.hasAwards))) || (obj.hasAwards.constructor === Array && (0 > obj.hasAwards.size || !checkAllOf(obj.hasAwards, "object") || obj.hasAwards[0] == null || !this.isOfExactType_Award_1(obj.hasAwards[0]) )) || (typeof obj.hasAwards !== "object" && obj.hasAwards.constructor !== Array))) return false; if ("hasRating" in obj && !((typeof obj.hasRating === "string" && false) || (obj.hasRating.constructor === Array && (1 > obj.hasRating.size || 1 < obj.hasRating.size || !checkAllOf(obj.hasRating, "string")) || (typeof obj.hasRating !== "string" && obj.hasRating.constructor !== Array)))) return false; return true; }, isOfExactType_Movie_2: function (obj) { if (!("Name" in obj) || !(typeof obj.Name === "string")) return false; if (!("Year" in obj) || !(typeof obj.Year === "number") || !(obj.Year % 1 === 0)) return false; if (!("Rating" in obj) || !(typeof obj.Rating === "number") || (obj.Rating % 1 === 0)) return false; if (!("Genre" in obj) || !(obj.Genre.constructor === Array) || (!checkAllOf(obj.Genre, "String"))) return false; if (!("Oscars" in obj) || !(typeof obj.Oscars === "number") || !(obj.Oscars % 1 === 0)) return false; if (!("hasDirector" in obj) || (typeof obj.hasDirector === "string" && false) || (obj.hasDirector.constructor === Array && (1 > obj.hasDirector.size || 1 < obj.hasDirector.size || !checkAllOf(obj.hasDirector, "string")) || (typeof obj.hasDirector !== "string" && obj.hasDirector.constructor !== Array))) return false; if (!("hasProducers" in obj) || (typeof obj.hasProducers === "string" && false) || (obj.hasProducers.constructor === Array && (1 > obj.hasProducers.size || !checkAllOf(obj.hasProducers, "string")) || (typeof obj.hasProducers !== "string" && obj.hasProducers.constructor !== Array))) return false; if (!("hasActors" in obj) || (typeof obj.hasActors === "string" && false) || (obj.hasActors.constructor === Array && (0 > obj.hasActors.size || !checkAllOf(obj.hasActors, "string")) || (typeof obj.hasActors !== "string" && obj.hasActors.constructor !== Array))) return false; if (!("type" in obj) || !(typeof obj.type === "string") || (obj.type !== "Movie")) return false; if ("Director" in obj && !(!(typeof obj.Director === "string"))) return false; if ("Awards" in obj && !(!(typeof obj.Awards === "number") || !(obj.Awards % 1 === 0))) return false; if ("hasRating" in obj && !((typeof obj.hasRating === "object" && !(obj.hasRating instanceof Array) && (!this.isOfExactType_Rating_1(obj.hasRating))) || (obj.hasRating.constructor === Array && (1 > obj.hasRating.size || 1 < obj.hasRating.size || !checkAllOf(obj.hasRating, "object") || obj.hasRating[0] == null || !this.isOfExactType_Rating_1(obj.hasRating[0]) )) || (typeof obj.hasRating !== "object" && obj.hasRating.constructor !== Array))) return false; if ("hasRating" in obj && !((typeof obj.hasRating === "object" && !(obj.hasRating instanceof Array) && (!this.isOfExactType_Rating_2(obj.hasRating))) || (obj.hasRating.constructor === Array && (1 > obj.hasRating.size || 1 < obj.hasRating.size || !checkAllOf(obj.hasRating, "object") || obj.hasRating[0] == null || !this.isOfExactType_Rating_2(obj.hasRating[0]) )) || (typeof obj.hasRating !== "object" && obj.hasRating.constructor !== Array))) return false; if ("hasAwards" in obj && !((typeof obj.hasAwards === "object" && !(obj.hasAwards instanceof Array) && (!this.isOfExactType_Award_1(obj.hasAwards))) || (obj.hasAwards.constructor === Array && (0 > obj.hasAwards.size || !checkAllOf(obj.hasAwards, "object") || obj.hasAwards[0] == null || !this.isOfExactType_Award_1(obj.hasAwards[0]) )) || (typeof obj.hasAwards !== "object" && obj.hasAwards.constructor !== Array))) return false; if ("hasRating" in obj && !((typeof obj.hasRating === "string" && false) || (obj.hasRating.constructor === Array && (1 > obj.hasRating.size || 1 < obj.hasRating.size || !checkAllOf(obj.hasRating, "string")) || (typeof obj.hasRating !== "string" && obj.hasRating.constructor !== Array)))) return false; return true; }, isOfExactType_Movie_3: function (obj) { if (!("Name" in obj) || !(typeof obj.Name === "string")) return false; if (!("Year" in obj) || !(typeof obj.Year === "number") || !(obj.Year % 1 === 0)) return false; if (!("Genre" in obj) || !(obj.Genre.constructor === Array) || (!checkAllOf(obj.Genre, "String"))) return false; if (!("Awards" in obj) || !(typeof obj.Awards === "number") || !(obj.Awards % 1 === 0)) return false; if (!("hasDirector" in obj) || (typeof obj.hasDirector === "string" && false) || (obj.hasDirector.constructor === Array && (1 > obj.hasDirector.size || 1 < obj.hasDirector.size || !checkAllOf(obj.hasDirector, "string")) || (typeof obj.hasDirector !== "string" && obj.hasDirector.constructor !== Array))) return false; if (!("hasProducers" in obj) || (typeof obj.hasProducers === "string" && false) || (obj.hasProducers.constructor === Array && (1 > obj.hasProducers.size || !checkAllOf(obj.hasProducers, "string")) || (typeof obj.hasProducers !== "string" && obj.hasProducers.constructor !== Array))) return false; if (!("hasActors" in obj) || (typeof obj.hasActors === "string" && false) || (obj.hasActors.constructor === Array && (0 > obj.hasActors.size || !checkAllOf(obj.hasActors, "string")) || (typeof obj.hasActors !== "string" && obj.hasActors.constructor !== Array))) return false; if (!("hasRating" in obj) || (typeof obj.hasRating === "string" && false) || (obj.hasRating.constructor === Array && (1 > obj.hasRating.size || 1 < obj.hasRating.size || !checkAllOf(obj.hasRating, "string")) || (typeof obj.hasRating !== "string" && obj.hasRating.constructor !== Array))) return false; if (!("type" in obj) || !(typeof obj.type === "string") || (obj.type !== "Movie")) return false; if ("Director" in obj && !(!(typeof obj.Director === "string"))) return false; if ("Rating" in obj && !(!(typeof obj.Rating === "number") || (obj.Rating % 1 === 0))) return false; if ("Oscars" in obj && !(!(typeof obj.Oscars === "number") || !(obj.Oscars % 1 === 0))) return false; if ("hasRating" in obj && !((typeof obj.hasRating === "object" && !(obj.hasRating instanceof Array) && (!this.isOfExactType_Rating_1(obj.hasRating))) || (obj.hasRating.constructor === Array && (1 > obj.hasRating.size || 1 < obj.hasRating.size || !checkAllOf(obj.hasRating, "object") || obj.hasRating[0] == null || !this.isOfExactType_Rating_1(obj.hasRating[0]) )) || (typeof obj.hasRating !== "object" && obj.hasRating.constructor !== Array))) return false; if ("hasRating" in obj && !((typeof obj.hasRating === "object" && !(obj.hasRating instanceof Array) && (!this.isOfExactType_Rating_2(obj.hasRating))) || (obj.hasRating.constructor === Array && (1 > obj.hasRating.size || 1 < obj.hasRating.size || !checkAllOf(obj.hasRating, "object") || obj.hasRating[0] == null || !this.isOfExactType_Rating_2(obj.hasRating[0]) )) || (typeof obj.hasRating !== "object" && obj.hasRating.constructor !== Array))) return false; if ("hasAwards" in obj && !((typeof obj.hasAwards === "object" && !(obj.hasAwards instanceof Array) && (!this.isOfExactType_Award_1(obj.hasAwards))) || (obj.hasAwards.constructor === Array && (0 > obj.hasAwards.size || !checkAllOf(obj.hasAwards, "object") || obj.hasAwards[0] == null || !this.isOfExactType_Award_1(obj.hasAwards[0]) )) || (typeof obj.hasAwards !== "object" && obj.hasAwards.constructor !== Array))) return false; return true; }, isOfExactType_Movie_4: function (obj) { if (!("Name" in obj) || !(typeof obj.Name === "string")) return false; if (!("Year" in obj) || !(typeof obj.Year === "number") || !(obj.Year % 1 === 0)) return false; if (!("Genre" in obj) || !(obj.Genre.constructor === Array) || (!checkAllOf(obj.Genre, "String"))) return false; if (!("Awards" in obj) || !(typeof obj.Awards === "number") || !(obj.Awards % 1 === 0)) return false; if (!("hasDirector" in obj) || (typeof obj.hasDirector === "string" && false) || (obj.hasDirector.constructor === Array && (1 > obj.hasDirector.size || 1 < obj.hasDirector.size || !checkAllOf(obj.hasDirector, "string")) || (typeof obj.hasDirector !== "string" && obj.hasDirector.constructor !== Array))) return false; if (!("hasProducers" in obj) || (typeof obj.hasProducers === "string" && false) || (obj.hasProducers.constructor === Array && (1 > obj.hasProducers.size || !checkAllOf(obj.hasProducers, "string")) || (typeof obj.hasProducers !== "string" && obj.hasProducers.constructor !== Array))) return false; if (!("hasActors" in obj) || (typeof obj.hasActors === "string" && false) || (obj.hasActors.constructor === Array && (0 > obj.hasActors.size || !checkAllOf(obj.hasActors, "string")) || (typeof obj.hasActors !== "string" && obj.hasActors.constructor !== Array))) return false; if (!("hasRating" in obj) || (typeof obj.hasRating === "object" && !(obj.hasRating instanceof Array) && (!this.isOfExactType_Rating_1(obj.hasRating))) || (obj.hasRating.constructor === Array && (1 > obj.hasRating.size || 1 < obj.hasRating.size || !checkAllOf(obj.hasRating, "object") || obj.hasRating[0] == null || !this.isOfExactType_Rating_1(obj.hasRating[0]) )) || (typeof obj.hasRating !== "object" && obj.hasRating.constructor !== Array)) return false; if (!("type" in obj) || !(typeof obj.type === "string") || (obj.type !== "Movie")) return false; if ("Director" in obj && !(!(typeof obj.Director === "string"))) return false; if ("Rating" in obj && !(!(typeof obj.Rating === "number") || (obj.Rating % 1 === 0))) return false; if ("Oscars" in obj && !(!(typeof obj.Oscars === "number") || !(obj.Oscars % 1 === 0))) return false; if ("hasRating" in obj && !((typeof obj.hasRating === "object" && !(obj.hasRating instanceof Array) && (!this.isOfExactType_Rating_2(obj.hasRating))) || (obj.hasRating.constructor === Array && (1 > obj.hasRating.size || 1 < obj.hasRating.size || !checkAllOf(obj.hasRating, "object") || obj.hasRating[0] == null || !this.isOfExactType_Rating_2(obj.hasRating[0]) )) || (typeof obj.hasRating !== "object" && obj.hasRating.constructor !== Array))) return false; if ("hasAwards" in obj && !((typeof obj.hasAwards === "object" && !(obj.hasAwards instanceof Array) && (!this.isOfExactType_Award_1(obj.hasAwards))) || (obj.hasAwards.constructor === Array && (0 > obj.hasAwards.size || !checkAllOf(obj.hasAwards, "object") || obj.hasAwards[0] == null || !this.isOfExactType_Award_1(obj.hasAwards[0]) )) || (typeof obj.hasAwards !== "object" && obj.hasAwards.constructor !== Array))) return false; if ("hasRating" in obj && !((typeof obj.hasRating === "string" && false) || (obj.hasRating.constructor === Array && (1 > obj.hasRating.size || 1 < obj.hasRating.size || !checkAllOf(obj.hasRating, "string")) || (typeof obj.hasRating !== "string" && obj.hasRating.constructor !== Array)))) return false; return true; }, isOfExactType_Movie_5: function (obj) { if (!("Name" in obj) || !(typeof obj.Name === "string")) return false; if (!("Year" in obj) || !(typeof obj.Year === "number") || !(obj.Year % 1 === 0)) return false; if (!("Genre" in obj) || !(obj.Genre.constructor === Array) || (!checkAllOf(obj.Genre, "String"))) return false; if (!("Awards" in obj) || !(typeof obj.Awards === "number") || !(obj.Awards % 1 === 0)) return false; if (!("hasDirector" in obj) || (typeof obj.hasDirector === "string" && false) || (obj.hasDirector.constructor === Array && (1 > obj.hasDirector.size || 1 < obj.hasDirector.size || !checkAllOf(obj.hasDirector, "string")) || (typeof obj.hasDirector !== "string" && obj.hasDirector.constructor !== Array))) return false; if (!("hasProducers" in obj) || (typeof obj.hasProducers === "string" && false) || (obj.hasProducers.constructor === Array && (1 > obj.hasProducers.size || !checkAllOf(obj.hasProducers, "string")) || (typeof obj.hasProducers !== "string" && obj.hasProducers.constructor !== Array))) return false; if (!("hasActors" in obj) || (typeof obj.hasActors === "string" && false) || (obj.hasActors.constructor === Array && (0 > obj.hasActors.size || !checkAllOf(obj.hasActors, "string")) || (typeof obj.hasActors !== "string" && obj.hasActors.constructor !== Array))) return false; if (!("hasRating" in obj) || (typeof obj.hasRating === "object" && !(obj.hasRating instanceof Array) && (!this.isOfExactType_Rating_2(obj.hasRating))) || (obj.hasRating.constructor === Array && (1 > obj.hasRating.size || 1 < obj.hasRating.size || !checkAllOf(obj.hasRating, "object") || obj.hasRating[0] == null || !this.isOfExactType_Rating_2(obj.hasRating[0]) )) || (typeof obj.hasRating !== "object" && obj.hasRating.constructor !== Array)) return false; if (!("type" in obj) || !(typeof obj.type === "string") || (obj.type !== "Movie")) return false; if ("Director" in obj && !(!(typeof obj.Director === "string"))) return false; if ("Rating" in obj && !(!(typeof obj.Rating === "number") || (obj.Rating % 1 === 0))) return false; if ("Oscars" in obj && !(!(typeof obj.Oscars === "number") || !(obj.Oscars % 1 === 0))) return false; if ("hasRating" in obj && !((typeof obj.hasRating === "object" && !(obj.hasRating instanceof Array) && (!this.isOfExactType_Rating_1(obj.hasRating))) || (obj.hasRating.constructor === Array && (1 > obj.hasRating.size || 1 < obj.hasRating.size || !checkAllOf(obj.hasRating, "object") || obj.hasRating[0] == null || !this.isOfExactType_Rating_1(obj.hasRating[0]) )) || (typeof obj.hasRating !== "object" && obj.hasRating.constructor !== Array))) return false; if ("hasAwards" in obj && !((typeof obj.hasAwards === "object" && !(obj.hasAwards instanceof Array) && (!this.isOfExactType_Award_1(obj.hasAwards))) || (obj.hasAwards.constructor === Array && (0 > obj.hasAwards.size || !checkAllOf(obj.hasAwards, "object") || obj.hasAwards[0] == null || !this.isOfExactType_Award_1(obj.hasAwards[0]) )) || (typeof obj.hasAwards !== "object" && obj.hasAwards.constructor !== Array))) return false; if ("hasRating" in obj && !((typeof obj.hasRating === "string" && false) || (obj.hasRating.constructor === Array && (1 > obj.hasRating.size || 1 < obj.hasRating.size || !checkAllOf(obj.hasRating, "string")) || (typeof obj.hasRating !== "string" && obj.hasRating.constructor !== Array)))) return false; return true; }, isOfExactType_Movie_6: function (obj) { if (!("Name" in obj) || !(typeof obj.Name === "string")) return false; if (!("Year" in obj) || !(typeof obj.Year === "number") || !(obj.Year % 1 === 0)) return false; if (!("Genre" in obj) || !(obj.Genre.constructor === Array) || (!checkAllOf(obj.Genre, "String"))) return false; if (!("hasDirector" in obj) || (typeof obj.hasDirector === "string" && false) || (obj.hasDirector.constructor === Array && (1 > obj.hasDirector.size || 1 < obj.hasDirector.size || !checkAllOf(obj.hasDirector, "string")) || (typeof obj.hasDirector !== "string" && obj.hasDirector.constructor !== Array))) return false; if (!("hasProducers" in obj) || (typeof obj.hasProducers === "string" && false) || (obj.hasProducers.constructor === Array && (1 > obj.hasProducers.size || !checkAllOf(obj.hasProducers, "string")) || (typeof obj.hasProducers !== "string" && obj.hasProducers.constructor !== Array))) return false; if (!("hasActors" in obj) || (typeof obj.hasActors === "string" && false) || (obj.hasActors.constructor === Array && (0 > obj.hasActors.size || !checkAllOf(obj.hasActors, "string")) || (typeof obj.hasActors !== "string" && obj.hasActors.constructor !== Array))) return false; if (!("hasRating" in obj) || (typeof obj.hasRating === "object" && !(obj.hasRating instanceof Array) && (!this.isOfExactType_Rating_2(obj.hasRating))) || (obj.hasRating.constructor === Array && (1 > obj.hasRating.size || 1 < obj.hasRating.size || !checkAllOf(obj.hasRating, "object") || obj.hasRating[0] == null || !this.isOfExactType_Rating_2(obj.hasRating[0]) )) || (typeof obj.hasRating !== "object" && obj.hasRating.constructor !== Array)) return false; if (!("hasAwards" in obj) || (typeof obj.hasAwards === "object" && !(obj.hasAwards instanceof Array) && (!this.isOfExactType_Award_1(obj.hasAwards))) || (obj.hasAwards.constructor === Array && (0 > obj.hasAwards.size || !checkAllOf(obj.hasAwards, "object") || obj.hasAwards[0] == null || !this.isOfExactType_Award_1(obj.hasAwards[0]) )) || (typeof obj.hasAwards !== "object" && obj.hasAwards.constructor !== Array)) return false; if (!("type" in obj) || !(typeof obj.type === "string") || (obj.type !== "Movie")) return false; if ("Director" in obj && !(!(typeof obj.Director === "string"))) return false; if ("Rating" in obj && !(!(typeof obj.Rating === "number") || (obj.Rating % 1 === 0))) return false; if ("Oscars" in obj && !(!(typeof obj.Oscars === "number") || !(obj.Oscars % 1 === 0))) return false; if ("Awards" in obj && !(!(typeof obj.Awards === "number") || !(obj.Awards % 1 === 0))) return false; if ("hasRating" in obj && !((typeof obj.hasRating === "object" && !(obj.hasRating instanceof Array) && (!this.isOfExactType_Rating_1(obj.hasRating))) || (obj.hasRating.constructor === Array && (1 > obj.hasRating.size || 1 < obj.hasRating.size || !checkAllOf(obj.hasRating, "object") || obj.hasRating[0] == null || !this.isOfExactType_Rating_1(obj.hasRating[0]) )) || (typeof obj.hasRating !== "object" && obj.hasRating.constructor !== Array))) return false; if ("hasRating" in obj && !((typeof obj.hasRating === "string" && false) || (obj.hasRating.constructor === Array && (1 > obj.hasRating.size || 1 < obj.hasRating.size || !checkAllOf(obj.hasRating, "string")) || (typeof obj.hasRating !== "string" && obj.hasRating.constructor !== Array)))) return false; return true; }, isOfExactType_Producer_1: function (obj) { if (!("Name" in obj) || !(typeof obj.Name === "string")) return false; if (!("Budget" in obj) || !(typeof obj.Budget === "number") || (obj.Budget % 1 === 0)) return false; if (!("hasStudio" in obj) || (typeof obj.hasStudio === "object" && !(obj.hasStudio instanceof Array) && (!this.isOfExactType_Studio_1(obj.hasStudio))) || (obj.hasStudio.constructor === Array && (1 > obj.hasStudio.size || !checkAllOf(obj.hasStudio, "object") || obj.hasStudio[0] == null || !this.isOfExactType_Studio_1(obj.hasStudio[0]) )) || (typeof obj.hasStudio !== "object" && obj.hasStudio.constructor !== Array)) return false; if (!("type" in obj) || !(typeof obj.type === "string") || (obj.type !== "Producer")) return false; if ("Budget_per_year" in obj && !(!(typeof obj.Budget_per_year === "number") || (obj.Budget_per_year % 1 === 0))) return false; if ("Movies_per_year" in obj && !(!(typeof obj.Movies_per_year === "number") || !(obj.Movies_per_year % 1 === 0))) return false; if ("hasStudio" in obj && !((typeof obj.hasStudio === "object" && !(obj.hasStudio instanceof Array) && (!this.isOfExactType_Studio_2(obj.hasStudio))) || (obj.hasStudio.constructor === Array && (1 > obj.hasStudio.size || !checkAllOf(obj.hasStudio, "object") || obj.hasStudio[0] == null || !this.isOfExactType_Studio_2(obj.hasStudio[0]) )) || (typeof obj.hasStudio !== "object" && obj.hasStudio.constructor !== Array))) return false; return true; }, isOfExactType_Producer_2: function (obj) { if (!("Name" in obj) || !(typeof obj.Name === "string")) return false; if (!("Budget_per_year" in obj) || !(typeof obj.Budget_per_year === "number") || (obj.Budget_per_year % 1 === 0)) return false; if (!("Movies_per_year" in obj) || !(typeof obj.Movies_per_year === "number") || !(obj.Movies_per_year % 1 === 0)) return false; if (!("hasStudio" in obj) || (typeof obj.hasStudio === "object" && !(obj.hasStudio instanceof Array) && (!this.isOfExactType_Studio_2(obj.hasStudio))) || (obj.hasStudio.constructor === Array && (1 > obj.hasStudio.size || !checkAllOf(obj.hasStudio, "object") || obj.hasStudio[0] == null || !this.isOfExactType_Studio_2(obj.hasStudio[0]) )) || (typeof obj.hasStudio !== "object" && obj.hasStudio.constructor !== Array)) return false; if (!("type" in obj) || !(typeof obj.type === "string") || (obj.type !== "Producer")) return false; if ("Budget" in obj && !(!(typeof obj.Budget === "number") || (obj.Budget % 1 === 0))) return false; if ("hasStudio" in obj && !((typeof obj.hasStudio === "object" && !(obj.hasStudio instanceof Array) && (!this.isOfExactType_Studio_1(obj.hasStudio))) || (obj.hasStudio.constructor === Array && (1 > obj.hasStudio.size || !checkAllOf(obj.hasStudio, "object") || obj.hasStudio[0] == null || !this.isOfExactType_Studio_1(obj.hasStudio[0]) )) || (typeof obj.hasStudio !== "object" && obj.hasStudio.constructor !== Array))) return false; return true; }, isOfExactType_Rating_1: function (obj) { if (!("Rating" in obj) || !(typeof obj.Rating === "number") || (obj.Rating % 1 === 0)) return false; if (!("type" in obj) || !(typeof obj.type === "string") || (obj.type !== "Rating")) return false; if ("Votes" in obj && !(!(typeof obj.Votes === "number") || !(obj.Votes % 1 === 0))) return false; return true; }, isOfExactType_Rating_2: function (obj) { if (!("Rating" in obj) || !(typeof obj.Rating === "number") || (obj.Rating % 1 === 0)) return false; if (!("Votes" in obj) || !(typeof obj.Votes === "number") || !(obj.Votes % 1 === 0)) return false; if (!("type" in obj) || !(typeof obj.type === "string") || (obj.type !== "Rating")) return false; return true; }, isOfExactType_Studio_1: function (obj) { if (!("Name" in obj) || !(typeof obj.Name === "string")) return false; if (!("Location" in obj) || !(typeof obj.Location === "string")) return false; if (!("Year" in obj) || !(typeof obj.Year === "string")) return false; if (!("Website" in obj) || !(typeof obj.Website === "string")) return false; if (!("type" in obj) || !(typeof obj.type === "string") || (obj.type !== "Studio")) return false; if ("Year" in obj && !(!(typeof obj.Year === "number") || !(obj.Year % 1 === 0))) return false; if ("Founder" in obj && !(!(typeof obj.Founder === "string"))) return false; return true; }, isOfExactType_Studio_2: function (obj) { if (!("Name" in obj) || !(typeof obj.Name === "string")) return false; if (!("Location" in obj) || !(typeof obj.Location === "string")) return false; if (!("Year" in obj) || !(typeof obj.Year === "number") || !(obj.Year % 1 === 0)) return false; if (!("Website" in obj) || !(typeof obj.Website === "string")) return false; if (!("Founder" in obj) || !(typeof obj.Founder === "string")) return false; if (!("type" in obj) || !(typeof obj.type === "string") || (obj.type !== "Studio")) return false; if ("Year" in obj && !(!(typeof obj.Year === "string"))) return false; return true; } };
mit
adamgreenhall/openreviewquarterly
test/unit/helpers/author_helper_test.rb
73
require 'test_helper' class AuthorHelperTest < ActionView::TestCase end
mit
atomixnmc/AtomMini
src/sg/atom/ai/Mover.java
187
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package sg.atom.ai; /** * * @author CuongNguyen */ public interface Mover { }
mit
iluu/algs-progfun
src/test/java/com/hackerrank/LeftRotationTest.java
365
package com.hackerrank; import org.junit.Test; import static com.hackerrank.LeftRotation.rotateLeft; import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; public class LeftRotationTest { @Test public void simpleTestCase() { assertThat(rotateLeft(new int[]{1, 2, 3, 4, 5}, 4)) .isEqualTo("5 1 2 3 4"); } }
mit
casser/asx
src/babel/transformation/modules/index.js
399
export default { commonStrict: require("./common-strict"), amdStrict: require("./amd-strict"), umdStrict: require("./umd-strict"), asxStrict: require("./asx-strict"), common: require("./common"), system: require("./system"), ignore: require("./ignore"), amd: require("./amd"), umd: require("./umd"), asx: require("./asx") };
mit
neonichu/xcode-install
spec/install_spec.rb
2830
require File.expand_path('../spec_helper', __FILE__) module XcodeInstall describe Command::Install do describe 'when invoked' do before do Installer.any_instance.stubs(:exists).returns(true) Installer.any_instance.stubs(:installed).returns([]) fixture = Pathname.new('spec/fixtures/xcode_63.json').read xcode = Xcode.new(JSON.parse(fixture)) Installer.any_instance.stubs(:seedlist).returns([xcode]) end it 'downloads and installs' do Installer.any_instance.expects(:download).with('6.3', true, nil, nil, 3).returns('/some/path') Installer.any_instance.expects(:install_dmg).with('/some/path', '-6.3', true, true) Command::Install.run(['6.3']) end it 'downloads and installs with custom HTTP URL' do url = 'http://yolo.com/xcode.dmg' Installer.any_instance.expects(:download).with('6.3', true, url, nil, 3).returns('/some/path') Installer.any_instance.expects(:install_dmg).with('/some/path', '-6.3', true, true) Command::Install.run(['6.3', "--url=#{url}"]) end it 'downloads and installs and does not switch if --no-switch given' do Installer.any_instance.expects(:download).with('6.3', true, nil, nil, 3).returns('/some/path') Installer.any_instance.expects(:install_dmg).with('/some/path', '-6.3', false, true) Command::Install.run(['6.3', '--no-switch']) end it 'downloads without progress if switch --no-progress is given' do Installer.any_instance.expects(:download).with('6.3', false, nil, nil, 3).returns('/some/path') Installer.any_instance.expects(:install_dmg).with('/some/path', '-6.3', true, true) Command::Install.run(['6.3', '--no-progress']) end it 'reads .xcode-version' do Installer.any_instance.expects(:download).with('6.3', true, nil, nil, 3).returns('/some/path') Installer.any_instance.expects(:install_dmg).with('/some/path', '-6.3', true, true) File.expects(:exist?).with('.xcode-version').returns(true) File.expects(:read).returns('6.3') Command::Install.run([]) end end it 'parses hdiutil output' do installer = Installer.new fixture = Pathname.new('spec/fixtures/hdiutil.plist').read installer.expects(:hdiutil).with('mount', '-plist', '-nobrowse', '-noverify', '/some/path').returns(fixture) location = installer.send(:mount, Pathname.new('/some/path')) location.should == '/Volumes/XcodeME' end it 'gives more helpful error when downloaded DMG turns out to be HTML' do installer = Installer.new should.raise(Informative) { installer.mount('spec/fixtures/mail-verify.html') }.message .should.include 'logging into your account from a browser' end end end
mit
haefele/Mileage
src/03 Server/Mileage.Server.Infrastructure/Api/Configuration/MileageExceptionLogger.cs
645
using System.Web.Http.ExceptionHandling; using Anotar.NLog; namespace Mileage.Server.Infrastructure.Api.Configuration { public class MileageExceptionLogger : ExceptionLogger { /// <summary> /// When overridden in a derived class, logs the exception synchronously. /// </summary> /// <param name="context">The exception logger context.</param> public override void Log(ExceptionLoggerContext context) { LogTo.ErrorException(string.Format("Unhandled exception. Returning 501 Internal Server Error. Catch block: {0}", context.CatchBlock), context.Exception); } } }
mit
afritz1/OpenTESArena
OpenTESArena/src/World/SkyDefinition.cpp
5550
#include <algorithm> #include "SkyDefinition.h" #include "components/debug/Debug.h" SkyDefinition::LandPlacementDef::LandPlacementDef(LandDefID id, std::vector<Radians> &&positions) : positions(std::move(positions)) { this->id = id; } SkyDefinition::AirPlacementDef::AirPlacementDef(AirDefID id, std::vector<std::pair<Radians, Radians>> &&positions) : positions(std::move(positions)) { this->id = id; } SkyDefinition::StarPlacementDef::StarPlacementDef(StarDefID id, std::vector<Double3> &&positions) : positions(std::move(positions)) { this->id = id; } SkyDefinition::SunPlacementDef::SunPlacementDef(SunDefID id, std::vector<double> &&positions) : positions(std::move(positions)) { this->id = id; } SkyDefinition::MoonPlacementDef::Position::Position(const Double3 &baseDir, double orbitPercent, double bonusLatitude, int imageIndex) : baseDir(baseDir) { this->orbitPercent = orbitPercent; this->bonusLatitude = bonusLatitude; this->imageIndex = imageIndex; } SkyDefinition::MoonPlacementDef::MoonPlacementDef(MoonDefID id, std::vector<MoonPlacementDef::Position> &&positions) : positions(std::move(positions)) { this->id = id; } void SkyDefinition::init(Buffer<Color> &&skyColors) { this->skyColors = std::move(skyColors); } int SkyDefinition::getSkyColorCount() const { return this->skyColors.getCount(); } const Color &SkyDefinition::getSkyColor(int index) const { return this->skyColors.get(index); } int SkyDefinition::getLandPlacementDefCount() const { return static_cast<int>(this->landPlacementDefs.size()); } const SkyDefinition::LandPlacementDef &SkyDefinition::getLandPlacementDef(int index) const { DebugAssertIndex(this->landPlacementDefs, index); return this->landPlacementDefs[index]; } int SkyDefinition::getAirPlacementDefCount() const { return static_cast<int>(this->airPlacementDefs.size()); } const SkyDefinition::AirPlacementDef &SkyDefinition::getAirPlacementDef(int index) const { DebugAssertIndex(this->airPlacementDefs, index); return this->airPlacementDefs[index]; } int SkyDefinition::getStarPlacementDefCount() const { return static_cast<int>(this->starPlacementDefs.size()); } const SkyDefinition::StarPlacementDef &SkyDefinition::getStarPlacementDef(int index) const { DebugAssertIndex(this->starPlacementDefs, index); return this->starPlacementDefs[index]; } int SkyDefinition::getSunPlacementDefCount() const { return static_cast<int>(this->sunPlacementDefs.size()); } const SkyDefinition::SunPlacementDef &SkyDefinition::getSunPlacementDef(int index) const { DebugAssertIndex(this->sunPlacementDefs, index); return this->sunPlacementDefs[index]; } int SkyDefinition::getMoonPlacementDefCount() const { return static_cast<int>(this->moonPlacementDefs.size()); } const SkyDefinition::MoonPlacementDef &SkyDefinition::getMoonPlacementDef(int index) const { DebugAssertIndex(this->moonPlacementDefs, index); return this->moonPlacementDefs[index]; } void SkyDefinition::addLand(LandDefID id, Radians angle) { const auto iter = std::find_if(this->landPlacementDefs.begin(), this->landPlacementDefs.end(), [id](const LandPlacementDef &def) { return def.id == id; }); if (iter != this->landPlacementDefs.end()) { std::vector<Radians> &positions = iter->positions; positions.push_back(angle); } else { this->landPlacementDefs.emplace_back(id, std::vector<Radians> { angle }); } } void SkyDefinition::addAir(AirDefID id, Radians angleX, Radians angleY) { const auto iter = std::find_if(this->airPlacementDefs.begin(), this->airPlacementDefs.end(), [id](const AirPlacementDef &def) { return def.id == id; }); if (iter != this->airPlacementDefs.end()) { std::vector<std::pair<Radians, Radians>> &positions = iter->positions; positions.emplace_back(angleX, angleY); } else { this->airPlacementDefs.emplace_back(id, std::vector<std::pair<Radians, Radians>> { std::make_pair(angleX, angleY) }); } } void SkyDefinition::addStar(StarDefID id, const Double3 &direction) { const auto iter = std::find_if(this->starPlacementDefs.begin(), this->starPlacementDefs.end(), [id](const StarPlacementDef &def) { return def.id == id; }); if (iter != this->starPlacementDefs.end()) { std::vector<Double3> &positions = iter->positions; positions.emplace_back(direction); } else { this->starPlacementDefs.emplace_back(id, std::vector<Double3> { direction }); } } void SkyDefinition::addSun(SunDefID id, double bonusLatitude) { const auto iter = std::find_if(this->sunPlacementDefs.begin(), this->sunPlacementDefs.end(), [id](const SunPlacementDef &def) { return def.id == id; }); if (iter != this->sunPlacementDefs.end()) { std::vector<double> &positions = iter->positions; positions.push_back(bonusLatitude); } else { this->sunPlacementDefs.emplace_back(id, std::vector<double> { bonusLatitude }); } } void SkyDefinition::addMoon(MoonDefID id, const Double3 &baseDir, double orbitPercent, double bonusLatitude, int imageIndex) { const auto iter = std::find_if(this->moonPlacementDefs.begin(), this->moonPlacementDefs.end(), [id](const MoonPlacementDef &def) { return def.id == id; }); if (iter != this->moonPlacementDefs.end()) { std::vector<MoonPlacementDef::Position> &positions = iter->positions; positions.emplace_back(baseDir, orbitPercent, bonusLatitude, imageIndex); } else { std::vector<MoonPlacementDef::Position> positions; positions.emplace_back(baseDir, orbitPercent, bonusLatitude, imageIndex); this->moonPlacementDefs.emplace_back(id, std::move(positions)); } }
mit
error-404-unlam/jrpg-2017b-cliente
src/main/java/edu/unlam/wome/comandos/ActualizarTrueque.java
942
package edu.unlam.wome.comandos; import edu.unlam.wome.mensajeria.PaquetePersonaje; /** * Comando Actualizar Trueque * @author Miguel */ public class ActualizarTrueque extends ComandosEscucha { @Override public void ejecutar() { PaquetePersonaje paquetePersonaje = (PaquetePersonaje) getGson(). fromJson(getCadenaLeida(), PaquetePersonaje.class); this.getJuego().getPersonajesConectados().remove(paquetePersonaje.getId()); this.getJuego().getPersonajesConectados().put(paquetePersonaje.getId(), paquetePersonaje); if (this.getJuego().getPersonaje().getId() == paquetePersonaje.getId()) { this.getJuego().actualizarPersonaje(); this.getJuego().getEstadoJuego().actualizarPersonaje(); this.getJuego().getCli().actualizarItems(paquetePersonaje); this.getJuego().getCli().actualizarPersonaje(this.getJuego().getPersonajesConectados(). get(paquetePersonaje.getId())); } } }
mit
Filipkovarik/JS_projects
Polynomial.js
4385
var AdvMath; (function(){ function shallowCopy(a){var target={}; for (var i in a){if(a.hasOwnProperty(i)) target[i] = a[i];} return target} AdvMath = { Cartez:function(a,b){var c=[];for(var i=0;i<a.length;i++){for(var j=0;j<b.length;j++){c.push([a[i],b[j]])}}return c}, Monomial:function(a,b){if("string"==typeof a)return AdvMath.Monomial.parse(a);if(a instanceof AdvMath.Monomial){this.coef=a.coef; this.memb=shallowCopy(a.memb);} else {this.coef = a||1; this.memb = b||{}}}, Polynomial:function(a){if("string"==typeof a)return AdvMath.Polynomial.parse(a);if(a instanceof AdvMath.Polynomial){this.memb = a.clone().memb} else {var u = (a instanceof Array)?a:arguments;this.memb = []; for(var i=0;i<u.length;i+=2) { if(u[i] instanceof Object) [].splice.call(u,i,0,1); if(+u[i+1]==u[i+1]) [].splice.call(u,i+1,0,{}); this.memb.push(new AdvMath.Monomial(u[i],u[i+1]))} } } } AdvMath.Monomial.parse = function(a){ var k=new AdvMath.Monomial(); if(a[0]=="+") a = a.split("").slice(1).join(""); var h=a.split("*"); k.coef = isNaN(parseFloat(h[0]))?(h[0][0]=="-"?-1:1):parseFloat(h[0]); if(k.coef==-1) h[0] = h[0].split("").slice(1).join(""); else if(k.coef!==1) h.splice(0,1); h.forEach(function(i){var m = i.split("^"); k.memb[m[0]] = parseFloat(m[1])||1}) return k; } AdvMath.Monomial.prototype = { constructor: AdvMath.Monomial, mult: function(a){a=new AdvMath.Monomial(a);k=this.clone();k.coef*=a.coef;for(var g in a.memb)k.memb[g]=k.memb[g]?k.memb[g]+a.memb[g]:a.memb[g];return k}, membString:function(){a=""; for(var m in this.memb){for(var i =0;i<this.memb[m];i++){a+=m;}} return a;}, order:function(){return Math.max.apply(0,Object.keys(this.memb).map((function(i){return this.memb[i]}).bind(this)))}, pow:function(i){var k = this; for(var m=1;m<i;m++){k=k.mult(this);} return k;}, clone:function(){return new AdvMath.Monomial(this.coef,shallowCopy(this.memb));}, coefForm:function(i){ var g = (Object.keys(this.memb).every((function(i){return this[i]==0;}).bind(this.memb))?"1":""); return (this.coef>=0&&i?"+":"")+(this.coef==1?g:(this.coef==-1?"-"+g:parseFloat(this.coef.toFixed(3))))}, toString:function(i){a=this.coefForm(i);for(var b in this.memb)a+=(this.memb[b]==0?"":(((["+","-",""].indexOf(a)>-1)?"":"*")+b+(this.memb[b]==1?"":("^"+this.memb[b])))); return a}, toHTMLString:function(i){a=this.coefForm(i);for(var b in this.memb)a+=(this.memb[b]==0?"":(b+(this.memb[b]==1?"":this.memb[b].toString().sup())));return a}, eval: function(a){ k=this.clone(); for(var b in k.memb){ if(a.hasOwnProperty(b)){ k.coef*=Math.pow(a[b],k.memb[b]); k.memb[b] = 0; } } return k; } } AdvMath.Polynomial.parse = function(a){ var k = new AdvMath.Polynomial(); ("+"+a).match(/[\+\-]+[^\+\-]*/g).forEach(function(i){k.memb.push(AdvMath.Monomial.parse(i));}) return k; } AdvMath.Polynomial.prototype = { constructor: AdvMath.Polynomial, sort:function(){var k=this.undup(); k.memb=k.memb .sort(function(a,b){var m=a.membString(); var n=b.membString(); return m<n-m>n}); return k;}, add:function(a){a=new AdvMath.Polynomial(a);var k=this.clone(); for(var i=0;i<a.memb.length;i++){k.memb.push(a.memb[i])} return k;}, sub:function(a){a=new AdvMath.Polynomial(a);var k=this.clone(); var g = a.mult(new AdvMath.Polynomial(-1,{})); for(var i=0;i<a.memb.length;i++){k.memb.push(g.memb[i])} return k;}, pow:function(i){var k = this; for(var m=1;m<i;m++){k=k.mult(this);} return k;}, toString: function(){b="";for(var i=0;i<this.memb.length;i++)b+=this.memb[i].toString(i); return b}, toHTMLString: function(){b="";for(var i=0;i<this.memb.length;i++)b+=this.memb[i].toHTMLString(i); return b}, clone: function(){c=new AdvMath.Polynomial();for(var i=0;i<this.memb.length;i++)c.memb.push(this.memb[i].clone()); return c}, eval: function(a){var k = this.clone();for(var i = 0;i<this.memb.length;i++){k.memb[i] = k.memb[i].eval(a)}; return k}, mult: function(a){a=new AdvMath.Polynomial(a);var k = new AdvMath.Polynomial();var g = AdvMath.Cartez(this.memb,a.memb); for(var i=0; i<g.length;i++)k.memb.push(g[i][0].mult(g[i][1])); return k;}, undup:function(){var k = this.clone(); k.memb = k.memb.reduce(function(m,v){return m.every(function(i,k,p){if(Object.keys(i.memb).every(function(p){return (v.memb[p]||0)==(i.memb[p]||0)})){i.coef+=v.coef; if(i.coef==0){p.splice(k,1);} return false;} return true;})?m.concat(v):m; },[]).reverse(); return k; } } })()
mit
junyanz/iGAN
lib/activations.py
2424
import theano.tensor as T from lib.theano_utils import sharedX class Softmax(object): def __init__(self): pass def __call__(self, x): e_x = T.exp(x - x.max(axis=1).dimshuffle(0, 'x')) return e_x / e_x.sum(axis=1).dimshuffle(0, 'x') class ConvSoftmax(object): def __init__(self): pass def __call__(self, x): e_x = T.exp(x - x.max(axis=1, keepdims=True)) return e_x / e_x.sum(axis=1, keepdims=True) class Maxout(object): def __init__(self, n_pool=2): self.n_pool = n_pool def __call__(self, x): if x.ndim == 2: x = T.max([x[:, n::self.n_pool] for n in range(self.n_pool)], axis=0) elif x.ndim == 4: x = T.max([x[:, n::self.n_pool, :, :] for n in range(self.n_pool)], axis=0) else: raise NotImplementedError return x class Rectify(object): def __init__(self): pass def __call__(self, x): return (x + T.abs_(x)) / 2.0 class ClippedRectify(object): def __init__(self, clip=10.): self.clip = clip def __call__(self, x): return T.clip((x + T.abs_(x)) / 2.0, 0., self.clip) class LeakyRectify(object): def __init__(self, leak=0.2): self.leak = sharedX(leak) def __call__(self, x): f1 = 0.5 * (1 + self.leak) f2 = 0.5 * (1 - self.leak) return f1 * x + f2 * T.abs_(x) class Prelu(object): def __init__(self): pass def __call__(self, x, leak): if x.ndim == 4: leak = leak.dimshuffle('x', 0, 'x', 'x') f1 = 0.5 * (1 + leak) f2 = 0.5 * (1 - leak) return f1 * x + f2 * T.abs_(x) class Tanh(object): def __init__(self): pass def __call__(self, x): return T.tanh(x) class Sigmoid(object): def __init__(self): pass def __call__(self, x): return T.nnet.sigmoid(x) class Linear(object): def __init__(self): pass def __call__(self, x): return x class HardSigmoid(object): def __init__(self): pass def __call__(self, X): return T.clip(X + 0.5, 0., 1.) class TRec(object): def __init__(self, t=1): self.t = t def __call__(self, X): return X * (X > self.t) class HardTanh(object): def __init__(self): pass def __call__(self, X): return T.clip(X, -1., 1.)
mit
EvgenKostenko/go-harvest
authentication_test.go
1158
package harvest import ( "fmt" "net/http" "testing" ) func TestAcquireFail(t *testing.T) { setup() defer teardown() testMux.HandleFunc("/account/who_am_i", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "GET") testRequestURL(t, r, "/account/who_am_i") // Emulate error w.WriteHeader(http.StatusInternalServerError) }) res, err := testClient.Authentication.Acquire("foo", "bar") if err == nil { t.Error("Expected error, but no error given") } if res == true { t.Error("Expected error, but result was true") } if testClient.Authentication.Authenticated() != false { t.Error("Expected false, but result was true") } } func TestAcquire(t *testing.T) { setup() defer teardown() testAPIEndpoint := "/account/who_am_i" testMux.HandleFunc(testAPIEndpoint, func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "GET") testRequestURL(t, r, testAPIEndpoint) fmt.Fprint(w, "{}") }) res, err := testClient.Authentication.Acquire("user", "password") if err != nil { t.Error("Expected request, but error given", err) } if res != true { t.Error("Expected error, but result was true") } }
mit
7sDream/rikka
plugins/fs/fs.go
447
package fs import ( "flag" "github.com/7sDream/rikka/plugins" ) // plugin type type fsPlugin struct{} var ( l = plugins.SubLogger("[FS]") argFilesDir = flag.String("dir", "files", "Where files will be save when use fs plugin.") argFsDebugSleep = flag.Int("fsDebugSleep", 0, "Debug: sleep some ms before copy file to fs, used to test javascript ajax") imageDir string // Plugin is the main plugin instance. Plugin = fsPlugin{} )
mit
JeroenZegers/Nabu-MSSS
nabu/processing/__init__.py
233
'''@package processing This package contains all the functionality for data processing: - feature computation - feature storing and loading - file interpretation ''' from . import feature_computers, processors, tfreaders, tfwriters
mit
didclab/stork
stork/feather/Session.java
8716
package stork.feather; import java.io.*; import java.util.*; import stork.feather.util.*; /** * A {@code Session} is a stateful context for operating on {@code Resource}s. * {@code Session}s serve as a nexus for all of the stateful information * related to operating on a particular class of {@code Resource}s, which may * include network connections, user credentials, configuration options, and * other state necessary for operating on the {@code Resource}s it supports. * <p/> * {@code Resource}s handled by the {@code Session} may be <i>selected</i> * through the {@code Session}, in which case all operations on the {@code * Resource} will be performed in the context of the {@code Session}. Whether * or not a particular {@code Resource} is capable of being handled by the * {@code Session} depends on the URI associated with the {@code Resource} in * question. * </p> * {@code Session}s maintain state information regarding whether or not they * are ready for operation, and can be tested for equality based the URI and * user credentials used to instantiate them. This makes {@code Session}s * suitable for caching and reusing. A {@code Resource} selected on an * unconnected {@code Session} can, for instance, be reselected through an * equivalent {@code Session} that is still "warm", allowing the {@code * Session} to be reused and the initialization overhead to be avoided. * * @see Resource * * @param <S> The type of the subclass of this {@code Session}. This * unfortunate redundancy exists solely to circumvent weaknesses in Java's * typing system. * @param <R> The type of {@code Resource}s handled by this {@code Session}. */ public abstract class Session<S extends Session<S,R>, R extends Resource<S,R>> { /** The URI used to describe this {@code Session}. */ public final URI uri; /** The authentication factor used for this endpoint. */ public final Credential credential; // If we've already started initializing, this will be non-null. private volatile Bell initializeBell; // Rung on close. Avoid letting this leak out. private final Bell<S> onClose = new Bell<S>() { public void always() { Session.this.cleanup(); } }; /** * Create a {@code Session} with the given root URI. * * @param uri a {@link URI} representing the root of the {@code Session}. * @throws NullPointerException if {@code root} or {@code uri} is {@code * null}. */ protected Session(URI uri) { this(uri, null); } /** * Create a {@code Session} with the given root URI and {@code Credential}. * * @param uri a {@link URI} describing the {@code Session}. * @param credential a {@link Credential} used to authenticate with the * endpoint. This may be {@code null} if no additional authentication factors * are required. * @throws NullPointerException if {@code root} or {@code uri} is {@code * null}. */ protected Session(URI uri, Credential credential) { this.uri = uri; this.credential = credential; } /** * Select a {@code Resource} relative to the root {@code Resource} of this * {@code Session} given a {@code String} representation of a {@code Path}. * * @param path the {@code Path} to the {@code Resource} being selected. */ public final R select(String path) { return select(Path.create(path)); } /** * Select a {@code Resource} relative to the root {@code Resource} of this * {@code Session}. * * @param path the {@code Path} to the {@code Resource} being selected. */ public abstract R select(Path path); /** * Return the root {@code Resource} of this {@code Session}. * * @return The root {@code Resource} of this {@code Session}. */ public final R root() { return select(Path.ROOT); } /** * This is what actually gets called and returned when {@code * Resource.initialize()} is called. It enforces the guarantee that {@code * initialize()} will be called only once, and that the same {@code Bell} * will always be returned. It will also return a failed {@code Bell} if the * {@code Session} is closed. */ final synchronized Bell<S> mediatedInitialize() { if (initializeBell != null) { return initializeBell; } try { Bell ib = initialize(); initializeBell = (ib != null) ? ib : Bell.rungBell(); } catch (Exception e) { initializeBell = new Bell<S>(e); } return initializeBell.as(this); } /** * Prepare the {@code Session} to perform operations on its {@code * Resource}s. The exact nature of this preparation varies from * implementation to implementation, but generally includes establishing * network connections and performing authentication. Access to this method * is mediated such that the implementor may assume that this method will be * called at most once. * <p/> * Implementations may return {@code null} if {@code resource} does not * require any asynchronous initialization. This method may also throw an * {@code Exception} if it is certain that initialization cannot be performed * for some reason (perhaps invalid input). By default, this method returns * {@code null}. * * @return A {@code Bell} which will ring with this {@code Session} when it * is prepared to perform operations on {@code resource}, or {@code null} if * the {@code Resource} requires no initialization. * @throws Exception either via the returned {@code Bell} or from the method * itself if a problem occurs. Subclasses should only declare {@code throws * Exception} in the signature if it actually does so, and should omit it * otherwise. */ protected Bell<S> initialize() throws Exception { return null; } /** * Release any resources allocated during the initialization of this {@code * Session}. This method should close any connections and finalize any * ongoing transactions. */ protected void cleanup() { } protected void finalize() { close(); } /** * Close this {@code Session} and call {@code finalize()}. {@code * initialize()} will never be called after this has been called. * * @return This {@code Session}. */ public final synchronized S close() { return close(null); } /** * Close this {@code Session} due to the given {@code reason}. {@code * initialize()} will never be called after this has been called. * * @param reason a {@code Throwable} explaining why the {@code Session} was * closed. * @return This {@code Session}. */ public final synchronized S close(Throwable reason) { if (reason == null) reason = new IllegalStateException("Session is closed."); if (initializeBell != null) initializeBell.ring(reason); initializeBell = new Bell<S>(reason); onClose.ring((S) this); return (S) this; } /** * Promise to close this channel when {@code bell} rings. * * @param bell the {@code Bell} to promise the closing of this channel to. */ public final synchronized void closeWhen(Bell bell) { bell.new Promise() { public void done() { close(); } public void fail(Throwable t) { close(t); } }; } /** * Check if the closing procedure has begun. * * @return {@code true} if closing has begun; {@code false} otherwise. */ public final synchronized boolean isClosed() { return onClose.isDone(); } /** * Return a bell that will be rung with this {@code Session} when the {@code * Session} is closed. * * @return A {@code Bell} that will be rung when the {@code Session} is * closed. */ public final Bell<S> onClose() { return onClose.new Promise(); } /** * Register a {@code Bell} to be rung with this {@code Session} when the * {@code Session} is closed. This is slightly more memory-efficient than * promising on the {@code Bell} returned by {@link #onClose()}, as it * gets promised to an internal {@code Bell} directly. * * @param bell a {@code Bell} that will be rung when the {@code Session} is * closed. * @return Whatever value was passed in for {@code bell}. */ public final Bell<? super S> onClose(Bell<? super S> bell) { return onClose.promise(bell); } public String toString() { return uri.toString(); } public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Session)) return false; Session s = (Session) o; if (!uri.equals(s.uri)) return false; if (credential == null) return s.credential == null; return credential.equals(s.credential); } public int hashCode() { return 1 + 13*uri.hashCode() + (credential != null ? 17*credential.hashCode() : 0); } }
mit
robjohnson189/home-assistant
homeassistant/components/tts/voicerss.py
5028
""" Support for the voicerss speech service. For more details about this component, please refer to the documentation at https://home-assistant.io/components/tts/voicerss/ """ import asyncio import logging import aiohttp import async_timeout import voluptuous as vol from homeassistant.const import CONF_API_KEY from homeassistant.components.tts import Provider, PLATFORM_SCHEMA, CONF_LANG from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) VOICERSS_API_URL = "https://api.voicerss.org/" ERROR_MSG = [ b'Error description', b'The subscription is expired or requests count limitation is exceeded!', b'The request content length is too large!', b'The language does not support!', b'The language is not specified!', b'The text is not specified!', b'The API key is not available!', b'The API key is not specified!', b'The subscription does not support SSML!', ] SUPPORT_LANGUAGES = [ 'ca-es', 'zh-cn', 'zh-hk', 'zh-tw', 'da-dk', 'nl-nl', 'en-au', 'en-ca', 'en-gb', 'en-in', 'en-us', 'fi-fi', 'fr-ca', 'fr-fr', 'de-de', 'it-it', 'ja-jp', 'ko-kr', 'nb-no', 'pl-pl', 'pt-br', 'pt-pt', 'ru-ru', 'es-mx', 'es-es', 'sv-se', ] SUPPORT_CODECS = [ 'mp3', 'wav', 'aac', 'ogg', 'caf' ] SUPPORT_FORMATS = [ '8khz_8bit_mono', '8khz_8bit_stereo', '8khz_16bit_mono', '8khz_16bit_stereo', '11khz_8bit_mono', '11khz_8bit_stereo', '11khz_16bit_mono', '11khz_16bit_stereo', '12khz_8bit_mono', '12khz_8bit_stereo', '12khz_16bit_mono', '12khz_16bit_stereo', '16khz_8bit_mono', '16khz_8bit_stereo', '16khz_16bit_mono', '16khz_16bit_stereo', '22khz_8bit_mono', '22khz_8bit_stereo', '22khz_16bit_mono', '22khz_16bit_stereo', '24khz_8bit_mono', '24khz_8bit_stereo', '24khz_16bit_mono', '24khz_16bit_stereo', '32khz_8bit_mono', '32khz_8bit_stereo', '32khz_16bit_mono', '32khz_16bit_stereo', '44khz_8bit_mono', '44khz_8bit_stereo', '44khz_16bit_mono', '44khz_16bit_stereo', '48khz_8bit_mono', '48khz_8bit_stereo', '48khz_16bit_mono', '48khz_16bit_stereo', 'alaw_8khz_mono', 'alaw_8khz_stereo', 'alaw_11khz_mono', 'alaw_11khz_stereo', 'alaw_22khz_mono', 'alaw_22khz_stereo', 'alaw_44khz_mono', 'alaw_44khz_stereo', 'ulaw_8khz_mono', 'ulaw_8khz_stereo', 'ulaw_11khz_mono', 'ulaw_11khz_stereo', 'ulaw_22khz_mono', 'ulaw_22khz_stereo', 'ulaw_44khz_mono', 'ulaw_44khz_stereo', ] CONF_CODEC = 'codec' CONF_FORMAT = 'format' DEFAULT_LANG = 'en-us' DEFAULT_CODEC = 'mp3' DEFAULT_FORMAT = '8khz_8bit_mono' PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_API_KEY): cv.string, vol.Optional(CONF_LANG, default=DEFAULT_LANG): vol.In(SUPPORT_LANGUAGES), vol.Optional(CONF_CODEC, default=DEFAULT_CODEC): vol.In(SUPPORT_CODECS), vol.Optional(CONF_FORMAT, default=DEFAULT_FORMAT): vol.In(SUPPORT_FORMATS), }) @asyncio.coroutine def async_get_engine(hass, config): """Setup VoiceRSS speech component.""" return VoiceRSSProvider(hass, config) class VoiceRSSProvider(Provider): """VoiceRSS speech api provider.""" def __init__(self, hass, conf): """Init VoiceRSS TTS service.""" self.hass = hass self._extension = conf[CONF_CODEC] self._lang = conf[CONF_LANG] self._form_data = { 'key': conf[CONF_API_KEY], 'hl': conf[CONF_LANG], 'c': (conf[CONF_CODEC]).upper(), 'f': conf[CONF_FORMAT], } @property def default_language(self): """Default language.""" return self._lang @property def supported_languages(self): """List of supported languages.""" return SUPPORT_LANGUAGES @asyncio.coroutine def async_get_tts_audio(self, message, language): """Load TTS from voicerss.""" websession = async_get_clientsession(self.hass) form_data = self._form_data.copy() form_data['src'] = message form_data['hl'] = language request = None try: with async_timeout.timeout(10, loop=self.hass.loop): request = yield from websession.post( VOICERSS_API_URL, data=form_data ) if request.status != 200: _LOGGER.error("Error %d on load url %s.", request.status, request.url) return (None, None) data = yield from request.read() if data in ERROR_MSG: _LOGGER.error( "Error receive %s from voicerss.", str(data, 'utf-8')) return (None, None) except (asyncio.TimeoutError, aiohttp.errors.ClientError): _LOGGER.error("Timeout for voicerss api.") return (None, None) finally: if request is not None: yield from request.release() return (self._extension, data)
mit
baconcoins/ChickenBaconRanch
src/qt/locale/bitcoin_nl.ts
119471
<?xml version="1.0" ?><!DOCTYPE TS><TS language="nl" version="2.0"> <defaultcodec>UTF-8</defaultcodec> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About ChickenBaconRanch</source> <translation>Over ChickenBaconRanch</translation> </message> <message> <location line="+39"/> <source>&lt;b&gt;ChickenBaconRanch&lt;/b&gt; version</source> <translation>&lt;b&gt;ChickenBaconRanch&lt;/b&gt; versie</translation> </message> <message> <location line="+57"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source> <translation> Dit is experimentele software. Gedistribueerd onder de MIT/X11 software licentie, zie het bijgevoegde bestand COPYING of http://www.opensource.org/licenses/mit-license.php. Dit product bevat software ontwikkeld door het OpenSSL Project voor gebruik in de OpenSSL Toolkit (http://www.openssl.org/) en cryptografische software gemaakt door Eric Young (eay@cryptsoft.com) en UPnP software geschreven door Thomas Bernard.</translation> </message> <message> <location filename="../aboutdialog.cpp" line="+14"/> <source>Copyright</source> <translation>Auteursrecht</translation> </message> <message> <location line="+0"/> <source>The ChickenBaconRanch developers</source> <translation>De ChickenBaconRanch-ontwikkelaars</translation> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation>Adresboek</translation> </message> <message> <location line="+19"/> <source>Double-click to edit address or label</source> <translation>Dubbelklik om adres of label te wijzigen</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>Maak een nieuw adres aan</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Kopieer het huidig geselecteerde adres naar het klembord</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation>&amp;Nieuw Adres</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+63"/> <source>These are your ChickenBaconRanch addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation>Dit zijn uw ChickenBaconRanchadressen om betalingen mee te ontvangen. U kunt er voor kiezen om een uniek adres aan te maken voor elke afzender. Op deze manier kunt u bijhouden wie al aan u betaald heeft.</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>&amp;Copy Address</source> <translation>&amp;Kopiëer Adres</translation> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation>Toon &amp;QR-Code</translation> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a ChickenBaconRanch address</source> <translation>Onderteken een bericht om te bewijzen dat u een bepaald ChickenBaconRanchadres bezit</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>&amp;Onderteken Bericht</translation> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation>Verwijder het geselecteerde adres van de lijst</translation> </message> <message> <location line="+27"/> <source>Export the data in the current tab to a file</source> <translation>Exporteer de data in de huidige tab naar een bestand</translation> </message> <message> <location line="+3"/> <source>&amp;Export</source> <translation>&amp;Exporteer</translation> </message> <message> <location line="-44"/> <source>Verify a message to ensure it was signed with a specified ChickenBaconRanch address</source> <translation>Controleer een bericht om te verifiëren dat het gespecificeerde ChickenBaconRanchadres het bericht heeft ondertekend.</translation> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation>&amp;Verifiëer Bericht</translation> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>&amp;Verwijder</translation> </message> <message> <location filename="../addressbookpage.cpp" line="-5"/> <source>These are your ChickenBaconRanch addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation>Dit zijn uw ChickenBaconRanchadressen om betalingen mee te verzenden. Check altijd het bedrag en het ontvangende adres voordat u uw chickenbaconranchs verzendt.</translation> </message> <message> <location line="+13"/> <source>Copy &amp;Label</source> <translation>Kopiëer &amp;Label</translation> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation>&amp;Bewerk</translation> </message> <message> <location line="+1"/> <source>Send &amp;Coins</source> <translation>Verstuur &amp;Coins</translation> </message> <message> <location line="+260"/> <source>Export Address Book Data</source> <translation>Exporteer Gegevens van het Adresboek</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Kommagescheiden bestand (*.csv)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation>Fout bij exporteren</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Kon niet schrijven naar bestand %1.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>Label</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Adres</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(geen label)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation>Wachtwoorddialoogscherm</translation> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>Voer wachtwoord in</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>Nieuw wachtwoord</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>Herhaal wachtwoord</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+33"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>Vul een nieuw wachtwoord in voor uw portemonnee. &lt;br/&gt; Gebruik een wachtwoord van &lt;b&gt;10 of meer lukrake karakters&lt;/b&gt;, of &lt;b&gt; acht of meer woorden&lt;/b&gt; . </translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>Versleutel portemonnee</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Deze operatie vereist uw portemonneewachtwoord om de portemonnee te openen.</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>Open portemonnee</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Deze operatie vereist uw portemonneewachtwoord om de portemonnee te ontsleutelen</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>Ontsleutel portemonnee</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>Wijzig wachtwoord</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Vul uw oude en nieuwe portemonneewachtwoord in.</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>Bevestig versleuteling van de portemonnee</translation> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR LITECOINS&lt;/b&gt;!</source> <translation>Waarschuwing: Als u uw portemonnee versleutelt en uw wachtwoord vergeet, zult u &lt;b&gt;AL UW LITECOINS VERLIEZEN&lt;/b&gt;!</translation> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation>Weet u zeker dat u uw portemonnee wilt versleutelen?</translation> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation>BELANGRIJK: Elke eerder gemaakte backup van uw portemonneebestand dient u te vervangen door het nieuw gegenereerde, versleutelde portemonneebestand. Om veiligheidsredenen zullen eerdere backups van het niet-versleutelde portemonneebestand onbruikbaar worden zodra u uw nieuwe, versleutelde, portemonnee begint te gebruiken.</translation> </message> <message> <location line="+100"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation>Waarschuwing: De Caps-Lock-toets staat aan!</translation> </message> <message> <location line="-130"/> <location line="+58"/> <source>Wallet encrypted</source> <translation>Portemonnee versleuteld</translation> </message> <message> <location line="-56"/> <source>ChickenBaconRanch will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your chickenbaconranchs from being stolen by malware infecting your computer.</source> <translation>ChickenBaconRanch zal nu afsluiten om het versleutelingsproces te voltooien. Onthoud dat het versleutelen van uw portemonnee u niet volledig kan beschermen: Malware kan uw computer infecteren en uw chickenbaconranchs stelen.</translation> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+42"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>Portemonneeversleuteling mislukt</translation> </message> <message> <location line="-54"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Portemonneeversleuteling mislukt door een interne fout. Uw portemonnee is niet versleuteld.</translation> </message> <message> <location line="+7"/> <location line="+48"/> <source>The supplied passphrases do not match.</source> <translation>De opgegeven wachtwoorden komen niet overeen</translation> </message> <message> <location line="-37"/> <source>Wallet unlock failed</source> <translation>Portemonnee openen mislukt</translation> </message> <message> <location line="+1"/> <location line="+11"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>Het opgegeven wachtwoord voor de portemonnee-ontsleuteling is niet correct.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>Portemonnee-ontsleuteling mislukt</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation>Portemonneewachtwoord is met succes gewijzigd.</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+233"/> <source>Sign &amp;message...</source> <translation>&amp;Onderteken bericht...</translation> </message> <message> <location line="+280"/> <source>Synchronizing with network...</source> <translation>Synchroniseren met netwerk...</translation> </message> <message> <location line="-349"/> <source>&amp;Overview</source> <translation>&amp;Overzicht</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation>Toon algemeen overzicht van de portemonnee</translation> </message> <message> <location line="+20"/> <source>&amp;Transactions</source> <translation>&amp;Transacties</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>Blader door transactieverleden</translation> </message> <message> <location line="+7"/> <source>Edit the list of stored addresses and labels</source> <translation>Bewerk de lijst van opgeslagen adressen en labels</translation> </message> <message> <location line="-14"/> <source>Show the list of addresses for receiving payments</source> <translation>Toon lijst van adressen om betalingen mee te ontvangen</translation> </message> <message> <location line="+31"/> <source>E&amp;xit</source> <translation>&amp;Afsluiten</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>Programma afsluiten</translation> </message> <message> <location line="+4"/> <source>Show information about ChickenBaconRanch</source> <translation>Laat informatie zien over ChickenBaconRanch</translation> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>Over &amp;Qt</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>Toon informatie over Qt</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>O&amp;pties...</translation> </message> <message> <location line="+6"/> <source>&amp;Encrypt Wallet...</source> <translation>&amp;Versleutel Portemonnee...</translation> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation>&amp;Backup Portemonnee...</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>&amp;Wijzig Wachtwoord</translation> </message> <message> <location line="+285"/> <source>Importing blocks from disk...</source> <translation>Blokken aan het importeren vanaf harde schijf...</translation> </message> <message> <location line="+3"/> <source>Reindexing blocks on disk...</source> <translation>Bezig met herindexeren van blokken op harde schijf...</translation> </message> <message> <location line="-347"/> <source>Send coins to a ChickenBaconRanch address</source> <translation>Verstuur munten naar een ChickenBaconRanchadres</translation> </message> <message> <location line="+49"/> <source>Modify configuration options for ChickenBaconRanch</source> <translation>Wijzig instellingen van ChickenBaconRanch</translation> </message> <message> <location line="+9"/> <source>Backup wallet to another location</source> <translation>&amp;Backup portemonnee naar een andere locatie</translation> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>Wijzig het wachtwoord voor uw portemonneversleuteling</translation> </message> <message> <location line="+6"/> <source>&amp;Debug window</source> <translation>&amp;Debugscherm</translation> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation>Open debugging en diagnostische console</translation> </message> <message> <location line="-4"/> <source>&amp;Verify message...</source> <translation>&amp;Verifiëer bericht...</translation> </message> <message> <location line="-165"/> <location line="+530"/> <source>ChickenBaconRanch</source> <translation>ChickenBaconRanch</translation> </message> <message> <location line="-530"/> <source>Wallet</source> <translation>Portemonnee</translation> </message> <message> <location line="+101"/> <source>&amp;Send</source> <translation>&amp;Versturen</translation> </message> <message> <location line="+7"/> <source>&amp;Receive</source> <translation>&amp;Ontvangen</translation> </message> <message> <location line="+14"/> <source>&amp;Addresses</source> <translation>&amp;Adressen</translation> </message> <message> <location line="+22"/> <source>&amp;About ChickenBaconRanch</source> <translation>&amp;Over ChickenBaconRanch</translation> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation>&amp;Toon / Verberg</translation> </message> <message> <location line="+1"/> <source>Show or hide the main Window</source> <translation>Toon of verberg het hoofdvenster</translation> </message> <message> <location line="+3"/> <source>Encrypt the private keys that belong to your wallet</source> <translation>Versleutel de geheime sleutels die bij uw portemonnee horen</translation> </message> <message> <location line="+7"/> <source>Sign messages with your ChickenBaconRanch addresses to prove you own them</source> <translation>Onderteken berichten met uw ChickenBaconRanchadressen om te bewijzen dat u deze adressen bezit</translation> </message> <message> <location line="+2"/> <source>Verify messages to ensure they were signed with specified ChickenBaconRanch addresses</source> <translation>Verifiëer handtekeningen om zeker te zijn dat de berichten zijn ondertekend met de gespecificeerde ChickenBaconRanchadressen</translation> </message> <message> <location line="+28"/> <source>&amp;File</source> <translation>&amp;Bestand</translation> </message> <message> <location line="+7"/> <source>&amp;Settings</source> <translation>&amp;Instellingen</translation> </message> <message> <location line="+6"/> <source>&amp;Help</source> <translation>&amp;Hulp</translation> </message> <message> <location line="+9"/> <source>Tabs toolbar</source> <translation>Tab-werkbalk</translation> </message> <message> <location line="+17"/> <location line="+10"/> <source>[testnet]</source> <translation>[testnetwerk]</translation> </message> <message> <location line="+47"/> <source>ChickenBaconRanch client</source> <translation>ChickenBaconRanch client</translation> </message> <message numerus="yes"> <location line="+141"/> <source>%n active connection(s) to ChickenBaconRanch network</source> <translation><numerusform>%n actieve connectie naar ChickenBaconRanchnetwerk</numerusform><numerusform>%n actieve connecties naar ChickenBaconRanchnetwerk</numerusform></translation> </message> <message> <location line="+22"/> <source>No block source available...</source> <translation>Geen bron van blokken beschikbaar...</translation> </message> <message> <location line="+12"/> <source>Processed %1 of %2 (estimated) blocks of transaction history.</source> <translation>%1 van %2 (geschat) blokken van de transactiehistorie verwerkt.</translation> </message> <message> <location line="+4"/> <source>Processed %1 blocks of transaction history.</source> <translation>%1 blokken van transactiehistorie verwerkt.</translation> </message> <message numerus="yes"> <location line="+20"/> <source>%n hour(s)</source> <translation><numerusform>%n uur</numerusform><numerusform>%n uur</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation><numerusform>%n dag</numerusform><numerusform>%n dagen</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n week(s)</source> <translation><numerusform>%n week</numerusform><numerusform>%n weken</numerusform></translation> </message> <message> <location line="+4"/> <source>%1 behind</source> <translation>%1 achter</translation> </message> <message> <location line="+14"/> <source>Last received block was generated %1 ago.</source> <translation>Laatst ontvangen blok was %1 geleden gegenereerd.</translation> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation>Transacties na dit moment zullen nu nog niet zichtbaar zijn.</translation> </message> <message> <location line="+22"/> <source>Error</source> <translation>Fout</translation> </message> <message> <location line="+3"/> <source>Warning</source> <translation>Waarschuwing</translation> </message> <message> <location line="+3"/> <source>Information</source> <translation>Informatie</translation> </message> <message> <location line="+70"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation>Deze transactie overschrijdt de groottelimiet. Om de transactie alsnog te versturen kunt u transactiekosten betalen van %1. Deze transactiekosten gaan naar de nodes die uw transactie verwerken en het helpt op deze manier bij het ondersteunen van het ChickenBaconRanchnetwerk. Wilt u de transactiekosten betalen?</translation> </message> <message> <location line="-140"/> <source>Up to date</source> <translation>Bijgewerkt</translation> </message> <message> <location line="+31"/> <source>Catching up...</source> <translation>Aan het bijwerken...</translation> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation>Bevestig transactiekosten</translation> </message> <message> <location line="+8"/> <source>Sent transaction</source> <translation>Verzonden transactie</translation> </message> <message> <location line="+0"/> <source>Incoming transaction</source> <translation>Binnenkomende transactie</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>Datum: %1 Bedrag: %2 Type: %3 Adres: %4 </translation> </message> <message> <location line="+33"/> <location line="+23"/> <source>URI handling</source> <translation>URI-behandeling</translation> </message> <message> <location line="-23"/> <location line="+23"/> <source>URI can not be parsed! This can be caused by an invalid ChickenBaconRanch address or malformed URI parameters.</source> <translation>URI kan niet worden geïnterpreteerd. Dit kan komen door een ongeldig ChickenBaconRanchadres of misvormde URI-parameters.</translation> </message> <message> <location line="+17"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>Portemonnee is &lt;b&gt;versleuteld&lt;/b&gt; en momenteel &lt;b&gt;geopend&lt;/b&gt;</translation> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>Portemonnee is &lt;b&gt;versleuteld&lt;/b&gt; en momenteel &lt;b&gt;gesloten&lt;/b&gt;</translation> </message> <message> <location filename="../bitcoin.cpp" line="+111"/> <source>A fatal error occurred. ChickenBaconRanch can no longer continue safely and will quit.</source> <translation>Er is een fatale fout opgetreden. ChickenBaconRanch kan niet meer veilig doorgaan en zal nu afgesloten worden.</translation> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+104"/> <source>Network Alert</source> <translation>Netwerkwaarschuwing</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>Bewerk Adres</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>&amp;Label</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation>Het label dat geassocieerd is met dit adres</translation> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>&amp;Adres</translation> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation>Het adres dat geassocieerd is met deze inschrijving in het adresboek. Dit kan alleen worden veranderd voor zend-adressen.</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation>Nieuw ontvangstadres</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>Nieuw adres om naar te verzenden</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>Bewerk ontvangstadres</translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>Bewerk adres om naar te verzenden</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>Het opgegeven adres &quot;%1&quot; bestaat al in uw adresboek.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid ChickenBaconRanch address.</source> <translation>Het opgegeven adres &quot;%1&quot; is een ongeldig ChickenBaconRanchadres</translation> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>Kon de portemonnee niet openen.</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>Genereren nieuwe sleutel mislukt.</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+424"/> <location line="+12"/> <source>ChickenBaconRanch-Qt</source> <translation>ChickenBaconRanch-Qt</translation> </message> <message> <location line="-12"/> <source>version</source> <translation>versie</translation> </message> <message> <location line="+2"/> <source>Usage:</source> <translation>Gebruik:</translation> </message> <message> <location line="+1"/> <source>command-line options</source> <translation>commandoregel-opties</translation> </message> <message> <location line="+4"/> <source>UI options</source> <translation>gebruikersinterfaceopties</translation> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation>Stel taal in, bijvoorbeeld &apos;&apos;de_DE&quot; (standaard: systeeminstellingen)</translation> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation>Geminimaliseerd starten</translation> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation>Laat laadscherm zien bij het opstarten. (standaard: 1)</translation> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>Opties</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation>&amp;Algemeen</translation> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source> <translation>Optionele transactiekosten per kB. Transactiekosten helpen ervoor te zorgen dat uw transacties snel verwerkt worden. De meeste transacties zijn 1kB.</translation> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation>Betaal &amp;transactiekosten</translation> </message> <message> <location line="+31"/> <source>Automatically start ChickenBaconRanch after logging in to the system.</source> <translation>Start ChickenBaconRanch automatisch na inloggen in het systeem</translation> </message> <message> <location line="+3"/> <source>&amp;Start ChickenBaconRanch on system login</source> <translation>Start &amp;ChickenBaconRanch bij het inloggen in het systeem</translation> </message> <message> <location line="+35"/> <source>Reset all client options to default.</source> <translation>Reset alle clientopties naar de standaardinstellingen.</translation> </message> <message> <location line="+3"/> <source>&amp;Reset Options</source> <translation>&amp;Reset Opties</translation> </message> <message> <location line="+13"/> <source>&amp;Network</source> <translation>&amp;Netwerk</translation> </message> <message> <location line="+6"/> <source>Automatically open the ChickenBaconRanch client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation>Open de ChickenBaconRanch-poort automatisch op de router. Dit werkt alleen als de router UPnP ondersteunt en het aanstaat.</translation> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation>Portmapping via &amp;UPnP</translation> </message> <message> <location line="+7"/> <source>Connect to the ChickenBaconRanch network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation>Verbind met het ChickenBaconRanch-netwerk via een SOCKS-proxy (bijv. wanneer u via Tor wilt verbinden)</translation> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation>&amp;Verbind via een SOCKS-proxy</translation> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation>Proxy &amp;IP:</translation> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation>IP-adres van de proxy (bijv. 127.0.0.1)</translation> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation>&amp;Poort:</translation> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation>Poort van de proxy (bijv. 9050)</translation> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation>SOCKS-&amp;Versie:</translation> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation>SOCKS-versie van de proxy (bijv. 5)</translation> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation>&amp;Scherm</translation> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation>Laat alleen een systeemvak-icoon zien wanneer het venster geminimaliseerd is</translation> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>&amp;Minimaliseer naar het systeemvak in plaats van de taakbalk</translation> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation>Minimaliseer het venster in de plaats van de applicatie af te sluiten als het venster gesloten wordt. Wanneer deze optie aan staan, kan de applicatie alleen worden afgesloten door Afsluiten te kiezen in het menu.</translation> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation>Minimaliseer bij sluiten van het &amp;venster</translation> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation>&amp;Interface</translation> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation>Taal &amp;Gebruikersinterface:</translation> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting ChickenBaconRanch.</source> <translation>De taal van de gebruikersinterface kan hier ingesteld worden. Deze instelling zal pas van kracht worden nadat ChickenBaconRanch herstart wordt.</translation> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation>&amp;Eenheid om bedrag in te tonen:</translation> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>Kies de standaard onderverdelingseenheid om weer te geven in uw programma, en voor het versturen van munten</translation> </message> <message> <location line="+9"/> <source>Whether to show ChickenBaconRanch addresses in the transaction list or not.</source> <translation>Of ChickenBaconRanchadressen getoond worden in de transactielijst</translation> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation>Toon a&amp;dressen in de transactielijst</translation> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation>&amp;OK</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>Ann&amp;uleren</translation> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation>&amp;Toepassen</translation> </message> <message> <location filename="../optionsdialog.cpp" line="+53"/> <source>default</source> <translation>standaard</translation> </message> <message> <location line="+130"/> <source>Confirm options reset</source> <translation>Bevestig reset opties</translation> </message> <message> <location line="+1"/> <source>Some settings may require a client restart to take effect.</source> <translation>Sommige instellingen vereisen het herstarten van de client voordat ze in werking treden.</translation> </message> <message> <location line="+0"/> <source>Do you want to proceed?</source> <translation> Wilt u doorgaan?</translation> </message> <message> <location line="+42"/> <location line="+9"/> <source>Warning</source> <translation>Waarschuwing</translation> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting ChickenBaconRanch.</source> <translation>Deze instelling zal pas van kracht worden na het herstarten van ChickenBaconRanch.</translation> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation>Het opgegeven proxyadres is ongeldig.</translation> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>Vorm</translation> </message> <message> <location line="+50"/> <location line="+166"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the ChickenBaconRanch network after a connection is established, but this process has not completed yet.</source> <translation>De weergegeven informatie kan verouderd zijn. Uw portemonnee synchroniseert automaticsh met het ChickenBaconRanchnetwerk nadat een verbinding is gelegd, maar dit proces is nog niet voltooid.</translation> </message> <message> <location line="-124"/> <source>Balance:</source> <translation>Saldo:</translation> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation>Onbevestigd:</translation> </message> <message> <location line="-78"/> <source>Wallet</source> <translation>Portemonnee</translation> </message> <message> <location line="+107"/> <source>Immature:</source> <translation>Immatuur:</translation> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation>Gedolven saldo dat nog niet tot wasdom is gekomen</translation> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Recente transacties&lt;/b&gt;</translation> </message> <message> <location line="-101"/> <source>Your current balance</source> <translation>Uw huidige saldo</translation> </message> <message> <location line="+29"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation>Totaal van de transacties die nog moeten worden bevestigd en nog niet zijn meegeteld in uw huidige saldo </translation> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation>niet gesynchroniseerd</translation> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+107"/> <source>Cannot start chickenbaconranch: click-to-pay handler</source> <translation>Kan chickenbaconranch niet starten: click-to-pay handler</translation> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation>QR-codescherm</translation> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation>Vraag betaling aan</translation> </message> <message> <location line="+56"/> <source>Amount:</source> <translation>Bedrag:</translation> </message> <message> <location line="-44"/> <source>Label:</source> <translation>Label:</translation> </message> <message> <location line="+19"/> <source>Message:</source> <translation>Bericht:</translation> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation>&amp;Opslaan Als...</translation> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation>Fout tijdens encoderen URI in QR-code</translation> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation>Het opgegeven bedrag is ongeldig, controleer het s.v.p.</translation> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation>Resulterende URI te lang, probeer de tekst korter te maken voor het label/bericht.</translation> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation>Sla QR-code op</translation> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation>PNG-Afbeeldingen (*.png)</translation> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation>Clientnaam</translation> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+339"/> <source>N/A</source> <translation>N.v.t.</translation> </message> <message> <location line="-217"/> <source>Client version</source> <translation>Clientversie</translation> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation>&amp;Informatie</translation> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation>Gebruikt OpenSSL versie</translation> </message> <message> <location line="+49"/> <source>Startup time</source> <translation>Opstarttijd</translation> </message> <message> <location line="+29"/> <source>Network</source> <translation>Netwerk</translation> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation>Aantal connecties</translation> </message> <message> <location line="+23"/> <source>On testnet</source> <translation>Op testnet</translation> </message> <message> <location line="+23"/> <source>Block chain</source> <translation>Blokketen</translation> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation>Huidig aantal blokken</translation> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation>Geschat totaal aantal blokken</translation> </message> <message> <location line="+23"/> <source>Last block time</source> <translation>Tijd laatste blok</translation> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation>&amp;Open</translation> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation>Commandoregel-opties</translation> </message> <message> <location line="+7"/> <source>Show the ChickenBaconRanch-Qt help message to get a list with possible ChickenBaconRanch command-line options.</source> <translation>Toon het ChickenBaconRanchQt-hulpbericht voor een lijst met mogelijke ChickenBaconRanch commandoregel-opties.</translation> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation>&amp;Toon</translation> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation>&amp;Console</translation> </message> <message> <location line="-260"/> <source>Build date</source> <translation>Bouwdatum</translation> </message> <message> <location line="-104"/> <source>ChickenBaconRanch - Debug window</source> <translation>ChickenBaconRanch-debugscherm</translation> </message> <message> <location line="+25"/> <source>ChickenBaconRanch Core</source> <translation>ChickenBaconRanch Kern</translation> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation>Debug-logbestand</translation> </message> <message> <location line="+7"/> <source>Open the ChickenBaconRanch debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation>Open het ChickenBaconRanchdebug-logbestand van de huidige datamap. Dit kan een aantal seconden duren voor grote logbestanden.</translation> </message> <message> <location line="+102"/> <source>Clear console</source> <translation>Maak console leeg</translation> </message> <message> <location filename="../rpcconsole.cpp" line="-30"/> <source>Welcome to the ChickenBaconRanch RPC console.</source> <translation>Welkom bij de ChickenBaconRanch RPC-console.</translation> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation>Gebruik de pijltjestoetsen om door de geschiedenis te navigeren, en &lt;b&gt;Ctrl-L&lt;/b&gt; om het scherm leeg te maken.</translation> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation>Typ &lt;b&gt;help&lt;/b&gt; voor een overzicht van de beschikbare commando&apos;s.</translation> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+124"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation>Verstuur munten</translation> </message> <message> <location line="+50"/> <source>Send to multiple recipients at once</source> <translation>Verstuur aan verschillende ontvangers ineens</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation>Voeg &amp;Ontvanger Toe</translation> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation>Verwijder alle transactievelden</translation> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation>Verwijder &amp;Alles</translation> </message> <message> <location line="+22"/> <source>Balance:</source> <translation>Saldo:</translation> </message> <message> <location line="+10"/> <source>123.456 BTC</source> <translation>123.456 BTC</translation> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation>Bevestig de verstuuractie</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>&amp;Verstuur</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-59"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation>&lt;b&gt;%1&lt;/b&gt; aan %2 (%3)</translation> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation>Bevestig versturen munten</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation>Weet u zeker dat u %1 wil versturen?</translation> </message> <message> <location line="+0"/> <source> and </source> <translation> en </translation> </message> <message> <location line="+23"/> <source>The recipient address is not valid, please recheck.</source> <translation>Het ontvangstadres is niet geldig, controleer uw invoer.</translation> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>Het ingevoerde bedrag moet groter zijn dan 0.</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation>Bedrag is hoger dan uw huidige saldo</translation> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>Totaal overschrijdt uw huidige saldo wanneer de %1 transactiekosten worden meegerekend</translation> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation>Dubbel adres gevonden, u kunt slechts eenmaal naar een bepaald adres verzenden per verstuurtransactie</translation> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed!</source> <translation>Fout: Aanmaak transactie mislukt!</translation> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation>Fout: De transactie was afgewezen. Dit kan gebeuren als u eerder uitgegeven munten opnieuw wilt versturen, zoals wanneer u een kopie van uw portemonneebestand (wallet.dat) heeft gebruikt en in de kopie deze munten zijn uitgegeven, maar in de huidige portemonnee deze nog niet als zodanig zijn gemarkeerd.</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation>Vorm</translation> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>Bedra&amp;g:</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>Betaal &amp;Aan:</translation> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Het adres waaraan u wilt betalen (bijv. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="+60"/> <location filename="../sendcoinsentry.cpp" line="+26"/> <source>Enter a label for this address to add it to your address book</source> <translation>Vul een label in voor dit adres om het toe te voegen aan uw adresboek</translation> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation>&amp;Label:</translation> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation>Kies adres uit adresboek</translation> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation>Plak adres vanuit klembord</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation>Verwijder deze ontvanger</translation> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a ChickenBaconRanch address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Vul een ChickenBaconRanchadres in (bijv. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation>Handtekeningen - Onderteken een bericht / Verifiëer een handtekening</translation> </message> <message> <location line="+13"/> <source>&amp;Sign Message</source> <translation>O&amp;nderteken Bericht</translation> </message> <message> <location line="+6"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation>U kunt berichten ondertekenen met een van uw adressen om te bewijzen dat u dit adres bezit. Pas op dat u geen onduidelijke dingen ondertekent, want phishingaanvallen zouden u kunnen misleiden om zo uw identiteit te stelen. Onderteken alleen berichten waarmee u het volledig eens bent.</translation> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Het adres om het bericht mee te ondertekenen (Vb.: Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2).</translation> </message> <message> <location line="+10"/> <location line="+213"/> <source>Choose an address from the address book</source> <translation>Kies een adres uit het adresboek</translation> </message> <message> <location line="-203"/> <location line="+213"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="-203"/> <source>Paste address from clipboard</source> <translation>Plak adres vanuit klembord</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation>Typ hier het bericht dat u wilt ondertekenen</translation> </message> <message> <location line="+7"/> <source>Signature</source> <translation>Handtekening</translation> </message> <message> <location line="+27"/> <source>Copy the current signature to the system clipboard</source> <translation>Kopieer de huidige handtekening naar het systeemklembord</translation> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this ChickenBaconRanch address</source> <translation>Onderteken een bericht om te bewijzen dat u een bepaald ChickenBaconRanchadres bezit</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>Onderteken &amp;Bericht</translation> </message> <message> <location line="+14"/> <source>Reset all sign message fields</source> <translation>Verwijder alles in de invulvelden</translation> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation>Verwijder &amp;Alles</translation> </message> <message> <location line="-87"/> <source>&amp;Verify Message</source> <translation>&amp;Verifiëer Bericht</translation> </message> <message> <location line="+6"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation>Voer het ondertekenende adres, bericht en handtekening hieronder in (let erop dat u nieuwe regels, spaties en tabs juist overneemt) om de handtekening te verifiëren. Let erop dat u niet meer uit het bericht interpreteert dan er daadwerkelijk staat, om te voorkomen dat u wordt misleid in een man-in-the-middle-aanval.</translation> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Het adres waarmee bet bericht was ondertekend (Vb.: Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2).</translation> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified ChickenBaconRanch address</source> <translation>Controleer een bericht om te verifiëren dat het gespecificeerde ChickenBaconRanchadres het bericht heeft ondertekend.</translation> </message> <message> <location line="+3"/> <source>Verify &amp;Message</source> <translation>Verifiëer &amp;Bericht</translation> </message> <message> <location line="+14"/> <source>Reset all verify message fields</source> <translation>Verwijder alles in de invulvelden</translation> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a ChickenBaconRanch address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Vul een ChickenBaconRanchadres in (bijv. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation>Klik &quot;Onderteken Bericht&quot; om de handtekening te genereren</translation> </message> <message> <location line="+3"/> <source>Enter ChickenBaconRanch signature</source> <translation>Voer ChickenBaconRanch-handtekening in</translation> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation>Het opgegeven adres is ongeldig.</translation> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation>Controleer s.v.p. het adres en probeer het opnieuw.</translation> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation>Het opgegeven adres verwijst niet naar een sleutel.</translation> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation>Portemonnee-ontsleuteling is geannuleerd</translation> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation>Geheime sleutel voor het ingevoerde adres is niet beschikbaar.</translation> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation>Ondertekenen van het bericht is mislukt.</translation> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation>Bericht ondertekend.</translation> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation>De handtekening kon niet worden gedecodeerd.</translation> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation>Controleer s.v.p. de handtekening en probeer het opnieuw.</translation> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation>De handtekening hoort niet bij het bericht.</translation> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation>Berichtverificatie mislukt.</translation> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation>Bericht correct geverifiëerd.</translation> </message> </context> <context> <name>SplashScreen</name> <message> <location filename="../splashscreen.cpp" line="+22"/> <source>The ChickenBaconRanch developers</source> <translation>De ChickenBaconRanch-ontwikkelaars</translation> </message> <message> <location line="+1"/> <source>[testnet]</source> <translation>[testnetwerk]</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+20"/> <source>Open until %1</source> <translation>Openen totdat %1</translation> </message> <message> <location line="+6"/> <source>%1/offline</source> <translation>%1/offline</translation> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/onbevestigd</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 bevestigingen</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation>Status</translation> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation><numerusform>, uitgezonden naar %n node</numerusform><numerusform>, uitgezonden naar %n nodes</numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>Datum</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation>Bron</translation> </message> <message> <location line="+0"/> <source>Generated</source> <translation>Gegenereerd</translation> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation>Van</translation> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation>Aan</translation> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation>eigen adres</translation> </message> <message> <location line="-2"/> <source>label</source> <translation>label</translation> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation>Credit</translation> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation><numerusform>komt tot wasdom na %n nieuw blok</numerusform><numerusform>komt tot wasdom na %n nieuwe blokken</numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation>niet geaccepteerd</translation> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation>Debet</translation> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation>Transactiekosten</translation> </message> <message> <location line="+16"/> <source>Net amount</source> <translation>Netto bedrag</translation> </message> <message> <location line="+6"/> <source>Message</source> <translation>Bericht</translation> </message> <message> <location line="+2"/> <source>Comment</source> <translation>Opmerking</translation> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation>Transactie-ID:</translation> </message> <message> <location line="+3"/> <source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation>Gegeneerde munten moeten 120 blokken wachten voordat ze tot wasdom komen en kunnen worden uitgegeven. Uw net gegenereerde blok is uitgezonden aan het netwerk om te worden toegevoegd aan de blokketen. Als het niet wordt geaccepteerd in de keten, zal het blok als &quot;niet geaccepteerd&quot; worden aangemerkt en kan het niet worden uitgegeven. Dit kan soms gebeuren als een andere node net iets sneller een blok heeft gegenereerd; een paar seconden voor het uwe.</translation> </message> <message> <location line="+7"/> <source>Debug information</source> <translation>Debug-informatie</translation> </message> <message> <location line="+8"/> <source>Transaction</source> <translation>Transactie</translation> </message> <message> <location line="+3"/> <source>Inputs</source> <translation>Inputs</translation> </message> <message> <location line="+23"/> <source>Amount</source> <translation>Bedrag</translation> </message> <message> <location line="+1"/> <source>true</source> <translation>waar</translation> </message> <message> <location line="+0"/> <source>false</source> <translation>onwaar</translation> </message> <message> <location line="-209"/> <source>, has not been successfully broadcast yet</source> <translation>, is nog niet met succes uitgezonden</translation> </message> <message numerus="yes"> <location line="-35"/> <source>Open for %n more block(s)</source> <translation><numerusform>Open voor nog %n blok</numerusform><numerusform>Open voor nog %n blokken</numerusform></translation> </message> <message> <location line="+70"/> <source>unknown</source> <translation>onbekend</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>Transactiedetails</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>Dit venster laat een uitgebreide beschrijving van de transactie zien</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+225"/> <source>Date</source> <translation>Datum</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>Type</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Adres</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>Bedrag</translation> </message> <message numerus="yes"> <location line="+57"/> <source>Open for %n more block(s)</source> <translation><numerusform>Open voor nog %n blok</numerusform><numerusform>Open voor nog %n blokken</numerusform></translation> </message> <message> <location line="+3"/> <source>Open until %1</source> <translation>Open tot %1</translation> </message> <message> <location line="+3"/> <source>Offline (%1 confirmations)</source> <translation>Niet verbonden (%1 bevestigingen)</translation> </message> <message> <location line="+3"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation>Onbevestigd (%1 van %2 bevestigd)</translation> </message> <message> <location line="+3"/> <source>Confirmed (%1 confirmations)</source> <translation>Bevestigd (%1 bevestigingen)</translation> </message> <message numerus="yes"> <location line="+8"/> <source>Mined balance will be available when it matures in %n more block(s)</source> <translation><numerusform>Gedolven saldo zal beschikbaar komen als het tot wasdom komt na %n blok</numerusform><numerusform>Gedolven saldo zal beschikbaar komen als het tot wasdom komt na %n blokken</numerusform></translation> </message> <message> <location line="+5"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>Dit blok is niet ontvangen bij andere nodes en zal waarschijnlijk niet worden geaccepteerd!</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>Gegenereerd maar niet geaccepteerd</translation> </message> <message> <location line="+43"/> <source>Received with</source> <translation>Ontvangen met</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>Ontvangen van</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>Verzonden aan</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>Betaling aan uzelf</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>Gedolven</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>(nvt)</translation> </message> <message> <location line="+199"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Transactiestatus. Houd de muiscursor boven dit veld om het aantal bevestigingen te laten zien.</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>Datum en tijd waarop deze transactie is ontvangen.</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>Type transactie.</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>Ontvangend adres van transactie.</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>Bedrag verwijderd van of toegevoegd aan saldo</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+52"/> <location line="+16"/> <source>All</source> <translation>Alles</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>Vandaag</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>Deze week</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>Deze maand</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>Vorige maand</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>Dit jaar</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>Bereik...</translation> </message> <message> <location line="+11"/> <source>Received with</source> <translation>Ontvangen met</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>Verzonden aan</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>Aan uzelf</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>Gedolven</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>Anders</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>Vul adres of label in om te zoeken</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>Min. bedrag</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>Kopieer adres</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Kopieer label</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Kopieer bedrag</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation>Kopieer transactie-ID</translation> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>Bewerk label</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation>Toon transactiedetails</translation> </message> <message> <location line="+139"/> <source>Export Transaction Data</source> <translation>Exporteer transactiegegevens</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Kommagescheiden bestand (*.csv)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>Bevestigd</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>Datum</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>Type</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>Label</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>Adres</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>Bedrag</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>ID</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation>Fout bij exporteren</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Kon niet schrijven naar bestand %1.</translation> </message> <message> <location line="+100"/> <source>Range:</source> <translation>Bereik:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>naar</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+193"/> <source>Send Coins</source> <translation>Verstuur munten</translation> </message> </context> <context> <name>WalletView</name> <message> <location filename="../walletview.cpp" line="+42"/> <source>&amp;Export</source> <translation>&amp;Exporteer</translation> </message> <message> <location line="+1"/> <source>Export the data in the current tab to a file</source> <translation>Exporteer de data in de huidige tab naar een bestand</translation> </message> <message> <location line="+193"/> <source>Backup Wallet</source> <translation>Portomonnee backuppen</translation> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation>Portemonnee-data (*.dat)</translation> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation>Backup Mislukt</translation> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation>Er is een fout opgetreden bij het wegschrijven van de portemonnee-data naar de nieuwe locatie.</translation> </message> <message> <location line="+4"/> <source>Backup Successful</source> <translation>Backup Succesvol</translation> </message> <message> <location line="+0"/> <source>The wallet data was successfully saved to the new location.</source> <translation>De portemonneedata is succesvol opgeslagen op de nieuwe locatie.</translation> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+94"/> <source>ChickenBaconRanch version</source> <translation>ChickenBaconRanchversie</translation> </message> <message> <location line="+102"/> <source>Usage:</source> <translation>Gebruik:</translation> </message> <message> <location line="-29"/> <source>Send command to -server or chickenbaconranchd</source> <translation>Stuur commando naar -server of chickenbaconranchd</translation> </message> <message> <location line="-23"/> <source>List commands</source> <translation>Lijst van commando&apos;s</translation> </message> <message> <location line="-12"/> <source>Get help for a command</source> <translation>Toon hulp voor een commando</translation> </message> <message> <location line="+24"/> <source>Options:</source> <translation>Opties:</translation> </message> <message> <location line="+24"/> <source>Specify configuration file (default: chickenbaconranch.conf)</source> <translation>Specificeer configuratiebestand (standaard: chickenbaconranch.conf) </translation> </message> <message> <location line="+3"/> <source>Specify pid file (default: chickenbaconranchd.pid)</source> <translation>Specificeer pid-bestand (standaard: chickenbaconranchd.pid) </translation> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>Stel datamap in</translation> </message> <message> <location line="-9"/> <source>Set database cache size in megabytes (default: 25)</source> <translation>Stel databankcachegrootte in in megabytes (standaard: 25)</translation> </message> <message> <location line="-28"/> <source>Listen for connections on &lt;port&gt; (default: 8011 or testnet: 8012)</source> <translation>Luister voor verbindingen op &lt;poort&gt; (standaard: 8011 of testnet: 8012)</translation> </message> <message> <location line="+5"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>Onderhoud maximaal &lt;n&gt; verbindingen naar peers (standaard: 125)</translation> </message> <message> <location line="-48"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation>Verbind naar een node om adressen van anderen op te halen, en verbreek vervolgens de verbinding</translation> </message> <message> <location line="+82"/> <source>Specify your own public address</source> <translation>Specificeer uw eigen publieke adres</translation> </message> <message> <location line="+3"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>Drempel om verbinding te verbreken naar zich misdragende peers (standaard: 100)</translation> </message> <message> <location line="-134"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>Aantal seconden dat zich misdragende peers niet opnieuw mogen verbinden (standaard: 86400)</translation> </message> <message> <location line="-29"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation>Er is een fout opgetreden tijdens het instellen van de inkomende RPC-poort %u op IPv4: %s</translation> </message> <message> <location line="+27"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 8013 or testnet: 8014)</source> <translation>Wacht op JSON-RPC-connecties op poort &lt;port&gt; (standaard: 8013 of testnet: 8014)</translation> </message> <message> <location line="+37"/> <source>Accept command line and JSON-RPC commands</source> <translation>Aanvaard commandoregel- en JSON-RPC-commando&apos;s</translation> </message> <message> <location line="+76"/> <source>Run in the background as a daemon and accept commands</source> <translation>Draai in de achtergrond als daemon en aanvaard commando&apos;s</translation> </message> <message> <location line="+37"/> <source>Use the test network</source> <translation>Gebruik het testnetwerk</translation> </message> <message> <location line="-112"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation>Accepteer verbindingen van buitenaf (standaard: 1 als geen -proxy of -connect is opgegeven)</translation> </message> <message> <location line="-80"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=chickenbaconranchrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;ChickenBaconRanch Alert&quot; admin@foo.com </source> <translation>%s, u moet een RPC-wachtwoord instellen in het configuratiebestand: %s U wordt aangeraden het volgende willekeurige wachtwoord te gebruiken: rpcuser=chickenbaconranchrpc rpcpassword=%s (u hoeft dit wachtwoord niet te onthouden) De gebruikersnaam en wachtwoord mogen niet hetzelfde zijn. Als het bestand niet bestaat, make hem dan aan met leesrechten voor enkel de eigenaar. Het is ook aan te bevelen &quot;alertnotify&quot; in te stellen zodat u op de hoogte gesteld wordt van problemen; for example: alertnotify=echo %%s | mail -s &quot;ChickenBaconRanch Alert&quot; admin@foo.com</translation> </message> <message> <location line="+17"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation>Er is een fout opgetreden tijdens het instellen van de inkomende RPC-poort %u op IPv6, terugval naar IPv4: %s</translation> </message> <message> <location line="+3"/> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation>Bind aan opgegeven adres en luister er altijd op. Gebruik [host]:port notatie voor IPv6</translation> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. ChickenBaconRanch is probably already running.</source> <translation>Kan geen lock op de datamap %s verkrijgen. ChickenBaconRanch draait vermoedelijk reeds.</translation> </message> <message> <location line="+3"/> <source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation>Fout: De transactie was afgewezen! Dit kan gebeuren als sommige munten in uw portemonnee al eerder uitgegeven zijn, zoals wanneer u een kopie van uw wallet.dat heeft gebruikt en in de kopie deze munten zijn uitgegeven, maar in deze portemonnee die munten nog niet als zodanig zijn gemarkeerd.</translation> </message> <message> <location line="+4"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source> <translation>Fout: Deze transactie vereist transactiekosten van tenminste %s, vanwege zijn grootte, complexiteit, of het gebruik van onlangs ontvangen munten!</translation> </message> <message> <location line="+3"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation>Voer opdracht uit zodra een relevante melding ontvangen is (%s wordt in cmd vervangen door het bericht)</translation> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation>Voer opdracht uit zodra een portemonneetransactie verandert (%s in cmd wordt vervangen door TxID)</translation> </message> <message> <location line="+11"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation>Stel maximumgrootte in in bytes voor hoge-prioriteits-/lage-transactiekosten-transacties (standaard: 27000)</translation> </message> <message> <location line="+6"/> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation>Dit is een pre-release testversie - gebruik op eigen risico! Gebruik deze niet voor het delven van munten of handelsdoeleinden</translation> </message> <message> <location line="+5"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation>Waarschuwing: -paytxfee is zeer hoog ingesteld. Dit zijn de transactiekosten die u betaalt bij het versturen van een transactie.</translation> </message> <message> <location line="+3"/> <source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source> <translation>Waarschuwing: Weergegeven transacties zijn mogelijk niet correct! Mogelijk dient u te upgraden, of andere nodes dienen te upgraden.</translation> </message> <message> <location line="+3"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong ChickenBaconRanch will not work properly.</source> <translation>Waarschuwing: Controleer dat de datum en tijd op uw computer correct zijn ingesteld. Als uw klok fout staat zal ChickenBaconRanch niet correct werken.</translation> </message> <message> <location line="+3"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation>Waarschuwing: Fout bij het lezen van wallet.dat! Alle sleutels zijn in goede orde uitgelezen, maar transactiedata of adresboeklemma&apos;s zouden kunnen ontbreken of fouten bevatten.</translation> </message> <message> <location line="+3"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation>Waarschuwing: wallet.dat is corrupt, data is veiliggesteld! Originele wallet.dat is opgeslagen als wallet.{tijdstip}.bak in %s; als uw balans of transacties incorrect zijn dient u een backup terug te zetten.</translation> </message> <message> <location line="+14"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation>Poog de geheime sleutels uit een corrupt wallet.dat bestand terug te halen</translation> </message> <message> <location line="+2"/> <source>Block creation options:</source> <translation>Blokcreatie-opties:</translation> </message> <message> <location line="+5"/> <source>Connect only to the specified node(s)</source> <translation>Verbind alleen naar de gespecificeerde node(s)</translation> </message> <message> <location line="+3"/> <source>Corrupted block database detected</source> <translation>Corrupte blokkendatabase gedetecteerd</translation> </message> <message> <location line="+1"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation>Ontdek eigen IP-adres (standaard: 1 als er wordt geluisterd en geen -externalip is opgegeven)</translation> </message> <message> <location line="+1"/> <source>Do you want to rebuild the block database now?</source> <translation>Wilt u de blokkendatabase nu herbouwen?</translation> </message> <message> <location line="+2"/> <source>Error initializing block database</source> <translation>Fout bij intialisatie blokkendatabase</translation> </message> <message> <location line="+1"/> <source>Error initializing wallet database environment %s!</source> <translation>Probleem met initializeren van de database-omgeving %s!</translation> </message> <message> <location line="+1"/> <source>Error loading block database</source> <translation>Fout bij het laden van blokkendatabase</translation> </message> <message> <location line="+4"/> <source>Error opening block database</source> <translation>Fout bij openen blokkendatabase</translation> </message> <message> <location line="+2"/> <source>Error: Disk space is low!</source> <translation>Fout: Weinig vrije diskruimte!</translation> </message> <message> <location line="+1"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation>Fout: Portemonnee vergrendeld, aanmaak transactie niet mogelijk!</translation> </message> <message> <location line="+1"/> <source>Error: system error: </source> <translation>Fout: Systeemfout:</translation> </message> <message> <location line="+1"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation>Mislukt om op welke poort dan ook te luisteren. Gebruik -listen=0 as u dit wilt.</translation> </message> <message> <location line="+1"/> <source>Failed to read block info</source> <translation>Lezen van blokinformatie mislukt</translation> </message> <message> <location line="+1"/> <source>Failed to read block</source> <translation>Lezen van blok mislukt</translation> </message> <message> <location line="+1"/> <source>Failed to sync block index</source> <translation>Synchroniseren van blokindex mislukt</translation> </message> <message> <location line="+1"/> <source>Failed to write block index</source> <translation>Schrijven van blokindex mislukt</translation> </message> <message> <location line="+1"/> <source>Failed to write block info</source> <translation>Schrijven van blokinformatie mislukt</translation> </message> <message> <location line="+1"/> <source>Failed to write block</source> <translation>Schrijven van blok mislukt</translation> </message> <message> <location line="+1"/> <source>Failed to write file info</source> <translation>Schrijven van bestandsinformatie mislukt</translation> </message> <message> <location line="+1"/> <source>Failed to write to coin database</source> <translation>Schrijven naar coindatabase mislukt</translation> </message> <message> <location line="+1"/> <source>Failed to write transaction index</source> <translation>Schrijven van transactieindex mislukt</translation> </message> <message> <location line="+1"/> <source>Failed to write undo data</source> <translation>Schrijven van undo-data mislukt</translation> </message> <message> <location line="+2"/> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation>Vind andere nodes d.m.v. DNS-naslag (standaard: 1 tenzij -connect)</translation> </message> <message> <location line="+1"/> <source>Generate coins (default: 0)</source> <translation>Genereer munten (standaard: 0)</translation> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation>Aantal te checken blokken bij het opstarten (standaard: 288, 0 = allemaal)</translation> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-4, default: 3)</source> <translation>Hoe grondig de blokverificatie is (0-4, standaard: 3)</translation> </message> <message> <location line="+19"/> <source>Not enough file descriptors available.</source> <translation>Niet genoeg file descriptors beschikbaar.</translation> </message> <message> <location line="+8"/> <source>Rebuild block chain index from current blk000??.dat files</source> <translation>Blokketen opnieuw opbouwen van huidige blk000??.dat-bestanden</translation> </message> <message> <location line="+16"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation>Stel het aantal threads in om RPC-aanvragen mee te bedienen (standaard: 4)</translation> </message> <message> <location line="+26"/> <source>Verifying blocks...</source> <translation>Blokken aan het controleren...</translation> </message> <message> <location line="+1"/> <source>Verifying wallet...</source> <translation>Portomonnee aan het controleren...</translation> </message> <message> <location line="-69"/> <source>Imports blocks from external blk000??.dat file</source> <translation>Importeert blokken van extern blk000??.dat bestand</translation> </message> <message> <location line="-76"/> <source>Set the number of script verification threads (up to 16, 0 = auto, &lt;0 = leave that many cores free, default: 0)</source> <translation>Stel het aantal threads voor scriptverificatie in (max 16, 0 = auto, &lt;0 = laat zoveel cores vrij, standaard: 0)</translation> </message> <message> <location line="+77"/> <source>Information</source> <translation>Informatie</translation> </message> <message> <location line="+3"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation>Ongeldig -tor adres: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Ongeldig bedrag voor -minrelaytxfee=&lt;bedrag&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Ongeldig bedrag voor -mintxfee=&lt;bedrag&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+8"/> <source>Maintain a full transaction index (default: 0)</source> <translation>Onderhoud een volledige transactieindex (standaard: 0)</translation> </message> <message> <location line="+2"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation>Maximum per-connectie ontvangstbuffer, &lt;n&gt;*1000 bytes (standaard: 5000)</translation> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation>Maximum per-connectie zendbuffer, &lt;n&gt;*1000 bytes (standaard: 1000)</translation> </message> <message> <location line="+2"/> <source>Only accept block chain matching built-in checkpoints (default: 1)</source> <translation>Accepteer alleen blokketen die overeenkomt met de ingebouwde checkpoints (standaard: 1)</translation> </message> <message> <location line="+1"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation>Verbind alleen naar nodes in netwerk &lt;net&gt; (IPv4, IPv6 of Tor)</translation> </message> <message> <location line="+2"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation>Output extra debugginginformatie. Impliceert alle andere -debug* opties</translation> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation>Output extra netwerk-debugginginformatie</translation> </message> <message> <location line="+2"/> <source>Prepend debug output with timestamp</source> <translation>Voorzie de debuggingsuitvoer van een tijdsaanduiding</translation> </message> <message> <location line="+5"/> <source>SSL options: (see the ChickenBaconRanch Wiki for SSL setup instructions)</source> <translation>SSL-opties: (zie de ChickenBaconRanch wiki voor SSL-instructies)</translation> </message> <message> <location line="+1"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation>Selecteer de versie van de SOCKS-proxy om te gebruiken (4 of 5, standaard is 5)</translation> </message> <message> <location line="+3"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>Stuur trace/debug-info naar de console in plaats van het debug.log bestand</translation> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation>Stuur trace/debug-info naar debugger</translation> </message> <message> <location line="+5"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation>Stel maximum blokgrootte in in bytes (standaard: 250000)</translation> </message> <message> <location line="+1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation>Stel minimum blokgrootte in in bytes (standaard: 0)</translation> </message> <message> <location line="+2"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation>Verklein debug.log-bestand bij het opstarten van de client (standaard: 1 als geen -debug)</translation> </message> <message> <location line="+1"/> <source>Signing transaction failed</source> <translation>Ondertekenen van transactie mislukt</translation> </message> <message> <location line="+2"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation>Specificeer de time-outtijd in milliseconden (standaard: 5000)</translation> </message> <message> <location line="+4"/> <source>System error: </source> <translation>Systeemfout:</translation> </message> <message> <location line="+4"/> <source>Transaction amount too small</source> <translation>Transactiebedrag te klein</translation> </message> <message> <location line="+1"/> <source>Transaction amounts must be positive</source> <translation>Transactiebedragen moeten positief zijn</translation> </message> <message> <location line="+1"/> <source>Transaction too large</source> <translation>Transactie te groot</translation> </message> <message> <location line="+7"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation>Gebruik UPnP om de luisterende poort te mappen (standaard: 0)</translation> </message> <message> <location line="+1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation>Gebruik UPnP om de luisterende poort te mappen (standaard: 1 als er wordt geluisterd)</translation> </message> <message> <location line="+1"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation>Gebruik proxy om &apos;tor hidden services&apos; te bereiken (standaard: hetzelfde als -proxy)</translation> </message> <message> <location line="+2"/> <source>Username for JSON-RPC connections</source> <translation>Gebruikersnaam voor JSON-RPC-verbindingen</translation> </message> <message> <location line="+4"/> <source>Warning</source> <translation>Waarschuwing</translation> </message> <message> <location line="+1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation>Waarschuwing: Deze versie is verouderd, een upgrade is vereist!</translation> </message> <message> <location line="+1"/> <source>You need to rebuild the databases using -reindex to change -txindex</source> <translation>U moet de databases herbouwen met behulp van -reindex om -txindex te kunnen veranderen</translation> </message> <message> <location line="+1"/> <source>wallet.dat corrupt, salvage failed</source> <translation>wallet.dat corrupt, veiligstellen mislukt</translation> </message> <message> <location line="-50"/> <source>Password for JSON-RPC connections</source> <translation>Wachtwoord voor JSON-RPC-verbindingen</translation> </message> <message> <location line="-67"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>Sta JSON-RPC verbindingen van opgegeven IP-adres toe</translation> </message> <message> <location line="+76"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>Verstuur commando&apos;s naar proces dat op &lt;ip&gt; draait (standaard: 127.0.0.1)</translation> </message> <message> <location line="-120"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation>Voer commando uit zodra het beste blok verandert (%s in cmd wordt vervangen door blockhash)</translation> </message> <message> <location line="+147"/> <source>Upgrade wallet to latest format</source> <translation>Vernieuw portemonnee naar nieuwste versie</translation> </message> <message> <location line="-21"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>Stel sleutelpoelgrootte in op &lt;n&gt; (standaard: 100)</translation> </message> <message> <location line="-12"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>Doorzoek de blokketen op ontbrekende portemonnee-transacties</translation> </message> <message> <location line="+35"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>Gebruik OpenSSL (https) voor JSON-RPC-verbindingen</translation> </message> <message> <location line="-26"/> <source>Server certificate file (default: server.cert)</source> <translation>Certificaat-bestand voor server (standaard: server.cert)</translation> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation>Geheime sleutel voor server (standaard: server.pem)</translation> </message> <message> <location line="-151"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation>Aanvaardbare ciphers (standaard: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation> </message> <message> <location line="+165"/> <source>This help message</source> <translation>Dit helpbericht</translation> </message> <message> <location line="+6"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation>Niet in staat om aan %s te binden op deze computer (bind gaf error %d, %s)</translation> </message> <message> <location line="-91"/> <source>Connect through socks proxy</source> <translation>Verbind via een socks-proxy</translation> </message> <message> <location line="-10"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>Sta DNS-naslag toe voor -addnode, -seednode en -connect</translation> </message> <message> <location line="+55"/> <source>Loading addresses...</source> <translation>Adressen aan het laden...</translation> </message> <message> <location line="-35"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>Fout bij laden wallet.dat: Portemonnee corrupt</translation> </message> <message> <location line="+1"/> <source>Error loading wallet.dat: Wallet requires newer version of ChickenBaconRanch</source> <translation>Fout bij laden wallet.dat: Portemonnee vereist een nieuwere versie van ChickenBaconRanch</translation> </message> <message> <location line="+93"/> <source>Wallet needed to be rewritten: restart ChickenBaconRanch to complete</source> <translation>Portemonnee moest herschreven worden: Herstart ChickenBaconRanch om te voltooien</translation> </message> <message> <location line="-95"/> <source>Error loading wallet.dat</source> <translation>Fout bij laden wallet.dat</translation> </message> <message> <location line="+28"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation>Ongeldig -proxy adres: &apos;%s&apos;</translation> </message> <message> <location line="+56"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation>Onbekend netwerk gespecificeerd in -onlynet: &apos;%s&apos;</translation> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation>Onbekende -socks proxyversie aangegeven: %i</translation> </message> <message> <location line="-96"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation>Kan -bind adres niet herleiden: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation>Kan -externlip adres niet herleiden: &apos;%s&apos;</translation> </message> <message> <location line="+44"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Ongeldig bedrag voor -paytxfee=&lt;bedrag&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount</source> <translation>Ongeldig bedrag</translation> </message> <message> <location line="-6"/> <source>Insufficient funds</source> <translation>Ontoereikend saldo</translation> </message> <message> <location line="+10"/> <source>Loading block index...</source> <translation>Blokindex aan het laden...</translation> </message> <message> <location line="-57"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>Voeg een node om naar te verbinden toe en probeer de verbinding open te houden</translation> </message> <message> <location line="-25"/> <source>Unable to bind to %s on this computer. ChickenBaconRanch is probably already running.</source> <translation>Niet in staat om aan %s te binden op deze computer. ChickenBaconRanch draait vermoedelijk reeds.</translation> </message> <message> <location line="+64"/> <source>Fee per KB to add to transactions you send</source> <translation>Kosten per KB om aan transacties toe te voegen die u verstuurt</translation> </message> <message> <location line="+19"/> <source>Loading wallet...</source> <translation>Portemonnee aan het laden...</translation> </message> <message> <location line="-52"/> <source>Cannot downgrade wallet</source> <translation>Kan portemonnee niet downgraden</translation> </message> <message> <location line="+3"/> <source>Cannot write default address</source> <translation>Kan standaardadres niet schrijven</translation> </message> <message> <location line="+64"/> <source>Rescanning...</source> <translation>Blokketen aan het doorzoeken...</translation> </message> <message> <location line="-57"/> <source>Done loading</source> <translation>Klaar met laden</translation> </message> <message> <location line="+82"/> <source>To use the %s option</source> <translation>Om de %s optie te gebruiken</translation> </message> <message> <location line="-74"/> <source>Error</source> <translation>Fout</translation> </message> <message> <location line="-31"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation>U dient rpcpassword=&lt;wachtwoord&gt; in te stellen in het configuratiebestand: %s Als het bestand niet bestaat, maak het dan aan, met een alleen-lezen-permissie.</translation> </message> </context> </TS>
mit
ndelvalle/ng-giphy
src/directives/findbyid.directive.js
658
(function () { 'use strict'; angular.module('ng-giphy') .directive('giphyId', findGiphyById); /** * Directive: find gif by id */ function findGiphyById() { return { scope: { id: '=gId', rating: '=' }, controller: findGiphyByIdController, controllerAs: 'vm', bindToController: true, templateUrl: 'imgTemplate.html' }; } findGiphyByIdController.$inject = ['giphy']; /* @ngInject */ function findGiphyByIdController(giphy) { /* jshint validthis: true */ var vm = this; giphy.findUrlById(vm.id).then(function (url) { vm.giphysrc = url; }); } })();
mit
speedlog/mapping-tools-performance
domain/src/main/java/pl/speedlog/demo/entity/Address.java
237
package pl.speedlog.demo.entity; import lombok.Data; /** * @author Mariusz Wyszomierski <mariusz@wyszomierski.pl> */ @Data public class Address { private String street; private String postalCode; private String city; }
mit
ngovanbon16/dulichboss
application/controllers/login.php
3310
<?php if (!defined('BASEPATH')) exit('No direct script access allowed'); class Login extends CI_Controller { public function __construct() { parent::__construct(); $this->load->model("mlogin"); } public function index() { //$this->_data['subview'] = 'login_view'; //$this->_data['title'] = 'Đăng nhập'; //$this->load->view('main.php', $this->_data); $this->load->view("login_view"); } public function login() { $email = $this->db->escape_like_str($_POST["email"]); $password = $this->db->escape_like_str($_POST["password"]); $msg = array(); $error = ""; if(empty($email)) { $msg["email"] = lang('please').' '.lang('input').' '.lang('email'); $error = lang('error'); } else if(!($this->mlogin->testEmail($email))) { $msg["email"] = lang('email').' '.lang('is').' '.lang('invalid'); $error = lang('error'); } else { if($this->mlogin->khoa($email)) { $error = lang('your_account_has_been_locked'); } else { if(!$this->mlogin->kichhoat($email)) { $error = lang('your_account_not_activated'); //$error = lang('error'); } else { if(empty($password)) { $msg["password"] = lang('please').' '.lang('input').' '.lang('password'); $error = lang('error'); } else if(!($this->mlogin->testpassword($email, $password))) { $msg["password"] = lang('password').' '.lang('is').' '.lang('invalid'); $error = lang('error'); } } } } if($error != "") { $msg['error'] = $error; } $status = "error"; if(count($msg) == 0) { $status = "success"; $query = $this->mlogin->getuser($email, $password); $quyen = "0"; if($this->mlogin->testquyen($email)) { $quyen = "1"; } if($query) { foreach ($query as $row) { $newdata = array( 'admin' => $quyen, 'id' => $row->ND_MA, 'email' => $row->ND_DIACHIMAIL, 'avata' => $row->ND_HINH, 'T_MA' => $row->T_MA, 'NQ_MA' => $row->NQ_MA ); $this->session->set_userdata($newdata); // Tạo Session cho Users //redirect(base_url() . "index.php/home"); } } } $response = array('status' => $status,'msg' => $msg ); $jsonString = json_encode($response); echo $jsonString; } private function _user_is_login() { $id = $this->session->userdata('id'); if(!$id) { return false; } return true; } public function logout($trang) { if($this->_user_is_login()) { //neu thanh vien da dang nhap thi xoa session login $this->session->unset_userdata('admin'); $this->session->unset_userdata('id'); $this->session->unset_userdata('email'); $this->session->unset_userdata('avata'); $this->session->unset_userdata('T_MA'); $this->session->unset_userdata('NQ_MA'); $this->session->set_flashdata('flash_message', 'Đăng xuất thành công'); redirect(base_url() . "home/".$trang); } else { redirect(base_url() . "login"); } } }
mit
zuku/bmff
lib/bmff/box/degradation_priority.rb
460
# coding: utf-8 # vim: set expandtab tabstop=2 shiftwidth=2 softtabstop=2 autoindent: class BMFF::Box::DegradationPriority < BMFF::Box::Full attr_accessor :priority register_box "stdp" def parse_data super sample_size_box = parent.find(BMFF::Box::SampleSize) if sample_size_box sample_count = sample_size_box.sample_count @priority = [] sample_count.times do @priority << io.get_uint16 end end end end
mit
AntonGrafstrom/select
matrix.js
11030
var js = (js || {}); (function(ctx){ ctx.matrix = function(ary){ return new ctx.Matrix((ary.e || ary)); } ctx.rowVector = function(ary){ return new ctx.Matrix([(ary.e || ary)]); } ctx.columnVector = function(ary){ var a = (ary.e || ary); return new ctx.Matrix(a.map(function(v) {return [v]})) } ctx.Matrix = function(ary) { this.e = (ary.e || ary).slice(); } ctx.Matrix.prototype.list = function() { var v = [], i, j; for(j=0;j<this.ncol();j++){ for(i=0;i<this.nrow();i++){ v.push(this.e[i][j]); } } return ctx.list(v); } ctx.Matrix.prototype.ncol = function(){return this.e[0].length;} ctx.Matrix.prototype.nrow = function(){return this.e.length;} ctx.Matrix.prototype.size = function(){return [this.e.length,this.e[0].length];} ctx.Matrix.prototype.row = function(i){return ctx.list(this.e[i-1].slice());} ctx.Matrix.prototype.col = function(i){return ctx.list(this.e.map(function(v) {return v[i-1];}))} ctx.Matrix.prototype.map = function(f) { var i,j,x =[]; for(i=0;i<this.nrow();i++){ x.push([]); for(j=0;j<this.ncol();j++){ x[i].push(f(this.e[i][j],i+1,j+1)); } } return new ctx.Matrix(x); } ctx.Matrix.prototype.forEach = function(f) { var i,j; for(i=0;i<this.nrow();i++){ for(j=0;j<this.ncol();j++){ f(this.e[i][j],i+1,j+1); } } } ctx.Matrix.prototype.sqrt = function(){return this.map(Math.sqrt);} ctx.Matrix.prototype.abs = function(){return this.map(Math.abs);} ctx.Matrix.prototype.acos = function(){return this.map(Math.acos);} ctx.Matrix.prototype.asin = function(){return this.map(Math.asin);} ctx.Matrix.prototype.atan = function(){return this.map(Math.atan);} ctx.Matrix.prototype.ceil = function(){return this.map(Math.ceil);} ctx.Matrix.prototype.floor = function(){return this.map(Math.floor);} ctx.Matrix.prototype.round = function(){return this.map(Math.round);} ctx.Matrix.prototype.exp = function(){return this.map(Math.exp);} ctx.Matrix.prototype.log = function(){return this.map(Math.log);} ctx.Matrix.prototype.sin = function(){return this.map(Math.sin);} ctx.Matrix.prototype.cos = function(){return this.map(Math.cos);} ctx.Matrix.prototype.tan = function(){return this.map(Math.tan);} ctx.Matrix.prototype.pow = function(n){ return this.map(function(v,r,c){return Math.pow(v,n);}); } ctx.Matrix.prototype.sign = function(){ return this.map(function(v,r,c){return v > 0 ? 1 : v == 0 ? 0 : -1;}); } ctx.Matrix.prototype.snap = function(d){ var k = d || 0; return this.map(function(v,r,c){return parseFloat(v.toFixed(k))}); } ctx.Matrix.prototype.sum = function(){ var s = 0; this.forEach(function(v,r,c){s+=v;}); return s; } ctx.Matrix.prototype.add = function(n){ if(typeof(n)=='number'){return this.map(function(v,r,c){return v+n;});} if(this.nrow()==n.nrow() && this.ncol()==n.ncol()){ return this.map(function(v,r,c){return v+n.e[r-1][c-1];}); } return null; //incompatible sizes } ctx.Matrix.prototype.substract = function(n){ if(typeof(n)=='number'){return this.map(function(v,r,c){return v-n;});} if(this.nrow()==n.nrow() && this.ncol()==n.ncol()){ return this.map(function(v,r,c){return v-n.e[r-1][c-1];}); } return null; //incompatible sizes } ctx.Matrix.prototype.multiply = function(n){ if(typeof(n)=='number'){return this.map(function(v,r,c){return v*n;});} if(this.nrow()==n.nrow() && this.ncol()==n.ncol()){ return this.map(function(v,r,c){return v*n.e[r-1][c-1];}); } return null; //incompatible sizes } ctx.Matrix.prototype.divide = function(n){ if(typeof(n)=='number'){return this.map(function(v,r,c){return v/n;});} if(this.nrow()==n.nrow() && this.ncol()==n.ncol()){ return this.map(function(v,r,c){return v/n.e[r-1][c-1];}); } return null; //incompatible sizes } ctx.Matrix.prototype.min = function(){ var m = Infinity; this.forEach(function(v,r,c){m = Math.min(m,v);}); return m; } ctx.Matrix.prototype.max = function(){ var m = -Infinity; this.forEach(function(v,r,c){m = Math.max(m,v);}); return m; } ctx.Matrix.prototype.prod = function(){ var p = 1; this.forEach(function(v,r,c){p*=v;}); return p; } ctx.Matrix.prototype.mean = function(){ return this.sum()/(this.nrow()*this.ncol()); } ctx.Matrix.prototype.variance = function(){ var m = this.mean(), s = 0, ss = 0; var N = this.nrow()*this.ncol(); this.forEach(function(v,r,c){s+=v; ss+=v*v;}); return (ss-s*s/N)/(N-1); } ctx.Matrix.prototype.std = function(){ return Math.sqrt(this.variance()); } ctx.Matrix.prototype.colSums = function(){ var s = [],i,j; for(i=0;i<this.ncol();i++){ s.push(0); } for(i=0;i<this.nrow();i++){ for(j=0;j<this.ncol();j++){ s[j]+=this.e[i][j]; } } return new ctx.Matrix([s]); } ctx.Matrix.prototype.colMeans = function(){ var nr = this.nrow(); return this.colSums().map(function(v,r,c){return v/nr;}); } ctx.Matrix.prototype.cov = function(){ var means = this.colMeans(); var m = means.e[0]; for(var i=0;i<this.nrow()-1;i++){ means.e.push(m); } var xme = this.substract(means); var nr = this.nrow(); return xme.transpose().mmult(xme).divide(nr-1); } ctx.Matrix.prototype.colVar = function(){ var means = this.colMeans(); var m = means.e[0]; for(var i=0;i<this.nrow()-1;i++){ means.e.push(m); } return this.substract(means).pow(2).colSums().divide(this.nrow()-1); } ctx.Matrix.prototype.colStd = function(){ return this.colVar().sqrt(); } ctx.Matrix.prototype.colStandardized = function(){ var means = this.colMeans(); var stds = this.colStd(); return this.map(function(v,i,j){return (v-means.e[0][j-1])/stds.e[0][j-1]}); } ctx.Matrix.prototype.cbind = function(){ var a = arguments.length, x =[], i, j; for(i=0;i<this.nrow();i++){ x.push(this.e[i]); for(j=0;j<a;j++){ if(arguments[j].nrow()!=this.nrow()){ //incompatible sizes return null; } x[i] = x[i].concat(arguments[j][i]); } } return new ctx.Matrix(x); } ctx.Matrix.prototype.toString = function() { return '[['+this.e.join("], [")+']]'; } ctx.Matrix.prototype.toJSON = function() { return this.e; } // returns a new ctx.Matrix ctx.Matrix.prototype.copy = function() { var s = [] for (var i = 0; i < this.e.length; i++) s.push(this.e[i].slice()); return new ctx.Matrix(s); } // returns a new ctx.Matrix ctx.Matrix.prototype.transpose = function() { var transposed = []; for (var i = 0; i < this.ncol(); i++) { transposed[i] = []; for (var j = 0; j < this.nrow(); j++) { transposed[i][j] = this.e[j][i]; } } return new ctx.Matrix(transposed); } ctx.Matrix.prototype.t = ctx.Matrix.prototype.transpose; // returns a new ctx.Matrix ctx.Matrix.prototype.mmult = function(other) { if (this.ncol() != other.nrow()) { return null; //incompatible sizes; } var result = []; for (var i = 0; i < this.nrow(); i++) { result[i]=[]; for (var j = 0; j < other.ncol(); j++) { var sum = 0; for (var k = 0; k < other.nrow(); k++) { sum += this.e[i][k] * other.e[k][j]; } result[i][j] = sum; } } return new ctx.Matrix(result); } // returns a new ctx.Matrix // to Reduced Row Echelon Form ctx.Matrix.prototype.rref = function() { var x = this.copy(), lead = 0, r, i, j, tmp, val; for (r = 0; r < x.nrow(); r++) { if (x.ncol() <= lead) { break; } i = r; while (x.e[i][lead] == 0) { i++; if (x.nrow() == i) { i = r; lead++; if (x.ncol() == lead) { return x; } } } tmp = x.e[i]; x.e[i] = x.e[r]; x.e[r] = tmp; val = x.e[r][lead]; for (j = 0; j < x.ncol(); j++) { x.e[r][j] /= val; } for (i = 0; i < x.nrow(); i++) { if (i == r) continue; val = x.e[i][lead]; for (j = 0; j < x.ncol(); j++) { x.e[i][j] -= val * x.e[r][j]; } } lead++; } return x; } // identityMatrix ctx.identityMatrix = function(n) { this.e = []; var i,j; for (i = 0; i < n; i++) { this.e[i] = []; for (j = 0; j < n; j++) { this.e[i][j] = (i == j ? 1 : 0); } } } ctx.identityMatrix.prototype = ctx.Matrix.prototype; // Borrowed and rewritten from Sylvester, (c) 2007–2012 James Coglan, MIT license // Make the matrix upper (right) triangular by Gaussian elimination. // This method only adds multiples of rows to other rows. No rows are // scaled up or switched, and the determinant is preserved. ctx.Matrix.prototype.toRightTriangular = function() { var M = this.copy(), els; var n = this.e.length, k = n, i, np, kp = this.e[0].length, p; do { i = k - n; if (M.e[i][i] == 0) { for (j = i + 1; j < k; j++) { if (M.e[j][i] != 0) { els = []; np = kp; do { p = kp - np; els.push(M.e[i][p] + M.e[j][p]); } while (--np); M.e[i] = els; break; } } } if (M.e[i][i] != 0) { for (j = i + 1; j < k; j++) { var multiplier = M.e[j][i] / M.e[i][i]; els = []; np = kp; do { p = kp - np; // Elements with column numbers up to an including the number // of the row that we're subtracting can safely be set straight to // zero, since that's the point of this routine and it avoids having // to loop over and correct rounding errors later els.push(p <= i ? 0 : M.e[j][p] - M.e[i][p] * multiplier); } while (--np); M.e[j] = els; } } } while (--n); return M; }; // Borrowed and rewritten from Sylvester, (c) 2007–2012 James Coglan, MIT license ctx.Matrix.prototype.isSquare = function() { return (this.e.length == this.e[0].length); }; // Borrowed and rewritten from Sylvester, (c) 2007–2012 James Coglan, MIT license // Returns the determinant for square matrices ctx.Matrix.prototype.determinant = function() { if (!this.isSquare()) { return null; } var M = this.toRightTriangular(), det = M.e[0][0], n = M.e.length - 1, k = n, i; do { i = k - n + 1; det = det * M.e[i][i]; } while (--n); return det; }; // returns a new ctx.Matrix ctx.Matrix.prototype.inverse = function() { var x = this.copy(); var nr = this.nrow(); if (x.nrow() != x.ncol()) { //not a non-square matrix return null; } if(x.determinant()===0){ //not invertible return null; } var I = new ctx.identityMatrix(x.nrow()),i; for(i = 0; i < x.nrow(); i++){ x.e[i] = x.e[i].concat(I.e[i]); } x = x.rref(); for(i = 0; i < nr; i++){ x.e[i].splice(0, nr); } return x; } ctx.Matrix.prototype.regression_coefficients = function(x) { var x_t = x.transpose(); return x_t.mmult(x).inverse().mmult(x_t).mmult(this); } })(js);
mit
SkillsFundingAgency/das-employerapprenticeshipsservice
src/SFA.DAS.EmployerFinance/Models/Payments/PaymentFundsOut.cs
252
namespace SFA.DAS.EmployerFinance.Models.Payments { public class PaymentFundsOut { public int CalendarPeriodYear { get; set; } public int CalendarPeriodMonth { get; set; } public decimal FundsOut { get; set; } } }
mit
maxleiko/wsmsgbroker-java
src/main/java/fr/braindead/wsmsgbroker/protocol/Send.java
701
package fr.braindead.wsmsgbroker.protocol; import fr.braindead.wsmsgbroker.actions.client.Action; /** * Created by leiko on 30/10/14. */ public class Send { private String action = Action.SEND.toString(); private String ack; private Object message; private String[] dest; public String getAck() { return ack; } public void setAck(String ack) { this.ack = ack; } public Object getMessage() { return message; } public void setMessage(Object message) { this.message = message; } public String[] getDest() { return dest; } public void setDest(String[] dest) { this.dest = dest; } }
mit
ElegantWhelp/LWJGL-3-Tutorial
src/main/java/com/github/elegantwhelp/game/Main.java
3222
package com.github.elegantwhelp.game; import static org.lwjgl.glfw.GLFW.*; import static org.lwjgl.opengl.GL11.*; import org.lwjgl.opengl.GL; import com.github.elegantwhelp.assets.Assets; import com.github.elegantwhelp.gui.Gui; import com.github.elegantwhelp.io.Timer; import com.github.elegantwhelp.io.Window; import com.github.elegantwhelp.render.Camera; import com.github.elegantwhelp.render.Shader; import com.github.elegantwhelp.world.TileRenderer; import com.github.elegantwhelp.world.World; public class Main { public Main() { Window.setCallbacks(); if (!glfwInit()) { System.err.println("GLFW Failed to initialize!"); System.exit(1); } Window window = new Window(); window.setSize(640, 480); window.setFullscreen(false); window.createWindow("Game"); GL.createCapabilities(); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); Camera camera = new Camera(window.getWidth(), window.getHeight()); glEnable(GL_TEXTURE_2D); TileRenderer tiles = new TileRenderer(); Assets.initAsset(); // float[] vertices = new float[] { // -1f, 1f, 0, //TOP LEFT 0 // 1f, 1f, 0, //TOP RIGHT 1 // 1f, -1f, 0, //BOTTOM RIGHT 2 // -1f, -1f, 0,//BOTTOM LEFT 3 // }; // // float[] texture = new float[] { // 0,0, // 1,0, // 1,1, // 0,1, // }; // // int[] indices = new int[] { // 0,1,2, // 2,3,0 // }; // // Model model = new Model(vertices, texture, indices); Shader shader = new Shader("shader"); World world = new World("test_level", camera); world.calculateView(window); Gui gui = new Gui(window); double frame_cap = 1.0 / 60.0; double frame_time = 0; int frames = 0; double time = Timer.getTime(); double unprocessed = 0; while (!window.shouldClose()) { boolean can_render = false; double time_2 = Timer.getTime(); double passed = time_2 - time; unprocessed += passed; frame_time += passed; time = time_2; while (unprocessed >= frame_cap) { if (window.hasResized()) { camera.setProjection(window.getWidth(), window.getHeight()); gui.resizeCamera(window); world.calculateView(window); glViewport(0, 0, window.getWidth(), window.getHeight()); } unprocessed -= frame_cap; can_render = true; if (window.getInput().isKeyReleased(GLFW_KEY_ESCAPE)) { glfwSetWindowShouldClose(window.getWindow(), true); } gui.update(window.getInput()); world.update((float) frame_cap, window, camera); world.correctCamera(camera, window); window.update(); if (frame_time >= 1.0) { frame_time = 0; System.out.println("FPS: " + frames); frames = 0; } } if (can_render) { glClear(GL_COLOR_BUFFER_BIT); // shader.bind(); // shader.setUniform("sampler", 0); // shader.setUniform("projection", // camera.getProjection().mul(target)); // model.render(); // tex.bind(0); world.render(tiles, shader, camera); gui.render(); window.swapBuffers(); frames++; } } Assets.deleteAsset(); glfwTerminate(); } public static void main(String[] args) { new Main(); } }
mit
lucasdesenna/generic-search-flow
src/app/main/main.controller.spec.js
192
describe('controllers', () => { let vm; beforeEach(angular.mock.module('generic-search-flow')); beforeEach(inject(($controller) => { vm = $controller('MainController'); })); });
mit
BitClubDev/ClubCoin
src/qt/locale/bitcoin_la.ts
119453
<?xml version="1.0" ?><!DOCTYPE TS><TS language="la" version="2.1"> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About ClubCoin</source> <translation type="unfinished"/> </message> <message> <location line="+39"/> <source>&lt;b&gt;ClubCoin&lt;/b&gt; version</source> <translation type="unfinished"/> </message> <message> <location line="+41"/> <source>Copyright © 2009-2014 The Bitcoin developers Copyright © 2012-2014 The NovaCoin developers Copyright © 2014 The BlackCoin developers Copyright © 2015 The ClubCoin developers</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or &lt;a href=&quot;http://www.opensource.org/licenses/mit-license.php&quot;&gt;http://www.opensource.org/licenses/mit-license.php&lt;/a&gt;. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (&lt;a href=&quot;https://www.openssl.org/&quot;&gt;https://www.openssl.org/&lt;/a&gt;) and cryptographic software written by Eric Young (&lt;a href=&quot;mailto:eay@cryptsoft.com&quot;&gt;eay@cryptsoft.com&lt;/a&gt;) and UPnP software written by Thomas Bernard.</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Double-click to edit address or label</source> <translation>Dupliciter-clicca ut inscriptionem vel titulum mutes</translation> </message> <message> <location line="+24"/> <source>Create a new address</source> <translation>Crea novam inscriptionem</translation> </message> <message> <location line="+10"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Copia inscriptionem iam selectam in latibulum systematis</translation> </message> <message> <location line="-7"/> <source>&amp;New Address</source> <translation type="unfinished"/> </message> <message> <location line="-43"/> <source>These are your ClubCoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation type="unfinished"/> </message> <message> <location line="+53"/> <source>&amp;Copy Address</source> <translation>&amp;Copia Inscriptionem</translation> </message> <message> <location line="+7"/> <source>Show &amp;QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Sign a message to prove you own a ClubCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Delete the currently selected address from the list</source> <translation>Dele active selectam inscriptionem ex enumeratione</translation> </message> <message> <location line="-10"/> <source>Verify a message to ensure it was signed with a specified ClubCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>&amp;Delete</source> <translation>&amp;Dele</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+65"/> <source>Copy &amp;Label</source> <translation>Copia &amp;Titulum</translation> </message> <message> <location line="+2"/> <source>&amp;Edit</source> <translation>&amp;Muta</translation> </message> <message> <location line="+250"/> <source>Export Address Book Data</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Comma Separata Plica (*.csv)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+145"/> <source>Label</source> <translation>Titulus</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Inscriptio</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(nullus titulus)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation>Dialogus Tesserae</translation> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>Insere tesseram</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>Nova tessera</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>Itera novam tesseram</translation> </message> <message> <location line="+33"/> <source>Serves to disable the trivial sendmoney when OS account compromised. Provides no real security.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>For staking only</source> <translation type="unfinished"/> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+38"/> <source>Encrypt wallet</source> <translation>Cifra cassidile</translation> </message> <message> <location line="+7"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Huic operationi necesse est tessera cassidili tuo ut cassidile reseret.</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>Resera cassidile</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Huic operationi necesse est tessera cassidili tuo ut cassidile decifret.</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>Decifra cassidile</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>Muta tesseram</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Insero veterem novamque tesseram cassidili.</translation> </message> <message> <location line="+45"/> <source>Confirm wallet encryption</source> <translation>Confirma cifrationem cassidilis</translation> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR COINS&lt;/b&gt;!</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation>Certusne es te velle tuum cassidile cifrare?</translation> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation>GRAVE: Oportet ulla prioria conservata quae fecisti de plica tui cassidilis reponi a nove generata cifrata plica cassidilis. Propter securitatem, prioria conservata de plica non cifrata cassidilis inutilia fiet simul atque incipis uti novo cifrato cassidili.</translation> </message> <message> <location line="+103"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation>Monitio: Litterae ut capitales seratae sunt!</translation> </message> <message> <location line="-133"/> <location line="+60"/> <source>Wallet encrypted</source> <translation>Cassidile cifratum</translation> </message> <message> <location line="-140"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;ten or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <source>ClubCoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your coins from being stolen by malware infecting your computer.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+44"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>Cassidile cifrare abortum est</translation> </message> <message> <location line="-56"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Cassidile cifrare abortum est propter internum errorem. Tuum cassidile cifratum non est.</translation> </message> <message> <location line="+7"/> <location line="+50"/> <source>The supplied passphrases do not match.</source> <translation>Tesserae datae non eaedem sunt.</translation> </message> <message> <location line="-38"/> <source>Wallet unlock failed</source> <translation>Cassidile reserare abortum est.</translation> </message> <message> <location line="+1"/> <location line="+12"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>Tessera inserta pro cassidilis decifrando prava erat.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>Cassidile decifrare abortum est.</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation>Tessera cassidilis successa est in mutando.</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+297"/> <source>Sign &amp;message...</source> <translation>Signa &amp;nuntium...</translation> </message> <message> <location line="-64"/> <source>Show general overview of wallet</source> <translation>Monstra generale summarium cassidilis</translation> </message> <message> <location line="+17"/> <source>&amp;Transactions</source> <translation>&amp;Transactiones</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>Inspicio historiam transactionum</translation> </message> <message> <location line="+5"/> <source>&amp;Address Book</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit the list of stored addresses and labels</source> <translation type="unfinished"/> </message> <message> <location line="-18"/> <source>Show the list of addresses for receiving payments</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>E&amp;xit</source> <translation>E&amp;xi</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>Exi applicatione</translation> </message> <message> <location line="+4"/> <source>Show information about ClubCoin</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>Informatio de &amp;Qt</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>Monstra informationem de Qt</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>&amp;Optiones</translation> </message> <message> <location line="+4"/> <source>&amp;Encrypt Wallet...</source> <translation>&amp;Cifra Cassidile...</translation> </message> <message> <location line="+2"/> <source>&amp;Backup Wallet...</source> <translation>&amp;Conserva Cassidile...</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>&amp;Muta tesseram...</translation> </message> <message> <location line="+9"/> <source>&amp;Export...</source> <translation type="unfinished"/> </message> <message> <location line="-55"/> <source>Send coins to a ClubCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+39"/> <source>Modify configuration options for ClubCoin</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="-13"/> <source>Encrypt or decrypt wallet</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Backup wallet to another location</source> <translation>Conserva cassidile in locum alium</translation> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>Muta tesseram utam pro cassidilis cifrando</translation> </message> <message> <location line="+10"/> <source>&amp;Debug window</source> <translation>Fenestra &amp;Debug</translation> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation>Aperi terminalem debug et diagnosticalem</translation> </message> <message> <location line="-5"/> <source>&amp;Verify message...</source> <translation>&amp;Verifica nuntium...</translation> </message> <message> <location line="-214"/> <location line="+551"/> <source>ClubCoin</source> <translation type="unfinished"/> </message> <message> <location line="-551"/> <source>Wallet</source> <translation>Cassidile</translation> </message> <message> <location line="+193"/> <source>&amp;About ClubCoin</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation>&amp;Monstra/Occulta</translation> </message> <message> <location line="+8"/> <source>Unlock wallet</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>&amp;Lock Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Lock wallet</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>&amp;File</source> <translation>&amp;Plica</translation> </message> <message> <location line="+8"/> <source>&amp;Settings</source> <translation>&amp;Configuratio</translation> </message> <message> <location line="+8"/> <source>&amp;Help</source> <translation>&amp;Auxilium</translation> </message> <message> <location line="+17"/> <source>Tabs toolbar</source> <translation>Tabella instrumentorum &quot;Tabs&quot;</translation> </message> <message> <location line="+46"/> <location line="+9"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> <message> <location line="+0"/> <location line="+58"/> <source>ClubCoin client</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+70"/> <source>%n active connection(s) to ClubCoin network</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+488"/> <source>Staking.&lt;br&gt;Your weight is %1&lt;br&gt;Network weight is %2&lt;br&gt;Expected time to earn reward is %3</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Not staking because wallet is locked</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because wallet is offline</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because wallet is syncing</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because you don&apos;t have mature coins</source> <translation type="unfinished"/> </message> <message> <location line="-808"/> <source>&amp;Dashboard</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>&amp;Receive</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>&amp;Send</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>&amp;Unlock Wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+273"/> <source>Up to date</source> <translation>Recentissimo</translation> </message> <message> <location line="+43"/> <source>Catching up...</source> <translation>Persequens...</translation> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Sent transaction</source> <translation>Transactio missa</translation> </message> <message> <location line="+1"/> <source>Incoming transaction</source> <translation>Transactio incipiens</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>Dies: %1 Quantitas: %2 Typus: %3 Inscriptio: %4 </translation> </message> <message> <location line="+100"/> <location line="+15"/> <source>URI handling</source> <translation type="unfinished"/> </message> <message> <location line="-15"/> <location line="+15"/> <source>URI can not be parsed! This can be caused by an invalid ClubCoin address or malformed URI parameters.</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Wallet is &lt;b&gt;not encrypted&lt;/b&gt;</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>Cassidile &lt;b&gt;cifratum&lt;/b&gt; est et iam nunc &lt;b&gt;reseratum&lt;/b&gt;</translation> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>Cassidile &lt;b&gt;cifratum&lt;/b&gt; est et iam nunc &lt;b&gt;seratum&lt;/b&gt;</translation> </message> <message> <location line="+24"/> <source>Backup Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+91"/> <source>%n second(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n minute(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="-429"/> <location line="+433"/> <source>%n hour(s)</source> <translation><numerusform>%n hora</numerusform><numerusform>%n horae</numerusform></translation> </message> <message> <location line="-456"/> <source>Processed %1 blocks of transaction history.</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+27"/> <location line="+433"/> <source>%n day(s)</source> <translation><numerusform>%n dies</numerusform><numerusform>%n dies</numerusform></translation> </message> <message numerus="yes"> <location line="-429"/> <location line="+6"/> <source>%n week(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+0"/> <source>%1 and %2</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+0"/> <source>%n year(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+5"/> <source>%1 behind</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Last received block was generated %1 ago.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Error</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="+69"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation type="unfinished"/> </message> <message> <location line="+324"/> <source>Not staking</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoin.cpp" line="+104"/> <source>A fatal error occurred. ClubCoin can no longer continue safely and will quit.</source> <translation type="unfinished"/> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+110"/> <source>Network Alert</source> <translation>Monitio Retis</translation> </message> </context> <context> <name>CoinControlDialog</name> <message> <location filename="../forms/coincontroldialog.ui" line="+14"/> <source>Coin Control</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Quantity:</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Bytes:</source> <translation type="unfinished"/> </message> <message> <location line="+48"/> <source>Amount:</source> <translation>Quantitas:</translation> </message> <message> <location line="+32"/> <source>Priority:</source> <translation type="unfinished"/> </message> <message> <location line="+48"/> <source>Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Low Output:</source> <translation type="unfinished"/> </message> <message> <location filename="../coincontroldialog.cpp" line="+552"/> <source>no</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/coincontroldialog.ui" line="+51"/> <source>After Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Change:</source> <translation type="unfinished"/> </message> <message> <location line="+69"/> <source>(un)select all</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Tree mode</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>List mode</source> <translation type="unfinished"/> </message> <message> <location line="+45"/> <source>Amount</source> <translation>Quantitas</translation> </message> <message> <location line="+5"/> <source>Label</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Address</source> <translation>Inscriptio</translation> </message> <message> <location line="+5"/> <source>Date</source> <translation>Dies</translation> </message> <message> <location line="+5"/> <source>Confirmations</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Confirmed</source> <translation>Confirmatum</translation> </message> <message> <location line="+5"/> <source>Priority</source> <translation type="unfinished"/> </message> <message> <location filename="../coincontroldialog.cpp" line="-515"/> <source>Copy address</source> <translation>Copia inscriptionem</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Copia titulum</translation> </message> <message> <location line="+1"/> <location line="+26"/> <source>Copy amount</source> <translation>Copia quantitatem</translation> </message> <message> <location line="-25"/> <source>Copy transaction ID</source> <translation>Copia transactionis ID</translation> </message> <message> <location line="+24"/> <source>Copy quantity</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Copy fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy after fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy bytes</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy priority</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy low output</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy change</source> <translation type="unfinished"/> </message> <message> <location line="+317"/> <source>highest</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>high</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>medium-high</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>medium</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>low-medium</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>low</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>lowest</source> <translation type="unfinished"/> </message> <message> <location line="+155"/> <source>DUST</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>yes</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>This label turns red, if the transaction size is bigger than 10000 bytes. This means a fee of at least %1 per kb is required. Can vary +/- 1 Byte per input.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transactions with higher priority get more likely into a block. This label turns red, if the priority is smaller than &quot;medium&quot;. This means a fee of at least %1 per kb is required.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This label turns red, if any recipient receives an amount smaller than %1. This means a fee of at least %2 is required. Amounts below 0.546 times the minimum relay fee are shown as DUST.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This label turns red, if the change is smaller than %1. This means a fee of at least %2 is required.</source> <translation type="unfinished"/> </message> <message> <location line="+36"/> <location line="+66"/> <source>(no label)</source> <translation>(nullus titulus)</translation> </message> <message> <location line="-9"/> <source>change from %1 (%2)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>(change)</source> <translation type="unfinished"/> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>Muta Inscriptionem</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>&amp;Titulus</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>&amp;Inscriptio</translation> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation type="unfinished"/> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation>Nova inscriptio accipiendi</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>Nova inscriptio mittendi</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>Muta inscriptionem accipiendi</translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>Muta inscriptionem mittendi</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>Inserta inscriptio &quot;%1&quot; iam in libro inscriptionum est.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid ClubCoin address.</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>Non potuisse cassidile reserare</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>Generare novam clavem abortum est.</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+426"/> <location line="+12"/> <source>ClubCoin-Qt</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>version</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Usage:</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>UI options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation type="unfinished"/> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>Optiones</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation>&amp;Princeps</translation> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation>Solve &amp;mercedem transactionis</translation> </message> <message> <location line="+31"/> <source>Reserved amount does not participate in staking and is therefore spendable at any time.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Reserve</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Automatically start ClubCoin after logging in to the system.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Start ClubCoin on system login</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>&amp;Network</source> <translation>&amp;Rete</translation> </message> <message> <location line="+6"/> <source>Automatically open the ClubCoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation>Designa portam utendo &amp;UPnP</translation> </message> <message> <location line="+7"/> <source>Connect to the ClubCoin network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation>&amp;IP vicarii:</translation> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation>&amp;Porta:</translation> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation>Porta vicarii (e.g. 9050)</translation> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation>SOCKS &amp;Versio:</translation> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation>SOCKS versio vicarii (e.g. 5)</translation> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation>&amp;Fenestra</translation> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation>Monstra tantum iconem in tabella systematis postquam fenestram minifactam est.</translation> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>&amp;Minifac in tabellam systematis potius quam applicationum</translation> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation>Minifac potius quam exire applicatione quando fenestra clausa sit. Si haec optio activa est, applicatio clausa erit tantum postquam selegeris Exi in menu.</translation> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation>M&amp;inifac ad claudendum</translation> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation>&amp;UI</translation> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation>&amp;Lingua monstranda utenti:</translation> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting ClubCoin.</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation>&amp;Unita qua quantitates monstrare:</translation> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>Selige praedefinitam unitam subdivisionis monstrare in interfacie et quando nummos mittere</translation> </message> <message> <location line="+9"/> <source>Whether to show coin control features or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Display coin &amp;control features (experts only!)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Whether to select the coin outputs randomly or with minimal coin age.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Minimize weight consumption (experimental)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Use black visual theme (requires restart)</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation>&amp;OK</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>&amp;Cancella</translation> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="+53"/> <source>default</source> <translation>praedefinitum</translation> </message> <message> <location line="+149"/> <location line="+9"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting ClubCoin.</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation>Inscriptio vicarii tradita non valida est.</translation> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>Schema</translation> </message> <message> <location line="+46"/> <location line="+247"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the ClubCoin network after a connection is established, but this process has not completed yet.</source> <translation type="unfinished"/> </message> <message> <location line="-173"/> <source>Stake:</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Unconfirmed:</source> <translation type="unfinished"/> </message> <message> <location line="-113"/> <source>Wallet</source> <translation>Cassidile</translation> </message> <message> <location line="+49"/> <source>Spendable:</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Your current spendable balance</source> <translation type="unfinished"/> </message> <message> <location line="+80"/> <source>Immature:</source> <translation>Immatura:</translation> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation>Fossum pendendum quod nondum maturum est</translation> </message> <message> <location line="+23"/> <source>Total:</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Your current total balance</source> <translation type="unfinished"/> </message> <message> <location line="+50"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Recentes transactiones&lt;/b&gt;</translation> </message> <message> <location line="-118"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation type="unfinished"/> </message> <message> <location line="-32"/> <source>Total of coins that was staked, and do not yet count toward the current balance</source> <translation type="unfinished"/> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation>non synchronizato</translation> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+107"/> <source>Cannot start blackcoin: click-to-pay handler</source> <translation type="unfinished"/> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation type="unfinished"/> </message> <message> <location line="+56"/> <source>Amount:</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>Label:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Message:</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation type="unfinished"/> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation type="unfinished"/> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation>Nomen clientis</translation> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <source>N/A</source> <translation>N/A</translation> </message> <message> <location line="-194"/> <source>Client version</source> <translation>Versio clientis</translation> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation>&amp;Informatio</translation> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation>Utens OpenSSL versione</translation> </message> <message> <location line="+49"/> <source>Startup time</source> <translation>Tempus initiandi</translation> </message> <message> <location line="+29"/> <source>Network</source> <translation>Rete</translation> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation>Numerus conexionum</translation> </message> <message> <location line="+23"/> <source>On testnet</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Block chain</source> <translation>Catena frustorum</translation> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation>Numerus frustorum iam nunc</translation> </message> <message> <location line="+197"/> <source>&amp;Network Traffic</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>&amp;Clear</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Totals</source> <translation type="unfinished"/> </message> <message> <location line="+64"/> <source>In:</source> <translation type="unfinished"/> </message> <message> <location line="+80"/> <source>Out:</source> <translation type="unfinished"/> </message> <message> <location line="-383"/> <source>Last block time</source> <translation>Hora postremi frusti</translation> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation>&amp;Aperi</translation> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Show the ClubCoin-Qt help message to get a list with possible ClubCoin command-line options.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation>&amp;Terminale</translation> </message> <message> <location line="-237"/> <source>Build date</source> <translation>Dies aedificandi</translation> </message> <message> <location line="-104"/> <source>ClubCoin - Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>ClubCoin Core</source> <translation type="unfinished"/> </message> <message> <location line="+256"/> <source>Debug log file</source> <translation>Debug catalogi plica</translation> </message> <message> <location line="+7"/> <source>Open the ClubCoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation type="unfinished"/> </message> <message> <location line="+102"/> <source>Clear console</source> <translation>Vacuefac terminale</translation> </message> <message> <location filename="../rpcconsole.cpp" line="+325"/> <source>Welcome to the ClubCoin RPC console.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation>Utere sagittis sursum deorsumque ut per historiam naviges, et &lt;b&gt;Ctrl+L&lt;/b&gt; ut scrinium vacuefacias.</translation> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation>Scribe &lt;b&gt;help&lt;/b&gt; pro summario possibilium mandatorum.</translation> </message> <message> <location line="+127"/> <source>%1 B</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 KB</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 MB</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 GB</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>%1 m</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>%1 h</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 h %2 m</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+181"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation>Mitte Nummos</translation> </message> <message> <location line="+76"/> <source>Coin Control Features</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>Inputs...</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>automatically selected</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Insufficient funds!</source> <translation type="unfinished"/> </message> <message> <location line="+77"/> <source>Quantity:</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <location line="+35"/> <source>0</source> <translation type="unfinished"/> </message> <message> <location line="-19"/> <source>Bytes:</source> <translation type="unfinished"/> </message> <message> <location line="+51"/> <source>Amount:</source> <translation>Quantitas:</translation> </message> <message> <location line="+22"/> <location line="+86"/> <location line="+86"/> <location line="+32"/> <source>0.00 CC</source> <translation type="unfinished"/> </message> <message> <location line="-191"/> <source>Priority:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>medium</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Low Output:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>no</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>After Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Change</source> <translation type="unfinished"/> </message> <message> <location line="+50"/> <source>custom change address</source> <translation type="unfinished"/> </message> <message> <location line="+106"/> <source>Send to multiple recipients at once</source> <translation>Mitte pluribus accipientibus simul</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation>Adde &amp;Accipientem</translation> </message> <message> <location line="+16"/> <source>Remove all transaction fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation>Vacuefac &amp;Omnia</translation> </message> <message> <location line="+24"/> <source>Balance:</source> <translation>Pendendum:</translation> </message> <message> <location line="+16"/> <source>123.456 CC</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation>Confirma actionem mittendi</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>&amp;Mitte</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-173"/> <source>Enter a ClubCoin address (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Copy quantity</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Copia quantitatem</translation> </message> <message> <location line="+1"/> <source>Copy fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy after fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy bytes</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy priority</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy low output</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy change</source> <translation type="unfinished"/> </message> <message> <location line="+86"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation>Confirma mittendum nummorum</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source> and </source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The recipient address is not valid, please recheck.</source> <translation>Inscriptio accipientis non est valida, sodes reproba.</translation> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>Oportet quantitatem ad pensandum maiorem quam 0 esse.</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation>Quantitas est ultra quod habes.</translation> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>Quantitas est ultra quod habes cum merces transactionis %1 includitur.</translation> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation>Geminata inscriptio inventa, tantum posse mittere ad quamque inscriptionem semel singulare operatione.</translation> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed!</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="+247"/> <source>WARNING: Invalid ClubCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>(no label)</source> <translation>(nullus titulus)</translation> </message> <message> <location line="+4"/> <source>WARNING: unknown change address</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>&amp;Quantitas:</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>Pensa &amp;Ad:</translation> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source> <translation type="unfinished"/> </message> <message> <location line="+60"/> <location filename="../sendcoinsentry.cpp" line="+26"/> <source>Enter a label for this address to add it to your address book</source> <translation>Insero titulum huic inscriptioni ut eam in tuum librum inscriptionum addas.</translation> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation>&amp;Titulus:</translation> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation>Conglutina inscriptionem ex latibulo</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a ClubCoin address (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source> <translation type="unfinished"/> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation>Signationes - Signa / Verifica nuntium</translation> </message> <message> <location line="+13"/> <location line="+124"/> <source>&amp;Sign Message</source> <translation>&amp;Signa Nuntium</translation> </message> <message> <location line="-118"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation>Potes nuntios signare inscriptionibus tuis ut demonstres te eas possidere. Cautus es non amibiguum signare, quia impetus phiscatorum conentur te fallere ut signes identitatem tuam ad eos. Solas signa sententias cuncte descriptas quibus convenis.</translation> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+203"/> <source>Choose an address from the address book</source> <translation type="unfinished"/> </message> <message> <location line="-193"/> <location line="+203"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="-193"/> <source>Paste address from clipboard</source> <translation>Glutina inscriptionem ex latibulo</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation>Insere hic nuntium quod vis signare</translation> </message> <message> <location line="+24"/> <source>Copy the current signature to the system clipboard</source> <translation>Copia signationem in latibulum systematis</translation> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this ClubCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Reset all sign message fields</source> <translation>Reconstitue omnes campos signandi nuntii</translation> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation>Vacuefac &amp;Omnia</translation> </message> <message> <location line="-87"/> <location line="+70"/> <source>&amp;Verify Message</source> <translation>&amp;Verifica Nuntium</translation> </message> <message> <location line="-64"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation>Insere inscriptionem signantem, nuntium (cura ut copias intermissiones linearum, spatia, tabs, et cetera exacte) et signationem infra ut nuntium verifices. Cautus esto ne magis legas in signationem quam in nuntio signato ipso est, ut vites falli ab impetu homo-in-medio.</translation> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified ClubCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Reset all verify message fields</source> <translation>Reconstitue omnes campos verificandi nuntii</translation> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a ClubCoin address (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation>Clicca &quot;Signa Nuntium&quot; ut signatio generetur</translation> </message> <message> <location line="+3"/> <source>Enter ClubCoin signature</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation>Inscriptio inserta non valida est.</translation> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation>Sodes inscriptionem proba et rursus conare.</translation> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation>Inserta inscriptio clavem non refert.</translation> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation>Cassidilis reserare cancellatum est.</translation> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation>Clavis privata absens est pro inserta inscriptione.</translation> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation>Nuntium signare abortum est.</translation> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation>Nuntius signatus.</translation> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation>Signatio decodificari non potuit.</translation> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation>Sodes signationem proba et rursus conare.</translation> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation>Signatio non convenit digesto nuntii</translation> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation>Nuntium verificare abortum est.</translation> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation>Nuntius verificatus.</translation> </message> </context> <context> <name>TrafficGraphWidget</name> <message> <location filename="../trafficgraphwidget.cpp" line="+75"/> <source>KB/s</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+25"/> <source>Open until %1</source> <translation>Apertum donec %1</translation> </message> <message> <location line="+6"/> <source>conflicted</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1/offline</source> <translation>%1/non conecto</translation> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/non confirmata</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 confirmationes</translation> </message> <message> <location line="+17"/> <source>Status</source> <translation>Status</translation> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation><numerusform>, disseminatum per %n nodo</numerusform><numerusform>, disseminata per %n nodis</numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>Dies</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation>Fons</translation> </message> <message> <location line="+0"/> <source>Generated</source> <translation>Generatum</translation> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation>Ab</translation> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation>Ad</translation> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation>inscriptio propria</translation> </message> <message> <location line="-2"/> <source>label</source> <translation>titulus</translation> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation>Creditum</translation> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation><numerusform>maturum erit in %n plure frusto</numerusform><numerusform>maturum erit in %n pluribus frustis</numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation>non acceptum</translation> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation>Debitum</translation> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation>Transactionis merces</translation> </message> <message> <location line="+16"/> <source>Net amount</source> <translation>Cuncta quantitas</translation> </message> <message> <location line="+6"/> <source>Message</source> <translation>Nuntius</translation> </message> <message> <location line="+2"/> <source>Comment</source> <translation>Annotatio</translation> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation>ID transactionis</translation> </message> <message> <location line="+3"/> <source>Generated coins must mature 101 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Debug information</source> <translation>Informatio de debug</translation> </message> <message> <location line="+8"/> <source>Transaction</source> <translation>Transactio</translation> </message> <message> <location line="+5"/> <source>Inputs</source> <translation>Lectenda</translation> </message> <message> <location line="+21"/> <source>Amount</source> <translation>Quantitas</translation> </message> <message> <location line="+1"/> <source>true</source> <translation>verum</translation> </message> <message> <location line="+0"/> <source>false</source> <translation>falsum</translation> </message> <message> <location line="-209"/> <source>, has not been successfully broadcast yet</source> <translation>, nondum prospere disseminatum est</translation> </message> <message numerus="yes"> <location line="-36"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+71"/> <source>unknown</source> <translation>ignotum</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>Particularia transactionis</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>Haec tabula monstrat descriptionem verbosam transactionis</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+231"/> <source>Date</source> <translation>Dies</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>Typus</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Inscriptio</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>Quantitas</translation> </message> <message> <location line="+52"/> <source>Open until %1</source> <translation>Apertum donec %1</translation> </message> <message> <location line="+12"/> <source>Confirmed (%1 confirmations)</source> <translation>Confirmatum (%1 confirmationes)</translation> </message> <message numerus="yes"> <location line="-15"/> <source>Open for %n more block(s)</source> <translation><numerusform>Aperi pro %n plure frusto</numerusform><numerusform>Aperi pro %n pluribus frustis</numerusform></translation> </message> <message> <location line="+6"/> <source>Offline</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Unconfirmed</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Confirming (%1 of %2 recommended confirmations)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Conflicted</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Immature (%1 confirmations, will be available after %2)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>Hoc frustum non acceptum est ab ulla alia nodis et probabiliter non acceptum erit!</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>Generatum sed non acceptum</translation> </message> <message> <location line="+42"/> <source>Received with</source> <translation>Acceptum cum</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>Acceptum ab</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>Missum ad</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>Pensitatio ad te ipsum</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>Fossa</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>(n/a)</translation> </message> <message> <location line="+194"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Status transactionis. Supervola cum mure ut monstretur numerus confirmationum.</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>Dies et tempus quando transactio accepta est.</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>Typus transactionis.</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>Inscriptio destinationis transactionis.</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>Quantitas remota ex pendendo aut addita ei.</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+54"/> <location line="+17"/> <source>All</source> <translation>Omne</translation> </message> <message> <location line="-16"/> <source>Today</source> <translation>Hodie</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>Hac hebdomade</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>Hoc mense</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>Postremo mense</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>Hoc anno</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>Intervallum...</translation> </message> <message> <location line="+12"/> <source>Received with</source> <translation>Acceptum cum</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>Missum ad</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>Ad te ipsum</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>Fossa</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>Alia</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>Insere inscriptionem vel titulum ut quaeras</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>Quantitas minima</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>Copia inscriptionem</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Copia titulum</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Copia quantitatem</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation>Copia transactionis ID</translation> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>Muta titulum</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation>Monstra particularia transactionis</translation> </message> <message> <location line="+138"/> <source>Export Transaction Data</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Comma Separata Plica (*.csv)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>Confirmatum</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>Dies</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>Typus</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>Titulus</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>Inscriptio</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>Quantitas</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>ID</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <source>Range:</source> <translation>Intervallum:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>ad</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+208"/> <source>Sending...</source> <translation type="unfinished"/> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+173"/> <source>ClubCoin version</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Usage:</source> <translation>Usus:</translation> </message> <message> <location line="+1"/> <source>Send command to -server or blackcoind</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>List commands</source> <translation>Enumera mandata</translation> </message> <message> <location line="+1"/> <source>Get help for a command</source> <translation>Accipe auxilium pro mandato</translation> </message> <message> <location line="-147"/> <source>Options:</source> <translation>Optiones:</translation> </message> <message> <location line="+2"/> <source>Specify configuration file (default: blackcoin.conf)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Specify pid file (default: blackcoind.pid)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify wallet file (within data directory)</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>Specifica indicem datorum</translation> </message> <message> <location line="-25"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=blackcoinrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;ClubCoin Alert&quot; admin@foo.com </source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Set database cache size in megabytes (default: 25)</source> <translation>Constitue magnitudinem databasis cache in megabytes (praedefinitum: 25)</translation> </message> <message> <location line="+1"/> <source>Set database disk log size in megabytes (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Listen for connections on &lt;port&gt; (default: 15714 or testnet: 25714)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>Manutene non plures quam &lt;n&gt; conexiones ad paria (praedefinitum: 125)</translation> </message> <message> <location line="+3"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation>Conecta ad nodum acceptare inscriptiones parium, et disconecte</translation> </message> <message> <location line="+1"/> <source>Specify your own public address</source> <translation>Specifica tuam propriam publicam inscriptionem</translation> </message> <message> <location line="+4"/> <source>Bind to given address. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Always query for peer addresses via DNS lookup (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>Limen pro disconectendo paria improba (praedefinitum: 100)</translation> </message> <message> <location line="+1"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>Numerum secundorum prohibere ne paria improba reconectant (praedefinitum: 86400)</translation> </message> <message> <location line="-37"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation>Error erat dum initians portam RPC %u pro auscultando in IPv4: %s</translation> </message> <message> <location line="+65"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 15715 or testnet: 25715)</source> <translation type="unfinished"/> </message> <message> <location line="-17"/> <source>Accept command line and JSON-RPC commands</source> <translation>Accipe terminalis et JSON-RPC mandata.</translation> </message> <message> <location line="+1"/> <source>Run in the background as a daemon and accept commands</source> <translation>Operare infere sicut daemon et mandata accipe</translation> </message> <message> <location line="+1"/> <source>Use the test network</source> <translation>Utere rete experimentale</translation> </message> <message> <location line="-24"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation>Accipe conexiones externas (praedefinitum: 1 nisi -proxy neque -connect)</translation> </message> <message> <location line="-29"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation>Error erat dum initians portam RPC %u pro auscultando in IPv6, labens retrorsum ad IPv4: %s</translation> </message> <message> <location line="+96"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation>Monitio: -paytxfee constitutum valde magnum! Hoc est merces transactionis solves si mittis transactionem.</translation> </message> <message> <location line="-103"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong ClubCoin will not work properly.</source> <translation type="unfinished"/> </message> <message> <location line="+132"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation>Monitio: error legendo wallet.dat! Omnes claves recte lectae, sed data transactionum vel libri inscriptionum fortasse desint vel prava sint.</translation> </message> <message> <location line="-18"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation>Monitio: wallet.data corrupta, data salvata! Originalis wallet.dat salvata ut wallet.{timestamp}.bak in %s; si pendendum tuum vel transactiones pravae sunt, oportet ab conservato restituere.</translation> </message> <message> <location line="-31"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation>Conare recipere claves privatas de corrupto wallet.dat</translation> </message> <message> <location line="+5"/> <source>Block creation options:</source> <translation>Optiones creandi frustorum:</translation> </message> <message> <location line="-69"/> <source>Connect only to the specified node(s)</source> <translation>Conecte sole ad nodos specificatos (vel nodum specificatum)</translation> </message> <message> <location line="+4"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation>Discooperi propriam inscriptionem IP (praedefinitum: 1 quando auscultans et nullum -externalip)</translation> </message> <message> <location line="+101"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation>Non potuisse auscultare in ulla porta. Utere -listen=0 si hoc vis.</translation> </message> <message> <location line="-91"/> <source>Sync checkpoints policy (default: strict)</source> <translation type="unfinished"/> </message> <message> <location line="+89"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Invalid amount for -reservebalance=&lt;amount&gt;</source> <translation type="unfinished"/> </message> <message> <location line="-88"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation>Maxima magnitudo memoriae pro datis accipendis singulis conexionibus, &lt;n&gt;*1000 octetis/bytes (praedefinitum: 5000)</translation> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation>Maxima magnitudo memoriae pro datis mittendis singulis conexionibus, &lt;n&gt;*1000 octetis/bytes (praedefinitum: 1000)</translation> </message> <message> <location line="-17"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation>Tantum conecte ad nodos in rete &lt;net&gt; (IPv4, IPv6 aut Tor)</translation> </message> <message> <location line="+31"/> <source>Prepend debug output with timestamp</source> <translation type="unfinished"/> </message> <message> <location line="+41"/> <source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source> <translation>Optiones SSL: (vide vici de Bitcoin pro instructionibus SSL configurationis)</translation> </message> <message> <location line="-81"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation type="unfinished"/> </message> <message> <location line="+42"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>Mitte informationem vestigii/debug ad terminale potius quam plicam debug.log</translation> </message> <message> <location line="+5"/> <source>Send trace/debug info to debugger</source> <translation type="unfinished"/> </message> <message> <location line="+30"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation>Constitue minimam magnitudinem frusti in octetis/bytes (praedefinitum: 0)</translation> </message> <message> <location line="-35"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation>Diminue plicam debug.log ad initium clientis (praedefinitum: 1 nisi -debug)</translation> </message> <message> <location line="-43"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation>Specifica tempumfati conexionis in millisecundis (praedefinitum: 5000)</translation> </message> <message> <location line="+116"/> <source>Unable to sign checkpoint, wrong checkpointkey? </source> <translation type="unfinished"/> </message> <message> <location line="-86"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation>Utere UPnP designare portam auscultandi (praedefinitum: 0)</translation> </message> <message> <location line="-1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation>Utere UPnP designare portam auscultandi (praedefinitum: 1 quando auscultans)</translation> </message> <message> <location line="-26"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation type="unfinished"/> </message> <message> <location line="+47"/> <source>Username for JSON-RPC connections</source> <translation>Nomen utentis pro conexionibus JSON-RPC</translation> </message> <message> <location line="+51"/> <source>Verifying database integrity...</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Error: Transaction creation failed!</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>WARNING: syncronized checkpoint violation detected, but skipped!</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation>Monitio: Haec versio obsoleta est, progressio postulata!</translation> </message> <message> <location line="-54"/> <source>wallet.dat corrupt, salvage failed</source> <translation>wallet.dat corrupta, salvare abortum est</translation> </message> <message> <location line="-56"/> <source>Password for JSON-RPC connections</source> <translation>Tessera pro conexionibus JSON-RPC</translation> </message> <message> <location line="-32"/> <source>Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>When creating transactions, ignore inputs with value less than this (default: 0.01)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Output debugging information (default: 0, supplying &lt;category&gt; is optional)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>If &lt;category&gt; is not supplied, output all debugging information.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>&lt;category&gt; can be:</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Enter regression test mode, which uses a special chain in which blocks can be solved instantly. This is intended for regression testing tools and app development.</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>Permitte conexionibus JSON-RPC ex inscriptione specificata</translation> </message> <message> <location line="+1"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>Mitte mandata nodo operanti in &lt;ip&gt; (praedefinitum: 127.0.0.1)</translation> </message> <message> <location line="+1"/> <source>Wait for RPC server to start</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation>Pelle mandatum quando optissimum frustum mutat (%s in mandato substituitur ab hash frusti)</translation> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation>Facere mandatum quotiescumque cassidilis transactio mutet (%s in mandato sbstituitur ab TxID)</translation> </message> <message> <location line="+3"/> <source>Require a confirmations for change (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Upgrade wallet to latest format</source> <translation>Progredere cassidile ad formam recentissimam</translation> </message> <message> <location line="+1"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>Constitue magnitudinem stagni clavium ad &lt;n&gt; (praedefinitum: 100)</translation> </message> <message> <location line="+1"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>Iterum perlege catenam frustorum propter absentes cassidilis transactiones</translation> </message> <message> <location line="+3"/> <source>How thorough the block verification is (0-6, default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Imports blocks from external blk000?.dat file</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>Utere OpenSSL (https) pro conexionibus JSON-RPC</translation> </message> <message> <location line="+1"/> <source>Server certificate file (default: server.cert)</source> <translation>Plica certificationis daemonis moderantis (praedefinitum: server.cert)</translation> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation>Clavis privata daemonis moderans (praedefinitum: server.pem)</translation> </message> <message> <location line="+10"/> <source>Initialization sanity check failed. ClubCoin is shutting down.</source> <translation type="unfinished"/> </message> <message> <location line="+50"/> <source>Error: Wallet unlocked for staking only, unable to create transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Error: Disk space is low!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.</source> <translation type="unfinished"/> </message> <message> <location line="-174"/> <source>This help message</source> <translation>Hic nuntius auxilii</translation> </message> <message> <location line="+104"/> <source>Wallet %s resides outside data directory %s.</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation>Non posse conglutinare ad %s in hoc computatro (conglutinare redidit errorem %d, %s)</translation> </message> <message> <location line="-133"/> <source>Connect through socks proxy</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>Permitte quaerenda DNS pro -addnode, -seednode, et -connect</translation> </message> <message> <location line="+126"/> <source>Loading addresses...</source> <translation>Legens inscriptiones...</translation> </message> <message> <location line="-12"/> <source>Error loading blkindex.dat</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>Error legendi wallet.dat: Cassidile corruptum</translation> </message> <message> <location line="+4"/> <source>Error loading wallet.dat: Wallet requires newer version of ClubCoin</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Wallet needed to be rewritten: restart ClubCoin to complete</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading wallet.dat</source> <translation>Error legendi wallet.dat</translation> </message> <message> <location line="-16"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation>Inscriptio -proxy non valida: &apos;%s&apos;</translation> </message> <message> <location line="-1"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation>Ignotum rete specificatum in -onlynet: &apos;%s&apos;</translation> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation>Ignota -socks vicarii versio postulata: %i</translation> </message> <message> <location line="+4"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation>Non posse resolvere -bind inscriptonem: &apos;%s&apos;</translation> </message> <message> <location line="+2"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation>Non posse resolvere -externalip inscriptionem: &apos;%s&apos;</translation> </message> <message> <location line="-23"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Quantitas non valida pro -paytxfee=&lt;quantitas&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+60"/> <source>Sending...</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Invalid amount</source> <translation>Quantitas non valida</translation> </message> <message> <location line="+1"/> <source>Insufficient funds</source> <translation>Inopia nummorum</translation> </message> <message> <location line="-40"/> <source>Loading block index...</source> <translation>Legens indicem frustorum...</translation> </message> <message> <location line="-110"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>Adice nodum cui conectere et conare sustinere conexionem apertam</translation> </message> <message> <location line="+125"/> <source>Unable to bind to %s on this computer. ClubCoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="-101"/> <source>Fee per KB to add to transactions you send</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>Minimize weight consumption (experimental) (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>How many blocks to check at startup (default: 500, 0 = all)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Keep at most &lt;n&gt; unconnectable blocks in memory (default: %u)</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Acceptable ciphers (default: TLSv1.2+HIGH:TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: Deprecated argument -debugnet ignored, use -debug=net</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Invalid amount for -mininput=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. ClubCoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error initializing wallet database environment %s!</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Loading wallet...</source> <translation>Legens cassidile...</translation> </message> <message> <location line="+8"/> <source>Cannot downgrade wallet</source> <translation>Non posse cassidile regredi</translation> </message> <message> <location line="+1"/> <source>Cannot write default address</source> <translation>Non posse scribere praedefinitam inscriptionem</translation> </message> <message> <location line="+1"/> <source>Rescanning...</source> <translation>Iterum perlegens...</translation> </message> <message> <location line="+2"/> <source>Done loading</source> <translation>Completo lengendi</translation> </message> <message> <location line="-161"/> <source>To use the %s option</source> <translation>Ut utaris optione %s</translation> </message> <message> <location line="+188"/> <source>Error</source> <translation>Error</translation> </message> <message> <location line="-18"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation>Necesse est te rpcpassword=&lt;tesseram&gt; constituere in plica configurationum: %s Si plica non existat, crea eam cum permissionibus ut solus eius dominus eam legere sinatur.</translation> </message> </context> </TS>
mit
rabbanyk/CommunityEvaluation
libs/matrix-toolkits-java-mtj-1.0.1/src/main/java/no/uib/cipr/matrix/sparse/ArpackSym.java
4783
package no.uib.cipr.matrix.sparse; import com.github.fommil.netlib.ARPACK; import lombok.extern.java.Log; import no.uib.cipr.matrix.*; import org.netlib.util.doubleW; import org.netlib.util.intW; import java.util.Comparator; import java.util.Map; import java.util.TreeMap; /** * Uses ARPACK to partially solve symmetric eigensystems * (ARPACK is designed to compute a subset of eigenvalues/eigenvectors). * * @author Sam Halliday */ @Log public class ArpackSym { public enum Ritz { /** * compute the NEV largest (algebraic) eigenvalues. */ LA, /** * compute the NEV smallest (algebraic) eigenvalues. */ SA, /** * compute the NEV largest (in magnitude) eigenvalues. */ LM, /** * compute the NEV smallest (in magnitude) eigenvalues. */ SM, /** * compute NEV eigenvalues, half from each end of the spectrum */ BE } private final ARPACK arpack = ARPACK.getInstance(); private static final double TOL = 0.0001; private static final boolean EXPENSIVE_CHECKS = true; private final Matrix matrix; public ArpackSym(Matrix matrix) { if (!matrix.isSquare()) throw new IllegalArgumentException("matrix must be square"); if (EXPENSIVE_CHECKS) for (MatrixEntry entry : matrix) { if (entry.get() != matrix.get(entry.column(), entry.row())) throw new IllegalArgumentException("matrix must be symmetric"); } this.matrix = matrix; } /** * Solve the eigensystem for the number of eigenvalues requested. * <p> * NOTE: The references to the eigenvectors will keep alive a reference to * a {@code nev * n} double array, so use the {@code copy()} method to free * it up if only a subset is required. * * @param eigenvalues * @param ritz preference for solutions * @return a map from eigenvalues to corresponding eigenvectors. */ public Map<Double, DenseVectorSub> solve(int eigenvalues, Ritz ritz) { if (eigenvalues <= 0) throw new IllegalArgumentException(eigenvalues + " <= 0"); if (eigenvalues >= matrix.numColumns()) throw new IllegalArgumentException(eigenvalues + " >= " + (matrix.numColumns())); int n = matrix.numRows(); intW nev = new intW(eigenvalues); int ncv = Math.min(2 * eigenvalues, n); String bmat = "I"; String which = ritz.name(); doubleW tol = new doubleW(TOL); intW info = new intW(0); int[] iparam = new int[11]; iparam[0] = 1; iparam[2] = 300; iparam[6] = 1; intW ido = new intW(0); // used for initial residual (if info != 0) // and eventually the output residual double[] resid = new double[n]; // Lanczos basis vectors double[] v = new double[n * ncv]; // Arnoldi reverse communication double[] workd = new double[3 * n]; // private work array double[] workl = new double[ncv * (ncv + 8)]; int[] ipntr = new int[11]; int i = 0; while (true) { i++; arpack.dsaupd(ido, bmat, n, which, nev.val, tol, resid, ncv, v, n, iparam, ipntr, workd, workl, workl.length, info); if (ido.val == 99) break; if (ido.val != -1 && ido.val != 1) throw new IllegalStateException("ido = " + ido.val); // could be refactored to handle the other types of mode av(workd, ipntr[0] - 1, ipntr[1] - 1); } ArpackSym.log.fine(i + " iterations for " + n); if (info.val != 0) throw new IllegalStateException("info = " + info.val); double[] d = new double[nev.val]; boolean[] select = new boolean[ncv]; double[] z = java.util.Arrays.copyOfRange(v, 0, nev.val * n); arpack.dseupd(true, "A", select, d, z, n, 0, bmat, n, which, nev, TOL, resid, ncv, v, n, iparam, ipntr, workd, workl, workl.length, info); if (info.val != 0) throw new IllegalStateException("info = " + info.val); int computed = iparam[4]; ArpackSym.log.fine("computed " + computed + " eigenvalues"); Map<Double, DenseVectorSub> solution = new TreeMap<Double, DenseVectorSub>(new Comparator<Double>() { @Override public int compare(Double o1, Double o2) { // highest first return Double.compare(o2, o1); } }); DenseVector eigenvectors = new DenseVector(z, false); for (i = 0; i < computed; i++) { double eigenvalue = d[i]; DenseVectorSub eigenvector = new DenseVectorSub(eigenvectors, i * n, n); solution.put(eigenvalue, eigenvector); } return solution; } private void av(double[] work, int input_offset, int output_offset) { DenseVector w = new DenseVector(work, false); Vector x = new DenseVectorSub(w, input_offset, matrix.numColumns()); Vector y = new DenseVectorSub(w, output_offset, matrix.numColumns()); matrix.mult(x, y); } }
mit
Carlodeboer/GFY1-03
Opleveren/Code/Website/admin/contentbeheer.php
1597
<?php /******************************************************************************* * Copyright (c) 2017 Carlo de Boer, Floris de Grip, Thijs Marschalk, * Ralphine de Roo, Sophie Roos and Ian Vredenburg * * This Source Code Form is subject to the terms of the MIT license. * If a copy of the MIT license was not distributed with this file. You can * obtain one at https://opensource.org/licenses/MIT *******************************************************************************/ ?> <?php include "../toegang.php"; ?> <br><br> <div id="contentwrapper"> <form method="get" action="beheerpaneel.php?beheer=Content"> <div class="form-group"> <label for="select111" class="col-md-2 control-label">Pagina</label> <div class="col-md-10"> <select name="pagina" id="select111" class="form-control"> <option value="index">Thuispagina</option> <option value="informatie">Accommodatie</option> <option value="prijzen">Prijzen</option> </select> </div> </div> <div class="form-group"> <label for="select111" class="col-md-2 control-label">Taal</label> <div class="col-md-10"> <select name="taal" id="select111" class="form-control"> <option value="NLD">Nederlands</option> <option value="ENG">Engels</option> <option value="DEU">Duits</option> </select> </div> </div> <input type="submit" name="selecteerContent" value="Kies" class="btn btn-raised btn-primary"> </form> </div>
mit
alwintje/school-pvb
src/UserBundle/Entity/UserRepository.php
2053
<?php namespace UserBundle\Entity; use Symfony\Bridge\Doctrine\Security\User\UserLoaderInterface; use Symfony\Component\Security\Core\User\UserInterface; use Symfony\Component\Security\Core\User\UserProviderInterface; use Symfony\Component\Security\Core\Exception\UsernameNotFoundException; use Symfony\Component\Security\Core\Exception\UnsupportedUserException; use Doctrine\ORM\EntityRepository; use Doctrine\ORM\NoResultException; /** * UserRepository * * This class was generated by the Doctrine ORM. Add your own custom * repository methods below. */ class UserRepository extends EntityRepository implements UserProviderInterface, UserLoaderInterface { public function loadUserByUsername($username) { $q = $this ->createQueryBuilder('u') ->select('u, r') ->leftJoin('u.roles', 'r') ->where('u.username = :username OR u.email = :username') ->setParameter('username', $username) ->getQuery(); try { // The Query::getSingleResult() method throws an exception // if there is no record matching the criteria. $user = $q->getSingleResult(); } catch (NoResultException $e) { $message = sprintf( 'Unable to find an active admin UserBundle:User object identified by "%s".', $username ); throw new UsernameNotFoundException($message, 0, $e); } return $user; } public function refreshUser(UserInterface $user) { $class = get_class($user); if (!$this->supportsClass($class)) { throw new UnsupportedUserException( sprintf( 'Instances of "%s" are not supported.', $class ) ); } return $this->find($user->getId()); } public function supportsClass($class) { return $this->getEntityName() === $class || is_subclass_of($class, $this->getEntityName()); } }
mit
aleacoin/aleacoin-release
src/rpcrawtransaction.cpp
20286
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <boost/assign/list_of.hpp> #include "base58.h" #include "bitcoinrpc.h" #include "txdb.h" #include "init.h" #include "main.h" #include "net.h" #include "wallet.h" using namespace std; using namespace boost; using namespace boost::assign; using namespace json_spirit; void ScriptPubKeyToJSON(const CScript& scriptPubKey, Object& out, bool fIncludeHex) { txnouttype type; vector<CTxDestination> addresses; int nRequired; out.push_back(Pair("asm", scriptPubKey.ToString())); if (fIncludeHex) out.push_back(Pair("hex", HexStr(scriptPubKey.begin(), scriptPubKey.end()))); if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired)) { out.push_back(Pair("type", GetTxnOutputType(TX_NONSTANDARD))); return; } out.push_back(Pair("reqSigs", nRequired)); out.push_back(Pair("type", GetTxnOutputType(type))); Array a; BOOST_FOREACH(const CTxDestination& addr, addresses) a.push_back(CBitcoinAddress(addr).ToString()); out.push_back(Pair("addresses", a)); } void TxToJSON(const CTransaction& tx, const uint256 hashBlock, Object& entry) { entry.push_back(Pair("txid", tx.GetHash().GetHex())); entry.push_back(Pair("version", tx.nVersion)); entry.push_back(Pair("time", (boost::int64_t)tx.nTime)); entry.push_back(Pair("locktime", (boost::int64_t)tx.nLockTime)); Array vin; BOOST_FOREACH(const CTxIn& txin, tx.vin) { Object in; if (tx.IsCoinBase()) in.push_back(Pair("coinbase", HexStr(txin.scriptSig.begin(), txin.scriptSig.end()))); else { in.push_back(Pair("txid", txin.prevout.hash.GetHex())); in.push_back(Pair("vout", (boost::int64_t)txin.prevout.n)); Object o; o.push_back(Pair("asm", txin.scriptSig.ToString())); o.push_back(Pair("hex", HexStr(txin.scriptSig.begin(), txin.scriptSig.end()))); in.push_back(Pair("scriptSig", o)); } in.push_back(Pair("sequence", (boost::int64_t)txin.nSequence)); vin.push_back(in); } entry.push_back(Pair("vin", vin)); Array vout; for (unsigned int i = 0; i < tx.vout.size(); i++) { const CTxOut& txout = tx.vout[i]; Object out; out.push_back(Pair("value", ValueFromAmount(txout.nValue))); out.push_back(Pair("n", (boost::int64_t)i)); Object o; ScriptPubKeyToJSON(txout.scriptPubKey, o, false); out.push_back(Pair("scriptPubKey", o)); vout.push_back(out); } entry.push_back(Pair("vout", vout)); if (hashBlock != 0) { entry.push_back(Pair("blockhash", hashBlock.GetHex())); map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock); if (mi != mapBlockIndex.end() && (*mi).second) { CBlockIndex* pindex = (*mi).second; if (pindex->IsInMainChain()) { entry.push_back(Pair("confirmations", 1 + nBestHeight - pindex->nHeight)); entry.push_back(Pair("time", (boost::int64_t)pindex->nTime)); entry.push_back(Pair("blocktime", (boost::int64_t)pindex->nTime)); } else entry.push_back(Pair("confirmations", 0)); } } } Value getrawtransaction(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getrawtransaction <txid> [verbose=0]\n" "If verbose=0, returns a string that is\n" "serialized, hex-encoded data for <txid>.\n" "If verbose is non-zero, returns an Object\n" "with information about <txid>."); uint256 hash; hash.SetHex(params[0].get_str()); bool fVerbose = false; if (params.size() > 1) fVerbose = (params[1].get_int() != 0); CTransaction tx; uint256 hashBlock = 0; if (!GetTransaction(hash, tx, hashBlock)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction"); CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << tx; string strHex = HexStr(ssTx.begin(), ssTx.end()); if (!fVerbose) return strHex; Object result; result.push_back(Pair("hex", strHex)); TxToJSON(tx, hashBlock, result); return result; } Value listunspent(const Array& params, bool fHelp) { if (fHelp || params.size() > 3) throw runtime_error( "listunspent [minconf=1] [maxconf=9999999] [\"address\",...]\n" "Returns array of unspent transaction outputs\n" "with between minconf and maxconf (inclusive) confirmations.\n" "Optionally filtered to only include txouts paid to specified addresses.\n" "Results are an array of Objects, each of which has:\n" "{txid, vout, scriptPubKey, amount, confirmations}"); RPCTypeCheck(params, list_of(int_type)(int_type)(array_type)); int nMinDepth = 1; if (params.size() > 0) nMinDepth = params[0].get_int(); int nMaxDepth = 9999999; if (params.size() > 1) nMaxDepth = params[1].get_int(); set<CBitcoinAddress> setAddress; if (params.size() > 2) { Array inputs = params[2].get_array(); BOOST_FOREACH(Value& input, inputs) { CBitcoinAddress address(input.get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid Aleacoin address: ")+input.get_str()); if (setAddress.count(address)) throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+input.get_str()); setAddress.insert(address); } } Array results; vector<COutput> vecOutputs; pwalletMain->AvailableCoins(vecOutputs, false); BOOST_FOREACH(const COutput& out, vecOutputs) { if (out.nDepth < nMinDepth || out.nDepth > nMaxDepth) continue; if(setAddress.size()) { CTxDestination address; if(!ExtractDestination(out.tx->vout[out.i].scriptPubKey, address)) continue; if (!setAddress.count(address)) continue; } int64_t nValue = out.tx->vout[out.i].nValue; const CScript& pk = out.tx->vout[out.i].scriptPubKey; Object entry; entry.push_back(Pair("txid", out.tx->GetHash().GetHex())); entry.push_back(Pair("vout", out.i)); CTxDestination address; if (ExtractDestination(out.tx->vout[out.i].scriptPubKey, address)) { entry.push_back(Pair("address", CBitcoinAddress(address).ToString())); if (pwalletMain->mapAddressBook.count(address)) entry.push_back(Pair("account", pwalletMain->mapAddressBook[address])); } entry.push_back(Pair("scriptPubKey", HexStr(pk.begin(), pk.end()))); entry.push_back(Pair("amount",ValueFromAmount(nValue))); entry.push_back(Pair("confirmations",out.nDepth)); results.push_back(entry); } return results; } Value createrawtransaction(const Array& params, bool fHelp) { if (fHelp || params.size() != 2) throw runtime_error( "createrawtransaction [{\"txid\":txid,\"vout\":n},...] {address:amount,...}\n" "Create a transaction spending given inputs\n" "(array of objects containing transaction id and output number),\n" "sending to given address(es).\n" "Returns hex-encoded raw transaction.\n" "Note that the transaction's inputs are not signed, and\n" "it is not stored in the wallet or transmitted to the network."); RPCTypeCheck(params, list_of(array_type)(obj_type)); Array inputs = params[0].get_array(); Object sendTo = params[1].get_obj(); CTransaction rawTx; BOOST_FOREACH(Value& input, inputs) { const Object& o = input.get_obj(); const Value& txid_v = find_value(o, "txid"); if (txid_v.type() != str_type) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing txid key"); string txid = txid_v.get_str(); if (!IsHex(txid)) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected hex txid"); const Value& vout_v = find_value(o, "vout"); if (vout_v.type() != int_type) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key"); int nOutput = vout_v.get_int(); if (nOutput < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive"); CTxIn in(COutPoint(uint256(txid), nOutput)); rawTx.vin.push_back(in); } set<CBitcoinAddress> setAddress; BOOST_FOREACH(const Pair& s, sendTo) { CBitcoinAddress address(s.name_); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid Aleacoin address: ")+s.name_); if (setAddress.count(address)) throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+s.name_); setAddress.insert(address); CScript scriptPubKey; scriptPubKey.SetDestination(address.Get()); int64_t nAmount = AmountFromValue(s.value_); CTxOut out(nAmount, scriptPubKey); rawTx.vout.push_back(out); } CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss << rawTx; return HexStr(ss.begin(), ss.end()); } Value decoderawtransaction(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "decoderawtransaction <hex string>\n" "Return a JSON object representing the serialized, hex-encoded transaction."); RPCTypeCheck(params, list_of(str_type)); vector<unsigned char> txData(ParseHex(params[0].get_str())); CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION); CTransaction tx; try { ssData >> tx; } catch (std::exception &e) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed"); } Object result; TxToJSON(tx, 0, result); return result; } Value decodescript(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "decodescript <hex string>\n" "Decode a hex-encoded script."); RPCTypeCheck(params, list_of(str_type)); Object r; CScript script; if (params[0].get_str().size() > 0){ vector<unsigned char> scriptData(ParseHexV(params[0], "argument")); script = CScript(scriptData.begin(), scriptData.end()); } else { // Empty scripts are valid } ScriptPubKeyToJSON(script, r, false); r.push_back(Pair("p2sh", CBitcoinAddress(script.GetID()).ToString())); return r; } Value signrawtransaction(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 4) throw runtime_error( "signrawtransaction <hex string> [{\"txid\":txid,\"vout\":n,\"scriptPubKey\":hex},...] [<privatekey1>,...] [sighashtype=\"ALL\"]\n" "Sign inputs for raw transaction (serialized, hex-encoded).\n" "Second optional argument (may be null) is an array of previous transaction outputs that\n" "this transaction depends on but may not yet be in the blockchain.\n" "Third optional argument (may be null) is an array of base58-encoded private\n" "keys that, if given, will be the only keys used to sign the transaction.\n" "Fourth optional argument is a string that is one of six values; ALL, NONE, SINGLE or\n" "ALL|ANYONECANPAY, NONE|ANYONECANPAY, SINGLE|ANYONECANPAY.\n" "Returns json object with keys:\n" " hex : raw transaction with signature(s) (hex-encoded string)\n" " complete : 1 if transaction has a complete set of signature (0 if not)" + HelpRequiringPassphrase()); RPCTypeCheck(params, list_of(str_type)(array_type)(array_type)(str_type), true); vector<unsigned char> txData(ParseHex(params[0].get_str())); CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION); vector<CTransaction> txVariants; while (!ssData.empty()) { try { CTransaction tx; ssData >> tx; txVariants.push_back(tx); } catch (std::exception &e) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed"); } } if (txVariants.empty()) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Missing transaction"); // mergedTx will end up with all the signatures; it // starts as a clone of the rawtx: CTransaction mergedTx(txVariants[0]); bool fComplete = true; // Fetch previous transactions (inputs): map<COutPoint, CScript> mapPrevOut; for (unsigned int i = 0; i < mergedTx.vin.size(); i++) { CTransaction tempTx; MapPrevTx mapPrevTx; CTxDB txdb("r"); map<uint256, CTxIndex> unused; bool fInvalid; // FetchInputs aborts on failure, so we go one at a time. tempTx.vin.push_back(mergedTx.vin[i]); tempTx.FetchInputs(txdb, unused, false, false, mapPrevTx, fInvalid); // Copy results into mapPrevOut: BOOST_FOREACH(const CTxIn& txin, tempTx.vin) { const uint256& prevHash = txin.prevout.hash; if (mapPrevTx.count(prevHash) && mapPrevTx[prevHash].second.vout.size()>txin.prevout.n) mapPrevOut[txin.prevout] = mapPrevTx[prevHash].second.vout[txin.prevout.n].scriptPubKey; } } // Add previous txouts given in the RPC call: if (params.size() > 1 && params[1].type() != null_type) { Array prevTxs = params[1].get_array(); BOOST_FOREACH(Value& p, prevTxs) { if (p.type() != obj_type) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "expected object with {\"txid'\",\"vout\",\"scriptPubKey\"}"); Object prevOut = p.get_obj(); RPCTypeCheck(prevOut, map_list_of("txid", str_type)("vout", int_type)("scriptPubKey", str_type)); string txidHex = find_value(prevOut, "txid").get_str(); if (!IsHex(txidHex)) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "txid must be hexadecimal"); uint256 txid; txid.SetHex(txidHex); int nOut = find_value(prevOut, "vout").get_int(); if (nOut < 0) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "vout must be positive"); string pkHex = find_value(prevOut, "scriptPubKey").get_str(); if (!IsHex(pkHex)) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "scriptPubKey must be hexadecimal"); vector<unsigned char> pkData(ParseHex(pkHex)); CScript scriptPubKey(pkData.begin(), pkData.end()); COutPoint outpoint(txid, nOut); if (mapPrevOut.count(outpoint)) { // Complain if scriptPubKey doesn't match if (mapPrevOut[outpoint] != scriptPubKey) { string err("Previous output scriptPubKey mismatch:\n"); err = err + mapPrevOut[outpoint].ToString() + "\nvs:\n"+ scriptPubKey.ToString(); throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err); } } else mapPrevOut[outpoint] = scriptPubKey; } } bool fGivenKeys = false; CBasicKeyStore tempKeystore; if (params.size() > 2 && params[2].type() != null_type) { fGivenKeys = true; Array keys = params[2].get_array(); BOOST_FOREACH(Value k, keys) { CBitcoinSecret vchSecret; bool fGood = vchSecret.SetString(k.get_str()); if (!fGood) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY,"Invalid private key"); CKey key; bool fCompressed; CSecret secret = vchSecret.GetSecret(fCompressed); key.SetSecret(secret, fCompressed); tempKeystore.AddKey(key); } } else EnsureWalletIsUnlocked(); const CKeyStore& keystore = (fGivenKeys ? tempKeystore : *pwalletMain); int nHashType = SIGHASH_ALL; if (params.size() > 3 && params[3].type() != null_type) { static map<string, int> mapSigHashValues = boost::assign::map_list_of (string("ALL"), int(SIGHASH_ALL)) (string("ALL|ANYONECANPAY"), int(SIGHASH_ALL|SIGHASH_ANYONECANPAY)) (string("NONE"), int(SIGHASH_NONE)) (string("NONE|ANYONECANPAY"), int(SIGHASH_NONE|SIGHASH_ANYONECANPAY)) (string("SINGLE"), int(SIGHASH_SINGLE)) (string("SINGLE|ANYONECANPAY"), int(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY)) ; string strHashType = params[3].get_str(); if (mapSigHashValues.count(strHashType)) nHashType = mapSigHashValues[strHashType]; else throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid sighash param"); } bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE); // Sign what we can: for (unsigned int i = 0; i < mergedTx.vin.size(); i++) { CTxIn& txin = mergedTx.vin[i]; if (mapPrevOut.count(txin.prevout) == 0) { fComplete = false; continue; } const CScript& prevPubKey = mapPrevOut[txin.prevout]; txin.scriptSig.clear(); // Only sign SIGHASH_SINGLE if there's a corresponding output: if (!fHashSingle || (i < mergedTx.vout.size())) SignSignature(keystore, prevPubKey, mergedTx, i, nHashType); // ... and merge in other signatures: BOOST_FOREACH(const CTransaction& txv, txVariants) { txin.scriptSig = CombineSignatures(prevPubKey, mergedTx, i, txin.scriptSig, txv.vin[i].scriptSig); } if (!VerifyScript(txin.scriptSig, prevPubKey, mergedTx, i, 0)) fComplete = false; } Object result; CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << mergedTx; result.push_back(Pair("hex", HexStr(ssTx.begin(), ssTx.end()))); result.push_back(Pair("complete", fComplete)); return result; } Value sendrawtransaction(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 1) throw runtime_error( "sendrawtransaction <hex string>\n" "Submits raw transaction (serialized, hex-encoded) to local node and network."); RPCTypeCheck(params, list_of(str_type)); // parse hex string from parameter vector<unsigned char> txData(ParseHex(params[0].get_str())); CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION); CTransaction tx; // deserialize binary data stream try { ssData >> tx; } catch (std::exception &e) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed"); } uint256 hashTx = tx.GetHash(); // See if the transaction is already in a block // or in the memory pool: CTransaction existingTx; uint256 hashBlock = 0; if (GetTransaction(hashTx, existingTx, hashBlock)) { if (hashBlock != 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("transaction already in block ")+hashBlock.GetHex()); // Not in block, but already in the memory pool; will drop // through to re-relay it. } else { // push to local node CTxDB txdb("r"); if (!tx.AcceptToMemoryPool(txdb)) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX rejected"); SyncWithWallets(tx, NULL, true); } RelayTransaction(tx, hashTx); return hashTx.GetHex(); }
mit
vi-kon/laravel-bootstrap
src/ViKon/Bootstrap/FormBuilder.php
10037
<?php namespace ViKon\Bootstrap; use Collective\Html\HtmlBuilder; use Illuminate\Database\Eloquent\Collection; use Illuminate\Session\Store; use Illuminate\Support\Arr; use Illuminate\Support\MessageBag; /** * Class FormBuilder * * @package ViKon\Bootstrap * * @author Kovács Vince<vincekovacs@hotmail.com> */ class FormBuilder { /** @type \Collective\Html\HtmlBuilder */ protected $html; /** @type \Collective\Html\FormBuilder */ protected $form; /** @type \Illuminate\Session\Store */ protected $session; /** * FormBuilder constructor. * * @param \Collective\Html\HtmlBuilder $html * @param \Collective\Html\FormBuilder $form */ public function __construct(HtmlBuilder $html, \Collective\Html\FormBuilder $form) { $this->html = $html; $this->form = $form; } /** * @param \Illuminate\Session\Store $session * * @return $this */ public function setSessionStore(Store $session) { $this->session = $session; return $this; } /** * Create text input field * * @param string $name * @param string|null $value * @param array $options * * @return string */ public function text($name, $value = null, array $options = []) { return $this->form->text($name, $value, $this->addFormControlClass($this->getFieldOptions($name, $options))); } /** * Create password field * * @param string $name * @param array $options * * @return string */ public function password($name, array $options = []) { return $this->form->password($name, $this->addFormControlClass($this->getFieldOptions($name, $options))); } /** * Create file field * * @param string $name * @param array $options * * @return string */ public function file($name, array $options = []) { return $this->form->file($name, $this->addFormControlClass($this->getFieldOptions($name, $options))); } /** * Create textarea * * @param string $name * @param string|null $value * @param array $options * * @return string */ public function textarea($name, $value = null, array $options = []) { return $this->form->textarea($name, $value, $this->addFormControlClass($this->getFieldOptions($name, $options))); } /** * @param string $name * @param array $list * @param array|null $selected * @param array $options * * @return string */ public function select($name, array $list = [], $selected = null, array $options = []) { return $this->form->select($name, $list, $selected, $this->addFormControlClass($this->getFieldOptions($name, $options))); } /** * @param string $name * @param string|int $value * @param bool|null $checked * @param array $options * * @return string */ public function checkbox($name, $value = 1, $checked = null, array $options = []) { $field = $this->form->checkbox($name, $value, $checked, $this->getFieldOptions($name, $options)); if ((bool)Arr::get($options, 'inline', false)) { return '<label class="checkbox-inline">' . $field . Arr::get($options, 'content', '') . '</label>'; } return '<div class="checkbox"><label>' . $field . Arr::get($options, 'content', '') . '</label></div>'; } /** * Create token input field * * @param string $name * @param string $url * @param null $value * @param array $options * * @return string */ public function tokenInput($name, $url, $value = null, array $options = []) { $script = '<script type="text/javascript"> (function ($, undefined) { var selector = \'#' . $this->getFieldId($name, $options) . '\'; $(selector).tokenInput({ ajax : { url : \'' . $url . '\', data: { _token: \'' . csrf_token() . '\' }, loadByIdentifier: true }, unique : true,' . (Arr::has($options, 'js.resultFormatterId') ? 'resultFormat: $(\'#' . Arr::get($options, 'js.resultFormatterId') . '\').html(),' : '') . ' preloaded: ' . Arr::get($options, 'js.preloaded', new Collection())->toJson() . ', disabled : ' . (Arr::get($options, 'disabled', false) ? 'true' : 'false') . ' }); }(jQuery)); </script>'; return $this->text($name, $value, $options) . $script; } public function groupText($name, $value = null, array $options = []) { return $this->wrapToGroup($name, $this->text($name, $value, $options), $options); } public function groupPassword($name, array $options = []) { return $this->wrapToGroup($name, $this->password($name, $options), $options); } public function groupFile($name, array $options = []) { return $this->wrapToGroup($name, $this->file($name, $options), $options); } public function groupTextarea($name, $value, array $options = []) { return $this->wrapToGroup($name, $this->textarea($name, $value, $options), $options); } public function groupSelect($name, array $list = [], $selected = null, array $options = []) { return $this->wrapToGroup($name, $this->select($name, $list, $selected, $options), $options); } public function groupCheckbox($name, $value = 1, $checked = null, array $options = []) { return $this->wrapToGroup($name, $this->checkbox($name, $value, $checked, $options), $options); } public function groupTokenInput($name, $url, $value = null, array $options = []) { return $this->wrapToGroup($name, $this->tokenInput($name, $url, $value, $options), $options); } public function groupStatic($name, $text, array $options = []) { return $this->wrapToGroup($name, '<p class="form-control-static">' . $text . '</p>', $options); } public function wrapToGroup($name, $field, array $options = []) { $errors = $this->session->get('errors', new MessageBag()); $fieldId = $this->getFieldId($name, $options); $key = str_replace(['.', '[]', '[', ']'], ['_', '', '.', ''], $name); $hasError = $errors->has($key); $output = '<div class="form-group form-group-' . $fieldId . ($hasError ? ' has-error' : '') . '">'; if (Arr::has($options, 'label')) { $output .= $this->form->label($name, Arr::get($options, 'label'), [ 'for' => $this->getFieldId($name, $options), 'class' => 'control-label' . (Arr::get($options, 'vertical', false) === true ? '' : ' col-sm-' . Arr::get($options, 'labelSize', 3)), ]); }; // Field holding div if (Arr::get($options, 'vertical', false) === true) { $output .= '<div>'; } else { $output .= '<div class="' . (!Arr::has($options, 'label') ? 'col-sm-offset-' . Arr::get($options, 'labelSize', 3) . ' ' : '') . 'col-sm-' . (12 - Arr::get($options, 'labelSize', 3)) . '">'; } $output .= '<div class="form-group-field">' . $field . '</div>'; if ($hasError) { $output .= '<div class="help-block error-block">' . $errors->first($key) . '</div>'; } if (Arr::has($options, 'help') && trim(Arr::get($options, 'help', '')) !== '') { $output .= '<div class="help-block text-justify">' . Arr::get($options, 'help') . '</div>'; } $output .= '</div></div>'; return $output; } /** * Get field options * * @param string $name * @param array $options * * @return mixed */ protected function getFieldOptions($name, array $options = []) { $fieldOptions = Arr::get($options, 'field', []); if ($this->isFieldDisabled($options)) { $fieldOptions['disabled'] = 'disabled'; } $fieldOptions['id'] = $this->getFieldId($name, $options); return $fieldOptions; } /** * Add form-control class to field options * * @param array $fieldOptions * * @return array */ protected function addFormControlClass(array $fieldOptions = []) { $class = Arr::get($fieldOptions, 'class', 'form-control'); if (strpos($class, 'form-control') === false) { $class .= ' form-control'; } $fieldOptions['class'] = $class; return $fieldOptions; } /** * Check if field is disabled or not * * @param array $options * * @return bool */ protected function isFieldDisabled(array $options = []) { return Arr::get($options, 'disabled', false) === true; } /** * Get field id * * @param string $name * @param array $options * * @return mixed|string */ protected function getFieldId($name, array $options = []) { if (Arr::has($options, 'field.id')) { return Arr::get($options, 'field.id'); } return 'field-' . str_replace('_', '-', $name); } }
mit
cgafeng/BTSMobileS
app/dl/src/stores/ImportKeysStore.js
370
import alt from "alt-instance" import ImportKeysActions from "actions/ImportKeysActions" class ImportKeysStore { constructor() { this.bindActions(ImportKeysActions) } onSetStatus(status) { this.setState({status}) } } export var ImportKeysStoreWrapped = alt.createStore(ImportKeysStore) export default ImportKeysStoreWrapped
mit
regenschauer490/TopicModel
SigTM/lib/model/lda_interface.hpp
7033
/* Copyright(c) 2014 Akihiro Nishimura This software is released under the MIT License. http://opensource.org/licenses/mit-license.php */ #ifndef SIGTM_LDA_INTERFACE_HPP #define SIGTM_LDA_INTERFACE_HPP #include "../sigtm.hpp" #include "../helper/compare_method.hpp" #include "../helper/data_format.hpp" namespace sigtm { class LDA; using LDAPtr = std::shared_ptr<LDA>; template<class T> using MatrixTK = VectorT<VectorK<T>>; // token - topic template<class T> using MatrixDK = VectorD<VectorK<T>>; // document - topic template<class T> using MatrixVK = VectorV<VectorK<T>>; // word - topic template<class T> using MatrixKV = VectorK<VectorV<T>>; // topic - word /* template<class T> using SVectorD = std::shared_ptr<VectorD<T>>; template<class T> using SVectorK = std::shared_ptr<VectorK<T>>; template<class T> using SVectorV = std::shared_ptr<VectorV<T>>; template<class T> using SMatrixDK = SVectorD<SVectorK<T>>; template<class T> using SMatrixVK = SVectorV<SVectorK<T>>; template<class T> using SMatrixKV = SVectorK<SVectorV<T>>; */ #define SIG_INIT_VECTOR(type, index_name, value)\ Vector ## index_name ## <type>(index_name ## _, value) #define SIG_INIT_VECTOR_R(type, index_name, range, value)\ Vector ## index_name ## <type>(range, value) #define SIG_INIT_MATRIX(type, index_name1, index_name2, value)\ Matrix ## index_name1 ## index_name2 ## <type>(index_name1 ## _, SIG_INIT_VECTOR(type, index_name2, value)) #define SIG_INIT_MATRIX_R(type, index_name1,range1, index_name2, range2, value)\ Matrix ## index_name1 ## index_name2 ## <type>(range1, SIG_INIT_VECTOR_R(type, index_name2, range2, value)) #define SIG_INIT_MATRIX3(type, index_name1, index_name2, index_name3, value)\ Vector ## index_name1 ## <type>(index_name1 ## _, SIG_INIT_MATRIX(type, index_name2, index_name3, value)) // LDAインタフェース class LDA { public: enum class DynamicType{ GIBBS, MRLDA, CVB0 }; // 実装次第追加 virtual DynamicType getDynamicType() const = 0; public: // LDAで得られる確率分布やベクトル enum class Distribution{ DOCUMENT, TOPIC, TERM_SCORE }; SIG_MakeCompareInnerClass(LDA); protected: // method chain 生成 SIG_MakeDist2CmpMapBase; SIG_MakeDist2CmpMap(Distribution::DOCUMENT, LDA::CmpD<std::function< VectorD<double>(DocumentId) >>); SIG_MakeDist2CmpMap(Distribution::TOPIC, LDA::CmpD<std::function< VectorK<double>(TopicId) >>); SIG_MakeDist2CmpMap(Distribution::TERM_SCORE, LDA::CmpV<std::function< VectorK<double>(TopicId) >>); //SIG_MakeDist2CmpMap(Distribution::DOC_TERM, LDA::CmpV); template <LDA::Distribution Select> friend auto compare(LDAPtr lda, Id id1, Id id2) ->typename Map2Cmp<Select>::type; // 確率分布同士の類似度を測る(メソッドチェーンな感じに使用) template <Distribution Select> auto compareDefault(Id id1, Id id2, uint D, uint K) const->typename Map2Cmp<Select>::type { return Select == Distribution::DOCUMENT ? typename Map2Cmp<Select>::type(id1, id2, [this](DocumentId id){ return this->getTheta(id); }, id1 < D && id2 < D ? true : false) : Select == Distribution::TOPIC ? typename Map2Cmp<Select>::type(id1, id2, [this](TopicId id){ return this->getPhi(id); }, id1 < K && id2 < K ? true : false) : Select == Distribution::TERM_SCORE ? typename Map2Cmp<Select>::type(id1, id2, [this](TopicId id){ return this->getTermScore(id); }, id1 < K && id2 < K ? true : false) : typename Map2Cmp<Select>::type(id1, id2, [](TopicId id){ return std::vector<double>(); }, false); } protected: LDA() = default; LDA(LDA const&) = delete; LDA(LDA&&) = delete; public: virtual ~LDA(){} // モデルの学習を行う virtual void train(uint iteration_num) = 0; virtual void train(uint iteration_num, std::function<void(LDA const*)> callback) = 0; // コンソールに出力 virtual void print(Distribution target) const = 0; // ファイルに出力 // save_folder: 保存先のフォルダのパス // detail: 詳細なデータも全て出力するか virtual void save(Distribution target, FilepassString save_folder, bool detail = false) const = 0; //ドキュメントのトピック分布 [doc][topic] virtual auto getTheta() const->MatrixDK<double>; virtual auto getTheta(DocumentId d_id) const->VectorK<double> = 0; //トピックの単語分布 [topic][word] virtual auto getPhi() const->MatrixKV<double>; virtual auto getPhi(TopicId k_id) const->VectorV<double> = 0; //トピックを強調する単語スコア [topic][word] virtual auto getTermScore() const->MatrixKV<double> = 0; virtual auto getTermScore(TopicId t_id) const->VectorV<double> = 0; // 指定トピックの上位return_word_num個の、語彙とスコアを返す // [topic][ranking]<vocab, score> virtual auto getWordOfTopic(Distribution target, uint return_word_num) const->VectorK< std::vector< std::tuple<std::wstring, double>>>; // [ranking]<vocab, score> virtual auto getWordOfTopic(Distribution target, uint return_word_num, TopicId k_id) const->std::vector< std::tuple<std::wstring, double>> = 0; // 指定ドキュメントの上位return_word_num個の、語彙とスコアを返す // [doc][ranking]<vocab, score> virtual auto getWordOfDocument(uint return_word_num) const->VectorD< std::vector< std::tuple<std::wstring, double>>>; //[ranking]<vocab, score> virtual auto getWordOfDocument(uint return_word_num, DocumentId d_id) const->std::vector< std::tuple<std::wstring, double>> = 0; virtual uint getDocumentNum() const = 0; virtual uint getTopicNum() const = 0; virtual uint getWordNum() const = 0; // get hyper-parameter of topic distribution virtual auto getAlpha() const->VectorK<double> = 0; // get hyper-parameter of word distribution virtual auto getBeta() const->VectorV<double> = 0; virtual double getLogLikelihood() const = 0; virtual double getPerplexity() const = 0; }; const std::function<void(LDA const*)> null_lda_callback = [](LDA const*){}; inline auto LDA::getTheta() const->MatrixDK<double> { MatrixDK<double> theta; for (DocumentId d = 0, D = getDocumentNum(); d < D; ++d) theta.push_back(getTheta(d)); return theta; } inline auto LDA::getPhi() const->MatrixKV<double> { MatrixKV<double> phi; for (TopicId k = 0, K = getTopicNum(); k < K; ++k) phi.push_back(getPhi(k)); return std::move(phi); } inline auto LDA::getWordOfTopic(LDA::Distribution target, uint return_word_num) const->VectorK< std::vector< std::tuple<std::wstring, double>>> { VectorK< std::vector< std::tuple<std::wstring, double> > > result; for (TopicId k = 0, K = getTopicNum(); k < K; ++k){ result.push_back(getWordOfTopic(target, return_word_num, k)); } return std::move(result); } inline auto LDA::getWordOfDocument(uint return_word_num) const->VectorD< std::vector< std::tuple<std::wstring, double>>> { std::vector< std::vector< std::tuple<std::wstring, double>>> result; for (DocumentId d = 0, D = getDocumentNum(); d < D; ++d){ result.push_back(getWordOfDocument(return_word_num, d)); } return std::move(result); } } #endif
mit
ybrs/Rhombus
src/main/java/com/pardot/rhombus/cobject/async/StatementIteratorConsumer.java
3970
package com.pardot.rhombus.cobject.async; import com.datastax.driver.core.*; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import com.pardot.rhombus.RhombusException; import com.pardot.rhombus.cobject.BoundedCQLStatementIterator; import com.pardot.rhombus.cobject.CQLExecutor; import com.pardot.rhombus.cobject.CQLStatement; import com.yammer.metrics.Metrics; import com.yammer.metrics.core.MetricsRegistry; import com.yammer.metrics.core.Timer; import com.yammer.metrics.core.TimerContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; import java.util.concurrent.*; import static com.google.common.util.concurrent.Uninterruptibles.awaitUninterruptibly; /** * Pardot, an ExactTarget company * User: Michael Frank * Date: 6/21/13 */ public class StatementIteratorConsumer { private static Logger logger = LoggerFactory.getLogger(StatementIteratorConsumer.class); private static ExecutorService executorService = Executors.newFixedThreadPool(260); private final BoundedCQLStatementIterator statementIterator; private CQLExecutor cqlExecutor; private final CountDownLatch shutdownLatch; private final long timeout; private final Set<Future> futures = Collections.synchronizedSet(new HashSet<Future>()); public StatementIteratorConsumer(BoundedCQLStatementIterator statementIterator, CQLExecutor cqlExecutor, long timeout) { this.statementIterator = statementIterator; this.cqlExecutor = cqlExecutor; this.timeout = timeout; this.shutdownLatch = new CountDownLatch((new Long(statementIterator.size())).intValue()); logger.trace("Created consumer with countdown {}", shutdownLatch.getCount()); } public void start() { while(statementIterator.hasNext()) { final CQLStatement next = statementIterator.next(); Runnable r = new Runnable() { @Override public void run() { handle(next); } }; executorService.execute(r); } } public void join() throws RhombusException { logger.trace("Awaiting shutdownLatch with timeout {}ms", timeout); try { boolean complete = shutdownLatch.await(timeout, TimeUnit.MILLISECONDS); if(!complete) { Metrics.defaultRegistry().newMeter(StatementIteratorConsumer.class, "asyncTimeout", "asyncTimeout", TimeUnit.SECONDS).mark(); cancelFutures(); throw new RhombusException("Timout executing statements asynch"); } } catch (InterruptedException e) { logger.warn("Interrupted while executing statements asynch", e); cancelFutures(); } } private void cancelFutures() { for(Future future : futures) { try { future.cancel(true); } catch(Exception e) { logger.warn("Exception when cancelling future", e); } } } protected void handle(CQLStatement statement) { final Timer asyncExecTimer = Metrics.defaultRegistry().newTimer(StatementIteratorConsumer.class, "asyncExec"); final TimerContext asyncExecTimerContext = asyncExecTimer.time(); final long startTime = System.nanoTime(); ResultSetFuture future = this.cqlExecutor.executeAsync(statement); futures.add(future); Futures.addCallback(future, new FutureCallback<ResultSet>() { @Override public void onSuccess(final ResultSet result) { Host queriedHost = result.getExecutionInfo().getQueriedHost(); Metrics.defaultRegistry().newMeter(StatementIteratorConsumer.class, "queriedhost." + queriedHost.getDatacenter(), queriedHost.getDatacenter(), TimeUnit.SECONDS).mark(); asyncExecTimerContext.stop(); logger.debug("Async exec time {}us", (System.nanoTime() - startTime) / 1000); shutdownLatch.countDown(); } @Override public void onFailure(final Throwable t) { //TODO Stop processing and return error logger.error("Error during async request: {}", t); asyncExecTimerContext.stop(); shutdownLatch.countDown(); } } , executorService ); } }
mit
djtms/superputty
SuperPutty/Utils/PortableSettingsProvider.cs
11328
/* * Copyright (c) 2009 - 2015 Jim Radford http://www.jimradford.com * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Configuration; using System.Windows.Forms; using System.IO; using System.Xml; using log4net; using System.Collections; using System.Linq; namespace SuperPutty.Utils { /// <summary> /// PortableSettingsProvider /// /// Based on /// http://www.codeproject.com/Articles/20917/Creating-a-Custom-Settings-Provider /// </summary> public class PortableSettingsProvider : SettingsProvider { private static readonly ILog Log = LogManager.GetLogger(typeof(PortableSettingsProvider)); private static bool ForceRoamingSettings = Convert.ToBoolean(ConfigurationManager.AppSettings["SuperPuTTY.ForceRoamingSettings"] ?? "True"); public const string SettingsRoot = "Settings"; private XmlDocument settingsXML; public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config) { base.Initialize(this.ApplicationName, config); } public override string ApplicationName { get { if (Application.ProductName.Trim().Length > 0) { return Application.ProductName; } else { FileInfo fi = new FileInfo(Application.ExecutablePath); return fi.Name.Substring(0, fi.Name.Length - fi.Extension.Length); } } set { } } /// <summary> /// Return a list of possible locations for the settings file. If non are found, create the /// default in the first location /// </summary> /// <returns></returns> public virtual string[] GetAppSettingsPaths() { string[] paths = new string[2]; paths[0] = Environment.GetEnvironmentVariable("USERPROFILE"); paths[1] = Path.GetDirectoryName(Application.ExecutablePath); return paths; } public virtual string GetAppSettingsFileName() { return ApplicationName + ".settings"; } /// <summary> /// Return first existing file path or the first if none found /// </summary> /// <returns></returns> string GetAppSettingsFilePath() { string[] paths = GetAppSettingsPaths(); string fileName = GetAppSettingsFileName(); string path = Path.Combine(paths[0], fileName); foreach (string dir in paths) { string filePath = Path.Combine(dir, fileName); if (File.Exists(filePath)) { path = filePath; break; } } return path; } public string SettingsFilePath { get; private set; } public override void SetPropertyValues(SettingsContext context, SettingsPropertyValueCollection collection) { foreach (SettingsPropertyValue propVal in collection) { SetValue(propVal); } try { SettingsXML.Save(GetAppSettingsFilePath()); } catch(Exception ex){ Log.Error("Error saving settings", ex); } } public override SettingsPropertyValueCollection GetPropertyValues(SettingsContext context, SettingsPropertyCollection collection) { // Create new collection of values SettingsPropertyValueCollection values = new SettingsPropertyValueCollection(); // Iterate through the settings to be retrieved foreach (SettingsProperty setting in collection) { SettingsPropertyValue value = new SettingsPropertyValue(setting) { IsDirty = true, SerializedValue = GetValue(setting) }; values.Add(value); } return values; } public XmlDocument SettingsXML { get { // If we dont hold an xml document, try opening one. // If it doesnt exist then create a new one ready. if (this.settingsXML == null) { this.settingsXML = new XmlDocument(); string settingsFile = GetAppSettingsFilePath(); this.SettingsFilePath = settingsFile; try { this.settingsXML.Load( settingsFile ); Log.InfoFormat("Loaded settings from {0}", settingsFile); } catch (Exception) { Log.InfoFormat("Could not load file ({0}), creating settings file", settingsFile); // Create new document XmlDeclaration declaration = this.settingsXML.CreateXmlDeclaration("1.0", "utf-8", String.Empty); this.settingsXML.AppendChild(declaration); XmlNode nodeRoot = this.settingsXML.CreateNode(XmlNodeType.Element, SettingsRoot, String.Empty); this.settingsXML.AppendChild(nodeRoot); } } return this.settingsXML; } } private string GetValue(SettingsProperty setting) { string value = String.Empty; try { if (UseRoamingSettings(setting)) { XmlNode node = SettingsXML.SelectSingleNode(SettingsRoot + "/" + setting.Name); if (node == null) { // try go by host...backwards compatibility node = SettingsXML.SelectSingleNode(SettingsRoot + "/" + GetHostName() + "/" + setting.Name); } value = node.InnerText; } else { value = SettingsXML.SelectSingleNode(SettingsRoot + "/" + GetHostName() + "/" + setting.Name).InnerText; } } catch (Exception) { value = setting.DefaultValue != null ? setting.DefaultValue.ToString() : String.Empty; } return value; } private void SetValue(SettingsPropertyValue propVal) { XmlNode machineNode; XmlNode settingNode; // Determine if the setting is roaming. // If roaming then the value is stored as an element under the root // Otherwise it is stored under a machine name node try { if (UseRoamingSettings(propVal.Property)) settingNode = (XmlElement)SettingsXML.SelectSingleNode(SettingsRoot + "/" + propVal.Name); else settingNode = (XmlElement)SettingsXML.SelectSingleNode(SettingsRoot + "/" + GetHostName() + "/" + propVal.Name); } catch (Exception) { settingNode = null; } // Check to see if the node exists, if so then set its new value if (settingNode != null) { settingNode.InnerText = propVal.SerializedValue.ToString(); } else { if (UseRoamingSettings(propVal.Property)) { // Store the value as an element of the Settings Root Node settingNode = SettingsXML.CreateElement(propVal.Name); settingNode.InnerText = propVal.SerializedValue.ToString(); SettingsXML.SelectSingleNode(SettingsRoot).AppendChild(settingNode); } else { // Its machine specific, store as an element of the machine name node, // creating a new machine name node if one doesnt exist. string nodePath = SettingsRoot + "/" + GetHostName(); try { machineNode = (XmlElement)SettingsXML.SelectSingleNode(nodePath); } catch (Exception ex) { Log.Error("Error selecting node, " + nodePath, ex); machineNode = SettingsXML.CreateElement(GetHostName()); SettingsXML.SelectSingleNode(SettingsRoot).AppendChild(machineNode); } if (machineNode == null) { machineNode = SettingsXML.CreateElement(GetHostName()); SettingsXML.SelectSingleNode(SettingsRoot).AppendChild(machineNode); } settingNode = SettingsXML.CreateElement(propVal.Name); settingNode.InnerText = propVal.SerializedValue.ToString(); machineNode.AppendChild(settingNode); } } } private static string GetHostName() { return Environment.MachineName; } private bool UseRoamingSettings(SettingsProperty prop) { if (ForceRoamingSettings || string.IsNullOrEmpty(Environment.MachineName) || Char.IsDigit(Environment.MachineName[0])) { return true; } // Determine if the setting is marked as Roaming return (from DictionaryEntry de in prop.Attributes select (Attribute) de.Value).OfType<SettingsManageabilityAttribute>().Any(); } } }
mit
unmeshpro/easyPost
static/node_modules/react-document-meta/lib/index.js
5340
import React from 'react'; import { renderToStaticMarkup } from 'react-dom/server'; import { canUseDOM } from 'exenv'; import withSideEffect from 'react-side-effect'; import { clone, defaults, forEach } from './utils'; function reducePropsTostate ( propsList ) { const props = {}; let extend = true; for (var i = propsList.length - 1; extend && i >= 0; i--) { const _props = clone(propsList[i]); if ( _props.hasOwnProperty('description') ) { defaults(_props, { meta: { name: { description: _props.description } } } ); } if ( _props.hasOwnProperty('canonical') ) { defaults(_props, { link: { rel: { canonical: _props.canonical } } } ); } defaults(props, _props); extend = _props.hasOwnProperty('extend'); } if (props.auto) { autoProps( props ); } return props; } function autoProps ( props ) { if (props.auto.ograph === true) { ograph(props); } return props; } function handleStateChangeOnClient ( props ) { if ( canUseDOM ) { document.title = props.title || ''; insertDocumentMeta( props ); } } function ograph ( p ) { if (!p.meta) { p.meta = {}; } if (!p.meta.property) { p.meta.property = {}; } const group = p.meta.property; if ( group ) { if ( p.title && !group['og:title'] ) { group['og:title'] = p.title; } if ( p.hasOwnProperty('description') && !group['og:description'] ) { group['og:description'] = p.description; } if ( p.hasOwnProperty('canonical') && !group['og:url'] ) { group['og:url'] = p.canonical; } } return p; } function parseTags ( tagName, props = {} ) { const tags = []; const contentKey = tagName === 'link' ? 'href' : 'content'; Object.keys( props ).forEach(( groupKey ) => { const group = props[groupKey]; if (typeof group === 'string') { tags.push({ tagName, [ groupKey ]: group }); return; } Object.keys( group ).forEach(( key ) => { const values = Array.isArray(group[key]) ? group[key] : [group[key]]; values.forEach(( value ) => { if (value === null ) { return; } tags.push({ tagName, [ groupKey ]: key, [ contentKey ]: value }); }); }); }); return tags; } function getTags ( _props ) { return [].concat( parseTags( 'meta', _props.meta ), parseTags( 'link', _props.link ) ); } function removeNode ( node ) { node.parentNode.removeChild(node); } function removeDocumentMeta () { forEach(document.querySelectorAll('head [data-rdm]'), removeNode); } function insertDocumentMetaNode ( entry ) { const { tagName, ...attr } = entry; var newNode = document.createElement( tagName ); for (var prop in attr) { if (entry.hasOwnProperty(prop)) { newNode.setAttribute(prop, entry[prop]); } } newNode.setAttribute('data-rdm', ''); document.getElementsByTagName('head')[0].appendChild(newNode); } function insertDocumentMeta ( props ) { removeDocumentMeta(); forEach( getTags( props ), insertDocumentMetaNode); } function render ( meta = {}, opts ) { if ( typeof opts !== 'object' ) { return meta; } let i = 0; const tags = []; function renderTag ( entry ) { const { tagName, ...attr } = entry; if ( tagName === 'meta' ) { return ( <meta {...attr} key={ i++ } data-rdm /> ); } if ( tagName === 'link' ) { return ( <link {...attr} key={ i++ } data-rdm /> ); } return null; } if ( meta.title ) { tags.push( <title key={ i++ }>{ meta.title }</title> ); } getTags( meta ).reduce(( acc, entry ) => { tags.push( renderTag(entry) ); return tags; }, tags); if ( opts.asReact ) { return tags; } return renderToStaticMarkup( <div>{ tags }</div> ).replace(/(^<div>|<\/div>$)/g, ''); } const DocumentMeta = React.createClass({ displayName: 'DocumentMeta', propTypes: { title: React.PropTypes.string, description: React.PropTypes.string, canonical: React.PropTypes.string, meta: React.PropTypes.objectOf( React.PropTypes.oneOfType([ React.PropTypes.string, React.PropTypes.objectOf( React.PropTypes.oneOfType([ React.PropTypes.string, React.PropTypes.arrayOf(React.PropTypes.string) ]) ) ]) ), link: React.PropTypes.objectOf( React.PropTypes.objectOf( React.PropTypes.oneOfType([ React.PropTypes.string, React.PropTypes.arrayOf(React.PropTypes.string) ]) ) ), auto: React.PropTypes.objectOf(React.PropTypes.bool) }, render: function render () { const { children } = this.props; const count = React.Children.count(children); return count === 1 ? React.Children.only(children) : ( count ? <div>{ this.props.children }</div> : null ); } }); const DocumentMetaWithSideEffect = withSideEffect( reducePropsTostate, handleStateChangeOnClient )(DocumentMeta); DocumentMetaWithSideEffect.renderAsReact = function rewindAsReact () { return render( DocumentMetaWithSideEffect.rewind(), { asReact: true } ); }; DocumentMetaWithSideEffect.renderAsHTML = function rewindAsHTML () { return render( DocumentMetaWithSideEffect.rewind(), { asHtml: true } ); }; export default DocumentMetaWithSideEffect;
mit
quyse/flaw
flaw-font-icu/src/icu/source/test/intltest/callimts.cpp
20265
// © 2016 and later: Unicode, Inc. and others. // License & terms of use: http://www.unicode.org/copyright.html /*********************************************************************** * COPYRIGHT: * Copyright (c) 1997-2015, International Business Machines Corporation * and others. All Rights Reserved. ***********************************************************************/ #include "unicode/utypes.h" #if !UCONFIG_NO_FORMATTING #include "callimts.h" #include "caltest.h" #include "unicode/calendar.h" #include "unicode/gregocal.h" #include "unicode/datefmt.h" #include "unicode/smpdtfmt.h" #include "cstring.h" #include "mutex.h" #include "putilimp.h" #include "simplethread.h" U_NAMESPACE_USE void CalendarLimitTest::runIndexedTest( int32_t index, UBool exec, const char* &name, char* /*par*/ ) { if (exec) logln("TestSuite TestCalendarLimit"); switch (index) { // Re-enable this later case 0: name = "TestCalendarExtremeLimit"; if (exec) { logln("TestCalendarExtremeLimit---"); logln(""); TestCalendarExtremeLimit(); } break; case 1: name = "TestLimits"; if (exec) { logln("TestLimits---"); logln(""); TestLimits(); } break; default: name = ""; break; } } // ***************************************************************************** // class CalendarLimitTest // ***************************************************************************** // ------------------------------------- void CalendarLimitTest::test(UDate millis, icu::Calendar* cal, icu::DateFormat* fmt) { static const UDate kDrift = 1e-10; UErrorCode exception = U_ZERO_ERROR; UnicodeString theDate; UErrorCode status = U_ZERO_ERROR; cal->setTime(millis, exception); if (U_SUCCESS(exception)) { fmt->format(millis, theDate); UDate dt = fmt->parse(theDate, status); // allow a small amount of error (drift) if(! withinErr(dt, millis, kDrift)) { errln("FAIL:round trip for large milli, got: %.1lf wanted: %.1lf. (delta %.2lf greater than %.2lf)", dt, millis, uprv_fabs(millis-dt), uprv_fabs(dt*kDrift)); logln(UnicodeString(" ") + theDate + " " + CalendarTest::calToStr(*cal)); } else { logln(UnicodeString("OK: got ") + dt + ", wanted " + millis); logln(UnicodeString(" ") + theDate); } } } // ------------------------------------- // bug 986c: deprecate nextDouble/previousDouble //|double //|CalendarLimitTest::nextDouble(double a) //|{ //| return uprv_nextDouble(a, TRUE); //|} //| //|double //|CalendarLimitTest::previousDouble(double a) //|{ //| return uprv_nextDouble(a, FALSE); //|} UBool CalendarLimitTest::withinErr(double a, double b, double err) { return ( uprv_fabs(a - b) < uprv_fabs(a * err) ); } void CalendarLimitTest::TestCalendarExtremeLimit() { UErrorCode status = U_ZERO_ERROR; Calendar *cal = Calendar::createInstance(status); if (failure(status, "Calendar::createInstance", TRUE)) return; cal->adoptTimeZone(TimeZone::createTimeZone("GMT")); DateFormat *fmt = DateFormat::createDateTimeInstance(); if(!fmt || !cal) { dataerrln("can't open cal and/or fmt"); return; } fmt->adoptCalendar(cal); ((SimpleDateFormat*) fmt)->applyPattern("HH:mm:ss.SSS Z, EEEE, MMMM d, yyyy G"); // This test used to test the algorithmic limits of the dates that // GregorianCalendar could handle. However, the algorithm has // been rewritten completely since then and the prior limits no // longer apply. Instead, we now do basic round-trip testing of // some extreme (but still manageable) dates. UDate m; logln("checking 1e16..1e17"); for ( m = 1e16; m < 1e17; m *= 1.1) { test(m, cal, fmt); } logln("checking -1e14..-1e15"); for ( m = -1e14; m > -1e15; m *= 1.1) { test(m, cal, fmt); } // This is 2^52 - 1, the largest allowable mantissa with a 0 // exponent in a 64-bit double UDate VERY_EARLY_MILLIS = - 4503599627370495.0; UDate VERY_LATE_MILLIS = 4503599627370495.0; // I am removing the previousDouble and nextDouble calls below for // two reasons: 1. As part of jitterbug 986, I am deprecating // these methods and removing calls to them. 2. This test is a // non-critical boundary behavior test. test(VERY_EARLY_MILLIS, cal, fmt); //test(previousDouble(VERY_EARLY_MILLIS), cal, fmt); test(VERY_LATE_MILLIS, cal, fmt); //test(nextDouble(VERY_LATE_MILLIS), cal, fmt); delete fmt; } namespace { struct TestCase { const char *type; UBool hasLeapMonth; UDate actualTestStart; int32_t actualTestEnd; }; const UDate DEFAULT_START = 944006400000.0; // 1999-12-01T00:00Z const int32_t DEFAULT_END = -120; // Default for non-quick is run 2 minutes TestCase TestCases[] = { {"gregorian", FALSE, DEFAULT_START, DEFAULT_END}, {"japanese", FALSE, 596937600000.0, DEFAULT_END}, // 1988-12-01T00:00Z, Showa 63 {"buddhist", FALSE, DEFAULT_START, DEFAULT_END}, {"roc", FALSE, DEFAULT_START, DEFAULT_END}, {"persian", FALSE, DEFAULT_START, DEFAULT_END}, {"islamic-civil", FALSE, DEFAULT_START, DEFAULT_END}, {"islamic", FALSE, DEFAULT_START, 800000}, // Approx. 2250 years from now, after which // some rounding errors occur in Islamic calendar {"hebrew", TRUE, DEFAULT_START, DEFAULT_END}, {"chinese", TRUE, DEFAULT_START, DEFAULT_END}, {"dangi", TRUE, DEFAULT_START, DEFAULT_END}, {"indian", FALSE, DEFAULT_START, DEFAULT_END}, {"coptic", FALSE, DEFAULT_START, DEFAULT_END}, {"ethiopic", FALSE, DEFAULT_START, DEFAULT_END}, {"ethiopic-amete-alem", FALSE, DEFAULT_START, DEFAULT_END} }; struct { int32_t fIndex; UBool next (int32_t &rIndex) { Mutex lock; if (fIndex >= UPRV_LENGTHOF(TestCases)) { return FALSE; } rIndex = fIndex++; return TRUE; } void reset() { fIndex = 0; } } gTestCaseIterator; } // anonymous name space void CalendarLimitTest::TestLimits(void) { gTestCaseIterator.reset(); ThreadPool<CalendarLimitTest> threads(this, threadCount, &CalendarLimitTest::TestLimitsThread); threads.start(); threads.join(); } void CalendarLimitTest::TestLimitsThread(int32_t threadNum) { logln("thread %d starting", threadNum); int32_t testIndex = 0; LocalPointer<Calendar> cal; while (gTestCaseIterator.next(testIndex)) { TestCase &testCase = TestCases[testIndex]; logln("begin test of %s calendar.", testCase.type); UErrorCode status = U_ZERO_ERROR; char buf[64]; uprv_strcpy(buf, "root@calendar="); strcat(buf, testCase.type); cal.adoptInstead(Calendar::createInstance(buf, status)); if (failure(status, "Calendar::createInstance", TRUE)) { continue; } if (uprv_strcmp(cal->getType(), testCase.type) != 0) { errln((UnicodeString)"FAIL: Wrong calendar type: " + cal->getType() + " Requested: " + testCase.type); continue; } doTheoreticalLimitsTest(*(cal.getAlias()), testCase.hasLeapMonth); doLimitsTest(*(cal.getAlias()), testCase.actualTestStart, testCase.actualTestEnd); logln("end test of %s calendar.", testCase.type); } } void CalendarLimitTest::doTheoreticalLimitsTest(Calendar& cal, UBool leapMonth) { const char* calType = cal.getType(); int32_t nDOW = cal.getMaximum(UCAL_DAY_OF_WEEK); int32_t maxDOY = cal.getMaximum(UCAL_DAY_OF_YEAR); int32_t lmaxDOW = cal.getLeastMaximum(UCAL_DAY_OF_YEAR); int32_t maxWOY = cal.getMaximum(UCAL_WEEK_OF_YEAR); int32_t lmaxWOY = cal.getLeastMaximum(UCAL_WEEK_OF_YEAR); int32_t maxM = cal.getMaximum(UCAL_MONTH) + 1; int32_t lmaxM = cal.getLeastMaximum(UCAL_MONTH) + 1; int32_t maxDOM = cal.getMaximum(UCAL_DAY_OF_MONTH); int32_t lmaxDOM = cal.getLeastMaximum(UCAL_DAY_OF_MONTH); int32_t maxDOWIM = cal.getMaximum(UCAL_DAY_OF_WEEK_IN_MONTH); int32_t lmaxDOWIM = cal.getLeastMaximum(UCAL_DAY_OF_WEEK_IN_MONTH); int32_t maxWOM = cal.getMaximum(UCAL_WEEK_OF_MONTH); int32_t lmaxWOM = cal.getLeastMaximum(UCAL_WEEK_OF_MONTH); int32_t minDaysInFirstWeek = cal.getMinimalDaysInFirstWeek(); // Day of year int32_t expected; if (!leapMonth) { expected = maxM*maxDOM; if (maxDOY > expected) { errln((UnicodeString)"FAIL: [" + calType + "] Maximum value of DAY_OF_YEAR is too big: " + maxDOY + "/expected: <=" + expected); } expected = lmaxM*lmaxDOM; if (lmaxDOW < expected) { errln((UnicodeString)"FAIL: [" + calType + "] Least maximum value of DAY_OF_YEAR is too small: " + lmaxDOW + "/expected: >=" + expected); } } // Week of year expected = maxDOY/nDOW + 1; if (maxWOY > expected) { errln((UnicodeString)"FAIL: [" + calType + "] Maximum value of WEEK_OF_YEAR is too big: " + maxWOY + "/expected: <=" + expected); } expected = lmaxDOW/nDOW; if (lmaxWOY < expected) { errln((UnicodeString)"FAIL: [" + calType + "] Least maximum value of WEEK_OF_YEAR is too small: " + lmaxWOY + "/expected >=" + expected); } // Day of week in month expected = (maxDOM + nDOW - 1)/nDOW; if (maxDOWIM != expected) { errln((UnicodeString)"FAIL: [" + calType + "] Maximum value of DAY_OF_WEEK_IN_MONTH is incorrect: " + maxDOWIM + "/expected: " + expected); } expected = (lmaxDOM + nDOW - 1)/nDOW; if (lmaxDOWIM != expected) { errln((UnicodeString)"FAIL: [" + calType + "] Least maximum value of DAY_OF_WEEK_IN_MONTH is incorrect: " + lmaxDOWIM + "/expected: " + expected); } // Week of month expected = (maxDOM + (nDOW - 1) + (nDOW - minDaysInFirstWeek)) / nDOW; if (maxWOM != expected) { errln((UnicodeString)"FAIL: [" + calType + "] Maximum value of WEEK_OF_MONTH is incorrect: " + maxWOM + "/expected: " + expected); } expected = (lmaxDOM + (nDOW - minDaysInFirstWeek)) / nDOW; if (lmaxWOM != expected) { errln((UnicodeString)"FAIL: [" + calType + "] Least maximum value of WEEK_OF_MONTH is incorrect: " + lmaxWOM + "/expected: " + expected); } } void CalendarLimitTest::doLimitsTest(Calendar& cal, UDate startDate, int32_t endTime) { int32_t testTime = quick ? ( endTime / 40 ) : endTime; doLimitsTest(cal, NULL /*default fields*/, startDate, testTime); } void CalendarLimitTest::doLimitsTest(Calendar& cal, const int32_t* fieldsToTest, UDate startDate, int32_t testDuration) { static const int32_t FIELDS[] = { UCAL_ERA, UCAL_YEAR, UCAL_MONTH, UCAL_WEEK_OF_YEAR, UCAL_WEEK_OF_MONTH, UCAL_DAY_OF_MONTH, UCAL_DAY_OF_YEAR, UCAL_DAY_OF_WEEK_IN_MONTH, UCAL_YEAR_WOY, UCAL_EXTENDED_YEAR, -1, }; static const char* FIELD_NAME[] = { "ERA", "YEAR", "MONTH", "WEEK_OF_YEAR", "WEEK_OF_MONTH", "DAY_OF_MONTH", "DAY_OF_YEAR", "DAY_OF_WEEK", "DAY_OF_WEEK_IN_MONTH", "AM_PM", "HOUR", "HOUR_OF_DAY", "MINUTE", "SECOND", "MILLISECOND", "ZONE_OFFSET", "DST_OFFSET", "YEAR_WOY", "DOW_LOCAL", "EXTENDED_YEAR", "JULIAN_DAY", "MILLISECONDS_IN_DAY", "IS_LEAP_MONTH" }; UErrorCode status = U_ZERO_ERROR; int32_t i, j; UnicodeString ymd; GregorianCalendar greg(status); if (failure(status, "new GregorianCalendar")) { return; } greg.setTime(startDate, status); if (failure(status, "GregorianCalendar::setTime")) { return; } logln((UnicodeString)"Start: " + startDate); if (fieldsToTest == NULL) { fieldsToTest = FIELDS; } // Keep a record of minima and maxima that we actually see. // These are kept in an array of arrays of hashes. int32_t limits[UCAL_FIELD_COUNT][4]; for (j = 0; j < UCAL_FIELD_COUNT; j++) { limits[j][0] = INT32_MAX; limits[j][1] = INT32_MIN; limits[j][2] = INT32_MAX; limits[j][3] = INT32_MIN; } // This test can run for a long time; show progress. UDate millis = ucal_getNow(); UDate mark = millis + 5000; // 5 sec millis -= testDuration * 1000; // stop time if testDuration<0 for (i = 0; testDuration > 0 ? i < testDuration : ucal_getNow() < millis; ++i) { if (ucal_getNow() >= mark) { logln((UnicodeString)"(" + i + " days)"); mark += 5000; // 5 sec } UDate testMillis = greg.getTime(status); cal.setTime(testMillis, status); cal.setMinimalDaysInFirstWeek(1); if (failure(status, "Calendar set/getTime")) { return; } for (j = 0; fieldsToTest[j] >= 0; ++j) { UCalendarDateFields f = (UCalendarDateFields)fieldsToTest[j]; int32_t v = cal.get(f, status); int32_t minActual = cal.getActualMinimum(f, status); int32_t maxActual = cal.getActualMaximum(f, status); int32_t minLow = cal.getMinimum(f); int32_t minHigh = cal.getGreatestMinimum(f); int32_t maxLow = cal.getLeastMaximum(f); int32_t maxHigh = cal.getMaximum(f); if (limits[j][0] > minActual) { // the minimum limits[j][0] = minActual; } if (limits[j][1] < minActual) { // the greatest minimum limits[j][1] = minActual; } if (limits[j][2] > maxActual) { // the least maximum limits[j][2] = maxActual; } if (limits[j][3] < maxActual) { // the maximum limits[j][3] = maxActual; } if (minActual < minLow || minActual > minHigh) { errln((UnicodeString)"Fail: [" + cal.getType() + "] " + ymdToString(cal, ymd) + " Range for min of " + FIELD_NAME[f] + "(" + f + ")=" + minLow + ".." + minHigh + ", actual_min=" + minActual); } if (maxActual < maxLow || maxActual > maxHigh) { if ( uprv_strcmp(cal.getType(), "chinese") == 0 && testMillis >= 2842992000000.0 && testMillis <= 2906668800000.0 && logKnownIssue("12620", "chinese calendar failures for some actualMax tests")) { logln((UnicodeString)"KnownFail: [" + cal.getType() + "] " + ymdToString(cal, ymd) + " Range for max of " + FIELD_NAME[f] + "(" + f + ")=" + maxLow + ".." + maxHigh + ", actual_max=" + maxActual); } else { errln((UnicodeString)"Fail: [" + cal.getType() + "] " + ymdToString(cal, ymd) + " Range for max of " + FIELD_NAME[f] + "(" + f + ")=" + maxLow + ".." + maxHigh + ", actual_max=" + maxActual); } } if (v < minActual || v > maxActual) { // timebomb per #9967, fix with #9972 if ( uprv_strcmp(cal.getType(), "dangi") == 0 && testMillis >= 1865635198000.0 && logKnownIssue("9972", "as per #9967")) { // Feb 2029 gregorian, end of dangi 4361 logln((UnicodeString)"KnownFail: [" + cal.getType() + "] " + ymdToString(cal, ymd) + " " + FIELD_NAME[f] + "(" + f + ")=" + v + ", actual=" + minActual + ".." + maxActual + ", allowed=(" + minLow + ".." + minHigh + ")..(" + maxLow + ".." + maxHigh + ")"); } else if ( uprv_strcmp(cal.getType(), "chinese") == 0 && testMillis >= 2842992000000.0 && testMillis <= 2906668800000.0 && logKnownIssue("12620", "chinese calendar failures for some actualMax tests")) { logln((UnicodeString)"KnownFail: [" + cal.getType() + "] " + ymdToString(cal, ymd) + " " + FIELD_NAME[f] + "(" + f + ")=" + v + ", actual=" + minActual + ".." + maxActual + ", allowed=(" + minLow + ".." + minHigh + ")..(" + maxLow + ".." + maxHigh + ")"); } else { errln((UnicodeString)"Fail: [" + cal.getType() + "] " + ymdToString(cal, ymd) + " " + FIELD_NAME[f] + "(" + f + ")=" + v + ", actual=" + minActual + ".." + maxActual + ", allowed=(" + minLow + ".." + minHigh + ")..(" + maxLow + ".." + maxHigh + ")"); } } } greg.add(UCAL_DAY_OF_YEAR, 1, status); if (failure(status, "Calendar::add")) { return; } } // Check actual maxima and minima seen against ranges returned // by API. UnicodeString buf; for (j = 0; fieldsToTest[j] >= 0; ++j) { int32_t rangeLow, rangeHigh; UBool fullRangeSeen = TRUE; UCalendarDateFields f = (UCalendarDateFields)fieldsToTest[j]; buf.remove(); buf.append((UnicodeString)"[" + cal.getType() + "] " + FIELD_NAME[f]); // Minumum rangeLow = cal.getMinimum(f); rangeHigh = cal.getGreatestMinimum(f); if (limits[j][0] != rangeLow || limits[j][1] != rangeHigh) { fullRangeSeen = FALSE; } buf.append((UnicodeString)" minima range=" + rangeLow + ".." + rangeHigh); buf.append((UnicodeString)" minima actual=" + limits[j][0] + ".." + limits[j][1]); // Maximum rangeLow = cal.getLeastMaximum(f); rangeHigh = cal.getMaximum(f); if (limits[j][2] != rangeLow || limits[j][3] != rangeHigh) { fullRangeSeen = FALSE; } buf.append((UnicodeString)" maxima range=" + rangeLow + ".." + rangeHigh); buf.append((UnicodeString)" maxima actual=" + limits[j][2] + ".." + limits[j][3]); if (fullRangeSeen) { logln((UnicodeString)"OK: " + buf); } else { // This may or may not be an error -- if the range of dates // we scan over doesn't happen to contain a minimum or // maximum, it doesn't mean some other range won't. logln((UnicodeString)"Warning: " + buf); } } logln((UnicodeString)"End: " + greg.getTime(status)); } UnicodeString& CalendarLimitTest::ymdToString(const Calendar& cal, UnicodeString& str) { UErrorCode status = U_ZERO_ERROR; str.remove(); str.append((UnicodeString)"" + cal.get(UCAL_EXTENDED_YEAR, status) + "/" + (cal.get(UCAL_MONTH, status) + 1) + (cal.get(UCAL_IS_LEAP_MONTH, status) == 1 ? "(leap)" : "") + "/" + cal.get(UCAL_DATE, status) + " " + cal.get(UCAL_HOUR_OF_DAY, status) + ":" + cal.get(UCAL_MINUTE, status) + " zone(hrs) " + cal.get(UCAL_ZONE_OFFSET, status)/(60.0*60.0*1000.0) + " dst(hrs) " + cal.get(UCAL_DST_OFFSET, status)/(60.0*60.0*1000.0) + ", time(millis)=" + cal.getTime(status)); return str; } #endif /* #if !UCONFIG_NO_FORMATTING */ // eof
mit
SkuLpI/exozet
src/Exozet/BerlinBundle/Tests/Controller/IndexControllerTest.php
3582
<?php namespace Exozet\BerlinBundle\Tests\Controller; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; class IndexControllerTest extends WebTestCase { //initialise different testdata protected $emptydata = array(); protected $createdata = array( 'name' => "Batman", 'origin' => "Gotham City", 'element' => "fire", 'skill' => "brain", 'special' => "catwoman", 'test' => "true" ); protected $updatedata = array( 'id' => "2", 'name' => "Superman", 'origin' => "Metropolis", 'element' => "cryptonit", 'skill' => "lasereyes", 'special' => "lois lane", 'test' => "true" ); protected $deletedata = array( 'id' => "6", 'test' => "true" ); protected $sortdata = array( 'type' => "element", 'up' => "false", 'filter' => "conzales", 'test' => "true" ); protected $sortdata2 = array( 'type' => "element", 'up' => "true", 'filter' => "", 'test' => "true" ); protected $filterdata = array( 'filter' => "batman", 'test' => "true" ); /** * test the app of different Ajax Responses */ public function testDifferentAjaxResponse() { $client = static::createClient(); //create an array for all data to proove $states = ["/hero/create", "/hero/update", "/hero/delete", "/hero/sort", "/hero/filter"]; $data = ["" => $this->emptydata, "/hero/create" => $this->createdata, "/hero/update" => $this->updatedata, "/hero/delete" => $this->deletedata, "/hero/sort" => $this->sortdata, "/hero/sort" => $this->sortdata2, "/hero/filter" => $this->filterdata]; //create different clients with array //get the response and check then for ($i = 0; $i < count($states); $i++) { foreach ($data AS $key => $value) { $client->request('POST', $states[$i], $value); $response = $client->getResponse(); //check if an answer is expected or not if ($states[$i] === $key || $states[$i] === "/hero/filter") { $this->checkTheResponse($client, $response, true); } else { if ($states[$i] === "/hero/delete" && $key === "/hero/update") { $this->checkTheResponse($client, $response, true); } else { $this->checkTheResponse($client, $response, false); } } } } } /** * check the response if status is okay, * the response is json and the data is not empty or empty * @param Client $client * @param Response $response * @param boolean $trueorfalse */ protected function checkTheResponse($client, $response, $trueorfalse) { // Test if response is OK $this->assertSame(200, $client->getResponse()->getStatusCode()); // Test if Content-Type is valid application/json $this->assertSame('text/html; charset=UTF-8', $response->headers->get('Content-Type')); //check if the response is empty or not if ($trueorfalse) { $this->assertNotSame('null', $client->getResponse()->getContent()); } else { $this->assertSame('null', $client->getResponse()->getContent()); } } }
mit
ptownsend1984/SampleApplications
ImageOrganizer/ImageOrganizer.Presentation/ImageOrganizerWindow.cs
2558
using System; using System.Linq; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using ImageOrganizer.ViewModels; using ImageOrganizer.ViewModels.Common; namespace ImageOrganizer.Presentation { public class ImageOrganizerWindow : System.Windows.Window { #region Properties #endregion #region Events #endregion #region Constructor public ImageOrganizerWindow() { this.DataContextChanged += (s, e) => { var OldValue = e.OldValue as ViewModel; if (OldValue != null) ClearDataContext(OldValue); var NewValue = e.NewValue as ViewModel; if (NewValue != null) SetDataContext(NewValue); }; } #endregion #region Event Handlers protected virtual void OnRequestClose(object sender, RequestCloseEventArgs e) { //http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/c95f1acb-5dee-4670-b779-b07b06afafff/ if (System.Windows.Interop.ComponentDispatcher.IsThreadModal) this.DialogResult = e.DialogResult; this.Close(); } #endregion #region Methods protected virtual void SetDataContext(ViewModel ViewModel) { if (ViewModel == null) return; var WindowViewModel = ViewModel as WindowViewModel; if (WindowViewModel != null) SetWindowViewModel(WindowViewModel); } protected virtual void SetWindowViewModel(WindowViewModel WindowViewModel) { if (WindowViewModel == null) return; WindowViewModel.Owner = this; WindowViewModel.RequestClose += OnRequestClose; } protected virtual void ClearDataContext(ViewModel ViewModel) { if (ViewModel == null) return; var WindowViewModel = ViewModel as WindowViewModel; if (WindowViewModel != null) ClearWindowViewModel(WindowViewModel); } protected virtual void ClearWindowViewModel(WindowViewModel WindowViewModel) { if (WindowViewModel == null) return; WindowViewModel.RequestClose -= OnRequestClose; WindowViewModel.Owner = null; } #endregion } }
mit
python-practice/lpthw
ex26/ex26.py
2281
def break_words(stuff): """This function will break up words for us.""" words = stuff.split(' ') return words def sort_words(words): """Sorts the words.""" return sorted(words) def print_first_word(words): """Prints the first word after popping it off.""" word = words.pop(0) print word def print_last_word(words): """Prints the last word after popping it off.""" word = words.pop(-1) print word def sort_sentence(sentence): """Takes in a full sentence and returns the sorted words.""" words = break_words(sentence) return sort_words(words) def print_first_and_last(sentence): """Prints the first and last words of the sentence.""" words = break_words(sentence) print_first_word(words) print_last_word(words) def print_first_and_last_sorted(sentence): """Sorts the words then prints the first and last one.""" words = sort_sentence(sentence) print_first_word(words) print_last_word(words) print "Let's practice everything." print 'You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs.' poem = """ \tThe lovely world with logic so firmly planted cannot discern \n the needs of love nor comprehend passion from intuition and requires an explantion \n\t\twhere there is none. """ print "--------------" print poem print "--------------" five = 10 - 2 + 3 - 6 print "This should be five: %s" % five def secret_formula(started): jelly_beans = started * 500 jars = jelly_beans / 1000 crates = jars / 100 return jelly_beans, jars, crates start_point = 10000 beans, jars, crates = secret_formula(start_point) print "With a starting point of: %d" % start_point print "We'd have %d jeans, %d jars, and %d crates." % (beans, jars, crates) start_point = start_point / 10 print "We can also do that this way:" print "We'd have %d beans, %d jars, and %d crates." % secret_formula(start_point) sentence = "All good things come to those who wait." words = break_words(sentence) sorted_words = sort_words(words) print_first_word(words) print_last_word(words) print_first_word(sorted_words) print_last_word(sorted_words) sorted_words = sort_sentence(sentence) print sorted_words print_first_and_last(sentence) print_first_and_last_sorted(sentence)
mit
spthaolt/dmsnavigation
src/main.cpp
1531
/** The MIT License (MIT) Copyright (c) 2014 thelostcode Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <QApplication> #include <QtGui> #include "DMSNavigation.h" int main(int argc, char** argv) { QApplication app(argc, argv); DMSNavigation navi; navi.resize(600, 50); navi.show(); navi.addTab(new QTextEdit("The first."), "Text 1"); navi.addTab(new QTextEdit("The second."), "Text 2"); navi.addTab(new QTextEdit("The third."), "Text 3"); return app.exec(); }
mit
glejeune/Capcode.more
capcode-render-mail/examples/render-email.rb
1443
require 'rubygems' require 'capcode' require 'capcode/render/markaby' require 'capcode/render/erb' require 'capcode/render/static' require 'graphviz' $:.unshift( "../lib" ) require 'capcode/render/email' module Capcode set :email, { :server => '127.0.0.1', :port => 25 } set :erb, "mail" set :static, "mail" class Index < Route '/' def get render :markaby => :index, :layout => :glop end end class SendMail < Route '/send' def get @time = Time.now render :email => { :from => 'you@yourdomain.com', :to => 'friend@hisdomain.com', :subject => "Mail renderer example...", :body => { :text => { :erb => :mail_text }, :html => { :erb => :mail_html, :content_type => 'text/html; charset=UTF-8' } }, :file => [ { :data => :image, :filename => "hello.png", :mime_type => "image/png" }, "rubyfr.png" ], :ok => { :erb => :ok }, :error => { :redirect => Index } } end end end module Capcode::Views def glop html do body do yield end end end def index h1 "Send me an email" a "Send mail", :href => URL(Capcode::SendMail) end def image GraphViz::new( "G" ) { |g| g.hello << g.world g.bonjour - g.monde g.hola > g.mundo g.holla >> g.welt }.output( :png => String ) end end Capcode.run( )
mit
lubo-raykov/TelerikAcademy
Intro-Programming-Homework/PrintMyName/05_PrintMyName.cs
429
using System; class PrintMyName { static void Main() { /* Problem 5. Print Your Name Modify the previous application to print your name. Ensure you have named the application well (e.g. “PrintMyName”). You should submit a separate project Visual Studio project holding the PrintMyName class as part of your homework. */ Console.WriteLine("My name is Lero"); } }
mit
Tom94/osu-framework
osu.Framework/Platform/Windows/WindowsStorage.cs
908
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Diagnostics; using System.Text.RegularExpressions; namespace osu.Framework.Platform.Windows { public class WindowsStorage : DesktopStorage { public WindowsStorage(string baseName, GameHost host) : base(baseName, host) { // allows traversal of long directory/filenames beyond the standard limitations (see https://stackoverflow.com/a/5188559) BasePath = Regex.Replace(BasePath, @"^([a-zA-Z]):\\", @"\\?\$1:\"); } public override void OpenInNativeExplorer() => Process.Start("explorer.exe", GetFullPath(string.Empty)); protected override string LocateBasePath() => Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); } }
mit
visualjeff/paypal_ember_models
tests/unit/serializers/paypal-test.js
325
import { test, moduleFor } from 'ember-qunit'; moduleFor('serializer:paypal', 'PaypalSerializer', { // Specify the other units that are required for this test. // needs: ['serializer:foo'] }); // Replace this with your real tests. test('it exists', function() { var serializer = this.subject(); ok(serializer); });
mit
pleary/inaturalist
app/controllers/lists_controller.rb
12614
class ListsController < ApplicationController include Shared::ListsModule include Shared::GuideModule before_filter :authenticate_user!, :except => [:index, :show, :by_login, :taxa, :guide, :cached_guide, :guide_widget] load_except = [ :index, :new, :create, :by_login ] before_filter :load_list, :except => load_except blocks_spam :except => load_except, :instance => :list check_spam only: [:create, :update], instance: :list before_filter :owner_required, :only => [:edit, :update, :destroy, :remove_taxon, :reload_from_observations] before_filter :require_listed_taxa_editor, :only => [:add_taxon_batch, :batch_edit] before_filter :load_user_by_login, :only => :by_login before_filter :admin_required, :only => [:add_from_observations_now, :refresh_now] before_filter :set_iconic_taxa, :only => [:show] caches_page :show, :if => Proc.new {|c| c.request.format == :csv} requires_privilege :speech, only: [:new, :create] LIST_SORTS = %w"id title" LIST_ORDERS = %w"asc desc" ## Custom actions ############################################################ # gets lists by user login def by_login block_if_spammer(@selected_user) && return @prefs = current_preferences @life_list = @selected_user.life_list @lists = @selected_user.personal_lists. order("#{@prefs["lists_by_login_sort"]} #{@prefs["lists_by_login_order"]}"). paginate(:page => params[:page], :per_page => @prefs["per_page"]) # This is terribly inefficient. Might have to be smarter if there are # lots of lists. @iconic_taxa_for = {} @lists.each do |list| unless fragment_exist?(List.icon_preview_cache_key(list)) taxon_ids = list.listed_taxa.select(:taxon_id). order("id desc").limit(50).map(&:taxon_id) unless taxon_ids.blank? phototaxa = Taxon.where(id: taxon_ids).includes(:photos) @iconic_taxa_for[list.id] = phototaxa[0...9] end end end respond_to do |format| format.html end end # Compare two lists. Defaults to comparing the list in the URL with the # viewer's list. def compare @with = List.find_by_id(params[:with]) @with ||= current_user.life_list if logged_in? @iconic_taxa = Taxon::ICONIC_TAXA unless @with flash[:notice] = t(:you_cant_compare_a_list_with_nothing) return redirect_to(list_path(@list)) end find_options = { :include => [:taxon], :order => "taxa.ancestry" } # Load listed taxa for pagination paginating_find_options = find_options.merge( :page => params[:page], :per_page => 26) left_condition = ["list_id = ?", @list] right_condition = ["list_id = ?", @with] both_condition = ["list_id in (?)", [@list, @with].compact] # TODO: pull out check list logic if @list.is_a?(CheckList) && @list.is_default? left_condition = ["place_id = ?", @list.place_id] both_condition = ["(place_id = ? OR list_id = ?)", @list.place_id, @with] end @show_list = params[:show] if %w(left right).include?(params[:show]) list_conditions = case @show_list when "left" then left_condition when "right" then right_condition else both_condition end paginating_find_options[:conditions] = list_conditions # Handle iconic taxon filtering if params[:taxon] @filter_taxon = Taxon.find_by_id(params[:taxon]) paginating_find_options[:conditions] = update_conditions(paginating_find_options[:conditions], ["AND taxa.iconic_taxon_id = ?", @filter_taxon]) end @paginating_listed_taxa = ListedTaxon.where(paginating_find_options[:conditions]). includes(paginating_find_options[:include]). paginate(page: paginating_find_options[:page], per_page: paginating_find_options[:per_page]). order(paginating_find_options[:order]) # Load the listed taxa for display. The reason we do diplay and paginating # listed taxa is that strictly paginating and ordering by lft would sometimes # leave some taxa off the end. Say you grabbed 26 listed_taxa and the last in # list1 was a Snowy Egret, but since list2 actually had more taxa than list1 # on this page, the page didn't include list2's snowy egret, b/c it would be # on the next page. I know, I'm confused even writing it. KMU 2009-02-08 find_options[:conditions] = update_conditions(both_condition, ["AND listed_taxa.taxon_id IN (?)", @paginating_listed_taxa.map(&:taxon_id)]) find_options[:include] = [ :last_observation, {:taxon => [:iconic_taxon, :photos, :taxon_names]} ] @listed_taxa = ListedTaxon.where(find_options[:conditions]). includes(find_options[:include]). order(find_options[:order]) # Group listed_taxa into owner / other pairs @pairs = [] @listed_taxa.group_by(&:taxon_id).each do |taxon_id, listed_taxa| listed_taxa << nil if listed_taxa.size == 1 if @list.is_a?(CheckList) && @list.is_default? listed_taxa.reverse! if listed_taxa.first.place_id != @list.place_id else listed_taxa.reverse! if listed_taxa.first.list_id != @list.id end @pairs << listed_taxa end # Calculate the stats # TODO: pull out check list logic @total_listed_taxa = if @list.is_a?(CheckList) && @list.is_default? ListedTaxon.distinct.where(place_id: @list.place_id).count(:taxon_id) else @list.listed_taxa.count end @with_total_listed_taxa = @with.listed_taxa.count @max_total_listed_taxa = [@total_listed_taxa, @with_total_listed_taxa].max @iconic_taxon_counts = get_iconic_taxon_counts(@list, @iconic_taxa) @with_iconic_taxon_counts = get_iconic_taxon_counts(@with, @iconic_taxa) @iconic_taxon_counts_hash = {} @iconic_taxon_counts.each do |iconic_taxon, count| if iconic_taxon.nil? @iconic_taxon_counts_hash['Undefined'] = count else @iconic_taxon_counts_hash[iconic_taxon] = count end end @with_iconic_taxon_counts_hash = {} @with_iconic_taxon_counts.each do |iconic_taxon, count| if iconic_taxon.nil? @with_iconic_taxon_counts_hash['Undefined'] = count else @with_iconic_taxon_counts_hash[iconic_taxon] = count end end @paired_iconic_taxon_counts = @iconic_taxa.map do |iconic_taxon| pair = [ @iconic_taxon_counts_hash[iconic_taxon], @with_iconic_taxon_counts_hash[iconic_taxon] ] pair.compact.empty? ? nil : [iconic_taxon, pair] end.compact load_listed_taxon_photos end def remove_taxon respond_to do |format| if @listed_taxon = @list.listed_taxa.find_by_taxon_id(params[:taxon_id].to_i) @listed_taxon.destroy format.html do flash[:notice] = t(:taxon_removed_from_list) redirect_to @list end format.js do render :text => t(:taxon_removed_from_list) end format.json do render :json => @listed_taxon end else format.html do flash[:error] = t(:couldnt_find_that_taxon) redirect_to @list end format.js do render :status => :unprocessable_entity, :text => "That taxon isn't in this list." end format.json do render :status => :unprocessable_entity, :json => {:error => "That taxon isn't in this list."} end end end end def reload_from_observations delayed_task(@list.reload_from_observations_cache_key) do @list.reload_from_observations end respond_to_delayed_task( done: t(:list_reloaded_from_observations), error: t(:doh_something_went_wrong), timeout: t(:reload_timed_out) ) end def refresh delayed_task(@list.refresh_cache_key) do queue = @list.is_a?(CheckList) ? "slow" : nil if job = @list.delay(priority: USER_PRIORITY, queue: queue, unique_hash: { "#{ @list.class.name }::refresh": @list.id } ).refresh(skip_update_cache_columns: true) Rails.cache.write(@list.refresh_cache_key, job.id) job end end respond_to_delayed_task( done: t(:list_rules_reapplied), error: t(:doh_something_went_wrong), timeout: t(:request_timed_out) ) end def add_from_observations_now delayed_task(@list.reload_from_observations_cache_key) do if job = @list.delay(priority: USER_PRIORITY, unique_hash: { "#{ @list.class.name }::add_observed_taxa": @list.id } ).add_observed_taxa(:force_update_cache_columns => true) Rails.cache.write(@list.reload_from_observations_cache_key, job.id) job end end respond_to_delayed_task( :done => "List reloaded from observations", :error => "Something went wrong reloading from observations", :timeout => "Reload timed out, please try again later" ) end def refresh_now delayed_task(@list.refresh_cache_key) do if job = @list.delay(priority: USER_PRIORITY, unique_hash: { "#{ @list.class.name }::refresh": @list.id } ).refresh Rails.cache.write(@list.refresh_cache_key, job.id) job end end respond_to_delayed_task( :done => "List rules re-applied", :error => "Something went wrong re-applying list rules", :timeout => "Re-applying list rules timed out, please try again later" ) end def guide show_guide do |scope| scope = scope.on_list(@list) end @listed_taxa = @list.listed_taxa.where(taxon_id: @taxa). select("DISTINCT ON (taxon_id) listed_taxa.*") @listed_taxa_by_taxon_id = @listed_taxa.index_by{|lt| lt.taxon_id} render :layout => false, :partial => @partial end def guide_widget @guide_url = url_for(:action => "guide", :id => @list) show_guide_widget render :template => "guides/guide_widget" end private # Takes a block that sets the @job instance var def delayed_task(cache_key) @job_id = Rails.cache.read(cache_key) @job = Delayed::Job.find_by_id(@job_id) if @job_id && @job_id.is_a?(Integer) @tries = params[:tries].to_i @start = @tries == 0 && @job.blank? @done = @tries > 0 && @job.blank? @error = @job && !@job.failed_at.blank? @timeout = @tries > LifeList::MAX_RELOAD_TRIES if @start @job = yield elsif @done || @error || @timeout Rails.cache.delete(cache_key) end end def respond_to_delayed_task(messages = {}) @messages = { :done => "Success!", :error => "Something went wrong", :timeout => "Request timed out, please try again later", :processing => t(:processing3p) }.merge(messages) respond_to do |format| format.js do if @done flash[:notice] = messages[:done] render :status => :ok, :text => @messages[:done] elsif @error then render :status => :unprocessable_entity, :text => "#{@messages[:error]}: #{@job.last_error}" elsif @timeout then render :status => :request_timeout, :text => @messages[:timeout] else render :status => :created, :text => @messages[:processing] end end end end def owner_required unless logged_in? flash[:notice] = t(:only_the_owner_of_this_list_can_do_that) redirect_back_or_default('/') return false end if @list.is_a?(ProjectList) project = Project.find_by_id(@list.project_id) unless project.project_users.exists?(["role IN ('curator', 'manager') AND user_id = ?", current_user]) flash[:notice] = t(:only_the_owner_of_this_list_can_do_that) redirect_back_or_default('/') return false end else unless @list.user_id == current_user.id || current_user.is_admin? flash[:notice] = t(:only_the_owner_of_this_list_can_do_that) redirect_back_or_default('/') return false end end end def load_listed_taxon_photos @photos_by_listed_taxon_id = {} obs_ids = @listed_taxa.map(&:last_observation_id).compact obs_photos = ObservationPhoto.where(observation_id: obs_ids). select("DISTINCT ON (observation_id) *"). includes({ :photo => :user }) obs_photos_by_obs_id = obs_photos.index_by(&:observation_id) @listed_taxa.each do |lt| next unless (op = obs_photos_by_obs_id[lt.last_observation_id]) @photos_by_listed_taxon_id[lt.id] = op.photo end end end
mit
Mrokkk/objective-kernel
drivers/keyboard.cpp
3927
#include <kernel/cpu/io.hpp> #include <kernel/kernel.hpp> #include "keyboard.hpp" namespace drivers { namespace keyboard { #define CMD_PORT 0x64 #define DATA_PORT 0x60 #define STATUS_PORT 0x64 #define CMD_ENABLE_FIRST 0xae #define CMD_DISABLE_FIRST 0xad #define CMD_DISABLE_SECOND 0xa7 #define CMD_TEST_CONTROLLER 0xaa #define CMD_TEST_FIRST_PS2_PORT 0xab #define CMD_READ_CONFIGURATION_BYTE 0x20 #define CMD_WRITE_CONFIGURATION_BYTE 0x60 #define keyboard_disable() \ do { keyboard_send_command(CMD_DISABLE_FIRST); keyboard_wait(); } while (0) #define keyboard_enable() \ keyboard_send_command(CMD_ENABLE_FIRST) #define L_CTRL 0x1d #define L_ALT 0x38 #define L_SHIFT 0x2a #define R_SHIFT 0x36 //int shift = 0; //char ctrl = 0; //char alt = 0; //[> Scancodes actions <] //void s_shift_up() { //shift = 1; //} //void s_shift_down() { //shift = 0; //} //void s_ctrl_up() { //ctrl = 1; //} //void s_ctrl_down() { //ctrl = 0; //} //void s_alt_up() { //alt = 1; //} //void s_alt_down() { //alt = 0; //} //typedef void (*saction_t)(); #define scancode_action(code, action) \ [code] = action##_up, \ [code + 0x80] = action##_down, //saction_t special_scancodes[] = { //[L_CTRL] = &s_ctrl_up, //[L_CTRL+0x80] = &s_ctrl_down, //[L_SHIFT] = &s_shift_up, //[L_SHIFT+0x80] = &s_shift_down, //[R_SHIFT] = &s_shift_up, //[R_SHIFT+0x80] = &s_shift_down, //[L_ALT] = &s_alt_up, //[L_ALT+0x80] = &s_alt_down //}; const char *scancodes[] = { "\0\0", "\0\0", "1!", "2@", "3#", "4$", "5%", "6^", "7&", "8*", "9(", "0)", "-_", "=+", "\b\b", "\t\t", "qQ", "wW", "eE", "rR", "tT", "yY", "uU", "iI", "oO", "pP", "[{", "]}", "\n\n", "\0\0", "aA", "sS", "dD", "fF", "gG", "hH", "jJ", "kK", "lL", ";:", "'\"", "`~", "\0\0", "\\|", "zZ", "xX", "cC", "vV", "bB", "nN", "mM", ",<", ".>", "/?", "\0\0", "**", "\0\0", " ", "\0\0" }; namespace { void keyboard_wait() { for (auto i = 0; i < 10000; ++i) if (!(cpu::io::inb(STATUS_PORT) & 0x2)) return; //printk("Keyboard waiting timeout\n"); } void keyboard_send_command(const uint8_t byte) { keyboard_wait(); cpu::io::outb(byte, CMD_PORT); cpu::io::io_wait(); } uint8_t keyboard_receive() { while ((cpu::io::inb(STATUS_PORT) & 0x1) != 1); return cpu::io::inb(DATA_PORT); } void irs(uint32_t, cpu::stack_frame*) { auto scan_code = keyboard_receive(); if (scan_code > 0x39) return; keyboard_disable(); //auto character = scancodes[scan_code][0]; //console::printf("%c", character); keyboard_enable(); } } // namespace void initialize() { uint8_t byte; keyboard_disable(); keyboard_send_command(CMD_DISABLE_SECOND); while (cpu::io::inb(STATUS_PORT) & 1) cpu::io::inb(DATA_PORT); cpu::io::io_wait(); keyboard_send_command(CMD_TEST_CONTROLLER); byte = keyboard_receive(); if (byte != 0x55) return; keyboard_send_command(CMD_READ_CONFIGURATION_BYTE); byte = keyboard_receive(); /* If translation is disabled, try to enable it */ if (!(byte & (1 << 6))) { byte |= (1 << 6); keyboard_send_command(CMD_WRITE_CONFIGURATION_BYTE); cpu::io::outb(byte, DATA_PORT); keyboard_wait(); keyboard_send_command(CMD_READ_CONFIGURATION_BYTE); if (!(keyboard_receive() & (1 << 6))) return; } /* Enable interrupt */ if (!(byte & 0x1)) { byte |= 0x1; keyboard_send_command(CMD_WRITE_CONFIGURATION_BYTE); cpu::io::outb(byte, DATA_PORT); keyboard_wait(); } keyboard_enable(); kernel::kernel::interrupt_manager().register_handler(0x01, &irs, "keyboard"); } } // namespace keyboard } // namespace drivers
mit
xavier-berthiaume/HotelReservationSystem
src/dw317/lib/creditcard/MasterCard.java
1509
package dw317.lib.creditcard; public class MasterCard extends AbstractCreditCard{ private static final long serializeVersionUID = 42031768871L; public MasterCard(String number) throws IllegalArgumentException { super(cardtype.MASTERCARD, validateNumber(number)); } /** * This method evaluates the two first numbers of the entered credit card, to see if it complies * with a valid MasterCard. This is the first check to see if the card works. * * @param number - The number of the credit card * @return boolean - The value that determines if the two starting digits of the card comply with * the norms of MasterCard */ private static boolean checkTwoFirstNumbers(String number){ String checkNum = number.substring(0, 2); if (checkNum.equals("50") || checkNum.equals("51") || checkNum.equals("52") || checkNum.equals("53") || checkNum.equals("54") || checkNum.equals("55")) return true; return false; } /** * Validates the number to check if it's a valid credit card number. The validation scheme * is that the first number must be a 5, and then follow up with any number from 1 - 5, and the number * must be 16 digits long. * * @param number * @return The same number value if it passes the validation * @throws IllegalArgumentException */ private static String validateNumber(String number) throws IllegalArgumentException { if(number.length() == 16 && checkTwoFirstNumbers(number)) return number; throw new IllegalArgumentException(); } }
mit
marianamn/Telerik-Academy-Activities
Homeworks/03. CSharp-Advance/04. Numeral Systems/03.DecimalToHexadecimal/Properties/AssemblyInfo.cs
1422
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("03.DecimalToHexadecimal")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("03.DecimalToHexadecimal")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("29c9e6da-fc0f-40e1-bbbb-7521dbfb224a")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
pwistbac/material
src/components/dialog/dialog.js
46663
/** * @ngdoc module * @name material.components.dialog */ angular .module('material.components.dialog', [ 'material.core', 'material.components.backdrop' ]) .directive('mdDialog', MdDialogDirective) .provider('$mdDialog', MdDialogProvider); /** * @ngdoc directive * @name mdDialog * @module material.components.dialog * * @restrict E * * @description * `<md-dialog>` - The dialog's template must be inside this element. * * Inside, use an `<md-dialog-content>` element for the dialog's content, and use * an `<md-dialog-actions>` element for the dialog's actions. * * ## CSS * - `.md-dialog-content` - class that sets the padding on the content as the spec file * * ## Notes * - If you specify an `id` for the `<md-dialog>`, the `<md-dialog-content>` will have the same `id` * prefixed with `dialogContent_`. * * @usage * ### Dialog template * <hljs lang="html"> * <md-dialog aria-label="List dialog"> * <md-dialog-content> * <md-list> * <md-list-item ng-repeat="item in items"> * <p>Number {{item}}</p> * </md-list-item> * </md-list> * </md-dialog-content> * <md-dialog-actions> * <md-button ng-click="closeDialog()" class="md-primary">Close Dialog</md-button> * </md-dialog-actions> * </md-dialog> * </hljs> */ function MdDialogDirective($$rAF, $mdTheming, $mdDialog) { return { restrict: 'E', link: function(scope, element) { element.addClass('_md'); // private md component indicator for styling $mdTheming(element); $$rAF(function() { var images; var content = element[0].querySelector('md-dialog-content'); if (content) { images = content.getElementsByTagName('img'); addOverflowClass(); //-- delayed image loading may impact scroll height, check after images are loaded angular.element(images).on('load', addOverflowClass); } scope.$on('$destroy', function() { $mdDialog.destroy(element); }); /** * */ function addOverflowClass() { element.toggleClass('md-content-overflow', content.scrollHeight > content.clientHeight); } }); } }; } /** * @ngdoc service * @name $mdDialog * @module material.components.dialog * * @description * `$mdDialog` opens a dialog over the app to inform users about critical information or require * them to make decisions. There are two approaches for setup: a simple promise API * and regular object syntax. * * ## Restrictions * * - The dialog is always given an isolate scope. * - The dialog's template must have an outer `<md-dialog>` element. * Inside, use an `<md-dialog-content>` element for the dialog's content, and use * an `<md-dialog-actions>` element for the dialog's actions. * - Dialogs must cover the entire application to keep interactions inside of them. * Use the `parent` option to change where dialogs are appended. * * ## Sizing * - Complex dialogs can be sized with `flex="percentage"`, i.e. `flex="66"`. * - Default max-width is 80% of the `rootElement` or `parent`. * * ## CSS * - `.md-dialog-content` - class that sets the padding on the content as the spec file * * @usage * <hljs lang="html"> * <div ng-app="demoApp" ng-controller="EmployeeController"> * <div> * <md-button ng-click="showAlert()" class="md-raised md-warn"> * Employee Alert! * </md-button> * </div> * <div> * <md-button ng-click="showDialog($event)" class="md-raised"> * Custom Dialog * </md-button> * </div> * <div> * <md-button ng-click="closeAlert()" ng-disabled="!hasAlert()" class="md-raised"> * Close Alert * </md-button> * </div> * <div> * <md-button ng-click="showGreeting($event)" class="md-raised md-primary" > * Greet Employee * </md-button> * </div> * </div> * </hljs> * * ### JavaScript: object syntax * <hljs lang="js"> * (function(angular, undefined){ * "use strict"; * * angular * .module('demoApp', ['ngMaterial']) * .controller('AppCtrl', AppController); * * function AppController($scope, $mdDialog) { * var alert; * $scope.showAlert = showAlert; * $scope.showDialog = showDialog; * $scope.items = [1, 2, 3]; * * // Internal method * function showAlert() { * alert = $mdDialog.alert({ * title: 'Attention', * textContent: 'This is an example of how easy dialogs can be!', * ok: 'Close' * }); * * $mdDialog * .show( alert ) * .finally(function() { * alert = undefined; * }); * } * * function showDialog($event) { * var parentEl = angular.element(document.body); * $mdDialog.show({ * parent: parentEl, * targetEvent: $event, * template: * '<md-dialog aria-label="List dialog">' + * ' <md-dialog-content>'+ * ' <md-list>'+ * ' <md-list-item ng-repeat="item in items">'+ * ' <p>Number {{item}}</p>' + * ' </md-item>'+ * ' </md-list>'+ * ' </md-dialog-content>' + * ' <md-dialog-actions>' + * ' <md-button ng-click="closeDialog()" class="md-primary">' + * ' Close Dialog' + * ' </md-button>' + * ' </md-dialog-actions>' + * '</md-dialog>', * locals: { * items: $scope.items * }, * controller: DialogController * }); * function DialogController($scope, $mdDialog, items) { * $scope.items = items; * $scope.closeDialog = function() { * $mdDialog.hide(); * } * } * } * } * })(angular); * </hljs> * * ### Multiple Dialogs * Using the `multiple` option for the `$mdDialog` service allows developers to show multiple dialogs * at the same time. * * <hljs lang="js"> * // From plain options * $mdDialog.show({ * multiple: true * }); * * // From a dialog preset * $mdDialog.show( * $mdDialog * .alert() * .multiple(true) * ); * * </hljs> * * ### Pre-Rendered Dialogs * By using the `contentElement` option, it is possible to use an already existing element in the DOM. * * > Pre-rendered dialogs will be not linked to any scope and will not instantiate any new controller.<br/> * > You can manually link the elements to a scope or instantiate a controller from the template (`ng-controller`) * * <hljs lang="js"> * $scope.showPrerenderedDialog = function() { * $mdDialog.show({ * contentElement: '#myStaticDialog', * parent: angular.element(document.body) * }); * }; * </hljs> * * When using a string as value, `$mdDialog` will automatically query the DOM for the specified CSS selector. * * <hljs lang="html"> * <div style="visibility: hidden"> * <div class="md-dialog-container" id="myStaticDialog"> * <md-dialog> * This is a pre-rendered dialog. * </md-dialog> * </div> * </div> * </hljs> * * **Notice**: It is important, to use the `.md-dialog-container` as the content element, otherwise the dialog * will not show up. * * It also possible to use a DOM element for the `contentElement` option. * - `contentElement: document.querySelector('#myStaticDialog')` * - `contentElement: angular.element(TEMPLATE)` * * When using a `template` as content element, it will be not compiled upon open. * This allows you to compile the element yourself and use it each time the dialog opens. * * ### Custom Presets * Developers are also able to create their own preset, which can be easily used without repeating * their options each time. * * <hljs lang="js"> * $mdDialogProvider.addPreset('testPreset', { * options: function() { * return { * template: * '<md-dialog>' + * 'This is a custom preset' + * '</md-dialog>', * controllerAs: 'dialog', * bindToController: true, * clickOutsideToClose: true, * escapeToClose: true * }; * } * }); * </hljs> * * After you created your preset at config phase, you can easily access it. * * <hljs lang="js"> * $mdDialog.show( * $mdDialog.testPreset() * ); * </hljs> * * ### JavaScript: promise API syntax, custom dialog template * <hljs lang="js"> * (function(angular, undefined){ * "use strict"; * * angular * .module('demoApp', ['ngMaterial']) * .controller('EmployeeController', EmployeeEditor) * .controller('GreetingController', GreetingController); * * // Fictitious Employee Editor to show how to use simple and complex dialogs. * * function EmployeeEditor($scope, $mdDialog) { * var alert; * * $scope.showAlert = showAlert; * $scope.closeAlert = closeAlert; * $scope.showGreeting = showCustomGreeting; * * $scope.hasAlert = function() { return !!alert }; * $scope.userName = $scope.userName || 'Bobby'; * * // Dialog #1 - Show simple alert dialog and cache * // reference to dialog instance * * function showAlert() { * alert = $mdDialog.alert() * .title('Attention, ' + $scope.userName) * .textContent('This is an example of how easy dialogs can be!') * .ok('Close'); * * $mdDialog * .show( alert ) * .finally(function() { * alert = undefined; * }); * } * * // Close the specified dialog instance and resolve with 'finished' flag * // Normally this is not needed, just use '$mdDialog.hide()' to close * // the most recent dialog popup. * * function closeAlert() { * $mdDialog.hide( alert, "finished" ); * alert = undefined; * } * * // Dialog #2 - Demonstrate more complex dialogs construction and popup. * * function showCustomGreeting($event) { * $mdDialog.show({ * targetEvent: $event, * template: * '<md-dialog>' + * * ' <md-dialog-content>Hello {{ employee }}!</md-dialog-content>' + * * ' <md-dialog-actions>' + * ' <md-button ng-click="closeDialog()" class="md-primary">' + * ' Close Greeting' + * ' </md-button>' + * ' </md-dialog-actions>' + * '</md-dialog>', * controller: 'GreetingController', * onComplete: afterShowAnimation, * locals: { employee: $scope.userName } * }); * * // When the 'enter' animation finishes... * * function afterShowAnimation(scope, element, options) { * // post-show code here: DOM element focus, etc. * } * } * * // Dialog #3 - Demonstrate use of ControllerAs and passing $scope to dialog * // Here we used ng-controller="GreetingController as vm" and * // $scope.vm === <controller instance> * * function showCustomGreeting() { * * $mdDialog.show({ * clickOutsideToClose: true, * * scope: $scope, // use parent scope in template * preserveScope: true, // do not forget this if use parent scope * // Since GreetingController is instantiated with ControllerAs syntax * // AND we are passing the parent '$scope' to the dialog, we MUST * // use 'vm.<xxx>' in the template markup * * template: '<md-dialog>' + * ' <md-dialog-content>' + * ' Hi There {{vm.employee}}' + * ' </md-dialog-content>' + * '</md-dialog>', * * controller: function DialogController($scope, $mdDialog) { * $scope.closeDialog = function() { * $mdDialog.hide(); * } * } * }); * } * * } * * // Greeting controller used with the more complex 'showCustomGreeting()' custom dialog * * function GreetingController($scope, $mdDialog, employee) { * // Assigned from construction <code>locals</code> options... * $scope.employee = employee; * * $scope.closeDialog = function() { * // Easily hides most recent dialog shown... * // no specific instance reference is needed. * $mdDialog.hide(); * }; * } * * })(angular); * </hljs> */ /** * @ngdoc method * @name $mdDialog#alert * * @description * Builds a preconfigured dialog with the specified message. * * @returns {obj} an `$mdDialogPreset` with the chainable configuration methods: * * - $mdDialogPreset#title(string) - Sets the alert title. * - $mdDialogPreset#textContent(string) - Sets the alert message. * - $mdDialogPreset#htmlContent(string) - Sets the alert message as HTML. Requires ngSanitize * module to be loaded. HTML is not run through Angular's compiler. * - $mdDialogPreset#ok(string) - Sets the alert "Okay" button text. * - $mdDialogPreset#theme(string) - Sets the theme of the alert dialog. * - $mdDialogPreset#targetEvent(DOMClickEvent=) - A click's event object. When passed in as an option, * the location of the click will be used as the starting point for the opening animation * of the the dialog. * */ /** * @ngdoc method * @name $mdDialog#confirm * * @description * Builds a preconfigured dialog with the specified message. You can call show and the promise returned * will be resolved only if the user clicks the confirm action on the dialog. * * @returns {obj} an `$mdDialogPreset` with the chainable configuration methods: * * Additionally, it supports the following methods: * * - $mdDialogPreset#title(string) - Sets the confirm title. * - $mdDialogPreset#textContent(string) - Sets the confirm message. * - $mdDialogPreset#htmlContent(string) - Sets the confirm message as HTML. Requires ngSanitize * module to be loaded. HTML is not run through Angular's compiler. * - $mdDialogPreset#ok(string) - Sets the confirm "Okay" button text. * - $mdDialogPreset#cancel(string) - Sets the confirm "Cancel" button text. * - $mdDialogPreset#theme(string) - Sets the theme of the confirm dialog. * - $mdDialogPreset#targetEvent(DOMClickEvent=) - A click's event object. When passed in as an option, * the location of the click will be used as the starting point for the opening animation * of the the dialog. * */ /** * @ngdoc method * @name $mdDialog#prompt * * @description * Builds a preconfigured dialog with the specified message and input box. You can call show and the promise returned * will be resolved only if the user clicks the prompt action on the dialog, passing the input value as the first argument. * * @returns {obj} an `$mdDialogPreset` with the chainable configuration methods: * * Additionally, it supports the following methods: * * - $mdDialogPreset#title(string) - Sets the prompt title. * - $mdDialogPreset#textContent(string) - Sets the prompt message. * - $mdDialogPreset#htmlContent(string) - Sets the prompt message as HTML. Requires ngSanitize * module to be loaded. HTML is not run through Angular's compiler. * - $mdDialogPreset#placeholder(string) - Sets the placeholder text for the input. * - $mdDialogPreset#initialValue(string) - Sets the initial value for the prompt input. * - $mdDialogPreset#ok(string) - Sets the prompt "Okay" button text. * - $mdDialogPreset#cancel(string) - Sets the prompt "Cancel" button text. * - $mdDialogPreset#theme(string) - Sets the theme of the prompt dialog. * - $mdDialogPreset#targetEvent(DOMClickEvent=) - A click's event object. When passed in as an option, * the location of the click will be used as the starting point for the opening animation * of the the dialog. * */ /** * @ngdoc method * @name $mdDialog#show * * @description * Show a dialog with the specified options. * * @param {object} optionsOrPreset Either provide an `$mdDialogPreset` returned from `alert()`, and * `confirm()`, or an options object with the following properties: * - `templateUrl` - `{string=}`: The url of a template that will be used as the content * of the dialog. * - `template` - `{string=}`: HTML template to show in the dialog. This **must** be trusted HTML * with respect to Angular's [$sce service](https://docs.angularjs.org/api/ng/service/$sce). * This template should **never** be constructed with any kind of user input or user data. * - `contentElement` - `{string|Element}`: Instead of using a template, which will be compiled each time a * dialog opens, you can also use a DOM element.<br/> * * When specifying an element, which is present on the DOM, `$mdDialog` will temporary fetch the element into * the dialog and restores it at the old DOM position upon close. * * When specifying a string, the string be used as a CSS selector, to lookup for the element in the DOM. * - `autoWrap` - `{boolean=}`: Whether or not to automatically wrap the template with a * `<md-dialog>` tag if one is not provided. Defaults to true. Can be disabled if you provide a * custom dialog directive. * - `targetEvent` - `{DOMClickEvent=}`: A click's event object. When passed in as an option, * the location of the click will be used as the starting point for the opening animation * of the the dialog. * - `openFrom` - `{string|Element|object}`: The query selector, DOM element or the Rect object * that is used to determine the bounds (top, left, height, width) from which the Dialog will * originate. * - `closeTo` - `{string|Element|object}`: The query selector, DOM element or the Rect object * that is used to determine the bounds (top, left, height, width) to which the Dialog will * target. * - `scope` - `{object=}`: the scope to link the template / controller to. If none is specified, * it will create a new isolate scope. * This scope will be destroyed when the dialog is removed unless `preserveScope` is set to true. * - `preserveScope` - `{boolean=}`: whether to preserve the scope when the element is removed. Default is false * - `disableParentScroll` - `{boolean=}`: Whether to disable scrolling while the dialog is open. * Default true. * - `hasBackdrop` - `{boolean=}`: Whether there should be an opaque backdrop behind the dialog. * Default true. * - `clickOutsideToClose` - `{boolean=}`: Whether the user can click outside the dialog to * close it. Default false. * - `escapeToClose` - `{boolean=}`: Whether the user can press escape to close the dialog. * Default true. * - `focusOnOpen` - `{boolean=}`: An option to override focus behavior on open. Only disable if * focusing some other way, as focus management is required for dialogs to be accessible. * Defaults to true. * - `controller` - `{function|string=}`: The controller to associate with the dialog. The controller * will be injected with the local `$mdDialog`, which passes along a scope for the dialog. * - `locals` - `{object=}`: An object containing key/value pairs. The keys will be used as names * of values to inject into the controller. For example, `locals: {three: 3}` would inject * `three` into the controller, with the value 3. If `bindToController` is true, they will be * copied to the controller instead. * - `bindToController` - `bool`: bind the locals to the controller, instead of passing them in. * - `resolve` - `{object=}`: Similar to locals, except it takes promises as values, and the * dialog will not open until all of the promises resolve. * - `controllerAs` - `{string=}`: An alias to assign the controller to on the scope. * - `parent` - `{element=}`: The element to append the dialog to. Defaults to appending * to the root element of the application. * - `onShowing` - `function(scope, element)`: Callback function used to announce the show() action is * starting. * - `onComplete` - `function(scope, element)`: Callback function used to announce when the show() action is * finished. * - `onRemoving` - `function(element, removePromise)`: Callback function used to announce the * close/hide() action is starting. This allows developers to run custom animations * in parallel the close animations. * - `fullscreen` `{boolean=}`: An option to toggle whether the dialog should show in fullscreen * or not. Defaults to `false`. * - `multiple` `{boolean=}`: An option to allow this dialog to display over one that's currently open. * @returns {promise} A promise that can be resolved with `$mdDialog.hide()` or * rejected with `$mdDialog.cancel()`. */ /** * @ngdoc method * @name $mdDialog#hide * * @description * Hide an existing dialog and resolve the promise returned from `$mdDialog.show()`. * * @param {*=} response An argument for the resolved promise. * * @returns {promise} A promise that is resolved when the dialog has been closed. */ /** * @ngdoc method * @name $mdDialog#cancel * * @description * Hide an existing dialog and reject the promise returned from `$mdDialog.show()`. * * @param {*=} response An argument for the rejected promise. * * @returns {promise} A promise that is resolved when the dialog has been closed. */ function MdDialogProvider($$interimElementProvider) { // Elements to capture and redirect focus when the user presses tab at the dialog boundary. var topFocusTrap, bottomFocusTrap; return $$interimElementProvider('$mdDialog') .setDefaults({ methods: ['disableParentScroll', 'hasBackdrop', 'clickOutsideToClose', 'escapeToClose', 'targetEvent', 'closeTo', 'openFrom', 'parent', 'fullscreen', 'multiple'], options: dialogDefaultOptions }) .addPreset('alert', { methods: ['title', 'htmlContent', 'textContent', 'content', 'ariaLabel', 'ok', 'theme', 'css'], options: advancedDialogOptions }) .addPreset('confirm', { methods: ['title', 'htmlContent', 'textContent', 'content', 'ariaLabel', 'ok', 'cancel', 'theme', 'css'], options: advancedDialogOptions }) .addPreset('prompt', { methods: ['title', 'htmlContent', 'textContent', 'initialValue', 'content', 'placeholder', 'ariaLabel', 'ok', 'cancel', 'theme', 'css'], options: advancedDialogOptions }); /* @ngInject */ function advancedDialogOptions($mdDialog, $mdConstant) { return { template: [ '<md-dialog md-theme="{{ dialog.theme || dialog.defaultTheme }}" aria-label="{{ dialog.ariaLabel }}" ng-class="dialog.css">', ' <md-dialog-content class="md-dialog-content" role="document" tabIndex="-1">', ' <h2 class="md-title">{{ dialog.title }}</h2>', ' <div ng-if="::dialog.mdHtmlContent" class="md-dialog-content-body" ', ' ng-bind-html="::dialog.mdHtmlContent"></div>', ' <div ng-if="::!dialog.mdHtmlContent" class="md-dialog-content-body">', ' <p>{{::dialog.mdTextContent}}</p>', ' </div>', ' <md-input-container md-no-float ng-if="::dialog.$type == \'prompt\'" class="md-prompt-input-container">', ' <input ng-keypress="dialog.keypress($event)" md-autofocus ng-model="dialog.result" ' + ' placeholder="{{::dialog.placeholder}}">', ' </md-input-container>', ' </md-dialog-content>', ' <md-dialog-actions>', ' <md-button ng-if="dialog.$type === \'confirm\' || dialog.$type === \'prompt\'"' + ' ng-click="dialog.abort()" class="md-primary md-cancel-button">', ' {{ dialog.cancel }}', ' </md-button>', ' <md-button ng-click="dialog.hide()" class="md-primary md-confirm-button" md-autofocus="dialog.$type===\'alert\'">', ' {{ dialog.ok }}', ' </md-button>', ' </md-dialog-actions>', '</md-dialog>' ].join('').replace(/\s\s+/g, ''), controller: function mdDialogCtrl() { var isPrompt = this.$type == 'prompt'; if (isPrompt && this.initialValue) { this.result = this.initialValue; } this.hide = function() { $mdDialog.hide(isPrompt ? this.result : true); }; this.abort = function() { $mdDialog.cancel(); }; this.keypress = function($event) { if ($event.keyCode === $mdConstant.KEY_CODE.ENTER) { $mdDialog.hide(this.result); } }; }, controllerAs: 'dialog', bindToController: true, }; } /* @ngInject */ function dialogDefaultOptions($mdDialog, $mdAria, $mdUtil, $mdConstant, $animate, $document, $window, $rootElement, $log, $injector, $mdTheming, $interpolate, $mdInteraction) { return { hasBackdrop: true, isolateScope: true, onCompiling: beforeCompile, onShow: onShow, onShowing: beforeShow, onRemove: onRemove, clickOutsideToClose: false, escapeToClose: true, targetEvent: null, closeTo: null, openFrom: null, focusOnOpen: true, disableParentScroll: true, autoWrap: true, fullscreen: false, transformTemplate: function(template, options) { // Make the dialog container focusable, because otherwise the focus will be always redirected to // an element outside of the container, and the focus trap won't work probably.. // Also the tabindex is needed for the `escapeToClose` functionality, because // the keyDown event can't be triggered when the focus is outside of the container. var startSymbol = $interpolate.startSymbol(); var endSymbol = $interpolate.endSymbol(); var theme = startSymbol + (options.themeWatch ? '' : '::') + 'theme' + endSymbol; return '<div class="md-dialog-container" tabindex="-1" md-theme="' + theme + '">' + validatedTemplate(template) + '</div>'; /** * The specified template should contain a <md-dialog> wrapper element.... */ function validatedTemplate(template) { if (options.autoWrap && !/<\/md-dialog>/g.test(template)) { return '<md-dialog>' + (template || '') + '</md-dialog>'; } else { return template || ''; } } } }; function beforeCompile(options) { // Automatically apply the theme, if the user didn't specify a theme explicitly. // Those option changes need to be done, before the compilation has started, because otherwise // the option changes will be not available in the $mdCompilers locales. options.defaultTheme = $mdTheming.defaultTheme(); detectTheming(options); } function beforeShow(scope, element, options, controller) { if (controller) { var mdHtmlContent = controller.htmlContent || options.htmlContent || ''; var mdTextContent = controller.textContent || options.textContent || controller.content || options.content || ''; if (mdHtmlContent && !$injector.has('$sanitize')) { throw Error('The ngSanitize module must be loaded in order to use htmlContent.'); } if (mdHtmlContent && mdTextContent) { throw Error('md-dialog cannot have both `htmlContent` and `textContent`'); } // Only assign the content if nothing throws, otherwise it'll still be compiled. controller.mdHtmlContent = mdHtmlContent; controller.mdTextContent = mdTextContent; } } /** Show method for dialogs */ function onShow(scope, element, options, controller) { angular.element($document[0].body).addClass('md-dialog-is-showing'); var dialogElement = element.find('md-dialog'); // Once a dialog has `ng-cloak` applied on his template the dialog animation will not work properly. // This is a very common problem, so we have to notify the developer about this. if (dialogElement.hasClass('ng-cloak')) { var message = '$mdDialog: using `<md-dialog ng-cloak>` will affect the dialog opening animations.'; $log.warn( message, element[0] ); } captureParentAndFromToElements(options); configureAria(dialogElement, options); showBackdrop(scope, element, options); activateListeners(element, options); return dialogPopIn(element, options) .then(function() { lockScreenReader(element, options); warnDeprecatedActions(); focusOnOpen(); }); /** * Check to see if they used the deprecated .md-actions class and log a warning */ function warnDeprecatedActions() { if (element[0].querySelector('.md-actions')) { $log.warn('Using a class of md-actions is deprecated, please use <md-dialog-actions>.'); } } /** * For alerts, focus on content... otherwise focus on * the close button (or equivalent) */ function focusOnOpen() { if (options.focusOnOpen) { var target = $mdUtil.findFocusTarget(element) || findCloseButton() || dialogElement; target.focus(); } /** * If no element with class dialog-close, try to find the last * button child in md-actions and assume it is a close button. * * If we find no actions at all, log a warning to the console. */ function findCloseButton() { return element[0].querySelector('.dialog-close, md-dialog-actions button:last-child'); } } } /** * Remove function for all dialogs */ function onRemove(scope, element, options) { options.deactivateListeners(); options.unlockScreenReader(); options.hideBackdrop(options.$destroy); // Remove the focus traps that we added earlier for keeping focus within the dialog. if (topFocusTrap && topFocusTrap.parentNode) { topFocusTrap.parentNode.removeChild(topFocusTrap); } if (bottomFocusTrap && bottomFocusTrap.parentNode) { bottomFocusTrap.parentNode.removeChild(bottomFocusTrap); } // For navigation $destroy events, do a quick, non-animated removal, // but for normal closes (from clicks, etc) animate the removal return !!options.$destroy ? detachAndClean() : animateRemoval().then( detachAndClean ); /** * For normal closes, animate the removal. * For forced closes (like $destroy events), skip the animations */ function animateRemoval() { return dialogPopOut(element, options); } /** * Detach the element */ function detachAndClean() { angular.element($document[0].body).removeClass('md-dialog-is-showing'); // Reverse the container stretch if using a content element. if (options.contentElement) { options.reverseContainerStretch(); } // Exposed cleanup function from the $mdCompiler. options.cleanupElement(); // Restores the focus to the origin element if the last interaction upon opening was a keyboard. if (!options.$destroy && options.originInteraction === 'keyboard') { options.origin.focus(); } } } function detectTheming(options) { // Once the user specifies a targetEvent, we will automatically try to find the correct // nested theme. var targetEl; if (options.targetEvent && options.targetEvent.target) { targetEl = angular.element(options.targetEvent.target); } var themeCtrl = targetEl && targetEl.controller('mdTheme'); if (!themeCtrl) { return; } options.themeWatch = themeCtrl.$shouldWatch; var theme = options.theme || themeCtrl.$mdTheme; if (theme) { options.scope.theme = theme; } var unwatch = themeCtrl.registerChanges(function (newTheme) { options.scope.theme = newTheme; if (!options.themeWatch) { unwatch(); } }); } /** * Capture originator/trigger/from/to element information (if available) * and the parent container for the dialog; defaults to the $rootElement * unless overridden in the options.parent */ function captureParentAndFromToElements(options) { options.origin = angular.extend({ element: null, bounds: null, focus: angular.noop }, options.origin || {}); options.parent = getDomElement(options.parent, $rootElement); options.closeTo = getBoundingClientRect(getDomElement(options.closeTo)); options.openFrom = getBoundingClientRect(getDomElement(options.openFrom)); if ( options.targetEvent ) { options.origin = getBoundingClientRect(options.targetEvent.target, options.origin); options.originInteraction = $mdInteraction.getLastInteractionType(); } /** * Identify the bounding RECT for the target element * */ function getBoundingClientRect (element, orig) { var source = angular.element((element || {})); if (source && source.length) { // Compute and save the target element's bounding rect, so that if the // element is hidden when the dialog closes, we can shrink the dialog // back to the same position it expanded from. // // Checking if the source is a rect object or a DOM element var bounds = {top:0,left:0,height:0,width:0}; var hasFn = angular.isFunction(source[0].getBoundingClientRect); return angular.extend(orig || {}, { element : hasFn ? source : undefined, bounds : hasFn ? source[0].getBoundingClientRect() : angular.extend({}, bounds, source[0]), focus : angular.bind(source, source.focus), }); } } /** * If the specifier is a simple string selector, then query for * the DOM element. */ function getDomElement(element, defaultElement) { if (angular.isString(element)) { element = $document[0].querySelector(element); } // If we have a reference to a raw dom element, always wrap it in jqLite return angular.element(element || defaultElement); } } /** * Listen for escape keys and outside clicks to auto close */ function activateListeners(element, options) { var window = angular.element($window); var onWindowResize = $mdUtil.debounce(function() { stretchDialogContainerToViewport(element, options); }, 60); var removeListeners = []; var smartClose = function() { // Only 'confirm' dialogs have a cancel button... escape/clickOutside will // cancel or fallback to hide. var closeFn = ( options.$type == 'alert' ) ? $mdDialog.hide : $mdDialog.cancel; $mdUtil.nextTick(closeFn, true); }; if (options.escapeToClose) { var parentTarget = options.parent; var keyHandlerFn = function(ev) { if (ev.keyCode === $mdConstant.KEY_CODE.ESCAPE) { ev.stopPropagation(); ev.preventDefault(); smartClose(); } }; // Add keydown listeners element.on('keydown', keyHandlerFn); parentTarget.on('keydown', keyHandlerFn); // Queue remove listeners function removeListeners.push(function() { element.off('keydown', keyHandlerFn); parentTarget.off('keydown', keyHandlerFn); }); } // Register listener to update dialog on window resize window.on('resize', onWindowResize); removeListeners.push(function() { window.off('resize', onWindowResize); }); if (options.clickOutsideToClose) { var target = element; var sourceElem; // Keep track of the element on which the mouse originally went down // so that we can only close the backdrop when the 'click' started on it. // A simple 'click' handler does not work, // it sets the target object as the element the mouse went down on. var mousedownHandler = function(ev) { sourceElem = ev.target; }; // We check if our original element and the target is the backdrop // because if the original was the backdrop and the target was inside the dialog // we don't want to dialog to close. var mouseupHandler = function(ev) { if (sourceElem === target[0] && ev.target === target[0]) { ev.stopPropagation(); ev.preventDefault(); smartClose(); } }; // Add listeners target.on('mousedown', mousedownHandler); target.on('mouseup', mouseupHandler); // Queue remove listeners function removeListeners.push(function() { target.off('mousedown', mousedownHandler); target.off('mouseup', mouseupHandler); }); } // Attach specific `remove` listener handler options.deactivateListeners = function() { removeListeners.forEach(function(removeFn) { removeFn(); }); options.deactivateListeners = null; }; } /** * Show modal backdrop element... */ function showBackdrop(scope, element, options) { if (options.disableParentScroll) { // !! DO this before creating the backdrop; since disableScrollAround() // configures the scroll offset; which is used by mdBackDrop postLink() options.restoreScroll = $mdUtil.disableScrollAround(element, options.parent); } if (options.hasBackdrop) { options.backdrop = $mdUtil.createBackdrop(scope, "md-dialog-backdrop md-opaque"); $animate.enter(options.backdrop, options.parent); } /** * Hide modal backdrop element... */ options.hideBackdrop = function hideBackdrop($destroy) { if (options.backdrop) { if ( !!$destroy ) options.backdrop.remove(); else $animate.leave(options.backdrop); } if (options.disableParentScroll) { options.restoreScroll && options.restoreScroll(); delete options.restoreScroll; } options.hideBackdrop = null; }; } /** * Inject ARIA-specific attributes appropriate for Dialogs */ function configureAria(element, options) { var role = (options.$type === 'alert') ? 'alertdialog' : 'dialog'; var dialogContent = element.find('md-dialog-content'); var existingDialogId = element.attr('id'); var dialogContentId = 'dialogContent_' + (existingDialogId || $mdUtil.nextUid()); element.attr({ 'role': role, 'tabIndex': '-1' }); if (dialogContent.length === 0) { dialogContent = element; // If the dialog element already had an ID, don't clobber it. if (existingDialogId) { dialogContentId = existingDialogId; } } dialogContent.attr('id', dialogContentId); element.attr('aria-describedby', dialogContentId); if (options.ariaLabel) { $mdAria.expect(element, 'aria-label', options.ariaLabel); } else { $mdAria.expectAsync(element, 'aria-label', function() { var words = dialogContent.text().split(/\s+/); if (words.length > 3) words = words.slice(0, 3).concat('...'); return words.join(' '); }); } // Set up elements before and after the dialog content to capture focus and // redirect back into the dialog. topFocusTrap = document.createElement('div'); topFocusTrap.classList.add('md-dialog-focus-trap'); topFocusTrap.tabIndex = 0; bottomFocusTrap = topFocusTrap.cloneNode(false); // When focus is about to move out of the dialog, we want to intercept it and redirect it // back to the dialog element. var focusHandler = function() { element.focus(); }; topFocusTrap.addEventListener('focus', focusHandler); bottomFocusTrap.addEventListener('focus', focusHandler); // The top focus trap inserted immeidately before the md-dialog element (as a sibling). // The bottom focus trap is inserted at the very end of the md-dialog element (as a child). element[0].parentNode.insertBefore(topFocusTrap, element[0]); element.after(bottomFocusTrap); } /** * Prevents screen reader interaction behind modal window * on swipe interfaces */ function lockScreenReader(element, options) { var isHidden = true; // get raw DOM node walkDOM(element[0]); options.unlockScreenReader = function() { isHidden = false; walkDOM(element[0]); options.unlockScreenReader = null; }; /** * Walk DOM to apply or remove aria-hidden on sibling nodes * and parent sibling nodes * */ function walkDOM(element) { while (element.parentNode) { if (element === document.body) { return; } var children = element.parentNode.children; for (var i = 0; i < children.length; i++) { // skip over child if it is an ascendant of the dialog // or a script or style tag if (element !== children[i] && !isNodeOneOf(children[i], ['SCRIPT', 'STYLE'])) { children[i].setAttribute('aria-hidden', isHidden); } } walkDOM(element = element.parentNode); } } } /** * Ensure the dialog container fill-stretches to the viewport */ function stretchDialogContainerToViewport(container, options) { var isFixed = $window.getComputedStyle($document[0].body).position == 'fixed'; var backdrop = options.backdrop ? $window.getComputedStyle(options.backdrop[0]) : null; var height = backdrop ? Math.min($document[0].body.clientHeight, Math.ceil(Math.abs(parseInt(backdrop.height, 10)))) : 0; var previousStyles = { top: container.css('top'), height: container.css('height') }; // If the body is fixed, determine the distance to the viewport in relative from the parent. var parentTop = Math.abs(options.parent[0].getBoundingClientRect().top); container.css({ top: (isFixed ? parentTop : 0) + 'px', height: height ? height + 'px' : '100%' }); return function() { // Reverts the modified styles back to the previous values. // This is needed for contentElements, which should have the same styles after close // as before. container.css(previousStyles); }; } /** * Dialog open and pop-in animation */ function dialogPopIn(container, options) { // Add the `md-dialog-container` to the DOM options.parent.append(container); options.reverseContainerStretch = stretchDialogContainerToViewport(container, options); var dialogEl = container.find('md-dialog'); var animator = $mdUtil.dom.animator; var buildTranslateToOrigin = animator.calculateZoomToOrigin; var translateOptions = {transitionInClass: 'md-transition-in', transitionOutClass: 'md-transition-out'}; var from = animator.toTransformCss(buildTranslateToOrigin(dialogEl, options.openFrom || options.origin)); var to = animator.toTransformCss(""); // defaults to center display (or parent or $rootElement) dialogEl.toggleClass('md-dialog-fullscreen', !!options.fullscreen); return animator .translate3d(dialogEl, from, to, translateOptions) .then(function(animateReversal) { // Build a reversal translate function synced to this translation... options.reverseAnimate = function() { delete options.reverseAnimate; if (options.closeTo) { // Using the opposite classes to create a close animation to the closeTo element translateOptions = {transitionInClass: 'md-transition-out', transitionOutClass: 'md-transition-in'}; from = to; to = animator.toTransformCss(buildTranslateToOrigin(dialogEl, options.closeTo)); return animator .translate3d(dialogEl, from, to,translateOptions); } return animateReversal( to = animator.toTransformCss( // in case the origin element has moved or is hidden, // let's recalculate the translateCSS buildTranslateToOrigin(dialogEl, options.origin) ) ); }; // Function to revert the generated animation styles on the dialog element. // Useful when using a contentElement instead of a template. options.clearAnimate = function() { delete options.clearAnimate; // Remove the transition classes, added from $animateCSS, since those can't be removed // by reversely running the animator. dialogEl.removeClass([ translateOptions.transitionOutClass, translateOptions.transitionInClass ].join(' ')); // Run the animation reversely to remove the previous added animation styles. return animator.translate3d(dialogEl, to, animator.toTransformCss(''), {}); }; return true; }); } /** * Dialog close and pop-out animation */ function dialogPopOut(container, options) { return options.reverseAnimate().then(function() { if (options.contentElement) { // When we use a contentElement, we want the element to be the same as before. // That means, that we have to clear all the animation properties, like transform. options.clearAnimate(); } }); } /** * Utility function to filter out raw DOM nodes */ function isNodeOneOf(elem, nodeTypeArray) { if (nodeTypeArray.indexOf(elem.nodeName) !== -1) { return true; } } } }
mit
KLIM8D/AsmDiff.NET
AsmDiff.NET/Program.cs
10340
#region LICENSE /* The MIT License (MIT) Copyright (c) 2015 Morten Klim Sørensen See LICENSE.txt for more information */ #endregion using AsmAnalyzer; using AsmAnalyzer.Util; using NDesk.Options; using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.IO.Pipes; using System.Text.RegularExpressions; namespace AsmDiff.NET { class Program { static OptionSet options; static void Main(string[] args) { #region OptionVariables string source = ""; string target = ""; string filter = ""; string pattern = ""; string flags = ""; string theme = "light"; string title = "AsmDiff.NET report"; string filename = ""; UInt16 maxdepth = 1; bool isHtml = true; bool showHelp = false; #endregion options = new OptionSet { {"h|help", "show this message and exit", x => showHelp = true }, {"s|source=", "this is the OLD version of the library. Either a path to a specific assembly or a folder which contains assemblies", src => source = src}, {"t|target=", "this is the NEW version of the library. Either a path to a specific assembly or a folder which contains assemblies", tar => target = tar}, {"f|filter=", "specify a filter which will exclude other classes which doesn't reference what's specified in the filter (eg. System.Reflection.Assembly) ", f => filter = f}, {"p|pattern=", "specify a regex pattern which will exclude all files which doesn't match the regular expression ", p => pattern = p}, {"o|output=", "specify output format, JSON or HTML. Default: HTML", h => isHtml = !String.Equals(h.ToUpperInvariant(), "JSON") }, {"flags=", "specify which kind of analysis you want the application to do." + Environment.NewLine + "Options: (a = Addtions, c = Changes, d = Deletions)" + Environment.NewLine + "Ex. `flags=ad` will only search for and include Additions and Deletions from the analysis of the assemblies." + Environment.NewLine + "Default: `flags=cd`", fl => flags = fl }, {"theme=", "specify either a filename within Assets\\Themes or a path to a CSS file. " + Environment.NewLine + "Default options: light, dark" + Environment.NewLine + "Default: `theme=light`", th => theme = th}, {"title=", "the given title will be displayed at the top of the HTML report", t => { if(!String.IsNullOrEmpty(t)) title = t; } }, {"maxdepth=", "descend at most levels (a non-negative integer) levels of directories below the current", m => { if(UInt16.TryParse(m, out maxdepth)); } }, {"filename=", "the name the tool will use for naming the result file, excluding the file extension", f => { if(!String.IsNullOrEmpty(f)) filename = f; } } }; try { options.Parse(args); if (showHelp) { Help(); return; } #region HandleArguments // handle commandarguments bool sourceIsNull = false; if ((sourceIsNull = String.IsNullOrEmpty(source)) || String.IsNullOrEmpty(target)) throw new OptionException(String.Format("{0} cannot be empty. You have to specify a {0}", sourceIsNull ? "source" : "target"), sourceIsNull ? "source" : "target"); // verify that the files or directory in source and target exist if ((sourceIsNull = !Exists(source)) || !Exists(target)) throw new OptionException(String.Format("the program were unable to find the path specified in {0} ({1})", sourceIsNull ? "source" : "target", sourceIsNull ? source : target), sourceIsNull ? "source" : "target"); source = Path.GetFullPath(source); target = Path.GetFullPath(target); Regex regex = null; if (IsValidRegex(pattern)) regex = new Regex(@pattern, RegexOptions.Compiled); else if(!String.IsNullOrEmpty(pattern)) throw new OptionException(String.Format("the pattern specified is not a valid regular expression {0}", Environment.NewLine + pattern), "pattern"); var fl = !String.IsNullOrEmpty(flags) ? GetFlags(flags) : (Analyzer.AnalyzerFlags.Changes | Analyzer.AnalyzerFlags.Deletion); if(!Exists(theme) && !Exists(String.Format(@"{0}\Assets\Themes\{1}.css", Environment.CurrentDirectory, theme))) throw new OptionException(String.Format("invalid path or file does not exists {0}", Environment.NewLine + theme), "theme"); #endregion var metaData = new MetaData { Pattern = pattern, Filter = filter, Flags = GetFlagsString(flags), CommandArguments = String.Join(" ", args), Source = new AssemblyMetaData { Path = source, AssemblyErrors = new List<string>(), AssemblySuccess = new List<string>() }, Target = new AssemblyMetaData { Path = target, AssemblyErrors = new List<string>(), AssemblySuccess = new List<string>() } }; var analyzer = new Analyzer { Flags = fl, MaxDepth = maxdepth }; var s = analyzer.Invoke(@source, @target, @filter, regex, metaData); #region RenderOutput // is the outputformat HTML or not if (isHtml) { var htmlHelper = new HtmlHelper(theme, title); var html = htmlHelper.RenderHTML(s, metaData); string filepath = String.Format(@"{0}\{1}.html", Environment.CurrentDirectory, !String.IsNullOrEmpty(filename) ? filename : ("AssemblyScanReport-" + DateTime.Now.ToString("dd-MM-yyyy_HH-mm"))); using (var fileStream = File.Create(filepath)) { html.Seek(0, SeekOrigin.Begin); html.CopyTo(fileStream); } SendMessageAsync(filename, filepath); } else { var json = JsonHelper.SerializeJson<ICollection<Result>>(s); string filepath = String.Format(String.Format(@"{0}\{1}.json", Environment.CurrentDirectory, !String.IsNullOrEmpty(filename) ? filename : ("AssemblyScanReport-" + DateTime.Now.ToString("dd-MM-yyyy_HH-mm")))); File.WriteAllText(filepath, json); SendMessageAsync(filename, filepath); } #endregion } catch (OptionException e) { Console.Error.Write("AsmDiff.NET: "); Console.Error.WriteLine(e.Message); Console.Error.WriteLine("Try 'AsmDiffNET --help' for more information."); #if DEBUG //Console.ReadLine(); #endif return; } catch (Exception e) { Console.Error.Write("AsmDiff.NET: An unknown error occurred. Please see the CrashDump file for further information."); string fileName = String.Format(String.Format(@"{0}\CrashDump-{1}.txt", Environment.CurrentDirectory, DateTime.Now.ToString("dd-MM-yyyy_HH-mm"))); File.WriteAllText(fileName, e.ToString()); } } static void Help() { Console.WriteLine("Usage: AsmDiffNET [OPTIONS]"); Console.WriteLine(); Console.WriteLine("Options:"); options.WriteOptionDescriptions(Console.Out); } static bool Exists(string name) { return (Directory.Exists(name) || File.Exists(name)); } static bool IsValidRegex(string pattern) { if (String.IsNullOrEmpty(pattern)) return false; try { Regex.Match("", pattern); } catch (ArgumentException) { return false; } catch (RegexMatchTimeoutException) { return false; } return true; } static Analyzer.AnalyzerFlags GetFlags(string flags) { flags = flags.ToUpperInvariant(); Analyzer.AnalyzerFlags r = Analyzer.AnalyzerFlags.None; if (flags.Contains("A")) r = r | Analyzer.AnalyzerFlags.Addition; if (flags.Contains("C")) r = r | Analyzer.AnalyzerFlags.Changes; if (flags.Contains("D")) r = r | Analyzer.AnalyzerFlags.Deletion; return r; } static string GetFlagsString(string flags) { if (String.IsNullOrEmpty(flags)) return "Changes Deletions"; flags = flags.ToUpperInvariant(); string r = ""; if (flags.Contains("A")) r += "Additions "; if (flags.Contains("C")) r += "Changes "; if (flags.Contains("D")) r += "Deletions "; return r; } static async void SendMessageAsync(string pipeName, string message) { try { using (var pipe = new NamedPipeClientStream(".", pipeName, PipeDirection.Out, PipeOptions.Asynchronous)) using (var stream = new StreamWriter(pipe)) { pipe.Connect(2000); // write the message to the pipe stream await stream.WriteAsync(message); } } catch (Exception) { Console.Error.WriteLine("Error connecting to the pipe: " + pipeName); } } } }
mit
jcenturion/dashboard
app/components/FormTextAreaGroup.react.js
1172
var React = require('react'); var FormControlMixin = require('../mixins/FormControlMixin'); var Codemirror = require('react-codemirror'); var beautify = require('js-beautify').js_beautify; require('codemirror/mode/javascript/javascript'); var FormTextAreaGroup = React.createClass({ propTypes: { title: React.PropTypes.string.isRequired, defaultValue: React.PropTypes.string }, getInitialState: function () { return { value: beautify(this.props.defaultValue||'', { indent_size: 2 }) || '' }; }, getValue: function () { return this.state.value; }, _onChanged: function (updatedValue) { this.setState({value: updatedValue}); }, render: function () { var options = { mode: 'javascript', tabSize: 2 }; return ( <div className="form-group"> <label className="control-label col-xs-3">{this.props.title}</label> <div className="controls col-xs-9"> <Codemirror value={this.state.value} onChange={this._onChanged} options={options} className="form-control"/> </div> </div> ); } }); module.exports = FormTextAreaGroup;
mit
actsmart/actsmart
src/Utils/RegularExpressionHelper.php
2106
<?php namespace actsmart\actsmart\Utils; /** * Trait RegularExpressionHelper * @package actsmart\actsmart\Utils * * Helpful regex patterns, especially for conversations in Slack. */ trait RegularExpressionHelper { /** * Removes all usernames from the string. * * @param $message * @return null|string|string[] */ public function removeAllUsernames($message) { return preg_replace("/(<@)\w+(>)\s?/", "", $message); } /** * Removes all slash commands from the string * * @return null|string|string[] */ public function removeAllCommands($message) { return preg_replace("/\/\S+\s?/", "", $message); } /** * Strips all usernames and commands from the input message * * @param $message * @return null|string|string[] */ public function cleanseMessage($message) { $message = $this->removeAllUsernames($message); return $this->removeAllCommands($message); } /** * Returns true if the userName is mentioned. * * @param $message * @param $username * @return bool */ public function userNameMentioned($message, $username) { return preg_match("/(<@".$username.">)/", $message); } /** * Returns true if a candidate from each word group is present. * * @param string $message * @param array $wordGroups - an array of wordGroups - as an array. * @return bool */ public function wordsMentioned(string $message, $wordGroups = []) { $mentioned = true; foreach ($wordGroups as $group) { if (!preg_match("/" . $this->createCaptureGroup($group) . "/", $message)) { return false; } } return $mentioned; } private function createCaptureGroup($words) { $expression=''; foreach ($words as $word) { $expression .='(\b' . $word . '\b)'; $expression .='|'; } $expression = rtrim($expression, '|'); return $expression; } }
mit
Bernstern/Spartonics-2141
2019 Austin's Child/src/main/java/frc/robot/Robot.java
3702
/*----------------------------------------------------------------------------*/ /* Copyright (c) 2017-2018 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ package frc.robot; import edu.wpi.first.wpilibj.TimedRobot; import edu.wpi.first.wpilibj.command.Scheduler; import frc.robot.subsystems.Chassis; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the TimedRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the build.gradle file in the * project. */ public class Robot extends TimedRobot { public static Chassis chassis; public static OI oi; /** * This function is run when the robot is first started up and should be * used for any initialization code. */ @Override public void robotInit() { chassis = new Chassis(); oi = new OI(); // chooser.addOption("My Auto", new MyAutoCommand()); } /** * This function is called every robot packet, no matter the mode. Use * this for items like diagnostics that you want ran during disabled, * autonomous, teleoperated and test. * * <p>This runs after the mode specific periodic functions, but before * LiveWindow and SmartDashboard integrated updating. */ @Override public void robotPeriodic() { } /** * This function is called once each time the robot enters Disabled mode. * You can use it to reset any subsystem information you want to clear when * the robot is disabled. */ @Override public void disabledInit() { } @Override public void disabledPeriodic() { Scheduler.getInstance().run(); } /** * This autonomous (along with the chooser code above) shows how to select * between different autonomous modes using the dashboard. The sendable * chooser code works with the Java SmartDashboard. If you prefer the * LabVIEW Dashboard, remove all of the chooser code and uncomment the * getString code to get the auto name from the text box below the Gyro * * <p>You can add additional auto modes by adding additional commands to the * chooser code above (like the commented example) or additional comparisons * to the switch structure below with additional strings & commands. */ @Override public void autonomousInit() { /* * String autoSelected = SmartDashboard.getString("Auto Selector", * "Default"); switch(autoSelected) { case "My Auto": autonomousCommand * = new MyAutoCommand(); break; case "Default Auto": default: * autonomousCommand = new ExampleCommand(); break; } */ } /** * This function is called periodically during autonomous. */ @Override public void autonomousPeriodic() { Scheduler.getInstance().run(); } @Override public void teleopInit() { // This makes sure that the autonomous stops running when // teleop starts running. If you want the autonomous to // continue until interrupted by another command, remove // this line or comment it out. } /** * This function is called periodically during operator control. */ @Override public void teleopPeriodic() { Scheduler.getInstance().run(); } /** * This function is called periodically during test mode. */ @Override public void testPeriodic() { } }
mit
dazinator/GitVersion
src/GitVersionCore.Tests/VersionConverters/InformationalVersionBuilderTests.cs
3565
using System; using GitVersion; using GitVersionCore.Tests.Helpers; using NUnit.Framework; namespace GitVersionCore.Tests { [TestFixture] public class InformationalVersionBuilderTests : TestBase { [TestCase("feature1", "a682956dc1a2752aa24597a0f5cd939f93614509", "a682956d", 1, 2, 3, "unstable", "1c6609bcf", 1, "1.2.3-unstable+1.Branch.feature1.Sha.a682956dc1a2752aa24597a0f5cd939f93614509")] [TestCase("develop", "a682956dc1a2752aa24597a0f5cd939f93614509", "a682956d", 1, 2, 3, "alpha645", null, null, "1.2.3-alpha.645+Branch.develop.Sha.a682956dc1a2752aa24597a0f5cd939f93614509")] [TestCase("develop", "a682956dc1a2752aa24597a0f5cd939f93614509", "a682956d", 1, 2, 3, "unstable645", null, null, "1.2.3-unstable.645+Branch.develop.Sha.a682956dc1a2752aa24597a0f5cd939f93614509")] [TestCase("develop", "a682956dc1a2752aa24597a0f5cd939f93614509", "a682956d", 1, 2, 3, "beta645", null, null, "1.2.3-beta.645+Branch.develop.Sha.a682956dc1a2752aa24597a0f5cd939f93614509")] [TestCase("hotfix-foo", "a682956dc1a2752aa24597a0f5cd939f93614509", "a682956d", 1, 2, 3, "alpha645", null, null, "1.2.3-alpha.645+Branch.hotfix-foo.Sha.a682956dc1a2752aa24597a0f5cd939f93614509")] [TestCase("hotfix-foo", "a682956dc1a2752aa24597a0f5cd939f93614509", "a682956d", 1, 2, 3, "beta645", null, null, "1.2.3-beta.645+Branch.hotfix-foo.Sha.a682956dc1a2752aa24597a0f5cd939f93614509")] [TestCase("hotfix-foo", "a682956dc1a2752aa24597a0f5cd939f93614509", "a682956d", 1, 2, 3, null, null, null, "1.2.3+Branch.hotfix-foo.Sha.a682956dc1a2752aa24597a0f5cd939f93614509")] [TestCase("master", "a682956dc1a2752aa24597a0f5cd939f93614509", "a682956d", 1, 2, 3, null, null, null, "1.2.3+Branch.master.Sha.a682956dc1a2752aa24597a0f5cd939f93614509")] [TestCase("myPullRequest", "a682956dc1a2752aa24597a0f5cd939f93614509", "a682956d", 1, 2, 3, "unstable3", null, null, "1.2.3-unstable.3+Branch.myPullRequest.Sha.a682956dc1a2752aa24597a0f5cd939f93614509")] [TestCase("release-1.2", "a682956dc1a2752aa24597a0f5cd939f93614509", "a682956d", 1, 2, 0, "beta2", null, null, "1.2.0-beta.2+Branch.release-1.2.Sha.a682956dc1a2752aa24597a0f5cd939f93614509")] [TestCase("release-1.2", "a682956dc1a2752aa24597a0f5cd939f93614509", "a682956d", 1, 2, 0, "alpha2", null, null, "1.2.0-alpha.2+Branch.release-1.2.Sha.a682956dc1a2752aa24597a0f5cd939f93614509")] [TestCase("release/1.2", "a682956dc1a2752aa24597a0f5cd939f93614509", "a682956d", 1, 2, 0, "beta2", null, null, "1.2.0-beta.2+Branch.release-1.2.Sha.a682956dc1a2752aa24597a0f5cd939f93614509")] [TestCase("release/1.2", "a682956dc1a2752aa24597a0f5cd939f93614509", "a682956d", 1, 2, 0, "alpha2", null, null, "1.2.0-alpha.2+Branch.release-1.2.Sha.a682956dc1a2752aa24597a0f5cd939f93614509")] public void ValidateInformationalVersionBuilder(string branchName, string sha, string shortSha, int major, int minor, int patch, string tag, string versionSourceSha, int? commitsSinceTag, string versionString) { var semanticVersion = new SemanticVersion { Major = major, Minor = minor, Patch = patch, PreReleaseTag = tag, BuildMetaData = new SemanticVersionBuildMetaData(versionSourceSha, commitsSinceTag, branchName, sha, shortSha, DateTimeOffset.MinValue), }; var informationalVersion = semanticVersion.ToString("i"); Assert.AreEqual(versionString, informationalVersion); } } }
mit
edisond/zhihu-spider
src/constants/zhihu.js
2368
'use strict'; let zhihu = {}; zhihu.url = { home: () => 'https://www.zhihu.com', loginWithPhoneNum: () => 'https://www.zhihu.com/login/phone_num', captcha: () => `https://www.zhihu.com/captcha.gif?type=login&r=${new Date().getTime()}`, userProfile: (userName) => `https://www.zhihu.com/people/${userName}`, userFollowers: (userName) => `https://www.zhihu.com/people/${userName}/followers`, userFollowees: (userName) => `https://www.zhihu.com/people/${userName}/followees`, userTopics: (userName) => `https://www.zhihu.com/people/${userName}/topics` }; zhihu.api = { userFollowers: { url: () => 'https://www.zhihu.com/node/ProfileFollowersListV2', pageSize: () => 20, form: (hashId, offset) => { offset = typeof offset === 'undefined' ? 0 : offset; return { method: 'next', params: `{"offset":${offset},"order_by":"created","hash_id":"${hashId}"}` } }, header: (userName, token) => { return { 'X-Xsrftoken': token, 'X-Requested-With': 'XMLHttpRequest', 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', Referer: zhihu.url.userFollowers(userName) } } }, userFollowees: { url: () => 'https://www.zhihu.com/node/ProfileFolloweesListV2', pageSize: () => 20, form: (hashId, offset) => { offset = typeof offset === 'undefined' ? 0 : offset; return { method: 'next', params: `{"offset":${offset},"order_by":"created","hash_id":"${hashId}"}` } }, header: (userName, token) => { return { 'X-Xsrftoken': token, 'X-Requested-With': 'XMLHttpRequest', 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', Referer: zhihu.url.userFollowees(userName) } } }, userTopics: { url: (userName) => `https://www.zhihu.com/people/${userName}/topics`, pageSize: () => 20, form: (offset) => { offset = typeof offset === 'undefined' ? 0 : offset; return { start: 0, offset: offset } }, header: (userName, token) => { return { 'X-Xsrftoken': token, 'X-Requested-With': 'XMLHttpRequest', 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', Referer: zhihu.url.userTopics(userName) } } } }; module.exports = zhihu;
mit
D4H/minimodel
lib/index.js
3270
var Model = require('./Model'); var schemaParser = require('./schemaParser'); var inherits = require('inherits'); var merge = require('lodash/merge'); var utils = require('./utils'); var modelsRegistry = require('./modelsRegistry'); var self = module.exports; function defaultArgsMapper() { return arguments; } function extendModel(name, schema, extendOptions) { var Parent = this; if(!utils.isString(name)) { schema = name; name = undefined; extendOptions = schema; } if(name && modelsRegistry.find(name)) { throw new Error('Cannot redefine existing model with name: ' + name); } extendOptions = utils.defaults({}, extendOptions, { schemaParser: Parent.__schemaParser || schemaParser, extendArgsMapper: Parent.__extendArgsMapper || defaultArgsMapper }); var ExtendedModel = new Function("init", "return function " + (name || 'Model') + "(){ init.apply(this, arguments) };")( function() { var args = extendOptions.extendArgsMapper.apply(null, arguments); var obj = args[0]; var options = args[1]; return initialize.call(this, obj, options); } ); function initialize(obj, options) { Object.defineProperty(this, 'constructor', { enumerable: false, configurable: false, writable: true, value: ExtendedModel }); Parent.__initialize.call(this, obj, utils.defaults({}, options, { schemas: ExtendedModel.__schemas, schemaParser: ExtendedModel.schemaParser })); } if(name) { modelsRegistry.set(name, ExtendedModel); if(extendOptions.alias) { modelsRegistry.set(extendOptions.alias, ExtendedModel); } } //for Proto inherits(ExtendedModel, Parent); //for static utils.assign(ExtendedModel, Parent); var parsedSchema = extendOptions.schemaParser.parseSchema(schema).normalized; ExtendedModel.__schemas = extendOptions.schemaParser.parseSchema(merge({}, Parent.__schemas.normalized, parsedSchema)); ExtendedModel.__schemaParser = extendOptions.schemaParser; ExtendedModel.__extendArgsMapper = extendOptions.extendArgsMapper; /** * Define a property programmatically * * @param name * @param descriptor */ ExtendedModel.property = function(name, descriptor) { var propPath = name.split('.'); if(propPath.length > 1) { this.__schemas.typed[propPath[0]].property(propPath.slice(1).join("."), descriptor); } else { var parsedField = this.__schemaParser.parseField(descriptor); this.__schemas.normalized[name] = parsedField.normalized; this.__schemas.typed[name] = parsedField.typed; } }; ExtendedModel.extend = extendModel; return ExtendedModel; } Model.__schemaParser = schemaParser; Model.extend = extendModel; self.Model = Model; self.Collection = require('./Collection'); self.registry = modelsRegistry; self.Types = { String: require('./fields/StringField'), Number: require('./fields/NumberField'), Boolean: require('./fields/BooleanField'), Date: require('./fields/DateField'), Array: require('./fields/ArrayField'), Virtual: require('./fields/VirtualField'), Constant: require('./fields/ConstantField'), Any: require('./fields/Field') }; self.exportDeep = utils.exportDeep; self.Errors = require('./errors');
mit
freelook/info
api/components/goods/goods.server.route.js
160
'use strict'; module.exports = function (app) { // Api routing var goods = require('./goods.server.controller'); app.route('/goods').get(goods); };
mit
neotracker/neo-blockchain
packages/neo-blockchain-core/src/utils/index.js
670
/* @flow */ import equals from './equals'; import lazy from './lazy'; import lazyAsync from './lazyAsync'; import lazyOrValue from './lazyOrValue'; import utils from './utils'; import weightedAverage from './weightedAverage'; import weightedFilter from './weightedFilter'; export { default as BinaryReader } from './BinaryReader'; export { default as BinaryWriter } from './BinaryWriter'; export { default as IOHelper } from './IOHelper'; export { default as JSONHelper } from './JSONHelper'; export { default as ScriptBuilder } from './ScriptBuilder'; export default { ...utils, equals, lazy, lazyAsync, lazyOrValue, weightedAverage, weightedFilter, };
mit
karim/adila
database/src/main/java/adila/db/wecct.java
209
// This file is automatically generated. package adila.db; /* * oioo oioo Model 2 * * DEVICE: wecct * MODEL: Model 2 */ final class wecct { public static final String DATA = "oioo|oioo Model 2|"; }
mit
approached/laravel-image-optimizer
tests/CapitalizedTest.php
2250
<?php class CapitalizedTest extends TestCase { public function setUp() { parent::setUp(); $this->originalFile = __DIR__.'/files/capitalized.JPG'; $this->compressedFile = $temp_file = sys_get_temp_dir().'/php_image_optimizer.JPG'; copy($this->originalFile, $this->compressedFile); } public function tearDown() { unlink($this->compressedFile); parent::tearDown(); } /** * @test */ public function it_converts_capitalized_file() { /** @var \Approached\LaravelImageOptimizer\ImageOptimizer $imageOptimizer */ $imageOptimizer = app('Approached\LaravelImageOptimizer\ImageOptimizer'); // check original file $this->assertTrue(file_exists($this->originalFile)); $this->printFileInformation($this->originalFile); // compress $imageOptimizer->optimizeImage($this->compressedFile); // check compressed file $this->assertTrue(file_exists($this->compressedFile)); $this->printFileInformation($this->compressedFile); // check compressing $this->assertLessThan(filesize($this->originalFile), filesize($this->compressedFile)); $this->printFilesizeDifference($this->originalFile, $this->compressedFile); } /** * @test */ public function it_converts_capitalized_upload_file() { /** @var \Approached\LaravelImageOptimizer\ImageOptimizer $imageOptimizer */ $imageOptimizer = app('Approached\LaravelImageOptimizer\ImageOptimizer'); // check original file $this->assertTrue(file_exists($this->originalFile)); $this->printFileInformation($this->originalFile); // compress $imageOptimizer->optimizeUploadedImageFile(new \Symfony\Component\HttpFoundation\File\UploadedFile($this->compressedFile, 'foo.JPG')); // check compressed file $this->assertTrue(file_exists($this->compressedFile)); $this->printFileInformation($this->compressedFile); // check compressing $this->assertLessThan(filesize($this->originalFile), filesize($this->compressedFile)); $this->printFilesizeDifference($this->originalFile, $this->compressedFile); } }
mit
cuckata23/wurfl-data
data/sie_ax72_ver1_sub1.php
125
<?php return array ( 'id' => 'sie_ax72_ver1_sub1', 'fallback' => 'sie_ax72_ver1', 'capabilities' => array ( ), );
mit
Camyul/The-Begining
07. Arrays/05. Maximal increasing sequence/05. Maximal increasing sequence.cs
768
using System; class Program { static void Main() { int n = Convert.ToInt32(Console.ReadLine()); int[] num = new int[n]; for (int i = 0; i < n; i++) { num[i] = Convert.ToInt32(Console.ReadLine()); } int count = 1; int maxCount = 1; for (int i = 0; i < n - 1; i++) { if (num[i + 1] > num[i]) { count++; } else { if (maxCount < count) { maxCount = count; } count = 1; } } if (maxCount < count) { maxCount = count; } Console.WriteLine(maxCount); } }
mit
helsingborg-stad/api-event-manager
vendor/giggsey/locale/data/kea.php
6434
<?php /** * This file has been @generated by a phing task from CLDR version 34.0.0. * See [README.md](README.md#generating-data) for more information. * * @internal Please do not require this file directly. * It may change location/format between versions * * Do not modify this file directly! */ return array ( 'AC' => 'Ilha di Asensãu', 'AD' => 'Andora', 'AE' => 'Emiradus Árabi Unidu', 'AF' => 'Afeganistãu', 'AG' => 'Antigua i Barbuda', 'AI' => 'Angila', 'AL' => 'Albánia', 'AM' => 'Arménia', 'AO' => 'Angola', 'AQ' => 'Antártika', 'AR' => 'Arjentina', 'AS' => 'Samoa Merkanu', 'AT' => 'Áustria', 'AU' => 'Austrália', 'AW' => 'Aruba', 'AX' => 'Ilhas Åland', 'AZ' => 'Azerbaijãu', 'BA' => 'Bósnia i Erzegovina', 'BB' => 'Barbadus', 'BD' => 'Bangladexi', 'BE' => 'Béljika', 'BF' => 'Burkina Fasu', 'BG' => 'Bulgária', 'BH' => 'Barain', 'BI' => 'Burundi', 'BJ' => 'Benin', 'BL' => 'Sãu Bartolomeu', 'BM' => 'Bermudas', 'BN' => 'Brunei', 'BO' => 'Bolívia', 'BQ' => 'Karaibas Olandezas', 'BR' => 'Brazil', 'BS' => 'Baamas', 'BT' => 'Butãu', 'BW' => 'Botsuana', 'BY' => 'Belarus', 'BZ' => 'Belizi', 'CA' => 'Kanadá', 'CC' => 'Ilhas Kokus (Keeling)', 'CD' => 'Kongu - Kinxasa', 'CF' => 'Republika Sentru-Afrikanu', 'CG' => 'Kongu - Brazavili', 'CH' => 'Suisa', 'CI' => 'Kosta di Marfin', 'CK' => 'Ilhas Kuk', 'CL' => 'Xili', 'CM' => 'Kamarõis', 'CN' => 'Xina', 'CO' => 'Kolômbia', 'CR' => 'Kosta Rika', 'CU' => 'Kuba', 'CV' => 'Kabu Verdi', 'CW' => 'Kurasau', 'CX' => 'Ilha di Natal', 'CY' => 'Xipri', 'CZ' => 'Txékia', 'DE' => 'Alimanha', 'DG' => 'Diegu Garsia', 'DJ' => 'Djibuti', 'DK' => 'Dinamarka', 'DM' => 'Dominika', 'DO' => 'Repúblika Dominikana', 'DZ' => 'Arjélia', 'EA' => 'Seuta i Melilha', 'EC' => 'Ekuador', 'EE' => 'Stónia', 'EG' => 'Ejitu', 'EH' => 'Sara Osidental', 'ER' => 'Iritreia', 'ES' => 'Spanha', 'ET' => 'Etiópia', 'FI' => 'Finlándia', 'FJ' => 'Fidji', 'FK' => 'Ilhas Malvinas', 'FM' => 'Mikronézia', 'FO' => 'Ilhas Faroe', 'FR' => 'Fransa', 'GA' => 'Gabãu', 'GB' => 'Reinu Unidu', 'GD' => 'Granada', 'GE' => 'Jiórjia', 'GF' => 'Giana Franseza', 'GG' => 'Gernzi', 'GH' => 'Gana', 'GI' => 'Jibraltar', 'GL' => 'Gronelándia', 'GM' => 'Gámbia', 'GN' => 'Gine', 'GP' => 'Guadalupi', 'GQ' => 'Gine Ekuatorial', 'GR' => 'Grésia', 'GS' => 'Ilhas Jeórjia di Sul i Sanduixi di Sul', 'GT' => 'Guatimala', 'GU' => 'Guam', 'GW' => 'Gine-Bisau', 'GY' => 'Giana', 'HK' => 'Rejiãu Administrativu Spesial di Hong Kong', 'HN' => 'Onduras', 'HR' => 'Kroásia', 'HT' => 'Aití', 'HU' => 'Ungria', 'IC' => 'Kanárias', 'ID' => 'Indonézia', 'IE' => 'Irlanda', 'IL' => 'Israel', 'IM' => 'Ilha di Man', 'IN' => 'Índia', 'IO' => 'Ilhas Británikas di Índiku', 'IQ' => 'Iraki', 'IR' => 'Irãu', 'IS' => 'Islándia', 'IT' => 'Itália', 'JE' => 'Jersi', 'JM' => 'Jamaika', 'JO' => 'Jordánia', 'JP' => 'Japãu', 'KE' => 'Kénia', 'KG' => 'Kirgistãu', 'KH' => 'Kambodja', 'KI' => 'Kiribati', 'KM' => 'Kamoris', 'KN' => 'Sãu Kristovãu i Nevis', 'KP' => 'Koreia di Norti', 'KR' => 'Koreia di Sul', 'KW' => 'Kueiti', 'KY' => 'Ilhas Kaimãu', 'KZ' => 'Kazakistãu', 'LA' => 'Laus', 'LB' => 'Líbanu', 'LC' => 'Santa Lúsia', 'LI' => 'Lixenstain', 'LK' => 'Sri Lanka', 'LR' => 'Libéria', 'LS' => 'Lezotu', 'LT' => 'Lituánia', 'LU' => 'Luxemburgu', 'LV' => 'Letónia', 'LY' => 'Líbia', 'MA' => 'Marokus', 'MC' => 'Mónaku', 'MD' => 'Moldávia', 'ME' => 'Montenegru', 'MF' => 'Sãu Martinhu di Fransa', 'MG' => 'Madagaskar', 'MH' => 'Ilhas Marxal', 'MK' => 'Masidónia', 'ML' => 'Mali', 'MM' => 'Mianmar (Birmánia)', 'MN' => 'Mongólia', 'MO' => 'Rejiãu Administrativu Spesial di Makau', 'MP' => 'Ilhas Marianas di Norti', 'MQ' => 'Martinika', 'MR' => 'Mauritánia', 'MS' => 'Monserat', 'MT' => 'Malta', 'MU' => 'Maurísia', 'MV' => 'Maldivas', 'MW' => 'Malaui', 'MX' => 'Méxiku', 'MY' => 'Malázia', 'MZ' => 'Musambiki', 'NA' => 'Namíbia', 'NC' => 'Nova Kalidónia', 'NE' => 'Nijer', 'NF' => 'Ilhas Norfolk', 'NG' => 'Nijéria', 'NI' => 'Nikarágua', 'NL' => 'Olanda', 'NO' => 'Noruega', 'NP' => 'Nepal', 'NR' => 'Nauru', 'NU' => 'Niue', 'NZ' => 'Nova Zilándia', 'OM' => 'Oman', 'PA' => 'Panamá', 'PE' => 'Peru', 'PF' => 'Polinézia Franseza', 'PG' => 'Papua-Nova Gine', 'PH' => 'Filipinas', 'PK' => 'Pakistãu', 'PL' => 'Pulónia', 'PM' => 'San Piere i Mikelon', 'PN' => 'Pirkairn', 'PR' => 'Portu Riku', 'PS' => 'Palistina', 'PT' => 'Purtugal', 'PW' => 'Palau', 'PY' => 'Paraguai', 'QA' => 'Katar', 'RE' => 'Runiãu', 'RO' => 'Ruménia', 'RS' => 'Sérvia', 'RU' => 'Rúsia', 'RW' => 'Ruanda', 'SA' => 'Arábia Saudita', 'SB' => 'Ilhas Salumãu', 'SC' => 'Seixelis', 'SD' => 'Sudãu', 'SE' => 'Suésia', 'SG' => 'Singapura', 'SH' => 'Santa Ilena', 'SI' => 'Slovénia', 'SJ' => 'Svalbard i Jan Maien', 'SK' => 'Slovákia', 'SL' => 'Sera Lioa', 'SM' => 'San Marinu', 'SN' => 'Senegal', 'SO' => 'Sumália', 'SR' => 'Surinami', 'SS' => 'Sudãu di Sul', 'ST' => 'Sãu Tume i Prínsipi', 'SV' => 'El Salvador', 'SX' => 'Sãu Martinhu di Olanda', 'SY' => 'Síria', 'SZ' => 'Suazilándia', 'TA' => 'Tristan da Kunha', 'TC' => 'Ilhas Turkas i Kaikus', 'TD' => 'Txadi', 'TF' => 'Terras Franses di Sul', 'TG' => 'Togu', 'TH' => 'Tailándia', 'TJ' => 'Tadjikistãu', 'TK' => 'Tokelau', 'TL' => 'Timor Lesti', 'TM' => 'Turkumenistãu', 'TN' => 'Tunízia', 'TO' => 'Tonga', 'TR' => 'Turkia', 'TT' => 'Trinidad i Tobagu', 'TV' => 'Tuvalu', 'TW' => 'Taiuan', 'TZ' => 'Tanzánia', 'UA' => 'Ukránia', 'UG' => 'Uganda', 'UM' => 'Ilhas Minoris Distantis de Stadus Unidus', 'US' => 'Stadus Unidos di Merka', 'UY' => 'Uruguai', 'UZ' => 'Uzbekistãu', 'VA' => 'Vatikanu', 'VC' => 'Sãu Bisenti i Granadinas', 'VE' => 'Vinizuela', 'VG' => 'Ilhas Virjens Británikas', 'VI' => 'Ilhas Virjens Merkanas', 'VN' => 'Vietnam', 'VU' => 'Vanuatu', 'WF' => 'Ualis i Futuna', 'WS' => 'Samoa', 'XK' => 'Kozovu', 'YE' => 'Iémen', 'YT' => 'Maiote', 'ZA' => 'Áfrika di Sul', 'ZM' => 'Zámbia', 'ZW' => 'Zimbábui', );
mit
nazar/MediaCMS
db/migrate/021_drop_moderation_tables.rb
605
class DropModerationTables < ActiveRecord::Migration def self.up drop_table :moderatorships drop_table :monitorships end def self.down create_table "moderatorships", :force => true do |t| t.column "forum_id", :integer t.column "user_id", :integer end add_index "moderatorships", ["forum_id"], :name => "index_moderatorships_on_forum_id" create_table "monitorships", :force => true do |t| t.column "topic_id", :integer t.column "user_id", :integer t.column "active", :boolean, :default => true end end end
mit
gjeck/design-patterns
strategy/java/src/main/java/AttackWithAxe.java
122
public class AttackWithAxe implements AttackBehavior { public String attack() { return "Axe attack!"; } }
mit
Dentosal/python-sc2
sc2/paths.py
2888
import os from pathlib import Path import platform import re import logging logger = logging.getLogger(__name__) BASEDIR = { "Windows": "C:/Program Files (x86)/StarCraft II", "Darwin": "/Applications/StarCraft II", "Linux": "~/StarCraftII", "WineLinux": "~/.wine/drive_c/Program Files (x86)/StarCraft II", } USERPATH = { "Windows": "\\Documents\\StarCraft II\\ExecuteInfo.txt", "Darwin": "/Library/Application Support/Blizzard/StarCraft II/ExecuteInfo.txt", "Linux": None, "WineLinux": None, } BINPATH = { "Windows": "SC2_x64.exe", "Darwin": "SC2.app/Contents/MacOS/SC2", "Linux": "SC2_x64", "WineLinux": "SC2_x64.exe", } CWD = { "Windows": "Support64", "Darwin": None, "Linux": None, "WineLinux": "Support64", } PF = os.environ.get("SC2PF", platform.system()) def get_env(): # TODO: Linux env conf from: https://github.com/deepmind/pysc2/blob/master/pysc2/run_configs/platforms.py return None def latest_executeble(versions_dir): latest = max((int(p.name[4:]), p) for p in versions_dir.iterdir() if p.is_dir() and p.name.startswith("Base")) version, path = latest if version < 55958: logger.critical(f"Your SC2 binary is too old. Upgrade to 3.16.1 or newer.") exit(1) return path / BINPATH[PF] class _MetaPaths(type): """"Lazily loads paths to allow importing the library even if SC2 isn't installed.""" def __setup(self): if PF not in BASEDIR: logger.critical(f"Unsupported platform '{PF}'") exit(1) try: base = os.environ.get("SC2PATH") if base is None and USERPATH[PF] is not None: einfo = str(Path.home().expanduser()) + USERPATH[PF] if os.path.isfile(einfo): with open(einfo) as f: content = f.read() if content: base = re.search(r" = (.*)Versions", content).group(1) if not os.path.exists(base): base = None if base is None: base = BASEDIR[PF] self.BASE = Path(base).expanduser() self.EXECUTABLE = latest_executeble(self.BASE / "Versions") self.CWD = self.BASE / CWD[PF] if CWD[PF] else None self.REPLAYS = self.BASE / "Replays" if (self.BASE / "maps").exists(): self.MAPS = self.BASE / "maps" else: self.MAPS = self.BASE / "Maps" except FileNotFoundError as e: logger.critical(f"SC2 installation not found: File '{e.filename}' does not exist.") exit(1) def __getattr__(self, attr): self.__setup() return getattr(self, attr) class Paths(metaclass=_MetaPaths): """Paths for SC2 folders, lazily loaded using the above metaclass."""
mit
LordKiRon/fb2converters
epublibrary/Content/Manifest/ManifestItemV2.cs
671
using System; using System.Collections.Generic; using System.Linq; using System.Text; using EPubLibraryContracts; namespace EPubLibrary.Content.Manifest { public class ManifestItemV2 { public string ID { get; set; } public string HRef { get; set; } public EPubCoreMediaType MediaType { get; set; } // the following are supported only in V3 public string Fallback { get; set; } private readonly List<string> _properties = new List<string>(); public List<string> Properties { get { return _properties; } } public string MediaOverlay { get; set; } } }
mit
unisport/thumblr
thumblr/views.py
1143
from django.contrib import messages from django.contrib.contenttypes.models import ContentType from django.shortcuts import redirect from django.template.context import Context from django_tables2 import tables from thumblr.models import ImageSize from forms import ImageSizeForm class SizeTable(tables.Table): """ This class customizes the view of table. Can be used for adding columns """ class Meta: model = ImageSize def imagesizes(request): context = Context() context['form'] = ImageSizeForm() if request.method == 'POST': form = ImageSizeForm(request.POST, request.FILES) if form.is_valid(): imagesize = ImageSize() imagesize.name = form.data['name'] imagesize.width = form.data['width'] imagesize.height = form.data['height'] imagesize.content_type = ContentType.objects.get(pk=int(form.data['content_type'])) imagesize.save() messages.info(request, 'Size was successfully added') else: messages.error(request, form.errors) return redirect(request.META['HTTP_REFERER'])
mit
billroy/jchart
public/js/three.js/examples/js/loaders/VRMLLoader.js
56142
/** * @author Mugen87 / https://github.com/Mugen87 */ /* global chevrotain */ THREE.VRMLLoader = ( function () { // dependency check if ( typeof chevrotain === 'undefined' ) { throw Error( 'THREE.VRMLLoader: External library chevrotain.min.js required.' ); } // class definitions function VRMLLoader( manager ) { THREE.Loader.call( this, manager ); } VRMLLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), { constructor: VRMLLoader, load: function ( url, onLoad, onProgress, onError ) { var scope = this; var path = ( scope.path === '' ) ? THREE.LoaderUtils.extractUrlBase( url ) : scope.path; var loader = new THREE.FileLoader( this.manager ); loader.setPath( scope.path ); loader.load( url, function ( text ) { onLoad( scope.parse( text, path ) ); }, onProgress, onError ); }, parse: function ( data, path ) { var nodeMap = {}; function generateVRMLTree( data ) { // create lexer, parser and visitor var tokenData = createTokens(); var lexer = new VRMLLexer( tokenData.tokens ); var parser = new VRMLParser( tokenData.tokenVocabulary ); var visitor = createVisitor( parser.getBaseCstVisitorConstructor() ); // lexing var lexingResult = lexer.lex( data ); parser.input = lexingResult.tokens; // parsing var cstOutput = parser.vrml(); if ( parser.errors.length > 0 ) { console.error( parser.errors ); throw Error( 'THREE.VRMLLoader: Parsing errors detected.' ); } // actions var ast = visitor.visit( cstOutput ); return ast; } function createTokens() { var createToken = chevrotain.createToken; // from http://gun.teipir.gr/VRML-amgem/spec/part1/concepts.html#SyntaxBasics var RouteIdentifier = createToken( { name: 'RouteIdentifier', pattern: /[^\x30-\x39\0-\x20\x22\x27\x23\x2b\x2c\x2d\x2e\x5b\x5d\x5c\x7b\x7d][^\0-\x20\x22\x27\x23\x2b\x2c\x2d\x2e\x5b\x5d\x5c\x7b\x7d]*[\.][^\x30-\x39\0-\x20\x22\x27\x23\x2b\x2c\x2d\x2e\x5b\x5d\x5c\x7b\x7d][^\0-\x20\x22\x27\x23\x2b\x2c\x2d\x2e\x5b\x5d\x5c\x7b\x7d]*/ } ); var Identifier = createToken( { name: 'Identifier', pattern: /[^\x30-\x39\0-\x20\x22\x27\x23\x2b\x2c\x2d\x2e\x5b\x5d\x5c\x7b\x7d][^\0-\x20\x22\x27\x23\x2b\x2c\x2d\x2e\x5b\x5d\x5c\x7b\x7d]*/, longer_alt: RouteIdentifier } ); // from http://gun.teipir.gr/VRML-amgem/spec/part1/nodesRef.html var nodeTypes = [ 'Anchor', 'Billboard', 'Collision', 'Group', 'Transform', // grouping nodes 'Inline', 'LOD', 'Switch', // special groups 'AudioClip', 'DirectionalLight', 'PointLight', 'Script', 'Shape', 'Sound', 'SpotLight', 'WorldInfo', // common nodes 'CylinderSensor', 'PlaneSensor', 'ProximitySensor', 'SphereSensor', 'TimeSensor', 'TouchSensor', 'VisibilitySensor', // sensors 'Box', 'Cone', 'Cylinder', 'ElevationGrid', 'Extrusion', 'IndexedFaceSet', 'IndexedLineSet', 'PointSet', 'Sphere', // geometries 'Color', 'Coordinate', 'Normal', 'TextureCoordinate', // geometric properties 'Appearance', 'FontStyle', 'ImageTexture', 'Material', 'MovieTexture', 'PixelTexture', 'TextureTransform', // appearance 'ColorInterpolator', 'CoordinateInterpolator', 'NormalInterpolator', 'OrientationInterpolator', 'PositionInterpolator', 'ScalarInterpolator', // interpolators 'Background', 'Fog', 'NavigationInfo', 'Viewpoint', // bindable nodes 'Text' // Text must be placed at the end of the regex so there are no matches for TextureTransform and TextureCoordinate ]; // var Version = createToken( { name: 'Version', pattern: /#VRML.*/, longer_alt: Identifier } ); var NodeName = createToken( { name: 'NodeName', pattern: new RegExp( nodeTypes.join( '|' ) ), longer_alt: Identifier } ); var DEF = createToken( { name: 'DEF', pattern: /DEF/, longer_alt: Identifier } ); var USE = createToken( { name: 'USE', pattern: /USE/, longer_alt: Identifier } ); var ROUTE = createToken( { name: 'ROUTE', pattern: /ROUTE/, longer_alt: Identifier } ); var TO = createToken( { name: 'TO', pattern: /TO/, longer_alt: Identifier } ); // var StringLiteral = createToken( { name: "StringLiteral", pattern: /"(:?[^\\"\n\r]+|\\(:?[bfnrtv"\\/]|u[0-9a-fA-F]{4}))*"/ } ); var NumberLiteral = createToken( { name: 'NumberLiteral', pattern: /[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?/ } ); var TrueLiteral = createToken( { name: 'TrueLiteral', pattern: /TRUE/ } ); var FalseLiteral = createToken( { name: 'FalseLiteral', pattern: /FALSE/ } ); var NullLiteral = createToken( { name: 'NullLiteral', pattern: /NULL/ } ); var LSquare = createToken( { name: 'LSquare', pattern: /\[/ } ); var RSquare = createToken( { name: 'RSquare', pattern: /]/ } ); var LCurly = createToken( { name: 'LCurly', pattern: /{/ } ); var RCurly = createToken( { name: 'RCurly', pattern: /}/ } ); var Comment = createToken( { name: 'Comment', pattern: /#.*/, group: chevrotain.Lexer.SKIPPED } ); // commas, blanks, tabs, newlines and carriage returns are whitespace characters wherever they appear outside of string fields var WhiteSpace = createToken( { name: 'WhiteSpace', pattern: /[ ,\s]/, group: chevrotain.Lexer.SKIPPED } ); var tokens = [ WhiteSpace, // keywords appear before the Identifier NodeName, DEF, USE, ROUTE, TO, TrueLiteral, FalseLiteral, NullLiteral, // the Identifier must appear after the keywords because all keywords are valid identifiers Version, Identifier, RouteIdentifier, StringLiteral, NumberLiteral, LSquare, RSquare, LCurly, RCurly, Comment ]; var tokenVocabulary = {}; for ( var i = 0, l = tokens.length; i < l; i ++ ) { var token = tokens[ i ]; tokenVocabulary[ token.name ] = token; } return { tokens: tokens, tokenVocabulary: tokenVocabulary }; } function createVisitor( BaseVRMLVisitor ) { // the visitor is created dynmaically based on the given base class function VRMLToASTVisitor() { BaseVRMLVisitor.call( this ); this.validateVisitor(); } VRMLToASTVisitor.prototype = Object.assign( Object.create( BaseVRMLVisitor.prototype ), { constructor: VRMLToASTVisitor, vrml: function ( ctx ) { var data = { version: this.visit( ctx.version ), nodes: [], routes: [] }; for ( var i = 0, l = ctx.node.length; i < l; i ++ ) { var node = ctx.node[ i ]; data.nodes.push( this.visit( node ) ); } if ( ctx.route ) { for ( var i = 0, l = ctx.route.length; i < l; i ++ ) { var route = ctx.route[ i ]; data.routes.push( this.visit( route ) ); } } return data; }, version: function ( ctx ) { return ctx.Version[ 0 ].image; }, node: function ( ctx ) { var data = { name: ctx.NodeName[ 0 ].image, fields: [] }; if ( ctx.field ) { for ( var i = 0, l = ctx.field.length; i < l; i ++ ) { var field = ctx.field[ i ]; data.fields.push( this.visit( field ) ); } } // DEF if ( ctx.def ) { data.DEF = this.visit( ctx.def[ 0 ] ); } return data; }, field: function ( ctx ) { var data = { name: ctx.Identifier[ 0 ].image, type: null, values: null }; var result; // SFValue if ( ctx.singleFieldValue ) { result = this.visit( ctx.singleFieldValue[ 0 ] ); } // MFValue if ( ctx.multiFieldValue ) { result = this.visit( ctx.multiFieldValue[ 0 ] ); } data.type = result.type; data.values = result.values; return data; }, def: function ( ctx ) { return ctx.Identifier[ 0 ].image; }, use: function ( ctx ) { return { USE: ctx.Identifier[ 0 ].image }; }, singleFieldValue: function ( ctx ) { return processField( this, ctx ); }, multiFieldValue: function ( ctx ) { return processField( this, ctx ); }, route: function ( ctx ) { var data = { FROM: ctx.RouteIdentifier[ 0 ].image, TO: ctx.RouteIdentifier[ 1 ].image }; return data; } } ); function processField( scope, ctx ) { var field = { type: null, values: [] }; if ( ctx.node ) { field.type = 'node'; for ( var i = 0, l = ctx.node.length; i < l; i ++ ) { var node = ctx.node[ i ]; field.values.push( scope.visit( node ) ); } } if ( ctx.use ) { field.type = 'use'; for ( var i = 0, l = ctx.use.length; i < l; i ++ ) { var use = ctx.use[ i ]; field.values.push( scope.visit( use ) ); } } if ( ctx.StringLiteral ) { field.type = 'string'; for ( var i = 0, l = ctx.StringLiteral.length; i < l; i ++ ) { var stringLiteral = ctx.StringLiteral[ i ]; field.values.push( stringLiteral.image.replace( /'|"/g, '' ) ); } } if ( ctx.NumberLiteral ) { field.type = 'number'; for ( var i = 0, l = ctx.NumberLiteral.length; i < l; i ++ ) { var numberLiteral = ctx.NumberLiteral[ i ]; field.values.push( parseFloat( numberLiteral.image ) ); } } if ( ctx.TrueLiteral ) { field.type = 'boolean'; for ( var i = 0, l = ctx.TrueLiteral.length; i < l; i ++ ) { var trueLiteral = ctx.TrueLiteral[ i ]; if ( trueLiteral.image === 'TRUE' ) field.values.push( true ); } } if ( ctx.FalseLiteral ) { field.type = 'boolean'; for ( var i = 0, l = ctx.FalseLiteral.length; i < l; i ++ ) { var falseLiteral = ctx.FalseLiteral[ i ]; if ( falseLiteral.image === 'FALSE' ) field.values.push( false ); } } if ( ctx.NullLiteral ) { field.type = 'null'; ctx.NullLiteral.forEach( function () { field.values.push( null ); } ); } return field; } return new VRMLToASTVisitor(); } function parseTree( tree ) { // console.log( JSON.stringify( tree, null, 2 ) ); var nodes = tree.nodes; var scene = new THREE.Scene(); // first iteration: build nodemap based on DEF statements for ( var i = 0, l = nodes.length; i < l; i ++ ) { var node = nodes[ i ]; buildNodeMap( node ); } // second iteration: build nodes for ( var i = 0, l = nodes.length; i < l; i ++ ) { var node = nodes[ i ]; var object = getNode( node ); if ( object instanceof THREE.Object3D ) scene.add( object ); } return scene; } function buildNodeMap( node ) { if ( node.DEF ) { nodeMap[ node.DEF ] = node; } var fields = node.fields; for ( var i = 0, l = fields.length; i < l; i ++ ) { var field = fields[ i ]; if ( field.type === 'node' ) { var fieldValues = field.values; for ( var j = 0, jl = fieldValues.length; j < jl; j ++ ) { buildNodeMap( fieldValues[ j ] ); } } } } function getNode( node ) { // handle case where a node refers to a different one if ( node.USE ) { return resolveUSE( node.USE ); } if ( node.build !== undefined ) return node.build; node.build = buildNode( node ); return node.build; } // node builder function buildNode( node ) { var nodeName = node.name; var build; switch ( nodeName ) { case 'Group': case 'Transform': build = buildGroupingNode( node ); break; case 'Background': build = buildBackgroundNode( node ); break; case 'Shape': build = buildShapeNode( node ); break; case 'Appearance': build = buildApperanceNode( node ); break; case 'Material': build = buildMaterialNode( node ); break; case 'ImageTexture': build = buildImageTextureNode( node ); break; case 'TextureTransform': build = buildTextureTransformNode( node ); break; case 'IndexedFaceSet': build = buildIndexedFaceSetNode( node ); break; case 'IndexedLineSet': build = buildIndexedLineSetNode( node ); break; case 'PointSet': build = buildPointSetNode( node ); break; case 'Box': build = buildBoxNode( node ); break; case 'Cone': build = buildConeNode( node ); break; case 'Cylinder': build = buildCylinderNode( node ); break; case 'Sphere': build = buildSphereNode( node ); break; case 'Color': case 'Coordinate': case 'Normal': case 'TextureCoordinate': build = buildGeometricNode( node ); break; case 'Anchor': case 'Billboard': case 'Collision': case 'Inline': case 'LOD': case 'Switch': case 'AudioClip': case 'DirectionalLight': case 'PointLight': case 'Script': case 'Sound': case 'SpotLight': case 'WorldInfo': case 'CylinderSensor': case 'PlaneSensor': case 'ProximitySensor': case 'SphereSensor': case 'TimeSensor': case 'TouchSensor': case 'VisibilitySensor': case 'ElevationGrid': case 'Extrusion': case 'Text': case 'FontStyle': case 'MovieTexture': case 'PixelTexture': case 'ColorInterpolator': case 'CoordinateInterpolator': case 'NormalInterpolator': case 'OrientationInterpolator': case 'PositionInterpolator': case 'ScalarInterpolator': case 'Fog': case 'NavigationInfo': case 'Viewpoint': // node not supported yet break; default: console.warn( 'THREE.VRMLLoader: Unknown node:', nodeName ); break; } return build; } function buildGroupingNode( node ) { var object = new THREE.Group(); // var fields = node.fields; for ( var i = 0, l = fields.length; i < l; i ++ ) { var field = fields[ i ]; var fieldName = field.name; var fieldValues = field.values; switch ( fieldName ) { case 'center': // field not supported break; case 'children': parseFieldChildren( fieldValues, object ); break; case 'rotation': var axis = new THREE.Vector3( fieldValues[ 0 ], fieldValues[ 1 ], fieldValues[ 2 ] ); var angle = fieldValues[ 3 ]; object.quaternion.setFromAxisAngle( axis, angle ); break; case 'scale': object.scale.set( fieldValues[ 0 ], fieldValues[ 1 ], fieldValues[ 2 ] ); break; case 'scaleOrientation': // field not supported break; case 'translation': object.position.set( fieldValues[ 0 ], fieldValues[ 1 ], fieldValues[ 2 ] ); break; case 'bboxCenter': // field not supported break; case 'bboxSize': // field not supported break; default: console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); break; } } return object; } function buildBackgroundNode( node ) { var group = new THREE.Group(); var groundAngle, groundColor; var skyAngle, skyColor; var fields = node.fields; for ( var i = 0, l = fields.length; i < l; i ++ ) { var field = fields[ i ]; var fieldName = field.name; var fieldValues = field.values; switch ( fieldName ) { case 'groundAngle': groundAngle = fieldValues; break; case 'groundColor': groundColor = fieldValues; break; case 'backUrl': // field not supported break; case 'bottomUrl': // field not supported break; case 'frontUrl': // field not supported break; case 'leftUrl': // field not supported break; case 'rightUrl': // field not supported break; case 'topUrl': // field not supported break; case 'skyAngle': skyAngle = fieldValues; break; case 'skyColor': skyColor = fieldValues; break; default: console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); break; } } // sky if ( skyColor ) { var radius = 10000; var skyGeometry = new THREE.SphereBufferGeometry( radius, 32, 16 ); var skyMaterial = new THREE.MeshBasicMaterial( { fog: false, side: THREE.BackSide, depthWrite: false, depthTest: false } ); if ( skyColor.length > 3 ) { paintFaces( skyGeometry, radius, skyAngle, toColorArray( skyColor ), true ); skyMaterial.vertexColors = THREE.VertexColors; } else { skyMaterial.color.setRGB( skyColor[ 0 ], skyColor[ 1 ], skyColor[ 2 ] ); } var sky = new THREE.Mesh( skyGeometry, skyMaterial ); group.add( sky ); } // ground if ( groundColor ) { if ( groundColor.length > 0 ) { var groundGeometry = new THREE.SphereBufferGeometry( radius, 32, 16, 0, 2 * Math.PI, 0.5 * Math.PI, 1.5 * Math.PI ); var groundMaterial = new THREE.MeshBasicMaterial( { fog: false, side: THREE.BackSide, vertexColors: THREE.VertexColors, depthWrite: false, depthTest: false } ); paintFaces( groundGeometry, radius, groundAngle, toColorArray( groundColor ), false ); var ground = new THREE.Mesh( groundGeometry, groundMaterial ); group.add( ground ); } } // render background group first group.renderOrder = - Infinity; return group; } function buildShapeNode( node ) { var fields = node.fields; // if the appearance field is NULL or unspecified, lighting is off and the unlit object color is (0, 0, 0) var material = new THREE.MeshBasicMaterial( { color: 0x000000 } ); var geometry; for ( var i = 0, l = fields.length; i < l; i ++ ) { var field = fields[ i ]; var fieldName = field.name; var fieldValues = field.values; switch ( fieldName ) { case 'appearance': if ( fieldValues[ 0 ] !== null ) { material = getNode( fieldValues[ 0 ] ); } break; case 'geometry': if ( fieldValues[ 0 ] !== null ) { geometry = getNode( fieldValues[ 0 ] ); } break; default: console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); break; } } // build 3D object var object; if ( geometry && geometry.attributes.position ) { var type = geometry._type; if ( type === 'points' ) { // points var pointsMaterial = new THREE.PointsMaterial( { color: 0xffffff } ); if ( geometry.attributes.color !== undefined ) { pointsMaterial.vertexColors = THREE.VertexColors; } else { // if the color field is NULL and there is a material defined for the appearance affecting this PointSet, then use the emissiveColor of the material to draw the points if ( material.isMeshPhongMaterial ) { pointsMaterial.color.copy( material.emissive ); } } object = new THREE.Points( geometry, pointsMaterial ); } else if ( type === 'line' ) { // lines var lineMaterial = new THREE.LineBasicMaterial( { color: 0xffffff } ); if ( geometry.attributes.color !== undefined ) { lineMaterial.vertexColors = THREE.VertexColors; } else { // if the color field is NULL and there is a material defined for the appearance affecting this IndexedLineSet, then use the emissiveColor of the material to draw the lines if ( material.isMeshPhongMaterial ) { lineMaterial.color.copy( material.emissive ); } } object = new THREE.LineSegments( geometry, lineMaterial ); } else { // consider meshes // check "solid" hint (it's placed in the geometry but affects the material) if ( geometry._solid !== undefined ) { material.side = ( geometry._solid ) ? THREE.FrontSide : THREE.DoubleSide; } // check for vertex colors if ( geometry.attributes.color !== undefined ) { material.vertexColors = THREE.VertexColors; } object = new THREE.Mesh( geometry, material ); } } else { object = new THREE.Object3D(); // if the geometry field is NULL or no vertices are defined the object is not drawn object.visible = false; } return object; } function buildApperanceNode( node ) { var material = new THREE.MeshPhongMaterial(); var transformData; var fields = node.fields; for ( var i = 0, l = fields.length; i < l; i ++ ) { var field = fields[ i ]; var fieldName = field.name; var fieldValues = field.values; switch ( fieldName ) { case 'material': if ( fieldValues[ 0 ] !== null ) { var materialData = getNode( fieldValues[ 0 ] ); if ( materialData.diffuseColor ) material.color.copy( materialData.diffuseColor ); if ( materialData.emissiveColor ) material.emissive.copy( materialData.emissiveColor ); if ( materialData.shininess ) material.shininess = materialData.shininess; if ( materialData.specularColor ) material.specular.copy( materialData.specularColor ); if ( materialData.transparency ) material.opacity = 1 - materialData.transparency; if ( materialData.transparency > 0 ) material.transparent = true; } else { // if the material field is NULL or unspecified, lighting is off and the unlit object color is (0, 0, 0) material = new THREE.MeshBasicMaterial( { color: 0x000000 } ); } break; case 'texture': var textureNode = fieldValues[ 0 ]; if ( textureNode !== null ) { if ( textureNode.name === 'ImageTexture' ) { material.map = getNode( textureNode ); } else { // MovieTexture and PixelTexture not supported yet } } break; case 'textureTransform': if ( fieldValues[ 0 ] !== null ) { transformData = getNode( fieldValues[ 0 ] ); } break; default: console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); break; } } // only apply texture transform data if a texture was defined if ( material.map && transformData ) { material.map.center.copy( transformData.center ); material.map.rotation = transformData.rotation; material.map.repeat.copy( transformData.scale ); material.map.offset.copy( transformData.translation ); } return material; } function buildMaterialNode( node ) { var materialData = {}; var fields = node.fields; for ( var i = 0, l = fields.length; i < l; i ++ ) { var field = fields[ i ]; var fieldName = field.name; var fieldValues = field.values; switch ( fieldName ) { case 'ambientIntensity': // field not supported break; case 'diffuseColor': materialData.diffuseColor = new THREE.Color( fieldValues[ 0 ], fieldValues[ 1 ], fieldValues[ 2 ] ); break; case 'emissiveColor': materialData.emissiveColor = new THREE.Color( fieldValues[ 0 ], fieldValues[ 1 ], fieldValues[ 2 ] ); break; case 'shininess': materialData.shininess = fieldValues[ 0 ]; break; case 'specularColor': materialData.emissiveColor = new THREE.Color( fieldValues[ 0 ], fieldValues[ 1 ], fieldValues[ 2 ] ); break; case 'transparency': materialData.transparency = fieldValues[ 0 ]; break; default: console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); break; } } return materialData; } function buildImageTextureNode( node ) { var texture; var wrapS = THREE.RepeatWrapping; var wrapT = THREE.RepeatWrapping; var fields = node.fields; for ( var i = 0, l = fields.length; i < l; i ++ ) { var field = fields[ i ]; var fieldName = field.name; var fieldValues = field.values; switch ( fieldName ) { case 'url': var url = fieldValues[ 0 ]; if ( url ) texture = textureLoader.load( url ); break; case 'repeatS': if ( fieldValues[ 0 ] === false ) wrapS = THREE.ClampToEdgeWrapping; break; case 'repeatT': if ( fieldValues[ 0 ] === false ) wrapT = THREE.ClampToEdgeWrapping; break; default: console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); break; } } if ( texture ) { texture.wrapS = wrapS; texture.wrapT = wrapT; } return texture; } function buildTextureTransformNode( node ) { var transformData = { center: new THREE.Vector2(), rotation: new THREE.Vector2(), scale: new THREE.Vector2(), translation: new THREE.Vector2() }; var fields = node.fields; for ( var i = 0, l = fields.length; i < l; i ++ ) { var field = fields[ i ]; var fieldName = field.name; var fieldValues = field.values; switch ( fieldName ) { case 'center': transformData.center.set( fieldValues[ 0 ], fieldValues[ 1 ] ); break; case 'rotation': transformData.rotation = fieldValues[ 0 ]; break; case 'scale': transformData.scale.set( fieldValues[ 0 ], fieldValues[ 1 ] ); break; case 'translation': transformData.translation.set( fieldValues[ 0 ], fieldValues[ 1 ] ); break; default: console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); break; } } return transformData; } function buildGeometricNode( node ) { return node.fields[ 0 ].values; } function buildIndexedFaceSetNode( node ) { var color, coord, normal, texCoord; var ccw = true, solid = true, creaseAngle = 0; var colorIndex, coordIndex, normalIndex, texCoordIndex; var colorPerVertex = true, normalPerVertex = true; var fields = node.fields; for ( var i = 0, l = fields.length; i < l; i ++ ) { var field = fields[ i ]; var fieldName = field.name; var fieldValues = field.values; switch ( fieldName ) { case 'color': var colorNode = fieldValues[ 0 ]; if ( colorNode !== null ) { color = getNode( colorNode ); } break; case 'coord': var coordNode = fieldValues[ 0 ]; if ( coordNode !== null ) { coord = getNode( coordNode ); } break; case 'normal': var normalNode = fieldValues[ 0 ]; if ( normalNode !== null ) { normal = getNode( normalNode ); } break; case 'texCoord': var texCoordNode = fieldValues[ 0 ]; if ( texCoordNode !== null ) { texCoord = getNode( texCoordNode ); } break; case 'ccw': ccw = fieldValues[ 0 ]; break; case 'colorIndex': colorIndex = fieldValues; break; case 'colorPerVertex': colorPerVertex = fieldValues[ 0 ]; break; case 'convex': // field not supported break; case 'coordIndex': coordIndex = fieldValues; break; case 'creaseAngle': creaseAngle = fieldValues[ 0 ]; break; case 'normalIndex': normalIndex = fieldValues; break; case 'normalPerVertex': normalPerVertex = fieldValues[ 0 ]; break; case 'solid': solid = fieldValues[ 0 ]; break; case 'texCoordIndex': texCoordIndex = fieldValues; break; default: console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); break; } } if ( coordIndex === undefined ) { console.warn( 'THREE.VRMLLoader: Missing coordIndex.' ); return new THREE.BufferGeometry(); // handle VRML files with incomplete geometry definition } var triangulatedCoordIndex = triangulateFaceIndex( coordIndex, ccw ); var positionAttribute; var colorAttribute; var normalAttribute; var uvAttribute; if ( color ) { if ( colorPerVertex === true ) { if ( colorIndex && colorIndex.length > 0 ) { // if the colorIndex field is not empty, then it is used to choose colors for each vertex of the IndexedFaceSet. var triangulatedColorIndex = triangulateFaceIndex( colorIndex, ccw ); colorAttribute = computeAttributeFromIndexedData( triangulatedCoordIndex, triangulatedColorIndex, color, 3 ); } else { // if the colorIndex field is empty, then the coordIndex field is used to choose colors from the Color node colorAttribute = toNonIndexedAttribute( triangulatedCoordIndex, new THREE.Float32BufferAttribute( color, 3 ) ); } } else { if ( colorIndex && colorIndex.length > 0 ) { // if the colorIndex field is not empty, then they are used to choose one color for each face of the IndexedFaceSet var flattenFaceColors = flattenData( color, colorIndex ); var triangulatedFaceColors = triangulateFaceData( flattenFaceColors, coordIndex ); colorAttribute = computeAttributeFromFaceData( triangulatedCoordIndex, triangulatedFaceColors ); } else { // if the colorIndex field is empty, then the color are applied to each face of the IndexedFaceSet in order var triangulatedFaceColors = triangulateFaceData( color, coordIndex ); colorAttribute = computeAttributeFromFaceData( triangulatedCoordIndex, triangulatedFaceColors ); } } } if ( normal ) { if ( normalPerVertex === true ) { // consider vertex normals if ( normalIndex && normalIndex.length > 0 ) { // if the normalIndex field is not empty, then it is used to choose normals for each vertex of the IndexedFaceSet. var triangulatedNormalIndex = triangulateFaceIndex( normalIndex, ccw ); normalAttribute = computeAttributeFromIndexedData( triangulatedCoordIndex, triangulatedNormalIndex, normal, 3 ); } else { // if the normalIndex field is empty, then the coordIndex field is used to choose normals from the Normal node normalAttribute = toNonIndexedAttribute( triangulatedCoordIndex, new THREE.Float32BufferAttribute( normal, 3 ) ); } } else { // consider face normals if ( normalIndex && normalIndex.length > 0 ) { // if the normalIndex field is not empty, then they are used to choose one normal for each face of the IndexedFaceSet var flattenFaceNormals = flattenData( normal, normalIndex ); var triangulatedFaceNormals = triangulateFaceData( flattenFaceNormals, coordIndex ); normalAttribute = computeAttributeFromFaceData( triangulatedCoordIndex, triangulatedFaceNormals ); } else { // if the normalIndex field is empty, then the normals are applied to each face of the IndexedFaceSet in order var triangulatedFaceNormals = triangulateFaceData( normal, coordIndex ); normalAttribute = computeAttributeFromFaceData( triangulatedCoordIndex, triangulatedFaceNormals ); } } } else { // if the normal field is NULL, then the loader should automatically generate normals, using creaseAngle to determine if and how normals are smoothed across shared vertices normalAttribute = computeNormalAttribute( triangulatedCoordIndex, coord, creaseAngle ); } if ( texCoord ) { // texture coordinates are always defined on vertex level if ( texCoordIndex && texCoordIndex.length > 0 ) { // if the texCoordIndex field is not empty, then it is used to choose texture coordinates for each vertex of the IndexedFaceSet. var triangulatedTexCoordIndex = triangulateFaceIndex( texCoordIndex, ccw ); uvAttribute = computeAttributeFromIndexedData( triangulatedCoordIndex, triangulatedTexCoordIndex, texCoord, 2 ); } else { // if the texCoordIndex field is empty, then the coordIndex array is used to choose texture coordinates from the TextureCoordinate node uvAttribute = toNonIndexedAttribute( triangulatedCoordIndex, new THREE.Float32BufferAttribute( texCoord, 2 ) ); } } var geometry = new THREE.BufferGeometry(); positionAttribute = toNonIndexedAttribute( triangulatedCoordIndex, new THREE.Float32BufferAttribute( coord, 3 ) ); geometry.addAttribute( 'position', positionAttribute ); geometry.addAttribute( 'normal', normalAttribute ); // optional attributes if ( colorAttribute ) geometry.addAttribute( 'color', colorAttribute ); if ( uvAttribute ) geometry.addAttribute( 'uv', uvAttribute ); // "solid" influences the material so let's store it for later use geometry._solid = solid; geometry._type = 'mesh'; return geometry; } function buildIndexedLineSetNode( node ) { var color, coord; var colorIndex, coordIndex; var colorPerVertex = true; var fields = node.fields; for ( var i = 0, l = fields.length; i < l; i ++ ) { var field = fields[ i ]; var fieldName = field.name; var fieldValues = field.values; switch ( fieldName ) { case 'color': var colorNode = fieldValues[ 0 ]; if ( colorNode !== null ) { color = getNode( colorNode ); } break; case 'coord': var coordNode = fieldValues[ 0 ]; if ( coordNode !== null ) { coord = getNode( coordNode ); } break; case 'colorIndex': colorIndex = fieldValues; break; case 'colorPerVertex': colorPerVertex = fieldValues[ 0 ]; break; case 'coordIndex': coordIndex = fieldValues; break; default: console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); break; } } // build lines var colorAttribute; var expandedLineIndex = expandLineIndex( coordIndex ); // create an index for three.js's linesegment primitive if ( color ) { if ( colorPerVertex === true ) { if ( colorIndex.length > 0 ) { // if the colorIndex field is not empty, then one color is used for each polyline of the IndexedLineSet. var expandedColorIndex = expandLineIndex( colorIndex ); // compute colors for each line segment (rendering primitve) colorAttribute = computeAttributeFromIndexedData( expandedLineIndex, expandedColorIndex, color, 3 ); // compute data on vertex level } else { // if the colorIndex field is empty, then the colors are applied to each polyline of the IndexedLineSet in order. colorAttribute = toNonIndexedAttribute( expandedLineIndex, new THREE.Float32BufferAttribute( color, 3 ) ); } } else { if ( colorIndex.length > 0 ) { // if the colorIndex field is not empty, then colors are applied to each vertex of the IndexedLineSet var flattenLineColors = flattenData( color, colorIndex ); // compute colors for each VRML primitve var expandedLineColors = expandLineData( flattenLineColors, coordIndex ); // compute colors for each line segment (rendering primitve) colorAttribute = computeAttributeFromLineData( expandedLineIndex, expandedLineColors ); // compute data on vertex level } else { // if the colorIndex field is empty, then the coordIndex field is used to choose colors from the Color node var expandedLineColors = expandLineData( color, coordIndex ); // compute colors for each line segment (rendering primitve) colorAttribute = computeAttributeFromLineData( expandedLineIndex, expandedLineColors ); // compute data on vertex level } } } // var geometry = new THREE.BufferGeometry(); var positionAttribute = toNonIndexedAttribute( expandedLineIndex, new THREE.Float32BufferAttribute( coord, 3 ) ); geometry.addAttribute( 'position', positionAttribute ); if ( colorAttribute ) geometry.addAttribute( 'color', colorAttribute ); geometry._type = 'line'; return geometry; } function buildPointSetNode( node ) { var geometry; var color, coord; var fields = node.fields; for ( var i = 0, l = fields.length; i < l; i ++ ) { var field = fields[ i ]; var fieldName = field.name; var fieldValues = field.values; switch ( fieldName ) { case 'color': var colorNode = fieldValues[ 0 ]; if ( colorNode !== null ) { color = getNode( colorNode ); } break; case 'coord': var coordNode = fieldValues[ 0 ]; if ( coordNode !== null ) { coord = getNode( coordNode ); } break; default: console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); break; } } var geometry = new THREE.BufferGeometry(); geometry.addAttribute( 'position', new THREE.Float32BufferAttribute( coord, 3 ) ); if ( color ) geometry.addAttribute( 'color', new THREE.Float32BufferAttribute( color, 3 ) ); geometry._type = 'points'; return geometry; } function buildBoxNode( node ) { var size = new THREE.Vector3( 2, 2, 2 ); var fields = node.fields; for ( var i = 0, l = fields.length; i < l; i ++ ) { var field = fields[ i ]; var fieldName = field.name; var fieldValues = field.values; switch ( fieldName ) { case 'size': size.x = fieldValues[ 0 ]; size.y = fieldValues[ 1 ]; size.z = fieldValues[ 2 ]; break; default: console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); break; } } var geometry = new THREE.BoxBufferGeometry( size.x, size.y, size.z ); return geometry; } function buildConeNode( node ) { var radius = 1, height = 2, openEnded = false; var fields = node.fields; for ( var i = 0, l = fields.length; i < l; i ++ ) { var field = fields[ i ]; var fieldName = field.name; var fieldValues = field.values; switch ( fieldName ) { case 'bottom': openEnded = ! fieldValues[ 0 ]; break; case 'bottomRadius': radius = fieldValues[ 0 ]; break; case 'height': height = fieldValues[ 0 ]; break; case 'side': // field not supported break; default: console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); break; } } var geometry = new THREE.ConeBufferGeometry( radius, height, 16, 1, openEnded ); return geometry; } function buildCylinderNode( node ) { var radius = 1, height = 2; var fields = node.fields; for ( var i = 0, l = fields.length; i < l; i ++ ) { var field = fields[ i ]; var fieldName = field.name; var fieldValues = field.values; switch ( fieldName ) { case 'bottom': // field not supported break; case 'radius': radius = fieldValues[ 0 ]; break; case 'height': height = fieldValues[ 0 ]; break; case 'side': // field not supported break; case 'top': // field not supported break; default: console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); break; } } var geometry = new THREE.CylinderBufferGeometry( radius, radius, height, 16, 1 ); return geometry; } function buildSphereNode( node ) { var radius = 1; var fields = node.fields; for ( var i = 0, l = fields.length; i < l; i ++ ) { var field = fields[ i ]; var fieldName = field.name; var fieldValues = field.values; switch ( fieldName ) { case 'radius': radius = fieldValues[ 0 ]; break; default: console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName ); break; } } var geometry = new THREE.SphereBufferGeometry( radius, 16, 16 ); return geometry; } // helper functions function resolveUSE( identifier ) { var node = nodeMap[ identifier ]; var build = getNode( node ); // because the same 3D objects can have different transformations, it's necessary to clone them. // materials can be influenced by the geometry (e.g. vertex normals). cloning is necessary to avoid // any side effects return ( build.isObject3D || build.isMaterial ) ? build.clone() : build; } function parseFieldChildren( children, owner ) { for ( var i = 0, l = children.length; i < l; i ++ ) { var object = getNode( children[ i ] ); if ( object instanceof THREE.Object3D ) owner.add( object ); } } function triangulateFaceIndex( index, ccw ) { var indices = []; // since face defintions can have more than three vertices, it's necessary to // perform a simple triangulation var start = 0; for ( var i = 0, l = index.length; i < l; i ++ ) { var i1 = index[ start ]; var i2 = index[ i + ( ccw ? 1 : 2 ) ]; var i3 = index[ i + ( ccw ? 2 : 1 ) ]; indices.push( i1, i2, i3 ); // an index of -1 indicates that the current face has ended and the next one begins if ( index[ i + 3 ] === - 1 || i + 3 >= l ) { i += 3; start = i + 1; } } return indices; } function triangulateFaceData( data, index ) { var triangulatedData = []; var start = 0; for ( var i = 0, l = index.length; i < l; i ++ ) { var stride = start * 3; var x = data[ stride ]; var y = data[ stride + 1 ]; var z = data[ stride + 2 ]; triangulatedData.push( x, y, z ); // an index of -1 indicates that the current face has ended and the next one begins if ( index[ i + 3 ] === - 1 || i + 3 >= l ) { i += 3; start ++; } } return triangulatedData; } function flattenData( data, index ) { var flattenData = []; for ( var i = 0, l = index.length; i < l; i ++ ) { var i1 = index[ i ]; var stride = i1 * 3; var x = data[ stride ]; var y = data[ stride + 1 ]; var z = data[ stride + 2 ]; flattenData.push( x, y, z ); } return flattenData; } function expandLineIndex( index ) { var indices = []; for ( var i = 0, l = index.length; i < l; i ++ ) { var i1 = index[ i ]; var i2 = index[ i + 1 ]; indices.push( i1, i2 ); // an index of -1 indicates that the current line has ended and the next one begins if ( index[ i + 2 ] === - 1 || i + 2 >= l ) { i += 2; } } return indices; } function expandLineData( data, index ) { var triangulatedData = []; var start = 0; for ( var i = 0, l = index.length; i < l; i ++ ) { var stride = start * 3; var x = data[ stride ]; var y = data[ stride + 1 ]; var z = data[ stride + 2 ]; triangulatedData.push( x, y, z ); // an index of -1 indicates that the current line has ended and the next one begins if ( index[ i + 2 ] === - 1 || i + 2 >= l ) { i += 2; start ++; } } return triangulatedData; } var vA = new THREE.Vector3(); var vB = new THREE.Vector3(); var vC = new THREE.Vector3(); var uvA = new THREE.Vector2(); var uvB = new THREE.Vector2(); var uvC = new THREE.Vector2(); function computeAttributeFromIndexedData( coordIndex, index, data, itemSize ) { var array = []; // we use the coordIndex.length as delimiter since normalIndex must contain at least as many indices for ( var i = 0, l = coordIndex.length; i < l; i += 3 ) { var a = index[ i ]; var b = index[ i + 1 ]; var c = index[ i + 2 ]; if ( itemSize === 2 ) { uvA.fromArray( data, a * itemSize ); uvB.fromArray( data, b * itemSize ); uvC.fromArray( data, c * itemSize ); array.push( uvA.x, uvA.y ); array.push( uvB.x, uvB.y ); array.push( uvC.x, uvC.y ); } else { vA.fromArray( data, a * itemSize ); vB.fromArray( data, b * itemSize ); vC.fromArray( data, c * itemSize ); array.push( vA.x, vA.y, vA.z ); array.push( vB.x, vB.y, vB.z ); array.push( vC.x, vC.y, vC.z ); } } return new THREE.Float32BufferAttribute( array, itemSize ); } function computeAttributeFromFaceData( index, faceData ) { var array = []; for ( var i = 0, j = 0, l = index.length; i < l; i += 3, j ++ ) { vA.fromArray( faceData, j * 3 ); array.push( vA.x, vA.y, vA.z ); array.push( vA.x, vA.y, vA.z ); array.push( vA.x, vA.y, vA.z ); } return new THREE.Float32BufferAttribute( array, 3 ); } function computeAttributeFromLineData( index, lineData ) { var array = []; for ( var i = 0, j = 0, l = index.length; i < l; i += 2, j ++ ) { vA.fromArray( lineData, j * 3 ); array.push( vA.x, vA.y, vA.z ); array.push( vA.x, vA.y, vA.z ); } return new THREE.Float32BufferAttribute( array, 3 ); } function toNonIndexedAttribute( indices, attribute ) { var array = attribute.array; var itemSize = attribute.itemSize; var array2 = new array.constructor( indices.length * itemSize ); var index = 0, index2 = 0; for ( var i = 0, l = indices.length; i < l; i ++ ) { index = indices[ i ] * itemSize; for ( var j = 0; j < itemSize; j ++ ) { array2[ index2 ++ ] = array[ index ++ ]; } } return new THREE.Float32BufferAttribute( array2, itemSize ); } var ab = new THREE.Vector3(); var cb = new THREE.Vector3(); function computeNormalAttribute( index, coord, creaseAngle ) { var faces = []; var vertexNormals = {}; // prepare face and raw vertex normals for ( var i = 0, l = index.length; i < l; i += 3 ) { var a = index[ i ]; var b = index[ i + 1 ]; var c = index[ i + 2 ]; var face = new Face( a, b, c ); vA.fromArray( coord, a * 3 ); vB.fromArray( coord, b * 3 ); vC.fromArray( coord, c * 3 ); cb.subVectors( vC, vB ); ab.subVectors( vA, vB ); cb.cross( ab ); cb.normalize(); face.normal.copy( cb ); if ( vertexNormals[ a ] === undefined ) vertexNormals[ a ] = []; if ( vertexNormals[ b ] === undefined ) vertexNormals[ b ] = []; if ( vertexNormals[ c ] === undefined ) vertexNormals[ c ] = []; vertexNormals[ a ].push( face.normal ); vertexNormals[ b ].push( face.normal ); vertexNormals[ c ].push( face.normal ); faces.push( face ); } // compute vertex normals and build final geometry var normals = []; for ( var i = 0, l = faces.length; i < l; i ++ ) { var face = faces[ i ]; var nA = weightedNormal( vertexNormals[ face.a ], face.normal, creaseAngle ); var nB = weightedNormal( vertexNormals[ face.b ], face.normal, creaseAngle ); var nC = weightedNormal( vertexNormals[ face.c ], face.normal, creaseAngle ); vA.fromArray( coord, face.a * 3 ); vB.fromArray( coord, face.b * 3 ); vC.fromArray( coord, face.c * 3 ); normals.push( nA.x, nA.y, nA.z ); normals.push( nB.x, nB.y, nB.z ); normals.push( nC.x, nC.y, nC.z ); } return new THREE.Float32BufferAttribute( normals, 3 ); } function weightedNormal( normals, vector, creaseAngle ) { var normal = new THREE.Vector3(); if ( creaseAngle === 0 ) { normal.copy( vector ); } else { for ( var i = 0, l = normals.length; i < l; i ++ ) { if ( normals[ i ].angleTo( vector ) < creaseAngle ) { normal.add( normals[ i ] ); } } } return normal.normalize(); } function toColorArray( colors ) { var array = []; for ( var i = 0, l = colors.length; i < l; i += 3 ) { array.push( new THREE.Color( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ) ); } return array; } /** * Vertically paints the faces interpolating between the * specified colors at the specified angels. This is used for the Background * node, but could be applied to other nodes with multiple faces as well. * * When used with the Background node, default is directionIsDown is true if * interpolating the skyColor down from the Zenith. When interpolationg up from * the Nadir i.e. interpolating the groundColor, the directionIsDown is false. * * The first angle is never specified, it is the Zenith (0 rad). Angles are specified * in radians. The geometry is thought a sphere, but could be anything. The color interpolation * is linear along the Y axis in any case. * * You must specify one more color than you have angles at the beginning of the colors array. * This is the color of the Zenith (the top of the shape). * * @param {BufferGeometry} geometry * @param {number} radius * @param {array} angles * @param {array} colors * @param {boolean} topDown - Whether to work top down or bottom up. */ function paintFaces( geometry, radius, angles, colors, topDown ) { var direction = ( topDown === true ) ? 1 : - 1; var coord = [], A = {}, B = {}, applyColor = false; for ( var k = 0; k < angles.length; k ++ ) { // push the vector at which the color changes var vec = { x: direction * ( Math.cos( angles[ k ] ) * radius ), y: direction * ( Math.sin( angles[ k ] ) * radius ) }; coord.push( vec ); } var index = geometry.index; var positionAttribute = geometry.attributes.position; var colorAttribute = new THREE.BufferAttribute( new Float32Array( geometry.attributes.position.count * 3 ), 3 ); var position = new THREE.Vector3(); var color = new THREE.Color(); for ( var i = 0; i < index.count; i ++ ) { var vertexIndex = index.getX( i ); position.fromBufferAttribute( positionAttribute, vertexIndex ); for ( var j = 0; j < colors.length; j ++ ) { // linear interpolation between aColor and bColor, calculate proportion // A is previous point (angle) if ( j === 0 ) { A.x = 0; A.y = ( topDown === true ) ? radius : - 1 * radius; } else { A.x = coord[ j - 1 ].x; A.y = coord[ j - 1 ].y; } // B is current point (angle) B = coord[ j ]; if ( B !== undefined ) { // p has to be between the points A and B which we interpolate applyColor = ( topDown === true ) ? ( position.y <= A.y && position.y > B.y ) : ( position.y >= A.y && position.y < B.y ); if ( applyColor === true ) { var aColor = colors[ j ]; var bColor = colors[ j + 1 ]; // below is simple linear interpolation var t = Math.abs( position.y - A.y ) / ( A.y - B.y ); // to make it faster, you can only calculate this if the y coord changes, the color is the same for points with the same y color.copy( aColor ).lerp( bColor, t ); colorAttribute.setXYZ( vertexIndex, color.r, color.g, color.b ); } else { var colorIndex = ( topDown === true ) ? colors.length - 1 : 0; var c = colors[ colorIndex ]; colorAttribute.setXYZ( vertexIndex, c.r, c.g, c.b ); } } } } geometry.addAttribute( 'color', colorAttribute ); } // var textureLoader = new THREE.TextureLoader( this.manager ); textureLoader.setPath( this.resourcePath || path ).setCrossOrigin( this.crossOrigin ); // create JSON representing the tree structure of the VRML asset var tree = generateVRMLTree( data ); // check version (only 2.0 is supported) if ( tree.version.indexOf( 'V2.0' ) === - 1 ) { throw Error( 'THREE.VRMLLexer: Version of VRML asset not supported.' ); } // parse the tree structure to a three.js scene var scene = parseTree( tree ); return scene; } } ); function VRMLLexer( tokens ) { this.lexer = new chevrotain.Lexer( tokens ); } VRMLLexer.prototype = { constructor: VRMLLexer, lex: function ( inputText ) { var lexingResult = this.lexer.tokenize( inputText ); if ( lexingResult.errors.length > 0 ) { console.error( lexingResult.errors ); throw Error( 'THREE.VRMLLexer: Lexing errors detected.' ); } return lexingResult; } }; function VRMLParser( tokenVocabulary ) { chevrotain.Parser.call( this, tokenVocabulary ); var $ = this; var Version = tokenVocabulary[ 'Version' ]; var LCurly = tokenVocabulary[ 'LCurly' ]; var RCurly = tokenVocabulary[ 'RCurly' ]; var LSquare = tokenVocabulary[ 'LSquare' ]; var RSquare = tokenVocabulary[ 'RSquare' ]; var Identifier = tokenVocabulary[ 'Identifier' ]; var RouteIdentifier = tokenVocabulary[ 'RouteIdentifier' ]; var StringLiteral = tokenVocabulary[ 'StringLiteral' ]; var NumberLiteral = tokenVocabulary[ 'NumberLiteral' ]; var TrueLiteral = tokenVocabulary[ 'TrueLiteral' ]; var FalseLiteral = tokenVocabulary[ 'FalseLiteral' ]; var NullLiteral = tokenVocabulary[ 'NullLiteral' ]; var DEF = tokenVocabulary[ 'DEF' ]; var USE = tokenVocabulary[ 'USE' ]; var ROUTE = tokenVocabulary[ 'ROUTE' ]; var TO = tokenVocabulary[ 'TO' ]; var NodeName = tokenVocabulary[ 'NodeName' ]; $.RULE( 'vrml', function () { $.SUBRULE( $.version ); $.AT_LEAST_ONE( function () { $.SUBRULE( $.node ); } ); $.MANY( function () { $.SUBRULE( $.route ); } ); } ); $.RULE( 'version', function () { $.CONSUME( Version ); } ); $.RULE( 'node', function () { $.OPTION( function () { $.SUBRULE( $.def ); } ); $.CONSUME( NodeName ); $.CONSUME( LCurly ); $.MANY( function () { $.SUBRULE( $.field ); } ); $.CONSUME( RCurly ); } ); $.RULE( 'field', function () { $.CONSUME( Identifier ); $.OR2( [ { ALT: function () { $.SUBRULE( $.singleFieldValue ); } }, { ALT: function () { $.SUBRULE( $.multiFieldValue ); } } ] ); } ); $.RULE( 'def', function () { $.CONSUME( DEF ); $.CONSUME( Identifier ); } ); $.RULE( 'use', function () { $.CONSUME( USE ); $.CONSUME( Identifier ); } ); $.RULE( 'singleFieldValue', function () { $.AT_LEAST_ONE( function () { $.OR( [ { ALT: function () { $.SUBRULE( $.node ); } }, { ALT: function () { $.SUBRULE( $.use ); } }, { ALT: function () { $.CONSUME( StringLiteral ); } }, { ALT: function () { $.CONSUME( NumberLiteral ); } }, { ALT: function () { $.CONSUME( TrueLiteral ); } }, { ALT: function () { $.CONSUME( FalseLiteral ); } }, { ALT: function () { $.CONSUME( NullLiteral ); } } ] ); } ); } ); $.RULE( 'multiFieldValue', function () { $.CONSUME( LSquare ); $.MANY( function () { $.OR( [ { ALT: function () { $.SUBRULE( $.node ); } }, { ALT: function () { $.SUBRULE( $.use ); } }, { ALT: function () { $.CONSUME( StringLiteral ); } }, { ALT: function () { $.CONSUME( NumberLiteral ); } }, { ALT: function () { $.CONSUME( NullLiteral ); } } ] ); } ); $.CONSUME( RSquare ); } ); $.RULE( 'route', function () { $.CONSUME( ROUTE ); $.CONSUME( RouteIdentifier ); $.CONSUME( TO ); $.CONSUME2( RouteIdentifier ); } ); this.performSelfAnalysis(); } VRMLParser.prototype = Object.create( chevrotain.Parser.prototype ); VRMLParser.prototype.constructor = VRMLParser; function Face( a, b, c ) { this.a = a; this.b = b; this.c = c; this.normal = new THREE.Vector3(); } return VRMLLoader; } )();
mit
openforis/collect
collect-core/src/main/java/org/openforis/idm/model/expression/internal/CustomFunction.java
2455
package org.openforis.idm.model.expression.internal; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.commons.jxpath.Function; import org.apache.commons.jxpath.ri.compiler.Expression; import org.openforis.idm.metamodel.NodeDefinition; import org.openforis.idm.metamodel.expression.ExpressionValidator.ExpressionValidationResult; import org.openforis.idm.metamodel.expression.ExpressionValidator.ExpressionValidationResultFlag; public abstract class CustomFunction implements Function { private static final int UNLIMITED_ARGUMENTS_COUNT = Integer.MAX_VALUE; private static final List<Integer> UNLIMITED_ARGUMENT_COUNTS = Arrays.asList(UNLIMITED_ARGUMENTS_COUNT); private final Set<String> referencedPaths; private final List<Integer> supportedArgumentCounts; /** * Create a custom function, optionally including paths that are referenced * independent on any parameters passed to the function. */ public CustomFunction(String... referencedPaths) { this(UNLIMITED_ARGUMENT_COUNTS, referencedPaths); } public CustomFunction(int supportedArgumentCount, String... referencedPaths) { this(Arrays.asList(supportedArgumentCount), referencedPaths); } public CustomFunction(List<Integer> supportedArgumentCounts, String... referencedPaths) { this.supportedArgumentCounts = supportedArgumentCounts; Set<String> paths = new HashSet<String>(); Collections.addAll(paths, referencedPaths); this.referencedPaths = Collections.unmodifiableSet(paths); } public List<Integer> getSupportedArgumentCounts() { return supportedArgumentCounts; } public final ExpressionValidationResult validateArguments(NodeDefinition contextNodeDef, Expression[] arguments) { if (getSupportedArgumentCounts().contains(arguments.length) || UNLIMITED_ARGUMENT_COUNTS.equals(getSupportedArgumentCounts())) { return performArgumentValidation(contextNodeDef, arguments); } else { return new ExpressionValidationResult(ExpressionValidationResultFlag.ERROR, String.format("Invalid number of arguments: found %d but %d expected", arguments.length, getSupportedArgumentCounts())); } } protected ExpressionValidationResult performArgumentValidation(NodeDefinition contextNodeDef, Expression[] arguments) { return new ExpressionValidationResult(); } public Set<String> getReferencedPaths() { return referencedPaths; } }
mit
nahusha1987/Hackerrank-java-solutions
30-days-of-code/Day 8 Dictionaries and Maps/Solution.java
790
//Complete this code or write your own from scratch import java.util.*; import java.io.*; class Solution{ public static void main(String []argh){ Scanner in = new Scanner(System.in); int n = in.nextInt(); Map<String, Integer> directory = new HashMap<>(); for(int i = 0; i < n; i++){ String name = in.next(); int phone = in.nextInt(); // Write code here directory.put(name,phone); } while(in.hasNext()){ String s = in.next(); // Write code here Integer i = directory.get(s); if(i == null) System.out.println("Not found"); else System.out.println(s + "=" + i); } in.close(); } }
mit
crossoverJie/springboot-cloud
sbc-user/user/src/main/java/com/crossoverJie/sbcuser/req/UserReq.java
410
package com.crossoverJie.sbcuser.req; import com.crossoverJie.sbcorder.common.req.BaseRequest; /** * Function: * * @author crossoverJie * Date: 2017/6/8 上午12:10 * @since JDK 1.8 */ public class UserReq extends BaseRequest { private long userId ; public long getUserId() { return userId; } public void setUserId(long userId) { this.userId = userId; } }
mit
thomas-vds/thomas-vds.github.io
js/demo1.js
2425
var canvas = document.getElementById("demo1-canvas"); var ctx = canvas.getContext("2d"); var canvasPosition; canvas.width = window.innerWidth-95; canvas.height = 600; canvas.style.border = "5pt solid Indianred"; function getPosition(element){ var xPos = 0; var yPos = 0; while (element) { if (element.tagName == "BODY") { // deal with browser quirks with body/window/document and page scroll var xScroll = element.scrollLeft || document.documentElement.scrollLeft; var yScroll = element.scrollTop || document.documentElement.scrollTop; xPos += (element.offsetLeft - xScroll + element.clientLeft); yPos += (element.offsetTop - yScroll + element.clientTop); } else { // for all other non-BODY elements xPos += (element.offsetLeft - element.scrollLeft + element.clientLeft); yPos += (element.offsetTop - element.scrollTop + element.clientTop); } element = element.offsetParent; } return { x: xPos, y: yPos }; } function updatePosition(){ canvasPosition = getPosition(canvas); } var mouse = { dx:0, dy:0, down:false } var running = false; var interval; function init(){ ctx.fillStyle = "Mediumseagreen"; ctx.fillRect(0,0,canvas.width,canvas.height); }init(); function renderAll(){ if (mouse.down){ ctx.clearRect(mouse.dx - canvasPosition.x,mouse.dy - canvasPosition.y,50,50); } canvasPosition = getPosition(canvas); } function start(){ if(running === false){ interval = window.setInterval(renderAll,1000/60); running = true; console.log("started"); } } function stop(){ if(running){ window.clearInterval(interval); running = false; console.log("stopped"); } } // EVENT listeners canvas.addEventListener("mousedown",function (e) { e.preventDefault(); mouse.down = true; }); canvas.addEventListener("mouseup",function (e) { e.preventDefault(); mouse.down = false; }); canvas.addEventListener("mousemove",function (e){ mouse.dx = e.clientX; mouse.dy = e.clientY; }); canvas.addEventListener("mouseenter",function(e){ start(); }); canvas.addEventListener("mouseleave",function(e){ stop(); }); document.addEventListener("scroll", updatePosition,false); document.addEventListener("resize", updatePosition,false);
mit
rememberlenny/remind-to-read
app/models/account.rb
1224
class Account < ActiveRecord::Base has_many :users after_create :generate_uid after_create :send_welcome_emails after_create :make_default_forms def self.find_param(param) find_by! public_uid: param.split('-').first end def to_param "#{public_uid}-#{tile.gsub(/\s/,'-')}" end def make_default_forms RemindForm.create(can_be_changed: false, title: 'Need to stop reading?', cta: 'Send email', form_blocks: '', account_id: self.id) end def send_welcome_emails # UserMailer.delay.welcome_email(self.id) # UserMailer.delay_for(5.days).find_more_friends_email(self.id) end def self.check_is_unique_uid uid uu = Account.find_by_uid(uid) if uu.nil? return true end return false end def generate_uid uid = SecureRandom.hex(4) + '-' + SecureRandom.hex(1) checked = Account.check_is_unique_uid(uid) if checked == true self.uid = uid self.save else generate_uid end end def self.check_has_script_setup id uu = Account.where(uid: id) if uu.count > 0 u = uu.first u.has_script_setup = true u.save end end def self.check_account_status id Account.where(domain: id) end end
mit
jntkym/rappers
chainer_model/lyric_server.py
6360
#coding: utf-8 from __future__ import print_function, division from argparse import ArgumentParser import math import sys import time import os sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import utils import numpy as np import cPickle import chainer from chainer import cuda import chainer.functions as F from chainer import optimizers import os import socket p = ArgumentParser() p.add_argument('--gpu', '-G', default=-1, type=int, help='GPU ID (negative value indicates CPU)') p.add_argument('-M', '--model', type=str, help='model_file') p.add_argument('-O', '--output_file', type=str, default=sys.stderr, help='output file (default: stderr)') p.add_argument('-N', '--n_lines', type=int, default=1000, help='num of lines') p.add_argument('-H', '--highquality', default=False, action="store_true") args = p.parse_args() if args.output_file != sys.stderr: args.output_file = open(args.output_file, "w") # Prepare RNNLM model model = cPickle.load(open(args.model, 'rb')) vocab = cPickle.load(open("vocab.pkl", "rb")) inv_vocab = cPickle.load(open("inv_vocab.pkl", "rb")) n_units = model.embed.W.shape[1] xp = cuda.cupy if args.gpu >= 0 else np if args.gpu >= 0: cuda.check_cuda_available() cuda.get_device(args.gpu).use() model.to_gpu() if args.gpu < 0: model.to_cpu() # load mild yankee dict mild_yankee_dict = utils.load_csv_to_dict("mild_dict.csv") def force_mild(state, line, word_id): cur_word = xp.array([word_id], dtype=np.int32) state, predict = forward_one_step(cur_word, state, train=False) if mild_yankee_dict.has_key(unicode(inv_vocab[word_id])): for next_word in mild_yankee_dict[unicode(inv_vocab[word_id])].split(): line.append(next_word) next_word_id = xp.array([vocab[next_word]], dtype=np.int32) state, predict = forward_one_step(next_word_id, state, train=False) return predict def forward_one_step(x_data, state, train=True): if args.gpu >= 0: x_data = cuda.to_gpu(x_data) x = chainer.Variable(x_data, volatile=not train) h0 = model.embed(x) h1_in = model.l1_x(F.dropout(h0, train=train)) + model.l1_h(state['h1']) c1, h1 = F.lstm(state['c1'], h1_in) h2_in = model.l2_x(F.dropout(h1, train=train)) + model.l2_h(state['h2']) c2, h2 = F.lstm(state['c2'], h2_in) y = model.l3(F.dropout(h2, train=train)) state = {'c1': c1, 'h1': h1, 'c2': c2, 'h2': h2} return state, F.softmax(y) def make_initial_state(batchsize=1, train=True): return {name: chainer.Variable(xp.zeros((batchsize, n_units), dtype=np.float32), volatile=not train) for name in ('c1', 'h1', 'c2', 'h2')} def generate_line(seed=None): # start with <s> :1 is assigned to <s> line = [] state = make_initial_state(batchsize=1, train=False) if args.gpu >= 0: for key, value in state.items(): value.data = cuda.to_gpu(value.data) index = 1 cur_word = xp.array([index], dtype=xp.int32) if seed is not None: for word in seed: state, predict = forward_one_step(cur_word, state, train=False) index = vocab[word] cur_word = xp.array([index], dtype=xp.int32) if index != 1: line.append(inv_vocab[index]) if index == 1: state, predict = forward_one_step(cur_word, state, train=False) probability = cuda.to_cpu(predict.data)[0].astype(np.float64) probability /= np.sum(probability) index = np.random.choice(range(len(probability)), p=probability) line.append(inv_vocab[index]) seq_len = 1 while(1): predict = force_mild(state, line, index) probability = cuda.to_cpu(predict.data)[0].astype(np.float64) if args.highquality: sorted_prob = sorted(probability, reverse=True) max_10_list = sorted_prob[:10] for i in xrange(len(probability)): if probability[i] not in max_10_list: probability[i] = 0 probability /= np.sum(probability) index = np.random.choice(range(len(probability)), p=probability) # index = cuda.to_cpu(predict.data)[0].astype(np.float64).argmax() if seq_len < 10 and index == 2: seq_len += 1 continue if index == 2: # 2 is assigned to </s> break line.append(inv_vocab[index]) seq_len += 1 if seq_len > 30: break return " ".join(line)+"\n" if __name__ == '__main__': requestMax = 50 PORT = 50100 HOST = '0.0.0.0' sys.stderr.write("waiting...") for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_PASSIVE): af, socktype, proto, canonname, sa = res try: s = socket.socket(af, socktype, proto) except socket.error, msg: s = None continue try: s.bind(sa) s.listen(requestMax) except socket.error, msg: s.close() s = None continue break if s is None: print('could not open socket') sys.exit(1) conn, addr = s.accept() print('Connected by', addr) # pid = os.fork() # if pid == 0: # print("child process") # while 1: # msg = raw_input("> ") # conn.send('%s' % msg ) # if msg == ".": # break; # sys.exit() while 1: data = conn.recv(1024) seed = data.split() if not data: print('End') break elif data == "close": print("Client is closed") os.kill(pid, 9) break else: try: if "<unk>" in [inv_vocab[vocab[word]] for word in seed]: conn.send("sorry, out of vocabulary ... \n") else: for i in xrange(args.n_lines): line = generate_line(seed) conn.send(line) finally: conn.send("finish") conn.close() sys.exit()
mit
ld-test/pop3
lua/pop3/message.lua
25411
--- Implement class to decode mime messages -- @module pop3.message -- local DEFAULT_CP_CONV = require "pop3.charset" .convert local socket_mime = require "mime" -- luasocket local socket_ltn12 = require "ltn12" -- luasocket local CP = DEFAULT_CP_CONV local CRLF = '\r\n' local DECODERS = { ['base64'] = function(nl) local t = { -- socket_mime.normalize(), -- decode_content alwas set CRLF for this function(msg) return socket_mime.unb64('', msg) end, } if nl and nl ~= CRLF then table.insert(t, function(msg) return socket_mime.eol(0, msg, nl) end) end return socket_ltn12.filter.chain((unpack or table.unpack)(t)) end; ['quoted-printable'] = function(nl) local t = { -- socket_mime.normalize(), -- decode_content alwas set CRLF for this function(msg) return socket_mime.unqp('', msg) end, } if nl and nl ~= CRLF then table.insert(t, function(msg) return socket_mime.eol(0, msg, nl) end) end return socket_ltn12.filter.chain((unpack or table.unpack)(t)) end; } local IS_WINDOWS = (package.config:sub(1,1) == '\\') ------------------------------------------------------------------------- -- ------------------------------------------------------------------------- local function ltrim(s) return (string.gsub (s, "^%s+","")) end local function rtrim (s) return (string.gsub (s, "%s+$","")) end local function trim (s) return rtrim(ltrim (s)) end local function clone (t) local u = {} for i, v in pairs (t) do u[i] = v end return u end local function slice(t, s, e) local u = {} for i = (s or 1), (e or #t) do u[i - s + 1] = t[i] end return u end local function split(str, sep, plain) local b, res = 1, {} while b <= #str do local e, e2 = string.find(str, sep, b, plain) if e then table.insert(res, (string.sub(str, b, e-1))) b = e2 + 1 else table.insert(res, (string.sub(str, b))) break end end return res end local decode_str = function (target_charset, base_charset, str) if str == nil then return nil end if not str:find([[=%?([%w-]+)%?(.)%?(.-)%?=]]) then if base_charset then return CP(target_charset, base_charset, str) end return str end str = str:gsub([[(%?=)%s*(=%?)]],'%1%2') -- Romove ws. Is it necessary? return (str:gsub([[=%?([%w-]+)%?(.)%?(.-)%?=]],function(codepage,encoding,data) encoding = encoding:upper() local algo if encoding == 'B'then algo = assert(DECODERS['base64']) elseif encoding == 'Q' then algo = assert(DECODERS['quoted-printable']) end if algo then data = algo()(data) return CP(target_charset, codepage, data) end end)) end local function as_date(str) return str end -- if pcall( require, "date" ) then -- as_date = function (str) local d = date(str) return d or str end -- end ------------------------------------------------------------------------- -- разбирает заголовки to, from и т.д в список структур {name=;addr=} -- оба параметра не обязытельные local get_address_list do local function prequire(...) local ok, mod = pcall(require, ...) return ok and mod, mod end local re = prequire "re" if re then local function try_load_get_address_list() -- @todo unquot quoted name local mail_pat = re.compile[[ groups <- (group (%s* ([,;] %s*)+ group)*) -> {} group <- ( {:name: <phrase> :} %s* <addr> / {:name: <uq_phrase> :} %s* "<" <addr_spec> ">" / <addr> %s* {:name: <phrase> :} / "<" <addr_spec> ">" %s* {:name: <uq_phrase> :} / <addr> / {:name: <phrase> :} ) -> {} uq_phrase <- <uq_atom> (%s+ <uq_atom>)* uq_atom <- [^<>,; ]+ phrase <- <word> ([%s.]+ <word>)* / <quoted_string> word <- <atom> ! <domain_addr> atom <- [^] %c()<>@,;:\".[]+ quoted_string <- '"' ([^"\%nl] / "\" .)* '"' addr <- <addr_spec> / "<" <addr_spec> ">" addr_spec <- {:addr: <addr_chars> <domain_addr> :} domain_addr <- "@" <addr_chars> addr_chars <- [_%a%d][-._%a%d]* ]] return function(str) if (not str) or (str == '') then return nil end return mail_pat:match(str) end end local ok, fn = pcall(try_load_get_address_list) if ok then get_address_list = fn end if get_address_list then -- test -- local cmp_t local function cmp_v(v1,v2) local flag = true if type(v1) == 'table' then flag = (type(v2) == 'table') and cmp_t(v1, v2) else flag = (v1 == v2) end return flag end function cmp_t(t1,t2) for k in pairs(t2)do if t1[k] == nil then return false end end for k,v in pairs(t1)do if not cmp_v(t2[k],v) then return false end end return true end local tests = {} local tests_index={} local test = function(str, result) local t if type(result) == 'string' then local res = assert(tests_index[str]) t = {result, result = res.result} assert(result ~= str) tests_index[result] = t; else t = {str,result=result} tests_index[str] = t; end return table.insert(tests,t) end assert(get_address_list() == nil) assert(get_address_list('') == nil) test([[aaa@mail.ru]], {{ addr = "aaa@mail.ru" }} ) test([[aaa@mail.ru]],[[<aaa@mail.ru>]]) test([["aaa@mail.ru"]], {{ name = '"aaa@mail.ru"' }} ) test([[Subscriber YPAG.RU <aaa@mail.ru>]], {{ name = "Subscriber YPAG.RU", addr = "aaa@mail.ru" }} ) test([[Subscriber YPAG.RU <aaa@mail.ru>]], [[<aaa@mail.ru> Subscriber YPAG.RU]]) test([["Subscriber YPAG.RU" <aaa@mail.ru>]], {{ name = '"Subscriber YPAG.RU"', addr = "aaa@mail.ru" }} ) test([["Subscriber YPAG.RU" <aaa@mail.ru>]],[[<aaa@mail.ru> "Subscriber YPAG.RU"]]) test([["Subscriber ;,YPAG.RU" <aaa@mail.ru>]], {{ name = '"Subscriber ;,YPAG.RU"', addr = "aaa@mail.ru" }} ) test([[Subscriber ;,YPAG.RU <aaa@mail.ru>]], { { name = "Subscriber" }, { name = "YPAG.RU", addr = "aaa@mail.ru" } } ) test([["Subscriber ;,YPAG.RU" <aaa@mail.ru>]],[[<aaa@mail.ru> "Subscriber ;,YPAG.RU"]]) test([[info@arenda-a.com, travel@mama-africa.ru; info@some.mail.domain.ru ]], { { addr = "info@arenda-a.com" }, { addr = "travel@mama-africa.ru" }, { addr = "info@some.mail.domain.ru" } } ) test([[info@arenda-a.com, travel@mama-africa.ru; info@some.mail.domain.ru ]], [[<info@arenda-a.com>, travel@mama-africa.ru; info@some.mail.domain.ru ]]) test([["name@some.mail.domain.ru" <addr@some.mail.domain.ru>]], { { name = "\"name@some.mail.domain.ru\"", addr = "addr@some.mail.domain.ru" } } ) test([[name@some.mail.domain.ru <addr@some.mail.domain.ru>]], { { name = "name@some.mail.domain.ru", addr = "addr@some.mail.domain.ru" } } ) test([[MailList: рассылка номер 78236 <78236-response@maillist.ru>]], { { name = "MailList: рассылка номер 78236", addr = "78236-response@maillist.ru" } } ) test([[<aaa@mail.ru>, "Info Mail List" <bbb@mail.ru>, Сакен Матов <saken@from.kz>, "Evgeny Zhembrovsky \(ezhembro\)" <ezhembro@cisco.com> ]], { { addr = "aaa@mail.ru" }, { name = "\"Info Mail List\"", addr = "bbb@mail.ru" }, { name = "Сакен Матов", addr = "saken@from.kz" }, { name = "\"Evgeny Zhembrovsky \\(ezhembro\\)\"", addr = "ezhembro@cisco.com" } } ) if POP3_SELF_TEST then local lunit = require"lunit" function test_pop3_messege_get_address_list() for _, test_case in ipairs(tests) do lunit.assert_true(cmp_t(get_address_list(test_case[1]),test_case.result),test_case[1]) end end end if POP3_DEBUG then for _,test_case in ipairs(tests)do local res = get_address_list(test_case[1]) if not cmp_v(res, test_case.result ) then require "pprint" print"----------------------------------------------" print("ERROR:", test_case[1]) print"EXPECTED:" pprint(test_case.result) print"RESULT:" pprint(res) end end end --verify for _,test_case in ipairs(tests)do local res = get_address_list(test_case[1]) if not cmp_v(res, test_case.result) then get_address_list = nil end end end -- test -- end -- require "re" -- end -- get_address_list -- ------------------------------------------------------------------------- ------------------------------------------------------------------------- -- ------------------------------------------------------------------------- local DEFAULT_LOCAL_CP = 'utf-8' if IS_WINDOWS then DEFAULT_LOCAL_CP = require("pop3.win.cp").GetLocalCPName() end local DEFAULT_NL = IS_WINDOWS and CRLF or '\n' local MIME_ERR_NO_BOUNDARY = "Malformed mime header. No boundary in content-type." local MIME_ERR_BOUNDARY_TOO_LONG = "Malformed mime header. Boundary is too long." local MIME_ERR_BOUNDARY_NOCLOSE = "Malformed mime header. Boundary is not closed." ------------------------------------------------------------------------- -- ------------------------------------------------------------------------- local mime = {} local mime_header = {} local mime_headers = {} local mime_content = {} local mime_content_multipart = {} -------------------------------------------------------------------------- do -- mime_content_multipart local mime_content_multipart_mt = { __index = function(self, k) if type(k) == 'number' then return self.content_[k] end return mime_content_multipart[k] end; __len = function(self) return #self.content_ end; } function mime_content_multipart:parts() return #self.content_ end setmetatable(mime_content_multipart,{__call = function (self, headers, msg, index_begin, index_end) assert(index_begin <= index_end) assert(index_end <= #msg) local boundary = headers:param('content-type', 'boundary') if not boundary then return nil, MIME_ERR_NO_BOUNDARY end boundary = '--' .. boundary local boundary_close = boundary .. '--' if #boundary > 72 then return nil, MIME_ERR_BOUNDARY_TOO_LONG end local result = setmetatable({},mime_content_multipart_mt) result.is_multi = true result.content_ = {} -- array local i = index_begin while i <= index_end do while(i <= index_end)do if msg[i] == boundary or msg[i] == boundary_close then break end i = i + 1 end if i > index_end then break end local line = msg[i] if line == (boundary_close) then i = index_end + 1 break end assert(line == boundary) i = i + 1 local cstart = i while(i <= index_end)do if msg[i] == boundary or msg[i] == boundary_close then break end i = i + 1 end if i > index_end then result.is_truncated = true end -- if i > index_end then return nil, MIME_ERR_BOUNDARY_NOCLOSE end local cend = i - 1 local content, err, i1, i2 = mime(msg, cstart, cend) if not content then return nil, err, i1, i2 end table.insert(result.content_, content) end assert(i == (index_end + 1)) return result, i end}) end -------------------------------------------------------------------------- -------------------------------------------------------------------------- do -- mime_content function mime_content:as_string(sep) return table.concat(self.message_, sep or '', self.bound_[1], self.bound_[2]) end function mime_content:as_table() return slice(self.message_, self.bound_[1], self.bound_[2]) end; setmetatable(mime_content,{__call = function(self, mtype, headers, msg, index_begin, index_end) if string.sub(mtype,1,9) == 'multipart' then return mime_content_multipart(headers, msg, index_begin, index_end) end local result = {} --clone(self) result.is_data = true; result.message_ = msg;-- or create closure? result.bound_ = {index_begin, index_end}; return setmetatable(result, { __tostring = self.as_string, __index = self } ) end}) end -------------------------------------------------------------------------- -------------------------------------------------------------------------- do -- mime_header function mime_header:value() return self.value_ end function mime_header:key() return self.key_ end function mime_header:param(key) return self.param_[key] end setmetatable(mime_header,{__call = function (self, str) local result = setmetatable({},{__index = self}) --clone(self) result.raw_ = str; result.value_ = ""; result.param_ = {} local key_index = string.find(str, ":", 1, true) local key = key_index and (string.sub(str, 1, key_index-1)) or str key = string.lower(trim(key)) result.key_ = key if not key_index then return result end str = rtrim(string.sub(str, key_index + 1)) if string.sub(str, -1) ~= ';' then str = str .. ';' end local par_index = string.find(str, ';%s*[^%s=]+%s*=%s*.-;') local value = par_index and (string.sub(str, 1, par_index - 1)) or string.sub(str,1,-2) result.value_ = trim(value) -- result.value_ = string.lower(trim(value)) if not par_index then return result end str = string.sub(str, par_index) local param = {} for key, value in string.gmatch(str, "[;]?%s*([^%s=]+)%s*=%s*(.-);") do if not string.find(key, [[^%?([%w-]+)%?(.)%?]]) then -- "?utf-8?B?..."= if string.sub(value, 1, 1) == '"' then value = string.sub(value, 2, -2 ) value = string.gsub(value, '""', '"') --?? else value = trim(value) end key = string.lower(trim(key)) -- trim just in case param[ key ] = value end end result.param_ = param; return result end}) end -------------------------------------------------------------------------- -------------------------------------------------------------------------- do -- mime_headers function mime_headers:header(key) assert(key) key = string.lower(key) for i, h in ipairs (self.headers_) do if h:key() == key then return h end end end function mime_headers:value(key,def) local h = self:header(key) return h and h:value() or def end function mime_headers:param(key, param, def) local h = self:header(key) if h then return h:param(param) or def end return def end function mime_headers:headers(key) assert(key) key = string.lower(key) local result = {} for i, h in ipairs (self.headers_) do if h:key() == key then table.insert(result, h) end end return result end function mime_headers:as_table(key) key = key and string.lower(key) local result = {} for i, h in ipairs (self.headers_) do if (not key) or (h:key() == key) then if result[h:key()] == nil then result[h:key()] = h.raw_ end end end return result end setmetatable(mime_headers,{__call = function (self, msg, index_begin, index_end) local buffer = {} local result = setmetatable({},{__index = self}) result.headers_={} -- array for i = index_begin, index_end do local line = msg[i] or "" if line:find("^%s") then table.insert(buffer,ltrim(line)) else if buffer[1] then local str = table.concat(buffer, " ") local header = mime_header(str) table.insert(result.headers_, header) end buffer = {rtrim(line)} end if line == "" then return result, i + 1 end end return result, index_end + 1 end}) end -------------------------------------------------------------------------- -------------------------------------------------------------------------- do -- mime --- -- @type mime mime.cp_ = assert(DEFAULT_LOCAL_CP) mime.eol_ = assert(DEFAULT_NL) --- Return mime type -- return value of 'content-type' header function mime:type() return self.type_ end --- Set target codepage -- This codepage use when need decode text data. function mime:set_cp(cp) self:for_each(function(t) assert(t.cp_); t.cp_ = cp end) end --- Set target EOL -- This EOL use when need decode text data. function mime:set_eol(nl) self:for_each(function(t) assert(t.eol_); t.eol_ = nl end) end --- Retrun current codepage to decode. -- This is not codepage message itself. function mime:cp() return self.cp_ end --- Retrun current EOL to decode. -- This is not EOL message itself. function mime:eol() return self.eol_ end --- -- function mime:hvalue(key, def) return self.headers:value(key, def) end --- -- function mime:hparam(key, param, def) return self.headers:param(key, param, def) end --- -- function mime:header(key) return self.headers:header(key) end --- -- function mime:subject() return decode_str(self:cp(), self:charset(), self:hvalue("subject",'')) end --- -- @treturn string function mime:from() return decode_str(self:cp(), self:charset(), self:hvalue("from")) end --- -- @treturn string function mime:to() return decode_str(self:cp(), self:charset(), self:hvalue("to")) end --- -- @treturn string function mime:reply_to() return decode_str(self:cp(), self:charset(), self:hvalue("reply-to")) end if get_address_list then --- -- Depends on lpeg library -- @treturn table {{name=...,addr=...}, ...} function mime:from_list() return get_address_list(self:from()) end --- -- Depends on lpeg library -- @treturn table {{name=...,addr=...}, ...} function mime:to_list() return get_address_list(self:to()) end --- -- Depends on lpeg library -- @treturn table {{name=...,addr=...}, ...} function mime:reply_list() return get_address_list(self:reply_to()) end --- -- Depends on lpeg library -- @treturn string address -- @treturn string name function mime:from_address() local t = self:from_list() if t then for _,k in ipairs(t) do if k and k.addr then return k.addr, k.name end end end end --- -- Depends on lpeg library -- @treturn string address -- @treturn string name function mime:to_address() local t = self:to_list() if t then for _,k in ipairs(t) do if k and k.addr then return k.addr, k.name end end end end --- -- Depends on lpeg library -- @treturn string address -- @treturn string name function mime:reply_address() local t = self:reply_list() if t then for _,k in ipairs(t) do if k and k.addr then return k.addr, k.name end end end return self:from_address() end end function mime:as_string(nl) return table.concat(self.message_, nl or CRLF, self.bound_[1], self.bound_[2]) end function mime:as_table() return slice(self.message_, self.bound_[1], self.bound_[2]) end --- -- function mime:id() return self:hvalue("message-id", '') end --- -- function mime:date() local h = self:header("date") return h and as_date(h:value()) or '' end --- -- function mime:encoding() return self:hvalue("content-transfer-encoding") end --- -- function mime:charset() return self:hparam("content-type", "charset", self:cp()) end --- -- function mime:content_name() local h = self:hparam("content-type", "name") if h then return decode_str(self:cp(), self:charset(), h) end end --- -- function mime:file_name() local h = self:hparam("content-disposition", "filename") if h then return decode_str(self:cp(), self:charset(), h) end end --- -- function mime:disposition() return self:hvalue("content-disposition") end --- -- function mime:is_application() return self:type():sub(1,11) == 'application' end --- -- function mime:is_text() return self:type():sub(1,4) == 'text' end --- -- function mime:is_truncated() return self.content.is_truncated end --- -- function mime:is_multi() return self.content.is_multi end --- -- function mime:is_data() return self.content.is_data end --- -- function mime:is_binary() return (not self:is_text()) and (not self:is_multi()) end --- -- function mime:is_attachment() local h = self:disposition() return h and h:sub(1,10):lower() == 'attachment' end --- -- function mime:for_each(fn, ...) fn(self, ...) if self:is_multi() then for k, part in ipairs(self.content.content_) do fn(part, ...) if part:is_multi() then part:for_each(fn, ...) end end end end --- -- function mime:decode_content() assert(self.content) if self:is_data() then local data local encoding = self:encoding() if encoding then local algo = DECODERS[encoding:lower()] if algo then local content = self.content:as_string(CRLF) data = algo(self:is_text() and self:eol())( content ) end end if self:is_text() then local charset = self:charset() data = data or self.content:as_string(self:eol()) if charset then return CP(self:cp(), charset, data) end return data end return data or self.content:as_string() end return self.content end local function grab_text(self) return{ text = self:decode_content(), type = self:type() } end local function grab_binary(self) return{ data = self:decode_content(), name = self:content_name(), file_name = self:file_name(), type = self:type() } end local function content_collector(self, dst) dst = dst or {} if self:is_binary() then table.insert( dst, grab_binary(self) ) elseif self:is_text() then table.insert( dst, grab_text(self) ) else assert(self:is_multi()) end end local function if_collector(self, pred, grab, dst) dst = dst or {} if pred(self) then table.insert( dst, grab(self) ) end end function mime:collect(collector,t) t = t or {} self:for_each(collector, t) return t end function mime:collect_if(pred, grab, t) t = t or {} self:for_each(if_collector, pred, grab, t) return t end --- -- function mime:full_content() return self:collect(content_collector) end --- Return all attachments from message -- function mime:attachments() return self:collect_if(self.is_attachment, grab_binary) end --- Return all binary parts of message -- function mime:objects() return self:collect_if(self.is_binary, grab_binary) end --- Return text part of message -- function mime:text() return self:collect_if(self.is_text, grab_text) end setmetatable(mime,{__call = function (self, msg, index_begin, index_end) index_begin, index_end = index_begin or 1, index_end or #msg local result = setmetatable({},{__index = self}) -- clone(self) result.bound_ = {index_begin, index_end}; result.message_ = msg; local headers, index = mime_headers(msg, index_begin, index_end) result.headers = headers result.type_ = result:hvalue('content-type', 'text/plain'):lower() local err result.content, err = mime_content(result:type(), headers, msg, index, index_end) if not result.content then return nil, err, index_begin, index_end end return result end}) end -------------------------------------------------------------------------- local setmetatable = setmetatable local M = {} function M.set_cp(cp) DEFAULT_LOCAL_CP = cp end -- conv(target_charset, base_charset, str) function M.set_cp_converter(conv) CP = (conv or DEFAULT_CP_CONV) end function M.set_eol(nl) DEFAULT_NL = nl end function M.cp() return DEFAULT_LOCAL_CP end function M.cp_converter() return CP end function M.eol() return DEFAULT_NL end setmetatable(M, {__call = function(self, msg, ...) if type(msg) == "string" then msg = split(msg, CRLF, true) end return mime(msg, ...) end}) return M --[[ mime | +- bound_ = {index_begin, index_end} -- full mime | +- message_ = msg | +- type_ = hvalue 'content-type' | +- headers = array of mime header(mime_headers object) | +- content | \- mime_content - for data part (text, file, image etc.) is_data = true message_ = msg bound_ = {index_begin, index_end} -- only data (without headers) \- mime_content_multipart - for multipart is_multi = true content_ = array of mime --]]
mit
FagnerMartinsBrack/Servlet-URL-Convention
src/test/java/com/fagnerbrack/servlet/convention/test/unit/FileResourcePathTest.java
2241
package com.fagnerbrack.servlet.convention.test.unit; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.servlet.ServletContext; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; import com.fagnerbrack.servlet.convention.loader.FileResourcePath; import com.fagnerbrack.servlet.convention.property.PropertyValue; import com.fagnerbrack.servlet.convention.property.RootPropertyValue; @RunWith( MockitoJUnitRunner.class ) public class FileResourcePathTest { private @Mock ServletContext servletContext; @Test public void should_list_correct_children() { PropertyValue<String> rootProperty = new RootPropertyValue( "com.company" ); String path = "/com/company/"; Set<String> items = new HashSet<String>(); items.add( "/com/company/PageAction.class" ); Mockito.when( servletContext.getResourcePaths( path ) ).thenReturn( items ); FileResourcePath resourcePath = new FileResourcePath( path, rootProperty ); List<FileResourcePath> paths = resourcePath.children( servletContext ); Assert.assertEquals( 1, paths.size() ); Assert.assertEquals( "/com/company/PageAction.class", paths.get( 0 ).getAbsolutePath() ); } @Test public void should_lowercase_the_class_name() { String expected = "org/company/index"; String actual = FileResourcePath.filePathToURI( "org/company/Index" ); Assert.assertEquals( expected, actual ); } @Test public void should_dash_when_multiple_pascal_words() { String expected = "org/company/index-page"; String actual = FileResourcePath.filePathToURI( "org/company/IndexPage" ); Assert.assertEquals( expected, actual ); } @Test public void should_dash_correctly_when_first_character_of_a_second_word_is_a_digit() { String expected = "org/company/page-1"; String actual = FileResourcePath.filePathToURI( "org/company/Page1" ); Assert.assertEquals( expected, actual ); } @Test public void should_not_dash_multiple_digits() { String expected = "org/company/page-404"; String actual = FileResourcePath.filePathToURI( "org/company/Page404" ); Assert.assertEquals( expected, actual ); } }
mit
atealxt/work-workspaces
easyFramework/prj/src/main/java/sshdemo/service/ServiceB.java
265
package sshdemo.service; import org.springframework.stereotype.Service; @Service("ServiceB") public class ServiceB { public void testTransaction() { System.out.println("will auto rollback"); throw new UnsupportedOperationException(); } }
mit
kidshenlong/warpspeed
Project Files/Assets/Scripts/UI/UIPauseMenuDimScript.cs
875
using UnityEngine; using System.Collections; public class UIPauseMenuDimScript : MonoBehaviour, IGameStateListener { private UISprite sprite; private TweenColor tColor; void Awake() { sprite = GetComponent<UISprite>(); tColor = GetComponent<TweenColor>(); } void Start() { GameStateScript.addStateListener(this); } public void changeGameState(GameState change) { switch (change) { case GameState.Pause: gameObject.SetActive(true); tColor.Play(true); break; case GameState.Play: tColor.Play(false); StartCoroutine(fadeOut()); break; } } IEnumerator fadeOut() { yield return new WaitForSeconds(1); gameObject.SetActive(false); } }
mit
KHaertner/BAEmslandUsabilityGame
xmlsubmit.php
690
<?php $name = htmlentities($_POST['name']); $score = htmlentities($_POST['score']); $scores = new DOMDocument(); $scores->load("highscore.xml"); $scoresRoot = $scores->getElementsByTagName('highscore')->item(0); $scoresNode = $scores->createElement('player'); // erstellt das komplexe Element 'player' $scoresRoot->appendChild($scoresNode); $scoresNode->appendChild($scores->createElement("name", $name)); // fügt dem Element 'player' das simple Element 'name' hinzu mit der Variable Name $scoresNode->appendChild($scores->createElement("score", $score)); // fügt dem Element 'player' das simple Element 'score' hinzu mit der Variable Score $scores->save("highscore.xml"); ?>
mit
denormal/go-gitconfig
errors.go
186
package gitconfig import ( "github.com/denormal/go-gittools" ) var ( MissingGitError = gittools.MissingGitError MissingWorkingCopyError = gittools.MissingWorkingCopyError )
mit
meet-languages/test
src/app/app.component.ts
314
import { Component, OnInit } from '@angular/core'; import {UserService} from './services/user.service'; import {User} from '../User'; @Component({ selector: 'my-app', template: `<router-outlet></router-outlet>`, providers: [UserService], styleUrls: ['/style/style.css'] }) export class AppComponent { }
mit
mrayy/mrayGStreamerUnity
Plugin/sources/GstNetworkVideoPlayer.cpp
10098
#include "stdafx.h" #include "GstNetworkVideoPlayer.h" #include "CMyUDPSrc.h" #include "CMyUDPSink.h" #include "CMySrc.h" #include "CMySink.h" #include "VideoAppSinkHandler.h" #include "GstPipelineHandler.h" #include <gst/gst.h> #include <gst/app/gstappsink.h> namespace mray { namespace video { class GstNetworkVideoPlayerImpl :public GstPipelineHandler,IPipelineListener { GstNetworkVideoPlayer* m_owner; std::string m_ipAddr; uint m_videoPort; uint m_clockPort; std::string m_pipeLineString; GstElement* m_videoSrc; GstMyUDPSrc* m_videoRtcpSrc; GstMyUDPSink* m_videoRtcpSink; GstAppSink* m_videoSink; bool m_rtcp; VideoAppSinkHandler m_videoHandler; public: GstNetworkVideoPlayerImpl(GstNetworkVideoPlayer* o) { m_owner = o; m_ipAddr = "127.0.0.1"; m_videoPort = 5000; m_clockPort = 5010; m_videoSrc = 0; m_videoRtcpSrc = 0; m_videoRtcpSink = 0; m_videoSink = 0; AddListener(this); } virtual ~GstNetworkVideoPlayerImpl() { } void _BuildPipelineH264() { std::string videoStr = //video rtp "udpsrc name=videoSrc !" //"udpsrc port=7000 buffer-size=2097152 do-timestamp=true !" "application/x-rtp "; if (m_rtcp) { m_pipeLineString = "rtpbin " "name=rtpbin " + videoStr + "! rtpbin.recv_rtp_sink_0 " "rtpbin. ! rtph264depay ! avdec_h264 ! " "videoconvert ! video/x-raw,format=RGB !" " appsink name=videoSink " //video rtcp "myudpsrc name=videoRtcpSrc ! rtpbin.recv_rtcp_sink_0 " "rtpbin.send_rtcp_src_0 ! myudpsink name=videoRtcpSink sync=false async=false "; } else { m_pipeLineString = videoStr + "! queue !" "rtpjitterbuffer ! " "rtph264depay ! h264parse ! avdec_h264 ! " // " videorate ! "//"video/x-raw,framerate=60/1 ! " // "videoconvert ! video/x-raw,format=RGB !" // Very slow!! "videoconvert ! video/x-raw,format=I420 !" // " timeoverlay halignment=right text=\"Local Time =\"! " " appsink name=videoSink sync=false emit-signals=false"; //"fpsdisplaysink sync=false"; } } void _BuildPipelineMJPEG() { std::string videoStr = //video rtp "udpsrc " "name=videoSrc " "caps=application/x-rtp,media=(string)video,clock-rate=(int)90000,encoding-name=(string)JPEG "; if (m_rtcp) { m_pipeLineString = "rtpbin " "name=rtpbin " + videoStr + "! rtpbin.recv_rtp_sink_0 " "rtpbin. ! rtpjpegdepay ! jpegdec ! " "videoconvert ! video/x-raw,format=RGB !" " appsink name=videoSink " //video rtcp "myudpsrc name=videoRtcpSrc ! rtpbin.recv_rtcp_sink_0 " "rtpbin.send_rtcp_src_0 ! myudpsink name=videoRtcpSink sync=false async=false "; } else { m_pipeLineString = videoStr + "!" "rtpjpegdepay ! jpegdec ! " "videorate ! " "videoconvert ! video/x-raw,format=RGB !" " appsink name=videoSink sync=false"; } } void _UpdatePorts() { if (!GetPipeline()) return; #define SET_SRC(name,p) m_##name=GST_MyUDPSrc(gst_bin_get_by_name(GST_BIN(GetPipeline()), #name)); if(m_##name){m_##name->SetPort(p);} #define SET_SINK(name,p) m_##name=GST_MyUDPSink(gst_bin_get_by_name(GST_BIN(GetPipeline()), #name)); if(m_##name){m_##name->SetPort(m_ipAddr,p);} //SET_SRC(videoSrc, m_videoPort); SET_SINK(videoRtcpSink, (m_videoPort + 1)); SET_SRC(videoRtcpSrc, (m_videoPort + 2)); g_object_set(m_videoSrc, "port", m_videoPort, "host",m_ipAddr.c_str(),0); } void SetIPAddress(const std::string& ip, uint videoPort, uint clockPort, bool rtcp) { m_ipAddr = ip; m_videoPort = videoPort; m_clockPort = clockPort; m_rtcp = rtcp; //set src and sinks elements _UpdatePorts(); } static GstFlowReturn new_buffer(GstElement *sink, void *data) { GstBuffer *buffer; GstMapInfo map; GstSample *sample; //gsize size; g_signal_emit_by_name(sink, "pull-sample", &sample, NULL); if (sample) { buffer = gst_sample_get_buffer(sample); gst_buffer_map(buffer, &map, GST_MAP_READ); gst_buffer_unmap(buffer, &map); gst_sample_unref(sample); } return GST_FLOW_OK; } bool CreateStream() { if (IsLoaded()) return true; _BuildPipelineH264(); GError *err = 0; GstElement* p = gst_parse_launch(m_pipeLineString.c_str(), &err); if (err) { LogMessage("GstNetworkVideoPlayer: Pipeline error: " + std::string(err->message), ELL_WARNING); } if (!p) return false; SetPipeline(p); printf("Connecting Video stream with IP:%s\n", m_ipAddr.c_str()); _UpdatePorts(); m_videoSink = GST_APP_SINK(gst_bin_get_by_name(GST_BIN(p), "videoSink")); m_videoHandler.SetSink(m_videoSink); g_signal_connect(m_videoSink, "new-sample", G_CALLBACK(new_buffer), this); //attach videosink callbacks GstAppSinkCallbacks gstCallbacks; gstCallbacks.eos = &VideoAppSinkHandler::on_eos_from_source; gstCallbacks.new_preroll = &VideoAppSinkHandler::on_new_preroll_from_source; #if GST_VERSION_MAJOR==0 gstCallbacks.new_buffer = &VideoAppSinkHandler::on_new_buffer_from_source; #else gstCallbacks.new_sample = &VideoAppSinkHandler::on_new_buffer_from_source; #endif gst_app_sink_set_callbacks(GST_APP_SINK(m_videoSink), &gstCallbacks, &m_videoHandler, NULL); //gst_app_sink_set_emit_signals(GST_APP_SINK(m_videoSink), true); // gst_base_sink_set_async_enabled(GST_BASE_SINK(m_videoSink), TRUE); // gst_base_sink_set_sync(GST_BASE_SINK(m_videoSink), false); // gst_app_sink_set_drop(GST_APP_SINK(m_videoSink), TRUE); // gst_app_sink_set_max_buffers(GST_APP_SINK(m_videoSink), 8); // gst_base_sink_set_max_lateness(GST_BASE_SINK(m_videoSink), 0); /* GstCaps* caps; caps = gst_caps_new_simple("video/x-raw", "format", G_TYPE_STRING, "RGB", "pixel-aspect-ratio", GST_TYPE_FRACTION, 1, 1, "width", G_TYPE_INT, 1280, "height", G_TYPE_INT, 720, NULL); gst_app_sink_set_caps(GST_APP_SINK(m_videoSink), caps); gst_caps_unref(caps); // Set the configured video appsink to the main pipeline g_object_set(m_gstPipeline, "video-sink", m_videoSink, (void*)NULL); // Tell the video appsink that it should not emit signals as the buffer retrieving is handled via callback methods g_object_set(m_videoSink, "emit-signals", false, "sync", false, "async", false, (void*)NULL); */ return CreatePipeline(false,m_ipAddr,m_clockPort); } bool IsStream() { return true; } virtual void Close() { /*if (m_videoSrc && m_videoSrc->m_client) m_videoSrc->m_client->Close();*/ GstPipelineHandler::Close(); m_videoHandler.Close(); } void Play() { SetPaused(false); } void Pause() { SetPaused(true); } void SetVolume(float vol) { g_object_set(G_OBJECT(GetPipeline()), "volume", (gdouble)vol, (void*)0); } virtual int GetPort(int i) { /*if (m_videoSrc && m_videoSrc->m_client) return m_videoSrc->m_client->Port();*/ if (m_videoSrc) { gint port; g_object_get(m_videoSrc, "port", &port, 0); return port; } return m_videoPort; } virtual const Vector2d& GetFrameSize() { return m_videoHandler.GetFrameSize(); } virtual video::EPixelFormat GetImageFormat() { return m_videoHandler.getPixelsRef()->format; } const GstImageFrame* GetLastDataFrame() { return m_videoHandler.getPixelFrame(); } virtual unsigned long GetLastFrameTimestamp() { return m_videoHandler.getPixelFrame()->RTPPacket.timestamp; } void* GetLastFrameRTPMeta() { return &m_videoHandler.getPixelFrame()->RTPPacket; } virtual bool GrabFrame(){ return m_videoHandler.GrabFrame(); } virtual bool HasNewFrame(){ return m_videoHandler.isFrameNew(); } virtual ulong GetBufferID(){ return m_videoHandler.GetFrameID(); } virtual float GetCaptureFrameRate(){ return m_videoHandler.GetCaptureFrameRate(); } virtual const ImageInfo* GetLastFrame(){ return m_videoHandler.getPixelsRef(); } virtual void OnPipelineReady(GstPipelineHandler* p){ m_owner->__FIRE_OnPlayerReady(m_owner); } virtual void OnPipelinePlaying(GstPipelineHandler* p){ m_owner->__FIRE_OnPlayerStarted(m_owner); } virtual void OnPipelineStopped(GstPipelineHandler* p){ m_owner->__FIRE_OnPlayerStopped(m_owner); } }; GstNetworkVideoPlayer::GstNetworkVideoPlayer() { m_impl = new GstNetworkVideoPlayerImpl(this); } GstNetworkVideoPlayer::~GstNetworkVideoPlayer() { delete m_impl; } void GstNetworkVideoPlayer::SetIPAddress(const std::string& ip, uint videoPort, uint clockPort, bool rtcp) { m_impl->SetIPAddress(ip, videoPort, clockPort,rtcp); } bool GstNetworkVideoPlayer::CreateStream() { return m_impl->CreateStream(); } GstPipelineHandler*GstNetworkVideoPlayer::GetPipeline() { return m_impl; } void GstNetworkVideoPlayer::SetVolume(float vol) { m_impl->SetVolume(vol); } bool GstNetworkVideoPlayer::IsStream() { return m_impl->IsStream(); } void GstNetworkVideoPlayer::Play() { m_impl->Play(); } void GstNetworkVideoPlayer::Stop() { m_impl->Stop(); } void GstNetworkVideoPlayer::Pause() { m_impl->Pause(); } bool GstNetworkVideoPlayer::IsLoaded() { return m_impl->IsLoaded(); } bool GstNetworkVideoPlayer::IsPlaying() { return m_impl->IsPlaying(); } void GstNetworkVideoPlayer::Close() { m_impl->Close(); } const Vector2d& GstNetworkVideoPlayer::GetFrameSize() { return m_impl->GetFrameSize(); } video::EPixelFormat GstNetworkVideoPlayer::GetImageFormat() { return m_impl->GetImageFormat(); } bool GstNetworkVideoPlayer::GrabFrame(int i) { return m_impl->GrabFrame(); } bool GstNetworkVideoPlayer::HasNewFrame() { return m_impl->HasNewFrame(); } ulong GstNetworkVideoPlayer::GetBufferID() { return m_impl->GetBufferID(); } float GstNetworkVideoPlayer::GetCaptureFrameRate() { return m_impl->GetCaptureFrameRate(); } const ImageInfo* GstNetworkVideoPlayer::GetLastFrame(int i) { return m_impl->GetLastFrame(); } const GstImageFrame* GstNetworkVideoPlayer::GetLastDataFrame(int i) { return m_impl->GetLastDataFrame(); } void* GstNetworkVideoPlayer::GetLastFrameRTPMeta(int i) { return m_impl->GetLastFrameRTPMeta(); } unsigned long GstNetworkVideoPlayer::GetLastFrameTimestamp(int i ) { return m_impl->GetLastFrameTimestamp(); } int GstNetworkVideoPlayer::GetPort(int i) { return m_impl->GetPort(i); } } }
mit
RenatoMAlves/AnimaSom-Game
.history/animaSom/js/play_20170606133359.js
1925
var playState = { create: function(){ var background = game.add.sprite(0, 0, 'cidade'); background.width = 1300; background.height = 650; graphics = game.add.graphics(0, 0); groupCidade = game.add.group(); groupCidade.inputEnableChildren = true; var x = 100; for (var i = 0; i < 3; i++){ // Gera os retangulos que ficarão atras das imagens graphics.beginFill(0xFFFFFF); graphics.lineStyle(3, 0x05005e, 1); graphics.drawRoundedRect(x, 200, 315, 190, 10); graphics.endFill(); var button = groupCidade.create(x, 200, graphics.generateTexture()); button.tint = 0xff8800; button.name = 'groupCidade-child-' + i; x = x + 400; } graphics.destroy(); var cachorro = game.add.sprite(110, 210, 'cachorro'); cachorro.width = 300; cachorro.height = 170; // Desenha o gato e a borda da box var gato = game.add.sprite(510, 210, 'gato'); gato.width = 300; gato.height = 170; // Desenha o passaro e a borda da box var passaro = game.add.sprite(910, 210, 'passaro'); passaro.width = 300; passaro.height = 170; groupCidade.onChildInputDown.add(onDown, this); groupCidade.onChildInputOver.add(onOver, this); groupCidade.onChildInputOut.add(onOut, this); gato.tint = 0x000000 function onDown (sprite) { sprite.tint = 0x00ff00; } function onOver (sprite) { sprite.tint = 0xffff00; } function onOut (sprite) { sprite.tint = 0xff8800; // sprite.tint = Math.random() * 0xffffff; } }, update: function(){ }, Win: function(){ game.state.start('win'); } };
mit
AzureDay/2017-WebSite
TeamSpark.AzureDay.WebSite.Config/Configuration.cs
1922
using System; using System.Configuration; namespace TeamSpark.AzureDay.WebSite.Config { public static class Configuration { #region general public static string Year => "2017"; public static string Host => "https://azureday.net"; #endregion #region cdn public static string CdnEndpointWeb => GetConfigVariable("CdnEndpointWeb"); public static string CdnEndpointStorage => GetConfigVariable("CdnEndpointStorage"); #endregion #region azure storage public static string AzureStorageAccountName => GetConfigVariable("AzureStorageAccountName"); public static string AzureStorageAccountKey => GetConfigVariable("AzureStorageAccountKey"); #endregion #region application insight public static string ApplicationInsightInstrumentationKey => GetConfigVariable("ApplicationInsightInstrumentationKey"); public static string ApplicationInsightEnvironmentTag => GetConfigVariable("ApplicationInsightEnvironmentTag"); #endregion #region sendgrid public static string SendGridApiKey => GetConfigVariable("SendGridApiKey"); public static string SendGridFromEmail => GetConfigVariable("SendGridFromEmail"); public static string SendGridFromName => GetConfigVariable("SendGridFromName"); #endregion #region kaznachey public static Guid KaznacheyMerchantId => Guid.Parse(GetConfigVariable("KaznacheyMerchantId")); public static string KaznacheyMerchantSecreet => GetConfigVariable("KaznacheyMerchantSecreet"); #endregion #region tickets public static decimal TicketRegular => 750; public static decimal TicketWorkshop => 1750; #endregion private static string GetConfigVariable(string name) { var value = Environment.GetEnvironmentVariable(name); if (string.IsNullOrEmpty(value)) { value = ConfigurationManager.AppSettings.Get(name); } if (string.IsNullOrEmpty(value)) { return string.Empty; } return value; } } }
mit
Sunikee/Knockback-extravaganza
Knockback Extravaganza/Game/Source/Scenes/MPHostScene.cs
887
using ECS_Engine.Engine.Network; using ECS_Engine.Engine.Scenes; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Game.Source.Scenes { class MPHostScene : Scene { public MPHostScene(string name, ContentManager content, GraphicsDeviceManager graphics) : base(name, content, graphics) { } public override void InitScene() { var hostEntity = ComponentManager.MakeEntity(); var host = new NetworkServerComponent(); ComponentManager.AddComponent(hostEntity, host); SystemManager.AddSystem(new NetworkServerSystem()); base.InitScene(); } public override void ResetScene() { } } }
mit
magnusjt/regtemplate_php
tests/RegTemplateParseTest.php
2571
<?php class TestRegTemplateParse extends PHPUnit_Framework_TestCase{ /** @var \RegTemplate\RegTemplate */ public $regtemplate; public function setUp(){ $this->regtemplate = new \RegTemplate\RegTemplate(); } public function syntaxErrorTemplateProvider(){ return [ ['Empty variable', '{{ }}'], ['Unbalanced bracket right', '{{ number }'], ['Unknown rule', '{{ name|flargenblargen }}'], ['Regex missing end quote', '{{ name|reg="\d\d }}'], ['Missing variable name', '{{ |digits }}'] ]; } public function legalTemplateProvider(){ return [ ['Empty template', ''], ['Unbalanced bracket left (parsed as raw)', '{ number }}'], ['Variable', '{{ number }}'], ['Variable with rule digits', '{{ number|digits}}'], ['Variable with rule word', '{{number|word }}'], ['Variable with custom regex', '{{ number|reg="\d\d" }}'], ['Variable with custom regex, escaped quote', '{{ number|reg="\"" }}'], ['Two variables', '{{ blargen1 }}{{ blargen2 }}'] ]; } /** * @dataProvider syntaxErrorTemplateProvider */ public function test_IllegalTemplate_ParseTemplate_SyntaxError($description, $template){ try{ $this->regtemplate->parse_template($template); }catch(\RegTemplate\SyntaxError $e){ return; } $this->fail('SyntaxError not thrown: ' . $description); } /** * @dataProvider legalTemplateProvider */ public function test_LegalTemplate_ParseTemplate_NoException($description, $template){ try{ $this->regtemplate->parse_template($template); }catch(\RegTemplate\SyntaxError $e){ $this->fail('Legal template resulted in syntax error during parse: ' . $description . ', Exception: ' . $e->getMessage()); }catch(Exception $e){ $this->fail('Legal template resulted in exception during parse: ' . $description . ', Exception: ' . $e->getMessage()); } } public function test_TemplateWithCustomTags_Parse_NoException(){ $this->regtemplate->set_variable_tokens('<<', '>>'); $this->regtemplate->parse_template('<<myvariable|digits>>'); } }
mit
dhardtke/assetie
src/Dhardtke/Assetie/AssetieServiceProvider.php
879
<?php namespace Dhardtke\Assetie; use Illuminate\Support\ServiceProvider; class AssetieServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Bootstrap the application events. * * @return void */ public function boot() { $this->package('dhardtke/assetie'); // Load the asset collections if they're in app/collections.php if (file_exists($file = $this->app['path'].'/collections.php')) require $file; } /** * Register the service provider. * * @return void */ public function register() { $this->app["collection"] = $this->app->share(function($app) { return new Collection; }); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return array('assetie'); } }
mit
anorudes/redux-easy-boilerplate
app/containers/Posts/index.js
1370
import React, { Component, PropTypes } from 'react'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import Helmet from 'react-helmet'; import { asyncConnect } from 'redux-connect'; import * as actionCreators from 'redux/modules'; import { apiGetPosts } from 'redux/modules/posts/posts'; /* component styles */ import s from './styles.css'; export class Posts extends Component { static propTypes = { items: PropTypes.array, }; render() { const { items } = this.props; return ( <section className={s.root}> <Helmet title="posts" /> <h1>Posts page</h1> <div className={s.list}> { // Render posts items && items.map(post => <div className={s.item} key={post.id}> {post.id}) {post.text} </div> ) } </div> </section> ); } } export default asyncConnect([{ promise: ({ store: { dispatch, getState } }) => { if (!getState().posts.items) { // Get items from api server // see: app/redux/modules/posts return dispatch(apiGetPosts()); } }, }])(connect( // Conect to redux posts store // see: app/redux/modules/posts state => ({ ...state.posts }), dispatch => bindActionCreators({ ...actionCreators.posts, }, dispatch), )(Posts));
mit