code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
import { Routes, RouterModule } from '@angular/router'; import { Grupos } from './grupos.component'; import { Ckeditor } from './components/ckeditor/ckeditor.component'; // noinspection TypeScriptValidateTypes const routes: Routes = [ { path: '', component: Grupos, children: [ { path: 'ckeditor', component: Ckeditor } ] } ]; export const routing = RouterModule.forChild(routes);
Kmilo9433/arka-cliente-generador
src/app/pages/grupos/grupos.routing.ts
TypeScript
mit
411
import 'pixi' import 'p2' import Phaser from 'phaser' import BootState from './states/Boot' import SplashState from './states/Splash' import GameState from './states/Game' import config from './config' class Game extends Phaser.Game { constructor () { const docElement = document.documentElement const width = docElement.clientWidth; const height = docElement.clientHeight; super(width, height, Phaser.Auto, 'content', null) this.state.add('Boot', BootState, false); this.state.add('Splash', SplashState, false); this.state.add('Game', GameState, false); this.state.start('Boot') } } window.game = new Game();
juergensen/a-little-game-2
src/main.js
JavaScript
mit
690
#include "Chapter7.h" #include "Killable.h" bool IKillable::IsDead() { return false; } void IKillable::Die() { GEngine->AddOnScreenDebugMessage(-1,1, FColor::Red,"Arrrgh"); AActor* Me = Cast<AActor>(this); if (Me) { Me->Destroy(); } }
sunithshetty/Unreal-Engine-4-Scripting-with-CPlusPlus-Cookbook
Chapter07/Source/Chapter7/Killable.cpp
C++
mit
245
import lazy from "lazy.js"; import { EventEmitter } from "events"; import _ from "lodash"; import AppDispatcher from "../AppDispatcher"; import GameStatus from "../constants/GameStatus"; import CompsEvents from "../events/CompsEvents"; import GamesEvents from "../events/GamesEvents"; class GameStore { constructor() { this.info = { status: GameStatus.NOT_STARTED }; this.player = null; this.lastToken = null; this.states = []; } getInfo() { return this.info; } getPlayer() { return this.player; } getLastToken() { return this.lastToken; } getStatus() { return this.info.status; } getState(i) { return this.states[i]; } getCurrentState() { return this.states[this.states.length - 1]; } getAllStates() { return this.states; } getStateCount() { return this.states.length; } _setInfo(info) { this.info = info; } _setPlayer(player) { this.player = player; } _setLastToken(playerToken) { this.lastToken = playerToken; } _setStatus(status) { this.info.status = status; } _pushState(state) { this.states.push(state); } _setAllStates(states) { this.states = states; } } const GamesStore = lazy(EventEmitter.prototype).extend({ games: {}, getGame: function (gameHref, gameId) { let games = this.games[gameHref] = this.games[gameHref] || {}; return games[gameId] = games[gameId] || new GameStore(); }, getAllGames: function (gameHref) { let forHref = this.games[gameHref] = this.games[gameHref] || {}; return _.values(forHref); } }).value(); AppDispatcher.register(function (action) { const { actionType, gameHref, gameId, data, error } = action; let store = gameId ? GamesStore.getGame(gameHref, gameId) : null; switch (actionType) { case GamesEvents.GAME_INFO: store._setInfo(action.game); GamesStore.emit(actionType, gameHref, gameId); break; case GamesEvents.GAME_INFO_ERROR: GamesStore.emit(actionType, gameHref, gameId, error); break; case GamesEvents.GAMES_LIST: action.games.forEach(info => { GamesStore.getGame(gameHref, info.gameId)._setInfo(info); GamesStore.emit(GamesEvents.GAME_INFO, gameHref, info.gameId); }); GamesStore.emit(actionType, gameHref); break; case GamesEvents.GAMES_LIST_ERROR: GamesStore.emit(actionType, gameHref, error); break; case CompsEvents.COMP_GAMES: action.games.forEach(info => { GamesStore.getGame(gameHref, info.gameId)._setInfo(info); GamesStore.emit(GamesEvents.GAME_INFO, gameHref, info.gameId); }); break; case GamesEvents.REGISTER_SUCCESS: store._setLastToken(data.playerToken); GamesStore.emit(actionType, gameHref, gameId, data.playerToken); break; case GamesEvents.REGISTER_ERROR: GamesStore.emit(actionType, gameHref, gameId, error); break; case GamesEvents.INFO: store._setPlayer(data.player); GamesStore.emit(actionType, gameHref, gameId); break; case GamesEvents.HISTORY: store._setAllStates( lazy(data).filter(e => e.eventType === "state").map(e => e.state).value()); break; case GamesEvents.START: case GamesEvents.STATE: store._setStatus(GameStatus.STARTED); store._pushState(data); GamesStore.emit(GamesEvents.NEW_STATE, gameHref, gameId); break; case GamesEvents.END: store._setStatus(GameStatus.ENDED); store._pushState(data); GamesStore.emit(GamesEvents.NEW_STATE, gameHref, gameId); break; case GamesEvents.CONNECTION_OPENED: store._setLastToken(action.playerToken); store._setAllStates([]); GamesStore.emit(actionType, gameHref, gameId); break; case GamesEvents.CONNECTION_CLOSED: case GamesEvents.CONNECTION_ERROR: GamesStore.emit(actionType, gameHref, gameId); break; } }); export default GamesStore;
ruippeixotog/botwars
client/js/stores/GamesStore.js
JavaScript
mit
3,892
<?php namespace Cygnite\Base\EventHandler; use Cygnite\Helpers\Inflector; /** * Class EventRegistrarTrait * * @package Cygnite\Base\EventHandler */ trait EventRegistrarTrait { /** * @return $this */ public function boot() { $this->registerEvents($this->listen); return $this; } /** * Get user defined application events from event middle wares * * @return array|bool */ public function getAppEvents() { $class = APP_NS.'\Middlewares\Events\Event'; if (property_exists($class, 'appEvents') && $class::$activateAppEvent == true) { return \Apps\Middlewares\Events\Event::$appEvents; } return false; } /** * We will register user defined events, it will trigger event when matches * * @param $events * @throws \RuntimeException */ public function registerEvents($events) { if (empty($events)) { throw new \RuntimeException(sprintf("Empty argument passed %s", __FUNCTION__)); } foreach ($events as $event => $namespace) { $parts = explode('@', $namespace); // attach all before and after event to handler $this->attach("$event.before", $parts[0].'@before'.ucfirst(Inflector::pathAction(end($parts)))) ->attach("$event", $parts[0].'@'.Inflector::pathAction(end($parts))) ->attach("$event.after", $parts[0].'@after'.ucfirst(Inflector::pathAction(end($parts)))); } } /** * Fire all events registered with EventHandler * * @param $event * @return $this */ public function fire($event) { $this->trigger("$event.before"); $this->trigger($event); $this->trigger("$event.after"); return $this; } }
sanjoydesk/cygniteframework
vendor/cygnite/framework/src/Cygnite/Base/EventHandler/EventRegistrarTrait.php
PHP
mit
1,849
/* * @(#)ChoiceResource.java 1.3 97/06/27 * * (C) Copyright Taligent, Inc. 1996 - All Rights Reserved * (C) Copyright IBM Corp. 1996 - All Rights Reserved * * Portions copyright (c) 1996 Sun Microsystems, Inc. All Rights Reserved. * * The original version of this source code and documentation is copyrighted * and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These * materials are provided under terms of a License Agreement between Taligent * and Sun. This technology is protected by multiple US and International * patents. This notice and attribution to Taligent may not be removed. * Taligent is a registered trademark of Taligent, Inc. * * Permission to use, copy, modify, and distribute this software * and its documentation for NON-COMMERCIAL purposes and without * fee is hereby granted provided that this copyright notice * appears in all copies. Please refer to the file "copyright.html" * for further important copyright and licensing information. * * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. * */ import java.util.ListResourceBundle; public class ChoiceResource extends ListResourceBundle { public Object[][] getContents() { return contents; } static final Object[][] contents = { // LOCALIZE THIS {"patternText", "The disk {1} contained \n" + " {0,choice, " + "0#no files|" + "1#one file|" + "1< {0,number,integer} files} \n" + " on {2,date}."} }; // END OF MATERIAL TO LOCALIZE };
pitpitman/GraduateWork
Java_tutorial/intl/datamgmt/demos-1dot1/ChoiceResource.java
Java
mit
1,916
Template.sort.helpers({ activeRouteClass: function(/* route names */) { // Man kann natürlich benannte Argumente an die Funktion übergeben, aber man kann auch eine beliebige Anzahl von anonymen Parametern mitgeben und abrufen indem man innerhalb der Funktion das Objekt arguments aufruft. var args = Array.prototype.slice.call(arguments, 0); args.pop(); // Im letzten Fall sollte man das Objekt arguments in ein herkömmliches JavaScript Array konvertieren und dann pop() darauf anwenden um den Hash loszuwerden, den Spacebars am Ende eingefügt hat. var active = _.any(args, function(name) { return Router.current() && Router.current().route.name === name }); return active && 'active'; // JavaScript Pattern boolean && string, bei dem false && myString false zurückgibt, aber true && myString gibt myString zurück } });
shiftux/discover_meteor
client/templates/includes/sort.js
JavaScript
mit
859
//ECS 60 Homework #2 //Christopher Bird //ID: 997337048 //Professor: Hao Chen //Kruskal's Implementation along with Sorting Algorithm //Main.cpp #include <string> #include <iostream> #include "spantree.h" using namespace std; int main() { spantree Spantree; Spantree.readInput(); //Spantree.testInput(); //Reads input and stores Spantree.sortInfo(); //Sorts each regions roads by length and creates ordered arrays with least -> most length pointers Spantree.buildTree(); //Builds each region using the lowest cost edges from each region Spantree.printOut(); //Prints each region in the output desired by Chen return 0; }
CKBird/Kruskals
Source/main.cpp
C++
mit
643
<?xml version="1.0" ?><!DOCTYPE TS><TS language="pt_PT" version="2.0"> <defaultcodec>UTF-8</defaultcodec> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About PioneerCoin</source> <translation>Sobre PioneerCoin</translation> </message> <message> <location line="+39"/> <source>&lt;b&gt;PioneerCoin&lt;/b&gt; version</source> <translation>Versão do &lt;b&gt;PioneerCoin&lt;/b&gt;</translation> </message> <message> <location line="+57"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source> <translation> Este é um programa experimental. Distribuído sob uma licença de software MIT/X11, por favor verifique o ficheiro anexo license.txt ou http://www.opensource.org/licenses/mit-license.php. Este produto inclui software desenvolvido pelo Projecto OpenSSL para uso no OpenSSL Toolkit (http://www.openssl.org/), software criptográfico escrito por Eric Young (eay@cryptsoft.com) e software UPnP escrito por Thomas Bernard.</translation> </message> <message> <location filename="../aboutdialog.cpp" line="+14"/> <source>Copyright</source> <translation>Copyright</translation> </message> <message> <location line="+0"/> <source>The PioneerCoin developers</source> <translation>Os programadores PioneerCoin</translation> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation>Livro de endereços</translation> </message> <message> <location line="+19"/> <source>Double-click to edit address or label</source> <translation>Clique duas vezes para editar o endereço ou o rótulo</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>Criar um novo endereço</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Copie o endereço selecionado para a área de transferência</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation>&amp;Novo Endereço</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+63"/> <source>These are your PioneerCoin 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>Estes são os seus endereços PioneerCoin para receber pagamentos. Poderá enviar um endereço diferente para cada remetente para poder identificar os pagamentos.</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>&amp;Copy Address</source> <translation>&amp;Copiar Endereço</translation> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation>Mostrar Código &amp;QR</translation> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a PioneerCoin address</source> <translation>Assine uma mensagem para provar que é dono de um endereço PioneerCoin</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>Assinar &amp;Mensagem</translation> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation>Apagar o endereço selecionado da lista</translation> </message> <message> <location line="+27"/> <source>Export the data in the current tab to a file</source> <translation>Exportar os dados no separador actual para um ficheiro</translation> </message> <message> <location line="+3"/> <source>&amp;Export</source> <translation>&amp;Exportar</translation> </message> <message> <location line="-44"/> <source>Verify a message to ensure it was signed with a specified PioneerCoin address</source> <translation>Verifique a mensagem para assegurar que foi assinada com o endereço PioneerCoin especificado</translation> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation>&amp;Verificar Mensagem</translation> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>E&amp;liminar</translation> </message> <message> <location filename="../addressbookpage.cpp" line="-5"/> <source>These are your PioneerCoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation>Estes são os seus endereços PioneerCoin para enviar pagamentos. Verifique sempre o valor e a morada de envio antes de enviar moedas.</translation> </message> <message> <location line="+13"/> <source>Copy &amp;Label</source> <translation>Copiar &amp;Rótulo</translation> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation>&amp;Editar</translation> </message> <message> <location line="+1"/> <source>Send &amp;Coins</source> <translation>Enviar &amp;Moedas</translation> </message> <message> <location line="+260"/> <source>Export Address Book Data</source> <translation>Exportar dados do Livro de Endereços</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Ficheiro separado por vírgulas (*.csv)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation>Erro ao exportar</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Não foi possível escrever para o ficheiro %1.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>Rótulo</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Endereço</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(Sem rótulo)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation>Diálogo de Frase-Passe</translation> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>Escreva a frase de segurança</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>Nova frase de segurança</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>Repita a nova frase de segurança</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>Escreva a nova frase de seguraça da sua carteira. &lt;br/&gt; Por favor, use uma frase de &lt;b&gt;10 ou mais caracteres aleatórios,&lt;/b&gt; ou &lt;b&gt;oito ou mais palavras&lt;/b&gt;.</translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>Encriptar carteira</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>A sua frase de segurança é necessária para desbloquear a carteira.</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>Desbloquear carteira</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>A sua frase de segurança é necessária para desencriptar a carteira.</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>Desencriptar carteira</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>Alterar frase de segurança</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Escreva a frase de segurança antiga seguida da nova para a carteira.</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>Confirmar encriptação da carteira</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 DARKCOINS&lt;/b&gt;!</source> <translation>Atenção: Se encriptar a carteira e perder a sua senha irá &lt;b&gt;PERDER TODOS OS SEUS DARKCOINS&lt;/b&gt;!</translation> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation>Tem a certeza que deseja encriptar a carteira?</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>IMPORTANTE: Qualquer cópia de segurança anterior da carteira deverá ser substituída com o novo, actualmente encriptado, ficheiro de carteira. Por razões de segurança, cópias de segurança não encriptadas efectuadas anteriormente do ficheiro da carteira tornar-se-ão inúteis assim que começar a usar a nova carteira encriptada.</translation> </message> <message> <location line="+100"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation>Atenção: A tecla Caps Lock está activa!</translation> </message> <message> <location line="-130"/> <location line="+58"/> <source>Wallet encrypted</source> <translation>Carteira encriptada</translation> </message> <message> <location line="-56"/> <source>PioneerCoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your PioneerCoins from being stolen by malware infecting your computer.</source> <translation>O cliente PioneerCoin irá agora ser fechado para terminar o processo de encriptação. Recorde que a encriptação da sua carteira não protegerá totalmente os seus PioneerCoins de serem roubados por programas maliciosos que infectem o seu computador.</translation> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+42"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>A encriptação da carteira falhou</translation> </message> <message> <location line="-54"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>A encriptação da carteira falhou devido a um erro interno. A carteira não foi encriptada.</translation> </message> <message> <location line="+7"/> <location line="+48"/> <source>The supplied passphrases do not match.</source> <translation>As frases de segurança fornecidas não coincidem.</translation> </message> <message> <location line="-37"/> <source>Wallet unlock failed</source> <translation>O desbloqueio da carteira falhou</translation> </message> <message> <location line="+1"/> <location line="+11"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>A frase de segurança introduzida para a desencriptação da carteira estava incorreta.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>A desencriptação da carteira falhou</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation>A frase de segurança da carteira foi alterada com êxito.</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+233"/> <source>Sign &amp;message...</source> <translation>Assinar &amp;mensagem...</translation> </message> <message> <location line="+280"/> <source>Synchronizing with network...</source> <translation>Sincronizando com a rede...</translation> </message> <message> <location line="-349"/> <source>&amp;Overview</source> <translation>Visã&amp;o geral</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation>Mostrar visão geral da carteira</translation> </message> <message> <location line="+20"/> <source>&amp;Transactions</source> <translation>&amp;Transações</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>Navegar pelo histórico de transações</translation> </message> <message> <location line="+7"/> <source>Edit the list of stored addresses and labels</source> <translation>Editar a lista de endereços e rótulos</translation> </message> <message> <location line="-14"/> <source>Show the list of addresses for receiving payments</source> <translation>Mostrar a lista de endereços para receber pagamentos</translation> </message> <message> <location line="+31"/> <source>E&amp;xit</source> <translation>Fec&amp;har</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>Sair da aplicação</translation> </message> <message> <location line="+4"/> <source>Show information about PioneerCoin</source> <translation>Mostrar informação sobre PioneerCoin</translation> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>Sobre &amp;Qt</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>Mostrar informação sobre Qt</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>&amp;Opções...</translation> </message> <message> <location line="+6"/> <source>&amp;Encrypt Wallet...</source> <translation>E&amp;ncriptar Carteira...</translation> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation>&amp;Guardar Carteira...</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>Mudar &amp;Palavra-passe...</translation> </message> <message> <location line="+285"/> <source>Importing blocks from disk...</source> <translation>Importando blocos do disco...</translation> </message> <message> <location line="+3"/> <source>Reindexing blocks on disk...</source> <translation>Reindexando blocos no disco...</translation> </message> <message> <location line="-347"/> <source>Send coins to a PioneerCoin address</source> <translation>Enviar moedas para um endereço PioneerCoin</translation> </message> <message> <location line="+49"/> <source>Modify configuration options for PioneerCoin</source> <translation>Modificar opções de configuração para PioneerCoin</translation> </message> <message> <location line="+9"/> <source>Backup wallet to another location</source> <translation>Faça uma cópia de segurança da carteira para outra localização</translation> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>Mudar a frase de segurança utilizada na encriptação da carteira</translation> </message> <message> <location line="+6"/> <source>&amp;Debug window</source> <translation>Janela de &amp;depuração</translation> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation>Abrir consola de diagnóstico e depuração</translation> </message> <message> <location line="-4"/> <source>&amp;Verify message...</source> <translation>&amp;Verificar mensagem...</translation> </message> <message> <location line="-165"/> <location line="+530"/> <source>PioneerCoin</source> <translation>PioneerCoin</translation> </message> <message> <location line="-530"/> <source>Wallet</source> <translation>Carteira</translation> </message> <message> <location line="+101"/> <source>&amp;Send</source> <translation>&amp;Enviar</translation> </message> <message> <location line="+7"/> <source>&amp;Receive</source> <translation>&amp;Receber</translation> </message> <message> <location line="+14"/> <source>&amp;Addresses</source> <translation>E&amp;ndereços</translation> </message> <message> <location line="+22"/> <source>&amp;About PioneerCoin</source> <translation>&amp;Sobre o PioneerCoin</translation> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation>Mo&amp;strar / Ocultar</translation> </message> <message> <location line="+1"/> <source>Show or hide the main Window</source> <translation>Mostrar ou esconder a Janela principal</translation> </message> <message> <location line="+3"/> <source>Encrypt the private keys that belong to your wallet</source> <translation>Encriptar as chaves privadas que pertencem à sua carteira</translation> </message> <message> <location line="+7"/> <source>Sign messages with your PioneerCoin addresses to prove you own them</source> <translation>Assine mensagens com os seus endereços PioneerCoin para provar que os controla</translation> </message> <message> <location line="+2"/> <source>Verify messages to ensure they were signed with specified PioneerCoin addresses</source> <translation>Verifique mensagens para assegurar que foram assinadas com o endereço PioneerCoin especificado</translation> </message> <message> <location line="+28"/> <source>&amp;File</source> <translation>&amp;Ficheiro</translation> </message> <message> <location line="+7"/> <source>&amp;Settings</source> <translation>Con&amp;figurações</translation> </message> <message> <location line="+6"/> <source>&amp;Help</source> <translation>A&amp;juda</translation> </message> <message> <location line="+9"/> <source>Tabs toolbar</source> <translation>Barra de separadores</translation> </message> <message> <location line="+17"/> <location line="+10"/> <source>[testnet]</source> <translation>[rede de testes]</translation> </message> <message> <location line="+47"/> <source>PioneerCoin client</source> <translation>Cliente PioneerCoin</translation> </message> <message numerus="yes"> <location line="+141"/> <source>%n active connection(s) to PioneerCoin network</source> <translation><numerusform>%n ligação ativa à rede PioneerCoin</numerusform><numerusform>%n ligações ativas à rede PioneerCoin</numerusform></translation> </message> <message> <location line="+22"/> <source>No block source available...</source> <translation>Nenhum bloco fonto disponível</translation> </message> <message> <location line="+12"/> <source>Processed %1 of %2 (estimated) blocks of transaction history.</source> <translation>Processados %1 dos %2 blocos (estimados) do histórico de transacções.</translation> </message> <message> <location line="+4"/> <source>Processed %1 blocks of transaction history.</source> <translation>Processados %1 blocos do histórico de transações.</translation> </message> <message numerus="yes"> <location line="+20"/> <source>%n hour(s)</source> <translation><numerusform>%n hora</numerusform><numerusform>%n horas</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation><numerusform>%n dia</numerusform><numerusform>%n dias</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n week(s)</source> <translation><numerusform>%n semana</numerusform><numerusform>%n semanas</numerusform></translation> </message> <message> <location line="+4"/> <source>%1 behind</source> <translation>%1 em atraso</translation> </message> <message> <location line="+14"/> <source>Last received block was generated %1 ago.</source> <translation>Último bloco recebido foi gerado há %1 atrás.</translation> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation>Transações posteriores poderão não ser imediatamente visíveis.</translation> </message> <message> <location line="+22"/> <source>Error</source> <translation>Erro</translation> </message> <message> <location line="+3"/> <source>Warning</source> <translation>Aviso</translation> </message> <message> <location line="+3"/> <source>Information</source> <translation>Informação</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>Esta transação tem um tamanho superior ao limite máximo. Poderá enviá-la pagando uma taxa de %1, que será entregue ao nó que processar a sua transação e ajudará a suportar a rede. Deseja pagar a taxa?</translation> </message> <message> <location line="-140"/> <source>Up to date</source> <translation>Atualizado</translation> </message> <message> <location line="+31"/> <source>Catching up...</source> <translation>Recuperando...</translation> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation>Confirme a taxa de transação</translation> </message> <message> <location line="+8"/> <source>Sent transaction</source> <translation>Transação enviada</translation> </message> <message> <location line="+0"/> <source>Incoming transaction</source> <translation>Transação recebida</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>Data: %1 Quantia: %2 Tipo: %3 Endereço: %4 </translation> </message> <message> <location line="+33"/> <location line="+23"/> <source>URI handling</source> <translation>Manuseamento URI</translation> </message> <message> <location line="-23"/> <location line="+23"/> <source>URI can not be parsed! This can be caused by an invalid PioneerCoin address or malformed URI parameters.</source> <translation>URI não foi lido correctamente! Isto pode ser causado por um endereço PioneerCoin inválido ou por parâmetros URI malformados.</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>A carteira está &lt;b&gt;encriptada&lt;/b&gt; e atualmente &lt;b&gt;desbloqueada&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>A carteira está &lt;b&gt;encriptada&lt;/b&gt; e atualmente &lt;b&gt;bloqueada&lt;/b&gt;</translation> </message> <message> <location filename="../bitcoin.cpp" line="+111"/> <source>A fatal error occurred. PioneerCoin can no longer continue safely and will quit.</source> <translation>Ocorreu um erro fatal. O PioneerCoin não pode continuar com segurança e irá fechar.</translation> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+104"/> <source>Network Alert</source> <translation>Alerta da Rede</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>Editar Endereço</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>&amp;Rótulo</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation>O rótulo a ser associado com esta entrada do livro de endereços</translation> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>E&amp;ndereço</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>O endereço associado com esta entrada do livro de endereços. Apenas poderá ser modificado para endereços de saída.</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation>Novo endereço de entrada</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>Novo endereço de saída</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>Editar endereço de entrada</translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>Editar endereço de saída</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>O endereço introduzido &quot;%1&quot; já se encontra no livro de endereços.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid PioneerCoin address.</source> <translation>O endereço introduzido &quot;%1&quot; não é um endereço PioneerCoin válido.</translation> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>Impossível desbloquear carteira.</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>Falha ao gerar nova chave.</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+424"/> <location line="+12"/> <source>PioneerCoin-Qt</source> <translation>PioneerCoin-Qt</translation> </message> <message> <location line="-12"/> <source>version</source> <translation>versão</translation> </message> <message> <location line="+2"/> <source>Usage:</source> <translation>Utilização:</translation> </message> <message> <location line="+1"/> <source>command-line options</source> <translation>opções da linha de comandos</translation> </message> <message> <location line="+4"/> <source>UI options</source> <translation>Opções de UI</translation> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation>Definir linguagem, por exemplo &quot;pt_PT&quot; (por defeito: linguagem do sistema)</translation> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation>Iniciar minimizado</translation> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation>Mostrar animação ao iniciar (por defeito: 1)</translation> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>Opções</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation>&amp;Principal</translation> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source> <translation>Taxa de transação opcional por KB que ajuda a assegurar que as suas transações serão processadas rapidamente. A maioria das transações tem 1 kB.</translation> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation>Pagar &amp;taxa de transação</translation> </message> <message> <location line="+31"/> <source>Automatically start PioneerCoin after logging in to the system.</source> <translation>Começar o PioneerCoin automaticamente ao iniciar sessão no sistema.</translation> </message> <message> <location line="+3"/> <source>&amp;Start PioneerCoin on system login</source> <translation>&amp;Começar o PioneerCoin ao iniciar o sistema</translation> </message> <message> <location line="+35"/> <source>Reset all client options to default.</source> <translation>Repôr todas as opções.</translation> </message> <message> <location line="+3"/> <source>&amp;Reset Options</source> <translation>&amp;Repôr Opções</translation> </message> <message> <location line="+13"/> <source>&amp;Network</source> <translation>&amp;Rede</translation> </message> <message> <location line="+6"/> <source>Automatically open the PioneerCoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation>Abrir a porta do cliente PioneerCoin automaticamente no seu router. Isto penas funciona se o seu router suportar UPnP e este se encontrar ligado.</translation> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation>Mapear porta usando &amp;UPnP</translation> </message> <message> <location line="+7"/> <source>Connect to the PioneerCoin network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation>Ligar à rede PioneerCoin através de um proxy SOCKS (p.ex. quando ligar através de Tor).</translation> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation>Ligar através de proxy SO&amp;CKS:</translation> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation>&amp;IP do proxy:</translation> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation>Endereço IP do proxy (p.ex. 127.0.0.1)</translation> </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 do proxy (p.ex. 9050)</translation> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation>&amp;Versão SOCKS:</translation> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation>Versão do proxy SOCKS (p.ex. 5)</translation> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation>&amp;Janela</translation> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation>Apenas mostrar o ícone da bandeja após minimizar a janela.</translation> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>&amp;Minimizar para a bandeja e não para a barra de ferramentas</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>Minimize ao invés de sair da aplicação quando a janela é fechada. Com esta opção selecionada, a aplicação apenas será encerrada quando escolher Sair da aplicação no menú.</translation> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation>M&amp;inimizar ao fechar</translation> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation>Vis&amp;ualização</translation> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation>&amp;Linguagem da interface de utilizador:</translation> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting PioneerCoin.</source> <translation>A linguagem da interface do utilizador pode ser definida aqui. Esta definição entrará em efeito após reiniciar o PioneerCoin.</translation> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation>&amp;Unidade a usar em quantias:</translation> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>Escolha a subdivisão unitária a ser mostrada por defeito na aplicação e ao enviar moedas.</translation> </message> <message> <location line="+9"/> <source>Whether to show PioneerCoin addresses in the transaction list or not.</source> <translation>Se mostrar, ou não, os endereços PioneerCoin na lista de transações.</translation> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation>Mostrar en&amp;dereços na lista de transações</translation> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation>&amp;OK</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>&amp;Cancelar</translation> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation>&amp;Aplicar</translation> </message> <message> <location filename="../optionsdialog.cpp" line="+53"/> <source>default</source> <translation>padrão</translation> </message> <message> <location line="+130"/> <source>Confirm options reset</source> <translation>Confirme a reposição de opções</translation> </message> <message> <location line="+1"/> <source>Some settings may require a client restart to take effect.</source> <translation>Algumas opções requerem o reinício do programa para funcionar.</translation> </message> <message> <location line="+0"/> <source>Do you want to proceed?</source> <translation>Deseja proceder?</translation> </message> <message> <location line="+42"/> <location line="+9"/> <source>Warning</source> <translation>Aviso</translation> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting PioneerCoin.</source> <translation>Esta opção entrará em efeito após reiniciar o PioneerCoin.</translation> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation>O endereço de proxy introduzido é inválido. </translation> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>Formulário</translation> </message> <message> <location line="+50"/> <location line="+166"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the PioneerCoin network after a connection is established, but this process has not completed yet.</source> <translation>A informação mostrada poderá estar desatualizada. A sua carteira sincroniza automaticamente com a rede PioneerCoin depois de estabelecer ligação, mas este processo ainda não está completo.</translation> </message> <message> <location line="-124"/> <source>Balance:</source> <translation>Saldo:</translation> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation>Não confirmado:</translation> </message> <message> <location line="-78"/> <source>Wallet</source> <translation>Carteira</translation> </message> <message> <location line="+107"/> <source>Immature:</source> <translation>Imaturo:</translation> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation>O saldo minado ainda não maturou</translation> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Transações recentes&lt;/b&gt;</translation> </message> <message> <location line="-101"/> <source>Your current balance</source> <translation>O seu saldo atual</translation> </message> <message> <location line="+29"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation>Total de transações ainda não confirmadas, e que não estão contabilizadas ainda no seu saldo actual</translation> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation>fora de sincronia</translation> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+107"/> <source>Cannot start PioneerCoin: click-to-pay handler</source> <translation>Impossível começar o modo clicar-para-pagar com PioneerCoin:</translation> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation>Diálogo de Código QR</translation> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation>Requisitar Pagamento</translation> </message> <message> <location line="+56"/> <source>Amount:</source> <translation>Quantia:</translation> </message> <message> <location line="-44"/> <source>Label:</source> <translation>Rótulo:</translation> </message> <message> <location line="+19"/> <source>Message:</source> <translation>Mensagem:</translation> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation>&amp;Salvar Como...</translation> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation>Erro ao codificar URI em Código QR.</translation> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation>A quantia introduzida é inválida, por favor verifique.</translation> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation>URI resultante muito longo. Tente reduzir o texto do rótulo / mensagem.</translation> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation>Guardar Código QR</translation> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation>Imagens PNG (*.png)</translation> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation>Nome do Cliente</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/D</translation> </message> <message> <location line="-217"/> <source>Client version</source> <translation>Versão do Cliente</translation> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation>&amp;Informação</translation> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation>Usando versão OpenSSL</translation> </message> <message> <location line="+49"/> <source>Startup time</source> <translation>Tempo de início</translation> </message> <message> <location line="+29"/> <source>Network</source> <translation>Rede</translation> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation>Número de ligações</translation> </message> <message> <location line="+23"/> <source>On testnet</source> <translation>Em rede de testes</translation> </message> <message> <location line="+23"/> <source>Block chain</source> <translation>Cadeia de blocos</translation> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation>Número actual de blocos</translation> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation>Total estimado de blocos</translation> </message> <message> <location line="+23"/> <source>Last block time</source> <translation>Tempo do último bloco</translation> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation>&amp;Abrir</translation> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation>Opções de linha de comandos</translation> </message> <message> <location line="+7"/> <source>Show the PioneerCoin-Qt help message to get a list with possible PioneerCoin command-line options.</source> <translation>Mostrar a mensagem de ajuda do PioneerCoin-Qt para obter uma lista com possíveis opções a usar na linha de comandos.</translation> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation>Mo&amp;strar</translation> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation>&amp;Consola</translation> </message> <message> <location line="-260"/> <source>Build date</source> <translation>Data de construção</translation> </message> <message> <location line="-104"/> <source>PioneerCoin - Debug window</source> <translation>PioneerCoin - Janela de depuração</translation> </message> <message> <location line="+25"/> <source>PioneerCoin Core</source> <translation>Núcleo PioneerCoin</translation> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation>Ficheiro de registo de depuração</translation> </message> <message> <location line="+7"/> <source>Open the PioneerCoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation>Abrir o ficheiro de registo de depuração da pasta de dados actual. Isto pode demorar alguns segundos para ficheiros de registo maiores.</translation> </message> <message> <location line="+102"/> <source>Clear console</source> <translation>Limpar consola</translation> </message> <message> <location filename="../rpcconsole.cpp" line="-30"/> <source>Welcome to the PioneerCoin RPC console.</source> <translation>Bem-vindo à consola RPC PioneerCoin.</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>Use as setas para cima e para baixo para navegar no histórico e &lt;b&gt;Ctrl-L&lt;/b&gt; para limpar o ecrã.</translation> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation>Digite &lt;b&gt;help&lt;/b&gt; para visualizar os comandos disponíveis.</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>Enviar Moedas</translation> </message> <message> <location line="+50"/> <source>Send to multiple recipients at once</source> <translation>Enviar para múltiplos destinatários de uma vez</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation>Adicionar &amp;Destinatário</translation> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation>Remover todos os campos da transação</translation> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation>&amp;Limpar Tudo</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>Confirme ação de envio</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>&amp;Enviar</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; para %2 (%3)</translation> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation>Confirme envio de moedas</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation>Tem a certeza que deseja enviar %1?</translation> </message> <message> <location line="+0"/> <source> and </source> <translation> e </translation> </message> <message> <location line="+23"/> <source>The recipient address is not valid, please recheck.</source> <translation>O endereço de destino não é válido, por favor verifique.</translation> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>A quantia a pagar deverá ser maior que 0.</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation>A quantia excede o seu saldo.</translation> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>O total excede o seu saldo quando a taxa de transação de %1 for incluída.</translation> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation>Endereço duplicado encontrado, apenas poderá enviar uma vez para cada endereço por cada operação de envio.</translation> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed!</source> <translation>Erro: A criação da transacção falhou! </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>Erro: A transação foi rejeitada. Isso poderá acontecer se algumas das moedas na sua carteira já tiverem sido gastas, se por exemplo tiver usado uma cópia do ficheiro wallet.dat e as moedas foram gastas na cópia mas não foram marcadas como gastas aqui.</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation>Formulário</translation> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>Qu&amp;antia:</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>&amp;Pagar A:</translation> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>O endereço para onde enviar o pagamento (p.ex. 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>Escreva um rótulo para este endereço para o adicionar ao seu livro de endereços</translation> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation>Rótu&amp;lo:</translation> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation>Escolher endereço do livro de endereços</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>Cole endereço da área de transferência</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>Remover este destinatário</translation> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a PioneerCoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Introduza um endereço PioneerCoin (p.ex. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation>Assinaturas - Assinar / Verificar uma Mensagem</translation> </message> <message> <location line="+13"/> <source>&amp;Sign Message</source> <translation>A&amp;ssinar Mensagem</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>Pode assinar mensagens com os seus endereços para provar que são seus. Tenha atenção ao assinar mensagens ambíguas, pois ataques de phishing podem tentar enganá-lo, de modo a assinar a sua identidade para os atacantes. Apenas assine declarações completamente detalhadas com as quais concorde.</translation> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>O endereço a utilizar para assinar a mensagem (p.ex. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="+10"/> <location line="+213"/> <source>Choose an address from the address book</source> <translation>Escolher endereço do livro de endereços</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>Cole endereço da área de transferência</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>Escreva aqui a mensagem que deseja assinar</translation> </message> <message> <location line="+7"/> <source>Signature</source> <translation>Assinatura</translation> </message> <message> <location line="+27"/> <source>Copy the current signature to the system clipboard</source> <translation>Copiar a assinatura actual para a área de transferência</translation> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this PioneerCoin address</source> <translation>Assine uma mensagem para provar que é dono deste endereço PioneerCoin</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>Assinar &amp;Mensagem</translation> </message> <message> <location line="+14"/> <source>Reset all sign message fields</source> <translation>Repôr todos os campos de assinatura de mensagem</translation> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation>Limpar &amp;Tudo</translation> </message> <message> <location line="-87"/> <source>&amp;Verify Message</source> <translation>&amp;Verificar Mensagem</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>Introduza o endereço de assinatura, mensagem (assegure-se de copiar quebras de linha, espaços, tabuladores, etc. exactamente) e assinatura abaixo para verificar a mensagem. Tenha atenção para não ler mais na assinatura do que o que estiver na mensagem assinada, para evitar ser enganado por um atacante que se encontre entre si e quem assinou a mensagem.</translation> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>O endereço utilizado para assinar a mensagem (p.ex. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified PioneerCoin address</source> <translation>Verifique a mensagem para assegurar que foi assinada com o endereço PioneerCoin especificado</translation> </message> <message> <location line="+3"/> <source>Verify &amp;Message</source> <translation>Verificar &amp;Mensagem</translation> </message> <message> <location line="+14"/> <source>Reset all verify message fields</source> <translation>Repôr todos os campos de verificação de mensagem</translation> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a PioneerCoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Introduza um endereço PioneerCoin (p.ex. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation>Clique &quot;Assinar mensagem&quot; para gerar a assinatura</translation> </message> <message> <location line="+3"/> <source>Enter PioneerCoin signature</source> <translation>Introduza assinatura PioneerCoin</translation> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation>O endereço introduzido é inválido. </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>Por favor verifique o endereço e tente de novo.</translation> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation>O endereço introduzido não refere a chave alguma.</translation> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation>O desbloqueio da carteira foi cancelado.</translation> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation>A chave privada para o endereço introduzido não está disponível.</translation> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation>Assinatura de mensagem falhou.</translation> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation>Mensagem assinada.</translation> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation>A assinatura não pôde ser descodificada.</translation> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation>Por favor verifique a assinatura e tente de novo.</translation> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation>A assinatura não condiz com o conteúdo da mensagem.</translation> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation>Verificação da mensagem falhou.</translation> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation>Mensagem verificada.</translation> </message> </context> <context> <name>SplashScreen</name> <message> <location filename="../splashscreen.cpp" line="+22"/> <source>The PioneerCoin developers</source> <translation>Os programadores PioneerCoin</translation> </message> <message> <location line="+1"/> <source>[testnet]</source> <translation>[rede de testes]</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+20"/> <source>Open until %1</source> <translation>Aberto até %1</translation> </message> <message> <location line="+6"/> <source>%1/offline</source> <translation>%1/desligado</translation> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/não confirmada</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 confirmações</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation>Estado</translation> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation><numerusform>, transmitida através de %n nó</numerusform><numerusform>, transmitida através de %n nós</numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation>Origem</translation> </message> <message> <location line="+0"/> <source>Generated</source> <translation>Gerado</translation> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation>De</translation> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation>Para</translation> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation>endereço próprio</translation> </message> <message> <location line="-2"/> <source>label</source> <translation>rótulo</translation> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation>Crédito</translation> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation><numerusform>matura daqui por %n bloco</numerusform><numerusform>matura daqui por %n blocos</numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation>não aceite</translation> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation>Débito</translation> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation>Taxa de transação</translation> </message> <message> <location line="+16"/> <source>Net amount</source> <translation>Valor líquido</translation> </message> <message> <location line="+6"/> <source>Message</source> <translation>Mensagem</translation> </message> <message> <location line="+2"/> <source>Comment</source> <translation>Comentário</translation> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation>ID da Transação</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>Moedas geradas deverão maturar por 120 blocos antes de poderem ser gastas. Quando gerou este bloco, ele foi transmitido para a rede para ser incluído na cadeia de blocos. Se a inclusão na cadeia de blocos falhar, irá mudar o estado para &quot;não aceite&quot; e as moedas não poderão ser gastas. Isto poderá acontecer ocasionalmente se outro nó da rede gerar um bloco a poucos segundos de diferença do seu.</translation> </message> <message> <location line="+7"/> <source>Debug information</source> <translation>Informação de depuração</translation> </message> <message> <location line="+8"/> <source>Transaction</source> <translation>Transação</translation> </message> <message> <location line="+3"/> <source>Inputs</source> <translation>Entradas</translation> </message> <message> <location line="+23"/> <source>Amount</source> <translation>Quantia</translation> </message> <message> <location line="+1"/> <source>true</source> <translation>verdadeiro</translation> </message> <message> <location line="+0"/> <source>false</source> <translation>falso</translation> </message> <message> <location line="-209"/> <source>, has not been successfully broadcast yet</source> <translation>, ainda não foi transmitida com sucesso</translation> </message> <message numerus="yes"> <location line="-35"/> <source>Open for %n more block(s)</source> <translation><numerusform>Aberta por mais %n bloco</numerusform><numerusform>Aberta por mais %n blocos</numerusform></translation> </message> <message> <location line="+70"/> <source>unknown</source> <translation>desconhecido</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>Detalhes da transação</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>Esta janela mostra uma descrição detalhada da transação</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+225"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>Tipo</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Endereço</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>Quantia</translation> </message> <message numerus="yes"> <location line="+57"/> <source>Open for %n more block(s)</source> <translation><numerusform>Aberta por mais %n bloco</numerusform><numerusform>Aberta por mais %n blocos</numerusform></translation> </message> <message> <location line="+3"/> <source>Open until %1</source> <translation>Aberto até %1</translation> </message> <message> <location line="+3"/> <source>Offline (%1 confirmations)</source> <translation>Desligado (%1 confirmação)</translation> </message> <message> <location line="+3"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation>Não confirmada (%1 de %2 confirmações)</translation> </message> <message> <location line="+3"/> <source>Confirmed (%1 confirmations)</source> <translation>Confirmada (%1 confirmação)</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>Saldo minado ficará disponível quando maturar, daqui por %n bloco</numerusform><numerusform>Saldo minado ficará disponível quando maturar, daqui por %n blocos</numerusform></translation> </message> <message> <location line="+5"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>Este bloco não foi recebido por outros nós e provavelmente não será aceite pela rede!</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>Gerado mas não aceite</translation> </message> <message> <location line="+43"/> <source>Received with</source> <translation>Recebido com</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>Recebido de</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>Enviado para</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>Pagamento ao próprio</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>Minado</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>(n/d)</translation> </message> <message> <location line="+199"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Estado da transação. Pairar por cima deste campo para mostrar o número de confirmações.</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>Data e hora a que esta transação foi recebida.</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>Tipo de transação.</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>Endereço de destino da transação.</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>Quantia retirada ou adicionada ao saldo.</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+52"/> <location line="+16"/> <source>All</source> <translation>Todas</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>Hoje</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>Esta semana</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>Este mês</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>Mês passado</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>Este ano</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>Período...</translation> </message> <message> <location line="+11"/> <source>Received with</source> <translation>Recebida com</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>Enviada para</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>Para si</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>Minadas</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>Outras</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>Escreva endereço ou rótulo a procurar</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>Quantia mínima</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>Copiar endereço</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Copiar rótulo</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Copiar quantia</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation>Copiar ID da Transação</translation> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>Editar rótulo</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation>Mostrar detalhes da transação</translation> </message> <message> <location line="+139"/> <source>Export Transaction Data</source> <translation>Exportar Dados das Transações</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Ficheiro separado por vírgula (*.csv)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>Confirmada</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>Tipo</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>Rótulo</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>Endereço</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>Quantia</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>ID</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation>Erro ao exportar</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Impossível escrever para o ficheiro %1.</translation> </message> <message> <location line="+100"/> <source>Range:</source> <translation>Período:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>até</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+193"/> <source>Send Coins</source> <translation>Enviar Moedas</translation> </message> </context> <context> <name>WalletView</name> <message> <location filename="../walletview.cpp" line="+42"/> <source>&amp;Export</source> <translation>&amp;Exportar</translation> </message> <message> <location line="+1"/> <source>Export the data in the current tab to a file</source> <translation>Exportar os dados no separador actual para um ficheiro</translation> </message> <message> <location line="+193"/> <source>Backup Wallet</source> <translation>Cópia de Segurança da Carteira</translation> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation>Dados da Carteira (*.dat)</translation> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation>Cópia de Segurança Falhou</translation> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation>Ocorreu um erro ao tentar guardar os dados da carteira na nova localização.</translation> </message> <message> <location line="+4"/> <source>Backup Successful</source> <translation>Cópia de Segurança Bem Sucedida</translation> </message> <message> <location line="+0"/> <source>The wallet data was successfully saved to the new location.</source> <translation>Os dados da carteira foram salvos com sucesso numa nova localização.</translation> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+94"/> <source>PioneerCoin version</source> <translation>Versão PioneerCoin</translation> </message> <message> <location line="+102"/> <source>Usage:</source> <translation>Utilização:</translation> </message> <message> <location line="-29"/> <source>Send command to -server or PioneerCoind</source> <translation>Enviar comando para -server ou PioneerCoind</translation> </message> <message> <location line="-23"/> <source>List commands</source> <translation>Listar comandos</translation> </message> <message> <location line="-12"/> <source>Get help for a command</source> <translation>Obter ajuda para um comando</translation> </message> <message> <location line="+24"/> <source>Options:</source> <translation>Opções:</translation> </message> <message> <location line="+24"/> <source>Specify configuration file (default: PioneerCoin.conf)</source> <translation>Especificar ficheiro de configuração (por defeito: PioneerCoin.conf)</translation> </message> <message> <location line="+3"/> <source>Specify pid file (default: PioneerCoind.pid)</source> <translation>Especificar ficheiro pid (por defeito: PioneerCoind.pid)</translation> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>Especificar pasta de dados</translation> </message> <message> <location line="-9"/> <source>Set database cache size in megabytes (default: 25)</source> <translation>Definir o tamanho da cache de base de dados em megabytes (por defeito: 25)</translation> </message> <message> <location line="-28"/> <source>Listen for connections on &lt;port&gt; (default: 9333 or testnet: 19333)</source> <translation>Escute por ligações em &lt;port&gt; (por defeito: 9333 ou testnet: 19333)</translation> </message> <message> <location line="+5"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>Manter no máximo &lt;n&gt; ligações a outros nós da rede (por defeito: 125)</translation> </message> <message> <location line="-48"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation>Ligar a um nó para recuperar endereços de pares, e desligar</translation> </message> <message> <location line="+82"/> <source>Specify your own public address</source> <translation>Especifique o seu endereço público</translation> </message> <message> <location line="+3"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>Tolerância para desligar nós mal-formados (por defeito: 100)</translation> </message> <message> <location line="-134"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>Número de segundos a impedir que nós mal-formados se liguem de novo (por defeito: 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>Ocorreu um erro ao definir a porta %u do serviço RPC a escutar em IPv4: %s</translation> </message> <message> <location line="+27"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 9332 or testnet: 19332)</source> <translation>Escutar por ligações JSON-RPC em &lt;port&gt; (por defeito: 9332 ou rede de testes: 19332)</translation> </message> <message> <location line="+37"/> <source>Accept command line and JSON-RPC commands</source> <translation>Aceitar comandos da consola e JSON-RPC</translation> </message> <message> <location line="+76"/> <source>Run in the background as a daemon and accept commands</source> <translation>Correr o processo como um daemon e aceitar comandos</translation> </message> <message> <location line="+37"/> <source>Use the test network</source> <translation>Utilizar a rede de testes - testnet</translation> </message> <message> <location line="-112"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation>Aceitar ligações externas (padrão: 1 sem -proxy ou -connect)</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=PioneerCoinrpc 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;PioneerCoin Alert&quot; admin@foo.com </source> <translation>%s, deverá definir rpcpassword no ficheiro de configuração : %s É recomendado que use a seguinte palavra-passe aleatória: rpcuser=PioneerCoinrpc rpcpassword=%s (não precisa recordar esta palavra-passe) O nome de utilizador e password NÃO DEVEM ser iguais. Se o ficheiro não existir, crie-o com permissões de leitura apenas para o dono. Também é recomendado definir alertnotify para que seja alertado sobre problemas; por exemplo: alertnotify=echo %%s | mail -s &quot;Alerta PioneerCoin&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>Ocorreu um erro ao definir a porta %u do serviço RPC a escutar em IPv6, a usar 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>Trancar a endereço específio e sempre escutar nele. Use a notação [anfitrião]:porta para IPv6</translation> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. PioneerCoin is probably already running.</source> <translation>Impossível trancar a pasta de dados %s. Provavelmente o PioneerCoin já está a ser executado.</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>Erro: A transação foi rejeitada. Isso poderá acontecer se algumas das moedas na sua carteira já tiverem sido gastas, se por exemplo tiver usado uma cópia do ficheiro wallet.dat e as moedas foram gastas na cópia mas não foram marcadas como gastas aqui.</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>Erro: Esta transação requer uma taxa de transação mínima de %s devido á sua quantia, complexidade, ou uso de fundos recebidos recentemente! </translation> </message> <message> <location line="+3"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation>Executar comando quando um alerta relevante for recebido (no comando, %s é substituído pela mensagem)</translation> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation>Executar comando quando uma das transações na carteira mudar (no comando, %s é substituído pelo ID da Transação)</translation> </message> <message> <location line="+11"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation>Definir tamanho máximo de transações de alta-/baixa-prioridade em bytes (por defeito: 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>Esta é uma versão de pré-lançamento - use à sua responsabilidade - não usar para minar ou aplicações comerciais</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>Atenção: -paytxfee está definida com um valor muito alto! Esta é a taxa que irá pagar se enviar uma transação.</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>Atenção: As transações mostradas poderão não estar correctas! Poderá ter que atualizar ou outros nós poderão ter que atualizar.</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 PioneerCoin will not work properly.</source> <translation>Atenção: Por favor verifique que a data e hora do seu computador estão correctas! Se o seu relógio não estiver certo o PioneerCoin não irá funcionar correctamente.</translation> </message> <message> <location line="+3"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation>Atenção: erro ao ler wallet.dat! Todas as chaves foram lidas correctamente, mas dados de transação ou do livro de endereços podem estar em falta ou incorrectos.</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>Atenção: wallet.dat corrupto, dados recuperados! wallet.dat original salvo como wallet.{timestamp}.bak em %s; se o seu saldo ou transações estiverem incorrectos deverá recuperar de uma cópia de segurança.</translation> </message> <message> <location line="+14"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation>Tentar recuperar chaves privadas de um wallet.dat corrupto</translation> </message> <message> <location line="+2"/> <source>Block creation options:</source> <translation>Opções de criação de bloco:</translation> </message> <message> <location line="+5"/> <source>Connect only to the specified node(s)</source> <translation>Apenas ligar ao(s) nó(s) especificado(s)</translation> </message> <message> <location line="+3"/> <source>Corrupted block database detected</source> <translation>Cadeia de blocos corrompida detectada</translation> </message> <message> <location line="+1"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation>Descobrir endereço IP próprio (padrão: 1 ao escutar e sem -externalip)</translation> </message> <message> <location line="+1"/> <source>Do you want to rebuild the block database now?</source> <translation>Deseja reconstruir agora a cadeia de blocos?</translation> </message> <message> <location line="+2"/> <source>Error initializing block database</source> <translation>Erro ao inicializar a cadeia de blocos</translation> </message> <message> <location line="+1"/> <source>Error initializing wallet database environment %s!</source> <translation>Erro ao inicializar o ambiente de base de dados da carteira %s!</translation> </message> <message> <location line="+1"/> <source>Error loading block database</source> <translation>Erro ao carregar cadeia de blocos</translation> </message> <message> <location line="+4"/> <source>Error opening block database</source> <translation>Erro ao abrir a cadeia de blocos</translation> </message> <message> <location line="+2"/> <source>Error: Disk space is low!</source> <translation>Erro: Pouco espaço em disco!</translation> </message> <message> <location line="+1"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation>Erro: Carteira bloqueada, incapaz de criar transação! </translation> </message> <message> <location line="+1"/> <source>Error: system error: </source> <translation>Erro: erro do sistema:</translation> </message> <message> <location line="+1"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation>Falhou a escutar em qualquer porta. Use -listen=0 se quer isto.</translation> </message> <message> <location line="+1"/> <source>Failed to read block info</source> <translation>Falha ao ler info do bloco</translation> </message> <message> <location line="+1"/> <source>Failed to read block</source> <translation>Falha ao ler bloco</translation> </message> <message> <location line="+1"/> <source>Failed to sync block index</source> <translation>Falha ao sincronizar índice do bloco</translation> </message> <message> <location line="+1"/> <source>Failed to write block index</source> <translation>Falha ao escrever índice do bloco</translation> </message> <message> <location line="+1"/> <source>Failed to write block info</source> <translation>Falha ao escrever info do bloco</translation> </message> <message> <location line="+1"/> <source>Failed to write block</source> <translation>Falha ao escrever o bloco</translation> </message> <message> <location line="+1"/> <source>Failed to write file info</source> <translation>Falha ao escrever info do ficheiro</translation> </message> <message> <location line="+1"/> <source>Failed to write to coin database</source> <translation>Falha ao escrever na base de dados de moedas</translation> </message> <message> <location line="+1"/> <source>Failed to write transaction index</source> <translation>Falha ao escrever índice de transações</translation> </message> <message> <location line="+1"/> <source>Failed to write undo data</source> <translation>Falha ao escrever histórico de modificações</translation> </message> <message> <location line="+2"/> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation>Encontrar pares usando procura DNS (por defeito: 1 excepto -connect)</translation> </message> <message> <location line="+1"/> <source>Generate coins (default: 0)</source> <translation>Gerar moedas (por defeito: 0)</translation> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation>Quantos blocos verificar ao começar (por defeito: 288, 0 = todos)</translation> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-4, default: 3)</source> <translation>Qual a minúcia na verificação de blocos (0-4, por defeito: 3)</translation> </message> <message> <location line="+19"/> <source>Not enough file descriptors available.</source> <translation>Descritores de ficheiros disponíveis são insuficientes.</translation> </message> <message> <location line="+8"/> <source>Rebuild block chain index from current blk000??.dat files</source> <translation>Reconstruir a cadeia de blocos dos ficheiros blk000??.dat actuais</translation> </message> <message> <location line="+16"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation>Defina o número de processos para servir as chamadas RPC (por defeito: 4)</translation> </message> <message> <location line="+26"/> <source>Verifying blocks...</source> <translation>Verificando blocos...</translation> </message> <message> <location line="+1"/> <source>Verifying wallet...</source> <translation>Verificando a carteira...</translation> </message> <message> <location line="-69"/> <source>Imports blocks from external blk000??.dat file</source> <translation>Importar blocos de um ficheiro blk000??.dat externo</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>Defina o número de processos de verificação (até 16, 0 = automático, &lt;0 = disponibiliza esse número de núcleos livres, por defeito: 0)</translation> </message> <message> <location line="+77"/> <source>Information</source> <translation>Informação</translation> </message> <message> <location line="+3"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation>Endereço -tor inválido: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Quantia inválida para -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Quantia inválida para -mintxfee=&lt;amount&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+8"/> <source>Maintain a full transaction index (default: 0)</source> <translation>Manter índice de transações completo (por defeito: 0)</translation> </message> <message> <location line="+2"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation>Armazenamento intermédio de recepção por ligação, &lt;n&gt;*1000 bytes (por defeito: 5000)</translation> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation>Armazenamento intermédio de envio por ligação, &lt;n&gt;*1000 bytes (por defeito: 1000)</translation> </message> <message> <location line="+2"/> <source>Only accept block chain matching built-in checkpoints (default: 1)</source> <translation>Apenas aceitar cadeia de blocos coincidente com marcas de verificação internas (por defeito: 1)</translation> </message> <message> <location line="+1"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation>Apenas ligar a nós na rede &lt;net&gt; (IPv4, IPv6 ou Tor)</translation> </message> <message> <location line="+2"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation>Produzir informação de depuração extra. Implica todas as outras opções -debug*</translation> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation>Produzir informação de depuração extraordinária</translation> </message> <message> <location line="+2"/> <source>Prepend debug output with timestamp</source> <translation>Preceder informação de depuração com selo temporal</translation> </message> <message> <location line="+5"/> <source>SSL options: (see the PioneerCoin Wiki for SSL setup instructions)</source> <translation>Opções SSL: (ver a Wiki PioneerCoin para instruções de configuração SSL)</translation> </message> <message> <location line="+1"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation>Selecione a versão do proxy socks a usar (4-5, padrão: 5)</translation> </message> <message> <location line="+3"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>Enviar informação de rastreio/depuração para a consola e não para o ficheiro debug.log</translation> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation>Enviar informação de rastreio/depuração para o depurador</translation> </message> <message> <location line="+5"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation>Definir tamanho máximo de um bloco em bytes (por defeito: 250000)</translation> </message> <message> <location line="+1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation>Definir tamanho minímo de um bloco em bytes (por defeito: 0)</translation> </message> <message> <location line="+2"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation>Encolher ficheiro debug.log ao iniciar o cliente (por defeito: 1 sem -debug definido)</translation> </message> <message> <location line="+1"/> <source>Signing transaction failed</source> <translation>Falhou assinatura da transação</translation> </message> <message> <location line="+2"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation>Especificar tempo de espera da ligação em millisegundos (por defeito: 5000)</translation> </message> <message> <location line="+4"/> <source>System error: </source> <translation>Erro de sistema:</translation> </message> <message> <location line="+4"/> <source>Transaction amount too small</source> <translation>Quantia da transação é muito baixa</translation> </message> <message> <location line="+1"/> <source>Transaction amounts must be positive</source> <translation>Quantia da transação deverá ser positiva</translation> </message> <message> <location line="+1"/> <source>Transaction too large</source> <translation>Transação grande demais</translation> </message> <message> <location line="+7"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation>Usar UPnP para mapear a porta de escuta (padrão: 0)</translation> </message> <message> <location line="+1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation>Usar UPnP para mapear a porta de escuta (padrão: 1 ao escutar)</translation> </message> <message> <location line="+1"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation>Utilizar proxy para aceder a serviços escondidos Tor (por defeito: mesmo que -proxy)</translation> </message> <message> <location line="+2"/> <source>Username for JSON-RPC connections</source> <translation>Nome de utilizador para ligações JSON-RPC</translation> </message> <message> <location line="+4"/> <source>Warning</source> <translation>Aviso</translation> </message> <message> <location line="+1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation>Atenção: Esta versão está obsoleta, é necessário actualizar!</translation> </message> <message> <location line="+1"/> <source>You need to rebuild the databases using -reindex to change -txindex</source> <translation>Necessita reconstruir as bases de dados usando -reindex para mudar -txindex</translation> </message> <message> <location line="+1"/> <source>wallet.dat corrupt, salvage failed</source> <translation>wallet.dat corrupta, recuperação falhou</translation> </message> <message> <location line="-50"/> <source>Password for JSON-RPC connections</source> <translation>Palavra-passe para ligações JSON-RPC</translation> </message> <message> <location line="-67"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>Permitir ligações JSON-RPC do endereço IP especificado</translation> </message> <message> <location line="+76"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>Enviar comandos para o nó a correr em &lt;ip&gt; (por defeito: 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>Executar comando quando mudar o melhor bloco (no comando, %s é substituído pela hash do bloco)</translation> </message> <message> <location line="+147"/> <source>Upgrade wallet to latest format</source> <translation>Atualize a carteira para o formato mais recente</translation> </message> <message> <location line="-21"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>Definir o tamanho da memória de chaves para &lt;n&gt; (por defeito: 100)</translation> </message> <message> <location line="-12"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>Reexaminar a cadeia de blocos para transações em falta na carteira</translation> </message> <message> <location line="+35"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>Usar OpenSSL (https) para ligações JSON-RPC</translation> </message> <message> <location line="-26"/> <source>Server certificate file (default: server.cert)</source> <translation>Ficheiro de certificado do servidor (por defeito: server.cert)</translation> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation>Chave privada do servidor (por defeito: server.pem)</translation> </message> <message> <location line="-151"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation>Cifras aceitáveis (por defeito: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation> </message> <message> <location line="+165"/> <source>This help message</source> <translation>Esta mensagem de ajuda</translation> </message> <message> <location line="+6"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation>Incapaz de vincular a %s neste computador (vínculo retornou erro %d, %s)</translation> </message> <message> <location line="-91"/> <source>Connect through socks proxy</source> <translation>Ligar através de um proxy socks</translation> </message> <message> <location line="-10"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>Permitir procuras DNS para -addnode, -seednode e -connect</translation> </message> <message> <location line="+55"/> <source>Loading addresses...</source> <translation>Carregar endereços...</translation> </message> <message> <location line="-35"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>Erro ao carregar wallet.dat: Carteira danificada</translation> </message> <message> <location line="+1"/> <source>Error loading wallet.dat: Wallet requires newer version of PioneerCoin</source> <translation>Erro ao carregar wallet.dat: A Carteira requer uma versão mais recente do PioneerCoin</translation> </message> <message> <location line="+93"/> <source>Wallet needed to be rewritten: restart PioneerCoin to complete</source> <translation>A Carteira precisou ser reescrita: reinicie o PioneerCoin para completar</translation> </message> <message> <location line="-95"/> <source>Error loading wallet.dat</source> <translation>Erro ao carregar wallet.dat</translation> </message> <message> <location line="+28"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation>Endereço -proxy inválido: &apos;%s&apos;</translation> </message> <message> <location line="+56"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation>Rede desconhecida especificada em -onlynet: &apos;%s&apos;</translation> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation>Versão desconhecida de proxy -socks requisitada: %i</translation> </message> <message> <location line="-96"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation>Não conseguiu resolver endereço -bind: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation>Não conseguiu resolver endereço -externalip: &apos;%s&apos;</translation> </message> <message> <location line="+44"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Quantia inválida para -paytxfee=&lt;amount&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount</source> <translation>Quantia inválida</translation> </message> <message> <location line="-6"/> <source>Insufficient funds</source> <translation>Fundos insuficientes</translation> </message> <message> <location line="+10"/> <source>Loading block index...</source> <translation>Carregar índice de blocos...</translation> </message> <message> <location line="-57"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>Adicione um nó ao qual se ligar e tentar manter a ligação aberta</translation> </message> <message> <location line="-25"/> <source>Unable to bind to %s on this computer. PioneerCoin is probably already running.</source> <translation>Incapaz de vincular à porta %s neste computador. Provavelmente o PioneerCoin já está a funcionar.</translation> </message> <message> <location line="+64"/> <source>Fee per KB to add to transactions you send</source> <translation>Taxa por KB a adicionar a transações enviadas</translation> </message> <message> <location line="+19"/> <source>Loading wallet...</source> <translation>Carregar carteira...</translation> </message> <message> <location line="-52"/> <source>Cannot downgrade wallet</source> <translation>Impossível mudar a carteira para uma versão anterior</translation> </message> <message> <location line="+3"/> <source>Cannot write default address</source> <translation>Impossível escrever endereço por defeito</translation> </message> <message> <location line="+64"/> <source>Rescanning...</source> <translation>Reexaminando...</translation> </message> <message> <location line="-57"/> <source>Done loading</source> <translation>Carregamento completo</translation> </message> <message> <location line="+82"/> <source>To use the %s option</source> <translation>Para usar a opção %s</translation> </message> <message> <location line="-74"/> <source>Error</source> <translation>Erro</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>Deverá definir rpcpassword=&lt;password&gt; no ficheiro de configuração: %s Se o ficheiro não existir, crie-o com permissões de leitura apenas para o dono.</translation> </message> </context> </TS>
pioneercrypto/PioneerCoin
src/qt/locale/bitcoin_pt_PT.ts
TypeScript
mit
119,141
<? class Welcome_model extends CI_Model{ function __construct(){ //Llamado al contructor del modelo parent::__construct(); } public function insertar_alumno($persona){ if ($this->db->insert('usu_al', $persona)) return true; else return false; } public function insertar_docente($persona){ if ($this->db->insert('usu_doc', $persona)) return true; else return false; } public function insertar_ramo($ramo){ if ($this->db->insert('ramos', $ramo)) return true; else return false; } public function get_areas(){ $query = $this->db->query('SELECT area_id, area_nom FROM areas'); if ($query->num_rows() > 0) { foreach($query->result() as $row) $arrDatos[htmlspecialchars($row->area_id, ENT_QUOTES)] = htmlspecialchars($row->area_nom, ENT_QUOTES); $query->free_result(); return $arrDatos; } } public function get_docente(){ $query = $this->db->query('SELECT doc_id, doc_nom FROM usu_doc'); if ($query->num_rows() > 0) { foreach($query->result() as $row) $arrDatos[htmlspecialchars($row->doc_id, ENT_QUOTES)] = htmlspecialchars($row->doc_nom, ENT_QUOTES); $query->free_result(); return $arrDatos; } } public function get_alumno(){ #$this->db->order_by('al_id DESC'); $query = $this->db->query('SELECT usu_al.al_id,usu_al.al_rt,usu_al.al_dv, usu_al.al_nom,usu_al.al_lastn, areas.area_nom, areas.area_id from areas inner join usu_al on areas.area_id = usu_al.areas_area_id'); return $query->result(); //} } public function get_doc(){ #$this->db->order_by('al_id DESC'); $query = $this->db->query('SELECT usu_doc.doc_id,usu_doc.doc_rt,usu_doc.doc_dv, usu_doc.doc_nom,usu_doc.doc_lastn, areas.area_nom, areas.area_id from areas inner join usu_doc on areas.area_id = usu_doc.areas_area_id '); return $query->result(); } public function eliminarAlu($id){ $this->db->where('al_id', $id); return $this->db->delete('usu_al'); } public function eliminarDoce($id){ $this->db->where('doc_id', $id); return $this->db->delete('usu_doc'); } public function validate_credentials($username, $password){ $this->db->where('log_rt', $username); $this->db->where('log_pass', $password); return $this->db->get('login')->row(); } }
GrinGraz/CIMVC
application/models/welcome_model.php
PHP
mit
2,333
package br.com.splessons.configuration; import java.util.Properties; import javax.sql.DataSource; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.orm.hibernate4.HibernateTransactionManager; import org.springframework.orm.hibernate4.LocalSessionFactoryBean; import org.springframework.transaction.annotation.EnableTransactionManagement; @Configuration @EnableTransactionManagement @ComponentScan({ "br.com.splessons.configuration" }) @PropertySource(value = { "classpath:application.properties" }) public class HibernateConfiguration { @Autowired private Environment environment; /*@Bean public static PropertySourcesPlaceholderConfigurer placeHolderConfigurer() { return new PropertySourcesPlaceholderConfigurer(); }*/ @Bean public LocalSessionFactoryBean sessionFactory() { LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); sessionFactory.setDataSource(dataSource()); sessionFactory.setPackagesToScan(new String[] { "br.com.splessons.model" }); sessionFactory.setHibernateProperties(hibernateProperties()); return sessionFactory; } @Bean public DataSource dataSource() { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName")); dataSource.setUrl(environment.getRequiredProperty("jdbc.url")); dataSource.setUsername(environment.getRequiredProperty("jdbc.username")); dataSource.setPassword(environment.getRequiredProperty("jdbc.password")); return dataSource; } private Properties hibernateProperties() { Properties properties = new Properties(); properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect")); properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql")); properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql")); properties.put("hibernate.hbm2ddl.auto", environment.getRequiredProperty("hibernate.hbm2ddl.auto")); return properties; } @Bean @Autowired public HibernateTransactionManager transactionManager(SessionFactory s) { HibernateTransactionManager txManager = new HibernateTransactionManager(); txManager.setSessionFactory(s); //txManager.setNestedTransactionAllowed(Boolean.TRUE); return txManager; } /*@Bean public PersistenceExceptionTranslationPostProcessor persistenceExceptionTranslationPostProcessor() { return new PersistenceExceptionTranslationPostProcessor(); }*/ }
marcellorego/SpringLabs
lesson4/src/main/java/br/com/splessons/configuration/HibernateConfiguration.java
Java
mit
3,156
declare const foo: string; export default foo;
typings/core
src/lib/__test__/fixtures/compile-export-default/index.d.ts
TypeScript
mit
48
#coding: utf-8 require 'test_helper' class CoreExtTest < ActiveSupport::TestCase test "str.encode_emoji" do assert_equal "test string", "test string".encode_emoji assert_equal "{{260e}}️", "☎️".encode_emoji assert_equal "{{1f4f1}}", "📱".encode_emoji end test "str.decode_emoji" do assert_equal "test string", "test string".decode_emoji assert_equal "☎️", "{{260e}}️".decode_emoji assert_equal "📱","{{1f4f1}}".decode_emoji end test "nil.encode_emoji" do assert_equal nil, nil.encode_emoji end test "nil.decode_emoji" do assert_equal nil, nil.decode_emoji end end
phonezawphyo/monkey_emoji
test/core_ext_test.rb
Ruby
mit
633
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.Text; namespace BetterWords { [ServiceContract] public interface IWordService { [OperationContract] string LoadData(); [OperationContract] string Correct(string word); } }
amughni/SpellChecker
BetterWords/BetterWords/IWordService.cs
C#
mit
369
# Requires require "Core/CDImage" # An implementation for CDImage For RHEL module PackerFiles module RHEL class CD < Core::CDImageImpl # Override method for getting the ISO name def get_iso_name_pattern 'rhel-server-@release@-@arch@-dvd.iso' end # Override method for getting checksums def get_check_sum_pattern '' end # Override method for checksum type def get_check_sum_type 'none' end # Override method for getting index URLs. This is a dummy URL # which is not accessible. def index_urls ['https://download.redhat.com/isos/@release@/@arch@/'] end end end end
anandvenkatanarayanan/PackerFiles
lib/PackerFiles/OS/RHEL/CD.rb
Ruby
mit
670
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::Compute::Mgmt::V2016_04_30_preview module Models # # The List Usages operation response. # class ListUsagesResult include MsRestAzure include MsRest::JSONable # @return [Array<Usage>] The list of compute resource usages. attr_accessor :value # @return [String] The URI to fetch the next page of compute resource # usage information. Call ListNext() with this to fetch the next page of # compute resource usage information. attr_accessor :next_link # return [Proc] with next page method call. attr_accessor :next_method # # Gets the rest of the items for the request, enabling auto-pagination. # # @return [Array<Usage>] operation results. # def get_all_items items = @value page = self while page.next_link != nil && !page.next_link.strip.empty? do page = page.get_next_page items.concat(page.value) end items end # # Gets the next page of results. # # @return [ListUsagesResult] with next page content. # def get_next_page response = @next_method.call(@next_link).value! unless @next_method.nil? unless response.nil? @next_link = response.body.next_link @value = response.body.value self end end # # Mapper for ListUsagesResult class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'ListUsagesResult', type: { name: 'Composite', class_name: 'ListUsagesResult', model_properties: { value: { client_side_validation: true, required: true, serialized_name: 'value', type: { name: 'Sequence', element: { client_side_validation: true, required: false, serialized_name: 'UsageElementType', type: { name: 'Composite', class_name: 'Usage' } } } }, next_link: { client_side_validation: true, required: false, serialized_name: 'nextLink', type: { name: 'String' } } } } } end end end end
Azure/azure-sdk-for-ruby
management/azure_mgmt_compute/lib/2016-04-30-preview/generated/azure_mgmt_compute/models/list_usages_result.rb
Ruby
mit
2,848
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::Network::Mgmt::V2016_09_01 module Models # # Information gained from troubleshooting of specified resource. # class TroubleshootingDetails include MsRestAzure # @return [String] The id of the get troubleshoot operation. attr_accessor :id # @return [String] Reason type of failure. attr_accessor :reason_type # @return [String] A summary of troubleshooting. attr_accessor :summary # @return [String] Details on troubleshooting results. attr_accessor :detail # @return [Array<TroubleshootingRecommendedActions>] List of recommended # actions. attr_accessor :recommended_actions # # Mapper for TroubleshootingDetails class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'TroubleshootingDetails', type: { name: 'Composite', class_name: 'TroubleshootingDetails', model_properties: { id: { client_side_validation: true, required: false, serialized_name: 'id', type: { name: 'String' } }, reason_type: { client_side_validation: true, required: false, serialized_name: 'reasonType', type: { name: 'String' } }, summary: { client_side_validation: true, required: false, serialized_name: 'summary', type: { name: 'String' } }, detail: { client_side_validation: true, required: false, serialized_name: 'detail', type: { name: 'String' } }, recommended_actions: { client_side_validation: true, required: false, serialized_name: 'recommendedActions', type: { name: 'Sequence', element: { client_side_validation: true, required: false, serialized_name: 'TroubleshootingRecommendedActionsElementType', type: { name: 'Composite', class_name: 'TroubleshootingRecommendedActions' } } } } } } } end end end end
Azure/azure-sdk-for-ruby
management/azure_mgmt_network/lib/2016-09-01/generated/azure_mgmt_network/models/troubleshooting_details.rb
Ruby
mit
2,956
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::Network::Mgmt::V2019_02_01 module Models # # Application gateway backendhealth http settings. # class ApplicationGatewayBackendHealthServer include MsRestAzure # @return [String] IP address or FQDN of backend server. attr_accessor :address # @return [NetworkInterfaceIPConfiguration] Reference of IP configuration # of backend server. attr_accessor :ip_configuration # @return [ApplicationGatewayBackendHealthServerHealth] Health of backend # server. Possible values include: 'Unknown', 'Up', 'Down', 'Partial', # 'Draining' attr_accessor :health # @return [String] Health Probe Log. attr_accessor :health_probe_log # # Mapper for ApplicationGatewayBackendHealthServer class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'ApplicationGatewayBackendHealthServer', type: { name: 'Composite', class_name: 'ApplicationGatewayBackendHealthServer', model_properties: { address: { client_side_validation: true, required: false, serialized_name: 'address', type: { name: 'String' } }, ip_configuration: { client_side_validation: true, required: false, serialized_name: 'ipConfiguration', type: { name: 'Composite', class_name: 'NetworkInterfaceIPConfiguration' } }, health: { client_side_validation: true, required: false, serialized_name: 'health', type: { name: 'String' } }, health_probe_log: { client_side_validation: true, required: false, serialized_name: 'healthProbeLog', type: { name: 'String' } } } } } end end end end
Azure/azure-sdk-for-ruby
management/azure_mgmt_network/lib/2019-02-01/generated/azure_mgmt_network/models/application_gateway_backend_health_server.rb
Ruby
mit
2,482
<!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html;charset=UTF-8" /> <meta charset="utf-8" /> <title>Pages - Petugas Dashboard UI Kit</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" /> <link rel="apple-touch-icon" href="pages/ico/60.png"> <link rel="apple-touch-icon" sizes="76x76" href="pages/ico/76.png"> <link rel="apple-touch-icon" sizes="120x120" href="pages/ico/120.png"> <link rel="apple-touch-icon" sizes="152x152" href="pages/ico/152.png"> <link rel="icon" type="image/x-icon" href="favicon.ico" /> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-touch-fullscreen" content="yes"> <meta name="apple-mobile-web-app-status-bar-style" content="default"> <meta content="" name="description" /> <meta content="" name="author" /> <link href="<?php echo base_url(); ?>assets/plugins/pace/pace-theme-flash.css" rel="stylesheet" type="text/css" /> <link href="<?php echo base_url(); ?>assets/plugins/boostrapv3/css/bootstrap.min.css" rel="stylesheet" type="text/css" /> <link href="<?php echo base_url(); ?>assets/plugins/font-awesome/css/font-awesome.css" rel="stylesheet" type="text/css" /> <link href="<?php echo base_url(); ?>assets/plugins/jquery-scrollbar/jquery.scrollbar.css" rel="stylesheet" type="text/css" media="screen" /> <link href="<?php echo base_url(); ?>assets/plugins/bootstrap-select2/select2.css" rel="stylesheet" type="text/css" media="screen" /> <link href="<?php echo base_url(); ?>assets/plugins/switchery/css/switchery.min.css" rel="stylesheet" type="text/css" media="screen" /> <link href="<?php echo base_url(); ?>assets/plugins/nvd3/nv.d3.min.css" rel="stylesheet" type="text/css" media="screen" /> <link href="<?php echo base_url(); ?>assets/plugins/mapplic/css/mapplic.css" rel="stylesheet" type="text/css" /> <link href="<?php echo base_url(); ?>assets/plugins/rickshaw/rickshaw.min.css" rel="stylesheet" type="text/css" /> <link href="<?php echo base_url(); ?>assets/plugins/bootstrap-datepicker/css/datepicker3.css" rel="stylesheet" type="text/css" media="screen"> <link href="<?php echo base_url(); ?>assets/plugins/jquery-metrojs/MetroJs.css" rel="stylesheet" type="text/css" media="screen" /> <link href="<?php echo base_url(); ?>pages/css/pages-icons.css" rel="stylesheet" type="text/css"> <link class="main-stylesheet" href="<?php echo base_url(); ?>pages/css/pages.css" rel="stylesheet" type="text/css" /> <link href="<?php echo base_url(); ?>assets/plugins/bootstrap-daterangepicker/daterangepicker-bs3.css" rel="stylesheet" type="text/css" media="screen"> <!--[if lte IE 9]> <link href="pages/css/ie9.css" rel="stylesheet" type="text/css" /> <![endif]--> <!--[if lt IE 9]> <link href="assets/plugins/mapplic/css/mapplic-ie.css" rel="stylesheet" type="text/css" /> <![endif]--> <script src="<?php echo base_url(); ?>assets/plugins/pace/pace.min.js" type="text/javascript"></script> <script src="<?php echo base_url(); ?>assets/plugins/jquery/jquery-1.11.1.min.js" type="text/javascript"></script> <script src="<?php echo base_url(); ?>assets/plugins/modernizr.custom.js" type="text/javascript"></script> <script src="<?php echo base_url(); ?>assets/plugins/boostrapv3/js/bootstrap.min.js" type="text/javascript"></script> <script src="<?php echo base_url(); ?>assets/plugins/jquery/jquery-easy.js" type="text/javascript"></script> <script src="<?php echo base_url(); ?>assets/plugins/jquery-unveil/jquery.unveil.min.js" type="text/javascript"></script> <script src="<?php echo base_url(); ?>assets/plugins/jquery-bez/jquery.bez.min.js"></script> <script src="<?php echo base_url(); ?>assets/plugins/jquery-ios-list/jquery.ioslist.min.js" type="text/javascript"></script> <script src="<?php echo base_url(); ?>assets/plugins/jquery-actual/jquery.actual.min.js"></script> <script src="<?php echo base_url(); ?>assets/plugins/jquery-scrollbar/jquery.scrollbar.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/plugins/bootstrap-select2/select2.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/plugins/classie/classie.js"></script> <script src="<?php echo base_url(); ?>assets/plugins/switchery/js/switchery.min.js" type="text/javascript"></script> <script src="<?php echo base_url(); ?>assets/plugins/nvd3/lib/d3.v3.js" type="text/javascript"></script> <script src="<?php echo base_url(); ?>assets/plugins/nvd3/nv.d3.min.js" type="text/javascript"></script> <script src="<?php echo base_url(); ?>assets/plugins/nvd3/src/utils.js" type="text/javascript"></script> <script src="<?php echo base_url(); ?>assets/plugins/nvd3/src/tooltip.js" type="text/javascript"></script> <script src="<?php echo base_url(); ?>assets/plugins/nvd3/src/interactiveLayer.js" type="text/javascript"></script> <script src="<?php echo base_url(); ?>assets/plugins/nvd3/src/models/axis.js" type="text/javascript"></script> <script src="<?php echo base_url(); ?>assets/plugins/nvd3/src/models/line.js" type="text/javascript"></script> <script src="<?php echo base_url(); ?>assets/plugins/nvd3/src/models/lineWithFocusChart.js" type="text/javascript"></script> <script src="<?php echo base_url(); ?>assets/plugins/mapplic/js/hammer.js"></script> <script src="<?php echo base_url(); ?>assets/plugins/mapplic/js/jquery.mousewheel.js"></script> <script src="<?php echo base_url(); ?>assets/plugins/mapplic/js/mapplic.js"></script> <script src="<?php echo base_url(); ?>assets/plugins/jquery-validation/js/jquery.validate.min.js" type="text/javascript"></script> <!-- END VENDOR JS --> <!-- BEGIN CORE TEMPLATE JS --> <script src="<?php echo base_url(); ?>pages/js/pages.min.js"></script> <!-- END CORE TEMPLATE JS --> <!-- BEGIN PAGE LEVEL JS --> <!--<script src="<?php echo base_url(); ?>assets/js/dashboard.js" type="text/javascript"></script>--> <script src="<?php echo base_url(); ?>assets/js/scripts.js" type="text/javascript"></script> <!-- END PAGE LEVEL JS --> <script type="text/javascript"> window.onload = function() { // fix for windows 8 if (navigator.appVersion.indexOf("Windows NT 6.2") != -1) document.head.innerHTML += '<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>pages/css/windows.chrome.fix.css" />' } </script> </head> <body class="fixed-header dashboard "> <!-- BEGIN SIDEBPANEL--> <nav class="page-sidebar" data-pages="sidebar"> <!-- BEGIN SIDEBAR MENU TOP TRAY CONTENT--> <div class="sidebar-overlay-slide from-top" id="appMenu"> <div class="row"> <div class="col-xs-6 no-padding"> <a href="#" class="p-l-40"><img src="<?php echo base_url(); ?>assets/img/demo/social_app.svg" alt="socail"> </a> </div> <div class="col-xs-6 no-padding"> <a href="#" class="p-l-10"><img src="<?php echo base_url(); ?>assets/img/demo/email_app.svg" alt="socail"> </a> </div> </div> <div class="row"> <div class="col-xs-6 m-t-20 no-padding"> <a href="#" class="p-l-40"><img src="<?php echo base_url(); ?>assets/img/demo/calendar_app.svg" alt="socail"> </a> </div> <div class="col-xs-6 m-t-20 no-padding"> <a href="#" class="p-l-10"><img src="<?php echo base_url(); ?>assets/img/demo/add_more.svg" alt="socail"> </a> </div> </div> </div> <!-- END SIDEBAR MENU TOP TRAY CONTENT--> <!-- BEGIN SIDEBAR MENU HEADER--> <div class="sidebar-header"> <img src="assets/img/logo_white.png" alt="logo" class="brand" data-src="<?php echo base_url(); ?>assets/img/logo_white.png" data-src-retina="<?php echo base_url(); ?>assets/img/logo_white_2x.png" width="78" height="22"> <div class="sidebar-header-controls"> <!-- <button type="button" class="btn btn-xs sidebar-slide-toggle btn-link m-l-20" data-pages-toggle="#appMenu"><i class="fa fa-angle-down fs-16"></i> </button> --> <button type="button" class="btn btn-link visible-lg-inline" data-toggle-pin="sidebar"><i class="fa fs-12"></i> </button> </div> </div> <!-- END SIDEBAR MENU HEADER--> <!-- START SIDEBAR MENU --> <div class="sidebar-menu"> <!-- BEGIN SIDEBAR MENU ITEMS--> <ul class="menu-items"> <li class="m-t-30 open"> <a href="Pembayaran" class="detailed"> <span class="title">Masuk</span> </a> <span class="icon-thumbnail bg-success"><i class="fa fa-sign-in"></i></span> </li> <li class="m-t-30 open"> <a href="Registrasi" class="detailed"> <span class="title">Pendaftaran</span> </a> <span class="icon-thumbnail"><i class="pg-plus_circle"></i></span> </li> </ul> <div class="clearfix"></div> </div> <!-- END SIDEBAR MENU --> </nav>
Vancrew/IMK
application/views/template/header_umum.php
PHP
mit
9,330
define(function(require) { var _ = require('underscore'), d3 = require('d3'); function isTime(type) { return _.contains(['time', 'timestamp', 'date'], type); } function isNum(type) { return _.contains(['num', 'int4', 'int', 'int8', 'float8', 'float', 'bigint'], type); } function isStr(type) { return _.contains(['varchar', 'text', 'str'], type); } function debugMode() { try { return !$("#fake-type > input[type=checkbox]").get()[0].checked; } catch(e) { return false; } } function negateClause(SQL) { if (!SQL) return null; if ($("#selection-type > input[type=checkbox]").get()[0].checked) return SQL; return "not(" + SQL + ")"; } // points: [ { yalias:,..., xalias: } ] // ycols: [ { col, alias, expr } ] function getYDomain(points, ycols) { var yaliases = _.pluck(ycols, 'alias'), yss = _.map(yaliases, function(yalias) { return _.pluck(points, yalias) }), ydomain = [Infinity, -Infinity]; _.each(yss, function(ys) { ys = _.filter(ys, _.isFinite); if (ys.length) { ydomain[0] = Math.min(ydomain[0], d3.min(ys)); ydomain[1] = Math.max(ydomain[1], d3.max(ys)); } }); return ydomain; } // assume getx(point) and point.range contain x values function getXDomain(points, type, getx) { var xdomain = null; if (isStr(type)) { xdomain = {}; _.each(points, function(d) { if (d.range) { _.each(d.range, function(o) { xdomain[o] = 1; }); } xdomain[getx(d)] = 1 ; }); xdomain = _.keys(xdomain); return xdomain; } var diff = 1; var xvals = []; _.each(points, function(d) { if (d.range) xvals.push.apply(xvals, d.range); xvals.push(getx(d)); }); xvals = _.reject(xvals, _.isNull); if (isNum(type)) { xvals = _.filter(xvals, _.isFinite); xdomain = [ d3.min(xvals), d3.max(xvals) ]; diff = 1; if (xdomain[0] != xdomain[1]) diff = (xdomain[1] - xdomain[0]) * 0.05; xdomain[0] -= diff; xdomain[1] += diff; } else if (isTime(type)) { xvals = _.map(xvals, function(v) { return new Date(v); }); xdomain = [ d3.min(xvals), d3.max(xvals) ]; diff = 1000*60*60*24; // 1 day if (xdomain[0] != xdomain[1]) diff = (xdomain[1] - xdomain[0]) * 0.05; xdomain[0] = new Date(+xdomain[0] - diff); xdomain[1] = new Date(+xdomain[1] + diff); } //console.log([type, 'diff', diff, 'domain', JSON.stringify(xdomain)]); return xdomain; } function mergeDomain(oldd, newd, type) { var defaultd = [Infinity, -Infinity]; if (isStr(type)) defaultd = []; if (oldd == null) return newd; if (isStr(type)) return _.union(oldd, newd); var ret = _.clone(oldd); if (!_.isNull(newd[0]) && (_.isFinite(newd[0]) || isTime(newd[0]))) ret[0] = d3.min([ret[0], newd[0]]); if (!_.isNull(newd[1]) && (_.isFinite(newd[1]) || isTime(newd[1]))) ret[1] = d3.max([ret[1], newd[1]]); return ret; } function estNumXTicks(xaxis, type, w) { var xscales = xaxis.scale(); var ex = 40.0/5; var xticks = 10; while(xticks > 1) { if (isStr(type)) { var nchars = d3.sum(_.times( Math.min(xticks, xscales.domain().length), function(idx){return (""+xscales.domain()[idx]).length+.8}) ) } else { var fmt = xscales.tickFormat(); var fmtlen = function(s) {return fmt(s).length+.8;}; var nchars = d3.sum(xscales.ticks(xticks), fmtlen); } if (ex*nchars < w) break; xticks--; } xticks = Math.max(1, +xticks.toFixed()); return xticks; } function setAxisLabels(axis, type, nticks) { var scales = axis.scale(); axis.ticks(nticks).tickSize(0,0); if (isStr(type)) { var skip = scales.domain().length / nticks; var idx = 0; var previdx = null; var tickvals = []; while (idx < scales.domain().length) { if (previdx == null || Math.floor(idx) > previdx) { tickvals.push(scales.domain()[Math.floor(idx)]) } idx += skip; } axis.tickValues(tickvals); } return axis; } function toWhereClause(col, type, vals) { if (!vals || vals.length == 0) return null; var SQL = null; var re = new RegExp("'", "gi"); if (isStr(type)) { SQL = []; if (_.contains(vals, null)) { SQL.push(col + " is null"); } var nonnulls = _.reject(vals, _.isNull); if (nonnulls.length == 1) { var v = nonnulls[0]; if (_.isString(v)) v = "'" + v.replace(re, "\\'") + "'"; SQL.push(col + " = " + v); } else if (nonnulls.length > 1) { vals = _.map(nonnulls, function(v) { if (_.isString(v)) return "'" + v.replace(re, "\\'") + "'"; return v; }); SQL.push(col + " in ("+vals.join(', ')+")"); } if (SQL.length == 0) SQL = null; else if (SQL.length == 1) SQL = SQL[0]; else SQL = "("+SQL.join(' or ')+")"; } else { if (isTime(type)) { if (type == 'time') { var val2s = function(v) { // the values could have already been string encoded. if (_.isDate(v)) return "'" + (new Date(v)).toLocaleTimeString() + "'"; return v; }; } else { var val2s = function(v) { if(_.isDate(v)) return "'" + (new Date(v)).toISOString() + "'"; return v; }; } //vals = _.map(vals, function(v) { return new Date(v)}); } else { var val2s = function(v) { return +v }; } if (vals.length == 1) { SQL = col + " = " + val2s(vals[0]); } else { SQL = [ val2s(d3.min(vals)) + " <= " + col, col + " <= " + val2s(d3.max(vals)) ].join(' and '); } } return SQL; } return { isTime: isTime, isNum: isNum, isStr: isStr, estNumXTicks: estNumXTicks, setAxisLabels: setAxisLabels, toWhereClause: toWhereClause, negateClause: negateClause, getXDomain: getXDomain, getYDomain: getYDomain, mergeDomain: mergeDomain, debugMode: debugMode } })
sirrice/dbwipes
dbwipes/static/js/summary/util.js
JavaScript
mit
6,474
Package.describe({ name: 'angular-compilers', version: '0.4.0', summary: 'Rollup, AOT, SCSS, HTML and TypeScript compilers for Angular Meteor', git: 'https://github.com/Urigo/angular-meteor/tree/master/atmosphere-packages/angular-compilers', documentation: 'README.md' }); Package.registerBuildPlugin({ name: 'Angular Compilers', sources: [ 'plugin/register.js' ], use: [ // Uses an external packages to get the actual compilers 'ecmascript@0.10.5', 'angular-typescript-compiler@0.4.0', 'angular-html-compiler@0.4.0', 'angular-scss-compiler@0.4.0' ] }); Package.onUse(function (api) { api.versionsFrom('1.11'); // Required in order to register plugins api.use('isobuild:compiler-plugin@1.0.0'); });
Urigo/angular-meteor
atmosphere-packages/angular-compilers/package.js
JavaScript
mit
780
using CharacterGen.CharacterClasses; using CharacterGen.Domain.Tables; using CharacterGen.Races; using NUnit.Framework; namespace CharacterGen.Tests.Integration.Tables.Races.BaseRaces.Ages.Rolls { [TestFixture] public class IntuitiveAgeRollsTests : CollectionTests { protected override string tableName { get { return string.Format(TableNameConstants.Formattable.Collection.CLASSTYPEAgeRolls, CharacterClassConstants.TrainingTypes.Intuitive); } } [Test] public override void CollectionNames() { var baseRaceGroups = CollectionsMapper.Map(TableNameConstants.Set.Collection.BaseRaceGroups); var allBaseRaces = baseRaceGroups[GroupConstants.All]; AssertCollectionNames(allBaseRaces); } [TestCase(RaceConstants.BaseRaces.Aasimar, "1d6")] [TestCase(RaceConstants.BaseRaces.AquaticElf, "4d6")] [TestCase(RaceConstants.BaseRaces.Azer, "3d6")] [TestCase(RaceConstants.BaseRaces.BlueSlaad, "2d4")] [TestCase(RaceConstants.BaseRaces.Bugbear, "1d4")] [TestCase(RaceConstants.BaseRaces.Centaur, "1d6")] [TestCase(RaceConstants.BaseRaces.CloudGiant, "2d4")] [TestCase(RaceConstants.BaseRaces.DeathSlaad, "2d4")] [TestCase(RaceConstants.BaseRaces.DeepDwarf, "3d6")] [TestCase(RaceConstants.BaseRaces.DeepHalfling, "2d4")] [TestCase(RaceConstants.BaseRaces.Derro, "3d6")] [TestCase(RaceConstants.BaseRaces.Doppelganger, "1d4")] [TestCase(RaceConstants.BaseRaces.Drow, "4d6")] [TestCase(RaceConstants.BaseRaces.DuergarDwarf, "3d6")] [TestCase(RaceConstants.BaseRaces.FireGiant, "2d4")] [TestCase(RaceConstants.BaseRaces.ForestGnome, "4d6")] [TestCase(RaceConstants.BaseRaces.FrostGiant, "2d4")] [TestCase(RaceConstants.BaseRaces.Gargoyle, "1d4")] [TestCase(RaceConstants.BaseRaces.Githyanki, "2d4")] [TestCase(RaceConstants.BaseRaces.Githzerai, "2d4")] [TestCase(RaceConstants.BaseRaces.Gnoll, "1d4")] [TestCase(RaceConstants.BaseRaces.Goblin, "1d4")] [TestCase(RaceConstants.BaseRaces.GrayElf, "4d6")] [TestCase(RaceConstants.BaseRaces.GraySlaad, "2d4")] [TestCase(RaceConstants.BaseRaces.GreenSlaad, "2d4")] [TestCase(RaceConstants.BaseRaces.Grimlock, "1d4")] [TestCase(RaceConstants.BaseRaces.HalfElf, "1d6")] [TestCase(RaceConstants.BaseRaces.HalfOrc, "1d4")] [TestCase(RaceConstants.BaseRaces.Harpy, "1d3")] [TestCase(RaceConstants.BaseRaces.HighElf, "4d6")] [TestCase(RaceConstants.BaseRaces.HillDwarf, "3d6")] [TestCase(RaceConstants.BaseRaces.HillGiant, "2d4")] [TestCase(RaceConstants.BaseRaces.Hobgoblin, "1d4")] [TestCase(RaceConstants.BaseRaces.HoundArchon, "1d4")] [TestCase(RaceConstants.BaseRaces.Human, "1d4")] [TestCase(RaceConstants.BaseRaces.Janni, "1d4")] [TestCase(RaceConstants.BaseRaces.Kapoacinth, "1d4")] [TestCase(RaceConstants.BaseRaces.Kobold, "1d4")] [TestCase(RaceConstants.BaseRaces.KuoToa, "2d6")] [TestCase(RaceConstants.BaseRaces.LightfootHalfling, "2d4")] [TestCase(RaceConstants.BaseRaces.Lizardfolk, "1d3")] [TestCase(RaceConstants.BaseRaces.Locathah, "1d4")] [TestCase(RaceConstants.BaseRaces.Merfolk, "1d6")] [TestCase(RaceConstants.BaseRaces.Merrow, "2d6")] [TestCase(RaceConstants.BaseRaces.MindFlayer, "2d6")] [TestCase(RaceConstants.BaseRaces.Minotaur, "1d4")] [TestCase(RaceConstants.BaseRaces.MountainDwarf, "3d6")] [TestCase(RaceConstants.BaseRaces.Ogre, "2d6")] [TestCase(RaceConstants.BaseRaces.OgreMage, "2d6")] [TestCase(RaceConstants.BaseRaces.Orc, "1d4")] [TestCase(RaceConstants.BaseRaces.Pixie, "1d2-1")] [TestCase(RaceConstants.BaseRaces.Rakshasa, "1d4")] [TestCase(RaceConstants.BaseRaces.RedSlaad, "2d4")] [TestCase(RaceConstants.BaseRaces.RockGnome, "4d6")] [TestCase(RaceConstants.BaseRaces.Sahuagin, "1d4")] [TestCase(RaceConstants.BaseRaces.Satyr, "2d6")] [TestCase(RaceConstants.BaseRaces.Scorpionfolk, "1d4")] [TestCase(RaceConstants.BaseRaces.Scrag, "1d4")] [TestCase(RaceConstants.BaseRaces.StoneGiant, "2d4")] [TestCase(RaceConstants.BaseRaces.StormGiant, "2d4")] [TestCase(RaceConstants.BaseRaces.Svirfneblin, "4d6")] [TestCase(RaceConstants.BaseRaces.TallfellowHalfling, "2d4")] [TestCase(RaceConstants.BaseRaces.Tiefling, "1d6")] [TestCase(RaceConstants.BaseRaces.Troglodyte, "1d4")] [TestCase(RaceConstants.BaseRaces.Troll, "1d4")] [TestCase(RaceConstants.BaseRaces.WildElf, "4d6")] [TestCase(RaceConstants.BaseRaces.WoodElf, "4d6")] [TestCase(RaceConstants.BaseRaces.YuanTiAbomination, "1d4")] [TestCase(RaceConstants.BaseRaces.YuanTiHalfblood, "1d4")] [TestCase(RaceConstants.BaseRaces.YuanTiPureblood, "1d4")] public void IntuitiveAgeRoll(string name, string ageRoll) { DistinctCollection(name, ageRoll); } } }
DnDGen/CharacterGen
CharacterGen.Tests.Integration.Tables/Races/BaseRaces/Ages/Rolls/IntuitiveAgeRollsTests.cs
C#
mit
5,191
namespace WithFormat.DateTime { public interface IYearFormatter { DateTimeFormatBuilder WithOneDigit(); DateTimeFormatBuilder WithTwoDigits(); DateTimeFormatBuilder WithAtLeastThreeDigits(); DateTimeFormatBuilder WithFourDigits(); DateTimeFormatBuilder WithFiveDigits(); DateTimeFormatBuilder WithDigits(int digits); } }
TheCrow1213/WithFormat
WithFormat/DateTime/IYearFormatter.cs
C#
mit
394
<?php namespace Backend\Modules\Kwaliteitslabels\Ajax; use Backend\Core\Engine\Base\AjaxAction; use Backend\Modules\Kwaliteitslabels\Engine\Model as BackendKwaliteitslabelsModel; /** * Alters the sequence of Kwaliteitslabels articles * * @author Stijn Schets <stijn@schetss.be> */ class SequenceCategories extends AjaxAction { public function execute() { parent::execute(); // get parameters $newIdSequence = trim(\SpoonFilter::getPostValue('new_id_sequence', null, '', 'string')); // list id $ids = (array) explode(',', rtrim($newIdSequence, ',')); // loop id's and set new sequence foreach ($ids as $i => $id) { $item['id'] = $id; $item['sequence'] = $i + 1; // update sequence if (BackendKwaliteitslabelsModel::existsCategory($id)) { BackendKwaliteitslabelsModel::updateCategory($item); } } // success output $this->output(self::OK, null, 'sequence updated'); } }
Schetss/CarCor
src/Backend/Modules/Kwaliteitslabels/Ajax/SequenceCategories.php
PHP
mit
1,047
using Tweetinvi.Core.Controllers; using Tweetinvi.Core.Iterators; using Tweetinvi.Core.Web; using Tweetinvi.Models; using Tweetinvi.Models.DTO; using Tweetinvi.Parameters; namespace Tweetinvi.Controllers.Timeline { public class TimelineController : ITimelineController { private readonly ITimelineQueryExecutor _timelineQueryExecutor; private readonly IPageCursorIteratorFactories _pageCursorIteratorFactories; public TimelineController(ITimelineQueryExecutor timelineQueryExecutor, IPageCursorIteratorFactories pageCursorIteratorFactories) { _timelineQueryExecutor = timelineQueryExecutor; _pageCursorIteratorFactories = pageCursorIteratorFactories; } // Home Timeline public ITwitterPageIterator<ITwitterResult<ITweetDTO[]>, long?> GetHomeTimelineIterator(IGetHomeTimelineParameters parameters, ITwitterRequest request) { return _pageCursorIteratorFactories.Create(parameters, cursor => { var cursoredParameters = new GetHomeTimelineParameters(parameters) { MaxId = cursor }; return _timelineQueryExecutor.GetHomeTimelineAsync(cursoredParameters, new TwitterRequest(request)); }); } public ITwitterPageIterator<ITwitterResult<ITweetDTO[]>, long?> GetUserTimelineIterator(IGetUserTimelineParameters parameters, ITwitterRequest request) { return _pageCursorIteratorFactories.Create(parameters, cursor => { var cursoredParameters = new GetUserTimelineParameters(parameters) { MaxId = cursor }; return _timelineQueryExecutor.GetUserTimelineAsync(cursoredParameters, new TwitterRequest(request)); }); } public ITwitterPageIterator<ITwitterResult<ITweetDTO[]>, long?> GetMentionsTimelineIterator(IGetMentionsTimelineParameters parameters, ITwitterRequest request) { return _pageCursorIteratorFactories.Create(parameters, cursor => { var cursoredParameters = new GetMentionsTimelineParameters(parameters) { MaxId = cursor }; return _timelineQueryExecutor.GetMentionsTimelineAsync(cursoredParameters, new TwitterRequest(request)); }); } public ITwitterPageIterator<ITwitterResult<ITweetDTO[]>, long?> GetRetweetsOfMeTimelineIterator(IGetRetweetsOfMeTimelineParameters parameters, ITwitterRequest request) { return _pageCursorIteratorFactories.Create(parameters, cursor => { var cursoredParameters = new GetRetweetsOfMeTimelineParameters(parameters) { MaxId = cursor }; return _timelineQueryExecutor.GetRetweetsOfMeTimelineAsync(cursoredParameters, new TwitterRequest(request)); }); } } }
linvi/tweetinvi
src/Tweetinvi.Controllers/Timeline/TimelineController.cs
C#
mit
3,067
class DashboardController < ApplicationController respond_to :html def index @groups = Group.where(id: current_user.projects.pluck(:group_id)) @projects = current_user.projects_with_events @projects = @projects.page(params[:page]).per(20) @events = Event.in_projects(current_user.project_ids).limit(20).offset(params[:offset] || 0) @last_push = current_user.recent_push respond_to do |format| format.html format.js format.atom { render layout: false } end end # Get authored or assigned open merge requests def merge_requests @projects = current_user.projects.all @merge_requests = current_user.cared_merge_requests.recent.page(params[:page]).per(20) end # Get only assigned issues def issues @projects = current_user.projects.all @user = current_user @issues = current_user.assigned_issues.opened.recent.page(params[:page]).per(20) @issues = @issues.includes(:author, :project) respond_to do |format| format.html format.atom { render layout: false } end end end
robbkidd/gitlabhq
app/controllers/dashboard_controller.rb
Ruby
mit
1,079
#include <iostream> #include <vector> #include <string> #include <sstream> #include <set> #include <algorithm> //std::vector<std::string> parseCommand(std::string input); //std::vector<int> parseArray(std::string input); //void exchange(int index, std::vector<int> & numbers); //void printNumbersInArrayFormat(std::vector<int> & numbers); //void findMinMaxEvenOdd(std::vector<std::string> & commandParts,std::vector<int> & numbers); //void findFirstLastEvenOddNumbers(std::vector<std::string>& commandParts, std::vector<int> numbers); // std::vector<int> parseArray(std::string input) { std::vector<int> values; int n; std::stringstream stream(input); while (stream >> n) { values.push_back(n); } return values; } std::vector<std::string> parseCommand(std::string input) { std::vector<std::string> values; std::string n; std::stringstream stream(input); while (stream >> n) { values.push_back(n); } return values; } void printNumbersInArrayFormat(std::vector<int> & numbers) { std::cout << "["; int indexLastElement = numbers.size() - 1; int currentIndex = 0; for (std::vector<int>::iterator iterator = numbers.begin(); iterator != numbers.end(); iterator++, currentIndex++) { if (currentIndex == indexLastElement) { std::cout << *iterator; } else { std::cout << *iterator << ", "; } } std::cout << "]" << std::endl; } void findMinMaxEvenOdd(std::vector<std::string>& commandParts, std::vector<int>& numbers) { if (numbers.size() == 0) { std::cout << "No matches" << std::endl; } std::vector<int>::iterator iter = numbers.begin(); int indexOfMin = 0; int indexOfMax = 0; int currentMin = 10000; int currentMax = -1; bool isEven = commandParts[1] == "even"; int currentIndex = 0; for (; iter != numbers.end(); iter++, currentIndex++) { if (currentMin >= *iter) { if (isEven && *iter % 2 == 0) { currentMin = *iter; indexOfMin = currentIndex; } else if (!isEven && *iter % 2 == 1) { currentMin = *iter; indexOfMin = currentIndex; } } if (currentMax <= *iter) { if (isEven && *iter % 2 == 0) { currentMax = *iter; indexOfMax = currentIndex; } else if (!isEven && *iter % 2 == 1) { currentMax = *iter; indexOfMax = currentIndex; } } } if (commandParts[0] == "min") { if (currentMin == 10000) { std::cout << "No matches" << std::endl; } else { std::cout << indexOfMin << std::endl; } } else { if (currentMax == -1) { std::cout << "No matches" << std::endl; } else { std::cout << indexOfMax << std::endl; } } } void findFirstLastEvenOddNumbers(std::vector<std::string>& commandParts, std::vector<int> numbers) { std::vector<int> result; std::vector<int>::iterator begin; std::vector<int>::iterator end; bool isFirst = commandParts[0] == "first"; bool isEven = commandParts[2] == "even"; int count = stoi(commandParts[1]); if (numbers.size() < count) { std::cout << "Invalid count" << std::endl; return; } // wrong logic; if (isFirst) { begin = numbers.begin(); end = numbers.end(); } else { begin = numbers.end(); begin--; end = numbers.begin(); } for (; begin != end && numbers.size() > 1;) { if (count == result.size()) { break; } if (isEven && *begin % 2 == 0) { result.push_back(*begin); } else if (!isEven && *begin % 2 == 1) { result.push_back(*begin); } if (isFirst) { begin++; } else { begin--; if (count == result.size()) { break; } if (begin == end && !isEven && *begin % 2 == 1) { result.push_back(*begin); if (!isFirst) { std::reverse(result.begin(), result.end()); } printNumbersInArrayFormat(result); return; } } } if (!isFirst) { std::reverse(result.begin(), result.end()); } printNumbersInArrayFormat(result); } void exchange(int index, std::vector<int> & numbers) { if (index >= numbers.size()) { std::cout << "Invalid index" << std::endl; return; } if (index == numbers.size() - 1 && numbers.size() > 0) { return; } std::vector<int> newNumbers; for (int i = index + 1; i < numbers.size(); i++) { newNumbers.push_back(numbers[i]); } for (int i = 0; i <= index; i++) { newNumbers.push_back(numbers[i]); } numbers = newNumbers; } int main() { std::string input; std::getline(std::cin, input); std::vector<int> numbers = parseArray(input); while (true) { std::getline(std::cin, input); std::vector<std::string> commandParts = parseCommand(input); if (commandParts[0] == "end") { break; } else if (commandParts[0] == "exchange") { exchange(std::stoi(commandParts[1]), numbers); } else if (commandParts[0] == "min" || commandParts[0] == "max") { findMinMaxEvenOdd(commandParts, numbers); } else if (commandParts[0] == "first" || commandParts[0] == "last") { findFirstLastEvenOddNumbers(commandParts, numbers); } } printNumbersInArrayFormat(numbers); return 0; }
M-Yankov/CPlusPlus
10.ExamPreparation/ArrayManipulator11October2015/Source.cpp
C++
mit
6,155
using NUnit.Framework; namespace UsStateMapper.Tests.EndToEndTests { [TestFixture] public class UscgCodeInputTest { private StateMapper subject; [SetUp] public void SetUp() { subject = new StateMapper(); } [TestCase("HA", "Hawaii")] [TestCase("KA", "Kansas")] [TestCase("MC", "Michigan")] [TestCase("NB", "Nebraska")] [TestCase("WN", "Washington")] [TestCase("WS", "Wisconsin")] [TestCase("CM", "Northern Mariana Islands")] public void ToState_Matches_State_When_USCG_Codes_That_Dont_Conflict_With_USPS_Codes_Are_Supplied(string uscgCode, string expectedState) { var result = subject.ToState(uscgCode); Assert.That(result, Is.EqualTo(expectedState)); } } }
asciamanna/UsStateMapper
UsStateMapper.Tests/EndToEndTests/UscgCodeInputTest.cs
C#
mit
745
var $ = require('jquery'); var layout = module.exports = { init: function() { $('#toggle-sidebar').click(function(e) { e.preventDefault(); layout.sidebar(); }); $('#toggle-overlay').click(function(e) { e.preventDefault(); layout.overlay(); }); }, restore: function() { return this; }, overlay: function(b) { if( typeof b !== 'boolean' ) b = !$('body > .panel').hasClass('overlay'); if( b ) $('body > .panel').addClass('overlay'), $('#toggle-overlay').html('<i class="fa fa-compress"></i>'); else $('body > .panel').removeClass('overlay'), $('#toggle-overlay').html('<i class="fa fa-expand"></i>'); return this; }, sidebar: function(b) { if( typeof b !== 'boolean' ) b = !$('body > .panel').hasClass('sidebar-open'); if( b ) $('body > .panel').addClass('sidebar-open'); else $('body > .panel').removeClass('sidebar-open'); return this; }, fullsize: function(b) { if( typeof b !== 'boolean' ) b = !$('#page').hasClass('fullsize'); if( b ) $('#page').addClass('fullsize'); else $('#page').removeClass('fullsize'); return this; }, dark: function(b) { if( typeof b !== 'boolean' ) b = !$('#page').hasClass('dark'); if( b ) $('#page, header > .utilities').addClass('dark'); else $('#page, header > .utilities').removeClass('dark'); return this; }, gnb: { select: function(url) { $('.gnb > a').each(function() { var el = $(this); if( el.attr('href') === url ) el.addClass('active'); else el.removeClass('active'); }); return this; } } };
joje6/three-cats
www/js/layout.js
JavaScript
mit
1,624
// *********************************************************************** // Copyright (c) 2017 Charlie Poole, Rob Prouse // // 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. // *********************************************************************** #if PLATFORM_DETECTION using System; using System.Runtime.Serialization; namespace NUnit.Framework.Internal { /// <summary> /// InvalidPlatformException is thrown when the platform name supplied /// to a test is not recognized. /// </summary> [Serializable] class InvalidPlatformException : ArgumentException { /// <summary> /// Instantiates a new instance of the <see cref="InvalidPlatformException"/> class. /// </summary> public InvalidPlatformException() : base() { } /// <summary> /// Instantiates a new instance of the <see cref="InvalidPlatformException"/> class /// </summary> /// <param name="message">The message.</param> public InvalidPlatformException(string message) : base(message) { } /// <summary> /// Instantiates a new instance of the <see cref="InvalidPlatformException"/> class /// </summary> /// <param name="message">The message.</param> /// <param name="inner">The inner.</param> public InvalidPlatformException(string message, Exception inner) : base(message, inner) { } #if !NETSTANDARD1_6 /// <summary> /// Serialization constructor for the <see cref="InvalidPlatformException"/> class /// </summary> protected InvalidPlatformException(SerializationInfo info, StreamingContext context) : base(info, context) { } #endif } } #endif
jadarnel27/nunit
src/NUnitFramework/framework/Internal/InvalidPlatformException.cs
C#
mit
2,741
package com.nodlee.theogony.ui.adapter; import android.view.View; public interface ItemClickedListener { /** * 在单元格被点击的时候调用 * * @param position */ void onItemClicked(View view, int position); }
VernonLee/Theogony
app/src/main/java/com/nodlee/theogony/ui/adapter/ItemClickedListener.java
Java
mit
247
<?php /** * TOP API: taobao.media.file.delete request * * @author auto create * @since 1.0, 2014-09-13 16:51:05 */ class MediaFileDeleteRequest { /** * 接入多媒体平台的业务code 每个应用有一个特有的业务code **/ private $bizCode; /** * 文件ID字符串,可以一个也可以一组,用英文逗号间隔,如450,120,155 **/ private $fileIds; private $apiParas = array(); public function setBizCode($bizCode) { $this->bizCode = $bizCode; $this->apiParas["biz_code"] = $bizCode; } public function getBizCode() { return $this->bizCode; } public function setFileIds($fileIds) { $this->fileIds = $fileIds; $this->apiParas["file_ids"] = $fileIds; } public function getFileIds() { return $this->fileIds; } public function getApiMethodName() { return "taobao.media.file.delete"; } public function getApiParas() { return $this->apiParas; } public function check() { RequestCheckUtil::checkNotNull($this->bizCode,"bizCode"); RequestCheckUtil::checkNotNull($this->fileIds,"fileIds"); RequestCheckUtil::checkMaxListSize($this->fileIds,50,"fileIds"); } public function putOtherTextParam($key, $value) { $this->apiParas[$key] = $value; $this->$key = $value; } }
zhangbobell/mallshop
plugins/onekey/taobao/top/request/MediaFileDeleteRequest.php
PHP
mit
1,256
<div class="content"> <h2><?php echo $title;?></h2> <div class="panel panel-default"> <div class="panel-heading"> <b>The following is the list of various seed certification charges of Punjab State Certification Authorityu as applicable from Rabi-2004-05</b> </div> <div class="panel-body text-left"> <table class="table table-bordered"> <thead> <tr> <th class="text-center">S.No.</th> <th class="text-center">Name of the item</th> <th class="text-center">Rates(Rs.)</th> </tr> </thead> <tbody> <?php $sno = 1; ?> <tr> <td><?php echo $sno++;?></td> <td>Application Fee</td> <td>25.00 per grower per season</td> </tr> <tr> <td><?php echo $sno++;?></td> <td> Inspection Fee <ol style="list-style-type: upper-alpha"> <li>Self Pollinated Crops</li> <li>Cross Pollinated Crops / Often Cross Pollinated Crops</li> <li>Hybrids / Vegetables</li> </ol> </td> <td><br> 375 / hectare<br> 450 / hectare<br> 750 / hectare<br> </td> </tr> <tr> <td><?php echo $sno++;?></td> <td>Re-Inspection Fee</td> <td>As inspection fee</td> </tr> <tr> <td><?php echo $sno++;?></td> <td>Seed Processing Supervision Fee</td> <td> 5.00 per quintal <ol style="list-style-type: upper-alpha"> <li>3.00 per quintal at the time of sampling</li> <li>2.00 per quintal at the time of packing</li> </ol> </td> </tr> <tr> <td><?php echo $sno++;?></td> <td>Re-processing / Re-cleaning / Re-bagging etc.</td> <td>5.00 per quintal</td> </tr> <tr> <td><?php echo $sno++;?></td> <td>Sample Testing Fee</td> <td>25.00 per sample</td> </tr> <tr> <td><?php echo $sno++;?></td> <td>Grow-Out Test Fee</td> <td>200.00 per sample</td> </tr> <tr> <td><?php echo $sno++;?></td> <td>Validation Fee</td> <td> 8.00 per quintal plus cost of tag and seal <ol style="list-style-type: upper-alpha"> <li>3.00 per quintal at the time of sampling</li> <li>5.00 per quintal plus cos of tag and seal at the time of final validation</li> </ol> </td> </tr> <tr> <td><?php echo $sno++;?></td> <td> Tag Charges <ol style="list-style-type: upper-alpha"> <li>Certified Tag (blue color)</li> <li>Foundation Tag (white color)</li> </ol> </td> <td><br> 25.50 per tag<br> 4.00 per tag<br> </td> </tr> <tr> <td><?php echo $sno++;?></td> <td>Seal Charges</td> <td>0.20 per seal</td> </tr> <tr> <td><?php echo $sno++;?></td> <td>Regiestration of Processing Plant</td> <td>1000.00 per plant</td> </tr> <tr> <td><?php echo $sno++;?></td> <td>Renewal of Processing Plant</td> <td>500.00 per plant per year</td> </tr> <tr> <td><?php echo $sno++;?></td> <td colspan="2">The cost of tags for the seeds graded and cleared from the laboratory but not packed shall be recovered from the producing organization on per acre packing basis.</td> </tr> <tr> <td class="text-center" colspan="3"> NOTE - SERVICE TAX WILL BE CHARGED EXTRA </td> </tr> </tbody> </table> </div> </div> </div>
puneetarora2000/BiS-conformance-
application/views/front/fees.php
PHP
mit
3,364
package com.wt.studio.plugin.pagedesigner.gef.figure; import org.eclipse.draw2d.ColorConstants; import org.eclipse.draw2d.FrameBorder; import org.eclipse.draw2d.Graphics; import org.eclipse.draw2d.IFigure; import org.eclipse.draw2d.PositionConstants; import org.eclipse.draw2d.SchemeBorder; import org.eclipse.draw2d.TitleBarBorder; import org.eclipse.draw2d.geometry.Insets; import org.eclipse.draw2d.geometry.Rectangle; import org.eclipse.swt.graphics.Color; public class FormFrameBorder extends FrameBorder { protected void createBorders() { inner = new HorizontalBlockTitleBarBorder(); outer = new SchemeBorder(SCHEME_FRAME); } } class HorizontalBlockTitleBarBorder extends TitleBarBorder { Color orange = new Color(null, 211, 211, 211); private Insets padding = new Insets(2, 3, 2, 3); public void paint(IFigure figure, Graphics g, Insets insets) { tempRect.setBounds(getPaintRectangle(figure, insets)); Rectangle rec = tempRect; rec.height = Math.min(rec.height, getTextExtents(figure).height + padding.getHeight()); g.clipRect(rec); g.setBackgroundColor(orange); g.fillRectangle(rec); int x = rec.x + padding.left; int y = rec.y + padding.top; int textWidth = getTextExtents(figure).width; int freeSpace = rec.width - padding.getWidth() - textWidth; if (getTextAlignment() == PositionConstants.CENTER) freeSpace /= 2; if (getTextAlignment() != PositionConstants.LEFT) x += freeSpace; g.setFont(getFont(figure)); g.setForegroundColor(ColorConstants.black); g.drawString(getLabel(), x, y); } }
winture/wt-studio
com.wt.studio.plugin.modeldesigner/src/com/wt/studio/plugin/pagedesigner/gef/figure/FormFrameBorder.java
Java
mit
1,556
namespace Deldysoft.Foundation.CommandHandling { public interface ICommandExecuter { void Execute<T>(T command); } }
geekhubdk/geekhub
Deldysoft.Foundation/CommandHandling/ICommandExecuter.cs
C#
mit
139
require 'spec_helper' require 'rddd/authorization/rule' describe Rddd::Authorization::Rule do let(:action) { :foo } let(:block) { lambda { |user, params| true } } let(:authorize) do Rddd::Authorization::Rule.new( action, &block ) end describe 'should raise if rule block is invalid' do let(:block) { lambda { |user| true } } it { expect { authorize }.to raise_exception Rddd::Authorization::Rule::InvalidEvaluationBlock } end describe '#is_for?' do subject { authorize.is_for?(questioned_action) } context 'matching action' do let(:questioned_action) { :foo } it { should be_true } end context 'not matching action' do let(:questioned_action) { :bar } it { should be_false } end end describe '#can?' do let(:user) { stub('user, params') } let(:params) { stub('user, params') } subject { authorize.can?(user, params) } describe 'passing right params to block' do before do block.expects(:call).with(user, params).returns(false) end it { should be_false } end it 'should return true as lambda does' do should be_true end end end
petrjanda/rddd
spec/lib/authorization/rule_spec.rb
Ruby
mit
1,195
import os,sys #import ez_setup #ez_setup.use_setuptools() from setuptools import setup, find_packages import numpy from Cython.Build import cythonize # not compatible with distribute #from distutils.extension import Extension #from Cython.Distutils import build_ext version = '0.7.0' README = os.path.join(os.path.dirname(__file__), 'README') long_description = open(README).read() + '\n\n' classifiers = """\ Development Status :: 4 - Beta Environment :: Console Intended Audience :: Science/Research License :: OSI Approved :: MIT License Topic :: Scientific/Engineering :: Bio-Informatics Programming Language :: Python Operating System :: Unix """ entry_points = """ [console_scripts] seqview = seqtool.frontend.command:seqview get_genbank = seqtool.frontend.command:get_genbank geneview = seqtool.frontend.command:geneview tssview = seqtool.frontend.command:tssview primers = seqtool.frontend.command:primers sequencing = seqtool.frontend.command:sequencing seqtooldb = seqtool.db:seqdb_command abiview = seqtool.frontend.command:abiview convert_bs = seqtool.bowtie.convert_bs:main virtualpcr = seqtool.bowtie.virtualpcr:main primer = seqtool.nucleotide.primer:main probe = seqtool.nucleotide.primer:probe bsa_figure = seqtool.script.bsa_figure:main pdesign = seqtool.script.pdesign:main bisulfite = seqtool.script.bisulfite:main rpm = seqtool.script.cf:main translate = seqtool.script.translate:main server = seqtool.server.server:main """ setup( name='seqtool', version=version, description=("small scripts visualizing PCR products for molecular biology experimetnts."), classifiers = filter(None, classifiers.split("\n")), keywords='pcr biology bisulfite', author='mizuy', author_email='mizugy@gmail.com', url='http://github.com/mizuy/seqtool', license='MIT', packages=find_packages(), install_requires=['biopython','numpy', 'sqlalchemy', 'cython', 'appdirs', 'mysql-connector-python'], test_suite='nose.collector', ext_modules = cythonize('seqtool/seqtool/nucleotide/sw_c.pyx'), include_dirs = [numpy.get_include()], entry_points=entry_points )
mizuy/seqtool
setup.py
Python
mit
2,123
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Linq.Expressions; using System.Reflection; namespace Abc.Zebus.Routing { public class BindingKeyPredicateBuilder : IBindingKeyPredicateBuilder { private static readonly MethodInfo _toStringMethod = typeof(object).GetMethod("ToString"); private static readonly MethodInfo _toStringWithFormatMethod = typeof(IConvertible).GetMethod("ToString"); private readonly ConcurrentDictionary<Type, CacheItem> _cacheItems = new ConcurrentDictionary<Type, CacheItem>(); class CacheItem { public ParameterExpression ParameterExpression { get; set; } public IList<MethodCallExpression> MembersToStringExpressions { get; set; } } public Func<IMessage, bool> GetPredicate(Type messageType, BindingKey bindingKey) { if (bindingKey.IsEmpty) return _ => true; var cacheItem = GetOrCreateCacheItem(messageType); var count = Math.Min(cacheItem.MembersToStringExpressions.Count, bindingKey.PartCount); var subPredicates = new List<Expression>(); for (var index = 0; index < count; index++) { if (bindingKey.IsSharp(index)) break; if (bindingKey.IsStar(index)) continue; var part = bindingKey.GetPart(index); var memberToStringExpression = cacheItem.MembersToStringExpressions[index]; subPredicates.Add(Expression.MakeBinary(ExpressionType.Equal, memberToStringExpression, Expression.Constant(part))); } if (!subPredicates.Any()) return _ => true; var finalExpression = subPredicates.Aggregate((Expression)null, (final, exp) => final == null ? exp : Expression.AndAlso(final, exp)); return (Func<IMessage, bool>)Expression.Lambda(finalExpression, cacheItem.ParameterExpression).Compile(); } private CacheItem GetOrCreateCacheItem(Type messageType) { return _cacheItems.GetOrAdd(messageType, type => { var routingMembers = type.GetMembers(BindingFlags.Public | BindingFlags.Instance) .Select(x => new MemberExtendedInfo { Member = x, Attribute = x.GetCustomAttribute<RoutingPositionAttribute>(true) }) .Where(x => x.Attribute != null) .OrderBy(x => x.Attribute.Position) .ToList(); var parameterExpression = Expression.Parameter(typeof(IMessage), "m"); var castedMessage = Expression.Convert(parameterExpression, messageType); return new CacheItem { ParameterExpression = parameterExpression, MembersToStringExpressions = routingMembers.Select(x => GenerateMemberToStringExpression(castedMessage, x)).ToList() }; }); } private static MethodCallExpression GenerateMemberToStringExpression(Expression parameterExpression, MemberExtendedInfo memberExtendedInfo) { Func<Expression, Expression> memberAccessor; Type memberType; var memberInfo = memberExtendedInfo.Member; if (memberInfo.MemberType == MemberTypes.Property) { var propertyInfo = (PropertyInfo)memberInfo; memberAccessor = m => Expression.Property(m, propertyInfo); memberType = propertyInfo.PropertyType; } else if (memberInfo.MemberType == MemberTypes.Field) { var fieldInfo = (FieldInfo)memberInfo; memberAccessor = m => Expression.Field(m, fieldInfo); memberType = fieldInfo.FieldType; } else throw new InvalidOperationException("Cannot define routing position on a member other than a field or property"); var getMemberValue = typeof(IConvertible).IsAssignableFrom(memberType) && memberType != typeof(string) ? Expression.Call(memberAccessor(parameterExpression), _toStringWithFormatMethod, Expression.Constant(CultureInfo.InvariantCulture)) : Expression.Call(memberAccessor(parameterExpression), _toStringMethod); return getMemberValue; } } public class MemberExtendedInfo { public MemberInfo Member { get; set; } public RoutingPositionAttribute Attribute { get; set; } } }
biarne-a/Zebus
src/Abc.Zebus/Routing/BindingKeyPredicateBuilder.cs
C#
mit
4,768
var a = createElement("a"); attr(a, 'href', ""); function anchor(label, href) { var element = createElement(a); attr(element, "href", label); if (isString(label)) { text(element, label); } else { appendChild(element, label); } onclick(element, function (event) { if (/^\w+\:/.test(href)) return; event.preventDefault(); go(href); }); return element; }
yunxu1019/efront
coms/zimoli/anchor.js
JavaScript
mit
423
'use strict'; /** * Module Dependencies */ var config = require('../config/config'); var _ = require('lodash'); var Twit = require('twit'); var async = require('async'); var debug = require('debug')('skeleton'); // https://github.com/visionmedia/debug var graph = require('fbgraph'); var tumblr = require('tumblr.js'); var Github = require('github-api'); var stripe = require('stripe')(config.stripe.key); var twilio = require('twilio')(config.twilio.sid, config.twilio.token); var paypal = require('paypal-rest-sdk'); var cheerio = require('cheerio'); // https://github.com/cheeriojs/cheerio var request = require('request'); // https://github.com/mikeal/request var passport = require('passport'); var foursquare = require('node-foursquare')({ secrets: config.foursquare }); var LastFmNode = require('lastfm').LastFmNode; var querystring = require('querystring'); var passportConf = require('../config/passport'); /** * API Controller */ module.exports.controller = function (app) { /** * GET /api* * *ALL* api routes must be authenticated first */ app.all('/api*', passportConf.isAuthenticated); /** * GET /api * List of API examples. */ // app.get('/api', function (req, res) { // res.render('api/index', { // url: req.url // }); // }); /** * GET /api/react * React examples */ app.get('/api/react', function (req, res) { res.render('api/react', { url: req.url }); }); /** * GET /creditcard * Credit Card Form Example. */ app.get('/api/creditcard', function (req, res) { res.render('api/creditcard', { url: req.url }); }); /** * GET /api/lastfm * Last.fm API example. */ app.get('/api/lastfm', function (req, res, next) { var lastfm = new LastFmNode(config.lastfm); async.parallel({ artistInfo: function (done) { lastfm.request('artist.getInfo', { artist: 'Morcheeba', handlers: { success: function (data) { done(null, data); }, error: function (err) { done(err); } } }); }, artistTopAlbums: function (done) { lastfm.request('artist.getTopAlbums', { artist: 'Morcheeba', handlers: { success: function (data) { var albums = []; _.forEach(data.topalbums.album, function (album) { albums.push(album.image.slice(-1)[0]['#text']); }); done(null, albums.slice(0, 4)); }, error: function (err) { done(err); } } }); } }, function (err, results) { if (err) { return next(err.message); } var artist = { name: results.artistInfo.artist.name, image: results.artistInfo.artist.image.slice(-1)[0]['#text'], tags: results.artistInfo.artist.tags.tag, bio: results.artistInfo.artist.bio.summary, stats: results.artistInfo.artist.stats, similar: results.artistInfo.artist.similar.artist, topAlbums: results.artistTopAlbums }; res.render('api/lastfm', { artist: artist, url: '/apiopen' }); }); }); /** * GET /api/nyt * New York Times API example. */ app.get('/api/nyt', function (req, res, next) { var query = querystring.stringify({ 'api-key': config.nyt.key, 'list-name': 'young-adult' }); var url = 'http://api.nytimes.com/svc/books/v2/lists?' + query; request.get(url, function (error, request, body) { if (request.statusCode === 403) { return next(error('Missing or Invalid New York Times API Key')); } var bestsellers = {}; // NYT occasionally sends bad data :( try { bestsellers = JSON.parse(body); } catch (err) { bestsellers.results = ''; req.flash('error', { msg: err.message }); } res.render('api/nyt', { url: '/apiopen', books: bestsellers.results }); }); }); /** * GET /api/paypal * PayPal SDK example. */ app.get('/api/paypal', function (req, res, next) { paypal.configure(config.paypal); var payment_details = { intent: 'sale', payer: { payment_method: 'paypal' }, redirect_urls: { return_url: config.paypal.returnUrl, cancel_url: config.paypal.cancelUrl }, transactions: [ { description: 'ITEM: Something Awesome!', amount: { currency: 'USD', total: '2.99' } } ] }; paypal.payment.create(payment_details, function (error, payment) { if (error) { // TODO FIXME console.log(error); } else { req.session.payment_id = payment.id; var links = payment.links; for (var i = 0; i < links.length; i++) { if (links[i].rel === 'approval_url') { res.render('api/paypal', { url: '/apilocked', approval_url: links[i].href }); } } } }); }); /** * GET /api/paypal/success * PayPal SDK example. */ app.get('/api/paypal/success', function (req, res, next) { var payment_id = req.session.payment_id; var payment_details = { payer_id: req.query.PayerID }; paypal.payment.execute(payment_id, payment_details, function (error, payment) { if (error) { res.render('api/paypal', { url: req.url, result: true, success: false }); } else { res.render('api/paypal', { url: '/apilocked', result: true, success: true }); } }); }); /** * GET /api/paypal/cancel * PayPal SDK example. */ app.get('/api/paypal/cancel', function (req, res, next) { req.session.payment_id = null; res.render('api/paypal', { url: '/apilocked', result: true, canceled: true }); }); /** * GET /api/scraping * Web scraping example using Cheerio library. */ app.get('/api/scraping', function (req, res, next) { request.get({ url: 'https://news.ycombinator.com/', timeout: 3000 }, function (err, response, body) { if (!err && response.statusCode === 200) { var $ = cheerio.load(body); // Get Articles var links = []; $('.title a[href^="http"], .title a[href^="https"], .title a[href^="item"]').each(function () { if ($(this).text() !== 'scribd') { if ($(this).text() !== 'Bugs') { links.push($(this)); } } }); // Get Comments var comments = []; $('.subtext a[href^="item"]').each(function () { comments.push('<a href="https://news.ycombinator.com/' + $(this).attr('href') + '">' + $(this).text() + '</a>'); }); // Render Page res.render('api/scraping', { url: '/apiopen', links: links, comments: comments }); } else { req.flash('error', { msg: 'Sorry, something went wrong! MSG: ' + err.message }); return res.redirect('back'); } }); }); /** * GET /api/socrata * Web scraping example using Cheerio library. */ app.get('/api/socrata', function (req, res, next) { // Get the socrata open data as JSON // http://dev.socrata.com/docs/queries.html request.get({ url: 'http://controllerdata.lacity.org/resource/qjfm-3srk.json?$order=q4_earnings DESC&$where=year = 2014&$limit=20', timeout: 5000 }, function (err, response, body) { if (!err && response.statusCode === 200) { // Parse the data var payroll = JSON.parse(body); // Render the page res.render('api/socrata', { url: '/apiopen', data: payroll }); } else { req.flash('error', { msg: 'Sorry, something went wrong! MSG: ' + err.message }); return res.redirect('back'); } }); }); /** * GET /api/stripe * Stripe API example. */ app.get('/api/stripe', function (req, res, next) { res.render('api/stripe', { title: 'Stripe API' }); }); /** * POST /api/stripe * @param stipeToken * @param stripeEmail */ app.post('/api/stripe', function (req, res, next) { var stripeToken = req.body.stripeToken; var stripeEmail = req.body.stripeEmail; stripe.charges.create({ amount: 395, currency: 'usd', card: stripeToken, description: stripeEmail }, function (err, charge) { if (err && err.type === 'StripeCardError') { req.flash('error', { msg: 'Your card has been declined.' }); res.redirect('/api/stripe'); } req.flash('success', { msg: 'Your card has been charged successfully.' }); res.redirect('/api/stripe'); }); }); /** * GET /api/twilio * Twilio API example. */ app.get('/api/twilio', function (req, res, next) { res.render('api/twilio', { url: '/apiopen' }); }); /** * POST /api/twilio * Twilio API example. * @param telephone */ app.post('/api/twilio', function (req, res, next) { var message = { to: req.body.telephone, from: config.twilio.phone, body: 'Hello from ' + app.locals.application + '. We are happy you are testing our code!' }; twilio.sendMessage(message, function (err, responseData) { if (err) { return next(err); } req.flash('success', { msg: 'Text sent to ' + responseData.to + '.' }); res.redirect('/api/twilio'); }); }); /** * GET /api/foursquare * Foursquare API example. */ app.get('/api/foursquare', passportConf.isAuthenticated, passportConf.isAuthorized, function (req, res, next) { var token = _.find(req.user.tokens, { kind: 'foursquare' }); async.parallel({ trendingVenues: function (callback) { foursquare.Venues.getTrending('40.7222756', '-74.0022724', { limit: 50 }, token.accessToken, function (err, results) { callback(err, results); }); }, venueDetail: function (callback) { foursquare.Venues.getVenue('49da74aef964a5208b5e1fe3', token.accessToken, function (err, results) { callback(err, results); }); }, userCheckins: function (callback) { foursquare.Users.getCheckins('self', null, token.accessToken, function (err, results) { callback(err, results); }); } }, function (err, results) { if (err) { return next(err); } res.render('api/foursquare', { url: '/apilocked', trendingVenues: results.trendingVenues, venueDetail: results.venueDetail, userCheckins: results.userCheckins }); }); }); /** * GET /api/tumblr * Tumblr API example. */ app.get('/api/tumblr', passportConf.isAuthenticated, passportConf.isAuthorized, function (req, res) { var token = _.find(req.user.tokens, { kind: 'tumblr' }); var client = tumblr.createClient({ consumer_key: config.tumblr.key, consumer_secret: config.tumblr.secret, token: token.token, token_secret: token.tokenSecret }); client.posts('danielmoyerdesign.tumblr.com', { type: 'photo' }, function (err, data) { res.render('api/tumblr', { url: '/apilocked', blog: data.blog, photoset: data.posts[0].photos }); }); }); /** * GET /api/facebook * Facebook API example. */ app.get('/api/facebook', passportConf.isAuthenticated, passportConf.isAuthorized, function (req, res, next) { var token = _.find(req.user.tokens, { kind: 'facebook' }); graph.setAccessToken(token.accessToken); async.parallel({ getMe: function (done) { graph.get(req.user.facebook, function (err, me) { done(err, me); }); }, getMyFriends: function (done) { graph.get(req.user.facebook + '/friends', function (err, friends) { debug('Friends: ' + JSON.stringify(friends)); done(err, friends); }); } }, function (err, results) { if (err) { return next(err); } res.render('api/facebook', { url: '/apilocked', me: results.getMe, friends: results.getMyFriends }); }); }); /** * GET /api/github * GitHub API Example. */ app.get('/api/github', passportConf.isAuthenticated, passportConf.isAuthorized, function (req, res) { var token = _.find(req.user.tokens, { kind: 'github' }); var github = new Github({ token: token.accessToken }); var repo = github.getRepo('dstroot', 'skeleton'); repo.show(function (err, repo) { res.render('api/github', { url: '/apilocked', repo: repo }); }); }); /** * GET /api/twitter * Twitter API example. * https://dev.twitter.com/rest/reference/get/search/tweets */ app.get('/api/twitter', passportConf.isAuthenticated, passportConf.isAuthorized, function (req, res, next) { var token = _.find(req.user.tokens, { kind: 'twitter' }); var params = { q: 'iPhone 6', since_id: 24012619984051000, count: 10, result_type: 'popular' }; var T = new Twit({ consumer_key: config.twitter.consumerKey, consumer_secret: config.twitter.consumerSecret, access_token: token.token, access_token_secret: token.tokenSecret }); T.get('search/tweets', params, function (err, data, response) { if (err) { return next(err); } res.render('api/twitter', { url: '/apilocked', tweets: data.statuses }); }); }); /** * POST /api/twitter * Post a tweet. */ app.post('/api/twitter', passportConf.isAuthenticated, passportConf.isAuthorized, function (req, res, next) { req.assert('tweet', 'Tweet cannot be empty.').notEmpty(); var errors = req.validationErrors(); if (errors) { req.flash('errors', errors); return res.redirect('/api/twitter'); } var token = _.find(req.user.tokens, { kind: 'twitter' }); var T = new Twit({ consumer_key: config.twitter.consumerKey, consumer_secret: config.twitter.consumerSecret, access_token: token.token, access_token_secret: token.tokenSecret }); T.post('statuses/update', { status: req.body.tweet }, function (err, data, response) { if (err) { return next(err); } req.flash('success', { msg: 'Tweet has been posted.' }); res.redirect('/api/twitter'); }); }); /** * OAuth routes for API examples that require authorization. */ app.get('/auth/foursquare', passport.authorize('foursquare')); app.get('/auth/foursquare/callback', passport.authorize('foursquare', { failureRedirect: '/api' }), function (req, res) { res.redirect('/api/foursquare'); }); app.get('/auth/tumblr', passport.authorize('tumblr')); app.get('/auth/tumblr/callback', passport.authorize('tumblr', { failureRedirect: '/api' }), function (req, res) { res.redirect('/api/tumblr'); }); };
justyn-clark/mylockedemo
controllers/api.js
JavaScript
mit
15,388
range.collapse(true); // collapse to the starting point console.log(range.collapsed); // outputs "true"
msfrisbie/pjwd-src
Chapter16DOMLevels2And3/Ranges/CollapsingADOMRange/CollapsingADOMRangeExample01.js
JavaScript
mit
108
<?php /** * TL_ROOT/system/modules/videobox_vimeo/languages/lv/tl_videobox_settings.php * * Contao extension: videobox_vimeo 1.0.1 stable * Latvian translation file * * Copyright : David Enke 2010 * License : GNU/GPL * Author : David Enke (david.enke), www.davidenke.de * Translator: Maris Celmins (warrior), http://www.bauskasbiblioteka.lv * * This file was created automatically be the Contao extension repository translation module. * Do not edit this file manually. Contact the author or translator for this module to establish * permanent text corrections which are update-safe. */ $GLOBALS['TL_LANG']['tl_videobox_settings']['vimeo_legend'] = "Vimeo video"; $GLOBALS['TL_LANG']['tl_videobox_settings']['vimeo_template']['0'] = "Veidne"; $GLOBALS['TL_LANG']['tl_videobox_settings']['vimeo_template']['1'] = "Izvēleties veidni priekš Vimeo video."; $GLOBALS['TL_LANG']['tl_videobox_settings']['vimeo_size']['0'] = "Izmērs"; $GLOBALS['TL_LANG']['tl_videobox_settings']['vimeo_size']['1'] = "Iespējams norādīt video platuma un augstuma vērtības."; $GLOBALS['TL_LANG']['tl_videobox_settings']['vimeo_autoplay']['0'] = "Automātiska atskaņošana"; $GLOBALS['TL_LANG']['tl_videobox_settings']['vimeo_autoplay']['1'] = "Norāda vai video attēlošana tiks veikta automātiski pēc atskaņotāja ielādes vai nē."; $GLOBALS['TL_LANG']['tl_videobox_settings']['vimeo_color']['0'] = "Krāsa"; $GLOBALS['TL_LANG']['tl_videobox_settings']['vimeo_color']['1'] = "Šī krāsa tonē atskaņotāja kontroles."; $GLOBALS['TL_LANG']['tl_videobox_settings']['vimeo_showbyline']['0'] = "Rādīt video autora parakstu"; $GLOBALS['TL_LANG']['tl_videobox_settings']['vimeo_showbyline']['1'] = "Parāda video autora parakstu pirms video atskaņošanas sākuma."; $GLOBALS['TL_LANG']['tl_videobox_settings']['vimeo_showtitle']['0'] = "Parādīt video nosaukumu"; $GLOBALS['TL_LANG']['tl_videobox_settings']['vimeo_showtitle']['1'] = "Parāda video nosaukumu pirms video atskaņošanas sākuma."; $GLOBALS['TL_LANG']['tl_videobox_settings']['vimeo_showportrait']['0'] = "Parādīt lietotāja attēlu"; $GLOBALS['TL_LANG']['tl_videobox_settings']['vimeo_showportrait']['1'] = "Parāda lietotāja attēlu pirms video atskaņošanas sākuma."; ?>
TechnoGate/contao_template
contao/videobox_vimeo/system/modules/videobox_vimeo/languages/lv/tl_videobox_settings.php
PHP
mit
2,269
Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # Code is not reloaded between requests. config.cache_classes = true # Eager load code on boot. This eager loads most of Rails and # your application in memory, allowing both threaded web servers # and those relying on copy on write to perform better. # Rake tasks automatically ignore this option for performance. config.eager_load = true # Full error reports are disabled and caching is turned on. config.consider_all_requests_local = false config.action_controller.perform_caching = true # Disable serving static files from the `/public` folder by default since # Apache or NGINX already handles this. config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? # Compress JavaScripts and CSS. config.assets.js_compressor = :uglifier # config.assets.css_compressor = :sass # Do not fallback to assets pipeline if a precompiled asset is missed. config.assets.compile = false # `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb # Enable serving of images, stylesheets, and JavaScripts from an asset server. # config.action_controller.asset_host = 'http://assets.example.com' # Specifies the header that your server uses for sending files. # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX # Mount Action Cable outside main process or domain # config.action_cable.mount_path = nil # config.action_cable.url = 'wss://example.com/cable' # config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ] # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. config.force_ssl = true # Use the lowest log level to ensure availability of diagnostic information # when problems arise. config.log_level = :debug # Prepend all log lines with the following tags. config.log_tags = [ :request_id ] # Use a different cache store in production. # config.cache_store = :mem_cache_store # Use a real queuing backend for Active Job (and separate queues per environment) # config.active_job.queue_adapter = :resque # config.active_job.queue_name_prefix = "blog5_#{Rails.env}" config.action_mailer.perform_caching = false # Ignore bad email addresses and do not raise email delivery errors. # Set this to true and configure the email server for immediate delivery to raise delivery errors. config.action_mailer.delivery_method = :sendmail config.action_mailer.perform_deliveries = true config.action_mailer.raise_delivery_errors = true Rails.application.config.middleware.use ExceptionNotification::Rack, :email => { :deliver_with => :deliver, # Rails >= 4.2.1 do not need this option since it defaults to :deliver_now :email_prefix => "[BLOG5] ", :sender_address => %{"Error Notifier" <errors@michaeljbostler.com>}, :exception_recipients => %w{mbostler@gmail.com} } # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation cannot be found). config.i18n.fallbacks = true # Send deprecation notices to registered listeners. config.active_support.deprecation = :notify # Use default logging formatter so that PID and timestamp are not suppressed. config.log_formatter = ::Logger::Formatter.new # Use a different logger for distributed setups. # require 'syslog/logger' # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') if ENV["RAILS_LOG_TO_STDOUT"].present? logger = ActiveSupport::Logger.new(STDOUT) logger.formatter = config.log_formatter config.logger = ActiveSupport::TaggedLogging.new(logger) end # Do not dump schema after migrations. config.active_record.dump_schema_after_migration = false end
mbostler/blog5
config/environments/production.rb
Ruby
mit
4,041
<?php class Brandedcrate_Payjunction_Model_Result extends Varien_Object { }
brandedcrate/payjunction-magento
app/code/community/Brandedcrate/Payjunction/Model/Result.php
PHP
mit
82
// Generated by typings // Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/80060c94ef549c077a011977c2b5461bd0fd8947/strftime/index.d.ts declare module "strftime" { type strftimeFunction = (format: string, date?: Date) => string; namespace strftime { /** * Sets locale. * @param {Locale} locale A locale. * @return {strftimeFunction} A strftime function. */ export function localize(locale: Locale): strftimeFunction; /** * Sets timezone. * @param {number|string} offset A offset. * @return {strftimeFunction} A strftime function. */ export function timezone(offset: number | string): strftimeFunction; /** * Locale formats. * @interface */ export interface LocaleFormats { D?: string; F?: string; R?: string; T?: string; X?: string; c?: string; r?: string; v?: string; x?: string; } /** * Locale. * @interface */ export interface Locale { days?: Array<string>; shortDays?: Array<string>; months?: Array<string>; shortMonths?: Array<string>; AM?: string; PM?: string; am?: string; pm?: string; formats: LocaleFormats } } /** * Format a local time/date according to locale settings * @param {string} format A format. * @return {string} Returns a string formatted. */ function strftime(format: string): string; /** * Format a local time/date according to locale settings * @param {string} format A format. * @param {Date} date A date. * @return {string} Returns a string formatted according format using the given date or the current local time. */ function strftime(format: string, date: Date): string; export = strftime; }
liqu0/KentChat
src/server/typings/globals/strftime/index.d.ts
TypeScript
mit
2,057
var Sequelize = require('sequelize'); var sequelize = require('./db.js').Sequelize; var UserRooms = sequelize.define('UserRooms', { }, { updatedAt: false, createdAt: false }); module.exports = UserRooms;
nokia-wroclaw/innovativeproject-meetinghelper
server/NodeTest/models/userRoom.js
JavaScript
mit
236
(function(S, $) { var dom = S.Dom; var sharedUserAdmin = new Spontaneous.MetaView.UserAdmin(); var RootMenuView = new JS.Class(S.PopoverView, { initialize: function(afterCloseCallback) { this.afterCloseCallback = afterCloseCallback; this.callSuper(); }, width: function() { return 250; }, title: function() { return "Main Menu"; }, position_from_event: function(event) { var pos = this.callSuper(); return {left: pos.left - 12, top: pos.top + 1}; }, view: function() { var outer = dom.div("#root-menu") outer.append(this.serviceMenu(), this.userActionMenu()); return outer; }, after_close: function() { console.log("root menu after close") if (this.afterCloseCallback && (typeof this.afterCloseCallback === "function")) { this.afterCloseCallback(); } }, userActionMenu: function() { var menu = dom.ul(".user-actions"); menu.append(dom.li('.user.title').text(S.User.name())); if (S.User.is_admin()) { var manage = dom.a().text("User Administration").click(function() { Spontaneous.ContentArea.enterMeta(sharedUserAdmin); Spontaneous.Popover.close(); }); menu.append(dom.li('.user-administration').append(manage)); } var logout = dom.a().text("Logout").click(function() { console.log("Logout"); S.User.logout(); }); menu.append(dom.li('.logout').append(logout)); return menu; }, serviceMenu: function() { var menu = dom.ul(".external-services"); var self = this; var services = S.Services.serviceList(); if (services.length > 0) { menu.append(dom.li(".title").text("Services")); services.forEach(function(service) { var link = dom.a().text(service.title).click(function() { self.close(); S.Services.open(service); }); menu.append(dom.li().append(link)) }); } return menu; } }); S.RootMenuView = RootMenuView; }(Spontaneous, jQuery));
magnetised/spontaneous
application/js/panel/root_menu.js
JavaScript
mit
1,921
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; using UiuCanteen.Domain.Entities; namespace UiuCanteen.Domain.Concrete { public class EFDbContext : DbContext { public DbSet<Product> Products { get; set; } public DbSet<User> Users { get; set; } } }
rasel01/Project-1-Online-Cafeteria-
source/UiuCanteen/UiuCanteen.Domain/Concrete/EFDbContext.cs
C#
mit
377
const renderToString = require('rogain-render-string'); const html = require('html').prettyPrint; const config = require('./render.config.js'); const data = require('./fixtures/data.json'); var output = renderToString(config.components.get('Template'), data, config); console.log(html(output, { unformatted: [] }));
krambuhl/rogain
test/render.test.js
JavaScript
mit
318
module.exports = function(planetsData) { planetsData.createPlanet("Earth") .then((planet) => { console.log("Created new Planet"); console.log(planet); }) .catch(() => { console.log("Error"); console.dir(err, { colors: true }); }); }
shopOFF/TelerikAcademyCourses
Web-Applications-with-Node.js/NodeJs-Homeworks & Exams/nodeJSWorkshop/controllers/planets-controller.js
JavaScript
mit
316
// Copyright (c) 2014 Greenheart Games Pty. Ltd. All rights reserved. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "greenworks_workshop_workers.h" #include <algorithm> #include "nan.h" #include "steam/steam_api.h" #include "v8.h" #include "greenworks_utils.h" namespace { v8::Local<v8::Object> ConvertToJsObject(const SteamUGCDetails_t& item) { v8::Local<v8::Object> result = Nan::New<v8::Object>(); Nan::Set(result, Nan::New("acceptedForUse").ToLocalChecked(), Nan::New(item.m_bAcceptedForUse)); Nan::Set(result, Nan::New("banned").ToLocalChecked(), Nan::New(item.m_bBanned)); Nan::Set(result, Nan::New("tagsTruncated").ToLocalChecked(), Nan::New(item.m_bTagsTruncated)); Nan::Set(result, Nan::New("fileType").ToLocalChecked(), Nan::New(item.m_eFileType)); Nan::Set(result, Nan::New("result").ToLocalChecked(), Nan::New(item.m_eResult)); Nan::Set(result, Nan::New("visibility").ToLocalChecked(), Nan::New(item.m_eVisibility)); Nan::Set(result, Nan::New("score").ToLocalChecked(), Nan::New(item.m_flScore)); Nan::Set(result, Nan::New("file").ToLocalChecked(), Nan::New(utils::uint64ToString(item.m_hFile)).ToLocalChecked()); Nan::Set(result, Nan::New("fileName").ToLocalChecked(), Nan::New(item.m_pchFileName).ToLocalChecked()); Nan::Set(result, Nan::New("fileSize").ToLocalChecked(), Nan::New(item.m_nFileSize)); Nan::Set( result, Nan::New("previewFile").ToLocalChecked(), Nan::New(utils::uint64ToString(item.m_hPreviewFile)).ToLocalChecked()); Nan::Set(result, Nan::New("previewFileSize").ToLocalChecked(), Nan::New(item.m_nPreviewFileSize)); Nan::Set( result, Nan::New("steamIDOwner").ToLocalChecked(), Nan::New(utils::uint64ToString(item.m_ulSteamIDOwner)).ToLocalChecked()); Nan::Set(result, Nan::New("consumerAppID").ToLocalChecked(), Nan::New(item.m_nConsumerAppID)); Nan::Set(result, Nan::New("creatorAppID").ToLocalChecked(), Nan::New(item.m_nCreatorAppID)); Nan::Set(result, Nan::New("publishedFileId").ToLocalChecked(), Nan::New(utils::uint64ToString(item.m_nPublishedFileId)) .ToLocalChecked()); Nan::Set(result, Nan::New("title").ToLocalChecked(), Nan::New(item.m_rgchTitle).ToLocalChecked()); Nan::Set(result, Nan::New("description").ToLocalChecked(), Nan::New(item.m_rgchDescription).ToLocalChecked()); Nan::Set(result, Nan::New("URL").ToLocalChecked(), Nan::New(item.m_rgchURL).ToLocalChecked()); Nan::Set(result, Nan::New("tags").ToLocalChecked(), Nan::New(item.m_rgchTags).ToLocalChecked()); Nan::Set(result, Nan::New("timeAddedToUserList").ToLocalChecked(), Nan::New(item.m_rtimeAddedToUserList)); Nan::Set(result, Nan::New("timeCreated").ToLocalChecked(), Nan::New(item.m_rtimeCreated)); Nan::Set(result, Nan::New("timeUpdated").ToLocalChecked(), Nan::New(item.m_rtimeUpdated)); Nan::Set(result, Nan::New("votesDown").ToLocalChecked(), Nan::New(item.m_unVotesDown)); Nan::Set(result, Nan::New("votesUp").ToLocalChecked(), Nan::New(item.m_unVotesUp)); return result; } inline std::string GetAbsoluteFilePath(const std::string& file_path, const std::string& download_dir) { std::string file_name = file_path.substr(file_path.find_last_of("/\\") + 1); return download_dir + "/" + file_name; } } // namespace namespace greenworks { FileShareWorker::FileShareWorker(Nan::Callback* success_callback, Nan::Callback* error_callback, const std::string& file_path) :SteamCallbackAsyncWorker(success_callback, error_callback), file_path_(file_path) { } void FileShareWorker::Execute() { // Ignore empty path. if (file_path_.empty()) return; std::string file_name = utils::GetFileNameFromPath(file_path_); SteamAPICall_t share_result = SteamRemoteStorage()->FileShare( file_name.c_str()); call_result_.Set(share_result, this, &FileShareWorker::OnFileShareCompleted); // Wait for FileShare callback result. WaitForCompleted(); } void FileShareWorker::OnFileShareCompleted( RemoteStorageFileShareResult_t* result, bool io_failure) { if (io_failure) { SetErrorMessage("Error on sharing file: Steam API IO Failure"); } else if (result->m_eResult == k_EResultOK) { share_file_handle_ = result->m_hFile; } else { SetErrorMessage("Error on sharing file on Steam cloud."); } is_completed_ = true; } void FileShareWorker::HandleOKCallback() { Nan::HandleScope scope; v8::Local<v8::Value> argv[] = { Nan::New(utils::uint64ToString(share_file_handle_)).ToLocalChecked() }; Nan::AsyncResource resource("greenworks:FileShareWorker.HandleOKCallback"); callback->Call(1, argv, &resource); } PublishWorkshopFileWorker::PublishWorkshopFileWorker( Nan::Callback* success_callback, Nan::Callback* error_callback, uint32 app_id, const WorkshopFileProperties& properties) : SteamCallbackAsyncWorker(success_callback, error_callback), app_id_(app_id), properties_(properties) {} void PublishWorkshopFileWorker::Execute() { SteamParamStringArray_t tags; tags.m_nNumStrings = properties_.tags_scratch.size(); tags.m_ppStrings = reinterpret_cast<const char**>(&properties_.tags); std::string file_name = utils::GetFileNameFromPath(properties_.file_path); std::string image_name = utils::GetFileNameFromPath(properties_.image_path); SteamAPICall_t publish_result = SteamRemoteStorage()->PublishWorkshopFile( file_name.c_str(), image_name.empty()? nullptr:image_name.c_str(), app_id_, properties_.title.c_str(), properties_.description.empty()? nullptr:properties_.description.c_str(), k_ERemoteStoragePublishedFileVisibilityPublic, &tags, k_EWorkshopFileTypeCommunity); call_result_.Set(publish_result, this, &PublishWorkshopFileWorker::OnFilePublishCompleted); // Wait for FileShare callback result. WaitForCompleted(); } void PublishWorkshopFileWorker::OnFilePublishCompleted( RemoteStoragePublishFileResult_t* result, bool io_failure) { if (io_failure) { SetErrorMessage("Error on publishing workshop file: Steam API IO Failure"); } else if (result->m_eResult == k_EResultOK) { publish_file_id_ = result->m_nPublishedFileId; } else { SetErrorMessage("Error on publishing workshop file."); } is_completed_ = true; } void PublishWorkshopFileWorker::HandleOKCallback() { Nan::HandleScope scope; v8::Local<v8::Value> argv[] = { Nan::New(utils::uint64ToString(publish_file_id_)).ToLocalChecked() }; Nan::AsyncResource resource("greenworks:PublishWorkshopFileWorker.HandleOKCallback"); callback->Call(1, argv, &resource); } UpdatePublishedWorkshopFileWorker::UpdatePublishedWorkshopFileWorker( Nan::Callback* success_callback, Nan::Callback* error_callback, PublishedFileId_t published_file_id, const WorkshopFileProperties& properties) : SteamCallbackAsyncWorker(success_callback, error_callback), published_file_id_(published_file_id), properties_(properties) {} void UpdatePublishedWorkshopFileWorker::Execute() { PublishedFileUpdateHandle_t update_handle = SteamRemoteStorage()->CreatePublishedFileUpdateRequest( published_file_id_); const std::string file_name = utils::GetFileNameFromPath(properties_.file_path); const std::string image_name = utils::GetFileNameFromPath(properties_.image_path); if (!file_name.empty()) SteamRemoteStorage()->UpdatePublishedFileFile(update_handle, file_name.c_str()); if (!image_name.empty()) SteamRemoteStorage()->UpdatePublishedFilePreviewFile(update_handle, image_name.c_str()); if (!properties_.title.empty()) SteamRemoteStorage()->UpdatePublishedFileTitle(update_handle, properties_.title.c_str()); if (!properties_.description.empty()) SteamRemoteStorage()->UpdatePublishedFileDescription(update_handle, properties_.description.c_str()); if (!properties_.tags_scratch.empty()) { SteamParamStringArray_t tags; if (properties_.tags_scratch.size() == 1 && properties_.tags_scratch.front().empty()) { // clean the tag. tags.m_nNumStrings = 0; tags.m_ppStrings = nullptr; } else { tags.m_nNumStrings = properties_.tags_scratch.size(); tags.m_ppStrings = reinterpret_cast<const char**>(&properties_.tags); } SteamRemoteStorage()->UpdatePublishedFileTags(update_handle, &tags); } SteamAPICall_t commit_update_result = SteamRemoteStorage()->CommitPublishedFileUpdate(update_handle); update_published_file_call_result_.Set(commit_update_result, this, &UpdatePublishedWorkshopFileWorker:: OnCommitPublishedFileUpdateCompleted); // Wait for published workshop file updated. WaitForCompleted(); } void UpdatePublishedWorkshopFileWorker::OnCommitPublishedFileUpdateCompleted( RemoteStorageUpdatePublishedFileResult_t* result, bool io_failure) { if (io_failure) { SetErrorMessage( "Error on committing published file update: Steam API IO Failure"); } else if (result->m_eResult == k_EResultOK) { } else { SetErrorMessage("Error on getting published file details."); } is_completed_ = true; } QueryUGCWorker::QueryUGCWorker(Nan::Callback* success_callback, Nan::Callback* error_callback, EUGCMatchingUGCType ugc_matching_type, uint32 app_id, uint32 page_num) : SteamCallbackAsyncWorker(success_callback, error_callback), ugc_matching_type_(ugc_matching_type), app_id_(app_id), page_num_(page_num) {} void QueryUGCWorker::HandleOKCallback() { Nan::HandleScope scope; v8::Local<v8::Array> items = Nan::New<v8::Array>( static_cast<int>(ugc_items_.size())); for (size_t i = 0; i < ugc_items_.size(); ++i) Nan::Set(items, i, ConvertToJsObject(ugc_items_[i])); v8::Local<v8::Value> argv[] = { items }; Nan::AsyncResource resource("greenworks:QueryUGCWorker.HandleOKCallback"); callback->Call(1, argv, &resource); } void QueryUGCWorker::OnUGCQueryCompleted(SteamUGCQueryCompleted_t* result, bool io_failure) { if (io_failure) { SetErrorMessage("Error on querying all ugc: Steam API IO Failure"); } else if (result->m_eResult == k_EResultOK) { uint32 count = result->m_unNumResultsReturned; SteamUGCDetails_t item; for (uint32 i = 0; i < count; ++i) { SteamUGC()->GetQueryUGCResult(result->m_handle, i, &item); ugc_items_.push_back(item); } SteamUGC()->ReleaseQueryUGCRequest(result->m_handle); } else { SetErrorMessage("Error on querying ugc."); } is_completed_ = true; } QueryAllUGCWorker::QueryAllUGCWorker(Nan::Callback* success_callback, Nan::Callback* error_callback, EUGCMatchingUGCType ugc_matching_type, EUGCQuery ugc_query_type, uint32 app_id, uint32 page_num) : QueryUGCWorker(success_callback, error_callback, ugc_matching_type, app_id, page_num), ugc_query_type_(ugc_query_type) {} void QueryAllUGCWorker::Execute() { uint32 invalid_app_id = 0; // Set "creator_app_id" parameter to an invalid id to make Steam API return // all ugc items, otherwise the API won't get any results in some cases. UGCQueryHandle_t ugc_handle = SteamUGC()->CreateQueryAllUGCRequest( ugc_query_type_, ugc_matching_type_, /*creator_app_id=*/invalid_app_id, /*consumer_app_id=*/app_id_, page_num_); SteamAPICall_t ugc_query_result = SteamUGC()->SendQueryUGCRequest(ugc_handle); ugc_query_call_result_.Set(ugc_query_result, this, &QueryAllUGCWorker::OnUGCQueryCompleted); // Wait for query all ugc completed. WaitForCompleted(); } QueryUserUGCWorker::QueryUserUGCWorker( Nan::Callback* success_callback, Nan::Callback* error_callback, EUGCMatchingUGCType ugc_matching_type, EUserUGCList ugc_list, EUserUGCListSortOrder ugc_list_sort_order, uint32 app_id, uint32 page_num) : QueryUGCWorker(success_callback, error_callback, ugc_matching_type, app_id, page_num), ugc_list_(ugc_list), ugc_list_sort_order_(ugc_list_sort_order) {} void QueryUserUGCWorker::Execute() { UGCQueryHandle_t ugc_handle = SteamUGC()->CreateQueryUserUGCRequest( SteamUser()->GetSteamID().GetAccountID(), ugc_list_, ugc_matching_type_, ugc_list_sort_order_, app_id_, app_id_, page_num_); SteamAPICall_t ugc_query_result = SteamUGC()->SendQueryUGCRequest(ugc_handle); ugc_query_call_result_.Set(ugc_query_result, this, &QueryUserUGCWorker::OnUGCQueryCompleted); // Wait for query all ugc completed. WaitForCompleted(); } DownloadItemWorker::DownloadItemWorker(Nan::Callback* success_callback, Nan::Callback* error_callback, UGCHandle_t download_file_handle, const std::string& download_dir) :SteamCallbackAsyncWorker(success_callback, error_callback), download_file_handle_(download_file_handle), download_dir_(download_dir) { } void DownloadItemWorker::Execute() { SteamAPICall_t download_item_result = SteamRemoteStorage()->UGCDownload(download_file_handle_, 0); call_result_.Set(download_item_result, this, &DownloadItemWorker::OnDownloadCompleted); // Wait for downloading file completed. WaitForCompleted(); } void DownloadItemWorker::OnDownloadCompleted( RemoteStorageDownloadUGCResult_t* result, bool io_failure) { if (io_failure) { SetErrorMessage( "Error on downloading file: Steam API IO Failure"); } else if (result->m_eResult == k_EResultOK) { std::string target_path = GetAbsoluteFilePath(result->m_pchFileName, download_dir_); int file_size_in_bytes = result->m_nSizeInBytes; auto* content = new char[file_size_in_bytes]; SteamRemoteStorage()->UGCRead(download_file_handle_, content, file_size_in_bytes, 0, k_EUGCRead_Close); if (!utils::WriteFile(target_path, content, file_size_in_bytes)) { SetErrorMessage("Error on saving file on local machine."); } delete[] content; } else { SetErrorMessage("Error on downloading file."); } is_completed_ = true; } SynchronizeItemsWorker::SynchronizeItemsWorker(Nan::Callback* success_callback, Nan::Callback* error_callback, const std::string& download_dir, uint32 app_id, uint32 page_num) : SteamCallbackAsyncWorker(success_callback, error_callback), current_download_items_pos_(0), download_dir_(download_dir), app_id_(app_id), page_num_(page_num) {} void SynchronizeItemsWorker::Execute() { UGCQueryHandle_t ugc_handle = SteamUGC()->CreateQueryUserUGCRequest( SteamUser()->GetSteamID().GetAccountID(), k_EUserUGCList_Subscribed, k_EUGCMatchingUGCType_Items, k_EUserUGCListSortOrder_SubscriptionDateDesc, app_id_, app_id_, page_num_); SteamAPICall_t ugc_query_result = SteamUGC()->SendQueryUGCRequest(ugc_handle); ugc_query_call_result_.Set(ugc_query_result, this, &SynchronizeItemsWorker::OnUGCQueryCompleted); // Wait for synchronization completed. WaitForCompleted(); } void SynchronizeItemsWorker::OnUGCQueryCompleted( SteamUGCQueryCompleted_t* result, bool io_failure) { if (io_failure) { SetErrorMessage("Error on querying all ugc: Steam API IO Failure"); } else if (result->m_eResult == k_EResultOK) { SteamUGCDetails_t item; for (uint32 i = 0; i < result->m_unNumResultsReturned; ++i) { SteamUGC()->GetQueryUGCResult(result->m_handle, i, &item); std::string target_path = GetAbsoluteFilePath(item.m_pchFileName, download_dir_); int64 file_update_time = utils::GetFileLastUpdatedTime( target_path.c_str()); ugc_items_.push_back(item); // If the file is not existed or last update time is not equal to Steam, // download it. if (file_update_time == -1 || file_update_time != item.m_rtimeUpdated) download_ugc_items_handle_.push_back(item.m_hFile); } // Start download the file. if (download_ugc_items_handle_.size() > 0) { SteamAPICall_t download_item_result = SteamRemoteStorage()->UGCDownload( download_ugc_items_handle_[current_download_items_pos_], 0); download_call_result_.Set(download_item_result, this, &SynchronizeItemsWorker::OnDownloadCompleted); SteamUGC()->ReleaseQueryUGCRequest(result->m_handle); return; } } else { SetErrorMessage("Error on querying ugc."); } is_completed_ = true; } void SynchronizeItemsWorker::OnDownloadCompleted( RemoteStorageDownloadUGCResult_t* result, bool io_failure) { if (io_failure) { SetErrorMessage( "Error on downloading file: Steam API IO Failure"); } else if (result->m_eResult == k_EResultOK) { std::string target_path = GetAbsoluteFilePath(result->m_pchFileName, download_dir_); int file_size_in_bytes = result->m_nSizeInBytes; auto* content = new char[file_size_in_bytes]; SteamRemoteStorage()->UGCRead(result->m_hFile, content, file_size_in_bytes, 0, k_EUGCRead_Close); bool is_save_success = utils::WriteFile(target_path, content, file_size_in_bytes); delete[] content; if (!is_save_success) { SetErrorMessage("Error on saving file on local machine."); is_completed_ = true; return; } int64 file_updated_time = ugc_items_[current_download_items_pos_].m_rtimeUpdated; if (!utils::UpdateFileLastUpdatedTime( target_path.c_str(), static_cast<time_t>(file_updated_time))) { SetErrorMessage("Error on update file time on local machine."); is_completed_ = true; return; } ++current_download_items_pos_; if (current_download_items_pos_ < download_ugc_items_handle_.size()) { SteamAPICall_t download_item_result = SteamRemoteStorage()->UGCDownload( download_ugc_items_handle_[current_download_items_pos_], 0); download_call_result_.Set(download_item_result, this, &SynchronizeItemsWorker::OnDownloadCompleted); return; } } else { SetErrorMessage("Error on downloading file."); } is_completed_ = true; } void SynchronizeItemsWorker::HandleOKCallback() { Nan::HandleScope scope; v8::Local<v8::Array> items = Nan::New<v8::Array>( static_cast<int>(ugc_items_.size())); for (size_t i = 0; i < ugc_items_.size(); ++i) { v8::Local<v8::Object> item = ConvertToJsObject(ugc_items_[i]); bool is_updated = std::find(download_ugc_items_handle_.begin(), download_ugc_items_handle_.end(), ugc_items_[i].m_hFile) != download_ugc_items_handle_.end(); Nan::Set(item, Nan::New("isUpdated").ToLocalChecked(), Nan::New(is_updated)); Nan::Set(items, i, item); } v8::Local<v8::Value> argv[] = { items }; Nan::AsyncResource resource("greenworks:SynchronizeItemsWorker.HandleOKCallback"); callback->Call(1, argv, &resource); } UnsubscribePublishedFileWorker::UnsubscribePublishedFileWorker( Nan::Callback* success_callback, Nan::Callback* error_callback, PublishedFileId_t unsubscribe_file_id) :SteamCallbackAsyncWorker(success_callback, error_callback), unsubscribe_file_id_(unsubscribe_file_id) { } void UnsubscribePublishedFileWorker::Execute() { SteamAPICall_t unsubscribed_result = SteamRemoteStorage()->UnsubscribePublishedFile(unsubscribe_file_id_); unsubscribe_call_result_.Set(unsubscribed_result, this, &UnsubscribePublishedFileWorker::OnUnsubscribeCompleted); // Wait for unsubscribing job completed. WaitForCompleted(); } void UnsubscribePublishedFileWorker::OnUnsubscribeCompleted( RemoteStoragePublishedFileUnsubscribed_t* result, bool io_failure) { is_completed_ = true; } } // namespace greenworks
greenheartgames/greenworks
src/greenworks_workshop_workers.cc
C++
mit
20,261
class Camera { static init() { this.position = vec3.fromValues(-Terrain.tiles.length/2, -Terrain.tiles[0].length/2, -1 * slider_zoom.value); this.rotation = vec3.fromValues(0, 0, 0); } static getViewMatrix() { var q = quat.create(); quat.rotateX(q, q, this.rotation[0]); quat.rotateY(q, q, this.rotation[1]); quat.rotateZ(q, q, this.rotation[2]); var viewMatrix = mat4.create(); mat4.fromRotationTranslationScale(viewMatrix, q, this.position, [1,1,1]); return viewMatrix; } }
Pilex1/Pilex1.github.io
Projects/Wireworld/camera.js
JavaScript
mit
562
/** * Keyboard event keyCodes have proven to be really unreliable. * This util function will cover most of the edge cases where * String.fromCharCode() doesn't work. */ const _toAscii = { 188: '44', 109: '45', 190: '46', 191: '47', 192: '96', 220: '92', 222: '39', 221: '93', 219: '91', 173: '45', 187: '61', // IE Key codes 186: '59', // IE Key codes 189: '45' // IE Key codes }; const _shiftUps = { 96: '~', 49: '!', 50: '@', 51: '#', 52: '$', 53: '%', 54: '^', 55: '&', 56: '*', 57: '(', 48: ')', 45: '_', 61: '+', 91: '{', 93: '}', 92: '|', 59: ':', 39: "'", 44: '<', 46: '>', 47: '?' }; const _arrowKeys = { 38: '', 40: '', 39: '', 37: '' }; /** * This fn takes a keyboard event and returns * the character that was pressed. This fn * purposely doesn't take into account if the alt/meta * key was pressed. */ export default function fromCharCode(e) { let code = String(e.which); if ({}.hasOwnProperty.call(_arrowKeys, code)) { return _arrowKeys[code]; } if ({}.hasOwnProperty.call(_toAscii, code)) { code = _toAscii[code]; } const char = String.fromCharCode(code); if (e.shiftKey) { if ({}.hasOwnProperty.call(_shiftUps, code)) { return _shiftUps[code]; } return char.toUpperCase(); } return char.toLowerCase(); }
derrickpelletier/hyper
lib/utils/key-code.js
JavaScript
mit
1,367
/** * result Module * * Description */ angular .module('result') .directive('navBar', navBar); navBar.$inject = ['loginService', '$log', '$location']; function navBar(loginService, $log, $location) { return { restrict: 'A', link: function(scope, element, attrs, controller) { loginService.user() .success(function(data) { scope.user = data; }) .error(function(data, status) { loginService.logout(); }) scope.isloggedIn = loginService.isLoggedIn(); scope.$on('updateUser', function(event, args) { if(args.login) { scope.user = args.user; scope.isloggedIn = loginService.isLoggedIn(); } else { scope.user = null; scope.isloggedIn = loginService.isLoggedIn(); } }) scope.logout = function() { loginService.logout() .success(function() { $location.path('/login'); }) } }, replace: true, scope: true, templateUrl: 'packages/app/views/navbar.html' } }
techhahn/Result-Analyzer
public/packages/app/directives/app.navigationbarDirective.js
JavaScript
mit
969
<?php defined('BX_DOL') or die('hack attempt'); /** * Copyright (c) UNA, Inc - https://una.io * MIT License - https://opensource.org/licenses/MIT * * @defgroup UnaCore UNA Core * @{ */ /** * Message constants passed to _t_ext() function by checkAction() * * NOTE: checkAction() returns language dependent messages */ define('CHECK_ACTION_MESSAGE_NOT_ALLOWED', "_sys_acl_action_not_allowed"); define('CHECK_ACTION_MESSAGE_LIMIT_REACHED', "_sys_acl_action_limit_reached"); define('CHECK_ACTION_MESSAGE_MESSAGE_EVERY_PERIOD', "_sys_acl_action_every_period"); define('CHECK_ACTION_MESSAGE_NOT_ALLOWED_BEFORE', "_sys_acl_action_not_allowed_before"); define('CHECK_ACTION_MESSAGE_NOT_ALLOWED_AFTER', "_sys_acl_action_not_allowed_after"); define('CHECK_ACTION_MESSAGE_UNAUTHENTICATED', "_sys_acl_action_unauthenticated"); define('CHECK_ACTION_MESSAGE_UNCONFIRMED', "_sys_acl_action_unconfirmed"); define('CHECK_ACTION_MESSAGE_PENDING', "_sys_acl_action_pending"); define('CHECK_ACTION_MESSAGE_SUSPENDED', "_sys_acl_action_suspended"); /** * Nodes of $args array that are passed to _t_ext() function by checkAction() */ define('CHECK_ACTION_LANG_FILE_ACTION', 1); define('CHECK_ACTION_LANG_FILE_MEMBERSHIP', 2); define('CHECK_ACTION_LANG_FILE_LIMIT', 3); define('CHECK_ACTION_LANG_FILE_PERIOD', 4); define('CHECK_ACTION_LANG_FILE_AFTER', 5); define('CHECK_ACTION_LANG_FILE_BEFORE', 6); define('CHECK_ACTION_LANG_FILE_SITE_EMAIL', 7); define('CHECK_ACTION_LANG_FILE_PERIOD_RESTART_AT', 8); /** * Standard membership ID's */ define('MEMBERSHIP_ID_NON_MEMBER', 1); define('MEMBERSHIP_ID_ACCOUNT', 2); define('MEMBERSHIP_ID_STANDARD', 3); define('MEMBERSHIP_ID_UNCONFIRMED', 4); define('MEMBERSHIP_ID_PENDING', 5); define('MEMBERSHIP_ID_SUSPENDED', 6); define('MEMBERSHIP_ID_MODERATOR', 7); define('MEMBERSHIP_ID_ADMINISTRATOR', 8); /** * Indices for checkAction() result array */ define('CHECK_ACTION_RESULT', 0); define('CHECK_ACTION_MESSAGE', 1); define('CHECK_ACTION_PARAMETER', 3); /** * CHECK_ACTION_RESULT node values */ define('CHECK_ACTION_RESULT_ALLOWED', 0); define('CHECK_ACTION_RESULT_NOT_ALLOWED', 1); define('CHECK_ACTION_RESULT_NOT_ACTIVE', 2); define('CHECK_ACTION_RESULT_LIMIT_REACHED', 3); define('CHECK_ACTION_RESULT_NOT_ALLOWED_BEFORE', 4); define('CHECK_ACTION_RESULT_NOT_ALLOWED_AFTER', 5); /** * Standard period units */ define('MEMBERSHIP_PERIOD_UNIT_DAY', 'day'); define('MEMBERSHIP_PERIOD_UNIT_WEEK', 'week'); define('MEMBERSHIP_PERIOD_UNIT_MONTH', 'month'); define('MEMBERSHIP_PERIOD_UNIT_YEAR', 'year'); class BxDolAcl extends BxDolFactory implements iBxDolSingleton { protected static $_aCacheData = array(); protected $oDb; protected $_aStandardMemberships = array( MEMBERSHIP_ID_NON_MEMBER => 1, MEMBERSHIP_ID_ACCOUNT => 1, MEMBERSHIP_ID_UNCONFIRMED => 1, MEMBERSHIP_ID_PENDING => 1, MEMBERSHIP_ID_SUSPENDED => 1, MEMBERSHIP_ID_STANDARD => 1, ); protected $_aProfileStatus2LevelMap = array ( BX_PROFILE_STATUS_SUSPENDED => MEMBERSHIP_ID_SUSPENDED, BX_PROFILE_STATUS_PENDING => MEMBERSHIP_ID_PENDING, ); protected $_aLevel2MessageMap = array ( MEMBERSHIP_ID_NON_MEMBER => '_sys_acl_action_unauthenticated', MEMBERSHIP_ID_ACCOUNT => '_sys_acl_action_account', MEMBERSHIP_ID_UNCONFIRMED => '_sys_acl_action_unconfirmed', MEMBERSHIP_ID_PENDING => '_sys_acl_action_pending', MEMBERSHIP_ID_SUSPENDED => '_sys_acl_action_suspended', ); protected function __construct() { if (isset($GLOBALS['bxDolClasses'][get_class($this)])) trigger_error ('Multiple instances are not allowed for the class: ' . get_class($this), E_USER_ERROR); parent::__construct(); $this->oDb = BxDolAclQuery::getInstance(); } /** * Prevent cloning the instance */ public function __clone() { if (isset($GLOBALS['bxDolClasses'][get_class($this)])) trigger_error('Clone is not allowed for the class: ' . get_class($this), E_USER_ERROR); } /** * Get singleton instance of the class */ public static function getInstance() { if(!isset($GLOBALS['bxDolClasses'][__CLASS__])) $GLOBALS['bxDolClasses'][__CLASS__] = new BxTemplAcl(); return $GLOBALS['bxDolClasses'][__CLASS__]; } /** * Get necessary condition array to use membership level in search classes * @param $sContentField content table field name * @param $mixedLevelId level ID or array of level IDs * @return array of conditions is returned */ public function getContentByLevelAsCondition($sContentField, $mixedLevelId) { $iLevelId = !is_array($mixedLevelId) ? $mixedLevelId : 0; if (!$iLevelId && is_array($mixedLevelId) && 1 == count($mixedLevelId)) { $a = array_values($mixedLevelId); $iLevelId = array_shift($a); } // unconfirmed if (MEMBERSHIP_ID_UNCONFIRMED == $iLevelId) { return array( 'restriction_sql' => ' AND `sys_accounts`.`email_confirmed` = 0 ', 'restriction' => array (), 'join' => array (), ); } // standard elseif (MEMBERSHIP_ID_STANDARD == $iLevelId) { return array( 'restriction_sql' => ' AND (`tlm`.DateStarts IS NULL OR `tlm`.DateStarts <= NOW()) AND (`tlm`.DateExpires IS NULL OR `tlm`.DateExpires > NOW()) AND `tlm`.`IDMember` IS NULL AND `sys_accounts`.`email_confirmed` != 0 ', 'restriction' => array ( ), 'join' => array ( 'acl_members' => array( 'type' => 'LEFT', 'table' => 'sys_acl_levels_members', 'table_alias' => 'tlm', 'mainField' => $sContentField, 'onField' => 'IDMember', 'joinFields' => array(), ), ), ); } // other levels else { return array( 'restriction_sql' => ' AND (`tlm`.DateStarts IS NULL OR `tlm`.DateStarts <= NOW()) AND (`tlm`.DateExpires IS NULL OR `tlm`.DateExpires > NOW()) AND `sys_accounts`.`email_confirmed` != 0 ', 'restriction' => array ( 'acl_members' => array( 'value' => $mixedLevelId, 'field' => 'IDLevel', 'operator' => is_array($mixedLevelId) ? 'in' : '=', 'table' => 'tlm', ), ), 'join' => array ( 'acl_members' => array( 'type' => 'INNER', 'table' => 'sys_acl_levels_members', 'table_alias' => 'tlm', 'mainField' => $sContentField, 'onField' => 'IDMember', 'joinFields' => array(), ), ), ); } } /** * Get necessary parts of SQL query to use membership levels in other queries * @param $sContentTable content table name * @param $sContentField content table field name * @param $mixedLevelId level ID or array of level IDs * @return array of SQL string parts, for now 'where' part only is returned */ public function getContentByLevelAsSQLPart($sContentTable, $sContentField, $mixedLevelId) { return $this->oDb->getContentByLevelAsSQLPart($sContentTable, $sContentField, $mixedLevelId); } /** * Check if member has one of the provided membership levels * @param $mixedPermissions - integer value (every bit is matched with some membership ID) or an array of membership IDs to check permissions for * @param $iProfileId - profile to check, if it isn't provided or is false then currently logged in profile is used. * @return true if member has privided membership levels, or false if member hasn't. */ public function isMemberLevelInSet($mixedPermissions, $iProfileId = false) { $iPermissions = 0; if(is_array($mixedPermissions)) foreach($mixedPermissions as $iPermissionId) $iPermissions += pow(2, $iPermissionId - 1); else if(is_numeric($mixedPermissions)) $iPermissions = (int)$mixedPermissions; if(!$iPermissions) return false; return ($iPermissions & $this->getMemberLevelBit($iProfileId)); } /** * Get user's membership level bit for bitwise operarions */ public function getMemberLevelBit($iProfileId = 0) { if (!$iProfileId) $iProfileId = bx_get_logged_profile_id(); $aACL = $this->getMemberMembershipInfo($iProfileId); return pow(2, $aACL['id'] - 1); } /** * Checks if a given action is allowed for a given profile and updates action information if the * action is performed. * * @param int $iProfileId ID of a profile that is going to perform an action * @param int $iActionId ID of the action itself * @param boolean $bPerformAction if true, then action information is updated, i.e. action is 'performed' * @return array( * CHECK_ACTION_RESULT => CHECK_ACTION_RESULT_ constant, * CHECK_ACTION_MESSAGE => CHECK_ACTION_MESSAGE_ constant, * CHECK_ACTION_PARAMETER => additional action parameter (string) * ) * * NOTES: * * $aResult[CHECK_ACTION_MESSAGE] contains a message with detailed information about the result, * already processed by the language file * * if $aResult[CHECK_ACTION_RESULT] === CHECK_ACTION_RESULT_ALLOWED then this node contains * an empty string * * The error messages themselves are stored in the language file. Additional variables are * passed to the languages.inc.php function _t_ext() as an array and can be used there in the form of * {0}, {1}, {2} ... * * Additional variables passed to the lang. file on errors (can be used in error messages): * * For all errors: * * $arg0[CHECK_ACTION_LANG_FILE_ACTION] = name of the action * $arg0[CHECK_ACTION_LANG_FILE_MEMBERSHIP]= name of the current membership * * CHECK_ACTION_RESULT_LIMIT_REACHED: * * $arg0[CHECK_ACTION_LANG_FILE_LIMIT] = limit on number of actions allowed for the profile * $arg0[CHECK_ACTION_LANG_FILE_PERIOD] = period that the limit is set for (in hours, 0 if unlimited) * $arg0[CHECK_ACTION_LANG_FILE_PERIOD_RESTART_AT] = time when new period begins, so counter will be reset * * CHECK_ACTION_RESULT_NOT_ALLOWED_BEFORE: * * $arg0[CHECK_ACTION_LANG_FILE_BEFORE] = date/time since when the action is allowed * * CHECK_ACTION_RESULT_NOT_ALLOWED_AFTER: * * $arg0[CHECK_ACTION_LANG_FILE_AFTER] = date/time since when the action is not allowed * * $aResult[CHECK_ACTION_PARAMETER] contains an additional parameter that can be considered * when performing the action (like the number of profiles to show in search result) */ function checkAction($iProfileId, $iActionId, $bPerformAction = false) { $aResult = array(); $aLangFileParams = array(); $iProfileId = (int)$iProfileId; $iActionId = (int)$iActionId; $bPerformAction = $bPerformAction ? true : false; $aMembership = $this->getMemberMembershipInfo($iProfileId); // get current profile's membership information $aLangFileParams[CHECK_ACTION_LANG_FILE_MEMBERSHIP] = _t($aMembership['name']); $aLangFileParams[CHECK_ACTION_LANG_FILE_SITE_EMAIL] = getParam('site_email'); $aAction = $this->oDb->getAction($aMembership['id'], $iActionId); if (!$aAction) bx_trigger_error('Unknown action ID: ' . $iActionId, 2); $aResult[CHECK_ACTION_PARAMETER] = $aAction['additional_param_value']; $aLangFileParams[CHECK_ACTION_LANG_FILE_ACTION] = !empty($aAction['title']) ? _t($aAction['title']) : $aAction['name']; /** * Action is not allowed for the current membership */ if (is_null($aAction['id'])) { $sLangKey = CHECK_ACTION_MESSAGE_NOT_ALLOWED; if (isset($this->_aLevel2MessageMap[$aMembership['id']])) $sLangKey = $this->_aLevel2MessageMap[$aMembership['id']]; $aResult[CHECK_ACTION_RESULT] = CHECK_ACTION_RESULT_NOT_ALLOWED; $aResult[CHECK_ACTION_MESSAGE] = _t_ext($sLangKey, $aLangFileParams); return $aResult; } /** * Check fixed period limitations if present (also for non-members) */ if($aAction['allowed_period_start'] && time() < $aAction['allowed_period_start']) { $aLangFileParams[CHECK_ACTION_LANG_FILE_BEFORE] = bx_time_js($aAction['allowed_period_start'], BX_FORMAT_DATE_TIME); $aResult[CHECK_ACTION_RESULT] = CHECK_ACTION_RESULT_NOT_ALLOWED_BEFORE; $aResult[CHECK_ACTION_MESSAGE] = _t_ext(CHECK_ACTION_MESSAGE_NOT_ALLOWED_BEFORE, $aLangFileParams); return $aResult; } if($aAction['allowed_period_end'] && time() > $aAction['allowed_period_end']) { $aLangFileParams[CHECK_ACTION_LANG_FILE_AFTER] = bx_time_js($aAction['allowed_period_end'], BX_FORMAT_DATE_TIME); $aResult[CHECK_ACTION_RESULT] = CHECK_ACTION_RESULT_NOT_ALLOWED_AFTER; $aResult[CHECK_ACTION_MESSAGE] = _t_ext(CHECK_ACTION_MESSAGE_NOT_ALLOWED_AFTER, $aLangFileParams); return $aResult; } /** * if non-member, allow action without performing further checks */ if ($aMembership['id'] == MEMBERSHIP_ID_NON_MEMBER) { $aResult[CHECK_ACTION_RESULT] = CHECK_ACTION_RESULT_ALLOWED; return $aResult; } /** * Check other limitations (for members only) */ $iAllowedCnt = (int)$aAction['allowed_count']; ///< Number of allowed actions. Unlimited if not specified or 0 $iPeriodLen = (int)$aAction['allowed_period_len']; ///< Period for AllowedCount in hours. If not specified, AllowedCount is treated as total number of actions permitted. if($iAllowedCnt > 0) { $aActionTrack = $this->oDb->getActionTrack($iActionId, $iProfileId); $iActionsLeft = $bPerformAction ? $iAllowedCnt - 1 : $iAllowedCnt; $iValidSince = time(); /** * Member is requesting/performing this action for the first time, * and there is no corresponding record in sys_acl_actions_track table. */ if(!$aActionTrack) { $this->oDb->insertActionTarck($iActionId, $iProfileId, $iActionsLeft, $iValidSince); $aResult[CHECK_ACTION_RESULT] = CHECK_ACTION_RESULT_ALLOWED; return $aResult; } /** * Action has been requested/performed at least once at this point and there is a corresponding record in sys_acl_actions_track table * * Action record in sys_acl_actions_track table is out of date. */ $iPeriodEnd = (int)$aActionTrack['valid_since'] + $iPeriodLen * 3600; //ValidSince is in seconds, PeriodLen is in hours if($iPeriodLen > 0 && $iPeriodEnd < time()) { $this->oDb->updateActionTrack($iActionId, $iProfileId, $iActionsLeft, $iValidSince); $aResult[CHECK_ACTION_RESULT] = CHECK_ACTION_RESULT_ALLOWED; return $aResult; } $iActionsLeft = (int)$aActionTrack['actions_left']; ///< Action record is up to date /** * Action limit reached for now */ if($iActionsLeft <= 0){ $aLangFileParams[CHECK_ACTION_LANG_FILE_LIMIT] = $iAllowedCnt; $aLangFileParams[CHECK_ACTION_LANG_FILE_PERIOD] = $iPeriodLen; $aLangFileParams[CHECK_ACTION_LANG_FILE_PERIOD_RESTART_AT] = bx_time_js($iPeriodEnd); $aResult[CHECK_ACTION_RESULT] = CHECK_ACTION_RESULT_LIMIT_REACHED; $aResult[CHECK_ACTION_MESSAGE] = '<div class="bx-acl-err-msg">' . _t_ext(CHECK_ACTION_MESSAGE_LIMIT_REACHED, $aLangFileParams) . ($iPeriodLen > 0 ? _t_ext(CHECK_ACTION_MESSAGE_MESSAGE_EVERY_PERIOD, $aLangFileParams) : '') . '.</div>'; return $aResult; } if($bPerformAction) { $iActionsLeft--; $this->oDb->updateActionTrack($iActionId, $iProfileId, $iActionsLeft); } } $aResult[CHECK_ACTION_RESULT] = CHECK_ACTION_RESULT_ALLOWED; return $aResult; } /** * Get the number of allowed action * * @param int $iProfileId ID of a profile that is going to perform an action * @param int $iActionId ID of the action itself * @param boolean $bPerformAction if true, then action information is updated, i.e. action is 'performed' * @return int if the action is countable, or true if it's not countable */ function getActionNumberLeft($iProfileId, $iActionId) { $aMembership = $this->getMemberMembershipInfo($iProfileId); // get current profile's membership information $aAction = $this->oDb->getAction($aMembership['id'], $iActionId); $iAllowedCnt = (int)$aAction['allowed_count']; ///< Number of allowed actions. Unlimited if not specified or 0 if($iAllowedCnt > 0) { $aActionTrack = $this->oDb->getActionTrack($iActionId, $iProfileId); if(!$aActionTrack) return $iAllowedCnt; return (int)$aActionTrack['actions_left']; } return true; } /** * Get the list of existing memberships * * @param bool $bPurchasableOnly if true, fetches only purchasable memberships; 'purchasable' here means that: * - MemLevels.Purchasable = 'yes' * - MemLevels.Active = 'yes' * - there is at least one pricing option for the membership * @return array( membershipID_1 => membershipName_1, membershipID_2 => membershipName_2, ...) if no such memberships, then just array() */ function getMemberships($bPurchasableOnly = false, $bActiveOnly = false, $isTranslate = true, $bFilterOutSystemAutomaticLevels = false) { $sType = 'all_pair'; if($bPurchasableOnly) $sType = 'all_active_purchasble_pair'; else if($bActiveOnly) $sType = 'all_active_pair'; $aLevels = array(); $this->oDb->getLevels(array('type' => $sType), $aLevels, false); if ($isTranslate) foreach ($aLevels as $k => $s) $aLevels[$k] = _t($s); if ($bFilterOutSystemAutomaticLevels) { unset($aLevels[MEMBERSHIP_ID_NON_MEMBER]); unset($aLevels[MEMBERSHIP_ID_ACCOUNT]); unset($aLevels[MEMBERSHIP_ID_UNCONFIRMED]); unset($aLevels[MEMBERSHIP_ID_PENDING]); unset($aLevels[MEMBERSHIP_ID_SUSPENDED]); } return $aLevels; } function getMembershipsBy($aParams) { $aLevels = array(); $this->oDb->getLevels($aParams, $aLevels, false); return $aLevels; } /** * Get info about a given membership * * @param int $iLevelId membership to get info about * @return array( * 'id' => ID, * 'name' => name, * 'icon' => icon, * 'description' => description, * 'active' => active, * 'purchasable' => purchasable, * 'removable' => removable * 'quota_size' => quota size, * 'quota_number' => quota number, * 'quota_max_file_size' => quota max file size * ) */ function getMembershipInfo($iLevelId) { $aLevel = array(); $this->oDb->getLevels(array('type' => 'by_id', 'value' => $iLevelId), $aLevel, false); return $aLevel; } /** * Retrieves information about membership for a given profile at a given moment. * * If there are no memberships purchased/assigned to the * given profile or all of them have expired at the given point, * the profile is assumed to be a standard profile, and the function * returns information about the Standard membership. This will * also happen if a profile wasnt actually registered in the database * at that point - the function will still return info about Standard * membership, not the Non-member one. * * If there is no profile with the given $iProfileId, * the function returns information about the Non-member or Authenticated * predefined membership. * * The Standard, Authenticated and Non-member memberships have their * DateStarts and DateExpires attributes set to NULL. * * @param int $iProfileId ID of a profile to get info about * @param int $time specifies the time to use when determining membership; if not specified, the function takes the current time * @return array( * 'id' => membership id, * 'name' => membership name, * 'date_starts' => (UNIX timestamp) date/time purchased, * 'date_expires' => (UNIX timestamp) date/time expires * ) */ function getMemberMembershipInfo($iProfileId, $iTime = 0, $bClearCache = 0) { $aMembershipCurrent = $this->getMemberMembershipInfoCurrent($iProfileId, $iTime, $bClearCache); if (isset($this->_aStandardMemberships[$aMembershipCurrent['id']])) return $aMembershipCurrent; $aMembership = $aMembershipCurrent; do { $iDateStarts = $aMembership['date_starts']; $aMembership = $this->getMemberMembershipInfoCurrent($iProfileId, ((int)$iDateStarts < 1 ? 0 : $iDateStarts - 1), $bClearCache); } while($aMembership['id'] == $aMembershipCurrent['id'] && (int)$aMembership['date_starts']); $aMembership = $aMembershipCurrent; do { $iDateExpires = $aMembership['date_expires']; $aMembership = $this->getMemberMembershipInfoCurrent($iProfileId, $iDateExpires, $bClearCache); } while($aMembership['id'] == $aMembershipCurrent['id'] && (int)$aMembership['date_expires']); $aMembershipCurrent['date_starts'] = $iDateStarts; $aMembershipCurrent['date_expires'] = $iDateExpires; return $aMembershipCurrent; } /** * Set a membership for a profile * * @param int $iProfileId profile that is going to get the membership * @param int $iLevelId membership that is going to be assigned to the profile * if $iLevelId == MEMBERSHIP_ID_STANDARD then $days and $bStartsNow parameters are not used, * so Standard membership is always set immediately and `forever` * @param mixed $mixedPeriod number of Days to set membership for or an array with 'period'-'period unit' pair. If number or 'period' in pair equal 0, then the membership is set forever * @param boolean $bStartsNow if true, the membership will start immediately if false, the membership will start after the current membership expires * @return boolean true in case of success, false in case of failure */ function setMembership($iProfileId, $iLevelId, $mixedPeriod = 0, $bStartsNow = false, $sTransactionId = '') { $iProfileId = (int)$iProfileId; $iLevelId = (int)$iLevelId; $bStartsNow = $bStartsNow ? true : false; if (!$iProfileId) $iProfileId = -1; if (empty($sTransactionId)) $sTransactionId = 'NULL'; // check if profile exists if(($sProfileEmail = BxDolProfileQuery::getInstance()->getEmailById($iProfileId)) === false) return false; // check if membership exists $aLevel = array(); $this->oDb->getLevels(array('type' => 'by_id', 'value' => $iLevelId), $aLevel, false); if(empty($aLevel) || !is_array($aLevel)) return false; if($iLevelId == MEMBERSHIP_ID_NON_MEMBER) return false; $aMembershipCurrent = $this->getMemberMembershipInfo($iProfileId); $aMembershipLatest = $this->getMemberMembershipInfoLatest($iProfileId); // setting Standard membership level if ($iLevelId == MEMBERSHIP_ID_STANDARD) { if ($aMembershipCurrent['id'] == MEMBERSHIP_ID_STANDARD) return true; // delete present and future memberships $bResult = $this->oDb->deleteLevelByProfileId($iProfileId); if($bResult) { $this->oDb->cleanMemory('BxDolAclQuery::getLevelCurrent' . $iProfileId . time()); unset(self::$_aCacheData[$iProfileId . '_0']); } return $bResult; } if ((is_numeric($mixedPeriod) && (int)$mixedPeriod < 0) || (is_array($mixedPeriod) && (!isset($mixedPeriod['period']) || $mixedPeriod['period'] < 0))) return false; /* * Make the membership starts after the latest membership expires or starts immediately * if latest membership is lifetime membership or immediate start was requested. */ $iDateStarts = time(); if ($bStartsNow || empty($aMembershipLatest['date_expires'])) { // Delete any profile's membership level and actions traces $this->oDb->deleteLevelByProfileId($iProfileId, true); $this->oDb->clearActionsTracksForMember($iProfileId); $this->oDb->cleanMemory('BxDolAclQuery::getLevelCurrent' . $iProfileId . time()); unset(self::$_aCacheData[$iProfileId . '_0']); } else $iDateStarts = $aMembershipLatest['date_expires']; // set lifetime membership if 0 days is used. if(is_numeric($mixedPeriod)) $mixedPeriod = array('period' => (int)$mixedPeriod, 'period_unit' => MEMBERSHIP_PERIOD_UNIT_DAY); if(!$this->oDb->insertLevelByProfileId($iProfileId, $iLevelId, $iDateStarts, $mixedPeriod, $sTransactionId)) return false; // raise membership alert bx_alert('profile', 'set_membership', '', $iProfileId, array( 'mlevel'=> $iLevelId, 'period' => $mixedPeriod['period'], 'period_unit' => $mixedPeriod['period_unit'], 'starts_now' => $bStartsNow, 'txn_id' => $sTransactionId )); // audit $aDataForAudit = array(); if (!empty($aMembershipCurrent)) $aDataForAudit = array('new_membership_level' => _t($aLevel['name']), 'old_membership_level' => _t($aMembershipCurrent['name'])); BxDolProfile::getInstance($iProfileId)->doAudit('_sys_audit_action_set_membership', $aDataForAudit); // Send notification $aTemplate = BxDolEmailTemplates::getInstance()->parseTemplate('t_MemChanged', array('membership_level' => _t($aLevel['name'])), 0, $iProfileId); if ($aTemplate) sendMail($sProfileEmail, $aTemplate['Subject'], $aTemplate['Body']); return true; } function unsetMembership($iProfileId, $iLevelId, $sTransactionId) { return $this->oDb->deleteLevelBy(array( 'IDMember' => $iProfileId, 'IDLevel' => $iLevelId, 'TransactionID' => $sTransactionId )); } /** * get action id by module and name * @param $sAction action name * @param $sModule module name * @param $aActions array of actions from sys_acl_actions table, with default array keys (starting from 0) and text values */ function getMembershipActionId($sAction, $sModule) { $this->oDb->getActions(array('type' => 'by_names_and_module', 'value' => $sAction, 'module' => $sModule), $aActions, false); if (count($aActions) > 1) trigger_error('Duplicate action - name:' . $sAction . ', module:' . $sModule, E_USER_ERROR); $aAction = array_pop($aActions); return $aAction['id']; } function getExpirationLetter($iProfileId, $sLevelName, $iLevelExpireDays ) { $iProfileId = (int)$iProfileId; if(!$iProfileId) return false; $oProfileQuery = BxDolProfileQuery::getInstance(); $sProfileEmail = $oProfileQuery->getEmailById($iProfileId); $aPlus = array( 'membership_name' => _t($sLevelName), 'expire_days' => $iLevelExpireDays, 'page_url' => BxDolRequest::serviceExists('bx_acl', 'get_view_url') ? BxDolService::call('bx_acl', 'get_view_url') : '#' ); $aTemplate = BxDolEmailTemplates::getInstance()->parseTemplate('t_MemExpiration', $aPlus, 0, $iProfileId); $iResult = $aTemplate && sendMail($sProfileEmail, $aTemplate['Subject'], $aTemplate['Body'], $iProfileId, $aPlus); return !empty($iResult); } /** * clear expired membership levels */ public function maintenance() { return $this->oDb->maintenance(); } protected function getMemberMembershipInfoCurrent($iProfileId, $iTime = 0, $bClearCache = 0) { $sKey = $iProfileId . '_' . $iTime; if ($bClearCache && isset(self::$_aCacheData[$sKey])) unset(self::$_aCacheData[$sKey]); elseif (array_key_exists($sKey, self::$_aCacheData) && !defined('BX_DOL_INSTALL') && !defined('BX_DOL_CRON_EXECUTE')) return self::$_aCacheData[$sKey]; $aMemLevel = false; do { // get profile status $oProfile = BxDolProfile::getInstance($iProfileId); $aProfileInfo = $oProfile ? $oProfile->getInfo() : false; $sProfileStatus = $aProfileInfo ? $aProfileInfo['status'] : false; $sProfileType = $aProfileInfo ? $aProfileInfo['type'] : false; // account profile if($sProfileType == 'system') { $aMemLevel = $this->oDb->getLevelByIdCached(MEMBERSHIP_ID_ACCOUNT); if (!$aMemLevel) trigger_error ('Standard member level is missing: MEMBERSHIP_ID_ACCOUNT', E_USER_ERROR); break; } // check if account is unconfirmed, every account's profile is unconfirmed if account is unconfirmed $oAccount = $aProfileInfo ? BxDolAccount::getInstance($aProfileInfo['account_id']) : false; if ($oAccount && !$oAccount->isConfirmed()) { $aMemLevel = $this->oDb->getLevelByIdCached(MEMBERSHIP_ID_UNCONFIRMED); if (!$aMemLevel) trigger_error ('Standard member level is missing: MEMBERSHIP_ID_UNCONFIRMED', E_USER_ERROR); break; } // profile is not active, so return standard memberships according to profile status if (false === $sProfileStatus || BX_PROFILE_STATUS_ACTIVE != $sProfileStatus) { if (!isset($this->_aProfileStatus2LevelMap[$sProfileStatus])) $iLevelId = MEMBERSHIP_ID_NON_MEMBER; // if there is no profile status - then it isn't member else $iLevelId = $this->_aProfileStatus2LevelMap[$sProfileStatus]; // get member level id which associated with every non-active status $aMemLevel = $this->oDb->getLevelByIdCached($iLevelId); if (!$aMemLevel) trigger_error ('Standard member level is missing: ' . $iLevelId, E_USER_ERROR); break; } // profile is active get memebr level from profile $aMemLevel = $this->oDb->getLevelCurrent((int)$iProfileId, $iTime); // There are no purchased/assigned memberships for the profile or all of them have expired. // In this case the profile is assumed to have Standard membership. if (!$aMemLevel || is_null($aMemLevel['id'])) { $aMemLevel = $this->oDb->getLevelByIdCached(MEMBERSHIP_ID_STANDARD); if (!$aMemLevel) trigger_error ('Standard member level is missing: ' . MEMBERSHIP_ID_NON_MEMBER, E_USER_ERROR); break; } } while (0); return (self::$_aCacheData[$sKey] = $aMemLevel); } protected function getMemberMembershipInfoLatest($iProfileId, $iTime = 0, $bClearCache = 0) { $aMembershipCurrent = $this->getMemberMembershipInfoCurrent($iProfileId, $iTime, $bClearCache); if (isset($this->_aStandardMemberships[$aMembershipCurrent['id']])) return $aMembershipCurrent; $aMembership = $aMembershipCurrent; while ($aMembership['id'] != MEMBERSHIP_ID_STANDARD) { $aMembershipLast = $aMembership; if(!isset($aMembership['date_expires']) || (int)$aMembership['date_expires'] == 0) break; $aMembership = $this->getMemberMembershipInfoCurrent($iProfileId, $aMembership['date_expires'], $bClearCache); } return $aMembershipLast; } public function onProfileDelete ($iProfileId) { return $this->oDb->deleteLevelByProfileId($iProfileId, true); } } function checkAction($iProfileId, $iActionId, $bPerformAction = false) { return BxDolAcl::getInstance()->checkAction($iProfileId, $iActionId, $bPerformAction); } function checkActionModule($iProfileId, $sActionName, $sModuleName, $bPerformAction = false) { $oACL = BxDolAcl::getInstance(); $iActionId = $oACL->getMembershipActionId($sActionName, $sModuleName); if (!$iActionId) bx_trigger_error("Unknown action: '$sActionName' in module '$sModuleName'", 1); return $oACL->checkAction($iProfileId, $iActionId, $bPerformAction); } function getActionNumberLeftModule($iProfileId, $sActionName, $sModuleName) { $oACL = BxDolAcl::getInstance(); $iActionId = $oACL->getMembershipActionId($sActionName, $sModuleName); if (!$iActionId) bx_trigger_error("Unknown action: '$sActionName' in module '$sModuleName'", 1); return $oACL->getActionNumberLeft($iProfileId, $iActionId); } /** @} */
unaio/una
inc/classes/BxDolAcl.php
PHP
mit
35,178
import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import { ViewPropTypes, Text, View } from 'react-native'; import Icon from 'react-native-vector-icons/MaterialCommunityIcons'; import getStyles from './styles'; export default class DefaultMarker extends PureComponent { static propTypes = { markerStyle: ViewPropTypes.style, enabled: PropTypes.bool, currentValue: PropTypes.number, panHandlers: PropTypes.object, icon: PropTypes.bool, iconName: PropTypes.string, disabledIconName: PropTypes.string, iconColor: PropTypes.string, disabledIconColor: PropTypes.string, }; static defaultProps = { icon: false, }; renderDefault = () => { const styles = getStyles(this.props); const iconStyles = [ styles.icon, this.props.enabled ? styles.enabled : styles.disabled, ]; return ( <View style={iconStyles} /> ); }; renderIcon = () => { const styles = getStyles(this.props); const iconStyles = [ styles.icon, this.props.enabled ? styles.enabled : styles.disabled, ]; return ( <Icon size={16} style={iconStyles} selectable={false} name={this.props.enabled ? this.props.iconName : this.props.disabledIconName} color="white", backgroundColor={this.props.enabled ? this.props.iconColor : this.props.disabledIconColor} /> ); }; render() { const styles = getStyles(this.props); const rootStyles = [ styles.markerStyle, this.props.markerStyle, ]; const { currentValue } = this.props; return ( <View style={rootStyles} {...this.props.panHandlers} hitSlop={{ top: 30, bottom: 30, left: 30, right: 30 }} pointerEvents="box-only" > {this.props.icon ? this.renderIcon() : this.renderDefault()} <Text>{currentValue}</Text> </View> ); } }
joshjconlin/react-native-multi-slider-1
DefaultMarker/index.js
JavaScript
mit
1,946
/////////////////////////////////////////////////////////////////////////////// // Name: generic/vlbox.cpp // Purpose: implementation of wxVListBox // Author: Vadim Zeitlin // Modified by: // Created: 31.05.03 // RCS-ID: $Id: vlbox.cpp,v 1.22.2.1 2006/01/18 09:50:37 JS Exp $ // Copyright: (c) 2003 Vadim Zeitlin <vadim@wxwindows.org> // License: wxWindows license /////////////////////////////////////////////////////////////////////////////// // ============================================================================ // declarations // ============================================================================ // ---------------------------------------------------------------------------- // headers // ---------------------------------------------------------------------------- // For compilers that support precompilation, includes "wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #if wxUSE_LISTBOX #ifndef WX_PRECOMP #include "wx/settings.h" #include "wx/dcclient.h" #endif //WX_PRECOMP #include "wx/vlbox.h" #include "wx/dcbuffer.h" #include "wx/selstore.h" #include "wx/bitmap.h" // ---------------------------------------------------------------------------- // event tables // ---------------------------------------------------------------------------- BEGIN_EVENT_TABLE(wxVListBox, wxVScrolledWindow) EVT_PAINT(wxVListBox::OnPaint) EVT_KEY_DOWN(wxVListBox::OnKeyDown) EVT_LEFT_DOWN(wxVListBox::OnLeftDown) EVT_LEFT_DCLICK(wxVListBox::OnLeftDClick) END_EVENT_TABLE() // ============================================================================ // implementation // ============================================================================ IMPLEMENT_ABSTRACT_CLASS(wxVListBox, wxVScrolledWindow) // ---------------------------------------------------------------------------- // wxVListBox creation // ---------------------------------------------------------------------------- // due to ABI compatibility reasons, we need to declare double-buffer // outside the class static wxBitmap* gs_doubleBuffer = NULL; void wxVListBox::Init() { m_current = m_anchor = wxNOT_FOUND; m_selStore = NULL; } bool wxVListBox::Create(wxWindow *parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style, const wxString& name) { style |= wxWANTS_CHARS | wxFULL_REPAINT_ON_RESIZE; if ( !wxVScrolledWindow::Create(parent, id, pos, size, style, name) ) return false; if ( style & wxLB_MULTIPLE ) m_selStore = new wxSelectionStore; // make sure the native widget has the right colour since we do // transparent drawing by default SetBackgroundColour(GetBackgroundColour()); m_colBgSel = wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHT); // flicker-free drawing requires this SetBackgroundStyle(wxBG_STYLE_CUSTOM); return true; } wxVListBox::~wxVListBox() { delete m_selStore; delete gs_doubleBuffer; gs_doubleBuffer = NULL; } void wxVListBox::SetItemCount(size_t count) { if ( m_selStore ) { // tell the selection store that our number of items has changed m_selStore->SetItemCount(count); } SetLineCount(count); } // ---------------------------------------------------------------------------- // selection handling // ---------------------------------------------------------------------------- bool wxVListBox::IsSelected(size_t line) const { return m_selStore ? m_selStore->IsSelected(line) : (int)line == m_current; } bool wxVListBox::Select(size_t item, bool select) { wxCHECK_MSG( m_selStore, false, _T("Select() may only be used with multiselection listbox") ); wxCHECK_MSG( item < GetItemCount(), false, _T("Select(): invalid item index") ); bool changed = m_selStore->SelectItem(item, select); if ( changed ) { // selection really changed RefreshLine(item); } DoSetCurrent(item); return changed; } bool wxVListBox::SelectRange(size_t from, size_t to) { wxCHECK_MSG( m_selStore, false, _T("SelectRange() may only be used with multiselection listbox") ); // make sure items are in correct order if ( from > to ) { size_t tmp = from; from = to; to = tmp; } wxCHECK_MSG( to < GetItemCount(), false, _T("SelectRange(): invalid item index") ); wxArrayInt changed; if ( !m_selStore->SelectRange(from, to, true, &changed) ) { // too many items have changed, we didn't record them in changed array // so we have no choice but to refresh everything between from and to RefreshLines(from, to); } else // we've got the indices of the changed items { const size_t count = changed.GetCount(); if ( !count ) { // nothing changed return false; } // refresh just the lines which have really changed for ( size_t n = 0; n < count; n++ ) { RefreshLine(changed[n]); } } // something changed return true; } bool wxVListBox::DoSelectAll(bool select) { wxCHECK_MSG( m_selStore, false, _T("SelectAll may only be used with multiselection listbox") ); size_t count = GetItemCount(); if ( count ) { wxArrayInt changed; if ( !m_selStore->SelectRange(0, count - 1, select) || !changed.IsEmpty() ) { Refresh(); // something changed return true; } } return false; } bool wxVListBox::DoSetCurrent(int current) { wxASSERT_MSG( current == wxNOT_FOUND || (current >= 0 && (size_t)current < GetItemCount()), _T("wxVListBox::DoSetCurrent(): invalid item index") ); if ( current == m_current ) { // nothing to do return false; } if ( m_current != wxNOT_FOUND ) RefreshLine(m_current); m_current = current; if ( m_current != wxNOT_FOUND ) { // if the line is not visible at all, we scroll it into view but we // don't need to refresh it -- it will be redrawn anyhow if ( !IsVisible(m_current) ) { ScrollToLine(m_current); } else // line is at least partly visible { // it is, indeed, only partly visible, so scroll it into view to // make it entirely visible while ( (size_t)m_current == GetLastVisibleLine() && ScrollToLine(GetVisibleBegin()+1) ); // but in any case refresh it as even if it was only partly visible // before we need to redraw it entirely as its background changed RefreshLine(m_current); } } return true; } void wxVListBox::SendSelectedEvent() { wxASSERT_MSG( m_current != wxNOT_FOUND, _T("SendSelectedEvent() shouldn't be called") ); wxCommandEvent event(wxEVT_COMMAND_LISTBOX_SELECTED, GetId()); event.SetEventObject(this); event.SetInt(m_current); (void)GetEventHandler()->ProcessEvent(event); } void wxVListBox::SetSelection(int selection) { wxCHECK_RET( selection == wxNOT_FOUND || (selection >= 0 && (size_t)selection < GetItemCount()), _T("wxVListBox::SetSelection(): invalid item index") ); if ( HasMultipleSelection() ) { Select(selection); m_anchor = selection; } DoSetCurrent(selection); } size_t wxVListBox::GetSelectedCount() const { return m_selStore ? m_selStore->GetSelectedCount() : m_current == wxNOT_FOUND ? 0 : 1; } int wxVListBox::GetFirstSelected(unsigned long& cookie) const { cookie = 0; return GetNextSelected(cookie); } int wxVListBox::GetNextSelected(unsigned long& cookie) const { wxCHECK_MSG( m_selStore, wxNOT_FOUND, _T("GetFirst/NextSelected() may only be used with multiselection listboxes") ); while ( cookie < GetItemCount() ) { if ( IsSelected(cookie++) ) return cookie - 1; } return wxNOT_FOUND; } // ---------------------------------------------------------------------------- // wxVListBox appearance parameters // ---------------------------------------------------------------------------- void wxVListBox::SetMargins(const wxPoint& pt) { if ( pt != m_ptMargins ) { m_ptMargins = pt; Refresh(); } } void wxVListBox::SetSelectionBackground(const wxColour& col) { m_colBgSel = col; } // ---------------------------------------------------------------------------- // wxVListBox painting // ---------------------------------------------------------------------------- wxCoord wxVListBox::OnGetLineHeight(size_t line) const { return OnMeasureItem(line) + 2*m_ptMargins.y; } void wxVListBox::OnDrawSeparator(wxDC& WXUNUSED(dc), wxRect& WXUNUSED(rect), size_t WXUNUSED(n)) const { } void wxVListBox::OnDrawBackground(wxDC& dc, const wxRect& rect, size_t n) const { // we need to render selected and current items differently const bool isSelected = IsSelected(n), isCurrent = IsCurrent(n); if ( isSelected || isCurrent ) { if ( isSelected ) { dc.SetBrush(wxBrush(m_colBgSel, wxSOLID)); } else // !selected { dc.SetBrush(*wxTRANSPARENT_BRUSH); } dc.SetPen(*(isCurrent ? wxBLACK_PEN : wxTRANSPARENT_PEN)); dc.DrawRectangle(rect); } //else: do nothing for the normal items } void wxVListBox::OnPaint(wxPaintEvent& WXUNUSED(event)) { // If size is larger, recalculate double buffer bitmap wxSize clientSize = GetClientSize(); if ( !gs_doubleBuffer || clientSize.x > gs_doubleBuffer->GetWidth() || clientSize.y > gs_doubleBuffer->GetHeight() ) { delete gs_doubleBuffer; gs_doubleBuffer = new wxBitmap(clientSize.x+25,clientSize.y+25); } wxBufferedPaintDC dc(this,*gs_doubleBuffer); // the update rectangle wxRect rectUpdate = GetUpdateClientRect(); // Fill it with background colour dc.SetBrush(GetBackgroundColour()); dc.Clear(); // the bounding rectangle of the current line wxRect rectLine; rectLine.width = clientSize.x; // iterate over all visible lines const size_t lineMax = GetLastVisibleLine(); for ( size_t line = GetFirstVisibleLine(); line <= lineMax; line++ ) { const wxCoord hLine = OnGetLineHeight(line); rectLine.height = hLine; // and draw the ones which intersect the update rect if ( rectLine.Intersects(rectUpdate) ) { // don't allow drawing outside of the lines rectangle wxDCClipper clip(dc, rectLine); wxRect rect = rectLine; OnDrawBackground(dc, rect, line); OnDrawSeparator(dc, rect, line); rect.Deflate(m_ptMargins.x, m_ptMargins.y); OnDrawItem(dc, rect, line); } else // no intersection { if ( rectLine.GetTop() > rectUpdate.GetBottom() ) { // we are already below the update rect, no need to continue // further break; } //else: the next line may intersect the update rect } rectLine.y += hLine; } } // ============================================================================ // wxVListBox keyboard/mouse handling // ============================================================================ void wxVListBox::DoHandleItemClick(int item, int flags) { // has anything worth telling the client code about happened? bool notify = false; if ( HasMultipleSelection() ) { // select the iteem clicked? bool select = true; // NB: the keyboard interface we implement here corresponds to // wxLB_EXTENDED rather than wxLB_MULTIPLE but this one makes more // sense IMHO if ( flags & ItemClick_Shift ) { if ( m_current != wxNOT_FOUND ) { if ( m_anchor == wxNOT_FOUND ) m_anchor = m_current; select = false; // only the range from the selection anchor to new m_current // must be selected if ( DeselectAll() ) notify = true; if ( SelectRange(m_anchor, item) ) notify = true; } //else: treat it as ordinary click/keypress } else // Shift not pressed { m_anchor = item; if ( flags & ItemClick_Ctrl ) { select = false; if ( !(flags & ItemClick_Kbd) ) { Toggle(item); // the status of the item has definitely changed notify = true; } //else: Ctrl-arrow pressed, don't change selection } //else: behave as in single selection case } if ( select ) { // make the clicked item the only selection if ( DeselectAll() ) notify = true; if ( Select(item) ) notify = true; } } // in any case the item should become the current one if ( DoSetCurrent(item) ) { if ( !HasMultipleSelection() ) { // this has also changed the selection for single selection case notify = true; } } if ( notify ) { // notify the user about the selection change SendSelectedEvent(); } //else: nothing changed at all } // ---------------------------------------------------------------------------- // keyboard handling // ---------------------------------------------------------------------------- void wxVListBox::OnKeyDown(wxKeyEvent& event) { // flags for DoHandleItemClick() int flags = ItemClick_Kbd; int current; switch ( event.GetKeyCode() ) { case WXK_HOME: current = 0; break; case WXK_END: current = GetLineCount() - 1; break; case WXK_DOWN: if ( m_current == (int)GetLineCount() - 1 ) return; current = m_current + 1; break; case WXK_UP: if ( m_current == wxNOT_FOUND ) current = GetLineCount() - 1; else if ( m_current != 0 ) current = m_current - 1; else // m_current == 0 return; break; case WXK_PAGEDOWN: case WXK_NEXT: PageDown(); current = GetFirstVisibleLine(); break; case WXK_PAGEUP: case WXK_PRIOR: if ( m_current == (int)GetFirstVisibleLine() ) { PageUp(); } current = GetFirstVisibleLine(); break; case WXK_SPACE: // hack: pressing space should work like a mouse click rather than // like a keyboard arrow press, so trick DoHandleItemClick() in // thinking we were clicked flags &= ~ItemClick_Kbd; current = m_current; break; #ifdef __WXMSW__ case WXK_TAB: // Since we are using wxWANTS_CHARS we need to send navigation // events for the tabs on MSW { wxNavigationKeyEvent ne; ne.SetDirection(!event.ShiftDown()); ne.SetCurrentFocus(this); ne.SetEventObject(this); GetParent()->GetEventHandler()->ProcessEvent(ne); } // fall through to default #endif default: event.Skip(); current = 0; // just to silent the stupid compiler warnings wxUnusedVar(current); return; } if ( event.ShiftDown() ) flags |= ItemClick_Shift; if ( event.ControlDown() ) flags |= ItemClick_Ctrl; DoHandleItemClick(current, flags); } // ---------------------------------------------------------------------------- // wxVListBox mouse handling // ---------------------------------------------------------------------------- void wxVListBox::OnLeftDown(wxMouseEvent& event) { SetFocus(); int item = HitTest(event.GetPosition()); if ( item != wxNOT_FOUND ) { int flags = 0; if ( event.ShiftDown() ) flags |= ItemClick_Shift; // under Mac Apple-click is used in the same way as Ctrl-click // elsewhere #ifdef __WXMAC__ if ( event.MetaDown() ) #else if ( event.ControlDown() ) #endif flags |= ItemClick_Ctrl; DoHandleItemClick(item, flags); } } void wxVListBox::OnLeftDClick(wxMouseEvent& eventMouse) { int item = HitTest(eventMouse.GetPosition()); if ( item != wxNOT_FOUND ) { // if item double-clicked was not yet selected, then treat // this event as a left-click instead if ( item == m_current ) { wxCommandEvent event(wxEVT_COMMAND_LISTBOX_DOUBLECLICKED, GetId()); event.SetEventObject(this); event.SetInt(item); (void)GetEventHandler()->ProcessEvent(event); } else { OnLeftDown(eventMouse); } } } // ---------------------------------------------------------------------------- // use the same default attributes as wxListBox // ---------------------------------------------------------------------------- #include "wx/listbox.h" //static wxVisualAttributes wxVListBox::GetClassDefaultAttributes(wxWindowVariant variant) { return wxListBox::GetClassDefaultAttributes(variant); } #endif
SickheadGames/Torsion
code/wxWidgets/src/generic/vlbox.cpp
C++
mit
18,240
// // Load the AWS SDK for Node.js // var i = console.log(Math.round(new Date().getTime()/1000.0).toFixed(1)); // var AWS = require('aws-sdk'); // var path = require('path'); // var fs = require('fs'); // // // Load credentials and set region from JSON file // AWS.config.loadFromPath("/Users/jorge/Documents/javascipt_workspace/docking_station/uploader/config.json"); // AWS.config.update({endpoint: "https://dynamodb.sa-east-1.amazonaws.com"}); // // var DynamoDBManager = function () { }; // // DynamoDBManager.uploadToDynamo = function (sensor, file_path, table) { // var docClient = new AWS.DynamoDB.DocumentClient(); // var information = fs.readFileSync(file_path, 'utf-8'); // console.log("INFORMACION: " + information); // var params = { // TableName:table, // Item:{ // "sensor":sensor, // "timeStamp":file_path.split("/").pop(), // "data":information // } // }; // docClient.put(params, function(err, data) { // if (err) { // console.error("Unable to add item. Error JSON:", JSON.stringify(err, null, 2)); // } else { // console.log("Added item:", JSON.stringify(data, null, 2)); // } // }); // console.log(Math.round(new Date().getTime()/1000.0) - i); // }; // // DynamoDBManager.getItemFromDynamo = function (sensor, timestamp, bucket) { // // } // // // module.exports = DynamoDBManager;
PulseraMartin/docking_station
uploader/dynamoDBManager.js
JavaScript
mit
1,405
<?php namespace c2g\Base; /** * FoundationPile base class * * @author Thurairajah Thujeevan <thujee@gmail.com> */ class FoundationPile extends Pile { const LIMIT = 13; const NAME = 'Foundation'; /** * data member of this class, which holds the base card * when this pile is circular * @var Card */ static $baseCard; /** * Constructor function which initializes foundation pile with * pile name and the cards limit * Foundation piles are not fanned usually * * @param boolean $circular true if this is circular pile */ public function __construct($circular) { parent::__construct(self::LIMIT, self::NAME); $this->circular = $circular; $this->fanned = FALSE; } /** * Specialied version of Pile's can add function, control the restrictions * of adding cards to this pile * * @param \c2g\Base\Card $card card to be added to this pile * @param \c2g\Base\Pile $src the pile from which the card comes * @return boolean */ public function canAdd(Card $card, Pile $src = NULL) { if ($this->count() == $this->limit) { // pile is full return FALSE; } if (!$this->isEmpty() && !$card->isSameSuit($this->top())) { // doesn't belong to same suit return FALSE; } // pile is not circular // pile count is zero // card is not A if (!$this->circular && $this->isEmpty() && !$card->isFirstInRank()) { return FALSE; } // circular pile // has at least one card - implies, should have baseCard // topcard is K and card to be inserted is A if ($this->circular && !$this->isEmpty() && $this->top()->isLastInRank() && $card->isFirstInRank()) { return TRUE; } // can be circular or non circular if (!$this->isEmpty() && !$card->isGreaterThanByOne($this->top())) { return FALSE; } // circular pile // empty pile // basecard exists // card to be added not as equal as basecard in rank if ($this->circular && $this->isEmpty() && static::$baseCard && !$card->isEqual(static::$baseCard)) { return FALSE; } return TRUE; } /** * Foundation pile usually doesn't allow to remove cards * * @param \c2g\Base\Pile $dest Pile to which the card to be added * @return boolean */ public function canRemove(Pile $dest = NULL) { return FALSE; } /** * overridden function of Pile's add card * Since foundation piles can be circular sometimes * * @param \c2g\Base\Card $card * @return Pile */ public function addCard(Card $card) { if ($this->circular && $this->isEmpty()) { static::$baseCard = $card; } return parent::addCard(!$card->isFacedUp() ? $card->flip() : $card); } }
thujeevan/c2g
src/Base/FoundationPile.php
PHP
mit
3,047
using System; class SayHello { static void Main() { string name = Console.ReadLine(); printName(name); } static void printName(string name) { Console.WriteLine("Hello, {0}!", name); } }
ndvalkov/TelerikAcademy2016
Homework/CSharp-Part-2/03. Methods/SayHello.cs
C#
mit
235
// Copyright (c) 2011-2013 The BeCoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "addresstablemodel.h" #include "guiutil.h" #include "walletmodel.h" #include "base58.h" #include "wallet/wallet.h" #include <boost/foreach.hpp> #include <QFont> #include <QDebug> const QString AddressTableModel::Send = "S"; const QString AddressTableModel::Receive = "R"; struct AddressTableEntry { enum Type { Sending, Receiving, Hidden /* QSortFilterProxyModel will filter these out */ }; Type type; QString label; QString address; AddressTableEntry() {} AddressTableEntry(Type type, const QString &label, const QString &address): type(type), label(label), address(address) {} }; struct AddressTableEntryLessThan { bool operator()(const AddressTableEntry &a, const AddressTableEntry &b) const { return a.address < b.address; } bool operator()(const AddressTableEntry &a, const QString &b) const { return a.address < b; } bool operator()(const QString &a, const AddressTableEntry &b) const { return a < b.address; } }; /* Determine address type from address purpose */ static AddressTableEntry::Type translateTransactionType(const QString &strPurpose, bool isMine) { AddressTableEntry::Type addressType = AddressTableEntry::Hidden; // "refund" addresses aren't shown, and change addresses aren't in mapAddressBook at all. if (strPurpose == "send") addressType = AddressTableEntry::Sending; else if (strPurpose == "receive") addressType = AddressTableEntry::Receiving; else if (strPurpose == "unknown" || strPurpose == "") // if purpose not set, guess addressType = (isMine ? AddressTableEntry::Receiving : AddressTableEntry::Sending); return addressType; } // Private implementation class AddressTablePriv { public: CWallet *wallet; QList<AddressTableEntry> cachedAddressTable; AddressTableModel *parent; AddressTablePriv(CWallet *wallet, AddressTableModel *parent): wallet(wallet), parent(parent) {} void refreshAddressTable() { cachedAddressTable.clear(); { LOCK(wallet->cs_wallet); BOOST_FOREACH(const PAIRTYPE(CTxDestination, CAddressBookData)& item, wallet->mapAddressBook) { const CBeCoinAddress& address = item.first; bool fMine = IsMine(*wallet, address.Get()); AddressTableEntry::Type addressType = translateTransactionType( QString::fromStdString(item.second.purpose), fMine); const std::string& strName = item.second.name; cachedAddressTable.append(AddressTableEntry(addressType, QString::fromStdString(strName), QString::fromStdString(address.ToString()))); } } // qLowerBound() and qUpperBound() require our cachedAddressTable list to be sorted in asc order // Even though the map is already sorted this re-sorting step is needed because the originating map // is sorted by binary address, not by base58() address. qSort(cachedAddressTable.begin(), cachedAddressTable.end(), AddressTableEntryLessThan()); } void updateEntry(const QString &address, const QString &label, bool isMine, const QString &purpose, int status) { // Find address / label in model QList<AddressTableEntry>::iterator lower = qLowerBound( cachedAddressTable.begin(), cachedAddressTable.end(), address, AddressTableEntryLessThan()); QList<AddressTableEntry>::iterator upper = qUpperBound( cachedAddressTable.begin(), cachedAddressTable.end(), address, AddressTableEntryLessThan()); int lowerIndex = (lower - cachedAddressTable.begin()); int upperIndex = (upper - cachedAddressTable.begin()); bool inModel = (lower != upper); AddressTableEntry::Type newEntryType = translateTransactionType(purpose, isMine); switch(status) { case CT_NEW: if(inModel) { qWarning() << "AddressTablePriv::updateEntry: Warning: Got CT_NEW, but entry is already in model"; break; } parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex); cachedAddressTable.insert(lowerIndex, AddressTableEntry(newEntryType, label, address)); parent->endInsertRows(); break; case CT_UPDATED: if(!inModel) { qWarning() << "AddressTablePriv::updateEntry: Warning: Got CT_UPDATED, but entry is not in model"; break; } lower->type = newEntryType; lower->label = label; parent->emitDataChanged(lowerIndex); break; case CT_DELETED: if(!inModel) { qWarning() << "AddressTablePriv::updateEntry: Warning: Got CT_DELETED, but entry is not in model"; break; } parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex-1); cachedAddressTable.erase(lower, upper); parent->endRemoveRows(); break; } } int size() { return cachedAddressTable.size(); } AddressTableEntry *index(int idx) { if(idx >= 0 && idx < cachedAddressTable.size()) { return &cachedAddressTable[idx]; } else { return 0; } } }; AddressTableModel::AddressTableModel(CWallet *wallet, WalletModel *parent) : QAbstractTableModel(parent),walletModel(parent),wallet(wallet),priv(0) { columns << tr("Label") << tr("Address"); priv = new AddressTablePriv(wallet, this); priv->refreshAddressTable(); } AddressTableModel::~AddressTableModel() { delete priv; } int AddressTableModel::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return priv->size(); } int AddressTableModel::columnCount(const QModelIndex &parent) const { Q_UNUSED(parent); return columns.length(); } QVariant AddressTableModel::data(const QModelIndex &index, int role) const { if(!index.isValid()) return QVariant(); AddressTableEntry *rec = static_cast<AddressTableEntry*>(index.internalPointer()); if(role == Qt::DisplayRole || role == Qt::EditRole) { switch(index.column()) { case Label: if(rec->label.isEmpty() && role == Qt::DisplayRole) { return tr("(no label)"); } else { return rec->label; } case Address: return rec->address; } } else if (role == Qt::FontRole) { QFont font; if(index.column() == Address) { font = GUIUtil::becoinAddressFont(); } return font; } else if (role == TypeRole) { switch(rec->type) { case AddressTableEntry::Sending: return Send; case AddressTableEntry::Receiving: return Receive; default: break; } } return QVariant(); } bool AddressTableModel::setData(const QModelIndex &index, const QVariant &value, int role) { if(!index.isValid()) return false; AddressTableEntry *rec = static_cast<AddressTableEntry*>(index.internalPointer()); std::string strPurpose = (rec->type == AddressTableEntry::Sending ? "send" : "receive"); editStatus = OK; if(role == Qt::EditRole) { LOCK(wallet->cs_wallet); /* For SetAddressBook / DelAddressBook */ CTxDestination curAddress = CBeCoinAddress(rec->address.toStdString()).Get(); if(index.column() == Label) { // Do nothing, if old label == new label if(rec->label == value.toString()) { editStatus = NO_CHANGES; return false; } wallet->SetAddressBook(curAddress, value.toString().toStdString(), strPurpose); } else if(index.column() == Address) { CTxDestination newAddress = CBeCoinAddress(value.toString().toStdString()).Get(); // Refuse to set invalid address, set error status and return false if(boost::get<CNoDestination>(&newAddress)) { editStatus = INVALID_ADDRESS; return false; } // Do nothing, if old address == new address else if(newAddress == curAddress) { editStatus = NO_CHANGES; return false; } // Check for duplicate addresses to prevent accidental deletion of addresses, if you try // to paste an existing address over another address (with a different label) else if(wallet->mapAddressBook.count(newAddress)) { editStatus = DUPLICATE_ADDRESS; return false; } // Double-check that we're not overwriting a receiving address else if(rec->type == AddressTableEntry::Sending) { // Remove old entry wallet->DelAddressBook(curAddress); // Add new entry with new address wallet->SetAddressBook(newAddress, rec->label.toStdString(), strPurpose); } } return true; } return false; } QVariant AddressTableModel::headerData(int section, Qt::Orientation orientation, int role) const { if(orientation == Qt::Horizontal) { if(role == Qt::DisplayRole && section < columns.size()) { return columns[section]; } } return QVariant(); } Qt::ItemFlags AddressTableModel::flags(const QModelIndex &index) const { if(!index.isValid()) return 0; AddressTableEntry *rec = static_cast<AddressTableEntry*>(index.internalPointer()); Qt::ItemFlags retval = Qt::ItemIsSelectable | Qt::ItemIsEnabled; // Can edit address and label for sending addresses, // and only label for receiving addresses. if(rec->type == AddressTableEntry::Sending || (rec->type == AddressTableEntry::Receiving && index.column()==Label)) { retval |= Qt::ItemIsEditable; } return retval; } QModelIndex AddressTableModel::index(int row, int column, const QModelIndex &parent) const { Q_UNUSED(parent); AddressTableEntry *data = priv->index(row); if(data) { return createIndex(row, column, priv->index(row)); } else { return QModelIndex(); } } void AddressTableModel::updateEntry(const QString &address, const QString &label, bool isMine, const QString &purpose, int status) { // Update address book model from BeCoin core priv->updateEntry(address, label, isMine, purpose, status); } QString AddressTableModel::addRow(const QString &type, const QString &label, const QString &address) { std::string strLabel = label.toStdString(); std::string strAddress = address.toStdString(); editStatus = OK; if(type == Send) { if(!walletModel->validateAddress(address)) { editStatus = INVALID_ADDRESS; return QString(); } // Check for duplicate addresses { LOCK(wallet->cs_wallet); if(wallet->mapAddressBook.count(CBeCoinAddress(strAddress).Get())) { editStatus = DUPLICATE_ADDRESS; return QString(); } } } else if(type == Receive) { // Generate a new address to associate with given label CPubKey newKey; if(!wallet->GetKeyFromPool(newKey)) { WalletModel::UnlockContext ctx(walletModel->requestUnlock()); if(!ctx.isValid()) { // Unlock wallet failed or was cancelled editStatus = WALLET_UNLOCK_FAILURE; return QString(); } if(!wallet->GetKeyFromPool(newKey)) { editStatus = KEY_GENERATION_FAILURE; return QString(); } } strAddress = CBeCoinAddress(newKey.GetID()).ToString(); } else { return QString(); } // Add entry { LOCK(wallet->cs_wallet); wallet->SetAddressBook(CBeCoinAddress(strAddress).Get(), strLabel, (type == Send ? "send" : "receive")); } return QString::fromStdString(strAddress); } bool AddressTableModel::removeRows(int row, int count, const QModelIndex &parent) { Q_UNUSED(parent); AddressTableEntry *rec = priv->index(row); if(count != 1 || !rec || rec->type == AddressTableEntry::Receiving) { // Can only remove one row at a time, and cannot remove rows not in model. // Also refuse to remove receiving addresses. return false; } { LOCK(wallet->cs_wallet); wallet->DelAddressBook(CBeCoinAddress(rec->address.toStdString()).Get()); } return true; } /* Look up label for address in address book, if not found return empty string. */ QString AddressTableModel::labelForAddress(const QString &address) const { { LOCK(wallet->cs_wallet); CBeCoinAddress address_parsed(address.toStdString()); std::map<CTxDestination, CAddressBookData>::iterator mi = wallet->mapAddressBook.find(address_parsed.Get()); if (mi != wallet->mapAddressBook.end()) { return QString::fromStdString(mi->second.name); } } return QString(); } int AddressTableModel::lookupAddress(const QString &address) const { QModelIndexList lst = match(index(0, Address, QModelIndex()), Qt::EditRole, address, 1, Qt::MatchExactly); if(lst.isEmpty()) { return -1; } else { return lst.at(0).row(); } } void AddressTableModel::emitDataChanged(int idx) { Q_EMIT dataChanged(index(idx, 0, QModelIndex()), index(idx, columns.length()-1, QModelIndex())); }
MasterX1582/bitcoin-becoin
src/qt/addresstablemodel.cpp
C++
mit
14,351
import _plotly_utils.basevalidators class BgcolorValidator(_plotly_utils.basevalidators.ColorValidator): def __init__(self, plotly_name="bgcolor", parent_name="pie.hoverlabel", **kwargs): super(BgcolorValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, array_ok=kwargs.pop("array_ok", True), edit_type=kwargs.pop("edit_type", "none"), role=kwargs.pop("role", "style"), **kwargs )
plotly/python-api
packages/python/plotly/plotly/validators/pie/hoverlabel/_bgcolor.py
Python
mit
499
package be.echostyle.moola; import be.echostyle.moola.filters.TransactionFilter; import java.time.LocalDateTime; import java.util.Comparator; import java.util.List; import java.util.Set; import java.util.stream.Collectors; public interface GroupedAccount extends Account { default AccountType getType(){ return AccountType.GROUPED; } Set<Account> getMembers(); void addMember(Account member); void removeMember(Account member); default void setMembers(Set<Account> members){ Set<Account> original = getMembers(); for (Account originalMember : original) if (!members.contains(originalMember)) removeMember(originalMember); for (Account newMember : members){ if (!original.contains(newMember)) addMember(newMember); } } @Override default List<AccountEntry> getTransactions(LocalDateTime from, LocalDateTime to) { return getMembers().stream().flatMap(member -> member.getTransactions(from, to).stream()) .sorted(Comparator.comparing(AccountEntry::getTimestamp).thenComparing(AccountEntry::getId)) .collect(Collectors.toList()); } @Override default List<AccountEntry> getTransactions(String batchId) { return getMembers().stream().flatMap(member -> member.getTransactions(batchId).stream()) .sorted(Comparator.comparing(AccountEntry::getTimestamp).thenComparing(AccountEntry::getId)) .collect(Collectors.toList()); } @Override default List<AccountEntry> getTransactions(LocalDateTime to, int count, int from) { //TODO: this count+from trick will work, but it's far from optimal return getMembers().stream().flatMap(member -> member.getTransactions(to, count + from, 0).stream()) .sorted(Comparator.comparing(AccountEntry::getTimestamp).thenComparing(AccountEntry::getId)) .skip(from) .limit(count) .collect(Collectors.toList()); } @Override default List<AccountEntry> getTransactions(LocalDateTime to, TransactionFilter filter, int count, int from) { return getMembers().stream().flatMap(member -> member.getTransactions(to, filter, count + from, 0).stream()) .sorted(Comparator.comparing(AccountEntry::getTimestamp).thenComparing(AccountEntry::getId)) .skip(from) .limit(count) .collect(Collectors.toList()); } @Override default AccountEntry getTransaction(String id) { for (Account member:getMembers()){ AccountEntry r = member.getTransaction(id); if (r!=null) return r; } return null; } @Override default boolean contains(AccountEntry entry) { for (Account member : getMembers()){ if (member.contains(entry)) return true; } return false; } @Override default Set<String> getSimpleIds() { return getMembers().stream().flatMap(acc -> acc.getSimpleIds().stream()).collect(Collectors.toSet()); } }
Kjoep/moola
moola-domain/src/main/java/be/echostyle/moola/GroupedAccount.java
Java
mit
3,248
# Options require 'bobkit' include Bobkit::Tasks # Set options (these are only partial, and the defaults) templates_folder 'templates' layouts_folder "#{templates_folder}/layouts" styles_folder 'styles' output_folder 'output' css_output_folder "#{output_folder}/css" js_output_folder "#{output_folder}/js" # Generate the site render 'youtube', layout: 'default', video: 'tntOCGkgt98', output: "cat" compile_css 'main', output: 'style' compile_js 'main', output: 'script' # Output is in the output folder
DannyBen/bobkit
examples/03_options/example.rb
Ruby
mit
558
package seedu.jobs.storage; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Optional; import java.util.logging.Logger; import seedu.jobs.commons.core.LogsCenter; import seedu.jobs.commons.exceptions.DataConversionException; import seedu.jobs.commons.util.FileUtil; import seedu.jobs.model.ReadOnlyTaskBook; /** * A class to access AddressBook data stored as an xml file on the hard disk. */ public class XmlTaskBookStorage implements TaskBookStorage { private static final Logger logger = LogsCenter.getLogger(XmlTaskBookStorage.class); private String filePath; public XmlTaskBookStorage(String filePath) { this.filePath = filePath; } public String getTaskBookFilePath() { return filePath; } @Override public Optional<ReadOnlyTaskBook> readTaskBook() throws DataConversionException, IOException { return readTaskBook(filePath); } /** * Similar to {@link #readTaskBook()} * @param filePath location of the data. Cannot be null * @throws DataConversionException if the file is not in the correct format. */ public Optional<ReadOnlyTaskBook> readTaskBook(String filePath) throws DataConversionException, FileNotFoundException { assert filePath != null; File taskBookFile = new File(filePath); if (!taskBookFile.exists()) { logger.info("TaskBook file " + taskBookFile + " not found"); return Optional.empty(); } ReadOnlyTaskBook taskBookOptional = XmlFileStorage.loadDataFromSaveFile(new File(filePath)); return Optional.of(taskBookOptional); } @Override public void saveTaskBook(ReadOnlyTaskBook taskBook) throws IOException { saveTaskBook(taskBook, filePath); } /** * Similar to {@link #saveAddressBook(ReadOnlyTaskBook)} * @param filePath location of the data. Cannot be null */ public void saveTaskBook(ReadOnlyTaskBook taskBook, String filePath) throws IOException { assert taskBook != null; assert filePath != null; File file = new File(filePath); FileUtil.createIfMissing(file); XmlFileStorage.saveDataToFile(file, new XmlSerializableTaskBook(taskBook)); } public void setFilePath(String filePath) { this.filePath = filePath; } }
CS2103JAN2017-F11-B1/main
src/main/java/seedu/jobs/storage/XmlTaskBookStorage.java
Java
mit
2,457
/** Starting with version 2.0, this file "boots" Jasmine, performing all of the necessary initialization before executing the loaded environment and all of a project's specs. This file should be loaded after `jasmine.js` and `jasmine_html.js`, but before any project source files or spec files are loaded. Thus this file can also be used to customize Jasmine for a project. If a project is using Jasmine via the standalone distribution, this file can be customized directly. If a project is using Jasmine via the [Ruby gem][jasmine-gem], this file can be copied into the support directory via `jasmine copy_boot_js`. Other environments (e.g., Python) will have different mechanisms. The location of `boot.js` can be specified and/or overridden in `jasmine.yml`. [jasmine-gem]: http://github.com/pivotal/jasmine-gem */ (function() { /** * ## Require &amp; Instantiate * * Require Jasmine's core files. Specifically, this requires and attaches all of Jasmine's code to the `jasmine` reference. */ window.jasmine = jasmineRequire.core(jasmineRequire); /** * Since this is being run in a browser and the results should populate to an HTML page, require the HTML-specific Jasmine code, injecting the same reference. */ jasmineRequire.html(jasmine); /** * Create the Jasmine environment. This is used to run all specs in a project. */ var env = jasmine.getEnv(); var originalExecute = env.execute; /** * ## The Global Interface * * Build up the functions that will be exposed as the Jasmine public interface. A project can customize, rename or alias any of these functions as desired, provided the implementation remains unchanged. */ var jasmineInterface = jasmineRequire.interface(jasmine, env); /** * Add all of the Jasmine global/public interface to the global scope, so a project can use the public interface directly. For example, calling `describe` in specs instead of `jasmine.getEnv().describe`. */ extend(window, jasmineInterface); /** * ## Runner Parameters * * More browser specific code - wrap the query string in an object and to allow for getting/setting parameters from the runner user interface. */ var queryString = new jasmine.QueryString({ getWindowLocation: function() { return window.location; } }); var catchingExceptions = queryString.getParam("catch"); env.catchExceptions(typeof catchingExceptions === "undefined" ? true : catchingExceptions); var throwingExpectationFailures = queryString.getParam("throwFailures"); env.throwOnExpectationFailure(throwingExpectationFailures); var random = queryString.getParam("random"); env.randomizeTests(random); var seed = queryString.getParam("seed"); if (seed) { env.seed(seed); } /** * ## Reporters * The `HtmlReporter` builds all of the HTML UI for the runner page. This reporter paints the dots, stars, and x's for specs, as well as all spec names and all failures (if any). */ var htmlReporter = new jasmine.HtmlReporter({ env: env, onRaiseExceptionsClick: function() { queryString.navigateWithNewParam("catch", !env.catchingExceptions()); }, onThrowExpectationsClick: function() { queryString.navigateWithNewParam("throwFailures", !env.throwingExpectationFailures()); }, onRandomClick: function() { queryString.navigateWithNewParam("random", !env.randomTests()); }, addToExistingQueryString: function(key, value) { return queryString.fullStringWithNewParam(key, value); }, getContainer: function() { return document.body; }, createElement: function() { return document.createElement.apply(document, arguments); }, createTextNode: function() { return document.createTextNode.apply(document, arguments); }, timer: new jasmine.Timer() }); /** * The `jsApiReporter` also receives spec results, and is used by any environment that needs to extract the results from JavaScript. */ env.addReporter(jasmineInterface.jsApiReporter); env.addReporter(htmlReporter); /** * Filter which specs will be run by matching the start of the full name against the `spec` query param. */ var specFilter = new jasmine.HtmlSpecFilter({ filterString: function() { return queryString.getParam("spec"); } }); env.specFilter = function(spec) { return specFilter.matches(spec.getFullName()); }; /** * Setting up timing functions to be able to be overridden. Certain browsers (Safari, IE 8, phantomjs) require this hack. */ window.setTimeout = window.setTimeout; window.setInterval = window.setInterval; window.clearTimeout = window.clearTimeout; window.clearInterval = window.clearInterval; /** * ## Execution * * Replace the browser window's `onload`, ensure it's called, and then run all of the loaded specs. This includes initializing the `HtmlReporter` instance and then executing the loaded Jasmine environment. All of this will happen after all of the specs are loaded. */ // [Chutzpah]: Wrapping the onload code in a new function to be called and extracted a separate function for the starting Jasmine var initialized = false; window.initializeJasmine = function () { // [Chutzpah]: Guard against multiple initializations when running blanket if (!initialized && originalExecute == env.execute) { htmlReporter.initialize(); env.execute(); initialized = true; } }; window.initializeJasmineOnLoad = function() { var currentWindowOnload = window.onload; window.onload = function() { if (currentWindowOnload) { currentWindowOnload(); } window.initializeJasmine(); }; }; /** * Helper function for readability above. */ function extend(destination, source) { for (var property in source) destination[property] = source[property]; return destination; } }());
mukulikadey/SOEN341-Group1
chutzpah/Chutzpah/TestFiles/Jasmine/v2/boot.js
JavaScript
mit
5,936
package net.lightbody.bmp; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.MapMaker; import net.lightbody.bmp.client.ClientUtil; import net.lightbody.bmp.core.har.Har; import net.lightbody.bmp.core.har.HarLog; import net.lightbody.bmp.core.har.HarNameVersion; import net.lightbody.bmp.core.har.HarPage; import net.lightbody.bmp.filters.AddHeadersFilter; import net.lightbody.bmp.filters.AutoBasicAuthFilter; import net.lightbody.bmp.filters.BlacklistFilter; import net.lightbody.bmp.filters.BrowserMobHttpFilterChain; import net.lightbody.bmp.filters.HarCaptureFilter; import net.lightbody.bmp.filters.HttpConnectHarCaptureFilter; import net.lightbody.bmp.filters.HttpsHostCaptureFilter; import net.lightbody.bmp.filters.HttpsOriginalHostCaptureFilter; import net.lightbody.bmp.filters.LatencyFilter; import net.lightbody.bmp.filters.RegisterRequestFilter; import net.lightbody.bmp.filters.RequestFilter; import net.lightbody.bmp.filters.RequestFilterAdapter; import net.lightbody.bmp.filters.ResolvedHostnameCacheFilter; import net.lightbody.bmp.filters.ResponseFilter; import net.lightbody.bmp.filters.ResponseFilterAdapter; import net.lightbody.bmp.filters.RewriteUrlFilter; import net.lightbody.bmp.filters.UnregisterRequestFilter; import net.lightbody.bmp.filters.WhitelistFilter; import net.lightbody.bmp.mitm.KeyStoreFileCertificateSource; import net.lightbody.bmp.mitm.TrustSource; import net.lightbody.bmp.mitm.keys.ECKeyGenerator; import net.lightbody.bmp.mitm.keys.RSAKeyGenerator; import net.lightbody.bmp.mitm.manager.ImpersonatingMitmManager; import net.lightbody.bmp.proxy.ActivityMonitor; import net.lightbody.bmp.proxy.BlacklistEntry; import net.lightbody.bmp.proxy.CaptureType; import net.lightbody.bmp.proxy.RewriteRule; import net.lightbody.bmp.proxy.Whitelist; import net.lightbody.bmp.proxy.auth.AuthType; import net.lightbody.bmp.proxy.dns.AdvancedHostResolver; import net.lightbody.bmp.proxy.dns.DelegatingHostResolver; import net.lightbody.bmp.util.BrowserMobHttpUtil; import net.lightbody.bmp.util.BrowserMobProxyUtil; import org.littleshoot.proxy.ChainedProxy; import org.littleshoot.proxy.ChainedProxyAdapter; import org.littleshoot.proxy.ChainedProxyManager; import org.littleshoot.proxy.HttpFilters; import org.littleshoot.proxy.HttpFiltersSource; import org.littleshoot.proxy.HttpFiltersSourceAdapter; import org.littleshoot.proxy.HttpProxyServer; import org.littleshoot.proxy.HttpProxyServerBootstrap; import org.littleshoot.proxy.MitmManager; import org.littleshoot.proxy.impl.DefaultHttpProxyServer; import org.littleshoot.proxy.impl.ProxyUtils; import org.littleshoot.proxy.impl.ThreadPoolConfiguration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.InetAddress; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.EnumSet; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Set; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.regex.Pattern; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpObject; import io.netty.handler.codec.http.HttpRequest; /** * A LittleProxy-based implementation of {@link net.lightbody.bmp.BrowserMobProxy}. */ public class BrowserMobProxyServer implements BrowserMobProxy { private static final Logger log = LoggerFactory.getLogger(BrowserMobProxyServer.class); private static final HarNameVersion HAR_CREATOR_VERSION = new HarNameVersion("BrowserMob Proxy", BrowserMobProxyUtil.getVersionString()); /* Default MITM resources */ private static final String RSA_KEYSTORE_RESOURCE = "/sslSupport/ca-keystore-rsa.p12"; private static final String EC_KEYSTORE_RESOURCE = "/sslSupport/ca-keystore-ec.p12"; private static final String KEYSTORE_TYPE = "PKCS12"; private static final String KEYSTORE_PRIVATE_KEY_ALIAS = "key"; private static final String KEYSTORE_PASSWORD = "password"; /** * The default pseudonym to use when adding the Via header to proxied requests. */ public static final String VIA_HEADER_ALIAS = "browsermobproxy"; /** * True only after the proxy has been successfully started. */ private final AtomicBoolean started = new AtomicBoolean(false); /** * True only after the proxy has been successfully started, then successfully stopped or aborted. */ private final AtomicBoolean stopped = new AtomicBoolean(false); /** * Tracks the current page count, for use when auto-generating HAR page names. */ private final AtomicInteger harPageCount = new AtomicInteger(0); /** * When true, MITM will be disabled. The proxy will no longer intercept HTTPS requests, but they will still be proxied. */ private volatile boolean mitmDisabled = false; /** * The MITM manager that will be used for HTTPS requests. */ private volatile MitmManager mitmManager; /** * The list of filterFactories that will generate the filters that implement browsermob-proxy behavior. */ private final List<HttpFiltersSource> filterFactories = new CopyOnWriteArrayList<>(); /** * List of rejected URL patterns */ private volatile Collection<BlacklistEntry> blacklistEntries = new CopyOnWriteArrayList<>(); /** * List of URLs to rewrite */ private volatile CopyOnWriteArrayList<RewriteRule> rewriteRules = new CopyOnWriteArrayList<>(); /** * The LittleProxy instance that performs all proxy operations. */ private volatile HttpProxyServer proxyServer; /** * No capture types are enabled by default. */ private volatile EnumSet<CaptureType> harCaptureTypes = EnumSet.noneOf(CaptureType.class); /** * The current HAR being captured. */ private volatile Har har; /** * The current HarPage to which new requests will be associated. */ private volatile HarPage currentHarPage; /** * Maximum bandwidth to consume when reading responses from servers. */ private volatile long readBandwidthLimitBps; /** * Maximum bandwidth to consume when writing requests to servers. */ private volatile long writeBandwidthLimitBps; /** * List of accepted URL patterns. Unlisted URL patterns will be rejected with the response code contained in the Whitelist. */ private final AtomicReference<Whitelist> whitelist = new AtomicReference<>(Whitelist.WHITELIST_DISABLED); /** * Additional headers that will be sent with every request. The map is declared as a ConcurrentMap to indicate that writes may be performed * by other threads concurrently (e.g. due to an incoming REST call), but the concurrencyLevel is set to 1 because modifications to the * additionalHeaders are rare, and in most cases happen only once, at start-up. */ private volatile ConcurrentMap<String, String> additionalHeaders = new MapMaker().concurrencyLevel(1).makeMap(); /** * The amount of time to wait while connecting to a server. */ private volatile int connectTimeoutMs; /** * The amount of time a connection to a server can remain idle while receiving data from the server. */ private volatile int idleConnectionTimeoutSec; /** * The amount of time to wait before forwarding the response to the client. */ private volatile int latencyMs; /** * Set to true once the HAR capture filter has been added to the filter chain. */ private final AtomicBoolean harCaptureFilterEnabled = new AtomicBoolean(false); /** * The address of an upstream chained proxy to route traffic through. */ private volatile InetSocketAddress upstreamProxyAddress; /** * The chained proxy manager that manages upstream proxies. */ private volatile ChainedProxyManager chainedProxyManager; /** * The address of the network interface from which the proxy will initiate connections. */ private volatile InetAddress serverBindAddress; /** * The TrustSource that will be used to validate servers' certificates. If null, will not validate server certificates. */ private volatile TrustSource trustSource = TrustSource.defaultTrustSource(); /** * When true, use Elliptic Curve keys and certificates when impersonating upstream servers. */ private volatile boolean useEcc = false; /** * Resolver to use when resolving hostnames to IP addresses. This is a bridge between {@link org.littleshoot.proxy.HostResolver} and * {@link net.lightbody.bmp.proxy.dns.AdvancedHostResolver}. It allows the resolvers to be changed on-the-fly without re-bootstrapping the * littleproxy server. The default resolver (native JDK resolver) can be changed using {@link #setHostNameResolver(net.lightbody.bmp.proxy.dns.AdvancedHostResolver)} and * supplying one of the pre-defined resolvers in {@link ClientUtil}, such as {@link ClientUtil#createDnsJavaWithNativeFallbackResolver()} * or {@link ClientUtil#createDnsJavaResolver()}. You can also build your own resolver, or use {@link net.lightbody.bmp.proxy.dns.ChainedHostResolver} * to chain together multiple DNS resolvers. */ private final DelegatingHostResolver delegatingResolver = new DelegatingHostResolver(ClientUtil.createNativeCacheManipulatingResolver()); private final ActivityMonitor activityMonitor = new ActivityMonitor(); /** * The acceptor and worker thread configuration for the Netty thread pools. */ private volatile ThreadPoolConfiguration threadPoolConfiguration; /** * A mapping of hostnames to base64-encoded Basic auth credentials that will be added to the Authorization header for * matching requests. */ private final ConcurrentMap<String, String> basicAuthCredentials = new MapMaker() .concurrencyLevel(1) .makeMap(); /** * Base64-encoded credentials to use to authenticate with the upstream proxy. */ private volatile String chainedProxyCredentials; public BrowserMobProxyServer() { } @Override public void start(int port, InetAddress clientBindAddress, InetAddress serverBindAddress) { boolean notStarted = started.compareAndSet(false, true); if (!notStarted) { throw new IllegalStateException("Proxy server is already started. Not restarting."); } InetSocketAddress clientBindSocket; if (clientBindAddress == null) { // if no client bind address was specified, bind to the wildcard address clientBindSocket = new InetSocketAddress(port); } else { clientBindSocket = new InetSocketAddress(clientBindAddress, port); } this.serverBindAddress = serverBindAddress; // initialize all the default BrowserMob filter factories that provide core BMP functionality addBrowserMobFilters(); HttpProxyServerBootstrap bootstrap = DefaultHttpProxyServer.bootstrap() .withFiltersSource(new HttpFiltersSource() { @Override public HttpFilters filterRequest(HttpRequest originalRequest, ChannelHandlerContext channelHandlerContext) { return new BrowserMobHttpFilterChain(BrowserMobProxyServer.this, originalRequest, channelHandlerContext); } @Override public int getMaximumRequestBufferSizeInBytes() { return getMaximumRequestBufferSize(); } @Override public int getMaximumResponseBufferSizeInBytes() { return getMaximumResponseBufferSize(); } }) .withServerResolver(delegatingResolver) .withAddress(clientBindSocket) .withConnectTimeout(connectTimeoutMs) .withIdleConnectionTimeout(idleConnectionTimeoutSec) .withProxyAlias(VIA_HEADER_ALIAS); if (serverBindAddress != null) { bootstrap.withNetworkInterface(new InetSocketAddress(serverBindAddress, 0)); } if (!mitmDisabled) { if (mitmManager == null) { mitmManager = ImpersonatingMitmManager.builder() .rootCertificateSource(new KeyStoreFileCertificateSource( KEYSTORE_TYPE, useEcc ? EC_KEYSTORE_RESOURCE : RSA_KEYSTORE_RESOURCE, KEYSTORE_PRIVATE_KEY_ALIAS, KEYSTORE_PASSWORD)) .serverKeyGenerator(useEcc ? new ECKeyGenerator() : new RSAKeyGenerator()) .trustSource(trustSource) .build(); } bootstrap.withManInTheMiddle(mitmManager); } if (readBandwidthLimitBps > 0 || writeBandwidthLimitBps > 0) { bootstrap.withThrottling(readBandwidthLimitBps, writeBandwidthLimitBps); } if (chainedProxyManager != null) { bootstrap.withChainProxyManager(chainedProxyManager); } else if (upstreamProxyAddress != null) { bootstrap.withChainProxyManager(new ChainedProxyManager() { @Override public void lookupChainedProxies(HttpRequest httpRequest, Queue<ChainedProxy> chainedProxies) { final InetSocketAddress upstreamProxy = upstreamProxyAddress; if (upstreamProxy != null) { chainedProxies.add(new ChainedProxyAdapter() { @Override public InetSocketAddress getChainedProxyAddress() { return upstreamProxy; } @Override public void filterRequest(HttpObject httpObject) { String chainedProxyAuth = chainedProxyCredentials; if (chainedProxyAuth != null) { if (httpObject instanceof HttpRequest) { HttpHeaders.addHeader((HttpRequest)httpObject, HttpHeaders.Names.PROXY_AUTHORIZATION, "Basic " + chainedProxyAuth); } } } }); } } }); } if (threadPoolConfiguration != null) { bootstrap.withThreadPoolConfiguration(threadPoolConfiguration); } proxyServer = bootstrap.start(); } @Override public boolean isStarted() { return started.get(); } @Override public void start(int port) { this.start(port, null, null); } @Override public void start(int port, InetAddress bindAddress) { this.start(port, bindAddress, null); } @Override public void start() { this.start(0); } @Override public void stop() { stop(true); } @Override public void abort() { stop(false); } protected void stop(boolean graceful) { if (isStarted()) { if (stopped.compareAndSet(false, true)) { if (proxyServer != null) { if (graceful) { proxyServer.stop(); } else { proxyServer.abort(); } } else { log.warn("Attempted to stop proxy server, but proxy was never successfully started."); } } else { throw new IllegalStateException("Proxy server is already stopped. Cannot re-stop."); } } else { throw new IllegalStateException("Proxy server has not been started"); } } @Override public InetAddress getClientBindAddress() { if (started.get()) { return proxyServer.getListenAddress().getAddress(); } else { return null; } } @Override public int getPort() { if (started.get()) { return proxyServer.getListenAddress().getPort(); } else { return 0; } } @Override public InetAddress getServerBindAddress() { return serverBindAddress; } @Override public Har getHar() { return har; } @Override public Har newHar() { return newHar(null); } @Override public Har newHar(String initialPageRef) { return newHar(initialPageRef, null); } @Override public Har newHar(String initialPageRef, String initialPageTitle) { Har oldHar = getHar(); addHarCaptureFilter(); harPageCount.set(0); this.har = new Har(new HarLog(HAR_CREATOR_VERSION)); newPage(initialPageRef, initialPageTitle); return oldHar; } @Override public void setHarCaptureTypes(Set<CaptureType> harCaptureSettings) { if (harCaptureSettings == null || harCaptureSettings.isEmpty()) { harCaptureTypes = EnumSet.noneOf(CaptureType.class); } else { harCaptureTypes = EnumSet.copyOf(harCaptureSettings); } } @Override public void setHarCaptureTypes(CaptureType... captureTypes) { if (captureTypes == null) { setHarCaptureTypes(EnumSet.noneOf(CaptureType.class)); } else { setHarCaptureTypes(EnumSet.copyOf(Arrays.asList(captureTypes))); } } @Override public EnumSet<CaptureType> getHarCaptureTypes() { return EnumSet.copyOf(harCaptureTypes); } @Override public void enableHarCaptureTypes(Set<CaptureType> captureTypes) { harCaptureTypes.addAll(captureTypes); } @Override public void enableHarCaptureTypes(CaptureType... captureTypes) { if (captureTypes == null) { enableHarCaptureTypes(EnumSet.noneOf(CaptureType.class)); } else { enableHarCaptureTypes(EnumSet.copyOf(Arrays.asList(captureTypes))); } } @Override public void disableHarCaptureTypes(Set<CaptureType> captureTypes) { harCaptureTypes.removeAll(captureTypes); } @Override public void disableHarCaptureTypes(CaptureType... captureTypes) { if (captureTypes == null) { disableHarCaptureTypes(EnumSet.noneOf(CaptureType.class)); } else { disableHarCaptureTypes(EnumSet.copyOf(Arrays.asList(captureTypes))); } } @Override public Har newPage() { return newPage(null); } @Override public Har newPage(String pageRef) { return newPage(pageRef, null); } @Override public Har newPage(String pageRef, String pageTitle) { if (har == null) { throw new IllegalStateException("No HAR exists for this proxy. Use newHar() to create a new HAR before calling newPage()."); } Har endOfPageHar = null; if (currentHarPage != null) { String currentPageRef = currentHarPage.getId(); // end the previous page, so that page-wide timings are populated endPage(); // the interface requires newPage() to return the Har as it was immediately after the previous page was ended. endOfPageHar = BrowserMobProxyUtil.copyHarThroughPageRef(har, currentPageRef); } if (pageRef == null) { pageRef = "Page " + harPageCount.getAndIncrement(); } if (pageTitle == null) { pageTitle = pageRef; } HarPage newPage = new HarPage(pageRef, pageTitle); har.getLog().addPage(newPage); currentHarPage = newPage; return endOfPageHar; } @Override public Har endHar() { Har oldHar = getHar(); // end the page and populate timings endPage(); this.har = null; return oldHar; } @Override public void setReadBandwidthLimit(long bytesPerSecond) { this.readBandwidthLimitBps = bytesPerSecond; if (isStarted()) { proxyServer.setThrottle(this.readBandwidthLimitBps, this.writeBandwidthLimitBps); } } @Override public long getReadBandwidthLimit() { return readBandwidthLimitBps; } @Override public void setWriteBandwidthLimit(long bytesPerSecond) { this.writeBandwidthLimitBps = bytesPerSecond; if (isStarted()) { proxyServer.setThrottle(this.readBandwidthLimitBps, this.writeBandwidthLimitBps); } } @Override public long getWriteBandwidthLimit() { return writeBandwidthLimitBps; } public void endPage() { if (har == null) { throw new IllegalStateException("No HAR exists for this proxy. Use newHar() to create a new HAR."); } HarPage previousPage = this.currentHarPage; this.currentHarPage = null; if (previousPage == null) { return; } previousPage.getPageTimings().setOnLoad(new Date().getTime() - previousPage.getStartedDateTime().getTime()); } @Override public void addHeaders(Map<String, String> headers) { ConcurrentMap<String, String> newHeaders = new MapMaker().concurrencyLevel(1).makeMap(); newHeaders.putAll(headers); this.additionalHeaders = newHeaders; } @Override public void setLatency(long latency, TimeUnit timeUnit) { this.latencyMs = (int) TimeUnit.MILLISECONDS.convert(latency, timeUnit); } @Override public void autoAuthorization(String domain, String username, String password, AuthType authType) { switch (authType) { case BASIC: // base64 encode the "username:password" string String base64EncodedCredentials = BrowserMobHttpUtil.base64EncodeBasicCredentials(username, password); basicAuthCredentials.put(domain, base64EncodedCredentials); break; default: throw new UnsupportedOperationException("AuthType " + authType + " is not supported for HTTP Authorization"); } } @Override public void stopAutoAuthorization(String domain) { basicAuthCredentials.remove(domain); } @Override public void chainedProxyAuthorization(String username, String password, AuthType authType) { switch (authType) { case BASIC: chainedProxyCredentials = BrowserMobHttpUtil.base64EncodeBasicCredentials(username, password); break; default: throw new UnsupportedOperationException("AuthType " + authType + " is not supported for Proxy Authorization"); } } @Override public void setConnectTimeout(int connectTimeout, TimeUnit timeUnit) { this.connectTimeoutMs = (int) TimeUnit.MILLISECONDS.convert(connectTimeout, timeUnit); if (isStarted()) { proxyServer.setConnectTimeout((int) TimeUnit.MILLISECONDS.convert(connectTimeout, timeUnit)); } } /** * The LittleProxy implementation only allows idle connection timeouts to be specified in seconds. idleConnectionTimeouts greater than * 0 but less than 1 second will be set to 1 second; otherwise, values will be truncated (i.e. 1500ms will become 1s). */ @Override public void setIdleConnectionTimeout(int idleConnectionTimeout, TimeUnit timeUnit) { long timeout = TimeUnit.SECONDS.convert(idleConnectionTimeout, timeUnit); if (timeout == 0 && idleConnectionTimeout > 0) { this.idleConnectionTimeoutSec = 1; } else { this.idleConnectionTimeoutSec = (int) timeout; } if (isStarted()) { proxyServer.setIdleConnectionTimeout(idleConnectionTimeoutSec); } } @Override public void setRequestTimeout(int requestTimeout, TimeUnit timeUnit) { //TODO: implement Request Timeouts using LittleProxy. currently this only sets an idle connection timeout, if the idle connection // timeout is higher than the specified requestTimeout. if (idleConnectionTimeoutSec == 0 || idleConnectionTimeoutSec > TimeUnit.SECONDS.convert(requestTimeout, timeUnit)) { setIdleConnectionTimeout(requestTimeout, timeUnit); } } @Override public void rewriteUrl(String pattern, String replace) { rewriteRules.add(new RewriteRule(pattern, replace)); } @Override public void rewriteUrls(Map<String, String> rewriteRules) { List<RewriteRule> newRules = new ArrayList<>(rewriteRules.size()); for (Map.Entry<String, String> rewriteRule : rewriteRules.entrySet()) { RewriteRule newRule = new RewriteRule(rewriteRule.getKey(), rewriteRule.getValue()); newRules.add(newRule); } this.rewriteRules = new CopyOnWriteArrayList<>(newRules); } @Override public void clearRewriteRules() { rewriteRules.clear(); } @Override public void blacklistRequests(String pattern, int responseCode) { blacklistEntries.add(new BlacklistEntry(pattern, responseCode)); } @Override public void blacklistRequests(String pattern, int responseCode, String method) { blacklistEntries.add(new BlacklistEntry(pattern, responseCode, method)); } @Override public void setBlacklist(Collection<BlacklistEntry> blacklist) { this.blacklistEntries = new CopyOnWriteArrayList<>(blacklist); } @Override public Collection<BlacklistEntry> getBlacklist() { return Collections.unmodifiableCollection(blacklistEntries); } @Override public boolean isWhitelistEnabled() { return whitelist.get().isEnabled(); } @Override public Collection<String> getWhitelistUrls() { ImmutableList.Builder<String> builder = ImmutableList.builder(); for (Pattern pattern : whitelist.get().getPatterns()) { builder.add(pattern.pattern()); } return builder.build(); } @Override public int getWhitelistStatusCode() { return whitelist.get().getStatusCode(); } @Override public void clearBlacklist() { blacklistEntries.clear(); } @Override public void whitelistRequests(Collection<String> urlPatterns, int statusCode) { this.whitelist.set(new Whitelist(urlPatterns, statusCode)); } @Override public void addWhitelistPattern(String urlPattern) { // to make sure this method is threadsafe, we need to guarantee that the "snapshot" of the whitelist taken at the beginning // of the method has not been replaced by the time we have constructed a new whitelist at the end of the method boolean whitelistUpdated = false; while (!whitelistUpdated) { Whitelist currentWhitelist = this.whitelist.get(); if (!currentWhitelist.isEnabled()) { throw new IllegalStateException("Whitelist is disabled. Cannot add patterns to a disabled whitelist."); } // retrieve the response code and list of patterns from the current whitelist, the construct a new list of patterns that contains // all of the old whitelist's patterns + this new pattern int statusCode = currentWhitelist.getStatusCode(); List<String> newPatterns = new ArrayList<>(currentWhitelist.getPatterns().size() + 1); for (Pattern pattern : currentWhitelist.getPatterns()) { newPatterns.add(pattern.pattern()); } newPatterns.add(urlPattern); // create a new (immutable) Whitelist object with the new pattern list and status code Whitelist newWhitelist = new Whitelist(newPatterns, statusCode); // replace the current whitelist with the new whitelist only if the current whitelist has not changed since we started whitelistUpdated = this.whitelist.compareAndSet(currentWhitelist, newWhitelist); } } /** * Whitelist the specified request patterns, returning the specified responseCode for non-whitelisted * requests. * * @param patterns regular expression strings matching URL patterns to whitelist. if empty or null, * the whitelist will be enabled but will not match any URLs. * @param responseCode the HTTP response code to return for non-whitelisted requests */ public void whitelistRequests(String[] patterns, int responseCode) { if (patterns == null || patterns.length == 0) { this.enableEmptyWhitelist(responseCode); } else { this.whitelistRequests(Arrays.asList(patterns), responseCode); } } @Override public void enableEmptyWhitelist(int statusCode) { whitelist.set(new Whitelist(statusCode)); } @Override public void disableWhitelist() { whitelist.set(Whitelist.WHITELIST_DISABLED); } @Override public void addHeader(String name, String value) { additionalHeaders.put(name, value); } @Override public void removeHeader(String name) { additionalHeaders.remove(name); } @Override public void removeAllHeaders() { additionalHeaders.clear(); } @Override public Map<String, String> getAllHeaders() { return ImmutableMap.copyOf(additionalHeaders); } @Override public void setHostNameResolver(AdvancedHostResolver resolver) { delegatingResolver.setResolver(resolver); } @Override public AdvancedHostResolver getHostNameResolver() { return delegatingResolver.getResolver(); } @Override public boolean waitForQuiescence(long quietPeriod, long timeout, TimeUnit timeUnit) { return activityMonitor.waitForQuiescence(quietPeriod, timeout, timeUnit); } /** * Instructs this proxy to route traffic through an upstream proxy. Proxy chaining is not compatible with man-in-the-middle * SSL, so HAR capture will be disabled for HTTPS traffic when using an upstream proxy. * <p> * <b>Note:</b> Using {@link #setChainedProxyManager(ChainedProxyManager)} will supersede any value set by this method. * * @param chainedProxyAddress address of the upstream proxy */ @Override public void setChainedProxy(InetSocketAddress chainedProxyAddress) { upstreamProxyAddress = chainedProxyAddress; } @Override public InetSocketAddress getChainedProxy() { return upstreamProxyAddress; } /** * Allows access to the LittleProxy {@link ChainedProxyManager} for fine-grained control of the chained proxies. To enable a single * chained proxy, {@link BrowserMobProxy#setChainedProxy(InetSocketAddress)} is generally more convenient. * * @param chainedProxyManager chained proxy manager to enable */ public void setChainedProxyManager(ChainedProxyManager chainedProxyManager) { if (isStarted()) { throw new IllegalStateException("Cannot configure chained proxy manager after proxy has started."); } this.chainedProxyManager = chainedProxyManager; } /** * Configures the Netty thread pool used by the LittleProxy back-end. See {@link ThreadPoolConfiguration} for details. * * @param threadPoolConfiguration thread pool configuration to use */ public void setThreadPoolConfiguration(ThreadPoolConfiguration threadPoolConfiguration) { if (isStarted()) { throw new IllegalStateException("Cannot configure thread pool after proxy has started."); } this.threadPoolConfiguration = threadPoolConfiguration; } @Override public void addFirstHttpFilterFactory(HttpFiltersSource filterFactory) { filterFactories.add(0, filterFactory); } @Override public void addLastHttpFilterFactory(HttpFiltersSource filterFactory) { filterFactories.add(filterFactory); } /** * <b>Note:</b> The current implementation of this method forces a maximum response size of 2 MiB. To adjust the maximum response size, or * to disable aggregation (which disallows access to the {@link net.lightbody.bmp.util.HttpMessageContents}), you may add the filter source * directly: <code>addFirstHttpFilterFactory(new ResponseFilterAdapter.FilterSource(filter, bufferSizeInBytes));</code> */ @Override public void addResponseFilter(ResponseFilter filter) { addLastHttpFilterFactory(new ResponseFilterAdapter.FilterSource(filter)); } /** * <b>Note:</b> The current implementation of this method forces a maximum request size of 2 MiB. To adjust the maximum request size, or * to disable aggregation (which disallows access to the {@link net.lightbody.bmp.util.HttpMessageContents}), you may add the filter source * directly: <code>addFirstHttpFilterFactory(new RequestFilterAdapter.FilterSource(filter, bufferSizeInBytes));</code> */ @Override public void addRequestFilter(RequestFilter filter) { addFirstHttpFilterFactory(new RequestFilterAdapter.FilterSource(filter)); } @Override public Map<String, String> getRewriteRules() { ImmutableMap.Builder<String, String> builder = ImmutableMap.builder(); for (RewriteRule rewriteRule : rewriteRules) { builder.put(rewriteRule.getPattern().pattern(), rewriteRule.getReplace()); } return builder.build(); } @Override public void removeRewriteRule(String urlPattern) { // normally removing elements from the list we are iterating over would not be possible, but since this is a CopyOnWriteArrayList // the iterator it returns is a "snapshot" of the list that will not be affected by removal (and that does not support removal, either) for (RewriteRule rewriteRule : rewriteRules) { if (rewriteRule.getPattern().pattern().equals(urlPattern)) { rewriteRules.remove(rewriteRule); } } } public boolean isStopped() { return stopped.get(); } public HarPage getCurrentHarPage() { return currentHarPage; } public void addHttpFilterFactory(HttpFiltersSource filterFactory) { filterFactories.add(filterFactory); } public List<HttpFiltersSource> getFilterFactories() { return filterFactories; } @Override public void setMitmDisabled(boolean mitmDisabled) throws IllegalStateException { if (isStarted()) { throw new IllegalStateException("Cannot disable MITM after the proxy has been started"); } this.mitmDisabled = mitmDisabled; } @Override public void setMitmManager(MitmManager mitmManager) { this.mitmManager = mitmManager; } @Override public void setTrustAllServers(boolean trustAllServers) { if (isStarted()) { throw new IllegalStateException("Cannot disable upstream server verification after the proxy has been started"); } if (trustAllServers) { trustSource = null; } else { if (trustSource == null) { trustSource = TrustSource.defaultTrustSource(); } } } @Override public void setTrustSource(TrustSource trustSource) { if (isStarted()) { throw new IllegalStateException("Cannot change TrustSource after proxy has been started"); } this.trustSource = trustSource; } public boolean isMitmDisabled() { return this.mitmDisabled; } public void setUseEcc(boolean useEcc) { this.useEcc = useEcc; } /** * Adds the basic browsermob-proxy filters, except for the relatively-expensive HAR capture filter. */ protected void addBrowserMobFilters() { addHttpFilterFactory(new HttpFiltersSourceAdapter() { @Override public HttpFilters filterRequest(HttpRequest originalRequest, ChannelHandlerContext ctx) { return new ResolvedHostnameCacheFilter(originalRequest, ctx); } }); addHttpFilterFactory(new HttpFiltersSourceAdapter() { @Override public HttpFilters filterRequest(HttpRequest originalRequest, ChannelHandlerContext ctx) { return new RegisterRequestFilter(originalRequest, ctx, activityMonitor); } }); addHttpFilterFactory(new HttpFiltersSourceAdapter() { @Override public HttpFilters filterRequest(HttpRequest originalRequest, ChannelHandlerContext ctx) { return new HttpsOriginalHostCaptureFilter(originalRequest, ctx); } }); addHttpFilterFactory(new HttpFiltersSourceAdapter() { @Override public HttpFilters filterRequest(HttpRequest originalRequest, ChannelHandlerContext ctx) { return new BlacklistFilter(originalRequest, ctx, getBlacklist()); } }); addHttpFilterFactory(new HttpFiltersSourceAdapter() { @Override public HttpFilters filterRequest(HttpRequest originalRequest, ChannelHandlerContext ctx) { Whitelist currentWhitelist = whitelist.get(); return new WhitelistFilter(originalRequest, ctx, isWhitelistEnabled(), currentWhitelist.getStatusCode(), currentWhitelist.getPatterns()); } }); addHttpFilterFactory(new HttpFiltersSourceAdapter() { @Override public HttpFilters filterRequest(HttpRequest originalRequest, ChannelHandlerContext ctx) { return new AutoBasicAuthFilter(originalRequest, ctx, basicAuthCredentials); } }); addHttpFilterFactory(new HttpFiltersSourceAdapter() { @Override public HttpFilters filterRequest(HttpRequest originalRequest, ChannelHandlerContext ctx) { return new RewriteUrlFilter(originalRequest, ctx, rewriteRules); } }); addHttpFilterFactory(new HttpFiltersSourceAdapter() { @Override public HttpFilters filterRequest(HttpRequest originalRequest, ChannelHandlerContext ctx) { return new HttpsHostCaptureFilter(originalRequest, ctx); } }); addHttpFilterFactory(new HttpFiltersSourceAdapter() { @Override public HttpFilters filterRequest(HttpRequest originalRequest) { return new AddHeadersFilter(originalRequest, additionalHeaders); } }); addHttpFilterFactory(new HttpFiltersSourceAdapter() { @Override public HttpFilters filterRequest(HttpRequest originalRequest) { return new LatencyFilter(originalRequest, latencyMs); } }); addHttpFilterFactory(new HttpFiltersSourceAdapter() { @Override public HttpFilters filterRequest(HttpRequest originalRequest, ChannelHandlerContext ctx) { return new UnregisterRequestFilter(originalRequest, ctx, activityMonitor); } }); } private int getMaximumRequestBufferSize() { int maxBufferSize = 0; for (HttpFiltersSource source : filterFactories) { int requestBufferSize = source.getMaximumRequestBufferSizeInBytes(); if (requestBufferSize > maxBufferSize) { maxBufferSize = requestBufferSize; } } return maxBufferSize; } private int getMaximumResponseBufferSize() { int maxBufferSize = 0; for (HttpFiltersSource source : filterFactories) { int requestBufferSize = source.getMaximumResponseBufferSizeInBytes(); if (requestBufferSize > maxBufferSize) { maxBufferSize = requestBufferSize; } } return maxBufferSize; } /** * Enables the HAR capture filter if it has not already been enabled. The filter will be added to the end of the filter chain. * The HAR capture filter is relatively expensive, so this method is only called when a HAR is requested. */ protected void addHarCaptureFilter() { if (harCaptureFilterEnabled.compareAndSet(false, true)) { // the HAR capture filter is (relatively) expensive, so only enable it when a HAR is being captured. furthermore, // restricting the HAR capture filter to requests where the HAR exists, as well as excluding HTTP CONNECTs // from the HAR capture filter, greatly simplifies the filter code. addHttpFilterFactory(new HttpFiltersSourceAdapter() { @Override public HttpFilters filterRequest(HttpRequest originalRequest, ChannelHandlerContext ctx) { Har har = getHar(); if (har != null && !ProxyUtils.isCONNECT(originalRequest)) { return new HarCaptureFilter(originalRequest, ctx, har, getCurrentHarPage() == null ? null : getCurrentHarPage().getId(), getHarCaptureTypes()); } else { return null; } } }); // HTTP CONNECTs are a special case, since they require special timing and error handling addHttpFilterFactory(new HttpFiltersSourceAdapter() { @Override public HttpFilters filterRequest(HttpRequest originalRequest, ChannelHandlerContext ctx) { Har har = getHar(); if (har != null && ProxyUtils.isCONNECT(originalRequest)) { return new HttpConnectHarCaptureFilter(originalRequest, ctx, har, getCurrentHarPage() == null ? null : getCurrentHarPage().getId()); } else { return null; } } }); } } }
misakuo/Dream-Catcher
app/src/main/java/net/lightbody/bmp/BrowserMobProxyServer.java
Java
mit
42,816
require "spec_helper" describe RefreshTraktTokenJob do subject{described_class.new} Given(:credential){create :credential} Given!(:stub) do stub_request(:post, "https://api-v2launch.trakt.tv/oauth/token") .with(body: {refresh_token: credential.data["refresh_token"], grant_type: "refresh_token"}.to_json).to_return(body: File.new("spec/fixtures/trakt/refresh_token.json").read) end When{subject.perform} Given(:reloaded_credential){credential.reload} Then{expect(stub).to have_been_requested} And{expect(reloaded_credential.data).to include("access_token" => "the_access_token", "refresh_token" => "the_refresh_token")} end
mskog/broad
spec/jobs/refresh_trakt_token_job_spec.rb
Ruby
mit
654
/*! * Angular Material Design * https://github.com/angular/material * @license MIT * v0.11.4-master-5034a04 */ goog.provide('ng.material.components.swipe'); goog.require('ng.material.core'); /** * @ngdoc module * @name material.components.swipe * @description Swipe module! */ /** * @ngdoc directive * @module material.components.swipe * @name mdSwipeLeft * * @restrict A * * @description * The md-swipe-left directives allows you to specify custom behavior when an element is swiped * left. * * @usage * <hljs lang="html"> * <div md-swipe-left="onSwipeLeft()">Swipe me left!</div> * </hljs> */ /** * @ngdoc directive * @module material.components.swipe * @name mdSwipeRight * * @restrict A * * @description * The md-swipe-right directives allows you to specify custom behavior when an element is swiped * right. * * @usage * <hljs lang="html"> * <div md-swipe-right="onSwipeRight()">Swipe me right!</div> * </hljs> */ angular.module('material.components.swipe', ['material.core']) .directive('mdSwipeLeft', getDirective('SwipeLeft')) .directive('mdSwipeRight', getDirective('SwipeRight')); function getDirective(name) { var directiveName = 'md' + name; var eventName = '$md.' + name.toLowerCase(); DirectiveFactory.$inject = ["$parse"]; return DirectiveFactory; /* ngInject */ function DirectiveFactory($parse) { return { restrict: 'A', link: postLink }; function postLink(scope, element, attr) { var fn = $parse(attr[directiveName]); element.on(eventName, function(ev) { scope.$apply(function() { fn(scope, { $event: ev }); }); }); } } } ng.material.components.swipe = angular.module("material.components.swipe");
t0930198/shoait
app/bower_components/angular-material/modules/closure/swipe/swipe.js
JavaScript
mit
1,739
# encoding: utf-8 module BitBucket class Repos::Following < API # List repo followers # # = Examples # bitbucket = BitBucket.new :user => 'user-name', :repo => 'repo-name' # bitbucket.repos.following.followers # bitbucket.repos.following.followers { |watcher| ... } # def followers(user_name, repo_name, params={}) _update_user_repo_params(user_name, repo_name) _validate_user_repo_params(user, repo) unless user? && repo? normalize! params response = get_request("/repositories/#{user}/#{repo.downcase}/followers/", params) return response unless block_given? response.each { |el| yield el } end # List repos being followed by the authenticated user # # = Examples # bitbucket = BitBucket.new :oauth_token => '...', :oauth_secret => '...' # bitbucket.repos.following.followed # def followed(*args) params = args.extract_options! normalize! params response = get_request("/user/follows", params) return response unless block_given? response.each { |el| yield el } end end # Repos::Watching end # BitBucket
fairfaxmedia/bitbucket
lib/bitbucket_rest_api/repos/following.rb
Ruby
mit
1,155
'use strict'; const crypto = require('crypto'); /* lib/handshake.js * WebSocket handshake. * * */ module.exports = exports = function(data){ let headers = exports._headers(data); let sha1 = crypto.createHash('sha1'); sha1.update(headers['sec-websocket-key'] + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'); let resp = exports._headers({ Upgrade: 'websocket', Connection: 'Upgrade', 'Sec-WebSocket-Accept': sha1.digest('base64'), }); this.send(resp); this.emit('handshake-done'); }; exports._headers = function(raw){ // Parsing if (typeof raw === 'string' || raw instanceof Buffer) { if (raw instanceof Buffer) raw = raw.toString('utf-8'); let chunks = raw.split(/\r?\n/), headers = { 0:chunks[0] }, chunk = null, toObj = /^(.+?):\s?/; for (let i = 1; i < chunks.length - 1; i++) { chunk = chunks[i].split(toObj); if (chunk[1] && chunk[2]) headers[chunk[1].toLowerCase()] = chunk[2]; } return headers; } // Building else if (typeof raw === 'object' || !(raw instanceof Buffer)) { let val = null, result = ''; if (typeof raw[0] !== 'undefined') { result += raw[0] + '\r\n'; } else { result += 'HTTP/1.1 101 Switching Protocols\r\n'; } for (let key in raw) { if (typeof key !== 'string') continue; val = raw[key]; result += key + ': ' + val + '\r\n'; } return result + '\r\n'; } };
jamen/rela
lib/handshake.js
JavaScript
mit
1,440
require 'spec_helper' describe 'osx::time_machine::ask_to_use_new_disks_for_backup' do let(:facts) { {:boxen_user => 'ilikebees' } } describe('enabled') do let(:params) { {:ensure => 'present'} } it 'should set the value to true' do should contain_boxen__osx_defaults('Toggle Whether Time Machine Asks to Use New Disks for Backup').with({ :user => facts[:boxen_user], :key => 'DoNotOfferNewDisksForBackup', :domain => 'com.apple.TimeMachine', :value => true, }) end end describe('disabled') do let(:params) { {:ensure => 'absent'} } it 'should set the value to false' do should contain_boxen__osx_defaults('Toggle Whether Time Machine Asks to Use New Disks for Backup').with({ :user => facts[:boxen_user], :key => 'DoNotOfferNewDisksForBackup', :domain => 'com.apple.TimeMachine', :value => false, }) end end end
joebadmo/puppet-osx
spec/classes/time_machine/ask_to_use_new_disks_for_backup_spec.rb
Ruby
mit
950
<?php namespace Helpvel\Helpvel; use Illuminate\Support\ServiceProvider; class HelpvelServiceProvider 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('helpvel/helpvel'); } /** * Register the service provider. * * @return void */ public function register() { // } /** * Get the services provided by the provider. * * @return array */ public function provides() { return array(); } }
Helpvel/helpvel
src/Helpvel/Helpvel/HelpvelServiceProvider.php
PHP
mit
617
############### ### imports ### ############### from fabric.api import cd, env, lcd, put, prompt, local, sudo from fabric.contrib.files import exists ############## ### config ### ############## local_app_dir = './flask_project' local_config_dir = './config' remote_app_dir = '/home/www' remote_git_dir = '/home/git' remote_flask_dir = remote_app_dir + '/flask_project' remote_nginx_dir = '/etc/nginx/sites-enabled' remote_supervisor_dir = '/etc/supervisor/conf.d' env.hosts = ['add_ip_or_domain'] # replace with IP address or hostname env.user = 'newuser' # env.password = 'blah!' ############# ### tasks ### ############# def install_requirements(): """ Install required packages. """ sudo('apt-get update') sudo('apt-get install -y python') sudo('apt-get install -y python-pip') sudo('apt-get install -y python-virtualenv') sudo('apt-get install -y nginx') sudo('apt-get install -y gunicorn') sudo('apt-get install -y supervisor') sudo('apt-get install -y git') def install_flask(): """ 1. Create project directories 2. Create and activate a virtualenv 3. Copy Flask files to remote host """ if exists(remote_app_dir) is False: sudo('mkdir ' + remote_app_dir) if exists(remote_flask_dir) is False: sudo('mkdir ' + remote_flask_dir) with lcd(local_app_dir): with cd(remote_app_dir): sudo('virtualenv env') sudo('source env/bin/activate') sudo('pip install Flask==0.10.1') with cd(remote_flask_dir): put('*', './', use_sudo=True) def configure_nginx(): """ 1. Remove default nginx config file 2. Create new config file 3. Setup new symbolic link 4. Copy local config to remote config 5. Restart nginx """ sudo('/etc/init.d/nginx start') if exists('/etc/nginx/sites-enabled/default'): sudo('rm /etc/nginx/sites-enabled/default') if exists('/etc/nginx/sites-enabled/flask_project') is False: sudo('touch /etc/nginx/sites-available/flask_project') sudo('ln -s /etc/nginx/sites-available/flask_project' + ' /etc/nginx/sites-enabled/flask_project') with lcd(local_config_dir): with cd(remote_nginx_dir): put('./flask_project', './', use_sudo=True) sudo('/etc/init.d/nginx restart') def configure_supervisor(): """ 1. Create new supervisor config file 2. Copy local config to remote config 3. Register new command """ if exists('/etc/supervisor/conf.d/flask_project.conf') is False: with lcd(local_config_dir): with cd(remote_supervisor_dir): put('./flask_project.conf', './', use_sudo=True) sudo('supervisorctl reread') sudo('supervisorctl update') def configure_git(): """ 1. Setup bare Git repo 2. Create post-receive hook """ if exists(remote_git_dir) is False: sudo('mkdir ' + remote_git_dir) with cd(remote_git_dir): sudo('mkdir flask_project.git') with cd('flask_project.git'): sudo('git init --bare') with lcd(local_config_dir): with cd('hooks'): put('./post-receive', './', use_sudo=True) sudo('chmod +x post-receive') def run_app(): """ Run the app! """ with cd(remote_flask_dir): sudo('supervisorctl start flask_project') def deploy(): """ 1. Copy new Flask files 2. Restart gunicorn via supervisor """ with lcd(local_app_dir): local('git add -A') commit_message = prompt("Commit message?") local('git commit -am "{0}"'.format(commit_message)) local('git push production master') sudo('supervisorctl restart flask_project') def rollback(): """ 1. Quick rollback in case of error 2. Restart gunicorn via supervisor """ with lcd(local_app_dir): local('git revert master --no-edit') local('git push production master') sudo('supervisorctl restart flask_project') def status(): """ Is our app live? """ sudo('supervisorctl status') def create(): install_requirements() install_flask() configure_nginx() configure_supervisor() configure_git()
kaiocesar/automation-fab
fabfile.py
Python
mit
4,325
# encoding: UTF-8 # Author:: Akira FUNAI # Copyright:: Copyright (c) 2009 Akira FUNAI require "#{::File.dirname __FILE__}/t" class TC_Text < Test::Unit::TestCase def setup meta = nil Bike::Parser.gsub_scalar('$(foo text 3 1..5)') {|id, m| meta = m '' } @f = Bike::Field.instance meta end def teardown end def test_meta assert_equal( 3, @f[:size], 'Text#initialize should set :size from the token' ) assert_equal( 1, @f[:min], 'Text#initialize should set :min from the range token' ) assert_equal( 5, @f[:max], 'Text#initialize should set :max from the range token' ) end def test_val_cast assert_equal( '', @f.val, 'Text#val_cast should cast the given val to String' ) @f.load 123 assert_equal( '123', @f.val, 'Text#val_cast should cast the given val to String' ) end def test_get @f.load 'bar' assert_equal( 'bar', @f.get, 'Text#get should return proper string' ) assert_equal( '<span class="text"><input type="text" name="" value="bar" size="3" /></span>', @f.get(:action => :update), 'Text#get should return proper string' ) @f.load '<bar>' assert_equal( '&lt;bar&gt;', @f.get, 'Text#get should escape the special characters' ) assert_equal( '<span class="text"><input type="text" name="" value="&lt;bar&gt;" size="3" /></span>', @f.get(:action => :update), 'Text#get should escape the special characters' ) end def test_errors @f.load '' @f[:min] = 0 assert_equal( [], @f.errors, 'Text#errors should return the errors of the current val' ) @f[:min] = 1 assert_equal( ['mandatory'], @f.errors, 'Text#errors should return the errors of the current val' ) @f.load 'a' @f[:min] = 1 assert_equal( [], @f.errors, 'Text#errors should return the errors of the current val' ) @f[:min] = 2 assert_equal( ['too short: 2 characters minimum'], @f.errors, 'Text#errors should return the errors of the current val' ) @f.load 'abcde' @f[:max] = 5 assert_equal( [], @f.errors, 'Text#errors should return the errors of the current val' ) @f[:max] = 4 assert_equal( ['too long: 4 characters maximum'], @f.errors, 'Text#errors should return the errors of the current val' ) end end
afunai/bike
t/test_text.rb
Ruby
mit
2,573
import React from 'react'; import ReactDOM from 'react-dom'; import Deferred from 'deferred-js'; import ElementsModel from './visualizution/elementsModel'; import ElementsList from './visualizution/elementsList'; import ControlsView from './controls/controlsView'; import Immutable from 'immutable'; import styles from '../stylesheets/index.styl'; let state = Immutable.Map({}); const actions = {}; const elementsModel = new ElementsModel(); const elementsList = new ElementsList(); const initApp = () => { elementsList.setElement('periodic-table-data-visualization'); elementsList.setModel(elementsModel); elementsModel.fetch().done(() => { initElements(); elementsList.render(); }); }; const initElements = () => { const colors = { 'nonmetal': '#CD51CB', 'noble gas': '#73D74D', 'alkali metal': '#D55438', 'alkaline earth metal': '#559BBA', 'metalloid': '#57D29E', 'halogen': '#CC567E', 'metal': '#5D8A3A', 'transition metal': '#917ACA', 'lanthanoid': '#BE8630', 'actinoid': '#CDD143' }; setState({ parameters: [ 'atomicNumber', 'groupBlock', 'name', 'symbol' ], selectedSortingKey: 'groupBlock', colors }); elementsList.setColors(colors); }; // Actions actions.onSortingChanged = (selectedSortingKey) => { elementsList.setSortingKey(selectedSortingKey); elementsList.render(); setState({selectedSortingKey}) }; function setState(changes) { state = state.mergeDeep(changes); let Component = React.createElement(ControlsView, { state: state, actions }); ReactDOM.render(Component, document.getElementById('periodic-table-controls')); } window.document.addEventListener('DOMContentLoaded', initApp);
vogelino/periodic-table-data-visualization
src/js/index.js
JavaScript
mit
1,705
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SocketDog.Common { public struct ConnectionProtocol { public ConnectionProtocol(Type value) : this() { Value = value; } public enum Type { Tcp = 6, Udp = 17 } public Type Value { get; private set; } public override string ToString() { return Value.ToString(); } public static List<ConnectionProtocol> GetList() { return new List<ConnectionProtocol>(2) { new ConnectionProtocol(Type.Tcp), new ConnectionProtocol(Type.Udp) }; } } }
deniskucherov/SocketDog
SocketDog.Common/ConnectionProtocol.cs
C#
mit
809
package com.myconnector.domain; import com.myconnector.domain.base.BaseDictionary; public class Dictionary extends BaseDictionary { private static final long serialVersionUID = 1L; /*[CONSTRUCTOR MARKER BEGIN]*/ public Dictionary () { super(); } /** * Constructor for primary key */ public Dictionary (java.lang.String word) { super(word); } /*[CONSTRUCTOR MARKER END]*/ }
nileshk/myconnector
src/main/java/com/myconnector/domain/Dictionary.java
Java
mit
395
/* * The MIT License * * Copyright 2017 Arvind Sasikumar. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package sync.db.mysql; import java.sql.*; /** * An object of this class serves as the agent for the synchronization process. * All synchronization tasks are handed over to an object of this class, which * then takes the required steps to perform the actual synchronization depending * on its set properties. It requires all details for establishing a connection * to the server and client MySQL servers and some additional synchronization * specific properties.<p> * An object of this class is created using the Builder pattern as opposed to * the usual constructor based initialization.<p> * An example on using the Builder pattern to create a new DBSyncObject:<p> * <pre> * {@code * DBSyncAgent dbSyncAgent = new DBSyncAgent.Builder() .setServerDatabaseAddress("localhost") .setServerDatabaseName("test1") .setServerDatabaseUsername("root") .setServerDatabasePassword("root") .setServerDatabasePort(3306) .setServerDatabaseConnectionOptions("?useSSL=false") .setClientDatabaseAddress("localhost") .setClientDatabaseName("test2") .setClientDatabaseUsername("root") .setClientDatabasePassword("root") .setClientDatabasePort(3306) .setClientDatabaseConnectionOptions("?useSSL=false") .setDBMap(dbMap) .setSyncInterval(12) .build(); * } * </pre> * @see #DBSyncAgent(sync.db.mysql.DBSyncAgent.Builder) * @author Arvind Sasikumar */ public class DBSyncAgent { private final String serverDatabaseAddress; private final String serverDatabaseName; private final String serverDatabaseUsername; private final String serverDatabasePassword; private final String serverDatabaseConnectionOptions; private final int serverDatabasePort; private final String clientDatabaseAddress; private final String clientDatabaseName; private final String clientDatabaseUsername; private final String clientDatabasePassword; private final String clientDatabaseConnectionOptions; private final int clientDatabasePort; private final DBMap dbMap; private int syncInterval; private Connection serverConnection; private Connection clientConnection; private Statement serverStatement; private Statement clientStatement; private DBSynchronizer dbSynchronizer; private Thread dbSynchronizerThread; /** * Build the DBSyncAgent class using the Builder pattern. * @author Arvind Sasikumar * @see <a href="http://stackoverflow.com/questions/328496/when-would-you-use-the-builder-pattern">Builder Pattern</a> */ public static class Builder{ private String serverDatabaseAddress; private String serverDatabaseName; private String serverDatabaseUsername; private String serverDatabasePassword; private String serverDatabaseConnectionOptions; private int serverDatabasePort; private String clientDatabaseAddress; private String clientDatabaseName; private String clientDatabaseUsername; private String clientDatabasePassword; private String clientDatabaseConnectionOptions; private int clientDatabasePort; private DBMap dbMap; private int syncInterval; /** * Set the address of the server database. * @param serverDatabaseAddress address of the server database, * e.g. "localhost" or "59.23.54.22" * @return Builder object as per the Builder pattern */ public Builder setServerDatabaseAddress(String serverDatabaseAddress){ this.serverDatabaseAddress = serverDatabaseAddress; return this; } /** * Set the name of the server database. * @param serverDatabaseName name of the server database, e.g. "testdb" * @return Builder object as per the Builder pattern */ public Builder setServerDatabaseName(String serverDatabaseName){ this.serverDatabaseName = serverDatabaseName; return this; } /** * Set the username to access the server database. * @param serverDatabaseUsername username to access the server database * @return Builder object as per the Builder pattern */ public Builder setServerDatabaseUsername(String serverDatabaseUsername){ this.serverDatabaseUsername = serverDatabaseUsername; return this; } /** * Set the password to access the server database. * @param serverDatabasePassword password to access the server database * @return Builder object as per the Builder pattern */ public Builder setServerDatabasePassword(String serverDatabasePassword){ this.serverDatabasePassword = serverDatabasePassword; return this; } /** * Set the optional connection string to be used for the server * connection. * All options in the MySQL connection string as per the Connector/J * appear here. e.g. "?useSSL=false" * @param serverDatabaseConnectionOptions optional connection string * @return Builder object as per the Builder pattern */ public Builder setServerDatabaseConnectionOptions(String serverDatabaseConnectionOptions){ this.serverDatabaseConnectionOptions = serverDatabaseConnectionOptions; return this; } /** * Set the port for the server connection. * @param serverDatabasePort port for the server connection, e.g. 3306 * @return Builder object as per the Builder pattern */ public Builder setServerDatabasePort(int serverDatabasePort){ this.serverDatabasePort = serverDatabasePort; return this; } /** * Set the address of the client database. * @param clientDatabaseAddress address of the client database, * e.g. "localhost" or "59.23.54.22" * @return Builder object as per the Builder pattern */ public Builder setClientDatabaseAddress(String clientDatabaseAddress){ this.clientDatabaseAddress = clientDatabaseAddress; return this; } /** * Set the name of the client database. * @param clientDatabaseName name of the client database, e.g. "testdb" * @return Builder object as per the Builder pattern */ public Builder setClientDatabaseName(String clientDatabaseName){ this.clientDatabaseName = clientDatabaseName; return this; } /** * Set the username to access the client database. * @param clientDatabaseUsername username to access the client database * @return Builder object as per the Builder pattern */ public Builder setClientDatabaseUsername(String clientDatabaseUsername){ this.clientDatabaseUsername = clientDatabaseUsername; return this; } /** * Set the password to access the client database. * @param clientDatabasePassword password to access the client database * @return Builder object as per the Builder pattern */ public Builder setClientDatabasePassword(String clientDatabasePassword){ this.clientDatabasePassword = clientDatabasePassword; return this; } /** * Set the optional connection string to be used for the client * connection. * All options in the MySQL connection string as per the Connector/J * appear here. e.g. "?useSSL=false" * @param clientDatabaseConnectionOptions optional connection string * @return Builder object as per the Builder pattern */ public Builder setClientDatabaseConnectionOptions(String clientDatabaseConnectionOptions){ this.clientDatabaseConnectionOptions = clientDatabaseConnectionOptions; return this; } /** * Set the port for the client connection. * @param clientDatabasePort port for the client connection, e.g. 3306 * @return Builder object as per the Builder pattern */ public Builder setClientDatabasePort(int clientDatabasePort){ this.clientDatabasePort = clientDatabasePort; return this; } /** * Set the database map. * @param dbMap database map * @return Builder object as per the Builder pattern */ public Builder setDBMap(DBMap dbMap){ this.dbMap = dbMap; return this; } /** * Set the synchronization interval. * This specifies the time interval between two successive * synchronization attempts during a live sync. Specified in seconds. * @param syncInterval synchronization interval in seconds * @return Builder object as per the Builder pattern */ public Builder setSyncInterval(int syncInterval){ this.syncInterval = syncInterval; return this; } /** * Build the DBSyncAgent object using the Builder pattern after all * properties have been set using the Builder class. * @return a new DBSyncAgent object with all properties set * @see <a href="http://stackoverflow.com/questions/328496/when-would-you-use-the-builder-pattern">Builder Pattern</a> */ public DBSyncAgent build(){ return new DBSyncAgent(this); } } /** * Create a new DBSyncAgent object using the Builder Pattern. * This constructor is declared as private and is hence not accessible from * outside. To use this constructor, one must use the Builder pattern. * @param builder the builder object used to build the new DBSyncAgent * object using the Builder pattern * @see <a href="http://stackoverflow.com/questions/328496/when-would-you-use-the-builder-pattern">Builder Pattern</a> */ private DBSyncAgent(Builder builder){ serverDatabaseAddress = builder.serverDatabaseAddress; serverDatabaseName = builder.serverDatabaseName; serverDatabaseUsername = builder.serverDatabaseUsername; serverDatabasePassword = builder.serverDatabasePassword; serverDatabaseConnectionOptions = builder.serverDatabaseConnectionOptions; serverDatabasePort = builder.serverDatabasePort; clientDatabaseAddress = builder.clientDatabaseAddress; clientDatabaseName = builder.clientDatabaseName; clientDatabaseUsername = builder.clientDatabaseUsername; clientDatabasePassword = builder.clientDatabasePassword; clientDatabaseConnectionOptions = builder.clientDatabaseConnectionOptions; clientDatabasePort = builder.clientDatabasePort; dbMap = builder.dbMap; syncInterval = builder.syncInterval; } /** * Set the synchronization interval. * This specifies the time interval between two successive * synchronization attempts during a live sync. Specified in seconds. * @param syncInterval synchronization interval in seconds */ public void setSyncInterval(int syncInterval){ this.syncInterval = syncInterval; } /** * Connects to the client and server databases as per the set properties. */ public void connect(){ try{ System.out.println("\nAttempting connection..."); Class.forName("com.mysql.jdbc.Driver"); String connectionString = "jdbc:mysql://" + serverDatabaseAddress + ":" + serverDatabasePort + "/" + serverDatabaseName + serverDatabaseConnectionOptions; serverConnection = DriverManager.getConnection(connectionString, serverDatabaseUsername,serverDatabasePassword); serverStatement = serverConnection.createStatement(); connectionString = "jdbc:mysql://" + clientDatabaseAddress + ":" + clientDatabasePort + "/" + clientDatabaseName + clientDatabaseConnectionOptions; clientConnection = DriverManager.getConnection(connectionString, clientDatabaseUsername,clientDatabasePassword); clientStatement = clientConnection.createStatement(); System.out.println("Connection successful!"); } catch(Exception e){ e.printStackTrace(); } } /** * Performs initial synchronization between the client and the server * databases. * When synchronization is done for the first time or after a reasonable * interval of time, call this function before calling the {@link #liveSync()}. */ public void sync(){ dbSynchronizer = new DBSynchronizer(serverStatement, clientStatement, dbMap); dbSynchronizerThread = new Thread(dbSynchronizer); dbSynchronizerThread.start(); } /** * Synchronizes the client and the server databases periodically. * This synchronization is done periodically as specified using * {@link #setSyncInterval(int)} or initialized using the Builder pattern. */ public void liveSync(){ dbSynchronizer = new DBSynchronizer(serverStatement, clientStatement, dbMap, syncInterval); dbSynchronizerThread = new Thread(dbSynchronizer); dbSynchronizerThread.start(); } /** * Stops the synchronization process. * The current transaction will be finished before the stop takes places * to make sure the database is in proper state. */ public void stopSync(){ dbSynchronizer.stopSync(); } /** * Disconnects the existing client and server connections safely. * Call this method after calling {@link #stopSync()}. */ public void disconnect(){ try{ System.out.println("\nDisconnecting..."); clientStatement.close(); serverStatement.close(); clientConnection.close(); serverConnection.close(); System.out.println("Disconnected."); } catch(Exception e){ e.printStackTrace(); } } /** * Waits for the worker thread to finish its job before proceeding forward. * Call this method between {@link #sync()} and {@link #liveSync()}. */ public void hold(){ try{ dbSynchronizerThread.join(); } catch(Exception e){ e.printStackTrace(); } } }
arvindsasikumar/mysql-db-sync
sync/db/mysql/DBSyncAgent.java
Java
mit
17,612
<?php namespace Forecast\WeatherBundle\DependencyInjection; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\Config\FileLocator; use Symfony\Component\HttpKernel\DependencyInjection\Extension; use Symfony\Component\DependencyInjection\Loader; /** * This is the class that loads and manages your bundle configuration * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html} */ class ForecastWeatherExtension extends Extension { /** * {@inheritDoc} */ public function load(array $configs, ContainerBuilder $container) { $configuration = new Configuration(); $config = $this->processConfiguration($configuration, $configs); $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('services.yml'); $loader->load(sprintf('%s.yml', $config['db_driver'])); } }
alexastro/forecast
src/Forecast/WeatherBundle/DependencyInjection/ForecastWeatherExtension.php
PHP
mit
962
from django.contrib import admin from api_boilerplate.models import ApiKey admin.site.register(ApiKey)
kippt/django-api-boilerplate
api_boilerplate/admin.py
Python
mit
105
package com.sparcs.casino; import com.sparcs.casino.game.Bet; public interface Account { /** * @return The {@link Customer} who owns this Account. */ Customer getCustomer(); /** * @return The number of chips the Customer currently holds */ int getChipCount(); /** * A {@link Bet} has been won! - add chips * * @param pot Number of chips won */ void addChips(int pot); /** * A {@link Bet} has been accepted - remove chips * * @param stake Number of chips wagered. */ void deductChips(int stake); }
sparcs360/Casino
game-srvkit/src/main/java/com/sparcs/casino/Account.java
Java
mit
538
/* Generated By:JJTree: Do not edit this line. ASTInclusiveORExpression.java Version 4.3 */ /* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=true,TRACK_TOKENS=true,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ package org.iguanatool.testobject.cparser; public class ASTInclusiveORExpression extends SimpleNode { public ASTInclusiveORExpression(int id) { super(id); } public ASTInclusiveORExpression(CParser p, int id) { super(p, id); } /** * Accept the visitor. **/ public void jjtAccept(CParserVisitor visitor) { visitor.visit(this); } } /* JavaCC - OriginalChecksum=9dfaa0b606df3826250d5b96a252215d (do not edit this line) */
iguanatool/iguana
src/main/java/org/iguanatool/testobject/cparser/ASTInclusiveORExpression.java
Java
mit
742
package fi.csc.chipster.rest.websocket; import java.io.IOException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import jakarta.websocket.CloseReason; import jakarta.websocket.CloseReason.CloseCodes; import jakarta.websocket.Endpoint; import jakarta.websocket.EndpointConfig; import jakarta.websocket.MessageHandler; import jakarta.websocket.PongMessage; import jakarta.websocket.Session; public class WebSocketClientEndpoint extends Endpoint { public static interface EndpointListener { public void onOpen(Session session, EndpointConfig config); public void onClose(Session session, CloseReason reason); public void onError(Session session, Throwable thr); } private static final Logger logger = LogManager.getLogger(); private MessageHandler messageHandler; private CountDownLatch disconnectLatch; private CountDownLatch connectLatch = new CountDownLatch(1); private CloseReason closeReason; private Throwable throwable; private Session session; private EndpointListener endpointListener; public WebSocketClientEndpoint(MessageHandler.Whole<String> messageHandler, EndpointListener endpointListener) { this.messageHandler = messageHandler; this.endpointListener = endpointListener; } @Override public void onOpen(Session session, EndpointConfig config) { logger.debug("WebSocket client onOpen"); this.session = session; if (messageHandler != null) { session.addMessageHandler(messageHandler); } disconnectLatch = new CountDownLatch(1); /* Wait for connection or error * * If the server would use HTTP errors for signaling e.g. authentication errors, at this point * we would already know that the connection was successful. Unfortunately JSR 356 Java API * for WebSocket doesn't support servlet filters or other methods * for responding with HTTP errors to the original WebSocket upgrade request. * * The server will check the authentication in the onOpen() method and close the connection if * the authentication fails. We'll know that the authentication failed when the onClose() method * is called here in the client. The problem is to know when the authentication was * accepted. This is solved by sending a ping. If we get the ping reply, we know that authentication * was accepted. * * We have to wait for the ping reply in another thread, blocking this onOpen() method seems to stop also * the ping or it's reply (understandably). * * Side note: this logic is not critical for the information security, that has to be taken care in the server * side. However, this is critical for reliable tests and for the server's to notice when their connection * to other services fail. */ new Thread(new Runnable() { @Override public void run() { try { ping(); connectLatch.countDown(); } catch (IllegalArgumentException | IOException | TimeoutException | InterruptedException e) { logger.warn("WebSocket client error", e); } } }, "websocket-connection-ping").start(); this.endpointListener.onOpen(session, config); } @Override public void onClose(Session session, CloseReason reason) { logger.debug("WebSocket client onClose: " + reason); closeReason = reason; connectLatch.countDown(); disconnectLatch.countDown(); this.endpointListener.onClose(session, reason); } @Override public void onError(Session session, Throwable thr) { logger.debug("WebSocket client onError: " + thr.getMessage()); throwable = thr; connectLatch.countDown(); disconnectLatch.countDown(); this.endpointListener.onError(session, thr); } public void close() throws IOException { session.close(new CloseReason(CloseCodes.NORMAL_CLOSURE, "client closing")); } public boolean waitForDisconnect(long timeout) throws InterruptedException { logger.debug("WebSocket client will wait for disconnect max " + timeout + " seconds"); return disconnectLatch.await(timeout, TimeUnit.SECONDS); } public void waitForConnection() throws InterruptedException, WebSocketClosedException, WebSocketErrorException { logger.debug("WebSocket client waiting for connection " + closeReason); connectLatch.await(); if (closeReason != null) { throw new WebSocketClosedException(closeReason); } else if (throwable != null) { // most likely error in the HTTP upgrade request, probably happens // only if the configuration or network is broken throw new WebSocketErrorException(throwable); } } public void sendText(String text) throws IOException { session.getBasicRemote().sendText(text); } public void ping() throws IllegalArgumentException, IOException, TimeoutException, InterruptedException { logger.debug("WebSocket client sends ping"); PongHandler pongHandler = new PongHandler(); session.addMessageHandler(pongHandler); session.getBasicRemote().sendPing(null); pongHandler.await(); session.removeMessageHandler(pongHandler); } public static class PongHandler implements MessageHandler.Whole<PongMessage> { private CountDownLatch latch = new CountDownLatch(1); @Override public void onMessage(PongMessage message) { logger.debug("WebSocket client received pong"); latch.countDown(); } public void await() throws TimeoutException, InterruptedException { int timeout = 2; logger.debug("WebSocket client will wait for pong max " + timeout + " seconds"); boolean received = latch.await(timeout, TimeUnit.SECONDS); if (!received) { throw new TimeoutException("timeout while waiting for pong message"); } } } }
chipster/chipster-web-server
src/main/java/fi/csc/chipster/rest/websocket/WebSocketClientEndpoint.java
Java
mit
5,780
package com.infullmobile.jenkins.plugin.restrictedregister.settings; import hudson.model.AbstractDescribableImpl; import hudson.model.Descriptor; /** * Created by Adam Kobus on 27.05.2016. * Copyright (c) 2016 inFullMobile * License: MIT, file: /LICENSE */ public abstract class RegistrationRuleConfig extends AbstractDescribableImpl<RegistrationRuleConfig> { public abstract static class DescriptorImpl extends Descriptor<RegistrationRuleConfig> { } }
inFullMobile/restricted-register-plugin
src/main/java/com/infullmobile/jenkins/plugin/restrictedregister/settings/RegistrationRuleConfig.java
Java
mit
469
require 'open3' When(/^I execute it via the execute function of the PuppetShow module$/) do @results = PuppetShow.execute(@file) end When(/^I execute the PuppetShow binary with the option:$/) do |opt| cmd = "./bin/puppetshow #{opt}" @stdout_str, @status = Open3.capture2(cmd) end When(/^I execute it via the PuppetShow binary$/) do cmd = "./bin/puppetshow #{@file}" @stdout_str, @status = Open3.capture2(cmd) end
ludokng/puppetshow
features/step_definitions/execute_steps.rb
Ruby
mit
428
/* @author rich * Created on 07-Jul-2003 * * This code is covered by a Creative Commons * Attribution, Non Commercial, Share Alike license * <a href="http://creativecommons.org/licenses/by-nc-sa/1.0">License</a> */ package org.lsmp.djep.vectorJep.values; import org.lsmp.djep.vectorJep.*; //import JSci.maths.DoubleMatrix; //import JSci.physics.relativity.Rank1Tensor; /** * Represents a matrix. * * @author Rich Morris * Created on 07-Jul-2003 * @version 2.3.0.2 now extends number * @version 2.3.1.1 Bug with non square matricies fixed. * @since 2.3.2 Added equals method. */ public class Matrix extends Number implements MatrixValueI { // want package access to simplify addition of matricies int rows=0; int cols=0; Object data[][] = null; Dimensions dims; private Matrix() {} /** Construct a matrix with given rows and cols. */ public Matrix(int rows,int cols) { this.rows = rows; this.cols = cols; data = new Object[rows][cols]; dims = Dimensions.valueOf(rows,cols); } /** * Construct a Matrix from a set of row vectors. * @param vecs */ /* public Matrix(MVector[] vecs) throws ParseException { if(vecs==null) { throw new ParseException("Tried to create a matrix with null row vectors"); } rows = vecs.length; if(rows==0) { throw new ParseException("Tried to create a matrix with zero row vectors"); } // now check that each vector has the same size. cols = vecs[0].size(); for(int i = 1;i<rows;++i) if(cols != vecs[i].size()) throw new ParseException("Each vector must be of the same size"); data = new Object[rows][cols]; for(int i = 0;i<rows;++i) for(int j=0;j<cols;++j) { data[i][j]= vecs[i].elementAt(j); if(data[i][j] == null) throw new ParseException("Null element in vector"); } } */ /** * Returns a string rep of matrix. Uses [[a,b],[c,d]] syntax. */ public String toString() { StringBuffer sb = new StringBuffer(); sb.append('['); for(int i = 0;i<rows;++i) { if(i>0) sb.append(','); sb.append('['); for(int j=0;j<cols;++j) { if(j>0)sb.append(','); sb.append(data[i][j]); } sb.append(']'); } sb.append(']'); return sb.toString(); } public Dimensions getDim() { return dims; } public int getNumEles() { return rows*cols; } public int getNumRows() { return rows; } public int getNumCols() { return cols; } public void setEle(int n,Object value) { int i = n / cols; int j = n % cols; data[i][j] = value; } public void setEle(int i,int j,Object value) { data[i][j] = value; } public Object getEle(int n) { int i = n / cols; int j = n % cols; return data[i][j]; } public Object getEle(int i,int j) { return data[i][j]; } public Object[][] getEles() { return data; } /** sets the elements to those of the arguments. */ public void setEles(MatrixValueI val) { if(!dims.equals(val.getDim())) return; for(int i=0;i<rows;++i) System.arraycopy(((Matrix) val).data[i],0,data[i],0,cols); } /** value of ele(1,1). */ public int intValue() {return ((Number) data[0][0]).intValue(); } /** value of ele(1,1). */ public long longValue() {return ((Number) data[0][0]).longValue(); } /** value of ele(1,1). */ public float floatValue() { return ((Number) data[0][0]).floatValue(); } /** value of ele(1,1). */ public double doubleValue() {return ((Number) data[0][0]).doubleValue(); } /** Are two matricies equal, element by element * Overrides Object. */ public boolean equals(Object obj) { if(!(obj instanceof Matrix)) return false; Matrix mat = (Matrix) obj; if(!mat.getDim().equals(getDim())) return false; for(int i=0;i<rows;++i) for(int j=0;j<cols;++j) if(!data[i][j].equals(mat.data[i][j])) return false; return true; } /** * Always override hashCode when you override equals. * Efective Java, Joshua Bloch, Sun Press */ public int hashCode() { int result = 17; // long xl = Double.doubleToLongBits(this.re); // long yl = Double.doubleToLongBits(this.im); // int xi = (int)(xl^(xl>>32)); // int yi = (int)(yl^(yl>>32)); for(int i=0;i<rows;++i) for(int j=0;j<cols;++j) result = 37*result+ data[i][j].hashCode(); return result; } }
Kailashrb/Jep
src/org/lsmp/djep/vectorJep/values/Matrix.java
Java
mit
4,371
var demand = require('must'), DateArrayType = require('../DateArrayType'); exports.initList = function(List) { List.add({ datearr: { type: DateArrayType }, nested: { datearr: { type: DateArrayType } } }); }; exports.testFieldType = function(List) { var testItem = new List.model(); it('should default to an empty array', function() { demand(testItem.get('datearr')).eql([]); }); it('should validate input', function() { demand(List.fields.datearr.inputIsValid({ datearr: '2015-03-03' })).be(true); demand(List.fields.datearr.inputIsValid({ datearr: ['2015-03-03'] })).be(true); demand(List.fields.datearr.inputIsValid({ datearr: ['2015-03-03', '2015-03-04'] })).be(true); }); it('should validate no input', function() { demand(List.fields.datearr.inputIsValid({})).be(true); demand(List.fields.datearr.inputIsValid({}, true)).be(false); testItem.datearr = ['2015-03-03']; demand(List.fields.datearr.inputIsValid({}, true, testItem)).be(true); testItem.datearr = undefined; }); it('should validate length when required', function() { demand(List.fields.datearr.inputIsValid({ datearr: [] }, true)).be(false); }); it('should invalidate arrays with invalid dates', function() { demand(List.fields.datearr.inputIsValid({ datearr: 'not a real date' })).be(false); demand(List.fields.datearr.inputIsValid({ datearr: ['2001-01-35'] })).be(false); demand(List.fields.datearr.inputIsValid({ datearr: ['35-34-3210', '2001-01-01'] })).be(false); }); it('should update top level fields', function(done) { List.fields.datearr.updateItem(testItem, { datearr: ['2015-01-01', '2015-01-02', '2015-01-03', '2015-01-04'] }, function () { demand(testItem.datearr).eql([new Date('2015-01-01'), new Date('2015-01-02'), new Date('2015-01-03'), new Date('2015-01-04')]); testItem.datearr = undefined; done(); }); }); it('should update nested fields', function(done) { List.fields['nested.datearr'].updateItem(testItem, { nested: { datearr: ['2015-01-01', '2015-01-02', '2015-01-03', '2015-01-04'] } }, function () { demand(testItem.nested.datearr).eql([new Date('2015-01-01'), new Date('2015-01-02'), new Date('2015-01-03'), new Date('2015-01-04')]); testItem.nested.datearr = undefined; done(); }); }); it('should update nested fields with flat paths', function(done) { List.fields['nested.datearr'].updateItem(testItem, { 'nested.datearr': ['2015-01-01', '2015-01-02', '2015-01-03', '2015-01-04'] }, function () { demand(testItem.nested.datearr).eql([new Date('2015-01-01'), new Date('2015-01-02'), new Date('2015-01-03'), new Date('2015-01-04')]); testItem.nested.datearr = undefined; done(); }); }); it('should update empty arrays', function(done) { List.fields.datearr.updateItem(testItem, { datearr: [] }, function () { demand(testItem.datearr).eql([]); testItem.datearr = undefined; done(); }); }); it('should default on null', function(done) { List.fields.datearr.updateItem(testItem, { datearr: null }, function () { demand(testItem.datearr).eql([]); testItem.datearr = undefined; done(); }); }); it('should allow a single date value', function(done) { List.fields.datearr.updateItem(testItem, { datearr: '2015-01-01' }, function () { demand(testItem.datearr).eql([new Date('2015-01-01')]); testItem.datearr = undefined; done(); }); }); };
riyadhalnur/keystone
fields/types/datearray/test/server.js
JavaScript
mit
3,459
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-04-24 22:03 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('samples', '0004_sample'), ] operations = [ migrations.CreateModel( name='CollectionType', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('method_name', models.CharField(max_length=255, verbose_name='Método de coleta')), ('is_primary', models.BooleanField(default=True, verbose_name='Principal?')), ], ), migrations.AlterField( model_name='fluvaccine', name='was_applied', field=models.NullBooleanField(verbose_name='Recebeu vacina contra gripe?'), ), migrations.AddField( model_name='sample', name='collection_type', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='samples.CollectionType'), ), ]
gcrsaldanha/fiocruz
samples/migrations/0005_auto_20170424_1903.py
Python
mit
1,172
# -*- coding:utf-8 -*- import os def split_screen(): val = os.system("xrandr --output HDMI1 --right-of VGA1 --auto") def run_sensorcmd_web(): path = "/home/suyf/swork/git/sensorcmd-web/web/" os.chdir(path) val = os.system("./apprun.py") def run_cas(): path = "/home/suyf/swork/git/cas/web/" os.chdir(path) val = os.system("./casrun.py") def run_windpower(): path = "/home/suyf/swork/git/windpower/web" os.chdir(path) val = os.system("python apprun.py") if __name__ == '__main__': choose = input("Please choose your project(int):\n 1:cas\n 2:sensorcmd-web\n 3:windpower\n") if int(choose) == 1: cas_val = run_cas() print val if int(choose) == 2: cas_val = run_cas() val = run_sensorcmd_web() print val,cas_val if int(choose) == 3: val = run_windpower() print val
myyyy/wiki
shell/work_start.py
Python
mit
791
module.exports = { root: 'src', rulesDir: 'rules', rules: { 'stricter/unused-files': [ { level: 'error', config: { entry: [/.*[\\\/]src[\\\/]index\.ts/, /.*__snapshots__.*/, /.*__fixtures__.*/], relatedEntry: [/.*test\.ts/, /.*[\\\/]src[\\\/]start-debug\.ts/], }, }, ], 'stricter/circular-dependencies': [ { level: 'error', exclude: [/integration-tests[\\\/].*/], config: { checkSubTreeCycle: true, }, }, ], }, };
stricter/stricter
stricter.config.js
JavaScript
mit
682
package net.trolldad.dashclock.redditheadlines.testactivity; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import net.trolldad.dashclock.redditheadlines.activity.PreviewActivity_; /** * Created by jacob-tabak on 1/28/14. */ public class LaunchNonImgurActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = PreviewActivity_.intent(this) .mCommentsUrl("http://www.reddit.com/r/AdviceAnimals/comments/1wdqd3/after_my_second_paper_jam_in_the_office_today_i/") .mLinkName("t3_1wdqd3") .mLinkUrl("http://www.livememe.com/qk7bcf5.jpg") .get(); startActivity(intent); finish(); } }
Trolldad/Reddit-Headlines
Reddit Headlines for DashClock/src/main/java/net/trolldad/dashclock/redditheadlines/testactivity/LaunchNonImgurActivity.java
Java
mit
815
<?php namespace HeroBundle\Form\Paragraph; use HeroBundle\Entity\Item; use HeroBundle\Repository\ItemRepository; use Symfony\Bridge\Doctrine\Form\Type\EntityType; use Symfony\Component\Form\CallbackTransformer; use Symfony\Component\Form\Extension\Core\Type\IntegerType; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; class AccessConditionsType extends AbstractType { /** * {@inheritdoc} */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('character_level', IntegerType::class, [ 'label' => 'Niveau du personnage', 'required' => false, ]) ->add('required_items', EntityType::class, [ 'required' => false, 'class' => 'HeroBundle:Item', 'choice_value' => 'id', 'choice_label' => 'name', 'label' => 'Objet(s) requis', 'multiple' => true, // 'query_builder' => function(ItemRepository $er) { // return $er->createQueryBuilder('i') // ->where('i.id = 221'); // } ]) ; } /** * {@inheritdoc} */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([]); } /** * {@inheritdoc} */ public function getBlockPrefix() { return 'herobundle_access_conditions'; } }
Cryborg/you_are_the_hero
src/HeroBundle/Form/Paragraph/AccessConditionsType.php
PHP
mit
1,613
'use strict'; // CUSTOM ERROR // /** * FUNCTION: createClass() * Creates a CustomError class constructor. Note that we use function generation so that tests may be run in browsers not supporting ES2015 classes. This function may be loaded in non-ES2015 environments, but should only be invoked when ES2015 classes are supported. * * @returns {Function} constructor */ function createClass() { /* jshint evil:true */ var str = ''; str += '(function create() {'; str += 'class CustomError extends Error {'; str += 'constructor( msg ) {'; str += 'super( msg );'; str += '}'; str += '}'; str += 'return CustomError;'; str += '})()'; return eval( str ); } // end FUNCTION createClass() // EXPORTS // module.exports = createClass;
kgryte/utils-copy-error
test/fixtures/customerror.subclass.js
JavaScript
mit
741
let AutomaticComponent = require('./AutomaticComponent'); class PurifyCss extends AutomaticComponent { /** * Required dependencies for the component. */ dependencies() { if (Config.purifyCss) { throw new Error( 'PurifyCSS support is no longer available. We recommend using PurgeCss + postCss instead.' ); } } } module.exports = PurifyCss;
JeffreyWay/laravel-mix
src/components/PurifyCss.js
JavaScript
mit
419
import "ember"; var Router, App, AppView, templates, router, container; var get = Ember.get, set = Ember.set, compile = Ember.Handlebars.compile, forEach = Ember.EnumerableUtils.forEach; function bootApplication() { router = container.lookup('router:main'); Ember.run(App, 'advanceReadiness'); } function handleURL(path) { return Ember.run(function() { return router.handleURL(path).then(function(value) { ok(true, 'url: `' + path + '` was handled'); return value; }, function(reason) { ok(false, 'failed to visit:`' + path + '` reason: `' + QUnit.jsDump.parse(reason)); throw reason; }); }); } function handleURLAborts(path) { Ember.run(function() { router.handleURL(path).then(function(value) { ok(false, 'url: `' + path + '` was NOT to be handled'); }, function(reason) { ok(reason && reason.message === "TransitionAborted", 'url: `' + path + '` was to be aborted'); }); }); } function handleURLRejectsWith(path, expectedReason) { Ember.run(function() { router.handleURL(path).then(function(value) { ok(false, 'expected handleURLing: `' + path + '` to fail'); }, function(reason) { equal(expectedReason, reason); }); }); } module("Basic Routing", { setup: function() { Ember.run(function() { App = Ember.Application.create({ name: "App", rootElement: '#qunit-fixture' }); App.deferReadiness(); App.Router.reopen({ location: 'none' }); Router = App.Router; App.LoadingRoute = Ember.Route.extend({ }); container = App.__container__; Ember.TEMPLATES.application = compile("{{outlet}}"); Ember.TEMPLATES.home = compile("<h3>Hours</h3>"); Ember.TEMPLATES.homepage = compile("<h3>Megatroll</h3><p>{{home}}</p>"); Ember.TEMPLATES.camelot = compile('<section><h3>Is a silly place</h3></section>'); }); }, teardown: function() { Ember.run(function() { App.destroy(); App = null; Ember.TEMPLATES = {}; }); } }); test("warn on URLs not included in the route set", function () { Router.map(function() { this.route("home", { path: "/" }); }); bootApplication(); expectAssertion(function(){ Ember.run(function(){ router.handleURL("/what-is-this-i-dont-even"); }); }, "The URL '/what-is-this-i-dont-even' did not match any routes in your application"); }); test("The Homepage", function() { Router.map(function() { this.route("home", { path: "/" }); }); App.HomeRoute = Ember.Route.extend({ }); var currentPath; App.ApplicationController = Ember.Controller.extend({ currentPathDidChange: Ember.observer('currentPath', function() { currentPath = get(this, 'currentPath'); }) }); bootApplication(); equal(currentPath, 'home'); equal(Ember.$('h3:contains(Hours)', '#qunit-fixture').length, 1, "The home template was rendered"); }); test("The Home page and the Camelot page with multiple Router.map calls", function() { Router.map(function() { this.route("home", { path: "/" }); }); Router.map(function() { this.route("camelot", {path: "/camelot"}); }); App.HomeRoute = Ember.Route.extend({ }); App.CamelotRoute = Ember.Route.extend({ }); var currentPath; App.ApplicationController = Ember.Controller.extend({ currentPathDidChange: Ember.observer('currentPath', function() { currentPath = get(this, 'currentPath'); }) }); App.CamelotController = Ember.Controller.extend({ currentPathDidChange: Ember.observer('currentPath', function() { currentPath = get(this, 'currentPath'); }) }); bootApplication(); handleURL("/camelot"); equal(currentPath, 'camelot'); equal(Ember.$('h3:contains(silly)', '#qunit-fixture').length, 1, "The camelot template was rendered"); handleURL("/"); equal(currentPath, 'home'); equal(Ember.$('h3:contains(Hours)', '#qunit-fixture').length, 1, "The home template was rendered"); }); test("The Homepage register as activeView", function() { Router.map(function() { this.route("home", { path: "/" }); this.route("homepage"); }); App.HomeRoute = Ember.Route.extend({ }); App.HomepageRoute = Ember.Route.extend({ }); bootApplication(); ok(router._lookupActiveView('home'), '`home` active view is connected'); handleURL('/homepage'); ok(router._lookupActiveView('homepage'), '`homepage` active view is connected'); equal(router._lookupActiveView('home'), undefined, '`home` active view is disconnected'); }); test("The Homepage with explicit template name in renderTemplate", function() { Router.map(function() { this.route("home", { path: "/" }); }); App.HomeRoute = Ember.Route.extend({ renderTemplate: function() { this.render('homepage'); } }); bootApplication(); equal(Ember.$('h3:contains(Megatroll)', '#qunit-fixture').length, 1, "The homepage template was rendered"); }); test("An alternate template will pull in an alternate controller", function() { Router.map(function() { this.route("home", { path: "/" }); }); App.HomeRoute = Ember.Route.extend({ renderTemplate: function() { this.render('homepage'); } }); App.HomepageController = Ember.Controller.extend({ home: "Comes from homepage" }); bootApplication(); equal(Ember.$('h3:contains(Megatroll) + p:contains(Comes from homepage)', '#qunit-fixture').length, 1, "The homepage template was rendered"); }); test("The template will pull in an alternate controller via key/value", function() { Router.map(function() { this.route("homepage", { path: "/" }); }); App.HomepageRoute = Ember.Route.extend({ renderTemplate: function() { this.render({controller: 'home'}); } }); App.HomeController = Ember.Controller.extend({ home: "Comes from home." }); bootApplication(); equal(Ember.$('h3:contains(Megatroll) + p:contains(Comes from home.)', '#qunit-fixture').length, 1, "The homepage template was rendered from data from the HomeController"); }); test("The Homepage with explicit template name in renderTemplate and controller", function() { Router.map(function() { this.route("home", { path: "/" }); }); App.HomeController = Ember.Controller.extend({ home: "YES I AM HOME" }); App.HomeRoute = Ember.Route.extend({ renderTemplate: function() { this.render('homepage'); } }); bootApplication(); equal(Ember.$('h3:contains(Megatroll) + p:contains(YES I AM HOME)', '#qunit-fixture').length, 1, "The homepage template was rendered"); }); if(Ember.FEATURES.isEnabled("ember-routing-add-model-option")) { test("Model passed via renderTemplate model is set as controller's content", function(){ Ember.TEMPLATES['bio'] = compile("<p>{{name}}</p>"); App.BioController = Ember.ObjectController.extend(); Router.map(function(){ this.route('home', { path: '/'}); }); App.HomeRoute = Ember.Route.extend({ renderTemplate: function(){ this.render('bio', { model: {name: 'emberjs'} }); } }); bootApplication(); equal(Ember.$('p:contains(emberjs)', '#qunit-fixture').length, 1, "Passed model was set as controllers content"); }); } test("Renders correct view with slash notation", function() { Ember.TEMPLATES['home/page'] = compile("<p>{{view.name}}</p>"); Router.map(function() { this.route("home", { path: "/" }); }); App.HomeRoute = Ember.Route.extend({ renderTemplate: function() { this.render('home/page'); } }); App.HomePageView = Ember.View.extend({ name: "Home/Page" }); bootApplication(); equal(Ember.$('p:contains(Home/Page)', '#qunit-fixture').length, 1, "The homepage template was rendered"); }); test("Renders the view given in the view option", function() { Ember.TEMPLATES['home'] = compile("<p>{{view.name}}</p>"); Router.map(function() { this.route("home", { path: "/" }); }); App.HomeRoute = Ember.Route.extend({ renderTemplate: function() { this.render({view: 'homePage'}); } }); App.HomePageView = Ember.View.extend({ name: "Home/Page" }); bootApplication(); equal(Ember.$('p:contains(Home/Page)', '#qunit-fixture').length, 1, "The homepage view was rendered"); }); test('render does not replace templateName if user provided', function() { Router.map(function() { this.route("home", { path: "/" }); }); Ember.TEMPLATES.the_real_home_template = Ember.Handlebars.compile( "<p>THIS IS THE REAL HOME</p>" ); App.HomeView = Ember.View.extend({ templateName: 'the_real_home_template' }); App.HomeController = Ember.Controller.extend(); App.HomeRoute = Ember.Route.extend(); bootApplication(); equal(Ember.$('p', '#qunit-fixture').text(), "THIS IS THE REAL HOME", "The homepage template was rendered"); }); test('render does not replace template if user provided', function () { Router.map(function () { this.route("home", { path: "/" }); }); App.HomeView = Ember.View.extend({ template: Ember.Handlebars.compile("<p>THIS IS THE REAL HOME</p>") }); App.HomeController = Ember.Controller.extend(); App.HomeRoute = Ember.Route.extend(); bootApplication(); Ember.run(function () { router.handleURL("/"); }); equal(Ember.$('p', '#qunit-fixture').text(), "THIS IS THE REAL HOME", "The homepage template was rendered"); }); test('render uses templateName from route', function() { Router.map(function() { this.route("home", { path: "/" }); }); Ember.TEMPLATES.the_real_home_template = Ember.Handlebars.compile( "<p>THIS IS THE REAL HOME</p>" ); App.HomeController = Ember.Controller.extend(); App.HomeRoute = Ember.Route.extend({ templateName: 'the_real_home_template' }); bootApplication(); equal(Ember.$('p', '#qunit-fixture').text(), "THIS IS THE REAL HOME", "The homepage template was rendered"); }); test('defining templateName allows other templates to be rendered', function() { Router.map(function() { this.route("home", { path: "/" }); }); Ember.TEMPLATES.alert = Ember.Handlebars.compile( "<div class='alert-box'>Invader!</div>" ); Ember.TEMPLATES.the_real_home_template = Ember.Handlebars.compile( "<p>THIS IS THE REAL HOME</p>{{outlet alert}}" ); App.HomeController = Ember.Controller.extend(); App.HomeRoute = Ember.Route.extend({ templateName: 'the_real_home_template', actions: { showAlert: function(){ this.render('alert', { into: 'home', outlet: 'alert' }); } } }); bootApplication(); equal(Ember.$('p', '#qunit-fixture').text(), "THIS IS THE REAL HOME", "The homepage template was rendered"); Ember.run(function(){ router.send('showAlert'); }); equal(Ember.$('.alert-box', '#qunit-fixture').text(), "Invader!", "Template for alert was render into outlet"); }); test('Specifying a name to render should have precedence over everything else', function() { Router.map(function() { this.route("home", { path: "/" }); }); App.HomeController = Ember.Controller.extend(); App.HomeRoute = Ember.Route.extend({ templateName: 'home', controllerName: 'home', viewName: 'home', renderTemplate: function() { this.render('homepage'); } }); App.HomeView = Ember.View.extend({ template: Ember.Handlebars.compile("<h3>This should not be rendered</h3><p>{{home}}</p>") }); App.HomepageController = Ember.ObjectController.extend({ content: { home: 'Tinytroll' } }); App.HomepageView = Ember.View.extend({ layout: Ember.Handlebars.compile( "<span>Outer</span>{{yield}}<span>troll</span>" ), templateName: 'homepage' }); bootApplication(); equal(Ember.$('h3', '#qunit-fixture').text(), "Megatroll", "The homepage template was rendered"); equal(Ember.$('p', '#qunit-fixture').text(), "Tinytroll", "The homepage controller was used"); equal(Ember.$('span', '#qunit-fixture').text(), "Outertroll", "The homepage view was used"); }); test("The Homepage with a `setupController` hook", function() { Router.map(function() { this.route("home", { path: "/" }); }); App.HomeRoute = Ember.Route.extend({ setupController: function(controller) { set(controller, 'hours', Ember.A([ "Monday through Friday: 9am to 5pm", "Saturday: Noon to Midnight", "Sunday: Noon to 6pm" ])); } }); Ember.TEMPLATES.home = Ember.Handlebars.compile( "<ul>{{#each entry in hours}}<li>{{entry}}</li>{{/each}}</ul>" ); bootApplication(); equal(Ember.$('ul li', '#qunit-fixture').eq(2).text(), "Sunday: Noon to 6pm", "The template was rendered with the hours context"); }); test("The route controller is still set when overriding the setupController hook", function() { Router.map(function() { this.route("home", { path: "/" }); }); App.HomeRoute = Ember.Route.extend({ setupController: function(controller) { // no-op // importantly, we are not calling this._super here } }); container.register('controller:home', Ember.Controller.extend()); bootApplication(); deepEqual(container.lookup('route:home').controller, container.lookup('controller:home'), "route controller is the home controller"); }); test("The route controller can be specified via controllerName", function() { Router.map(function() { this.route("home", { path: "/" }); }); Ember.TEMPLATES.home = Ember.Handlebars.compile( "<p>{{myValue}}</p>" ); App.HomeRoute = Ember.Route.extend({ controllerName: 'myController' }); container.register('controller:myController', Ember.Controller.extend({ myValue: "foo" })); bootApplication(); deepEqual(container.lookup('route:home').controller, container.lookup('controller:myController'), "route controller is set by controllerName"); equal(Ember.$('p', '#qunit-fixture').text(), "foo", "The homepage template was rendered with data from the custom controller"); }); test("The route controller specified via controllerName is used in render", function() { Router.map(function() { this.route("home", { path: "/" }); }); Ember.TEMPLATES.alternative_home = Ember.Handlebars.compile( "<p>alternative home: {{myValue}}</p>" ); App.HomeRoute = Ember.Route.extend({ controllerName: 'myController', renderTemplate: function() { this.render("alternative_home"); } }); container.register('controller:myController', Ember.Controller.extend({ myValue: "foo" })); bootApplication(); deepEqual(container.lookup('route:home').controller, container.lookup('controller:myController'), "route controller is set by controllerName"); equal(Ember.$('p', '#qunit-fixture').text(), "alternative home: foo", "The homepage template was rendered with data from the custom controller"); }); test("The Homepage with a `setupController` hook modifying other controllers", function() { Router.map(function() { this.route("home", { path: "/" }); }); App.HomeRoute = Ember.Route.extend({ setupController: function(controller) { set(this.controllerFor('home'), 'hours', Ember.A([ "Monday through Friday: 9am to 5pm", "Saturday: Noon to Midnight", "Sunday: Noon to 6pm" ])); } }); Ember.TEMPLATES.home = Ember.Handlebars.compile( "<ul>{{#each entry in hours}}<li>{{entry}}</li>{{/each}}</ul>" ); bootApplication(); equal(Ember.$('ul li', '#qunit-fixture').eq(2).text(), "Sunday: Noon to 6pm", "The template was rendered with the hours context"); }); test("The Homepage with a computed context that does not get overridden", function() { Router.map(function() { this.route("home", { path: "/" }); }); App.HomeController = Ember.ArrayController.extend({ content: Ember.computed(function() { return Ember.A([ "Monday through Friday: 9am to 5pm", "Saturday: Noon to Midnight", "Sunday: Noon to 6pm" ]); }) }); Ember.TEMPLATES.home = Ember.Handlebars.compile( "<ul>{{#each}}<li>{{this}}</li>{{/each}}</ul>" ); bootApplication(); equal(Ember.$('ul li', '#qunit-fixture').eq(2).text(), "Sunday: Noon to 6pm", "The template was rendered with the context intact"); }); test("The Homepage getting its controller context via model", function() { Router.map(function() { this.route("home", { path: "/" }); }); App.HomeRoute = Ember.Route.extend({ model: function() { return Ember.A([ "Monday through Friday: 9am to 5pm", "Saturday: Noon to Midnight", "Sunday: Noon to 6pm" ]); }, setupController: function(controller, model) { equal(this.controllerFor('home'), controller); set(this.controllerFor('home'), 'hours', model); } }); Ember.TEMPLATES.home = Ember.Handlebars.compile( "<ul>{{#each entry in hours}}<li>{{entry}}</li>{{/each}}</ul>" ); bootApplication(); equal(Ember.$('ul li', '#qunit-fixture').eq(2).text(), "Sunday: Noon to 6pm", "The template was rendered with the hours context"); }); test("The Specials Page getting its controller context by deserializing the params hash", function() { Router.map(function() { this.route("home", { path: "/" }); this.resource("special", { path: "/specials/:menu_item_id" }); }); App.SpecialRoute = Ember.Route.extend({ model: function(params) { return Ember.Object.create({ menuItemId: params.menu_item_id }); }, setupController: function(controller, model) { set(controller, 'content', model); } }); Ember.TEMPLATES.special = Ember.Handlebars.compile( "<p>{{content.menuItemId}}</p>" ); bootApplication(); container.register('controller:special', Ember.Controller.extend()); handleURL("/specials/1"); equal(Ember.$('p', '#qunit-fixture').text(), "1", "The model was used to render the template"); }); test("The Specials Page defaults to looking models up via `find`", function() { Router.map(function() { this.route("home", { path: "/" }); this.resource("special", { path: "/specials/:menu_item_id" }); }); App.MenuItem = Ember.Object.extend(); App.MenuItem.reopenClass({ find: function(id) { return App.MenuItem.create({ id: id }); } }); App.SpecialRoute = Ember.Route.extend({ setupController: function(controller, model) { set(controller, 'content', model); } }); Ember.TEMPLATES.special = Ember.Handlebars.compile( "<p>{{content.id}}</p>" ); bootApplication(); container.register('controller:special', Ember.Controller.extend()); handleURL("/specials/1"); equal(Ember.$('p', '#qunit-fixture').text(), "1", "The model was used to render the template"); }); test("The Special Page returning a promise puts the app into a loading state until the promise is resolved", function() { Router.map(function() { this.route("home", { path: "/" }); this.resource("special", { path: "/specials/:menu_item_id" }); }); var menuItem; App.MenuItem = Ember.Object.extend(Ember.DeferredMixin); App.MenuItem.reopenClass({ find: function(id) { menuItem = App.MenuItem.create({ id: id }); return menuItem; } }); App.LoadingRoute = Ember.Route.extend({ }); App.SpecialRoute = Ember.Route.extend({ setupController: function(controller, model) { set(controller, 'content', model); } }); Ember.TEMPLATES.special = Ember.Handlebars.compile( "<p>{{content.id}}</p>" ); Ember.TEMPLATES.loading = Ember.Handlebars.compile( "<p>LOADING!</p>" ); bootApplication(); container.register('controller:special', Ember.Controller.extend()); handleURL("/specials/1"); equal(Ember.$('p', '#qunit-fixture').text(), "LOADING!", "The app is in the loading state"); Ember.run(function() { menuItem.resolve(menuItem); }); equal(Ember.$('p', '#qunit-fixture').text(), "1", "The app is now in the specials state"); }); test("The loading state doesn't get entered for promises that resolve on the same run loop", function() { Router.map(function() { this.route("home", { path: "/" }); this.resource("special", { path: "/specials/:menu_item_id" }); }); App.MenuItem = Ember.Object.extend(); App.MenuItem.reopenClass({ find: function(id) { return { id: id }; } }); App.LoadingRoute = Ember.Route.extend({ enter: function() { ok(false, "LoadingRoute shouldn't have been entered."); } }); App.SpecialRoute = Ember.Route.extend({ setupController: function(controller, model) { set(controller, 'content', model); } }); Ember.TEMPLATES.special = Ember.Handlebars.compile( "<p>{{content.id}}</p>" ); Ember.TEMPLATES.loading = Ember.Handlebars.compile( "<p>LOADING!</p>" ); bootApplication(); container.register('controller:special', Ember.Controller.extend()); handleURL("/specials/1"); equal(Ember.$('p', '#qunit-fixture').text(), "1", "The app is now in the specials state"); }); /* asyncTest("The Special page returning an error fires the error hook on SpecialRoute", function() { Router.map(function() { this.route("home", { path: "/" }); this.resource("special", { path: "/specials/:menu_item_id" }); }); var menuItem; App.MenuItem = Ember.Object.extend(Ember.DeferredMixin); App.MenuItem.reopenClass({ find: function(id) { menuItem = App.MenuItem.create({ id: id }); Ember.run.later(function() { menuItem.resolve(menuItem); }, 1); return menuItem; } }); App.SpecialRoute = Ember.Route.extend({ setup: function() { throw 'Setup error'; }, actions: { error: function(reason) { equal(reason, 'Setup error'); QUnit.start(); } } }); bootApplication(); handleURLRejectsWith('/specials/1', 'Setup error'); }); */ test("The Special page returning an error invokes SpecialRoute's error handler", function() { Router.map(function() { this.route("home", { path: "/" }); this.resource("special", { path: "/specials/:menu_item_id" }); }); var menuItem; App.MenuItem = Ember.Object.extend(Ember.DeferredMixin); App.MenuItem.reopenClass({ find: function(id) { menuItem = App.MenuItem.create({ id: id }); return menuItem; } }); App.SpecialRoute = Ember.Route.extend({ setup: function() { throw 'Setup error'; }, actions: { error: function(reason) { equal(reason, 'Setup error', 'SpecialRoute#error received the error thrown from setup'); } } }); bootApplication(); handleURLRejectsWith('/specials/1', 'Setup error'); Ember.run(menuItem, menuItem.resolve, menuItem); }); function testOverridableErrorHandler(handlersName) { expect(2); Router.map(function() { this.route("home", { path: "/" }); this.resource("special", { path: "/specials/:menu_item_id" }); }); var menuItem; App.MenuItem = Ember.Object.extend(Ember.DeferredMixin); App.MenuItem.reopenClass({ find: function(id) { menuItem = App.MenuItem.create({ id: id }); return menuItem; } }); var attrs = {}; attrs[handlersName] = { error: function(reason) { equal(reason, 'Setup error', "error was correctly passed to custom ApplicationRoute handler"); } }; App.ApplicationRoute = Ember.Route.extend(attrs); App.SpecialRoute = Ember.Route.extend({ setup: function() { throw 'Setup error'; } }); bootApplication(); handleURLRejectsWith("/specials/1", "Setup error"); Ember.run(menuItem, 'resolve', menuItem); } test("ApplicationRoute's default error handler can be overridden", function() { testOverridableErrorHandler('actions'); }); test("ApplicationRoute's default error handler can be overridden (with DEPRECATED `events`)", function() { testOverridableErrorHandler('events'); }); asyncTest("Moving from one page to another triggers the correct callbacks", function() { expect(3); Router.map(function() { this.route("home", { path: "/" }); this.resource("special", { path: "/specials/:menu_item_id" }); }); App.MenuItem = Ember.Object.extend(Ember.DeferredMixin); App.SpecialRoute = Ember.Route.extend({ setupController: function(controller, model) { set(controller, 'content', model); } }); Ember.TEMPLATES.home = Ember.Handlebars.compile( "<h3>Home</h3>" ); Ember.TEMPLATES.special = Ember.Handlebars.compile( "<p>{{content.id}}</p>" ); bootApplication(); container.register('controller:special', Ember.Controller.extend()); var transition = handleURL('/'); Ember.run(function() { transition.then(function() { equal(Ember.$('h3', '#qunit-fixture').text(), "Home", "The app is now in the initial state"); var promiseContext = App.MenuItem.create({ id: 1 }); Ember.run.later(function() { promiseContext.resolve(promiseContext); }, 1); return router.transitionTo('special', promiseContext); }).then(function(result) { deepEqual(router.location.path, '/specials/1'); QUnit.start(); }); }); }); asyncTest("Nested callbacks are not exited when moving to siblings", function() { Router.map(function() { this.resource("root", { path: "/" }, function() { this.resource("special", { path: "/specials/:menu_item_id" }); }); }); var currentPath; App.ApplicationController = Ember.Controller.extend({ currentPathDidChange: Ember.observer('currentPath', function() { currentPath = get(this, 'currentPath'); }) }); var menuItem; App.MenuItem = Ember.Object.extend(Ember.DeferredMixin); App.MenuItem.reopenClass({ find: function(id) { menuItem = App.MenuItem.create({ id: id }); return menuItem; } }); App.LoadingRoute = Ember.Route.extend({ }); App.RootRoute = Ember.Route.extend({ model: function() { rootModel++; return this._super.apply(this, arguments); }, serialize: function() { rootSerialize++; return this._super.apply(this, arguments); }, setupController: function() { rootSetup++; }, renderTemplate: function() { rootRender++; } }); App.HomeRoute = Ember.Route.extend({ }); App.SpecialRoute = Ember.Route.extend({ setupController: function(controller, model) { set(controller, 'content', model); } }); Ember.TEMPLATES['root/index'] = Ember.Handlebars.compile( "<h3>Home</h3>" ); Ember.TEMPLATES.special = Ember.Handlebars.compile( "<p>{{content.id}}</p>" ); Ember.TEMPLATES.loading = Ember.Handlebars.compile( "<p>LOADING!</p>" ); var rootSetup = 0, rootRender = 0, rootModel = 0, rootSerialize = 0; bootApplication(); container.register('controller:special', Ember.Controller.extend()); equal(Ember.$('h3', '#qunit-fixture').text(), "Home", "The app is now in the initial state"); equal(rootSetup, 1, "The root setup was triggered"); equal(rootRender, 1, "The root render was triggered"); equal(rootSerialize, 0, "The root serialize was not called"); equal(rootModel, 1, "The root model was called"); router = container.lookup('router:main'); Ember.run(function() { var menuItem = App.MenuItem.create({ id: 1 }); Ember.run.later(function() { menuItem.resolve(menuItem); }, 1); router.transitionTo('special', menuItem).then(function(result) { equal(rootSetup, 1, "The root setup was not triggered again"); equal(rootRender, 1, "The root render was not triggered again"); equal(rootSerialize, 0, "The root serialize was not called"); // TODO: Should this be changed? equal(rootModel, 1, "The root model was called again"); deepEqual(router.location.path, '/specials/1'); equal(currentPath, 'root.special'); QUnit.start(); }); }); }); asyncTest("Events are triggered on the controller if a matching action name is implemented", function() { Router.map(function() { this.route("home", { path: "/" }); }); var model = { name: "Tom Dale" }; var stateIsNotCalled = true; App.HomeRoute = Ember.Route.extend({ model: function() { return model; }, actions: { showStuff: function(obj) { stateIsNotCalled = false; } } }); Ember.TEMPLATES.home = Ember.Handlebars.compile( "<a {{action 'showStuff' content}}>{{name}}</a>" ); var controller = Ember.Controller.extend({ actions: { showStuff: function(context) { ok (stateIsNotCalled, "an event on the state is not triggered"); deepEqual(context, { name: "Tom Dale" }, "an event with context is passed"); QUnit.start(); } } }); container.register('controller:home', controller); bootApplication(); var actionId = Ember.$("#qunit-fixture a").data("ember-action"); var action = Ember.Handlebars.ActionHelper.registeredActions[actionId]; var event = new Ember.$.Event("click"); action.handler(event); }); asyncTest("Events are triggered on the current state when defined in `actions` object", function() { Router.map(function() { this.route("home", { path: "/" }); }); var model = { name: "Tom Dale" }; App.HomeRoute = Ember.Route.extend({ model: function() { return model; }, actions: { showStuff: function(obj) { ok(this instanceof App.HomeRoute, "the handler is an App.HomeRoute"); // Using Ember.copy removes any private Ember vars which older IE would be confused by deepEqual(Ember.copy(obj, true), { name: "Tom Dale" }, "the context is correct"); QUnit.start(); } } }); Ember.TEMPLATES.home = Ember.Handlebars.compile( "<a {{action 'showStuff' content}}>{{name}}</a>" ); bootApplication(); var actionId = Ember.$("#qunit-fixture a").data("ember-action"); var action = Ember.Handlebars.ActionHelper.registeredActions[actionId]; var event = new Ember.$.Event("click"); action.handler(event); }); asyncTest("Events defined in `actions` object are triggered on the current state when routes are nested", function() { Router.map(function() { this.resource("root", { path: "/" }, function() { this.route("index", { path: "/" }); }); }); var model = { name: "Tom Dale" }; App.RootRoute = Ember.Route.extend({ actions: { showStuff: function(obj) { ok(this instanceof App.RootRoute, "the handler is an App.HomeRoute"); // Using Ember.copy removes any private Ember vars which older IE would be confused by deepEqual(Ember.copy(obj, true), { name: "Tom Dale" }, "the context is correct"); QUnit.start(); } } }); App.RootIndexRoute = Ember.Route.extend({ model: function() { return model; } }); Ember.TEMPLATES['root/index'] = Ember.Handlebars.compile( "<a {{action 'showStuff' content}}>{{name}}</a>" ); bootApplication(); var actionId = Ember.$("#qunit-fixture a").data("ember-action"); var action = Ember.Handlebars.ActionHelper.registeredActions[actionId]; var event = new Ember.$.Event("click"); action.handler(event); }); asyncTest("Events are triggered on the current state when defined in `events` object (DEPRECATED)", function() { Router.map(function() { this.route("home", { path: "/" }); }); var model = { name: "Tom Dale" }; App.HomeRoute = Ember.Route.extend({ model: function() { return model; }, events: { showStuff: function(obj) { ok(this instanceof App.HomeRoute, "the handler is an App.HomeRoute"); // Using Ember.copy removes any private Ember vars which older IE would be confused by deepEqual(Ember.copy(obj, true), { name: "Tom Dale" }, "the context is correct"); QUnit.start(); } } }); Ember.TEMPLATES.home = Ember.Handlebars.compile( "<a {{action 'showStuff' content}}>{{name}}</a>" ); expectDeprecation(/Action handlers contained in an `events` object are deprecated/); bootApplication(); var actionId = Ember.$("#qunit-fixture a").data("ember-action"); var action = Ember.Handlebars.ActionHelper.registeredActions[actionId]; var event = new Ember.$.Event("click"); action.handler(event); }); asyncTest("Events defined in `events` object are triggered on the current state when routes are nested (DEPRECATED)", function() { Router.map(function() { this.resource("root", { path: "/" }, function() { this.route("index", { path: "/" }); }); }); var model = { name: "Tom Dale" }; App.RootRoute = Ember.Route.extend({ events: { showStuff: function(obj) { ok(this instanceof App.RootRoute, "the handler is an App.HomeRoute"); // Using Ember.copy removes any private Ember vars which older IE would be confused by deepEqual(Ember.copy(obj, true), { name: "Tom Dale" }, "the context is correct"); QUnit.start(); } } }); App.RootIndexRoute = Ember.Route.extend({ model: function() { return model; } }); Ember.TEMPLATES['root/index'] = Ember.Handlebars.compile( "<a {{action 'showStuff' content}}>{{name}}</a>" ); expectDeprecation(/Action handlers contained in an `events` object are deprecated/); bootApplication(); var actionId = Ember.$("#qunit-fixture a").data("ember-action"); var action = Ember.Handlebars.ActionHelper.registeredActions[actionId]; var event = new Ember.$.Event("click"); action.handler(event); }); test("Events can be handled by inherited event handlers", function() { expect(4); App.SuperRoute = Ember.Route.extend({ actions: { foo: function() { ok(true, 'foo'); }, bar: function(msg) { equal(msg, "HELLO"); } } }); App.RouteMixin = Ember.Mixin.create({ actions: { bar: function(msg) { equal(msg, "HELLO"); this._super(msg); } } }); App.IndexRoute = App.SuperRoute.extend(App.RouteMixin, { actions: { baz: function() { ok(true, 'baz'); } } }); bootApplication(); router.send("foo"); router.send("bar", "HELLO"); router.send("baz"); }); if (Ember.FEATURES.isEnabled('ember-routing-drop-deprecated-action-style')) { asyncTest("Actions are not triggered on the controller if a matching action name is implemented as a method", function() { Router.map(function() { this.route("home", { path: "/" }); }); var model = { name: "Tom Dale" }; var stateIsNotCalled = true; App.HomeRoute = Ember.Route.extend({ model: function() { return model; }, actions: { showStuff: function(context) { ok (stateIsNotCalled, "an event on the state is not triggered"); deepEqual(context, { name: "Tom Dale" }, "an event with context is passed"); QUnit.start(); } } }); Ember.TEMPLATES.home = Ember.Handlebars.compile( "<a {{action 'showStuff' content}}>{{name}}</a>" ); var controller = Ember.Controller.extend({ showStuff: function(context) { stateIsNotCalled = false; ok (stateIsNotCalled, "an event on the state is not triggered"); } }); container.register('controller:home', controller); bootApplication(); var actionId = Ember.$("#qunit-fixture a").data("ember-action"); var action = Ember.Handlebars.ActionHelper.registeredActions[actionId]; var event = new Ember.$.Event("click"); action.handler(event); }); } else { asyncTest("Events are triggered on the controller if a matching action name is implemented as a method (DEPRECATED)", function() { Router.map(function() { this.route("home", { path: "/" }); }); var model = { name: "Tom Dale" }; var stateIsNotCalled = true; App.HomeRoute = Ember.Route.extend({ model: function() { return model; }, events: { showStuff: function(obj) { stateIsNotCalled = false; ok (stateIsNotCalled, "an event on the state is not triggered"); } } }); Ember.TEMPLATES.home = Ember.Handlebars.compile( "<a {{action 'showStuff' content}}>{{name}}</a>" ); var controller = Ember.Controller.extend({ showStuff: function(context) { ok (stateIsNotCalled, "an event on the state is not triggered"); deepEqual(context, { name: "Tom Dale" }, "an event with context is passed"); QUnit.start(); } }); container.register('controller:home', controller); expectDeprecation(/Action handlers contained in an `events` object are deprecated/); bootApplication(); var actionId = Ember.$("#qunit-fixture a").data("ember-action"); var action = Ember.Handlebars.ActionHelper.registeredActions[actionId]; var event = new Ember.$.Event("click"); action.handler(event); }); } asyncTest("actions can be triggered with multiple arguments", function() { Router.map(function() { this.resource("root", { path: "/" }, function() { this.route("index", { path: "/" }); }); }); var model1 = { name: "Tilde" }, model2 = { name: "Tom Dale" }; App.RootRoute = Ember.Route.extend({ actions: { showStuff: function(obj1, obj2) { ok(this instanceof App.RootRoute, "the handler is an App.HomeRoute"); // Using Ember.copy removes any private Ember vars which older IE would be confused by deepEqual(Ember.copy(obj1, true), { name: "Tilde" }, "the first context is correct"); deepEqual(Ember.copy(obj2, true), { name: "Tom Dale" }, "the second context is correct"); QUnit.start(); } } }); App.RootIndexController = Ember.Controller.extend({ model1: model1, model2: model2 }); Ember.TEMPLATES['root/index'] = Ember.Handlebars.compile( "<a {{action 'showStuff' model1 model2}}>{{model1.name}}</a>" ); bootApplication(); var actionId = Ember.$("#qunit-fixture a").data("ember-action"); var action = Ember.Handlebars.ActionHelper.registeredActions[actionId]; var event = new Ember.$.Event("click"); action.handler(event); }); test("transitioning multiple times in a single run loop only sets the URL once", function() { Router.map(function() { this.route("root", { path: "/" }); this.route("foo"); this.route("bar"); }); bootApplication(); var urlSetCount = 0; router.get('location').setURL = function(path) { urlSetCount++; set(this, 'path', path); }; equal(urlSetCount, 0); Ember.run(function() { router.transitionTo("foo"); router.transitionTo("bar"); }); equal(urlSetCount, 1); equal(router.get('location').getURL(), "/bar"); }); test('navigating away triggers a url property change', function() { expect(3); Router.map(function() { this.route('root', { path: '/' }); this.route('foo', { path: '/foo' }); this.route('bar', { path: '/bar' }); }); bootApplication(); Ember.run(function() { Ember.addObserver(router, 'url', function() { ok(true, "url change event was fired"); }); }); forEach(['foo', 'bar', '/foo'], function(destination) { Ember.run(router, 'transitionTo', destination); }); }); test("using replaceWith calls location.replaceURL if available", function() { var setCount = 0, replaceCount = 0; Router.reopen({ location: Ember.NoneLocation.createWithMixins({ setURL: function(path) { setCount++; set(this, 'path', path); }, replaceURL: function(path) { replaceCount++; set(this, 'path', path); } }) }); Router.map(function() { this.route("root", { path: "/" }); this.route("foo"); }); bootApplication(); equal(setCount, 0); equal(replaceCount, 0); Ember.run(function() { router.replaceWith("foo"); }); equal(setCount, 0, 'should not call setURL'); equal(replaceCount, 1, 'should call replaceURL once'); equal(router.get('location').getURL(), "/foo"); }); test("using replaceWith calls setURL if location.replaceURL is not defined", function() { var setCount = 0; Router.reopen({ location: Ember.NoneLocation.createWithMixins({ setURL: function(path) { setCount++; set(this, 'path', path); } }) }); Router.map(function() { this.route("root", { path: "/" }); this.route("foo"); }); bootApplication(); equal(setCount, 0); Ember.run(function() { router.replaceWith("foo"); }); equal(setCount, 1, 'should call setURL once'); equal(router.get('location').getURL(), "/foo"); }); test("Route inherits model from parent route", function() { expect(9); Router.map(function() { this.resource("the_post", { path: "/posts/:post_id" }, function() { this.route("comments"); this.resource("shares", { path: "/shares/:share_id"}, function() { this.route("share"); }); }); }); var post1 = {}, post2 = {}, post3 = {}, currentPost; var share1 = {}, share2 = {}, share3 = {}, currentShare; var posts = { 1: post1, 2: post2, 3: post3 }; var shares = { 1: share1, 2: share2, 3: share3 }; App.ThePostRoute = Ember.Route.extend({ model: function(params) { return posts[params.post_id]; } }); App.ThePostCommentsRoute = Ember.Route.extend({ afterModel: function(post, transition) { var parent_model = this.modelFor('thePost'); equal(post, parent_model); } }); App.SharesRoute = Ember.Route.extend({ model: function(params) { return shares[params.share_id]; } }); App.SharesShareRoute = Ember.Route.extend({ afterModel: function(share, transition) { var parent_model = this.modelFor('shares'); equal(share, parent_model); } }); bootApplication(); currentPost = post1; handleURL("/posts/1/comments"); handleURL("/posts/1/shares/1"); currentPost = post2; handleURL("/posts/2/comments"); handleURL("/posts/2/shares/2"); currentPost = post3; handleURL("/posts/3/comments"); handleURL("/posts/3/shares/3"); }); test("Resource does not inherit model from parent resource", function() { expect(6); Router.map(function() { this.resource("the_post", { path: "/posts/:post_id" }, function() { this.resource("comments", function() { }); }); }); var post1 = {}, post2 = {}, post3 = {}, currentPost; var posts = { 1: post1, 2: post2, 3: post3 }; App.ThePostRoute = Ember.Route.extend({ model: function(params) { return posts[params.post_id]; } }); App.CommentsRoute = Ember.Route.extend({ afterModel: function(post, transition) { var parent_model = this.modelFor('thePost'); notEqual(post, parent_model); } }); bootApplication(); currentPost = post1; handleURL("/posts/1/comments"); currentPost = post2; handleURL("/posts/2/comments"); currentPost = post3; handleURL("/posts/3/comments"); }); test("It is possible to get the model from a parent route", function() { expect(9); Router.map(function() { this.resource("the_post", { path: "/posts/:post_id" }, function() { this.resource("comments"); }); }); var post1 = {}, post2 = {}, post3 = {}, currentPost; var posts = { 1: post1, 2: post2, 3: post3 }; App.ThePostRoute = Ember.Route.extend({ model: function(params) { return posts[params.post_id]; } }); App.CommentsRoute = Ember.Route.extend({ model: function() { // Allow both underscore / camelCase format. equal(this.modelFor('thePost'), currentPost); equal(this.modelFor('the_post'), currentPost); } }); bootApplication(); currentPost = post1; handleURL("/posts/1/comments"); currentPost = post2; handleURL("/posts/2/comments"); currentPost = post3; handleURL("/posts/3/comments"); }); test("A redirection hook is provided", function() { Router.map(function() { this.route("choose", { path: "/" }); this.route("home"); }); var chooseFollowed = 0, destination; App.ChooseRoute = Ember.Route.extend({ redirect: function() { if (destination) { this.transitionTo(destination); } }, setupController: function() { chooseFollowed++; } }); destination = 'home'; bootApplication(); equal(chooseFollowed, 0, "The choose route wasn't entered since a transition occurred"); equal(Ember.$("h3:contains(Hours)", "#qunit-fixture").length, 1, "The home template was rendered"); equal(router.container.lookup('controller:application').get('currentPath'), 'home'); }); test("Redirecting from the middle of a route aborts the remainder of the routes", function() { expect(3); Router.map(function() { this.route("home"); this.resource("foo", function() { this.resource("bar", function() { this.route("baz"); }); }); }); App.BarRoute = Ember.Route.extend({ redirect: function() { this.transitionTo("home"); }, setupController: function() { ok(false, "Should transition before setupController"); } }); App.BarBazRoute = Ember.Route.extend({ enter: function() { ok(false, "Should abort transition getting to next route"); } }); bootApplication(); handleURLAborts("/foo/bar/baz"); equal(router.container.lookup('controller:application').get('currentPath'), 'home'); equal(router.get('location').getURL(), "/home"); }); test("Redirecting to the current target in the middle of a route does not abort initial routing", function() { expect(5); Router.map(function() { this.route("home"); this.resource("foo", function() { this.resource("bar", function() { this.route("baz"); }); }); }); var successCount = 0; App.BarRoute = Ember.Route.extend({ redirect: function() { this.transitionTo("bar.baz").then(function() { successCount++; }); }, setupController: function() { ok(true, "Should still invoke bar's setupController"); } }); App.BarBazRoute = Ember.Route.extend({ setupController: function() { ok(true, "Should still invoke bar.baz's setupController"); } }); bootApplication(); handleURL("/foo/bar/baz"); equal(router.container.lookup('controller:application').get('currentPath'), 'foo.bar.baz'); equal(successCount, 1, 'transitionTo success handler was called once'); }); test("Redirecting to the current target with a different context aborts the remainder of the routes", function() { expect(4); Router.map(function() { this.route("home"); this.resource("foo", function() { this.resource("bar", { path: "bar/:id" }, function() { this.route("baz"); }); }); }); var model = { id: 2 }; var count = 0; App.BarRoute = Ember.Route.extend({ afterModel: function(context) { if (count++ > 10) { ok(false, 'infinite loop'); } else { this.transitionTo("bar.baz", model); } }, serialize: function(params) { return params; } }); App.BarBazRoute = Ember.Route.extend({ setupController: function() { ok(true, "Should still invoke setupController"); } }); bootApplication(); handleURLAborts("/foo/bar/1/baz"); equal(router.container.lookup('controller:application').get('currentPath'), 'foo.bar.baz'); equal(router.get('location').getURL(), "/foo/bar/2/baz"); }); test("Transitioning from a parent event does not prevent currentPath from being set", function() { Router.map(function() { this.resource("foo", function() { this.resource("bar", function() { this.route("baz"); }); this.route("qux"); }); }); App.FooRoute = Ember.Route.extend({ actions: { goToQux: function() { this.transitionTo('foo.qux'); } } }); bootApplication(); var applicationController = router.container.lookup('controller:application'); handleURL("/foo/bar/baz"); equal(applicationController.get('currentPath'), 'foo.bar.baz'); Ember.run(function() { router.send("goToQux"); }); equal(applicationController.get('currentPath'), 'foo.qux'); equal(router.get('location').getURL(), "/foo/qux"); }); test("Generated names can be customized when providing routes with dot notation", function() { expect(4); Ember.TEMPLATES.index = compile("<div>Index</div>"); Ember.TEMPLATES.application = compile("<h1>Home</h1><div class='main'>{{outlet}}</div>"); Ember.TEMPLATES.foo = compile("<div class='middle'>{{outlet}}</div>"); Ember.TEMPLATES.bar = compile("<div class='bottom'>{{outlet}}</div>"); Ember.TEMPLATES['bar/baz'] = compile("<p>{{name}}Bottom!</p>"); Router.map(function() { this.resource("foo", { path: "/top" }, function() { this.resource("bar", { path: "/middle" }, function() { this.route("baz", { path: "/bottom" }); }); }); }); App.FooRoute = Ember.Route.extend({ renderTemplate: function() { ok(true, "FooBarRoute was called"); return this._super.apply(this, arguments); } }); App.BarBazRoute = Ember.Route.extend({ renderTemplate: function() { ok(true, "BarBazRoute was called"); return this._super.apply(this, arguments); } }); App.BarController = Ember.Controller.extend({ name: "Bar" }); App.BarBazController = Ember.Controller.extend({ name: "BarBaz" }); bootApplication(); handleURL("/top/middle/bottom"); equal(Ember.$('.main .middle .bottom p', '#qunit-fixture').text(), "BarBazBottom!", "The templates were rendered into their appropriate parents"); }); test("Child routes render into their parent route's template by default", function() { Ember.TEMPLATES.index = compile("<div>Index</div>"); Ember.TEMPLATES.application = compile("<h1>Home</h1><div class='main'>{{outlet}}</div>"); Ember.TEMPLATES.top = compile("<div class='middle'>{{outlet}}</div>"); Ember.TEMPLATES.middle = compile("<div class='bottom'>{{outlet}}</div>"); Ember.TEMPLATES['middle/bottom'] = compile("<p>Bottom!</p>"); Router.map(function() { this.resource("top", function() { this.resource("middle", function() { this.route("bottom"); }); }); }); bootApplication(); handleURL("/top/middle/bottom"); equal(Ember.$('.main .middle .bottom p', '#qunit-fixture').text(), "Bottom!", "The templates were rendered into their appropriate parents"); }); test("Child routes render into specified template", function() { Ember.TEMPLATES.index = compile("<div>Index</div>"); Ember.TEMPLATES.application = compile("<h1>Home</h1><div class='main'>{{outlet}}</div>"); Ember.TEMPLATES.top = compile("<div class='middle'>{{outlet}}</div>"); Ember.TEMPLATES.middle = compile("<div class='bottom'>{{outlet}}</div>"); Ember.TEMPLATES['middle/bottom'] = compile("<p>Bottom!</p>"); Router.map(function() { this.resource("top", function() { this.resource("middle", function() { this.route("bottom"); }); }); }); App.MiddleBottomRoute = Ember.Route.extend({ renderTemplate: function() { this.render('middle/bottom', { into: 'top' }); } }); bootApplication(); handleURL("/top/middle/bottom"); equal(Ember.$('.main .middle .bottom p', '#qunit-fixture').length, 0, "should not render into the middle template"); equal(Ember.$('.main .middle > p', '#qunit-fixture').text(), "Bottom!", "The template was rendered into the top template"); }); test("Rendering into specified template with slash notation", function() { Ember.TEMPLATES['person/profile'] = compile("profile {{outlet}}"); Ember.TEMPLATES['person/details'] = compile("details!"); Router.map(function() { this.resource("home", { path: '/' }); }); App.HomeRoute = Ember.Route.extend({ renderTemplate: function() { this.render('person/profile'); this.render('person/details', { into: 'person/profile' }); } }); bootApplication(); equal(Ember.$('#qunit-fixture:contains(profile details!)').length, 1, "The templates were rendered"); }); test("Parent route context change", function() { var editCount = 0, editedPostIds = Ember.A(); Ember.TEMPLATES.application = compile("{{outlet}}"); Ember.TEMPLATES.posts = compile("{{outlet}}"); Ember.TEMPLATES.post = compile("{{outlet}}"); Ember.TEMPLATES['post/index'] = compile("showing"); Ember.TEMPLATES['post/edit'] = compile("editing"); Router.map(function() { this.resource("posts", function() { this.resource("post", { path: "/:postId" }, function() { this.route("edit"); }); }); }); App.PostsRoute = Ember.Route.extend({ actions: { showPost: function(context) { this.transitionTo('post', context); } } }); App.PostRoute = Ember.Route.extend({ model: function(params) { return {id: params.postId}; }, actions: { editPost: function(context) { this.transitionTo('post.edit'); } } }); App.PostEditRoute = Ember.Route.extend({ model: function(params) { var postId = this.modelFor("post").id; editedPostIds.push(postId); return null; }, setup: function() { this._super.apply(this, arguments); editCount++; } }); bootApplication(); handleURL("/posts/1"); Ember.run(function() { router.send('editPost'); }); Ember.run(function() { router.send('showPost', {id: '2'}); }); Ember.run(function() { router.send('editPost'); }); equal(editCount, 2, 'set up the edit route twice without failure'); deepEqual(editedPostIds, ['1', '2'], 'modelFor posts.post returns the right context'); }); test("Router accounts for rootURL on page load when using history location", function() { var rootURL = window.location.pathname + '/app', postsTemplateRendered = false, setHistory, HistoryTestLocation; setHistory = function(obj, path) { obj.set('history', { state: { path: path } }); }; // Create new implementation that extends HistoryLocation // and set current location to rootURL + '/posts' HistoryTestLocation = Ember.HistoryLocation.extend({ initState: function() { var path = rootURL + '/posts'; setHistory(this, path); this.set('location', { pathname: path }); }, replaceState: function(path) { setHistory(this, path); }, pushState: function(path) { setHistory(this, path); } }); container.register('location:historyTest', HistoryTestLocation); Router.reopen({ location: 'historyTest', rootURL: rootURL }); Router.map(function() { this.resource("posts", { path: '/posts' }); }); App.PostsRoute = Ember.Route.extend({ model: function() {}, renderTemplate: function() { postsTemplateRendered = true; } }); bootApplication(); ok(postsTemplateRendered, "Posts route successfully stripped from rootURL"); }); test("The rootURL is passed properly to the location implementation", function() { expect(1); var rootURL = "/blahzorz", HistoryTestLocation; HistoryTestLocation = Ember.HistoryLocation.extend({ rootURL: 'this is not the URL you are looking for', initState: function() { equal(this.get('rootURL'), rootURL); } }); container.register('location:history-test', HistoryTestLocation); Router.reopen({ location: 'history-test', rootURL: rootURL, // if we transition in this test we will receive failures // if the tests are run from a static file _doTransition: function(){} }); bootApplication(); }); test("Only use route rendered into main outlet for default into property on child", function() { Ember.TEMPLATES.application = compile("{{outlet menu}}{{outlet}}"); Ember.TEMPLATES.posts = compile("{{outlet}}"); Ember.TEMPLATES['posts/index'] = compile("postsIndex"); Ember.TEMPLATES['posts/menu'] = compile("postsMenu"); Router.map(function() { this.resource("posts", function() {}); }); App.PostsMenuView = Ember.View.extend({ tagName: 'div', templateName: 'posts/menu', classNames: ['posts-menu'] }); App.PostsIndexView = Ember.View.extend({ tagName: 'p', classNames: ['posts-index'] }); App.PostsRoute = Ember.Route.extend({ renderTemplate: function() { this.render(); this.render('postsMenu', { into: 'application', outlet: 'menu' }); } }); bootApplication(); handleURL("/posts"); equal(Ember.$('div.posts-menu:contains(postsMenu)', '#qunit-fixture').length, 1, "The posts/menu template was rendered"); equal(Ember.$('p.posts-index:contains(postsIndex)', '#qunit-fixture').length, 1, "The posts/index template was rendered"); }); test("Generating a URL should not affect currentModel", function() { Router.map(function() { this.route("post", { path: "/posts/:post_id" }); }); var posts = { 1: { id: 1 }, 2: { id: 2 } }; App.PostRoute = Ember.Route.extend({ model: function(params) { return posts[params.post_id]; } }); bootApplication(); handleURL("/posts/1"); var route = container.lookup('route:post'); equal(route.modelFor('post'), posts[1]); var url = router.generate('post', posts[2]); equal(url, "/posts/2"); equal(route.modelFor('post'), posts[1]); }); test("Generated route should be an instance of App.Route if provided", function() { var generatedRoute; Router.map(function() { this.route('posts'); }); App.Route = Ember.Route.extend(); bootApplication(); handleURL("/posts"); generatedRoute = container.lookup('route:posts'); ok(generatedRoute instanceof App.Route, 'should extend the correct route'); }); test("Nested index route is not overriden by parent's implicit index route", function() { Router.map(function() { this.resource('posts', function() { this.route('index', { path: ':category' } ); }); }); App.Route = Ember.Route.extend({ serialize: function(model) { return { category: model.category }; } }); bootApplication(); Ember.run(function() { router.transitionTo('posts', { category: 'emberjs' }); }); deepEqual(router.location.path, '/posts/emberjs'); }); test("Application template does not duplicate when re-rendered", function() { Ember.TEMPLATES.application = compile("<h3>I Render Once</h3>{{outlet}}"); Router.map(function() { this.route('posts'); }); App.ApplicationRoute = Ember.Route.extend({ model: function() { return Ember.A(); } }); bootApplication(); // should cause application template to re-render handleURL('/posts'); equal(Ember.$('h3:contains(I Render Once)').size(), 1); }); test("Child routes should render inside the application template if the application template causes a redirect", function() { Ember.TEMPLATES.application = compile("<h3>App</h3> {{outlet}}"); Ember.TEMPLATES.posts = compile("posts"); Router.map(function() { this.route('posts'); this.route('photos'); }); App.ApplicationRoute = Ember.Route.extend({ afterModel: function() { this.transitionTo('posts'); } }); bootApplication(); equal(Ember.$('#qunit-fixture > div').text(), "App posts"); }); test("The template is not re-rendered when the route's context changes", function() { Router.map(function() { this.route("page", { path: "/page/:name" }); }); App.PageRoute = Ember.Route.extend({ model: function(params) { return Ember.Object.create({name: params.name}); } }); var insertionCount = 0; App.PageView = Ember.View.extend({ didInsertElement: function() { insertionCount += 1; } }); Ember.TEMPLATES.page = Ember.Handlebars.compile( "<p>{{name}}</p>" ); bootApplication(); handleURL("/page/first"); equal(Ember.$('p', '#qunit-fixture').text(), "first"); equal(insertionCount, 1); handleURL("/page/second"); equal(Ember.$('p', '#qunit-fixture').text(), "second"); equal(insertionCount, 1, "view should have inserted only once"); Ember.run(function() { router.transitionTo('page', Ember.Object.create({name: 'third'})); }); equal(Ember.$('p', '#qunit-fixture').text(), "third"); equal(insertionCount, 1, "view should still have inserted only once"); }); test("The template is not re-rendered when two routes present the exact same template, view, & controller", function() { Router.map(function() { this.route("first"); this.route("second"); this.route("third"); this.route("fourth"); }); App.SharedRoute = Ember.Route.extend({ viewName: 'shared', setupController: function(controller) { this.controllerFor('shared').set('message', "This is the " + this.routeName + " message"); }, renderTemplate: function(controller, context) { this.render({ controller: 'shared' }); } }); App.FirstRoute = App.SharedRoute.extend(); App.SecondRoute = App.SharedRoute.extend(); App.ThirdRoute = App.SharedRoute.extend(); App.FourthRoute = App.SharedRoute.extend({ viewName: 'fourth' }); App.SharedController = Ember.Controller.extend(); var insertionCount = 0; App.SharedView = Ember.View.extend({ templateName: 'shared', didInsertElement: function() { insertionCount += 1; } }); // Extending, in essence, creates a different view App.FourthView = App.SharedView.extend(); Ember.TEMPLATES.shared = Ember.Handlebars.compile( "<p>{{message}}</p>" ); bootApplication(); handleURL("/first"); equal(Ember.$('p', '#qunit-fixture').text(), "This is the first message"); equal(insertionCount, 1, 'expected one assertion'); // Transition by URL handleURL("/second"); equal(Ember.$('p', '#qunit-fixture').text(), "This is the second message"); equal(insertionCount, 1, "view should have inserted only once"); // Then transition directly by route name Ember.run(function() { router.transitionTo('third').then(function(value){ ok(true, 'expected transition'); }, function(reason) { ok(false, 'unexpected transition failure: ', QUnit.jsDump.parse(reason)); }); }); equal(Ember.$('p', '#qunit-fixture').text(), "This is the third message"); equal(insertionCount, 1, "view should still have inserted only once"); // Lastly transition to a different view, with the same controller and template handleURL("/fourth"); equal(Ember.$('p', '#qunit-fixture').text(), "This is the fourth message"); equal(insertionCount, 2, "view should have inserted a second time"); }); test("ApplicationRoute with model does not proxy the currentPath", function() { var model = {}; var currentPath; App.ApplicationRoute = Ember.Route.extend({ model: function () { return model; } }); App.ApplicationController = Ember.ObjectController.extend({ currentPathDidChange: Ember.observer('currentPath', function() { currentPath = get(this, 'currentPath'); }) }); bootApplication(); equal(currentPath, 'index', 'currentPath is index'); equal('currentPath' in model, false, 'should have defined currentPath on controller'); }); test("Promises encountered on app load put app into loading state until resolved", function() { expect(2); var deferred = Ember.RSVP.defer(); App.IndexRoute = Ember.Route.extend({ model: function() { return deferred.promise; } }); Ember.TEMPLATES.index = Ember.Handlebars.compile("<p>INDEX</p>"); Ember.TEMPLATES.loading = Ember.Handlebars.compile("<p>LOADING</p>"); bootApplication(); equal(Ember.$('p', '#qunit-fixture').text(), "LOADING", "The loading state is displaying."); Ember.run(deferred.resolve); equal(Ember.$('p', '#qunit-fixture').text(), "INDEX", "The index route is display."); }); test("Route should tear down multiple outlets", function() { Ember.TEMPLATES.application = compile("{{outlet menu}}{{outlet}}{{outlet footer}}"); Ember.TEMPLATES.posts = compile("{{outlet}}"); Ember.TEMPLATES.users = compile("users"); Ember.TEMPLATES['posts/index'] = compile("postsIndex"); Ember.TEMPLATES['posts/menu'] = compile("postsMenu"); Ember.TEMPLATES['posts/footer'] = compile("postsFooter"); Router.map(function() { this.resource("posts", function() {}); this.resource("users", function() {}); }); App.PostsMenuView = Ember.View.extend({ tagName: 'div', templateName: 'posts/menu', classNames: ['posts-menu'] }); App.PostsIndexView = Ember.View.extend({ tagName: 'p', classNames: ['posts-index'] }); App.PostsFooterView = Ember.View.extend({ tagName: 'div', templateName: 'posts/footer', classNames: ['posts-footer'] }); App.PostsRoute = Ember.Route.extend({ renderTemplate: function() { this.render('postsMenu', { into: 'application', outlet: 'menu' }); this.render(); this.render('postsFooter', { into: 'application', outlet: 'footer' }); } }); bootApplication(); handleURL('/posts'); equal(Ember.$('div.posts-menu:contains(postsMenu)', '#qunit-fixture').length, 1, "The posts/menu template was rendered"); equal(Ember.$('p.posts-index:contains(postsIndex)', '#qunit-fixture').length, 1, "The posts/index template was rendered"); equal(Ember.$('div.posts-footer:contains(postsFooter)', '#qunit-fixture').length, 1, "The posts/footer template was rendered"); handleURL('/users'); equal(Ember.$('div.posts-menu:contains(postsMenu)', '#qunit-fixture').length, 0, "The posts/menu template was removed"); equal(Ember.$('p.posts-index:contains(postsIndex)', '#qunit-fixture').length, 0, "The posts/index template was removed"); equal(Ember.$('div.posts-footer:contains(postsFooter)', '#qunit-fixture').length, 0, "The posts/footer template was removed"); }); test("Route supports clearing outlet explicitly", function() { Ember.TEMPLATES.application = compile("{{outlet}}{{outlet modal}}"); Ember.TEMPLATES.posts = compile("{{outlet}}"); Ember.TEMPLATES.users = compile("users"); Ember.TEMPLATES['posts/index'] = compile("postsIndex {{outlet}}"); Ember.TEMPLATES['posts/modal'] = compile("postsModal"); Ember.TEMPLATES['posts/extra'] = compile("postsExtra"); Router.map(function() { this.resource("posts", function() {}); this.resource("users", function() {}); }); App.PostsIndexView = Ember.View.extend({ classNames: ['posts-index'] }); App.PostsModalView = Ember.View.extend({ templateName: 'posts/modal', classNames: ['posts-modal'] }); App.PostsExtraView = Ember.View.extend({ templateName: 'posts/extra', classNames: ['posts-extra'] }); App.PostsRoute = Ember.Route.extend({ actions: { showModal: function() { this.render('postsModal', { into: 'application', outlet: 'modal' }); }, hideModal: function() { this.disconnectOutlet({outlet: 'modal', parentView: 'application'}); } } }); App.PostsIndexRoute = Ember.Route.extend({ actions: { showExtra: function() { this.render('postsExtra', { into: 'posts/index' }); }, hideExtra: function() { this.disconnectOutlet({parentView: 'posts/index'}); } } }); bootApplication(); handleURL('/posts'); equal(Ember.$('div.posts-index:contains(postsIndex)', '#qunit-fixture').length, 1, "The posts/index template was rendered"); Ember.run(function() { router.send('showModal'); }); equal(Ember.$('div.posts-modal:contains(postsModal)', '#qunit-fixture').length, 1, "The posts/modal template was rendered"); Ember.run(function() { router.send('showExtra'); }); equal(Ember.$('div.posts-extra:contains(postsExtra)', '#qunit-fixture').length, 1, "The posts/extra template was rendered"); Ember.run(function() { router.send('hideModal'); }); equal(Ember.$('div.posts-modal:contains(postsModal)', '#qunit-fixture').length, 0, "The posts/modal template was removed"); Ember.run(function() { router.send('hideExtra'); }); equal(Ember.$('div.posts-extra:contains(postsExtra)', '#qunit-fixture').length, 0, "The posts/extra template was removed"); handleURL('/users'); equal(Ember.$('div.posts-index:contains(postsIndex)', '#qunit-fixture').length, 0, "The posts/index template was removed"); equal(Ember.$('div.posts-modal:contains(postsModal)', '#qunit-fixture').length, 0, "The posts/modal template was removed"); equal(Ember.$('div.posts-extra:contains(postsExtra)', '#qunit-fixture').length, 0, "The posts/extra template was removed"); }); test("Route supports clearing outlet using string parameter", function() { Ember.TEMPLATES.application = compile("{{outlet}}{{outlet modal}}"); Ember.TEMPLATES.posts = compile("{{outlet}}"); Ember.TEMPLATES.users = compile("users"); Ember.TEMPLATES['posts/index'] = compile("postsIndex {{outlet}}"); Ember.TEMPLATES['posts/modal'] = compile("postsModal"); Router.map(function() { this.resource("posts", function() {}); this.resource("users", function() {}); }); App.PostsIndexView = Ember.View.extend({ classNames: ['posts-index'] }); App.PostsModalView = Ember.View.extend({ templateName: 'posts/modal', classNames: ['posts-modal'] }); App.PostsRoute = Ember.Route.extend({ actions: { showModal: function() { this.render('postsModal', { into: 'application', outlet: 'modal' }); }, hideModal: function() { this.disconnectOutlet('modal'); } } }); bootApplication(); handleURL('/posts'); equal(Ember.$('div.posts-index:contains(postsIndex)', '#qunit-fixture').length, 1, "The posts/index template was rendered"); Ember.run(function() { router.send('showModal'); }); equal(Ember.$('div.posts-modal:contains(postsModal)', '#qunit-fixture').length, 1, "The posts/modal template was rendered"); Ember.run(function() { router.send('hideModal'); }); equal(Ember.$('div.posts-modal:contains(postsModal)', '#qunit-fixture').length, 0, "The posts/modal template was removed"); handleURL('/users'); equal(Ember.$('div.posts-index:contains(postsIndex)', '#qunit-fixture').length, 0, "The posts/index template was removed"); equal(Ember.$('div.posts-modal:contains(postsModal)', '#qunit-fixture').length, 0, "The posts/modal template was removed"); }); test("Route silently fails when cleaning an outlet from an inactive view", function() { expect(1); // handleURL Ember.TEMPLATES.application = compile("{{outlet}}"); Ember.TEMPLATES.posts = compile("{{outlet modal}}"); Ember.TEMPLATES.modal = compile("A Yo."); Router.map(function() { this.route("posts"); }); App.PostsRoute = Ember.Route.extend({ actions: { hideSelf: function() { this.disconnectOutlet({outlet: 'main', parentView: 'application'}); }, showModal: function() { this.render('modal', {into: 'posts', outlet: 'modal'}); }, hideModal: function() { this.disconnectOutlet({outlet: 'modal', parentView: 'posts'}); } } }); bootApplication(); handleURL('/posts'); Ember.run(function() { router.send('showModal'); }); Ember.run(function() { router.send('hideSelf'); }); Ember.run(function() { router.send('hideModal'); }); }); test("Aborting/redirecting the transition in `willTransition` prevents LoadingRoute from being entered", function() { expect(8); Router.map(function() { this.route("nork"); this.route("about"); }); var redirect = false; App.IndexRoute = Ember.Route.extend({ actions: { willTransition: function(transition) { ok(true, "willTransition was called"); if (redirect) { // router.js won't refire `willTransition` for this redirect this.transitionTo('about'); } else { transition.abort(); } } } }); var deferred = null; App.LoadingRoute = Ember.Route.extend({ activate: function() { ok(deferred, "LoadingRoute should be entered at this time"); }, deactivate: function() { ok(true, "LoadingRoute was exited"); } }); App.NorkRoute = Ember.Route.extend({ activate: function() { ok(true, "NorkRoute was entered"); } }); App.AboutRoute = Ember.Route.extend({ activate: function() { ok(true, "AboutRoute was entered"); }, model: function() { if (deferred) { return deferred.promise; } } }); bootApplication(); // Attempted transitions out of index should abort. Ember.run(router, 'transitionTo', 'nork'); Ember.run(router, 'handleURL', '/nork'); // Attempted transitions out of index should redirect to about redirect = true; Ember.run(router, 'transitionTo', 'nork'); Ember.run(router, 'transitionTo', 'index'); // Redirected transitions out of index to a route with a // promise model should pause the transition and // activate LoadingRoute deferred = Ember.RSVP.defer(); Ember.run(router, 'transitionTo', 'nork'); Ember.run(deferred.resolve); }); test("`didTransition` event fires on the router", function() { expect(3); Router.map(function(){ this.route("nork"); }); router = container.lookup('router:main'); router.one('didTransition', function(){ ok(true, 'didTransition fired on initial routing'); }); bootApplication(); router.one('didTransition', function(){ ok(true, 'didTransition fired on the router'); equal(router.get('url'), "/nork", 'The url property is updated by the time didTransition fires'); }); Ember.run(router, 'transitionTo', 'nork'); }); test("`didTransition` can be reopened", function() { expect(1); Router.map(function(){ this.route("nork"); }); Router.reopen({ didTransition: function(){ this._super.apply(this, arguments); ok(true, 'reopened didTransition was called'); } }); bootApplication(); }); test("Actions can be handled by inherited action handlers", function() { expect(4); App.SuperRoute = Ember.Route.extend({ actions: { foo: function() { ok(true, 'foo'); }, bar: function(msg) { equal(msg, "HELLO"); } } }); App.RouteMixin = Ember.Mixin.create({ actions: { bar: function(msg) { equal(msg, "HELLO"); this._super(msg); } } }); App.IndexRoute = App.SuperRoute.extend(App.RouteMixin, { actions: { baz: function() { ok(true, 'baz'); } } }); bootApplication(); router.send("foo"); router.send("bar", "HELLO"); router.send("baz"); }); test("currentRouteName is a property installed on ApplicationController that can be used in transitionTo", function() { expect(24); Router.map(function() { this.resource("be", function() { this.resource("excellent", function() { this.resource("to", function() { this.resource("each", function() { this.route("other"); }); }); }); }); }); bootApplication(); var appController = router.container.lookup('controller:application'); function transitionAndCheck(path, expectedPath, expectedRouteName) { if (path) { Ember.run(router, 'transitionTo', path); } equal(appController.get('currentPath'), expectedPath); equal(appController.get('currentRouteName'), expectedRouteName); } transitionAndCheck(null, 'index', 'index'); transitionAndCheck('/be', 'be.index', 'be.index'); transitionAndCheck('/be/excellent', 'be.excellent.index', 'excellent.index'); transitionAndCheck('/be/excellent/to', 'be.excellent.to.index', 'to.index'); transitionAndCheck('/be/excellent/to/each', 'be.excellent.to.each.index', 'each.index'); transitionAndCheck('/be/excellent/to/each/other', 'be.excellent.to.each.other', 'each.other'); transitionAndCheck('index', 'index', 'index'); transitionAndCheck('be', 'be.index', 'be.index'); transitionAndCheck('excellent', 'be.excellent.index', 'excellent.index'); transitionAndCheck('to.index', 'be.excellent.to.index', 'to.index'); transitionAndCheck('each', 'be.excellent.to.each.index', 'each.index'); transitionAndCheck('each.other', 'be.excellent.to.each.other', 'each.other'); }); test("Route model hook finds the same model as a manual find", function() { var Post; App.Post = Ember.Object.extend(); App.Post.reopenClass({ find: function() { Post = this; return {}; } }); Router.map(function() { this.route('post', { path: '/post/:post_id' }); }); bootApplication(); handleURL('/post/1'); equal(App.Post, Post); }); test("Can register an implementation via Ember.Location.registerImplementation (DEPRECATED)", function(){ var TestLocation = Ember.NoneLocation.extend({ implementation: 'test' }); expectDeprecation(/Using the Ember.Location.registerImplementation is no longer supported/); Ember.Location.registerImplementation('test', TestLocation); Router.reopen({ location: 'test' }); bootApplication(); equal(router.get('location.implementation'), 'test', 'custom location implementation can be registered with registerImplementation'); }); test("Ember.Location.registerImplementation is deprecated", function(){ var TestLocation = Ember.NoneLocation.extend({ implementation: 'test' }); expectDeprecation(function(){ Ember.Location.registerImplementation('test', TestLocation); }, "Using the Ember.Location.registerImplementation is no longer supported. Register your custom location implementation with the container instead."); }); test("Routes can refresh themselves causing their model hooks to be re-run", function() { Router.map(function() { this.resource('parent', { path: '/parent/:parent_id' }, function() { this.route('child'); }); }); var appcount = 0; App.ApplicationRoute = Ember.Route.extend({ model: function() { ++appcount; } }); var parentcount = 0; App.ParentRoute = Ember.Route.extend({ model: function(params) { equal(params.parent_id, '123'); ++parentcount; }, actions: { refreshParent: function() { this.refresh(); } } }); var childcount = 0; App.ParentChildRoute = Ember.Route.extend({ model: function() { ++childcount; } }); bootApplication(); equal(appcount, 1); equal(parentcount, 0); equal(childcount, 0); Ember.run(router, 'transitionTo', 'parent.child', '123'); equal(appcount, 1); equal(parentcount, 1); equal(childcount, 1); Ember.run(router, 'send', 'refreshParent'); equal(appcount, 1); equal(parentcount, 2); equal(childcount, 2); }); test("Specifying non-existent controller name in route#render throws", function() { expect(1); Router.map(function() { this.route("home", { path: "/" }); }); App.HomeRoute = Ember.Route.extend({ renderTemplate: function() { try { this.render('homepage', { controller: 'stefanpenneristhemanforme' }); } catch(e) { equal(e.message, "You passed `controller: 'stefanpenneristhemanforme'` into the `render` method, but no such controller could be found."); } } }); bootApplication(); }); test("Redirecting with null model doesn't error out", function() { Router.map(function() { this.route("home", { path: '/' }); this.route("about", { path: '/about/:hurhurhur' }); }); App.HomeRoute = Ember.Route.extend({ beforeModel: function() { this.transitionTo('about', null); } }); App.AboutRoute = Ember.Route.extend({ serialize: function(model) { if (model === null) { return { hurhurhur: 'TreeklesMcGeekles' }; } } }); bootApplication(); equal(router.get('location.path'), "/about/TreeklesMcGeekles"); }); test("rejecting the model hooks promise with a non-error prints the `message` property", function() { var rejectedMessage = 'OMG!! SOOOOOO BAD!!!!', rejectedStack = 'Yeah, buddy: stack gets printed too.', originalLoggerError = Ember.Logger.error; Router.map(function() { this.route("yippie", { path: "/" }); }); Ember.Logger.error = function(initialMessage, errorMessage, errorStack) { equal(initialMessage, 'Error while loading route: yippie', 'a message with the current route name is printed'); equal(errorMessage, rejectedMessage, "the rejected reason's message property is logged"); equal(errorStack, rejectedStack, "the rejected reason's stack property is logged"); }; App.YippieRoute = Ember.Route.extend({ model: function(){ return Ember.RSVP.reject({message: rejectedMessage, stack: rejectedStack}); } }); bootApplication(); Ember.Logger.error = originalLoggerError; }); test("rejecting the model hooks promise with no reason still logs error", function() { var originalLoggerError = Ember.Logger.error; Router.map(function() { this.route("wowzers", { path: "/" }); }); Ember.Logger.error = function(initialMessage) { equal(initialMessage, 'Error while loading route: wowzers', 'a message with the current route name is printed'); }; App.WowzersRoute = Ember.Route.extend({ model: function(){ return Ember.RSVP.reject(); } }); bootApplication(); Ember.Logger.error = originalLoggerError; }); test("rejecting the model hooks promise with a string shows a good error", function() { var originalLoggerError = Ember.Logger.error, rejectedMessage = "Supercalifragilisticexpialidocious"; Router.map(function() { this.route("yondo", { path: "/" }); }); Ember.Logger.error = function(initialMessage, errorMessage) { equal(initialMessage, 'Error while loading route: yondo', 'a message with the current route name is printed'); equal(errorMessage, rejectedMessage, "the rejected reason's message property is logged"); }; App.YondoRoute = Ember.Route.extend({ model: function(){ return Ember.RSVP.reject(rejectedMessage); } }); bootApplication(); Ember.Logger.error = originalLoggerError; }); if (Ember.FEATURES.isEnabled("ember-routing-will-change-hooks")) { test("willLeave, willChangeModel actions fire on routes", function() { expect(2); App.Router.map(function() { this.route('user', { path: '/user/:id' }); }); function shouldNotFire() { ok(false, "this action shouldn't have been received"); } var willChangeFired = false, willLeaveFired = false; App.IndexRoute = Ember.Route.extend({ actions: { willChangeModel: shouldNotFire, willChangeContext: shouldNotFire, willLeave: function() { willLeaveFired = true; } } }); App.UserRoute = Ember.Route.extend({ actions: { willChangeModel: function() { willChangeFired = true; }, willChangeContext: shouldNotFire, willLeave: shouldNotFire } }); bootApplication(); Ember.run(router, 'transitionTo', 'user', { id: 'wat' }); ok(willLeaveFired, "#actions.willLeaveFired"); Ember.run(router, 'transitionTo', 'user', { id: 'lol' }); ok(willChangeFired, "user#actions.willChangeModel"); }); } else { test("willLeave, willChangeContext, willChangeModel actions don't fire unless feature flag enabled", function() { expect(1); App.Router.map(function() { this.route('about'); }); function shouldNotFire() { ok(false, "this action shouldn't have been received"); } App.IndexRoute = Ember.Route.extend({ actions: { willChangeModel: shouldNotFire, willChangeContext: shouldNotFire, willLeave: shouldNotFire } }); App.AboutRoute = Ember.Route.extend({ setupController: function() { ok(true, "about route was entered"); } }); bootApplication(); Ember.run(router, 'transitionTo', 'about'); }); }
g13013/ember.js
packages_es6/ember/tests/routing/basic_test.js
JavaScript
mit
84,137
""" from https://codelab.interviewbit.com/problems/symmetry/ """ # Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param A : root node of tree # @return an integer def isSymmetric(self, A): return self.are_symmetric(A.left, A.right) def are_symmetric(self, tree1, tree2): if tree1 is None or tree2 is None: # when checking the bottom return tree1 == tree2 return tree1.val == tree2.val and self.are_symmetric(tree1.left, tree2.right) and self.are_symmetric( tree1.right, tree2.left) # Could
JuanCTorres/interview-prep-solutions
codelab/symmetric_trees.py
Python
mit
694
/** * Simple themeing with color overrides */ export namespace Colors { export let flatButtonPrimary = 'rgb(0, 188, 212)'; }
basarat/uic
src/base/styles.tsx
TypeScript
mit
129
/* Gruntfile.js * Grunt workflow for building kick-ass AngularJS applications. * @author Calvin Lai <calvin@wunwun.com> */ module.exports = function(grunt) { var _APP_NAME_ = "CHANGE ME IN Gruntfile.js"; // initial grunt configuration grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), appDir: 'app/www', tmpDir: 'tmp', srcDir: 'src', bowerDir: 'vendor', vendorDir: 'src/js/vendor', releaseDir: '<%= appDir %>', connect: { server: { options: { port: 9001, base: '<%= appDir %>', open: true } } }, assets: { css: { vendor: [ // Add additional Bower components here '<%= bowerDir %>/bootstrap/dist/css/bootstrap.css', '<%= bowerDir %>/font-awesome/css/font-awesome.css' ], // shouldn't need to touch this src: [ '<%= appDir %>/css/vendor.css', '<%= appDir %>/css/app.css' ] }, js: { vendor: [ // add any Bower components here. '<%= bowerDir %>/angular/angular.js', '<%= bowerDir %>/angular-route/angular-route.js', '<%= bowerDir %>/angular-touch/angular-touch.js' ], // shouldn't need to touch this. src: [ '<%= appDir %>/js/vendor.js', '<%= appDir %>/js/pg.js', '<%= appDir %>/js/app.js', '<%= appDir %>/js/config.js', '<%= appDir %>/js/modules.js', '<%= appDir %>/js/directives.js', '<%= appDir %>/js/filters.js', '<%= appDir %>/js/services.js', '<%= appDir %>/js/controllers.js' ] } }, // concatenate files for angularjs concat: { vendor: { files: { '<%= tmpDir %>/css/vendor.css': '<%= assets.css.vendor %>', '<%= tmpDir %>/js/vendor.js' : '<%= assets.js.vendor %>' } }, angular: { files: { '<%= tmpDir %>/js/config.js' : ['<%= srcDir %>/js/config/*.js'], '<%= tmpDir %>/js/modules.js' : ['<%= srcDir %>/js/modules/*.js', '<%= srcDir %>/js/modules/**/*.js'], '<%= tmpDir %>/js/controllers.js' : ['<%= srcDir %>/js/controllers/*.js', '<%= srcDir %>/js/controllers/**/*.js'], '<%= tmpDir %>/js/directives.js' : ['<%= srcDir %>/js/directives/*.js', '<%= srcDir %>/js/directives/**/*.js'], '<%= tmpDir %>/js/filters.js' : ['<%= srcDir %>/js/filters/*.js', '<%= srcDir %>/js/filters/**/*.js'], '<%= tmpDir %>/js/modules.js' : ['<%= srcDir %>/js/modules/*.js', '<%= srcDir %>/js/modules/**/*.js'], '<%= tmpDir %>/js/services.js' : ['<%= srcDir %>/js/services/*.js', '<%= srcDir %>/js/services/**/*.js'] } }, production: { files: { '<%= appDir %>/js/application.js': [ '<%= tmpDir %>/js/production.js', '<%= tmpDir %>/js/vendor.js', '<%= tmpDir %>/js/pg.js', '<%= tmpDir %>/js/app.js', '<%= tmpDir %>/js/config.js', '<%= tmpDir %>/js/modules.js', '<%= tmpDir %>/js/directives.js', '<%= tmpDir %>/js/filters.js', '<%= tmpDir %>/js/services.js', '<%= tmpDir %>/js/controllers.js' ] } } }, // for cleaning builds before re-building clean: { options: { force: true }, tmp: { src: ['<%= tmpDir %>'], }, development: { src: ['<%= tmpDir %>', '<%= appDir %>'] }, production: { src: ['<%= tmpDir %>', '<%= releaseDir %>'] }, css: { src: ['<%= appDir %>/css'] }, js: { src: ['<%= appDir %>/js'] }, img: { src: ['<%= appDir %>/img'] }, img: { src: ['<%= appDir %>/fonts'] }, partials: { src: ['<%= appDir %>/html/partials'] } }, copy: { config: { files: [ { src: '<%= srcDir %>/js/config/application.js', dest: '<%= tmpDir %>/js/config/application.js' }, { src: '<%= srcDir %>/js/app.js', dest: '<%= tmpDir %>/js/app.js' }, { src: '<%= srcDir %>/js/pg.js', dest: '<%= tmpDir %>/js/pg.js' }, { src: '<%= srcDir %>/config.xml', dest: '<%= appDir %>/config.xml' } ] }, vendor: { files: [ { src: '<%= tmpDir %>/css/vendor.css', dest: '<%= appDir %>/css/vendor.css' }, { src: '<%= tmpDir %>/js/vendor.js', dest: '<%= appDir %>/js/vendor.js' } ] }, img: { files: [ { expand: true, cwd: '<%= srcDir %>/img/', src: ['**'], dest: '<%= appDir %>/img/' } ] }, partials: { files: [ { expand: true, cwd: '<%= srcDir %>/html/partials/', src: ['**'], dest: '<%= appDir %>/html/partials/' } ] }, fonts: { files: [ { expand: true, cwd: '<%= bowerDir %>/font-awesome/fonts/', src: ['**'], dest: '<%= appDir %>/fonts/' } ] }, tmp_to_build: { files: [ { expand: true, cwd: '<%= tmpDir %>/js/', src: ['*'], dest: '<%= appDir %>/js/' } ] }, development: { files: [ { src: '<%= srcDir %>/js/config/environments/development.js', dest: '<%= appDir %>/js/config/development.js' } ] }, production: { files: [ { src: '<%= srcDir %>/js/config/environments/production.js', dest: '<%= tmpDir %>/js/production.js' } ] } }, // compile LESS files into CSS and store them in temp directories less: { options: { paths: [ // add any additional paths to LESS components here "<%= bowerDir %>/lesshat", "<%= srcDir %>/css/config" ] }, development: { files: { // put app.css directly into the build directory for development "<%= appDir %>/css/app.css": [ "<%= srcDir %>/css/common/*.less", "<%= srcDir %>/css/*.less" ] } }, production: { files: { // put app.css in tmp dir in production, so we can run cssmin on it after "<%= tmpDir %>/css/app.css": [ "<%= srcDir %>/css/common/*.less", "<%= srcDir %>/css/*.less" ] } } }, // ngmin for pre-minifying AngularJS apps ngmin: { routers: { src: '<%= tmpDir %>/js/config/router.js', dest: '<%= tmpDir %>/js/config/router.js' }, controllers: { src: '<%= tmpDir %>/js/controllers.js', dest: '<%= tmpDir %>/js/controllers.js' }, directives: { src: '<%= tmpDir %>/js/directives.js', dest: '<%= tmpDir %>/js/directives.js' }, modules: { src: '<%= tmpDir %>/js/modules.js', dest: '<%= tmpDir %>/js/modules.js' }, filters: { src: '<%= tmpDir %>/js/filters.js', dest: '<%= tmpDir %>/js/filters.js' }, services: { src: '<%= tmpDir %>/js/services.js', dest: '<%= tmpDir %>/js/services.js' }, vendor: { src: '<%= tmpDir %>/js/vendor.js', dest: '<%= tmpDir %>/js/vendor.js' } }, // uglify js for production uglify: { production: { files: { '<%= appDir %>/js/application.js': [ '<%= appDir %>/js/application.js' ] } }, }, // minify css for production cssmin: { production: { files: { '<%= appDir %>/css/app.css': [ '<%= tmpDir %>/css/vendor.css', '<%= tmpDir %>/css/app.css' ], } } }, // watch files, build on the fly for development watch: { root: { files: ['<%= srcDir %>/*'], tasks: ['copy:config'] }, scripts: { files: ['<%= srcDir %>/js/**','<%= srcDir %>/js/*'], tasks: [ 'clean:js', 'concat:angular', 'concat:vendor', 'copy:development', 'copy:config', 'copy:vendor', 'copy:tmp_to_build' ] }, less: { files: [ '<%= srcDir %>/css/*.less', '<%= srcDir %>/css/**/*.less' ], tasks: [ 'clean:css', 'concat:vendor', 'copy:vendor', 'less:development' ] }, img: { files: ['<%= srcDir %>/img/**'], tasks: ['clean:img', 'copy:img'] }, fonts: { files: ['<%= srcDir %>/fonts/**'], tasks: ['clean:fonts', 'copy:fonts'] }, partials: { files: ['<%= srcDir %>/html/partials/**'], tasks: ['clean:partials', 'copy:partials'] }, layouts: { files: ['<%= srcDir %>/html/layouts/**'], tasks: ['layouts:development'] } }, layouts: { options: { layout: '<%= srcDir %>/html/layouts/application.tmpl', }, development: { options: { dest: '<%= appDir %>/index.html' }, files: { css: '<%= assets.css.src %>', js: '<%= assets.js.src %>' } }, production: { options: { dest: '<%= releaseDir %>/index.html' }, files: { css: '<%= assets.css.src %>', js: '<%= assets.js.src %>' } } }, config: { options: { template: '<%= srcDir %>/config.xml.tmpl', dest: '<%= appDir %>/config.xml' }, enterprise: {}, production: {}, development: {} }, // main build task (custom) with options // this task also builds out the main index.html // file based on templates, which are environment-aware build: { development: {}, production: {}, enterprise: {} } }); // load grunt npm modules grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-contrib-copy'); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-less'); grunt.loadNpmTasks('grunt-contrib-sass'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-cssmin'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-connect'); grunt.loadNpmTasks('grunt-ngmin'); grunt.registerTask('dev', ['build:development', 'connect', 'watch']); // build HTML files based on target grunt.registerMultiTask('layouts', 'Builds an HTML file for angular.', function() { var opts = this.options() , target = this.target , css = this.files[0].src , js = this.files[1].src , layout = grunt.template.process(grunt.file.read(opts.layout), { data: { env: target, js: js, css: css, appName: _APP_NAME_ } }); // generate main index.html file grunt.file.write(opts.dest, layout); grunt.log.write('Generating ' + opts.dest + '...').ok(); }); grunt.registerMultiTask('config', 'Builds the Cordova configuration file from template.', function() { var opts = this.options() , target = this.target , version = this.args[0] || ''; var template = grunt.template.process(grunt.file.read(opts.template), { data: { target: target, appName: _APP_NAME_ } }); // generate main index.html file grunt.file.write(opts.dest, template); grunt.log.write('Generating ' + opts.dest + '...').ok(); }); // task for building main index page based on environment grunt.registerMultiTask('build', 'Build the app based on environment.', function() { var opts = this.options() , target = this.target , env = target , args = this.args , version = args[0]; if (target == 'enterprise') { env = 'production'; } // clean up directories grunt.task.run('clean:' + env); // build all less files based on environment grunt.task.run('less:' + env); // concat angular files grunt.task.run('concat:angular'); // use ngmin to pre-minify angular files grunt.task.run('ngmin'); // concat vendor libs grunt.task.run('concat:vendor'); // copy all files grunt.task.run('copy:' + env); grunt.task.run('copy:config'); grunt.task.run('copy:partials'); grunt.task.run('copy:img'); grunt.task.run('copy:fonts'); // copy tmp files to development if (target == 'development') { grunt.task.run('copy:vendor'); grunt.task.run('copy:tmp_to_build'); } if (target == 'production' || target == 'enterprise') { // concat all angular files into a single file grunt.task.run('concat:production'); grunt.task.run('uglify:production'); grunt.task.run('cssmin:production'); } // build cordova config.xml file, uses target so we // can switch from production to enterprise for bundle ID grunt.task.run('config:' + target); // build main index.html file last grunt.task.run('layouts:' + env); }); };
dharmapurikar/ng-phonegap
Gruntfile.js
JavaScript
mit
13,023
package CellContent; import java.util.*; import Cell.Cell; import Models.Ant; import javafx.scene.paint.Color; public class ForagingAntsContent extends CellContent{ List<Ant>antsHere; double homePheromone, foodPheromone, maxPheromone; boolean isFoodSource, isHome; public ForagingAntsContent (int i, Color col,boolean home, boolean food, double maxPh, double foodPh, double homePh, List<Ant> ants) { super(i, col); isHome = home; isFoodSource = food; antsHere = ants; homePheromone = homePh; foodPheromone = foodPh; // TODO Auto-generated constructor stub } public List<Ant> getAnts(){ return antsHere; } public void setAnts(List<Ant> ants){ antsHere = ants; } public void setIsFoodSource(boolean food){ isFoodSource = food; } public boolean getIsFoodSource(){ return isFoodSource; } public void setIsHome(boolean home){ isHome = home; } public boolean getIsHome(){ return isHome; } public void setHomePheromone(double home){ homePheromone = home; } public double getHomePheromone(){ return homePheromone; } public void setFoodPheromone(double food){ foodPheromone = food; } public double getFoodPheromone(){ return foodPheromone; } public double getPheromone(boolean goingHome){ if(goingHome){ return homePheromone; }else{ return foodPheromone; } } public double getMaxPheromone(){ return maxPheromone; } public void setMaxPheromone(boolean home){ if(home){ homePheromone = maxPheromone; }else{ foodPheromone = maxPheromone; } } public List<Ant> getAntsClone(){ List<Ant> clone = new ArrayList<Ant>(); for(Ant a : antsHere){ Ant aClone = new Ant(a.getLifeLeft()); aClone.setOrientation(a.getOrientation()); aClone.hasFoodItem(a.hasFoodItem()); clone.add(aClone); } return clone; } }
NaijiaoZhang/cellsociety
src/CellContent/ForagingAntsContent.java
Java
mit
2,214