repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
cs460-group1/chat-server
server.py
55
#!/usr/bin/env python3 from server import main main()
mit
TotalVerb/RTanque
lib/rtanque/runner.rb
2727
require 'ruby-prof' # Add the working directory so that loading of bots works as expected $LOAD_PATH << Dir.pwd # Add the gem root dir so that sample_bots can be loaded $LOAD_PATH << File.expand_path('../../../', __FILE__) module RTanque # Runner manages running an {RTanque::Match} class Runner LoadError = Class.new(::LoadError) attr_reader :match # @param [Integer] width # @param [Integer] height # @param [*match_args] args provided to {RTanque::Match#initialize} def initialize(width, height, *match_args) @match = RTanque::Match.new(RTanque::Arena.new(width, height), *match_args) end # Attempts to load given {RTanque::Bot::Brain} given its path # @param [String] brain_path # @raise [RTanque::Runner::LoadError] if brain could not be loaded def add_brain_path(brain_path, name = nil, sandbox: false) parsed_path = self.parse_brain_path(brain_path) relative_path = File.expand_path parsed_path.path, File.expand_path('../../../', __FILE__) if File.exists? parsed_path.path path = parsed_path.path elsif File.exists? relative_path path = relative_path else fail LoadError, "Could not find file #{parsed_path.path}" end code = File.read path add_brain_code code, parsed_path.multiplier, name, sandbox end def add_brain_code(code, num_bots = 1, name = nil, sandbox = false) brains = num_bots.times.map do begin BotSandbox.new(code, sandbox).bot rescue ::LoadError raise LoadError, 'Failed to load bot from code.' end end bots = brains.map { |klass| RTanque::Bot.new_random_location(self.match.arena, klass, name) } self.match.add_bots(bots) bots end # Starts the match # @param [Boolean] gui if false, runs headless match def start(profile = false) if profile RubyProf.measure_mode = RubyProf::PROCESS_TIME RubyProf.start end # RubyProf.pause trap(:INT) { self.match.stop } self.match.start if profile result = RubyProf.stop printer = RubyProf::FlatPrinterWithLineNumbers.new(result) printer.print(STDOUT) end end def recording? !self.recorder.nil? end protected BRAIN_PATH_PARSER = /\A(.+?)\:[x|X](\d+)\z/ # @!visibility private ParsedBrainPath = Struct.new(:path, :multiplier) def parse_brain_path(brain_path) path = brain_path.gsub('\.rb$', '') multiplier = 1 brain_path.match(BRAIN_PATH_PARSER) { |m| path = m[1] multiplier = m[2].to_i } ParsedBrainPath.new(path, multiplier) end end end
mit
stanley4162004/HashtagTrends
top20/js/mainCode.js
1328
var startIndex = 0; var jsonText = ""; getResponseText(); showFiveImages(); function showPrevious() { if (startIndex >= 5) { startIndex -= 5; } showFiveImages(); } function showNext() { if (startIndex <= 10) { startIndex += 5; } showFiveImages(); } function showFiveImages() { // parse the JSON file to array of posts var posts = []; posts = JSON.parse(jsonText); // sort the post from most liked to least liked posts.sort(function (a, b) { return b.likes.count - a.likes.count; }); // fill the top20Images <div> with 20 <img> tags var imageHTML = document.getElementById("top20Images"); var imgs = ""; var i = 0; imgs += "<table><tbody><tr>"; for (i = startIndex; i < startIndex + 5; ++i) { var currentImage = posts[i].images.thumbnail; //imgs += "<img src=" + currentImage.url + " width: " + currentImage.width + " height:" + currentImage.height + ">"; imgs += "<td><img src=" + currentImage.url + "></td>"; } imgs += "</tr></tbody></table>"; imageHTML.innerHTML = imgs; } function getResponseText() { var request = new XMLHttpRequest(); request.open("GET", "data/parisattacks.json", false); request.onreadystatechange = function () { if (request.readyState === XMLHttpRequest.DONE && request.status === 200) { jsonText = request.responseText; } } request.send(null); }
mit
Hearthstonepp/Hearthstonepp
Includes/Rosetta/Tasks/SimpleTasks/RandomEntourageTask.hpp
1310
// This code is based on Sabberstone project. // Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva // RosettaStone is hearthstone simulator using C++ with reinforcement learning. // Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon #ifndef ROSETTASTONE_RANDOM_ENTOURAGE_TASK_HPP #define ROSETTASTONE_RANDOM_ENTOURAGE_TASK_HPP #include <Rosetta/Tasks/ITask.hpp> namespace RosettaStone::SimpleTasks { //! //! \brief RandomEntourageTask class. //! //! This class represents the task for picking entourage at random. //! class RandomEntourageTask : public ITask { public: //! Constructs task with given \p count and \p isOpponent. //! \param count A value indicating the number of picking. //! \param isOpponent A flag to owner indicating opponent player. RandomEntourageTask(int count = 1, bool isOpponent = false); //! Returns task ID. //! \return Task ID. TaskID GetTaskID() const override; private: //! Processes task logic internally and returns meta data. //! \param player The player to run task. //! \return The result of task processing. TaskStatus Impl(Player& player) override; int m_count = 1; bool m_isOpponent = false; }; } // namespace RosettaStone::SimpleTasks #endif // ROSETTASTONE_RANDOM_ENTOURAGE_TASK_HPP
mit
washingtonsoares/hihiringPPI
app/controllers/front/front_controller.rb
88
class Front::FrontController < ApplicationController layout 'front/application' end
mit
ericsonmichaelj/fear-the-repo
src/components/ResumeHeader.js
3966
import React, { PropTypes } from 'react'; import _ from 'underscore'; import Editor from 'react-medium-editor'; import { exactLength, isDefined, isValidEmail } from 'utils/validation'; export default class ResumeHeader extends React.Component { static propTypes = { actions: PropTypes.object, currentErrorMessage: PropTypes.string, currentTheme: PropTypes.string, handleUpdateLocalState: PropTypes.func, resumeThemes: PropTypes.object, resumeState: PropTypes.object, styles: PropTypes.object, validations: PropTypes.object } validateField(event, validatorsArray, key, whereFrom) { const value = event.target.textContent; const validEntry = _.every(validatorsArray, validator => validator(value) ); if (validEntry) { this.props.validations[key] = true; this.props.handleUpdateLocalState(event, key, whereFrom); this.props.actions.updateErrorMessage(''); } else { this.props.validations[key] = false; this.props.actions.updateErrorMessage(key); } const shouldEnable = _.every(this.props.validations, validation => validation === true ); if (shouldEnable) { this.props.actions.enableSubmit('Resume'); } else { this.props.actions.disableSubmit('Resume'); } } render() { const { currentErrorMessage, currentTheme, resumeThemes } = this.props; const { resumeHeader } = this.props.resumeState; return ( <div style={resumeThemes[currentTheme].headerDiv}> {currentErrorMessage ? <div style={this.props.styles.errorMessageStyle}> {currentErrorMessage} </div> : ''} <div style={resumeThemes[currentTheme].headerLeft}> <Editor style={resumeThemes[currentTheme].name} text={resumeHeader.name || 'Your Full Name'} options={{toolbar: false}} onBlur={e => this.validateField(e, [isDefined], 'name', 'header')} /> <Editor style={resumeThemes[currentTheme].location} text={resumeHeader.city || 'Your City, ST'} options={{toolbar: false}} onBlur={e => this.validateField(e, [isDefined], 'city', 'header')} /> <div> <Editor style={resumeThemes[currentTheme].phone} text={resumeHeader.phone || 'Your Phone Number'} options={{toolbar: false}} onBlur={e => this.validateField(e, [isDefined], 'phone', 'header')} /> <div style={resumeThemes[currentTheme].headerPipe}> | </div> <Editor style={resumeThemes[currentTheme].email} text={resumeHeader.displayEmail || 'Your Email Address'} options={{toolbar: false}} onBlur={e => this.validateField(e, [isDefined, isValidEmail], 'email', 'header')} /> </div> </div> <div style={resumeThemes[currentTheme].headerRight}> <Editor style={resumeThemes[currentTheme].webLinkedin} text={resumeHeader.webLinkedin || 'LinkedIn.com/in/YourLinkedIn'} options={{toolbar: false}} onBlur={e => this.props.handleUpdateLocalState(e, 'webLinkedin', 'header')} /> <Editor style={resumeThemes[currentTheme].webOther} text={resumeHeader.webOther || 'Other web links (Github, Behance, etc)'} options={{toolbar: false}} onBlur={e => this.props.handleUpdateLocalState(e, 'webOther', 'header')} /> </div> </div> ); } } // <Editor style={resumeThemes[currentTheme].profession} // text={resumeHeader.profession || 'Your Profession or Job Title'} // options={{toolbar: false}} // onBlur={e => this.props.handleUpdateLocalState(e, 'profession', 'header')} />
mit
dxw/whippet
src/Services/BaseApi.php
773
<?php namespace Dxw\Whippet\Services; // A thin wrapper around the low-level API functions class BaseApi { private $client; public function __construct() { $this->client = new \GuzzleHttp\Client([ 'headers' => [ 'User-Agent' => 'Whippet https://github.com/dxw/whippet/' ] ]); } public function get($url) { try { $response = $this->client->get($url); } catch (\GuzzleHttp\Exception\ConnectException $e) { return \Result\Result::err('Failed to connect to '.$url); } catch (\GuzzleHttp\Exception\RequestException $e) { return \Result\Result::err('Failed to receive data from '.$url); } return \Result\Result::ok($response->getBody()); } }
mit
hosamshahin/OpenDSA
ODSAkhan-exercises/utils/test/math.js
3274
module("math" ); (function(){ test( "math miscellanea", 44, function() { deepEqual( KhanUtil.digits(376), [ 6, 7, 3 ], "digits(376)" ); deepEqual( KhanUtil.integerToDigits(376), [ 3, 7, 6 ], "integerToDigits(376)" ); equal( KhanUtil.getGCD(216, 1024), 8, "gcd(216, 1024)" ); equal( KhanUtil.getGCD(512341, 2325183), 1, "gcd(512341, 2325183)" ); equal( KhanUtil.getGCD(53110108, 109775188), 68, "gcd(53110108, 109775188)" ); equal( KhanUtil.getGCD(-21, 14), 7, "gcd(-21, 14)" ); equal( KhanUtil.getGCD(-21, -14), 7, "gcd(-21, -14)" ); equal( KhanUtil.getGCD(123, 1), 1, "gcd(123, 1)" ); equal( KhanUtil.getGCD(123, 1), 1, "gcd(123, 1)" ); equal( KhanUtil.getGCD(123, 123), 123, "gcd(123, 123)" ); equal( KhanUtil.getGCD(169, 26, -52), 13, "gcd(169, 26, -52)" ); equal( KhanUtil.getLCM(216, 1024), 27648, "lcm(216, 1024)" ); equal( KhanUtil.getLCM(216, -1024), 27648, "lcm(216, -1024)" ); equal( KhanUtil.getLCM(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), 2520, "lcm(1..10)" ); equal( KhanUtil.isPrime(1), false, "primeq 1" ); equal( KhanUtil.isPrime(2), true, "primeq 2" ); equal( KhanUtil.isPrime(216), false, "primeq 216" ); equal( KhanUtil.isPrime(127), true, "primeq 127" ); equal( KhanUtil.isPrime(129), false, "primeq 129" ); equal( KhanUtil.isOdd(0), false, "oddq 0" ); equal( KhanUtil.isOdd(1), true, "oddq 1" ); equal( KhanUtil.isEven(0), true, "evenq 0" ); equal( KhanUtil.isEven(1), false, "evenq 1" ); deepEqual( KhanUtil.getPrimeFactorization( 6 ), [ 2, 3 ], "factor 6" ); deepEqual( KhanUtil.getPrimeFactorization( 23 ), [ 23 ], "factor 23" ); deepEqual( KhanUtil.getPrimeFactorization( 49 ), [ 7, 7 ], "factor 49" ); deepEqual( KhanUtil.getPrimeFactorization( 45612394 ), [ 2, 17, 67, 20023 ], "factor 45612394" ); deepEqual( KhanUtil.getFactors( 6 ), [ 1, 2, 3, 6 ], "factors 6" ); deepEqual( KhanUtil.getFactors( 492 ), [ 1, 2, 3, 4, 6, 12, 41, 82, 123, 164, 246, 492 ], "factors 492" ); deepEqual( KhanUtil.getFactors( 45612394 ), [ 1, 2, 17, 34, 67, 134, 1139, 2278, 20023, 40046, 340391, 680782, 1341541, 2683082, 22806197, 45612394 ], "factors 45612394" ); deepEqual( KhanUtil.getMultiples( 7, 70 ), [ 7, 14, 21, 28, 35, 42, 49, 56, 63, 70 ], "multiples 7, 70" ); deepEqual( KhanUtil.getMultiples( 7, 80 ), [ 7, 14, 21, 28, 35, 42, 49, 56, 63, 70, 77 ], "multiples 7, 80" ); deepEqual( KhanUtil.getMultiples( 7, 83 ), [ 7, 14, 21, 28, 35, 42, 49, 56, 63, 70, 77 ], "multiples 7, 83" ); equal( KhanUtil.roundTo( 2, Math.PI ), 3.14, "roundTo 2, pi" ); equal( KhanUtil.roundTo( 0, Math.PI ), 3, "roundTo 0, pi" ); deepEqual( KhanUtil.toFraction( 4/8 ), [ 1, 2 ], "4/8" ); deepEqual( KhanUtil.toFraction( 0.666 ), [ 333, 500 ], "0.666" ); deepEqual( KhanUtil.toFraction( 0.666, 0.001 ), [ 2, 3 ], "0.666 with tol" ); deepEqual( KhanUtil.toFraction( 20/14 ), [ 10, 7 ], "20/14" ); deepEqual( KhanUtil.toFraction( 500 ), [ 500, 1 ], "500" ); deepEqual( KhanUtil.toFraction( -500 ), [ -500, 1 ], "-500" ); deepEqual( KhanUtil.toFraction( -Math.PI, 0.000001 ), [ -355, 113 ], "-pi" ); deepEqual( KhanUtil.sortNumbers([ 134, 17, 2, 46 ]), [ 2, 17, 46, 134 ], "sort some stuff" ); deepEqual( KhanUtil.sortNumbers( KhanUtil.shuffle( KhanUtil.primes ) ), KhanUtil.primes, "shuffle then sort the primes" ); }); })();
mit
Discordius/Telescope
packages/lesswrong/components/sequences/SequencesEditForm.tsx
1054
import { Components, registerComponent, getFragment } from '../../lib/vulcan-lib'; import React from 'react'; import Sequences from '../../lib/collections/sequences/collection'; const SequencesEditForm = ({ documentId, successCallback, cancelCallback, removeSuccessCallback }: { documentId: string, successCallback?: ()=>void, cancelCallback?: ()=>void, removeSuccessCallback?: any, }) => { return ( <div className="sequences-edit-form"> <Components.WrappedSmartForm collection={Sequences} documentId={documentId} successCallback={successCallback} cancelCallback={cancelCallback} removeSuccessCallback={removeSuccessCallback} showRemove={true} queryFragment={getFragment('SequencesEdit')} mutationFragment={getFragment('SequencesEdit')} /> </div> ) } const SequencesEditFormComponent = registerComponent('SequencesEditForm', SequencesEditForm); declare global { interface ComponentTypes { SequencesEditForm: typeof SequencesEditFormComponent } }
mit
dndtools2/dndtools2
manage.py
252
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dndtools2.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
mit
derantell/VersionTools
test/VersionTools.Lib.Test/Properties/AssemblyInfo.cs
1370
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("VersionTools.Lib.Test")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("VersionTools.Lib.Test")] [assembly: AssemblyCopyright("Copyright © 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("6aaa6917-ad60-43d4-8a4c-a5bc045cb882")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")]
mit
DanielMoraCSG/gramplatzi
app/src/androidTest/java/com/csgroup_platzigram2/mora/platzigramv2/ExampleInstrumentedTest.java
786
package com.csgroup_platzigram2.mora.platzigramv2; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumentation test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() throws Exception { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.csgroup_platzigram2.mora.platzigramv2", appContext.getPackageName()); } }
mit
dualspiral/Hammer
HammerCore/src/main/java/uk/co/drnaylor/minecraft/hammer/core/commands/enums/ReloadFlagEnum.java
1539
/* * This file is part of Hammer, licensed under the MIT License (MIT). * * Copyright (c) 2015 Daniel Naylor * Copyright (c) contributors * * 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 uk.co.drnaylor.minecraft.hammer.core.commands.enums; import com.google.common.collect.Sets; import java.util.Set; public enum ReloadFlagEnum implements FlagEnum { RELOAD_DATABASE { @Override public Set<Character> getStrings() { return Sets.newHashSet('d'); } } }
mit
Alex7Kom/alleluia
lib/pipes/loadPages.js
1529
var fs = require('fs'); var path = require('path'); var wrench = require('wrench'); var defaultPath = 'pages'; module.exports = function (lastResult, pipe, config, filters, callback) { var pagesPath = pipe.path || defaultPath; var pagesFilenames; try { pagesFilenames = wrench .readdirSyncRecursive(path.join(config.projectDir, pagesPath)) .filter(function (filename) { return !(/^(_|\.)/.test(filename) || /\/(_|\.)/.test(filename)) && /\.(html|md|markdown)$/.test(filename); }); } catch(e) { console.error('Error: Unable to load pages'); process.exit(1); } var pages = pagesFilenames.map(function (filename) { var contents; try { contents = fs .readFileSync(path.join(config.projectDir, pagesPath, filename), 'utf8') .split('---'); } catch (e) { console.error('Error: Unable to load the page \'' + filename + '\''); process.exit(1); } var page; try { page = JSON.parse(contents[0].trim()); } catch (e) { console.error('Error: Invalid meta of the page \'' + filename + '\''); process.exit(1); } page.content = contents[1].trim(); page.filePath = filename; var dirname = path.dirname(filename); page.path = (dirname === '.') ? '' : dirname; page.filename = path.basename(filename); return page; }).filter(function (page) { if (!page.status || page.status === 'draft'){ return false; } return true; }); return callback(null, pages); };
mit
ScaleRunner/PacmanAI
6 - Contest/capture.py
30006
# capture.py # ---------- # Licensing Information: Please do not distribute or publish solutions to this # project. You are free to use and extend these projects for educational # purposes. The Pacman AI projects were developed at UC Berkeley, primarily by # John DeNero ([email protected]) and Dan Klein ([email protected]). # For more info, see http://inst.eecs.berkeley.edu/~cs188/sp09/pacman.html """ Capture.py holds the logic for Pacman capture the flag. (i) Your interface to the pacman world: Pacman is a complex environment. You probably don't want to read through all of the code we wrote to make the game runs correctly. This section contains the parts of the code that you will need to understand in order to complete the project. There is also some code in game.py that you should understand. (ii) The hidden secrets of pacman: This section contains all of the logic code that the pacman environment uses to decide who can move where, who dies when things collide, etc. You shouldn't need to read this section of code, but you can if you want. (iii) Framework to start a game: The final section contains the code for reading the command you use to set up the game, then starting up a new game, along with linking in all the external parts (agent functions, graphics). Check this section out to see all the options available to you. To play your first game, type 'python capture.py' from the command line. The keys are P1: 'a', 's', 'd', and 'w' to move P2: 'l', ';', ',' and 'p' to move """ from game import GameStateData from game import Game from game import Directions from game import Actions from util import nearestPoint from util import manhattanDistance from game import Grid from game import Configuration from game import Agent from game import reconstituteGrid import sys, util, types, time, random # If you change these, you won't affect the server, so you can't cheat KILL_POINTS = 0 SONAR_NOISE_RANGE = 13 # Must be odd SONAR_NOISE_VALUES = [i - (SONAR_NOISE_RANGE - 1)/2 for i in range(SONAR_NOISE_RANGE)] SIGHT_RANGE = 5 # Manhattan distance MIN_FOOD = 2 SCARED_TIME = 40 def noisyDistance(pos1, pos2): return int(util.manhattanDistance(pos1, pos2) + random.choice(SONAR_NOISE_VALUES)) ################################################### # YOUR INTERFACE TO THE PACMAN WORLD: A GameState # ################################################### class GameState: """ A GameState specifies the full game state, including the food, capsules, agent configurations and score changes. GameStates are used by the Game object to capture the actual state of the game and can be used by agents to reason about the game. Much of the information in a GameState is stored in a GameStateData object. We strongly suggest that you access that data via the accessor methods below rather than referring to the GameStateData object directly. """ #################################################### # Accessor methods: use these to access state data # #################################################### def getLegalActions( self, agentIndex=0 ): """ Returns the legal actions for the agent specified. """ return AgentRules.getLegalActions( self, agentIndex ) def generateSuccessor( self, agentIndex, action): """ Returns the successor state (a GameState object) after the specified agent takes the action. """ # Copy current state state = GameState(self) # Find appropriate rules for the agent AgentRules.applyAction( state, action, agentIndex ) AgentRules.checkDeath(state, agentIndex) AgentRules.decrementTimer(state.data.agentStates[agentIndex]) # Book keeping state.data._agentMoved = agentIndex state.data.score += state.data.scoreChange return state def getAgentState(self, index): return self.data.agentStates[index] def getAgentPosition(self, index): """ Returns a location tuple if the agent with the given index is observable; if the agent is unobservable, returns None. """ agentState = self.data.agentStates[index] return agentState.getPosition() def getNumAgents( self ): return len( self.data.agentStates ) def getScore( self ): """ Returns a number corresponding to the current score. """ return self.data.score def getRedFood(self): """ Returns a matrix of food that corresponds to the food on the red team's side. For the matrix m, m[x][y]=true if there is food in (x,y) that belongs to red (meaning red is protecting it, blue is trying to eat it). """ return halfGrid(self.data.food, red = True) def getBlueFood(self): """ Returns a matrix of food that corresponds to the food on the blue team's side. For the matrix m, m[x][y]=true if there is food in (x,y) that belongs to blue (meaning blue is protecting it, red is trying to eat it). """ return halfGrid(self.data.food, red = False) def getRedCapsules(self): return halfList(self.data.capsules, self.data.food, red = True) def getBlueCapsules(self): return halfList(self.data.capsules, self.data.food, red = False) def getWalls(self): """ Just like getFood but for walls """ return self.data.layout.walls def hasFood(self, x, y): """ Returns true if the location (x,y) has food, regardless of whether it's blue team food or red team food. """ return self.data.food[x][y] def hasWall(self, x, y): """ Returns true if (x,y) has a wall, false otherwise. """ return self.data.layout.walls[x][y] def isOver( self ): return self.data._win def getRedTeamIndices(self): """ Returns a list of agent index numbers for the agents on the red team. """ return self.redTeam[:] def getBlueTeamIndices(self): """ Returns a list of the agent index numbers for the agents on the blue team. """ return self.blueTeam[:] def isOnRedTeam(self, agentIndex): """ Returns true if the agent with the given agentIndex is on the red team. """ return self.teams[agentIndex] def getAgentDistances(self): """ Returns a noisy distance to each agent. """ if 'agentDistances' in dir(self) : return self.agentDistances else: return None def getDistanceProb(self, trueDistance, noisyDistance): "Returns the probability of a noisy distance given the true distance" if noisyDistance - trueDistance in SONAR_NOISE_VALUES: return 1.0/SONAR_NOISE_RANGE else: return 0 def getInitialAgentPosition(self, agentIndex): "Returns the initial position of an agent." return self.data.layout.agentPositions[agentIndex][1] def getCapsules(self): """ Returns a list of positions (x,y) of the remaining capsules. """ return self.data.capsules ############################################# # Helper methods: # # You shouldn't need to call these directly # ############################################# def __init__( self, prevState = None ): """ Generates a new state by copying information from its predecessor. """ if prevState != None: # Initial state self.data = GameStateData(prevState.data) self.blueTeam = prevState.blueTeam self.redTeam = prevState.redTeam self.teams = prevState.teams self.agentDistances = prevState.agentDistances else: self.data = GameStateData() self.agentDistances = [] def deepCopy( self ): state = GameState( self ) state.data = self.data.deepCopy() state.blueTeam = self.blueTeam[:] state.redTeam = self.redTeam[:] state.teams = self.teams[:] state.agentDistances = self.agentDistances[:] return state def makeObservation(self, index): state = self.deepCopy() # Adds the sonar signal pos = state.getAgentPosition(index) n = state.getNumAgents() distances = [noisyDistance(pos, state.getAgentPosition(i)) for i in range(n)] state.agentDistances = distances # Remove states of distant opponents if index in self.blueTeam: team = self.blueTeam otherTeam = self.redTeam else: otherTeam = self.blueTeam team = self.redTeam for enemy in otherTeam: seen = False enemyPos = state.getAgentPosition(enemy) for teammate in team: if util.manhattanDistance(enemyPos, state.getAgentPosition(teammate)) <= SIGHT_RANGE: seen = True if not seen: state.data.agentStates[enemy].configuration = None return state def __eq__( self, other ): """ Allows two states to be compared. """ if other == None: return False return self.data == other.data def __hash__( self ): """ Allows states to be keys of dictionaries. """ return int(hash( self.data )) def __str__( self ): return str(self.data) def initialize( self, layout, numAgents): """ Creates an initial game state from a layout array (see layout.py). """ self.data.initialize(layout, numAgents) positions = [a.configuration for a in self.data.agentStates] self.blueTeam = [i for i,p in enumerate(positions) if not self.isRed(p)] self.redTeam = [i for i,p in enumerate(positions) if self.isRed(p)] self.teams = [self.isRed(p) for p in positions] def isRed(self, configOrPos): width = self.data.layout.width if type(configOrPos) == type( (0,0) ): return configOrPos[0] < width / 2 else: return configOrPos.pos[0] < width / 2 def halfGrid(grid, red): halfway = grid.width / 2 halfgrid = Grid(grid.width, grid.height, False) if red: xrange = list(range(halfway)) else: xrange = list(range(halfway, grid.width)) for y in range(grid.height): for x in xrange: if grid[x][y]: halfgrid[x][y] = True return halfgrid def halfList(l, grid, red): halfway = grid.width / 2 newList = [] for x,y in l: if red and x <= halfway: newList.append((x,y)) elif not red and x > halfway: newList.append((x,y)) return newList ############################################################################ # THE HIDDEN SECRETS OF PACMAN # # # # You shouldn't need to look through the code in this section of the file. # ############################################################################ COLLISION_TOLERANCE = 0.7 # How close ghosts must be to Pacman to kill class CaptureRules: """ These game rules manage the control flow of a game, deciding when and how the game starts and ends. """ def __init__(self, quiet = False): self.quiet = quiet def newGame( self, layout, agents, display, length, muteAgents, catchExceptions ): initState = GameState() initState.initialize( layout, len(agents) ) starter = random.randint(0,1) print(('%s team starts' % ['Red', 'Blue'][starter])) game = Game(agents, display, self, startingIndex=starter, muteAgents=muteAgents, catchExceptions=catchExceptions) game.state = initState game.length = length if 'drawCenterLine' in dir(display): display.drawCenterLine() self._initBlueFood = initState.getBlueFood().count() self._initRedFood = initState.getRedFood().count() return game def process(self, state, game): """ Checks to see whether it is time to end the game. """ if 'moveHistory' in dir(game): if len(game.moveHistory) == game.length: state.data._win = True if state.isOver(): game.gameOver = True if not game.rules.quiet: if state.getRedFood().count() == MIN_FOOD: print(('The Blue team has captured all but %d of the opponents\' dots.' % MIN_FOOD)) if state.getBlueFood().count() == MIN_FOOD: print(('The Red team has captured all but %d of the opponents\' dots.' % MIN_FOOD)) if state.getBlueFood().count() > MIN_FOOD and state.getRedFood().count() > MIN_FOOD: print('Time is up.') if state.data.score == 0: print('Tie game!') else: winner = 'Red' if state.data.score < 0: winner = 'Blue' print(('The %s team wins by %d points.' % (winner, abs(state.data.score)))) def getProgress(self, game): blue = 1.0 - (game.state.getBlueFood().count() / float(self._initBlueFood)) red = 1.0 - (game.state.getRedFood().count() / float(self._initRedFood)) moves = len(self.moveHistory) / float(game.length) # return the most likely progress indicator, clamped to [0, 1] return min(max(0.75 * max(red, blue) + 0.25 * moves, 0.0), 1.0) def agentCrash(self, game, agentIndex): if agentIndex % 2 == 0: print("Red agent crashed") game.state.data.score = -1 else: print("Blue agent crashed") game.state.data.score = 1 def getMaxTotalTime(self, agentIndex): return 900 # Move limits should prevent this from ever happening def getMaxStartupTime(self, agentIndex): return 15 # 15 seconds for registerInitialState def getMoveWarningTime(self, agentIndex): return 1 # One second per move def getMoveTimeout(self, agentIndex): return 3 # Three seconds results in instant forfeit def getMaxTimeWarnings(self, agentIndex): return 2 # Third violation loses the game class AgentRules: """ These functions govern how each agent interacts with her environment. """ def getLegalActions( state, agentIndex ): """ Returns a list of legal actions (which are both possible & allowed) """ agentState = state.getAgentState(agentIndex) conf = agentState.configuration possibleActions = Actions.getPossibleActions( conf, state.data.layout.walls ) return AgentRules.filterForAllowedActions( agentState, possibleActions) getLegalActions = staticmethod( getLegalActions ) def filterForAllowedActions(agentState, possibleActions): return possibleActions filterForAllowedActions = staticmethod( filterForAllowedActions ) def applyAction( state, action, agentIndex ): """ Edits the state to reflect the results of the action. """ legal = AgentRules.getLegalActions( state, agentIndex ) if action not in legal: raise Exception("Illegal action " + str(action)) # Update Configuration agentState = state.data.agentStates[agentIndex] speed = 1.0 # if agentState.isPacman: speed = 0.5 vector = Actions.directionToVector( action, speed ) oldConfig = agentState.configuration agentState.configuration = oldConfig.generateSuccessor( vector ) # Eat next = agentState.configuration.getPosition() nearest = nearestPoint( next ) if agentState.isPacman and manhattanDistance( nearest, next ) <= 0.9 : AgentRules.consume( nearest, state, state.isOnRedTeam(agentIndex) ) # Change agent type if next == nearest: agentState.isPacman = [state.isOnRedTeam(agentIndex), state.isRed(agentState.configuration)].count(True) == 1 applyAction = staticmethod( applyAction ) def consume( position, state, isRed ): x,y = position # Eat food if state.data.food[x][y]: score = -1 if isRed: score = 1 state.data.scoreChange += score state.data.food = state.data.food.copy() state.data.food[x][y] = False state.data._foodEaten = position if (isRed and state.getBlueFood().count() == MIN_FOOD) or (not isRed and state.getRedFood().count() == MIN_FOOD): state.data._win = True # Eat capsule if isRed: myCapsules = state.getBlueCapsules() else: myCapsules = state.getRedCapsules() if( position in myCapsules ): state.data.capsules.remove( position ) state.data._capsuleEaten = position # Reset all ghosts' scared timers if isRed: otherTeam = state.getBlueTeamIndices() else: otherTeam = state.getRedTeamIndices() for index in otherTeam: state.data.agentStates[index].scaredTimer = SCARED_TIME consume = staticmethod( consume ) def decrementTimer(state): timer = state.scaredTimer if timer == 1: state.configuration.pos = nearestPoint( state.configuration.pos ) state.scaredTimer = max( 0, timer - 1 ) decrementTimer = staticmethod( decrementTimer ) def checkDeath( state, agentIndex): agentState = state.data.agentStates[agentIndex] if state.isOnRedTeam(agentIndex): otherTeam = state.getBlueTeamIndices() else: otherTeam = state.getRedTeamIndices() if agentState.isPacman: for index in otherTeam: otherAgentState = state.data.agentStates[index] if otherAgentState.isPacman: continue ghostPosition = otherAgentState.getPosition() if ghostPosition == None: continue if manhattanDistance( ghostPosition, agentState.getPosition() ) <= COLLISION_TOLERANCE: #award points to the other team for killing Pacmen if otherAgentState.scaredTimer <= 0: score = KILL_POINTS if state.isOnRedTeam(agentIndex): score = -score state.data.scoreChange += score agentState.isPacman = False agentState.configuration = agentState.start agentState.scaredTimer = 0 else: score = KILL_POINTS if state.isOnRedTeam(agentIndex): score = -score state.data.scoreChange += score otherAgentState.isPacman = False otherAgentState.configuration = otherAgentState.start otherAgentState.scaredTimer = 0 else: # Agent is a ghost for index in otherTeam: otherAgentState = state.data.agentStates[index] if not otherAgentState.isPacman: continue pacPos = otherAgentState.getPosition() if pacPos == None: continue if manhattanDistance( pacPos, agentState.getPosition() ) <= COLLISION_TOLERANCE: #award points to the other team for killing Pacmen if agentState.scaredTimer <= 0: score = KILL_POINTS if not state.isOnRedTeam(agentIndex): score = -score state.data.scoreChange += score otherAgentState.isPacman = False otherAgentState.configuration = otherAgentState.start otherAgentState.scaredTimer = 0 else: score = KILL_POINTS if state.isOnRedTeam(agentIndex): score = -score state.data.scoreChange += score agentState.isPacman = False agentState.configuration = agentState.start agentState.scaredTimer = 0 checkDeath = staticmethod( checkDeath ) def placeGhost(state, ghostState): ghostState.configuration = ghostState.start placeGhost = staticmethod( placeGhost ) ############################# # FRAMEWORK TO START A GAME # ############################# def default(str): return str + ' [Default: %default]' def parseAgentArgs(str): if str == None or str == '': return {} pieces = str.split(',') opts = {} for p in pieces: if '=' in p: key, val = p.split('=') else: key,val = p, 1 opts[key] = val return opts def readCommand( argv ): """ Processes the command used to run pacman from the command line. """ from optparse import OptionParser usageStr = """ USAGE: python pacman.py <options> EXAMPLES: (1) python capture.py - starts an interactive game against two offensive agents (you control the red agent with the arrow keys) (2) python capture.py --player2 KeyboardAgent2 - starts a two-player interactive game with w,a,s,d & i,j,k,l keys (3) python capture.py --player2 DefensiveReflexAgent - starts a fully automated game """ parser = OptionParser(usageStr) parser.add_option('-r', '--red', help=default('Red team'), default='BaselineAgents') parser.add_option('-b', '--blue', help=default('Blue team'), default='BaselineAgents') parser.add_option('--redOpts', help=default('Options for red team (e.g. first=keys)'), default='') parser.add_option('--blueOpts', help=default('Options for blue team (e.g. first=keys)'), default='') parser.add_option('-l', '--layout', dest='layout', help=default('the LAYOUT_FILE from which to load the map layout; use RANDOM for a random maze'), metavar='LAYOUT_FILE', default='defaultCapture') parser.add_option('-t', '--textgraphics', action='store_true', dest='textgraphics', help='Display output as text only', default=False) parser.add_option('-q', '--quiet', action='store_true', help='Display minimal output and no graphics', default=False) parser.add_option('-Q', '--super-quiet', action='store_true', dest="super_quiet", help='Same as -q but agent output is also suppressed', default=False) parser.add_option('-k', '--numPlayers', type='int', dest='numPlayers', help=default('The maximum number of players'), default=4) parser.add_option('-z', '--zoom', type='float', dest='zoom', help=default('Zoom in the graphics'), default=1) parser.add_option('-i', '--time', type='int', dest='time', help=default('TIME limit of a game in moves'), default=3000, metavar='TIME') parser.add_option('-n', '--numGames', type='int', help=default('Number of games to play'), default=1) parser.add_option('-f', '--fixRandomSeed', action='store_true', help='Fixes the random seed to always play the same game', default=False) parser.add_option('--record', action='store_true', help='Writes game histories to a file (named by the time they were played)', default=False) parser.add_option('--replay', default=None, help='Replays a recorded game file.') parser.add_option('-x', '--numTraining', dest='numTraining', type='int', help=default('How many episodes are training (suppresses output)'), default=0) parser.add_option('-c', '--catchExceptions', action='store_true', default=False, help='Catch exceptions and enforce time limits') options, otherjunk = parser.parse_args(argv) assert len(otherjunk) == 0, "Unrecognized options: " + str(otherjunk) args = dict() # Choose a display format #if options.pygame: # import pygameDisplay # args['display'] = pygameDisplay.PacmanGraphics() if options.textgraphics: import textDisplay args['display'] = textDisplay.PacmanGraphics() elif options.quiet: import textDisplay args['display'] = textDisplay.NullGraphics() elif options.super_quiet: import textDisplay args['display'] = textDisplay.NullGraphics() args['muteAgents'] = True else: import graphicsDisplay graphicsDisplay.FRAME_TIME = 0 args['display'] = graphicsDisplay.PacmanGraphics(options.zoom, 0, capture=True) if options.fixRandomSeed: random.seed('cs188') # Special case: recorded games don't use the runGames method or args structure if options.replay != None: print(('Replaying recorded game %s.' % options.replay)) import pickle recorded = pickle.load(open(options.replay)) recorded['display'] = args['display'] replayGame(**recorded) sys.exit(0) # Choose a pacman agent redArgs, blueArgs = parseAgentArgs(options.redOpts), parseAgentArgs(options.blueOpts) if options.numTraining > 0: redArgs['numTraining'] = options.numTraining blueArgs['numTraining'] = options.numTraining nokeyboard = options.textgraphics or options.quiet or options.numTraining > 0 print(('\nRed team %s with %s:' % (options.red, redArgs))) redAgents = loadAgents(True, options.red, nokeyboard, redArgs) print(('\nBlue team %s with %s:' % (options.blue, blueArgs))) blueAgents = loadAgents(False, options.blue, nokeyboard, blueArgs) args['agents'] = sum([list(el) for el in zip(redAgents, blueAgents)],[]) # list of agents # Choose a layout if options.layout == 'RANDOM': options.layout = randomLayout() if options.layout.lower().find('capture') == -1: raise Exception( 'You must use a capture layout with capture.py') import layout args['layout'] = layout.getLayout( options.layout ) if args['layout'] == None: raise Exception("The layout " + options.layout + " cannot be found") args['agents'] = args['agents'][:min(args['layout'].getNumGhosts(), options.numPlayers)] args['length'] = options.time args['numGames'] = options.numGames args['numTraining'] = options.numTraining args['record'] = options.record args['catchExceptions'] = options.catchExceptions return args def randomLayout(): layout = 'layouts/random%08dCapture.lay' % random.randint(0,99999999) print(('Generating random layout in %s' % layout)) import mazeGenerator out = file(layout, 'w') out.write(mazeGenerator.generateMaze()) out.close() return layout import traceback def loadAgents(isRed, factory, textgraphics, cmdLineArgs): "Calls agent factories and returns lists of agents" # Looks through all pythonPath Directories for the right module import os dirname = 'teams/' sys.path.append(os.path.join(sys.path[0], 'teams')) try: conf = __import__(factory + ".config", fromlist="config") except ImportError: print(('Error: The team "' + factory + '" config could not be loaded! ')) traceback.print_exc() return [None for i in range(3)] factory = factory + "." + conf.AgentFactory args = dict(conf.AgentArgs) args.update(cmdLineArgs) # Add command line args with priority print(("Loading Team:", conf.TeamName)) print(("Arguments:", args)) print(("Partners:", conf.Partners)) print(("Agent Factory:", factory)) factoryClassName = factory.split(".")[-1] factoryPackageName = ".".join(factory.split(".")[:-1]) if factoryPackageName == "": factoryPackageName,factoryClassName=factoryClassName,factoryPackageName # if textgraphics and factoryClassName.startswith('Keyboard'): # raise Exception('Using the keyboard requires graphics (no text display, quiet or training games)') print(("Namespace: ", factoryPackageName)) print(("Agent: ", factoryClassName)) try: module = __import__(factoryPackageName, fromlist=factoryClassName) except ImportError as data: module = None foundFactory = getattr(module, factoryClassName, None) if not module or not foundFactory: print(('Error: The team "' + factory + '" could not be loaded! ')) traceback.print_exc() return [None for i in range(3)] foundFactory = foundFactory(isRed=isRed, **args) indexAddend = 0 if not isRed: indexAddend = 1 indices = [2*i + indexAddend for i in range(3)] return [foundFactory.getAgent(i) for i in indices] def replayGame( layout, agents, actions, display, length ): rules = CaptureRules() game = rules.newGame( layout, agents, display, length, False, False ) state = game.state display.initialize(state.data) for action in actions: # Execute the action state = state.generateSuccessor( *action ) # Change the display display.update( state.data ) # Allow for game specific conditions (winning, losing, etc.) rules.process(state, game) display.finish() def runGames( layout, agents, display, length, numGames, record, numTraining, muteAgents=False, catchExceptions=False ): # Hack for agents writing to the display import __main__ __main__.__dict__['_display'] = display rules = CaptureRules() games = [] if numTraining > 0: print(('Playing %d training games' % numTraining)) for i in range( numGames ): beQuiet = i < numTraining if beQuiet: # Suppress output and graphics import textDisplay gameDisplay = textDisplay.NullGraphics() rules.quiet = True else: gameDisplay = display rules.quiet = False g = rules.newGame( layout, agents, gameDisplay, length, muteAgents, catchExceptions ) g.run() if not beQuiet: games.append(g) g.record = None if record: import time, pickle, game #fname = ('recorded-game-%d' % (i + 1)) + '-'.join([str(t) for t in time.localtime()[1:6]]) #f = file(fname, 'w') components = {'layout': layout, 'agents': [game.Agent() for a in agents], 'actions': g.moveHistory, 'length': length} #f.close() print("recorded") g.record = pickle.dumps(components) if numGames > 1: scores = [game.state.data.score for game in games] redWinRate = [s > 0 for s in scores].count(True)/ float(len(scores)) blueWinRate = [s < 0 for s in scores].count(True)/ float(len(scores)) print(('Average Score:', sum(scores) / float(len(scores)))) print(('Scores: ', ', '.join([str(score) for score in scores]))) print(('Red Win Rate: %d/%d (%.2f)' % ([s > 0 for s in scores].count(True), len(scores), redWinRate))) print(('Blue Win Rate: %d/%d (%.2f)' % ([s < 0 for s in scores].count(True), len(scores), blueWinRate))) print(('Record: ', ', '.join([('Blue', 'Tie', 'Red')[max(0, min(2, 1 + s))] for s in scores]))) return games if __name__ == '__main__': """ The main function called when pacman.py is run from the command line: > python capture.py See the usage string for more details. > python capture.py --help """ options = readCommand( sys.argv[1:] ) # Get game components based on input runGames(**options) # import cProfile # cProfile.run('runGames( **options )', 'profile')
mit
CruGlobal/godtools-api
src/main/java/org/cru/godtools/domain/packages/PackageStructure.java
4585
package org.cru.godtools.domain.packages; import com.google.common.collect.Maps; import org.ccci.util.xml.XmlDocumentSearchUtilities; import org.cru.godtools.domain.GuavaHashGenerator; import org.cru.godtools.domain.images.Image; import org.jboss.logging.Logger; import org.w3c.dom.Document; import org.w3c.dom.Element; import java.io.Serializable; import java.util.List; import java.util.Map; import java.util.UUID; /** * Created by ryancarlson on 4/30/14. */ public class PackageStructure implements Serializable { private UUID id; private UUID packageId; private Integer versionNumber; private Document xmlContent; private String filename; private final Map<String,String> filenameMap = Maps.newHashMap(); private final Logger logger = Logger.getLogger(PackageStructure.class); public void setTranslatedFields(Map<UUID, TranslationElement> translationElementMap) { for(Element translatableElement : XmlDocumentSearchUtilities.findElementsWithAttribute(getXmlContent(), "gtapi-trx-id")) { try { UUID translationElementId = UUID.fromString(translatableElement.getAttribute("gtapi-trx-id")); if (translationElementMap.containsKey(translationElementId)) { String translatedText = translationElementMap.get(translationElementId).getTranslatedText(); String elementType = translatableElement.getTagName(); logger.debug(String.format("Setting translation element: %s with ID: %s to value: %s", elementType, translationElementId.toString(), translatedText)); translatableElement.setTextContent(translatedText); } } catch(IllegalArgumentException e) { logger.warn("Invalid UUID... oh well. Move along"); } } } public void replacePageNamesWithPageHashes(Map<String, PageStructure> pageStructures) { for(Element pageElement : XmlDocumentSearchUtilities.findElements(getXmlContent(), "page")) { String filenameFromXml = pageElement.getAttribute("filename"); String uuidFilename = pageStructures.get(filenameFromXml).getId() + ".xml"; pageElement.setAttribute("filename", uuidFilename); filenameMap.put(uuidFilename, filenameFromXml); } for(Element pageElement : XmlDocumentSearchUtilities.findElements(getXmlContent(), "about")) { String filenameFromXml = pageElement.getAttribute("filename"); String uuidFilename = pageStructures.get(filenameFromXml).getId() + ".xml"; pageElement.setAttribute("filename", pageStructures.get(filenameFromXml).getId() + ".xml"); filenameMap.put(uuidFilename, filenameFromXml); } } public void replaceImageNamesWithImageHashes(Map<String, Image> images) { for(Element pageElement : XmlDocumentSearchUtilities.findElementsWithAttribute(getXmlContent(), "page", "thumb")) { try { String filenameFromXml = pageElement.getAttribute("thumb"); pageElement.setAttribute("thumb", GuavaHashGenerator.calculateHash(images.get(filenameFromXml).getImageContent()) + ".png"); } catch (NullPointerException npe) { //missing image, life goes on... } } for(Element pageElement : XmlDocumentSearchUtilities.findElementsWithAttribute(getXmlContent(), "about", "thumb")) { try { String filenameFromXml = pageElement.getAttribute("thumb"); pageElement.setAttribute("thumb", GuavaHashGenerator.calculateHash(images.get(filenameFromXml).getImageContent()) + ".png"); } catch(NullPointerException npe) { //missing image, life goes on... } } } public String getPackageName() { if(xmlContent == null) return ""; List<Element> packageNameElements = XmlDocumentSearchUtilities.findElements(xmlContent, "packagename"); if(packageNameElements.size() != 1) throw new IllegalStateException("Expected one packagename element"); return packageNameElements.get(0).getTextContent(); } public String getOriginalFilenameForUUIDFilename(String uuidFilename) { return filenameMap.get(uuidFilename); } public UUID getId() { return id; } public void setId(UUID id) { this.id = id; } public UUID getPackageId() { return packageId; } public void setPackageId(UUID packageId) { this.packageId = packageId; } public Integer getVersionNumber() { return versionNumber; } public void setVersionNumber(Integer versionNumber) { this.versionNumber = versionNumber; } public Document getXmlContent() { return xmlContent; } public void setXmlContent(Document xmlContent) { this.xmlContent = xmlContent; } public String getFilename() { return filename; } public void setFilename(String filename) { this.filename = filename; } }
mit
FMCalisto/ttt-web-service-noughts-crosses-game-2
ttt-local/src/main/java/ttt/TTT.java
1838
package ttt; public class TTT { char board[][] = { { '1', '2', '3' }, /* Initial values are reference numbers */ { '4', '5', '6' }, /* used to select a vacant square for */ { '7', '8', '9' } /* a turn. */ }; int nextPlayer = 0; int numPlays = 0; public String currentBoard() { String s = "\n\n " + board[0][0] + " | " + board[0][1] + " | " + board[0][2] + " " + "\n---+---+---\n " + board[1][0] + " | " + board[1][1] + " | " + board[1][2] + " " + "\n---+---+---\n " + board[2][0] + " | " + board[2][1] + " | " + board[2][2] + " \n"; return s; } public boolean play(int row, int column, int player) { if (!(row >= 0 && row < 3 && column >= 0 && column < 3)) return false; if (board[row][column] > '9') return false; if (player != nextPlayer) return false; if (numPlays == 9) return false; board[row][column] = (player == 1) ? 'X' : 'O'; /* Insert player symbol */ nextPlayer = (nextPlayer + 1) % 2; numPlays++; return true; } public int checkWinner() { int i; /* Check for a winning line - diagonals first */ if ((board[0][0] == board[1][1] && board[0][0] == board[2][2]) || (board[0][2] == board[1][1] && board[0][2] == board[2][0])) { if (board[1][1] == 'X') return 1; else return 0; } else /* Check rows and columns for a winning line */ for (i = 0; i <= 2; i++) { if ((board[i][0] == board[i][1] && board[i][0] == board[i][2])) { if (board[i][0] == 'X') return 1; else return 0; } if ((board[0][i] == board[1][i] && board[0][i] == board[2][i])) { if (board[0][i] == 'X') return 1; else return 0; } } if (numPlays == 9) return 2; /* A draw! */ else return -1; /* Game is not over yet */ } }
mit
dklisiaris/metaspider
lib/metaspider/base.rb
1611
#!/bin/env ruby # encoding: utf-8 require 'rubygems' require 'open-uri' require 'nokogiri' class Base attr_reader :url, :page def initialize(url=nil) load_page(url) end # Downloads a page from the web. # # ==== Attributes # # * +url+ - The url of webpage to download. # def load_page(url=nil) begin @url = url puts "Downloading page: #{url}" open(url, :content_length_proc => lambda do |content_length| raise EmptyPageError.new(url, content_length) unless content_length.nil? or content_length > 1024 end) do |f| @page = f.read.gsub(/\s+/, " ") end rescue Errno::ENOENT => e puts "Page: #{url} NOT FOUND." puts e rescue EmptyPageError => e puts "Page: #{url} is EMPTY." puts e @page = nil rescue OpenURI::HTTPError => e puts e puts e.io.status rescue StandardError => e puts "Generic error #{e.class}. Will wait for 2 minutes and then try again." puts e sleep(120) retry end if present?(url) and url.match(/\A#{URI::regexp(['http', 'https'])}\z/) end def def present?(value) return (not value.nil? and not value.empty?) ? true : false end end # Raised when a page is considered empty. # class EmptyPageError < StandardError attr_reader :url, :content_length def initialize(url, content_length) @url = url @content_length = content_length msg = "Page: #{url} is only #{content_length} bytes, so it is considered EMPTY." super(msg) end end
mit
nullstyle/ruby-satisfaction
lib/satisfaction/product.rb
435
class Sfn::Product < Sfn::Resource attributes :name, :url, :image, :description attribute :last_active_at, :type => Time attribute :created_at, :type => Time def path "/products/#{@id}" end def setup_associations has_many :topics, :url => "#{path}/topics" has_many :people, :url => "#{path}/people" has_many :companies, :url => "#{path}/companies" has_many :tags, :url => "#{path}/tags" end end
mit
delian1986/SoftUni-C-Sharp-repo
Programming Basics/02.Simple Calculations/02. LEKCIA Simple Calculations/03.next/Program.cs
233
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _03.next { class Program { static void Main(string[] args) { } } }
mit
weberamaral/cs-desafio-node
index.js
805
/** * Module dependencies. */ const App = require('./src/config/express'); const debug = require('debug')('cs-desafio-node:index'); const config = require('./src/config/config'); const models = require('./src/config/sequelize'); /** * Main application entry file. * Please note that the order of loading is important. */ debug('Starting cs-desafio-node server'); // module.parent check is required to support mocha watch // src: https://github.com/mochajs/mocha/issues/1912 if (!module.parent) { // eslint-disable-line no-lonely-if App.listen(config.port, () => { debug(`Server started on port ${config.port} and pid ${process.pid}`); }); models.sequelize.sync({ force: config.sequelize.forceDbSync }).then(() => { debug('Database connection Okay.'); }); } module.exports = App;
mit
JamisHoo/Yagra
cgi-bin/home.py
2196
#!/usr/bin/env python from __future__ import print_function from collections import namedtuple from common import config from common.response import text_response, populate_html, redirect import os import cgi import hashlib import MySQLdb import Cookie def process_input(): # Load email and password from cookie cookie = Cookie.SimpleCookie(os.environ.get("HTTP_COOKIE")) email = cookie["email"].value if "email" in cookie else None password = cookie["password"].value if "password" in cookie else None generate_output(email, password) def generate_output(email, password): if not email or not password: print(redirect("signin.py")) return db_connection = MySQLdb.connect( host=config.mysql_host, user=config.mysql_user, passwd=config.mysql_password, db=config.mysql_db) db_cursor = db_connection.cursor() UserInformation = namedtuple( "UserInformation", "email, email_hash, salt, password_hash, random_password_hash, rating") # Fetch user information from database db_cursor.execute("""SELECT email, email_hash, salt, passwd_hash, random_passwd_hash, rating FROM users WHERE email = %s""", (email,)) record = db_cursor.fetchone() # Could not find this user if not record: print("Location: signin.py") print() return user_info = UserInformation._make(record) input_password_hash = hashlib.sha256(user_info.salt + password).digest() # Wrong password if (input_password_hash != user_info.password_hash and input_password_hash != user_info.random_password_hash): print(redirect("signin.py")) return # add r=x query to display images in all ratings image_url = "{}?r=x".format(user_info.email_hash.encode("hex").upper()) rating = user_info.rating.upper() if user_info.rating else "G" message_body = populate_html( "home.html", dict(email=email, image_url=image_url, rating=rating)) print(text_response("text/html", message_body)) try: process_input() except: cgi.print_exception()
mit
RaRe-Technologies/bounter
bounter/count_min_sketch.py
8979
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Author: Filip Stefanak <[email protected]> # Copyright (C) 2017 Rare Technologies # # This code is distributed under the terms and conditions # from the MIT License (MIT). import bounter_cmsc as cmsc class CountMinSketch(object): """ Data structure used to estimate frequencies of elements in massive data sets with fixed memory footprint. Example:: >>> cms = CountMinSketch(size_mb=512) # Use 512 MB >>> print(cms.width) # 16 777 216 >>> print(cms.depth) # 8 >>> print(cms.size) # 536 870 912 (512 MB in bytes) >>> cms.increment("foo") >>> cms.increment("bar") >>> cms.increment("foo") >>> print(cms["foo"]) # 2 >>> print(cms["bar"]) # 1 >>> print(cms.cardinality()) # 2 >>> print(cms.total()) # 3 To calculate memory footprint: ( width * depth * cell_size ) + HLL size Cell size is - 4B for default counting - 2B for log1024 counting - 1B for log8 counting HLL size is 64 KB Memory usage example: width 2^25 (33 554 432), depth 8, log1024 (2B) has 2^(25 + 3 + 1) + 64 KB = 512.06 MB Can be pickled to disk with this exact size How to choose parameters: Preferably, start with a high `size_mb` using default counting. After counting all elements of the set, check `cms.cardinality()` and check quality ratio with `quality()`. If this ratio is greater than 1, the table is likely to suffer small bias from collisions. As the ratio climbs over 5, the results are getting more and more biased. Therefore we recommend choosing a higher size (if possible) or switching to log1024 counting which can support twice the width with the same memory size (or log8 for quadruple). Both of these counters suffer from a different kind of bias but that tends to be less severe than the collision bias with a high quality ratio. If you can achieve the quality ratio below 1 with the default counting, we do not recommend using the log counting as the collision bias will already be minimal. """ def __init__(self, size_mb=64, width=None, depth=None, log_counting=None): """ Initialize the Count-Min Sketch structure with the given parameters Args: size_mb (int): controls the maximum size of the Count-min Sketch table. If both width and depth is provided, this parameter is ignored. Please note that the structure will use an overhead of approximately 65 KB in addition to the table size. depth (int): controls the number of rows of the table. Having more rows decreases probability of a big overestimation but also linearly affects performance and table size. Choose a small number such as 6-10. The algorithm will default depth 8 if width is provided. Otherwise, it will choose a depth in range 8-15 to best fill the maximum memory (for memory size which is a power of 2, depth of 8 is always used). width (int): controls the number of hash buckets in one row of the table. If width is not provided, the algorithm chooses the maximum width to fill the available size. The more, the better, should be very large, preferably in the same order of magnitude as the cardinality of the counted set. log_counting (int): Use logarithmic approximate counter value for reduced bucket size: - None (default): 4B, no counter error - 1024: 2B, value approximation error ~2% for values larger than 2048 - 8: 1B, value approximation error ~30% for values larger than 16 """ cell_size = CountMinSketch.cell_size(log_counting) self.cell_size_v = cell_size if size_mb is None or not isinstance(size_mb, int): raise ValueError("size_mb must be an integer representing the maximum size of the structure in MB") if width is None and depth is None: self.width = 1 << (size_mb * (2 ** 20) // (cell_size * 8 * 2)).bit_length() self.depth = (size_mb * (2 ** 20)) // (self.width * cell_size) elif width is None: self.depth = depth avail_width = (size_mb * (2 ** 20)) // (depth * cell_size) self.width = 1 << (avail_width.bit_length() - 1) if not self.width: raise ValueError("Requested depth is too large for maximum memory size.") elif depth is None: if width != 1 << (width.bit_length() - 1): raise ValueError("Requested width must be a power of 2.") self.width = width self.depth = (size_mb * (2 ** 20)) // (width * cell_size) if not self.depth: raise ValueError("Requested width is too large for maximum memory size.") else: if width != 1 << (width.bit_length() - 1): raise ValueError("Requested width must be a power of 2.") self.width = width self.depth = depth if log_counting == 8: self.cms = cmsc.CMS_Log8(width=self.width, depth=self.depth) elif log_counting == 1024: self.cms = cmsc.CMS_Log1024(width=self.width, depth=self.depth) elif log_counting is None: self.cms = cmsc.CMS_Conservative(width=self.width, depth=self.depth) else: raise ValueError("Unsupported parameter log_counting=%s. Use None, 8, or 1024." % log_counting) # optimize calls by directly binding to C implementation self.increment = self.cms.increment @staticmethod def cell_size(log_counting=None): if log_counting == 8: return 1 if log_counting == 1024: return 2 return 4 @staticmethod def table_size(width, depth=4, log_counting=None): """ Return size of Count-min Sketch table with provided parameters in bytes. Does *not* include additional constant overhead used by parameter variables and HLL table, totalling less than 65KB. """ return width * depth * CountMinSketch.cell_size(log_counting) def __getitem__(self, key): return self.cms.get(key) def __contains__(self, item): return self.cms.get(item) def cardinality(self): """ Return an estimate for the number of distinct keys counted by the structure. The estimate should be within 1%. """ return self.cms.cardinality() def total(self): """ Return a precise total sum of all increments performed on this counter. The counter keeps the total in a separate variable so the number is accurate in all circumstances (i.e. even with high number of collisions or when a log algorithm is used. """ return self.cms.total() def merge(self, other): """ Merge another Count-min sketch structure into this one. The other structure must be initialized with the same width, depth and algorithm, and remains unaffected by this operation. Please note that merging two halves is always less accurate than counting the whole set with a single counter, because the merging algorithm can not leverage the conservative update optimization. """ self.cms.merge(other.cms) def update(self, iterable): if isinstance(iterable, CountMinSketch): self.merge(iterable) else: self.cms.update(iterable) def size(self): """ Return current size of the Count-min Sketch table in bytes. Does *not* include additional constant overhead used by parameter variables and HLL table, totalling less than 65KB. """ return self.width * self.depth * self.cell_size_v def quality(self): """ Return the current estimated overflow rating of the structure, calculated as cardinality / width. For quality < 1, the table should return results without collision bias. For quality rating up to 5, collision bias is small. For a larger quality rating, the structure suffers from a considerable collision bias affecting smaller values. """ return float(self.cardinality()) / self.width def __getstate__(self): return self.width, self.depth, self.cell_size_v, self.cms def __setstate__(self, state): self.width, self.depth, self.cell_size_v, self.cms = state self.increment = self.cms.increment class CardinalityEstimator(CountMinSketch): def __init__(self): super(CardinalityEstimator, self).__init__(width=1, depth=1) def __getitem__(self, key): raise NotImplementedError("Individual item counting is not supported for cardinality estimator!")
mit
WellCommerce/ReportBundle
Provider/AbstractReportProvider.php
1430
<?php /* * WellCommerce Open-Source E-Commerce Platform * * This file is part of the WellCommerce package. * * (c) Adam Piotrowski <[email protected]> * * For the full copyright and license information, * please view the LICENSE file that was distributed with this source code. */ namespace WellCommerce\Bundle\ReportBundle\Provider; use WellCommerce\Bundle\CoreBundle\DependencyInjection\AbstractContainerAware; use WellCommerce\Bundle\CoreBundle\Repository\RepositoryInterface; use WellCommerce\Bundle\OrderBundle\Entity\OrderInterface; /** * Class AbstractReportProvider * * @author Adam Piotrowski <[email protected]> */ abstract class AbstractReportProvider extends AbstractContainerAware { /** * @var RepositoryInterface */ protected $repository; /** * Constructor * * @param RepositoryInterface $repository */ public function __construct(RepositoryInterface $repository) { $this->repository = $repository; } /** * Converts the order's gross total to target currency * * @param OrderInterface $order * * @return float */ protected function convertAmount(OrderInterface $order) { $amount = $order->getSummary()->getGrossAmount(); $baseCurrency = $order->getCurrency(); return $this->getCurrencyHelper()->convert($amount, $baseCurrency); } }
mit
awebeer256/prog30493-1171_4655-spaceinvaders
Assets/Script/EnemyBulletLogic.cs
1337
using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnemyBulletLogic : MonoBehaviour { /* * This class is designed to destory the enemybullet when it collides with anything * will check to see if bullet hits: shields or Player * if shield - destory whichever cube was hit in the shield * if player - reduce live, respawn player */ public GameObject enemyBullet; void OnCollisionEnter(Collision collision){ if (collision.gameObject.GetComponent<IsAShield> () != null) { //destory one block per sheild } else if (collision.gameObject.GetComponent<IsACharacter> () != null && collision.gameObject.GetComponent<IsAPlayerOwned>() != null) { //check game manager for player lives, //reduce number of lives for player, //respawn player in middle of screen } //playerDead (); Destroy (gameObject); //gameobject is destroyed when it collides with anything } void playerDead(string gameObjectName){ GameObject gm = GameObject.Find(gameObjectName); if (gm != null) { AudioSource asource = gm.GetComponent<AudioSource> (); if (asource == null) { asource = gm.AddComponent<AudioSource> (); } asource.Stop(); } } // Use this for initialization void Start () { } // Update is called once per frame void Update () { } }
mit
kunalrmhatre/fussroll
Fussroll/app/src/main/java/com/fussroll/fussroll/BlockAdapter.java
2736
package com.fussroll.fussroll; import android.content.Context; import android.support.v7.widget.AppCompatButton; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.List; class BlockAdapter extends RecyclerView.Adapter<BlockAdapter.BlockedContactsViewHolder> { private LayoutInflater inflater; private List<String> data; private List<String> data1; private ClickListener clickListener; BlockAdapter(Context context, List<String> data, List<String> data1) { inflater = LayoutInflater.from(context); this.data = data; this.data1 = data1; } @Override public BlockedContactsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = inflater.inflate(R.layout.blocked_contacts_row, parent, false); return new BlockedContactsViewHolder(view); } @Override public void onBindViewHolder(BlockedContactsViewHolder holder, int position) { if(data.get(position) != null) holder.textView.setText(data.get(position)); else holder.textView.setText(data1.get(position)); } int removeItem(String contact) { int position = data1.indexOf(contact); data1.remove(contact); data.remove(position); return position; } int addItem(String name, String contact) { data.add(name); data1.add(contact); return data.indexOf(name); } @Override public int getItemCount() { return data.size(); } class BlockedContactsViewHolder extends RecyclerView.ViewHolder{ TextView textView; AppCompatButton appCompatButton; BlockedContactsViewHolder(View itemView) { super(itemView); textView = (TextView) itemView.findViewById(R.id.textView); appCompatButton = (AppCompatButton) itemView.findViewById(R.id.button); appCompatButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(clickListener != null) clickListener.onItemUnblockClicked(data.get(getLayoutPosition()), data1.get(getLayoutPosition())); } }); } } void setData(List<String> data, List<String> data1) { this.data = data; this.data1 = data1; } void setClickListener(ClickListener clickListener) { this.clickListener = clickListener; } interface ClickListener { void onItemUnblockClicked(String contactName, String phoneNumber); } }
mit
yi-jiayu/chat-analytics
demo/script.js
2252
"use strict"; var googleDataArray = [[ {label: 'timestamp', type: 'datetime'}, {label: 'sender', type: 'string'}, {label: 'message', type: 'string'}], [new Date(), '', ''] ]; // Check for the various File API support. if (window.File && window.FileReader && window.FileList && window.Blob) { // Great success! All the File APIs are supported. } else { alert('The File APIs are not fully supported in this browser.'); } document.querySelector('#files').addEventListener('change', handleFileSelect, false); class WhatsAppTimestamp { constructor(datestring) { const re = /^(\d+)\/(\d+)\/(\d+),? (\d+):(\d+)(?::\d+)? (AM|PM|am|pm)?/; let match = re.exec(datestring); let day = Number(match[1]); let month = Number(match[2]); let year = Number(match[3]); let hour = Number(match[4]); let minutes = Number(match[5]); let ampm = match[6]; if (ampm && /PM|pm/.test(match[6])) hour += 12; this.date = new Date(year, month, day, hour, minutes); } } function handleFileSelect(evt) { // reset data googleDataArray = [[ {label: 'timestamp', type: 'datetime'}, {label: 'sender', type: 'string'}, {label: 'message', type: 'string'}], [new Date(), '', ''] ]; var files = evt.target.files; var chatHistory = files[0]; var reader = new FileReader(); reader.readAsText(chatHistory); var re = /^(\d+\/\d+\/\d+,? \d+:\d+(?::\d+)?(?: (?:AM|PM|am|pm)?:| -)) (.*?): ([\s\S]*?)(?=^\d+\/\d+\/\d+,? \d+:\d+(?::\d+)?(?: (?:AM|PM|am|pm)?:| -) (.*?):)/gm; reader.onload = function (event) { var match = ''; while (match != null) { match = re.exec(event.target.result); if (match != null) { googleDataArray.push([new WhatsAppTimestamp(match[1]).date, match[2], match[3]]); } } if (googleDataArray.length == 2) { alert('Oops, it looks like this file is probably not a whatsapp conversation.'); return; } chatName = evt.target.files[0].name.replace('.txt', ''); title = `${chatName} (${googleDataArray.length - 1} messages)`; drawDashboard(); }; }
mit
shengmin/coding-problem
leetcode/gray-code/Solution.java
351
import java.util.*; public class Solution { public ArrayList<Integer> grayCode(int n) { ArrayList<Integer> list = new ArrayList<Integer>(); list.add(0); for (int i = 0; i < n; i++) { int mask = 1 << i; for (int j = list.size() - 1; j >= 0; j--) { list.add(list.get(j) | mask); } } return list; } }
mit
valor-software/ng2-bootstrap
src/tooltip/tooltip-container.component.ts
2122
import { AfterViewInit, Component, ChangeDetectionStrategy } from '@angular/core'; import { TooltipConfig } from './tooltip.config'; import { getBsVer, IBsVersion } from 'ngx-bootstrap/utils'; import { PlacementForBs5 } from 'ngx-bootstrap/positioning'; @Component({ selector: 'bs-tooltip-container', changeDetection: ChangeDetectionStrategy.OnPush, // eslint-disable-next-line @angular-eslint/no-host-metadata-property host: { '[class]': '"tooltip in tooltip-" + placement + " " + "bs-tooltip-" + placement + " " + placement + " " + containerClass', '[class.show]': '!_bsVersions.isBs3', '[class.bs3]': '_bsVersions.isBs3', '[attr.id]': 'this.id', role: 'tooltip' }, styles: [ ` :host.tooltip { display: block; pointer-events: none; } :host.bs3.tooltip.top>.arrow { margin-left: -2px; } :host.bs3.tooltip.bottom { margin-top: 0px; } :host.bs3.bs-tooltip-left, :host.bs3.bs-tooltip-right{ margin: 0px; } :host.bs3.bs-tooltip-right .arrow, :host.bs3.bs-tooltip-left .arrow { margin: .3rem 0; } ` ], template: ` <div class="tooltip-arrow arrow"></div> <div class="tooltip-inner"><ng-content></ng-content></div> ` }) export class TooltipContainerComponent implements AfterViewInit { classMap?: { [key: string]: boolean }; placement?: string; containerClass?: string; animation?: boolean; id?: string; get _bsVersions(): IBsVersion { return getBsVer(); } constructor(config: TooltipConfig) { Object.assign(this, config); } ngAfterViewInit(): void { this.classMap = { in: false, fade: false }; if (this.placement) { if (this._bsVersions.isBs5) { this.placement = PlacementForBs5[this.placement as keyof typeof PlacementForBs5]; } this.classMap[this.placement] = true; } this.classMap[`tooltip-${this.placement}`] = true; this.classMap.in = true; if (this.animation) { this.classMap.fade = true; } if (this.containerClass) { this.classMap[this.containerClass] = true; } } }
mit
doug-martin/promise-utils
test/rotate.test.js
3550
var array = require("../"), is = require("is-extended"), date = require("date-extended"), promise = require("promise-extended"), Promise = promise.Promise, resolve = promise.resolve, when = promise.when, assert = require("assert"), it = require("it"); it.describe("promise-utils .rotate", function (it) { function asyncDeepEqual(p, expected) { return when(p).then(function (res) { assert.deepEqual(res, expected); }); } it.describe("as a monad", function (it) { it.should("rotate an array ", function () { var arr = ["a", "b", "c", "d"]; return when( asyncDeepEqual(array(arr).async().rotate(), ["b", "c", "d", "a"]), asyncDeepEqual(array(resolve(arr)).rotate(), ["b", "c", "d", "a"]), asyncDeepEqual(array(arr).async().rotate(2), ["c", "d", "a", "b"]), asyncDeepEqual(array(resolve(arr)).rotate(2), ["c", "d", "a", "b"]), asyncDeepEqual(array(arr).async().rotate(3), ["d", "a", "b", "c"]), asyncDeepEqual(array(resolve(arr)).rotate(3), ["d", "a", "b", "c"]), asyncDeepEqual(array(arr).async().rotate(4), ["a", "b", "c", "d"]), asyncDeepEqual(array(resolve(arr)).rotate(4), ["a", "b", "c", "d"]), asyncDeepEqual(array(arr).async().rotate(-1), ["d", "a", "b", "c"]), asyncDeepEqual(array(resolve(arr)).rotate(-1), ["d", "a", "b", "c"]), asyncDeepEqual(array(arr).async().rotate(-2), ["c", "d", "a", "b"]), asyncDeepEqual(array(resolve(arr)).rotate(-2), ["c", "d", "a", "b"]), asyncDeepEqual(array(arr).async().rotate(-3), ["b", "c", "d", "a"]), asyncDeepEqual(array(resolve(arr)).rotate(-3), ["b", "c", "d", "a"]), asyncDeepEqual(array(arr).async().rotate(-4), ["a", "b", "c", "d"]), asyncDeepEqual(array(resolve(arr)).rotate(-4), ["a", "b", "c", "d"]) ); }); }); it.describe("as a function", function (it) { it.should("rotate an array ", function () { var arr = ["a", "b", "c", "d"]; return when( asyncDeepEqual(array.rotate(arr), ["b", "c", "d", "a"]), asyncDeepEqual(array.rotate(resolve(arr)), ["b", "c", "d", "a"]), asyncDeepEqual(array.rotate(arr, 2), ["c", "d", "a", "b"]), asyncDeepEqual(array.rotate(resolve(arr), 2), ["c", "d", "a", "b"]), asyncDeepEqual(array.rotate(arr, 3), ["d", "a", "b", "c"]), asyncDeepEqual(array.rotate(resolve(arr), 3), ["d", "a", "b", "c"]), asyncDeepEqual(array.rotate(arr, 4), ["a", "b", "c", "d"]), asyncDeepEqual(array.rotate(resolve(arr), 4), ["a", "b", "c", "d"]), asyncDeepEqual(array.rotate(arr, -1), ["d", "a", "b", "c"]), asyncDeepEqual(array.rotate(resolve(arr), -1), ["d", "a", "b", "c"]), asyncDeepEqual(array.rotate(arr, -2), ["c", "d", "a", "b"]), asyncDeepEqual(array.rotate(resolve(arr), -2), ["c", "d", "a", "b"]), asyncDeepEqual(array.rotate(arr, -3), ["b", "c", "d", "a"]), asyncDeepEqual(array.rotate(resolve(arr), -3), ["b", "c", "d", "a"]), asyncDeepEqual(array.rotate(arr, -4), ["a", "b", "c", "d"]), asyncDeepEqual(array.rotate(resolve(arr), -4), ["a", "b", "c", "d"]) ); }); }); });
mit
tastphp/framework
src/Framework/Console/Command/BaseCommand.php
1578
<?php namespace TastPHP\Framework\Console\Command; use Symfony\Component\Console\Command\Command; class BaseCommand extends Command { protected function getControllerNameByEntityName($name) { return $this->processName($name); } protected function getRouteEntityNameByEntityName($entityName) { $names = explode('_', $entityName); $newName = ''; if (count($names) > 1) { foreach ($names as $name) { $newName .= '/' . $name; } $newName = substr($newName, 1, strlen($newName)); return $newName; } return $entityName; } protected function getGenerateEntityServiceNameByTableName($tableName) { return $this->processName($tableName); } protected function getQuestionHelper() { return $this->getHelper('question'); } protected function changeDir($dir) { chdir(__BASEDIR__ . "/{$dir}"); } protected function getTemplateDir() { return __IMPORT_DIR__ . "/Console/Command/Template"; } private function processName($name) { list($name, $names) = $this->handleName($name); $newName = ''; if (count($names) > 1) { foreach ($names as $name) { $newName .= ucfirst($name); } return $newName; } return $name; } private function handleName($name) { $name = ucfirst($name); $names = explode('_', $name); return [$name, $names]; } }
mit
simonvpe/borrkoll-react
tests/routes/Projects/modules/edit.js
4556
import { actions.update as update, actions.insert as insert } from 'routes/Projects/modules/projects' import { factory } from 'routes/Projects/modules/factory' import { actions, PROJECT_EDIT_START, PROJECT_EDIT_CANCEL, PROJECT_EDIT_SUBMIT, default as reducer } from 'routes/Projects/modules/edit' import configureStore from 'redux-mock-store' import thunk from 'redux-thunk' const middleware = [ thunk ] const mockStore = configureStore(middleware) describe('(Redux Module) Project edit', () => { it('Should export a constant PROJECT_EDIT_START.', () => { expect(PROJECT_EDIT_START).to.equal('PROJECT_EDIT_START') }) it('Should export a constant PROJECT_EDIT_CANCEL.', () => { expect(PROJECT_EDIT_CANCEL).to.equal('PROJECT_EDIT_CANCEL') }) it('Should export a constant PROJECT_EDIT_UPDATE.', () => { expect(PROJECT_EDIT_UPDATE).to.equal('PROJECT_EDIT_UPDATE') }) describe('(Action Creator) actions.start.', () => { it('Should be exported as a function.', () => { expect(actions.start).to.be.a('function') }) it('Should return an action with type PROJECT_EDIT_START.', () => { expect(actions.start()).to.have.property('type', PROJECT_EDIT_START) }) it('Should assign a deep copy of the first argument to the "project" property.', () => { let project = factory.project() let act = actions.start(project) expect(act).to.have.property('project').that.deep.equals(project) expect(act).to.have.property('project').that.not.equals(project) }) it('Should throw if omitting argument or using wrong type.', () => { expect(() => actions.start()).to.throw('Argument (project) must be an object!') expect(() => actions.start('')).to.throw('Argument (project) must be an object!') }) }) describe('(Action Creator) actions.cancel', () => { it('Should be exported as a function.', () => { expect(actions.cancel).to.be.a('function') }) it('Should return an action with type PROJECT_EDIT_CANCEL.', () => { expect(actions.cancel()).to.have.property('type', PROJECT_EDIT_CANCEL) }) }) describe('(Action Creator) actions.submit', () => { it('Should be exported as a function.', () => { expect(actions.submit).to.be.a('function') }) it('Should return an action with type PROJECT_EDIT_SUBMIT.', () => { expect(actions.submit()).to.have.property('type', PROJECT_EDIT_SUBMIT) }) }) describe('(Reducer)', () => { it('Should be a function.', () => { expect(reducer).to.be.a('function') }) it('Should initialize a state.', () => { let state = reducer(undefined, {}) expect(state.project).to.have.property('project', undefined) expect(state.project).to.have.property('working', false) expect(state.project).to.have.property('error', undefined) }) it('Should return previous state if an action was not matched.', () => { const state1 = reducer(undefined, {}) const state2 = reducer(state1, { type: '' }) expect(state1).to.equal(state2) }) describe('(Handler) PROJECT_EDIT_START', () => { it('Should assign a deep copy of the given project to the "project" property.', () => { const project = factory.project() const state = reducer(undefined, actions.start(project)) expect(state).to.have.property('project').that.deep.equals(project) expect(state).to.have.property('project').that.not.equals(project) }) // it('Should set the "working" property to true.', () => { // const project = factory.project() // const state1 = reducer(undefined, actions.start(project)) // expect(state).to.have.property('working', false) // const state2 = reducer(state1, actions.start(project)) // expect(state2).to.have.property('working', true) // }) }) describe('(Handler) PROJECT_EDIT_CANCEL', () => { it('Should set the "project" property to undefined.', () => { const project = factory.project() const store = mockStore({ project, working: false }) mockStore.dispatch(actions.cancel()) expect(store.getState()).to.have.property('project', undefined) }) it('Should set the "working" property to false.', () => { const project = factory.project() const store = mockStore({ project, working: true }) mockStore.dispatch(actions.cancel()) expect(store.getState()).to.have.property('working', false) }) }) }) })
mit
micahlanier/pyscreenshort
screenshort.py
13068
#!/usr/bin/env python ##### Setup ### Libraries import argparse import logging import math import os from PIL import Image, ImageColor, ImageDraw, ImageFont, ImageOps import re import sys ### System Settings # Default font paths for Mac OS X. # Order of list will be searchable order. font_dirs = ['/System/Library/Fonts/','/Library/Fonts/','~/Library/Fonts/'] ### Visual Settings # Rendering scale. # PIL fonts are rough, so we want to render the image larger and resize with anti-aliasing. render_scale = 4 # Default dimensions. default_min_height = 240 default_width = 600 default_padding = 20 # Default colors if received options are unparseable. default_color_bg = 'white' default_color_text = 'black' # Default fonts and related options. default_font_major = 'Hoefler Text' default_font_minor = 'HelveticaNeue' default_font_size_major = 24 default_font_size_minor = 16 default_font_spacing_major = 1 default_font_spacing_minor = 0 ##### Functions def process_text(text, font, width_limit): """Reformat text as a set of appropriate-length lines given a font and width limit. Return a list of strings (one line per entry). Keyword arguments: text: raw text to format. font: PIL font to use for formatting. width_limit: width limit of text area in pixels. """ # Tokenize each line. tokens = [re.sub(ur'\s+',' ',line.strip()).split(' ') for line in text.strip().split('\n')] # Create a container and traverse lines. tokens_processed = [] for l, line in enumerate(tokens): # Always append the first token. This handles empty lines, too-long tokens. current_line = [line[0]] # Traverse all tokens on this line. for token in line[1:]: # Test the new line. proposal = ' '.join(current_line+[token]) if font.getsize(proposal)[0] < width_limit: # If the new token does not make the line too long, append it. current_line.append(token) else: # Otherwise, start a new line. tokens_processed.append(current_line) current_line = [token] # At this point, we have finished processing a line. Add what remains to the full line list. tokens_processed.append(current_line) # Finally, bring it all together and return. return [' '.join(tokens) for tokens in tokens_processed] def find_font_by_name(path, name): """Find a font at a given path and return the whole path or None (if not found). Keyword arguments: path: directory to search. name: font name based on filename without extension. """ # Validate path. path = os.path.expanduser(path) if not os.path.isdir(path): return None # Traverse. found_fonts = [f for f in os.listdir(path) if os.path.splitext(f)[0] == name] return (os.path.join(path,found_fonts[0]) if found_fonts else None) def draw_text(image, lines, x, y, spacing, font, color): """Draw lines of text on a given image. Keyword arguments: image: PIL.Image on which to draw text. lines: list of strings (each one line). x: horizontal location to begin drawing text. y: vertical location to begin drawing text. spacing: spacing between lines in pixels. font: PIL ImageFont object. color: PIL.ImageColor name (e.g., 'red', 'darkgreen', '#ffffff'). """ # Draw the main text. draw = ImageDraw.Draw(image) # Keep track of line offset from top. line_offset = y # Traverse all lines. for line in lines: # Draw text. draw.text((x,line_offset), line, font=font, fill=color) # Update offset. line_offset += sum(font.getmetrics()) + spacing def validate_color(color,default,color_type): """Validate a color against known PIL values. Return the validated color if valid; otherwise return a default. Keyword arguments: color: color to test. default: default color string value if color is invalid. color_type: string name for color type, used for alerting users of defaults. """ # Use exception handling. If a given color throws an error, we may return false. try: c = ImageColor.getcolor(color,'RGB') return color except ValueError as e: logging.warning('"%s" is not a valid color specifier. Defaulting to "%s" for %s color.',color,default,color_type) return default ##### Execution def screenshort( main_text, secondary_text=None, width=default_width, min_height=default_min_height, padding=default_padding, bg_color=default_color_bg, text_color=default_color_text, major_font_name=default_font_major, major_font_size=default_font_size_major, major_font_spacing=default_font_spacing_major, major_text_color=None, minor_font_name=default_font_minor, minor_font_size=default_font_size_minor, minor_font_spacing=default_font_spacing_minor, minor_text_color=None, output=None ): """Generate a screenshort and save to the specified path.""" ### Input Validation # Determine if we're using minor text or not. use_minor_text = secondary_text not in {'',None} # Validate size. if width < padding*2: logging.error('Image width must be larger than 2*padding.') sys.exit(1) elif width < 200: logging.warning('Image width %d will likely produce a very cramped image.',width) min_height = max(0,min_height) padding = max(0,padding) # Validate colors. color_bg = validate_color(bg_color,default_color_bg,'background') color_text = validate_color(text_color,default_color_text,'text') # Intelligently select colors for each type of text. color_text_major = color_text if major_text_color is None else validate_color(major_text_color,'main text',color_text) color_text_minor = color_text if minor_text_color is None else validate_color(minor_text_color,'secondary text',color_text) # Validate text/font settings. # TODO ### Process Settings # This section sets up variables that we will actually use in the rendering process. # Parse text as UTF-8. text_major = main_text.decode('utf-8') if use_minor_text: text_minor = secondary_text.decode('utf-8') # Get rendering width. render_width = width * render_scale # Scale-specific padding and text margins. render_padding = padding * render_scale font_spacing_render_major = padding * major_font_spacing font_spacing_render_minor = padding * minor_font_spacing # Determine how much space the text has. render_text_width = render_width - render_padding*2 # Determine minimum render height. render_height_min = min_height*render_scale # Get fonts. font_path_major = None font_path_minor = None # Traverse font directories. for font_dir in reversed(font_dirs): # Get candidates for fonts. font_candidate_major = find_font_by_name(font_dir, major_font_name) font_path_major = font_candidate_major if font_candidate_major else font_path_major font_candidate_minor = find_font_by_name(font_dir, minor_font_name) font_path_minor = font_candidate_minor if font_candidate_minor else font_path_minor # Validate fonts. if not font_path_major: logging.error('No valid main text font found.') sys.exit(1) if use_minor_text and not font_path_major: logging.error('No valid secondary text font found.') sys.exit(1) # Turn fonts into actual objects. font_major = ImageFont.truetype(font_path_major, major_font_size*render_scale, encoding='unic') font_minor = ImageFont.truetype(font_path_minor, minor_font_size*render_scale, encoding='unic') # Get their line heights for later use as well. line_height_major = sum(font_major.getmetrics()) line_height_minor = sum(font_minor.getmetrics()) # Get height of each text element text_lines_major = process_text(text_major, font_major, render_text_width) if use_minor_text: # If there is secondary text, process it. text_lines_minor = process_text(text_minor, font_minor, render_text_width) # Also handle spacing in between major/minor text. intratext_spacing = line_height_major else: # No minor text height or buffer after major text if there is no minor text. line_height_minor = 0 intratext_spacing = 0 # Determine height. Calculate what it should be. text_height_major = len(text_lines_major)*line_height_major + (len(text_lines_major)-1)*font_spacing_render_major text_height_minor = len(text_lines_minor)*line_height_minor + (len(text_lines_minor)-1)*font_spacing_render_minor if use_minor_text else 0 render_height = (text_height_major+intratext_spacing+text_height_minor+render_padding*2) height = render_height/render_scale # Location for minor text to start. text_minor_y = max(render_height,render_height_min)-(render_padding+text_height_minor) # Alter height if the determined height is below minimum. if render_height < render_height_min: # If it's too small, adjust. render_height = render_height_min # Also make sure the main text starts middle-aligned. text_major_y = (text_minor_y+render_padding)/2 - text_height_major/2 else: text_major_y = render_padding # Determine final unscaled height. height = render_height/render_scale ### Image Composition # Now we're ready to compose the image. Start by creating it. img = Image.new('RGBA', (render_width,render_height), color_bg) # Draw text. draw_text(img, text_lines_major, render_padding, text_major_y, font_spacing_render_major, font_major, color_text_major) if use_minor_text: draw_text(img, text_lines_minor, render_padding, text_minor_y, font_spacing_render_minor, font_minor, color_text_minor) # Resize back down to intended size. # Use anti-aliasing. Inspiration: http://stackoverflow.com/questions/5414639/python-imaging-library-text-rendering img_resized = img.resize((width,height), Image.ANTIALIAS) # Save/show it. if output is None: img_resized.show() else: img_resized.save(output) ##### Standalone Execution def main(): """Parse input arguments and pass to screenshort().""" # Set up argument parser. parser = argparse.ArgumentParser(description='Generate a "screenshort" image.') # Text elements. parser.add_argument('main_text',type=str,help='main image text') parser.add_argument('secondary_text',nargs='?',type=str,help='secondary image text (optional)') # Image size. group_size = parser.add_argument_group('Image Size') group_size.add_argument('--min_height',metavar='PIXELS',type=int,default=default_min_height,help='minimum height in pixels (default: %d)'%default_min_height) group_size.add_argument('--width',metavar='PIXELS',type=int,default=default_width,help='width in pixels (default: %d)'%default_width) group_size.add_argument('--padding',metavar='PIXELS',type=int,default=default_padding,help='padding in pixels around the outside of the image (default: %d)'%default_padding) # Output. group_output = parser.add_argument_group('File Output') group_output.add_argument('--output',metavar='LOCATION',type=str,default=None,help='output destination file, including extension. if omitted, a BMP will be created and shown via xv') # Colors. group_color = parser.add_argument_group('Colors') group_color.add_argument('--bg_color',metavar='COLOR',dest='bg_color',type=str,default=default_color_bg,help='background color, a hexadecimal string or common color name (default: %s)'%default_color_bg) group_color.add_argument('--text_color',metavar='COLOR',dest='text_color',type=str,default=default_color_text,help='text color, a hexadecimal string or common color name (default: %s)'%default_color_text) group_color.add_argument('--main_text_color',metavar='COLOR',dest='major_text_color',type=str,default=None,help='main string text color (defaults to --text_color value)') group_color.add_argument('--secondary_text_color',metavar='COLOR',dest='minor_text_color',type=str,default=None,help='secondary string text color (defaults to --text_color value)') # Fonts. group_fonts = parser.add_argument_group('Fonts') group_fonts.add_argument('--main_font_name',metavar='FONT',dest='major_font_name',type=str,default=default_font_major,help='font name for main text, based on font filename with no extension (default: %s)'%default_font_major) group_fonts.add_argument('--secondary_font_name',metavar='FONT',dest='minor_font_name',type=str,default=default_font_minor,help='font name for secondary text, based on font filename with no extension (default: %s)'%default_font_minor) group_fonts.add_argument('--main_font_size',metavar='POINTS',dest='major_font_size',type=int,default=default_font_size_major,help='font size for main text in points (default: %d)'%default_font_size_major) group_fonts.add_argument('--secondary_font_size',metavar='POINTS',dest='minor_font_size',type=int,default=default_font_size_minor,help='font size for secondary text in points (default: %d)'%default_font_size_minor) group_fonts.add_argument('--main_font_spacing',metavar='PIXELS',dest='major_font_spacing',type=int,default=default_font_spacing_major,help='inter-line spacing for main text (default: %d)'%default_font_spacing_major) group_fonts.add_argument('--secondary_font_spacing',metavar='PIXELS',dest='minor_font_spacing',type=int,default=default_font_spacing_minor,help='inter-line spacing for secondary text (default: %d)'%default_font_spacing_minor) # Parse arguments. args = parser.parse_args() # Simply pass params to screenshort() method. screenshort(**vars(args)) if __name__ == '__main__': main()
mit
baohx2000/iamboard
frontend/shared/bootstrap.js
222
/* globals window */ import React from 'react'; import ReactDOM from 'react-dom'; import RootComponent from './root-component'; window.React = React; ReactDOM.render( RootComponent, document.getElementById('app') );
mit
petrocket/HeartOfStone
Assets/src/PlayerController.cs
3883
using UnityEngine; using System.Collections; //[RequireComponent (typeof (LineRenderer))] public class PlayerController : MonoBehaviour { public GameObject target; public GameObject gun; private LaserGun laserGun; private DamageTaker damageTaker; private CameraTracker cameraTracker; private GameRules gameRules; // these are the max extents the player can drift from 0,0,0 public Vector3 limits = new Vector3(3.0f,3.0f,3.0f); public Vector2 targetLimits = new Vector2 (3.0f, 3.0f); public Vector3 lookAt = new Vector3(0.0f, 10.0f, 0.0f); public float sensitivity = 2.0f; public float targetOffset = 30.0f; //public float laserWidth = 1.0f; //public Color laserColor = Color.red; public float laserMaxLength = 50.0f; public int laserNumSegments = 2; //private LineRenderer lineRenderer; // Use this for initialization void Start () { //lineRenderer = GetComponent<LineRenderer> (); //lineRenderer.SetVertexCount (laserNumSegments); //lineRenderer.SetPosition (0, Vector3.zero); GameObject newGun = (GameObject)Instantiate (gun, Vector3.zero, Quaternion.identity); newGun.transform.parent = transform; newGun.transform.localPosition = Vector3.zero; newGun.transform.localRotation = Quaternion.identity; laserGun = newGun.GetComponent<LaserGun> (); damageTaker = GetComponent<DamageTaker> (); cameraTracker = Camera.main.GetComponent<CameraTracker> (); gameRules = Camera.main.GetComponent<GameRules> (); } // Update is called once per frame void Update () { float dx = Input.GetAxis("Horizontal") * sensitivity * Time.deltaTime; float dy = Input.GetAxis("Vertical") * sensitivity * Time.deltaTime; transform.localPosition = new Vector3 ( Mathf.Clamp (transform.localPosition.x + dx, -limits.x, limits.x), Mathf.Clamp (transform.localPosition.y + dy, -limits.y, limits.y), transform.localPosition.z); Vector3 mousepos = Camera.main.ScreenToWorldPoint (new Vector3(Input.mousePosition.x, Input.mousePosition.y, targetOffset)); target.transform.position = mousepos; transform.LookAt (target.transform, Vector3.up); if (Input.GetButton("Fire1") && damageTaker.health > 0.0f) { laserGun.Fire(); } if (damageTaker.health <= 0.0f && !gameRules.paused) { Debug.Log ("Ending game"); gameRules.OnGameOver(); } } /* void RenderLaser() { UpdateLaserLength (); //lineRenderer.SetColors (laserColor, laserColor); Vector3 vertexPos = Vector3.zero; float dz = laserMaxLength / (float)laserNumSegments; for (int i = 1; i < laserNumSegments; ++i) { vertexPos.z = dz + ((float)i * dz); lineRenderer.SetPosition(i,vertexPos); } } */ void OnTriggerEnter(Collider other) { //if (other.tag != "Player" && other.tag != "Laser") { Debug.Log ("Collided"); if (damageTaker.health > 0.0f) { DamageTaker otherDamageTaker = other.GetComponent<DamageTaker>(); if(otherDamageTaker && otherDamageTaker.health > 0.0f) { otherDamageTaker.TakeDamage (1000.0f); damageTaker.TakeDamage(10.0f); cameraTracker.shake = 1.0f; if (damageTaker.health <= 0.0f) { gameRules.OnGameOver(); } } } //} } /* void UpdateLaserLength() { RaycastHit[] hit; hit = Physics.RaycastAll (transform.position, transform.forward, laserMaxLength ); int i = 0; float closest = -1.0f; int closestIndex = -1; while (i < hit.Length) { // TODO damage! if ( (closest < 0.0f || hit[i].distance < closest) && hit[i].collider.tag != "player") { closest = hit[i].distance; closestIndex = i; } i++; } if (closestIndex > -1 && closestIndex < hit.Length) { DamageTaker damageTaker = hit[closestIndex].collider.GetComponent<DamageTaker>(); //Debug.Log ("Hit " + hit[closestIndex].collider.GetType()); if (damageTaker != null) { //Debug.Log ("Taking Damage"); damageTaker.TakeDamage(1000.0f); } } } */ }
mit
LPGhatguy/lemur
lib/Enum/HorizontalAlignment.lua
125
local createEnum = import("../createEnum") return createEnum("HorizontalAlignment", { Center = 0, Left = 1, Right = 2, })
mit
galymzhan/wstats
spec/javascripts/UserSpec.js
1758
describe("User", function() { var client = new Client('test-key'), user = new User(client), async = new AsyncSpec(this); describe("unrecognizedKanji", function() { beforeEach(function() { spyOn(client, 'api').andCallFake(function(resource, callback) { callback(Factory.build('response', { requested_information: [ Factory.build('kanji', { character: '工' }), Factory.build('kanji', { character: '川' }) ] })); }); }); async.it("returns list of unrecognized kanji in a text", function(done) { user.unrecognizedKanji('私は田中です。川口です。', function(unrecognized) { expect(unrecognized.kanjiCount).toEqual(5); expect(unrecognized.list.sort()).toEqual(['私', '田', '中', '口'].sort()); done(); }); }); async.it("returns empty list if everything is recognized", function(done) { user.unrecognizedKanji('川 character. 工 character.', function(unrecognized) { expect(unrecognized.kanjiCount).toEqual(2); expect(unrecognized.list).toEqual([]); done(); }); }); async.it("ignores non-kanji characters", function(done) { user.unrecognizedKanji('hello world', function(unrecognized) { expect(unrecognized.kanjiCount).toEqual(0); expect(unrecognized.list).toEqual([]); done(); }); }); async.it("counts distinct kanjis", function(done) { user.unrecognizedKanji('this is 川 character - 川. 見返り柳.見返り柳.', function(unrecognized) { expect(unrecognized.kanjiCount).toEqual(4); expect(unrecognized.list).toEqual(['見', '返', '柳']); done(); }); }); }); });
mit
fxia22/pointGAN
show_gan_rnn3.py
1293
from __future__ import print_function from show3d_balls import * import argparse import os import random import numpy as np import torch import torch.nn as nn import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.optim as optim import torch.utils.data import torchvision.datasets as dset import torchvision.transforms as transforms import torchvision.utils as vutils from torch.autograd import Variable from datasets import PartDataset from pointnet import PointGen, PointGenR3 import torch.nn.functional as F import matplotlib.pyplot as plt #showpoints(np.random.randn(2500,3), c1 = np.random.uniform(0,1,size = (2500))) parser = argparse.ArgumentParser() parser.add_argument('--model', type=str, default = '', help='model path') opt = parser.parse_args() print (opt) gen = PointGenR3() gen.load_state_dict(torch.load(opt.model)) sim_noise = Variable(torch.randn(2, 100,5)) sim_noises = Variable(torch.zeros(30,100,5)) for i in range(30): x = i/30.0 sim_noises[i] = sim_noise[0] * x + sim_noise[1] * (1-x) points = gen(sim_noises) point_np = points.transpose(2,1).data.numpy() cmap = plt.cm.get_cmap("hsv", 10) cmap = np.array([cmap(i) for i in range(10)])[:,:3] color = cmap[np.repeat(np.array([1,2,3,4,5]), 500), :] showpoints(point_np, color)
mit
kimikimi714/composer_autoload_test
app.php
141
<?php require_once __DIR__ . '/vendor/autoload.php'; use kimikimi714\autoloader\Autoload; $autoload = new Autoload(); $autoload->hello();
mit
cperthuis/GameCode
src/shared/allocator.cpp
1554
#include "allocator.h" #include <vector> struct FrameAllocatorData { size_t _bufferSize; std::vector<char *> _buffers; size_t _bufferIndex; size_t _pos; void *_last; size_t _prevPos; size_t _count; }; FrameAllocator::FrameAllocator(size_t bufferSize) { _data = new FrameAllocatorData; _data->_bufferSize = bufferSize; char *buffer = new char[bufferSize]; _data->_buffers.push_back(buffer); reset(); } FrameAllocator::~FrameAllocator() { for (size_t i = 0; i < _data->_buffers.size(); i++) { delete[] _data->_buffers[i]; } } void FrameAllocator::reset() { _data->_pos = 0; _data->_bufferIndex = 0; _data->_prevPos = 0; _data->_last = NULL; _data->_count = 0; } void *FrameAllocator::allocate(size_t size) { if (_data->_pos + size > _data->_bufferSize) { if (size > _data->_bufferSize) return NULL; _data->_bufferIndex++; if (_data->_bufferIndex == _data->_buffers.size()) { char *buffer = new char[_data->_bufferSize]; _data->_buffers.push_back(buffer); } _data->_pos = 0; } char *mem = _data->_buffers[_data->_bufferIndex] + _data->_pos; _data->_last = mem; _data->_prevPos = _data->_pos; _data->_pos += size; _data->_count++; return mem; } void FrameAllocator::free(void *ptr) { //only free the simple cases if (ptr == _data->_last) { _data->_pos = _data->_prevPos; } _data->_count--; } AllocatorStats FrameAllocator::stats() { AllocatorStats s; s.allocationCount = _data->_count; return s; }
mit
mccarter/restaurant-order-demo
public/services/services.js
501
angular.module('rideCellApp.services', []) .factory('RideCellService', function($http, $location) { //Stores all previous orders var allOrders = []; //stores menu data for usage on menu detail page var menu; //stores order data for usage on admin page to populate POS table var orderData; //modular use of redirect function var redirect = function(route) { $location.path(route); }; return { allOrders: allOrders, menu: menu, orderData: orderData, redirect: redirect, } });
mit
overridethis/usgsclient
UsgsClient/Common/EnumExtensions.cs
817
using System; using System.ComponentModel; using System.Linq; using System.Reflection; namespace UsgsClient.Common { public static class EnumExtensions { public static T GetAttributeOfType<T>(this Enum value) where T : System.Attribute { var typeInfo = value.GetType().GetTypeInfo(); var memInfo = typeInfo.DeclaredMembers .First(mbr => mbr.Name == value.ToString()); var attributes = memInfo.GetCustomAttributes(typeof(T), false) .ToList(); return attributes.Any() ? (T)attributes[0] : null; } public static string GetDescription(this Enum value) { return value .GetAttributeOfType<DescriptionAttribute>()? .Description; } } }
mit
heyui/heyui
src/components/circle/index.js
55
import Circle from './circle'; export default Circle;
mit
seph-lang/seph
src/main/seph/lang/structure/SephObject_1_17.java
4509
/* THIS FILE IS GENERATED. DO NOT EDIT */ package seph.lang.structure; import seph.lang.*; import seph.lang.persistent.*; public class SephObject_1_17 extends SephObjectStructure { public final SephObject parent0; public final String selector0; public final SephObject cell0; public final String selector1; public final SephObject cell1; public final String selector2; public final SephObject cell2; public final String selector3; public final SephObject cell3; public final String selector4; public final SephObject cell4; public final String selector5; public final SephObject cell5; public final String selector6; public final SephObject cell6; public final String selector7; public final SephObject cell7; public final String selector8; public final SephObject cell8; public final String selector9; public final SephObject cell9; public final String selector10; public final SephObject cell10; public final String selector11; public final SephObject cell11; public final String selector12; public final SephObject cell12; public final String selector13; public final SephObject cell13; public final String selector14; public final SephObject cell14; public final String selector15; public final SephObject cell15; public final String selector16; public final SephObject cell16; public SephObject_1_17(IPersistentMap meta, SephObject parent0, String selector0, SephObject cell0, String selector1, SephObject cell1, String selector2, SephObject cell2, String selector3, SephObject cell3, String selector4, SephObject cell4, String selector5, SephObject cell5, String selector6, SephObject cell6, String selector7, SephObject cell7, String selector8, SephObject cell8, String selector9, SephObject cell9, String selector10, SephObject cell10, String selector11, SephObject cell11, String selector12, SephObject cell12, String selector13, SephObject cell13, String selector14, SephObject cell14, String selector15, SephObject cell15, String selector16, SephObject cell16) { super(meta); this.parent0 = parent0; this.selector0 = selector0.intern(); this.cell0 = cell0; this.selector1 = selector1.intern(); this.cell1 = cell1; this.selector2 = selector2.intern(); this.cell2 = cell2; this.selector3 = selector3.intern(); this.cell3 = cell3; this.selector4 = selector4.intern(); this.cell4 = cell4; this.selector5 = selector5.intern(); this.cell5 = cell5; this.selector6 = selector6.intern(); this.cell6 = cell6; this.selector7 = selector7.intern(); this.cell7 = cell7; this.selector8 = selector8.intern(); this.cell8 = cell8; this.selector9 = selector9.intern(); this.cell9 = cell9; this.selector10 = selector10.intern(); this.cell10 = cell10; this.selector11 = selector11.intern(); this.cell11 = cell11; this.selector12 = selector12.intern(); this.cell12 = cell12; this.selector13 = selector13.intern(); this.cell13 = cell13; this.selector14 = selector14.intern(); this.cell14 = cell14; this.selector15 = selector15.intern(); this.cell15 = cell15; this.selector16 = selector16.intern(); this.cell16 = cell16; } public final SephObject get(String name) { name = name.intern(); if(name == this.selector0) return this.cell0; if(name == this.selector1) return this.cell1; if(name == this.selector2) return this.cell2; if(name == this.selector3) return this.cell3; if(name == this.selector4) return this.cell4; if(name == this.selector5) return this.cell5; if(name == this.selector6) return this.cell6; if(name == this.selector7) return this.cell7; if(name == this.selector8) return this.cell8; if(name == this.selector9) return this.cell9; if(name == this.selector10) return this.cell10; if(name == this.selector11) return this.cell11; if(name == this.selector12) return this.cell12; if(name == this.selector13) return this.cell13; if(name == this.selector14) return this.cell14; if(name == this.selector15) return this.cell15; if(name == this.selector16) return this.cell16; return this.parent0.get(name); } }
mit
janslow/projection-mapper-world
src/com/jayanslow/projection/world/models/Face.java
658
package com.jayanslow.projection.world.models; import javax.vecmath.Vector3f; public interface Face { /** * Gets the id of the face, such that (parent, faceId) is unique * * @return Face id */ public int getFaceId(); /** * Friendly name of face * * @return Friendly name, or null */ public String getName(); /** * Gets the position * * @return */ public Vector3f getPosition(); /** * Gets the direction of the face * * @return Object direction and roll */ public Rotation3f getRotation(); /** * Gets the screen which this face is part of * * @return Parent Screen */ public Screen getScreen(); }
mit
Paleozoic/hd-client
src/main/java/com/maxplus1/hd_client/hbase/funciton/Schema.java
417
package com.maxplus1.hd_client.hbase.funciton; import org.apache.hadoop.hbase.HTableDescriptor; /** * 提供HBase schema的操作功能 * * @author zachary.zhang * @author Paleo */ public interface Schema { void createTable(String tableName, String... columnFamily) ; void deleteTable(String tableName) ; HTableDescriptor[] listTables() ; HTableDescriptor[] listTables(String regex) ; }
mit
Asquera/eson-dsl
test/search/filters/ids.rb
214
{:query => { :filtered => { :query => { :match_all => { } }, :filter => { :ids => { :type => "user", :values => [1,2,3,4,5,6,7] } } } } }
mit
baherramzy/DestinyStatus
app/destiny/Character/InventoryItemCollection.php
182
<?php namespace Destiny\Character; use Destiny\Collection; /** * @method \Destiny\Character\InventoryItem offsetGet($key) */ class InventoryItemCollection extends Collection { }
mit
garymabin/YGOMobile
proj.android/src/cn/garymb/ygomobile/widget/wheelview/WheelAdapter.java
579
package cn.garymb.ygomobile.widget.wheelview; public interface WheelAdapter { /** * Gets items count * * @return the count of wheel items */ public int getItemsCount(); /** * Gets a wheel item by index. * * @param index * the item index * @return the wheel item text or null */ public String getItem(int index); /** * Gets maximum item length. It is used to determine the wheel width. If -1 * is returned there will be used the default wheel width. * * @return the maximum item length or -1 */ public int getMaximumLength(); }
mit
sendaa/current4
I/CbaseEnqSubeventMVC.php
19393
<?php require_once 'CbaseMVC.php'; require_once 'CbaseFEnquete.php'; require_once 'CbaseFEventDesign.php'; require_once 'CbaseFCheckModule.php'; require_once 'CbaseFError.php'; require_once 'CbaseFForm.php'; require_once 'QuestionType.php'; class EnqSubeventModel extends Model { public function delete(& $request) { Delete_Subevent($request['seid'], $request['evid']); $flag = false; foreach ($this->subevents as $seid => $subevent) { if ($request['seid'] != $seid) $nextid = $seid; if ($flag) break; if ($request['seid'] == $seid) $flag = true; } $request['seid'] = $nextid; } public function getMatrixArray($subevent) { $aryDefData = Get_Design("id", 0); $aryDefData = $aryDefData[0]; $matrix_array = array (); $matrix_array['title'] = $subevent['title']; $matrix_array['hissu'] = $subevent['hissu']; $matrix_array['type1'] = $subevent['type1']; $matrix_array['type2'] = $subevent['type2']; if ($subevent['matrix'] == 5) { $matrix_array['html2'] = buildmatrix($aryDefData, 1, $subevent['choice']); } else { $matrix_array['html2'] = $subevent['html2']; } $matrix_array['choice'] = $subevent['choice']; $matrix_array['matrix'] = 6; $matrix_array['other'] = $subevent['other']; $matrix_array['width'] = $subevent['width']; $matrix_array['rows'] = $subevent['rows']; $matrix_array['word_limit'] = $subevent['word_limit']; $matrix_array['page'] = $subevent['page']; $matrix_array['chtable'] = $subevent['chtable']; $matrix_array['randomize'] = $subevent['randomize']; $matrix_array['ext'] = $subevent['ext']; return $matrix_array; } public function insertBefore(& $request) { //1個まえの設問がマトリックスだったときの処理 $subevent = $this->subevents[$this->subevents[$request['seid']]['pre_seid']]; $matrix_array = array (); if ($subevent['matrix'] == 5 || $subevent['matrix'] == 6) { $matrix_array = $this->getMatrixArray($subevent); } $new_seid = Insert_Subevent($request['evid'], $request['seid'], $matrix_array); $request['seid'] = $new_seid; } public function insertAfter(& $request) { //1個まえの設問がマトリックスだったときの処理 $subevent = $this->subevents[$request['seid']]; $matrix_array = array (); if ($subevent['matrix'] == 5 || $subevent['matrix'] == 6) { $matrix_array = $this->getMatrixArray($subevent); } //もしも最後の問題だったら別処理 if ($this->event['last_seid'] == $request['seid']) { $insertdata = array ( "seid" => "new", "evid" => $this->event['evid'], "title" => "追加", "type1" => 0, "type2" => "r", "choice" => "", "hissu" => 1, "width" => 50, "rows" => 1, "word_limit" => "", "cond" => "", "page" => $this->event['lastpage'], "other" => 0, "html1" => "", "html2" => "" ); foreach ($matrix_array as $key => $val) $insertdata[$key] = $val; $new_seid = Save_SubEnquete("new", $insertdata); $request['seid'] = $new_seid; } else { $new_seid = Insert_Subevent($request['evid'], $this->subevents[$request['seid']]['next_seid'], $matrix_array); $request['seid'] = $new_seid; } } public function update(& $request) { //type分割(ひとつのプルダウンで二つの要素を指定している) list($request["type1"], $request["type2"]) = QuestionType::resolveTypeString($request["typeA"]); //POST["html2"]が空→タイプ別にデフォルトデザインをセット if ((ereg_replace(" | ", "", trim($request["html2"])) == "" || $_POST["main"] == "フォーム再作成") && FCheck :: isNumber($request["fel"])) { $aryDefData = Get_Design("id", 0); $aryDefData = $aryDefData[0]; //html2に入れる if ($request["type2"] === "m") { switch ($request["type1"]) { case "5" : $request["html2"] = buildmatrix($aryDefData, 0, $request["choice"], $request["title"]); break; case "6" : $request["html2"] = buildmatrix($aryDefData, 1, $request["choice"]); break; case "7" : $request["html2"] = buildmatrix($aryDefData, 2, $request["choice"]); break; } } else { $request["html2"] = QuestionType::buildForm($request, $aryDefData); } } else { $request["html2"] = $request["html2"]; } if ($request["type2"] === "m") { $request['matrix'] = $request["type1"]; $request['randomize'] = ''; list($request["type1"], $request["type2"]) = QuestionType::resolveTypeString($request["typeM"]); } else $request['matrix'] = 0; if ($request["type2"] === "c" || $request["type2"] === "t" || $request["type2"] === "n") { $request["chtable"] = ""; } if (!QuestionType::isSettableHissu($request)) { $request["hissu"] = 0; } //typeによる、width,rows,choiceの制御 //width if (QuestionType::isSettableOther($request) && $request["other"] == 0) { $request["width"] = 50; $request["rows"] = 1; $request["word_limit"] = 0; } //chice if (!QuestionType::isSettableChoice($request)) unset ($request["choice"]); if (!QuestionType::isSettableOther($request)) $request["other"] = 0; $request['page'] = $this->subevents[$request['seid']]['page']; $postError = $this->checkError($request); if (!$postError) { $request["width"] = (int) $request["width"]; $request["rows"] = (int) $request["rows"]; $request["word_limit"] = (int) $request["word_limit"]; //DBへデータ挿入・更新 if ($request['seid'] == "new") { $seid = Save_SubEnquete("new", $request); $request['seid'] = $seid; } else { Save_SubEnquete("update", $request); } } else { $this->error = $postError; } } public function checkError($request) { $result = array (); if ($request['fel'] && (!is_numeric($request['fel']) || $request['fel'] < 0)) { $result['fel'] = '<br>半角数字のみで入力して下さい。'; } elseif (!preg_match("/^[0-9]+$/", $request['fel'])) { $result['fel'] = '<br>整数で入力してください。<br>'; } elseif ($request['fel'] > count(explode(",", $request["choice"]))) { $result['fel'] = '<br>選択肢の数以下の値を入力して下さい。'; } if ($request['width'] && (!is_numeric($request['width']) || $request['width'] < 0)) { $result['width'] = '半角数字のみで入力してください。<br>'; } elseif ($request['width'] && !preg_match("/^[0-9]+$/", $request['width'])) { $result['width'] = '整数で入力してください。<br>'; } if ($request['rows'] && (!is_numeric($request['rows']) || $request['rows'] < 0)) { $result['rows'] = '半角数字のみで入力してください。<br>'; } elseif ($result['rows'] && !preg_match("/^[0-9]+$/", $request['rows'])) { $result['rows'] = '整数で入力してください。<br>'; } if ($request['word_limit'] && (!is_numeric($request['word_limit']) || $request['word_limit'] < 0)) { $result['word_limit'] = '半角数字のみで入力してください。<br>'; } elseif ($result['word_limit'] && !preg_match("/^[0-9]+$/", $request['word_limit'])) { $result['word_limit'] = '整数で入力してください。<br>'; } if ($request['width'] > 1000) { $result['width'] = '値が大きすぎます。'; } if ($request['rows'] > 1000) { $result['rows'] = '値が大きすぎます。'; } if ($request['word_limit'] > 10000) { $result['word_limit'] = '値が大きすぎます。'; } if (($request['type2'] =='r' || $request['type2'] =='c' || $request['type2'] =='p') && $request['chtable'] !== '' && count(explode(",", $request["choice"])) != count(explode(",", $request["chtable"]))) { $result['chtable'] = '<br>選択肢と同数入力して下さい'; } if ($request['choice'] === '' && in_array($request['typeA'],array('1r','1p','2c','5m','6m','7m'))) { $result['choice'] = '<br>選択肢が空欄です。'; } $ras = randomArraySort(array (), $request["randomize"]); if (FError :: is($ras)) { $result["randomize"] = '<br>書式が不正です。'; $this->data["randomize_style"] = 'display:block;'; } if ($result) $result["error"] = "入力内容にエラーがあります<br>"; return $result; } } class EnqSubeventView extends View { public function EnqSubeventView() { $this->View('./enq_subevent_template.html'); } public function getHtml(& $request, & $model) { $this->model = & $model; if (!$request['seid']) { $request['seid'] = $this->model->event['first_seid']; } if (!$request['seid']) { $request['seid'] = 'new'; } if ($this->model->event['first_seid'] && $request['seid'] === 'new') { $request['seid'] = $this->model->event['first_seid']; } if ($request['seid'] == 'new') { $this->model->subevent = array ( "seid" => "new", "evid" => $this->model->event['evid'], "title" => "新規質問", "type1" => 0, "type2" => "r", "choice" => "", "hissu" => 1, "width" => 50, "rows" => 1, "word_limit" => "", "cond" => "", "page" => $this->model->event['lastpage'], "other" => 0, "html1" => "", "html2" => "", "num" => 0 ); } else { $this->model->subevent = $this->model->subevents[$request['seid']]; } if ($model->error) { foreach ($request as $key => $val) { $this->model->subevent[$key] = $val; } } if (!$this->model->subevent['fel']) $this->model->subevent['fel'] = 1; $this->setControllSeidPage(); //次の設問、ページなどのボタンを差し替えるためのデータを用意 $this->model->errors = $model->error; //差し替え $this->HTML = preg_replace_callback('/%%%%([a-zA-Z0-9:_]+)%%%%/', array ( $this, 'ReplaceHtmlCallBack' ), $this->HTML); if (DEBUG) return $this->HTML . $this->debugHtml(); return $this->HTML; } /** * 次の設問、ページなどのボタンを差し替えるためのデータを用意 */ public function setControllSeidPage() { if ($this->model->subevent['page'] == $this->model->event['lastpage']) { $this->model->data['next_page_hidden'] = ' style=visibility:hidden'; } else { foreach ($this->model->subevents as $tmp) { if ($this->model->subevent['page'] + 1 == $tmp['page']) { $seid = $tmp['seid']; break; } } $this->model->data['next_page_seid'] = $seid; } if ($this->model->subevent['page'] == 1) { $this->model->data['pre_page_hidden'] = ' style=visibility:hidden'; } else { foreach ($this->model->subevents as $tmp) { if ($this->model->subevent['page'] - 1 == $tmp['page']) { $seid = $tmp['seid']; break; } } $this->model->data['pre_page_seid'] = $seid; } if ($this->model->subevent['num'] == $this->model->event['lastnum']) { $this->model->data['next_seid_hidden'] = ' style=visibility:hidden'; } else { $this->model->data['next_seid'] = $this->model->subevents[$this->model->subevent['seid']]['next_seid']; } if ($this->model->subevent['num'] == 1) { $this->model->data['pre_seid_hidden'] = ' style=visibility:hidden'; } else { $this->model->data['pre_seid'] = $this->model->subevents[$this->model->subevent['seid']]['pre_seid']; } $this->model->data['preview'] = DIR_ROOT . PG_PREVIEW . '?rid=' . Create_QueryString('preview0', $this->model->event['rid']) . '&page=' . $this->model->subevent['page']; } /** * subevent編集画面テンプレート内の %%%%hoge%%%%を適切なものに置き換えます。 */ public function ReplaceHTMLCallBack($match) { $keys = explode(':',$match[1]); $key = $match[1]; if ($key == 'img_path') { return DIR_IMG; } if ($key == 'PHP_SELF') { return PHP_SELF; } if ($key == 'event_name') { return replaceMessage($this->model->event['evid'].'. '.$this->model->event['name']); } if ($key == 'money_mark') { return getMoneyMark(); } if ($key == 'OPTION_ENQ_RANDOMIZE') { if(OPTION_ENQ_RANDOMIZE!=1) return " disabled"; return ""; } if ($key == 'SUBEVENT_LIST') { return $this->getHtmlSubeventList(); } if ($key == 'replace_word') { $replace_word = array('', '%%%%form%%%%', '%%%%targets%%%%', '%%%%message%%%%', '%%%%title%%%%', '%%%%num_ext%%%%', '####category1####', '####category2####'); return FForm::option2($replace_word); } if ($key == 'subevent_typeA') { $type = ($this->model->subevent['matrix'])? $this->model->subevent['matrix'] . 'm': QuestionType::createTypeString( $this->model->subevent['type1'], $this->model->subevent['type2']); return $this->getOptionTag($this->getTypeAItem(), $type); } if ($key == 'subevent_typeM') { $type = QuestionType::createTypeString( $this->model->subevent['type1'], $this->model->subevent['type2']); return $this->getOptionTag($this->getTypeMItem(), $type); } if (ereg('([a-zA-Z0-9_]+):([a-zA-Z0-9_]+)', $key, $match2)) { $array_name = $match2[1]; $key = $match2[2]; } else { $key = $match[1]; } if ($array_name == 'subevent_hissu') { if ($this->model->subevent['hissu'] == $key) { $val = ' checked'; } else { $val = ''; } } elseif ($array_name == 'subevent_other') { if ($this->model->subevent['other'] == $key) { $val = ' checked'; } else { $val = ''; } } elseif ($array_name == 'error') { return '<span style="color:red;font-size:10px">' . $this->model->errors[$key] . '</span>'; } else { $val = $this->model->{$keys[0]}[$keys[1]]; } return transHtmlentities($val); } public function getTypeAItem() { $list = QuestionType::getTypes(); $list['5m'] = 'マトリクス開始'; $list['6m'] = 'マトリクス内部'; $list['7m'] = 'マトリクス終了'; return $list; } public function getTypeMItem() { $list = QuestionType::getTypes(); return array( '1r' => $list['1r'], '2c' => $list['2c'] ); } public function getOptionTag($item, $type) { $html = array(); foreach ($item as $k => $v) { $check = ($type == $k)? ' selected': ''; $sk = transHtmlentities($k); $sv = transHtmlentities($v); $html[] = <<<__HTML__ <option value="{$sk}"{$check}>{$sv}</option> __HTML__; } return implode("\n", $html); } public function getHtmlSubeventList() { $html = ''; $prev_page = 1; foreach ($this->model->subevents as $subevent) { $class = array(); $href = PHP_SELF . '&seid=' . $subevent['seid'] . '&evid=' . $subevent['evid']; $title = strip_tags($subevent['title']); if ($title === '') { $title = '[空欄]'; } if($this->model->subevent['seid'] == $subevent['seid']) $class[] = 'selected'; if($subevent['page'] != $prev_page) $class[] = 'page_break'; $class = (count($class)>0)? ' class="'.implode(' ', $class).'"':''; $html .=<<<HTML <li{$class}><a href="{$href}" onclick="return this.flag?false:this.flag=true;">{$title}</a></li> HTML; $prev_page = $subevent['page']; } return $html; } } class EnqSubeventController extends Controller { public function EnqSubeventController(& $model, & $view) { $this->Controller($model, $view); $this->model->loadEnquete($this->request['evid']); switch ($this->mode) { case 'insertBefore' : $this->model->insertBefore($this->request); $this->model->loadEnquete($this->request['evid']); break; case 'insertAfter' : $this->model->insertAfter($this->request); $this->model->loadEnquete($this->request['evid']); break; case 'delete' : $this->model->delete($this->request); $this->model->loadEnquete($this->request['evid']); break; case 'update' : $this->model->update($this->request); if (is_good($this->request['insertAfter']) && is_null($this->model->error)) { $this->model->insertAfter($this->request); } $this->model->loadEnquete($this->request['evid']); break; default : ; } } } /***************************************************************/
mit
dwalkr/wp-admin-utility
src/Field/Password.php
2118
<?php /* * The MIT License * * Copyright 2016 DJ Walker <[email protected]>. * * 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. */ namespace dwalkr\WPAdminUtility\Field; use dwalkr\WPAdminUtility\Field; use phpseclib\Crypt; /** * Description of Text * * @author DJ */ class Password extends Field { public function render() { require $this->templateHandler->getView('field/wrapper-start'); require $this->templateHandler->getView('field/password'); require $this->templateHandler->getView('field/wrapper-end'); } public function prepareData($data) { return self::encrypt($data); } public function getFieldValue() { if (isset($this->data)) { return self::decrypt($this->data); } } public static function encrypt($data){ $cipher = new Crypt\Blowfish(); $cipher->setKey(AUTH_KEY); return base64_encode($cipher->encrypt($data)); } public static function decrypt($data){ $cipher = new Crypt\Blowfish(); $cipher->setKey(AUTH_KEY); return $cipher->decrypt(base64_decode($data)); } }
mit
AlanCezarAraujo/performance-playground
app/scripts/memory-allocation.js
1022
(() => { 'use strict'; let memoryAllocated = 0; let memoryChunk = []; let btnAllocate = document.getElementById('btnAllocate'); let btnDeallocate = document.getElementById('btnDeallocate'); let btnFreeAllMemory = document.getElementById('btnFreeAllMemory'); function allocateMemory() { memoryChunk.push(new Array(1000000 * 10).join('.')); memoryAllocated += 10; updateView(); } function deallocateMemory() { if (!memoryAllocated) return; memoryChunk.pop(); memoryAllocated -= 10; updateView(); } function freeAllMemory() { memoryChunk = []; memoryAllocated = 0; updateView(); } function updateView() { document.getElementById('totalMemoryUsed').innerText = memoryAllocated; } btnAllocate.addEventListener('click', allocateMemory); btnDeallocate.addEventListener('click', deallocateMemory); btnFreeAllMemory.addEventListener('click', freeAllMemory); })();
mit
niquola/health_seven
lib/health_seven/2.6/messages/bps_o29.rb
1649
module HealthSeven::V2_6 class BpsO29 < ::HealthSeven::Message attribute :msh, Msh, position: "MSH", require: true attribute :sfts, Array[Sft], position: "SFT", multiple: true attribute :uac, Uac, position: "UAC" attribute :ntes, Array[Nte], position: "NTE", multiple: true class Patient < ::HealthSeven::SegmentGroup attribute :pid, Pid, position: "PID", require: true attribute :pd1, Pd1, position: "PD1" attribute :ntes, Array[Nte], position: "NTE", multiple: true class PatientVisit < ::HealthSeven::SegmentGroup attribute :pv1, Pv1, position: "PV1", require: true attribute :pv2, Pv2, position: "PV2" end attribute :patient_visit, PatientVisit, position: "BPS_O29.PATIENT_VISIT" end attribute :patient, Patient, position: "BPS_O29.PATIENT" class Order < ::HealthSeven::SegmentGroup attribute :orc, Orc, position: "ORC", require: true class Timing < ::HealthSeven::SegmentGroup attribute :tq1, Tq1, position: "TQ1", require: true attribute :tq2s, Array[Tq2], position: "TQ2", multiple: true end attribute :timings, Array[Timing], position: "BPS_O29.TIMING", multiple: true attribute :bpo, Bpo, position: "BPO", require: true attribute :ntes, Array[Nte], position: "NTE", multiple: true class Product < ::HealthSeven::SegmentGroup attribute :bpx, Bpx, position: "BPX", require: true attribute :ntes, Array[Nte], position: "NTE", multiple: true end attribute :products, Array[Product], position: "BPS_O29.PRODUCT", multiple: true end attribute :orders, Array[Order], position: "BPS_O29.ORDER", require: true, multiple: true end end
mit
MrChristofferson/Farmbot-Web-API
webpack/devices/components/__tests__/os_update_button_test.tsx
3766
jest.mock("../../../device", () => ({ devices: { current: { checkUpdates: jest.fn(() => { return Promise.resolve(); }), } } })); let mockOk = jest.fn(); jest.mock("farmbot-toastr", () => ({ success: mockOk })); import * as React from "react"; import { OsUpdateButton } from "../os_update_button"; import { mount } from "enzyme"; import { bot } from "../../../__test_support__/fake_state/bot"; import { devices } from "../../../device"; describe("<OsUpdateButton/>", () => { beforeEach(function () { bot.currentOSVersion = "3.1.6"; jest.clearAllMocks(); }); it("renders buttons: not connected", () => { let buttons = mount(<OsUpdateButton bot={bot} />); expect(buttons.find("button").length).toBe(2); let autoUpdate = buttons.find("button").first(); expect(autoUpdate.hasClass("yellow")).toBeTruthy(); let osUpdateButton = buttons.find("button").last(); expect(osUpdateButton.text()).toBe("Can't Connect to release server"); }); it("up to date", () => { bot.hardware.informational_settings.controller_version = "3.1.6"; let buttons = mount(<OsUpdateButton bot={bot} />); let osUpdateButton = buttons.find("button").last(); expect(osUpdateButton.text()).toBe("UP TO DATE"); }); it("update available", () => { bot.hardware.informational_settings.controller_version = "3.1.5"; let buttons = mount(<OsUpdateButton bot={bot} />); let osUpdateButton = buttons.find("button").last(); expect(osUpdateButton.text()).toBe("UPDATE"); }); it("calls checkUpdates", () => { let { mock } = devices.current.checkUpdates as jest.Mock<{}>; let buttons = mount(<OsUpdateButton bot={bot} />); let osUpdateButton = buttons.find("button").last(); osUpdateButton.simulate("click"); expect(mock.calls.length).toEqual(1); }); it("shows update progress: bytes", () => { bot.hardware.jobs = { "FBOS_OTA": { status: "working", bytes: 300, unit: "bytes" } }; let buttons = mount(<OsUpdateButton bot={bot} />); let osUpdateButton = buttons.find("button").last(); expect(osUpdateButton.text()).toBe("300B"); }); it("shows update progress: kilobytes", () => { bot.hardware.jobs = { "FBOS_OTA": { status: "working", bytes: 30000, unit: "bytes" } }; let buttons = mount(<OsUpdateButton bot={bot} />); let osUpdateButton = buttons.find("button").last(); expect(osUpdateButton.text()).toBe("29kB"); }); it("shows update progress: megabytes", () => { bot.hardware.jobs = { "FBOS_OTA": { status: "working", bytes: 3e6, unit: "bytes" } }; let buttons = mount(<OsUpdateButton bot={bot} />); let osUpdateButton = buttons.find("button").last(); expect(osUpdateButton.text()).toBe("3MB"); }); it("shows update progress: percent", () => { bot.hardware.jobs = { "FBOS_OTA": { status: "working", percent: 10, unit: "percent" } }; let buttons = mount(<OsUpdateButton bot={bot} />); let osUpdateButton = buttons.find("button").last(); expect(osUpdateButton.text()).toBe("10%"); }); it("update success", () => { bot.hardware.jobs = { "FBOS_OTA": { status: "complete", percent: 100, unit: "percent" } }; bot.hardware.informational_settings.controller_version = "3.1.6"; let buttons = mount(<OsUpdateButton bot={bot} />); let osUpdateButton = buttons.find("button").last(); expect(osUpdateButton.text()).toBe("UP TO DATE"); }); it("update failed", () => { bot.hardware.jobs = { "FBOS_OTA": { status: "error", percent: 10, unit: "percent" } }; bot.hardware.informational_settings.controller_version = "3.1.5"; let buttons = mount(<OsUpdateButton bot={bot} />); let osUpdateButton = buttons.find("button").last(); expect(osUpdateButton.text()).toBe("UPDATE"); }); });
mit
AdrianApostolov/TelerikAcademy
Homeworks/Databases/11.EntityFramework/07.Concurrency/Properties/AssemblyInfo.cs
1404
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("07.Concurrency")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("07.Concurrency")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("c6d337d0-020c-4b6b-b49d-d1482d57fa6c")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
AndreJSON/holy-integraal
src/actor.cpp
553
#include "actor.hpp" qhi::Actor::Actor(std::string desc) { description = desc; rightAnswer = -1; } qhi::Actor::~Actor() { } std::vector<std::string> qhi::Actor::getConversationOptions(int) const { return conversationOptions; } void qhi::Actor::addConversationOption(std::string opt) { conversationOptions.push_back(opt); } bool qhi::Actor::answer(int ans) { //Kan inte vara const if(ans == rightAnswer) return true; return false; } void qhi::Actor::setAnswer(int ans) { rightAnswer = ans; } int qhi::Actor::getType() const { return 1; }
mit
jordic/k8s
cloudsqlip/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/testapi/testapi.go
8241
/* Copyright 2014 The Kubernetes Authors All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Package testapi provides a helper for retrieving the KUBE_TEST_API environment variable. package testapi import ( "fmt" "os" "strings" "github.com/jordic/k8s/cloudsqlip/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api" _ "github.com/jordic/k8s/cloudsqlip/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/install" _ "github.com/jordic/k8s/cloudsqlip/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/extensions/install" _ "github.com/jordic/k8s/cloudsqlip/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/metrics/install" "github.com/jordic/k8s/cloudsqlip/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/latest" "github.com/jordic/k8s/cloudsqlip/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/meta" "github.com/jordic/k8s/cloudsqlip/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/unversioned" apiutil "github.com/jordic/k8s/cloudsqlip/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/util" "github.com/jordic/k8s/cloudsqlip/Godeps/_workspace/src/k8s.io/kubernetes/pkg/runtime" ) var ( Groups = make(map[string]TestGroup) Default TestGroup Extensions TestGroup ) type TestGroup struct { // Name of the group Group string // Version of the group Group under test VersionUnderTest string // Group and Version. In most cases equals to Group + "/" + VersionUnverTest GroupVersionUnderTest string } func init() { kubeTestAPI := os.Getenv("KUBE_TEST_API") if kubeTestAPI != "" { testGroupVersions := strings.Split(kubeTestAPI, ",") for _, groupVersion := range testGroupVersions { // TODO: caesarxuchao: the apiutil package is hacky, it will be replaced // by a following PR. Groups[apiutil.GetGroup(groupVersion)] = TestGroup{apiutil.GetGroup(groupVersion), apiutil.GetVersion(groupVersion), groupVersion} } } // TODO: caesarxuchao: we need a central place to store all available API // groups and their metadata. if _, ok := Groups[""]; !ok { // TODO: The second latest.GroupOrDie("").GroupVersion.Version will be latest.GroupVersion after we // have multiple group support Groups[""] = TestGroup{"", latest.GroupOrDie("").GroupVersion.Version, latest.GroupOrDie("").GroupVersion.String()} } if _, ok := Groups["extensions"]; !ok { Groups["extensions"] = TestGroup{"extensions", latest.GroupOrDie("extensions").GroupVersion.Version, latest.GroupOrDie("extensions").GroupVersion.String()} } Default = Groups[""] Extensions = Groups["extensions"] } // Version returns the API version to test against, as set by the KUBE_TEST_API env var. func (g TestGroup) Version() string { return g.VersionUnderTest } // GroupAndVersion returns the API version to test against for a group, as set // by the KUBE_TEST_API env var. // Return value is in the form of "group/version". func (g TestGroup) GroupAndVersion() string { return g.GroupVersionUnderTest } func (g TestGroup) GroupVersion() *unversioned.GroupVersion { return &unversioned.GroupVersion{Group: g.Group, Version: g.VersionUnderTest} } // InternalGroupVersion returns the group,version used to identify the internal // types for this API func (g TestGroup) InternalGroupVersion() unversioned.GroupVersion { return unversioned.GroupVersion{Group: g.Group} } // Codec returns the codec for the API version to test against, as set by the // KUBE_TEST_API env var. func (g TestGroup) Codec() runtime.Codec { // TODO: caesarxuchao: Restructure the body once we have a central `latest`. interfaces, err := latest.GroupOrDie(g.Group).InterfacesFor(g.GroupVersionUnderTest) if err != nil { panic(err) } return interfaces.Codec } // Converter returns the api.Scheme for the API version to test against, as set by the // KUBE_TEST_API env var. func (g TestGroup) Converter() runtime.ObjectConvertor { // TODO: caesarxuchao: Restructure the body once we have a central `latest`. if g.Group == "" { interfaces, err := latest.GroupOrDie("").InterfacesFor(g.VersionUnderTest) if err != nil { panic(err) } return interfaces.ObjectConvertor } if g.Group == "extensions" { interfaces, err := latest.GroupOrDie("extensions").InterfacesFor(g.VersionUnderTest) if err != nil { panic(err) } return interfaces.ObjectConvertor } panic(fmt.Errorf("cannot test group %s", g.Group)) } // MetadataAccessor returns the MetadataAccessor for the API version to test against, // as set by the KUBE_TEST_API env var. func (g TestGroup) MetadataAccessor() meta.MetadataAccessor { // TODO: caesarxuchao: Restructure the body once we have a central `latest`. if g.Group == "" { interfaces, err := latest.GroupOrDie("").InterfacesFor(g.VersionUnderTest) if err != nil { panic(err) } return interfaces.MetadataAccessor } if g.Group == "extensions" { interfaces, err := latest.GroupOrDie("extensions").InterfacesFor(g.VersionUnderTest) if err != nil { panic(err) } return interfaces.MetadataAccessor } panic(fmt.Errorf("cannot test group %s", g.Group)) } // SelfLink returns a self link that will appear to be for the version Version(). // 'resource' should be the resource path, e.g. "pods" for the Pod type. 'name' should be // empty for lists. func (g TestGroup) SelfLink(resource, name string) string { if g.Group == "" { if name == "" { return fmt.Sprintf("/api/%s/%s", g.Version(), resource) } return fmt.Sprintf("/api/%s/%s/%s", g.Version(), resource, name) } else { // TODO: will need a /apis prefix once we have proper multi-group // support if name == "" { return fmt.Sprintf("/apis/%s/%s/%s", g.Group, g.Version(), resource) } return fmt.Sprintf("/apis/%s/%s/%s/%s", g.Group, g.Version(), resource, name) } } // Returns the appropriate path for the given prefix (watch, proxy, redirect, etc), resource, namespace and name. // For ex, this is of the form: // /api/v1/watch/namespaces/foo/pods/pod0 for v1. func (g TestGroup) ResourcePathWithPrefix(prefix, resource, namespace, name string) string { var path string if len(g.Group) == 0 { path = "/api/" + g.Version() } else { // TODO: switch back once we have proper multiple group support // path = "/apis/" + g.Group + "/" + Version(group...) path = "/apis/" + g.Group + "/" + g.Version() } if prefix != "" { path = path + "/" + prefix } if namespace != "" { path = path + "/namespaces/" + namespace } // Resource names are lower case. resource = strings.ToLower(resource) if resource != "" { path = path + "/" + resource } if name != "" { path = path + "/" + name } return path } // Returns the appropriate path for the given resource, namespace and name. // For example, this is of the form: // /api/v1/namespaces/foo/pods/pod0 for v1. func (g TestGroup) ResourcePath(resource, namespace, name string) string { return g.ResourcePathWithPrefix("", resource, namespace, name) } func (g TestGroup) RESTMapper() meta.RESTMapper { return latest.GroupOrDie(g.Group).RESTMapper } // Get codec based on runtime.Object func GetCodecForObject(obj runtime.Object) (runtime.Codec, error) { _, kind, err := api.Scheme.ObjectVersionAndKind(obj) if err != nil { return nil, fmt.Errorf("unexpected encoding error: %v", err) } // TODO: caesarxuchao: we should detect which group an object belongs to // by using the version returned by Schem.ObjectVersionAndKind() once we // split the schemes for internal objects. // TODO: caesarxuchao: we should add a map from kind to group in Scheme. for _, group := range Groups { if api.Scheme.Recognizes(group.GroupAndVersion(), kind) { return group.Codec(), nil } } // Codec used for unversioned types if api.Scheme.Recognizes("", kind) { return api.Codec, nil } return nil, fmt.Errorf("unexpected kind: %v", kind) }
mit
detailnet/dfw-commanding-module
src/Factory/CommandDispatcherFactory.php
2096
<?php namespace Detail\Commanding\Factory; use Interop\Container\ContainerInterface; use Zend\EventManager\ListenerAggregateInterface; use Zend\ServiceManager\Exception\ServiceNotCreatedException; use Zend\ServiceManager\Factory\FactoryInterface; use Detail\Commanding\CommandDispatcher; use Detail\Commanding\CommandHandlerManager; use Detail\Commanding\Options\ModuleOptions; class CommandDispatcherFactory implements FactoryInterface { /** * Create CommandDispatcher * * @param ContainerInterface $container * @param string $requestedName * @param array|null $options * @return CommandDispatcher */ public function __invoke(ContainerInterface $container, $requestedName, array $options = null) { /** @var ModuleOptions $moduleOptions */ $moduleOptions = $container->get(ModuleOptions::CLASS); /** @var CommandHandlerManager $commandHandlerManager */ $commandHandlerManager = $container->get(CommandHandlerManager::CLASS); $commandDispatcher = new CommandDispatcher($commandHandlerManager); $commands = $moduleOptions->getCommands(); foreach ($commands as $command) { if (!isset($command['command'])) { throw new ServiceNotCreatedException( 'Command is missing required configuration option "command"' ); } if (!isset($command['handler'])) { throw new ServiceNotCreatedException( 'Command is missing required configuration option "handler"' ); } $commandDispatcher->register($command['command'], $command['handler']); } $listeners = $moduleOptions->getListeners(); foreach ($listeners as $listenerName) { /** @todo Lazy load listeners? */ /** @var ListenerAggregateInterface $listener */ $listener = $container->get($listenerName); $listener->attach($commandDispatcher->getEventManager()); } return $commandDispatcher; } }
mit
kevoj/nodetomic-api-swagger
src/lib/swagger/config.js
1817
import swaggerJSDoc from "swagger-jsdoc"; import config from "../../config"; export default (app) => { // Initialize Swagger let options = { swaggerDefinition: { swagger: "2.0", info: config.swagger.info, basePath: `/`, schemes: ["http", "https"], securityDefinitions: { Bearer: { type: "apiKey", name: "Authorization", in: "header", description: 'The following syntax must be used in the "Authorization" header xxxxxx.yyyyyyy.zzzzzz', }, OAuth2: { type: "oauth2", flow: "implicit", authorizationUrl: `http://${config.server.ip}:${config.server.port}/auth/github`, // tokenUrl: `http://${config.server.ip}:${config.server.port}/#/token`, description: 'Copy the generated token value in the url, and paste it into "Api key authorization"', }, }, }, consumes: ["application/json"], produces: ["application/json"], apis: [`${config.base}/auth/**/*.yaml`, `${config.base}/api/**/*.yaml`], }; return swaggerJSDoc(options); // If you want use Swagger into .js = ${config.base}/**/*.js /** * @swagger * definitions: * Example: * properties: * field1: * type: string * field2: * type: string */ /** * @swagger * /api/example: * get: * tags: * - Example * description: Returns all Example's * produces: * - application/json * responses: * 200: * description: An array of Example's * schema: * type: array * items: * $ref: '/definitions/Example' * 500: * description: Invalid status value */ };
mit
lordmilko/PrtgAPI
src/PrtgAPI/Parameters/ObjectData/LogParameters.cs
6449
using System; using System.Diagnostics.CodeAnalysis; using PrtgAPI.Request; using PrtgAPI.Request.Serialization; namespace PrtgAPI.Parameters { /// <summary> /// Represents parameters used to construct a <see cref="PrtgRequestMessage"/> for retrieving <see cref="Log"/> objects. /// </summary> [ExcludeFromCodeCoverage] public class LogParameters : TableParameters<Log>, IShallowCloneable<LogParameters> { /// <summary> /// Initializes a new instance of the <see cref="LogParameters"/> class for retrieving logs between two time periods. /// </summary> /// <param name="objectId">ID of the object to retrieve logs from. If this value is null or 0, logs will be retrieved from the root group.</param> /// <param name="startDate">Start date to retrieve logs from. If this value is null, logs will be retrieved from the current date and time.</param> /// <param name="endDate">End date to retrieve logs to. If this value is null, logs will be retrieved until the beginning of all logs.</param> /// <param name="count">Number of logs to retrieve. Depending on the number of logs stored in the system, specifying a high number may cause the request to timeout.</param> /// <param name="status">Log event types to retrieve records for. If no types are specified, all record types will be retrieved.</param> public LogParameters(int? objectId, DateTime? startDate, DateTime? endDate, int? count = 500, params LogStatus[] status) : this(objectId) { Count = count; if (status != null && status.Length > 0) Status = status; if (endDate != null) EndDate = endDate; if (startDate != null) StartDate = startDate; } /// <summary> /// Initializes a new instance of the <see cref="LogParameters"/> class for retrieving logs from a standard time period. /// </summary> /// <param name="objectId">ID of the object to retrieve logs from. If this value is null or 0, logs will be retrieved from the root group.</param> /// <param name="recordAge">Time period to retrieve logs from. Logs will be retrieved from the beginning of this period until the current date and time, ordered from newest to oldest.</param> /// <param name="count">Number of logs to retrieve. Depending on the number of logs stored in the system, specifying a high number may cause the request to timeout.</param> /// <param name="status">Log event types to retrieve records for. If no types are specified, all record types will be retrieved.</param> public LogParameters(int? objectId, RecordAge recordAge = PrtgAPI.RecordAge.LastWeek, int? count = 500, params LogStatus[] status) : this(objectId) { if (recordAge != PrtgAPI.RecordAge.All) RecordAge = recordAge; Count = count; if (status != null && status.Length > 0) Status = status; } internal LogParameters(int? objectId) : base(Content.Logs) { if (objectId != null) ObjectId = objectId; //PRTG returns the same object when you start at 0 and 1, resulting in the 499th and 500th //object being duplicates. To prevent this, instead of going 0-499, 500-999 we go 1-500, 501-1000 StartOffset = 1; } /// <summary> /// Gets or sets the ID of the object these parameters should apply to. /// </summary> public int? ObjectId { get { return (int?) this[Parameter.Id]; } set { this[Parameter.Id] = value; } } /// <summary> /// Gets or sets the start date to retrieve logs from. If this value is null, logs will be retrieved from the current date and time. /// </summary> public DateTime? StartDate { get { return GetDateTime(Property.EndDate); } set { SetDateTime(Property.EndDate, value); } } /// <summary> /// Gets or sets the end date to retrieve logs to. If this value is null, logs will be retrieved until the beginning of all logs. /// </summary> public DateTime? EndDate { get { return GetDateTime(Property.StartDate); } set { SetDateTime(Property.StartDate, value); } } /// <summary> /// Gets or sets log event types to retrieve records for. If no types are specified, all record types will be retrieved. /// </summary> public LogStatus[] Status { get { return GetMultiParameterFilterValue<LogStatus>(Property.Status); } set { SetMultiParameterFilterValue(Property.Status, value); } } /// <summary> /// Gets or sets the time period to retrieve logs from. Logs will be retrieved from the beginning of this period until the current date and time, ordered from newest to oldest. /// </summary> public RecordAge? RecordAge { get { return (RecordAge?) GetFilterValue(Property.RecordAge); } set { if (value != null && value == PrtgAPI.RecordAge.All) { SetFilterValue(Property.RecordAge, null); } else SetFilterValue(Property.RecordAge, value); } } private DateTime? GetDateTime(Property property) { var val = GetFilterValue(property); if (val == null) return null; if (val is DateTime) return (DateTime?) val; //We're retrieving a DateTime we serialized previously return TypeHelpers.StringToDate(val.ToString()); } private void SetDateTime(Property property, DateTime? value) { SetFilterValue(property, value == null ? null : TypeHelpers.DateToString(value.Value)); } LogParameters IShallowCloneable<LogParameters>.ShallowClone() { var newParameters = new LogParameters(null); ShallowClone(newParameters); return newParameters; } [ExcludeFromCodeCoverage] object IShallowCloneable.ShallowClone() => ((IShallowCloneable<LogParameters>)this).ShallowClone(); } }
mit
svenyurgensson/assorted_candy
assorted_candy/fpatterns/unevaluated.rb
950
module AssortedCandy module Null class Unevaluated < ::BasicObject def ==(*); false; end def to_f; 0.0; end def to_i; 0; end def to_s; ""; end def *(*); 0; end def +(*); 0; end def -(*); 0; end def /(*); 1; end def coerce(_other) [self,_other] end def inspect "#<%s:0x%x>" % [self.class, object_id] end def method_missing(*, &_) self end def respond_to?(message, include_private=false) true end end # class Unevaluated end end UNEVAL_OBJ = AssortedCandy::Null::Unevaluated.new.freeze if __FILE__ == $0 the_entity = AssortedCandy::Null::Unevaluated.new def check predicat line = 'line' + caller()[0][/:\d+:/] puts predicat ? "#{line} proved" : "#{line} not proven" end check( (the_entity + 42) == 0 ) check( (the_entity / 42) == 1 ) end
mit
wcneto/laravel-stocks-robo-advisor
app/Alertas.php
117
<?php namespace App; class Alertas extends BaseModel { protected $table = 'vw_alerta_atual'; }
mit
Vizzuality/grid-arendal
backend/app/controllers/backend/users_controller.rb
2778
# frozen_string_literal: true require_dependency 'backend/application_controller' module Backend class UsersController < ::Backend::ApplicationController load_and_authorize_resource before_action :set_user, except: [:index, :new, :create, :paginate] before_action :set_users, only: [:index, :edit, :new] before_action :set_roles_selection, only: [:update, :create, :new, :edit] def index end def edit end def new @user = User.new end def update if @user.update(user_params) redirect_to edit_user_url(id: @user, page: params[:page]), notice: 'User updated' else @users = current_user&.admin? ? User.filter_users(user_filters) : User.filter_actives render :edit end end def create @user = User.create_with_password(user_params) if @user.save redirect_to edit_user_url(@user), notice: 'User created' else @users = current_user&.admin? ? User.filter_users(user_filters) : User.filter_actives render :new end end def destroy @user = User.find(params[:id]) if @user.destroy redirect_to users_url end end def deactivate if @user.try(:deactivate) redirect_to users_url else redirect_to user_path(@user) end end def activate if @user.try(:activate) redirect_to users_url else redirect_to user_path(@user) end end def make_admin if @user.try(:make_admin) redirect_to users_url end end def make_publisher if @user.try(:make_publisher) redirect_to users_url end end def make_contributor if @user.try(:make_contributor) redirect_to users_url end end def paginate @users = current_user&.admin? ? User.filter_users(user_filters) : User.filter_actives @items = @users.order(:first_name, :last_name) .limit(@index_items_limit) .offset(@index_items_limit * (@page - 1)) @item_id = params[:id].present? ? params[:id].to_i : nil respond_to do |format| if(@items.empty?) head :no_content end format.js { render 'backend/shared/index_items_paginate' } end end private def user_filters params.permit(:active) end def set_user @user = User.find(params[:id]) end def set_users @users = User.users(current_user&.admin?, user_filters, @search, @index_items_limit * @page) end def set_roles_selection @user_roles = User.roles.map { |r,| [r, r] } end def user_params params.require(:user).permit! end end end
mit
XanderDwyl/bjssystem
app/controllers/PageController.php
1799
<?php class PageController extends BaseController { protected $layout = "layouts.main"; public function __construct() { $this->beforeFilter('csrf', array('on'=>'post')); $this->beforeFilter('auth', array('only'=>array('showDashboard', 'showRegisterForm', 'showEmployeeForm', 'showPayrollForm', 'showCashadvanceForm', 'showSalary'))); } public function showIndex() { return Redirect::to('login'); } public function showDashboard() { $this->layout->content = View::make('pages.dashboard'); } public function showLoginForm() { if(Auth::check()) return Redirect::to('dashboard'); else $this->layout->content = View::make('pages.login'); } public function showRegisterForm() { $this->layout->content = View::make('pages.register'); } public function showEmployeeForm() { $this->layout->content = View::make('pages.employee')->with( 'employees', TransactionQuery::getEmployeeCurrentSalary('')); } public function showSalary() { $this->layout->content = View::make('pages.salary'); } public function showPayrollForm() { $this->layout->content = View::make('pages.payroll') ->with( array( 'employees' => TransactionQuery::getEmployeeCurrentSalary(''), 'payrolls' => TransactionQuery::getCashAdvances() ) ); } public function showCashadvanceForm() { $this->layout->content = View::make('pages.cashadvance') ->with( array( 'employees' => TransactionQuery::getEmployeeCurrentSalary(''), 'cashtransactions' => TransactionQuery::getCashAdvances(), 'totalCA' => TransactionQuery::getTotalCashAdvances(), 'totalCollectable' => TransactionQuery::getTotalCACollectables() ) ); } }
mit
ninjasphere/sphere-api-service
lib/web/rest/v1/errors.js
571
'use strict'; module.exports = { unknown_error: { code:500, type: 'internal_error', message:'An unknown internal error occurred.'}, not_supported: { code:400, type: 'unsupported_endpoint', message:'This endpoint is not supported.'}, signing_unavailable: { code:503, type: 'signing_unavailable', message:'Session signing is temporarily unavailable.'}, unauthorized: {code: 401, type: 'unauthorized', message: 'This API call requires authentication'}, send_error: function(res, error) { return res.json(error.code, { type: 'error', data: error }); } };
mit
COMP4711Lab5Group30/starter-todo4
application/core/MY_Model.php
9560
<?php // pull in the interface we are supposed to implement // Note that it doesn't have to follow the normal CodeIgniter naming rules! require_once 'DataMapper.php'; /** * Generic data access model, for an RDB. * * This class is called MY_Model to keep CodeIgniter happy. * * @author JLP * @copyright Copyright (c) 2010-2017, James L. Parry * ------------------------------------------------------------------------ */ class MY_Model extends CI_Model implements DataMapper { protected $_tableName; // Which table is this a model for? protected $_keyField; // name of the primary key field //--------------------------------------------------------------------------- // Housekeeping methods //--------------------------------------------------------------------------- /** * Constructor. * @param string $tablename Name of the RDB table * @param string $keyfield Name of the primary key field */ function __construct($tablename = null, $keyfield = 'id') { parent::__construct(); if ($tablename == null) $this->_tableName = get_class($this); else $this->_tableName = $tablename; $this->_keyField = $keyfield; } //--------------------------------------------------------------------------- // Utility methods //--------------------------------------------------------------------------- /** * Return the number of records in this table. * @return int The number of records in this table */ function size() { $query = $this->db->get($this->_tableName); return $query->num_rows(); } /** * Return the field names in this table, from the table metadata. * @return array(string) The field names in this table */ function fields() { return $this->db->list_fields($this->_tableName); } //--------------------------------------------------------------------------- // C R U D methods //--------------------------------------------------------------------------- // Create a new data object. // Only use this method if intending to create an empty record and then // populate it. function create() { $names = $this->db->list_fields($this->_tableName); $object = new StdClass; foreach ($names as $name) $object->$name = ""; return $object; } // Add a record to the DB function add($record) { // convert object to associative array, if needed if (is_object($record)) { $data = get_object_vars($record); } else { $data = $record; } // update the DB table appropriately $key = $data[$this->_keyField]; $object = $this->db->insert($this->_tableName, $data); } // Retrieve an existing DB record as an object function get($key, $key2 = null) { $this->db->where($this->_keyField, $key); $query = $this->db->get($this->_tableName); if ($query->num_rows() < 1) return null; return $query->row(); } // Update a record in the DB function update($record) { // convert object to associative array, if needed if (is_object($record)) { $data = get_object_vars($record); } else { $data = $record; } // update the DB table appropriately $key = $data[$this->_keyField]; $this->db->where($this->_keyField, $key); $object = $this->db->update($this->_tableName, $data); } // Delete a record from the DB function delete($key, $key2 = null) { $this->db->where($this->_keyField, $key); $object = $this->db->delete($this->_tableName); } // Determine if a key exists function exists($key, $key2 = null) { $this->db->where($this->_keyField, $key); $query = $this->db->get($this->_tableName); if ($query->num_rows() < 1) return false; return true; } //--------------------------------------------------------------------------- // Aggregate methods //--------------------------------------------------------------------------- // Return all records as an array of objects function all() { $this->db->order_by($this->_keyField, 'asc'); $query = $this->db->get($this->_tableName); return $query->result(); } // Return all records as a result set function results() { $this->db->order_by($this->_keyField, 'asc'); $query = $this->db->get($this->_tableName); return $query; } // Return the most recent records as a result set function trailing($count = 10) { $start = $this->db->count_all($this->_tableName) - $count; if ($start < 0) $start = 0; $this->db->limit($count, $start); $this->db->order_by($this->_keyField, 'asc'); $query = $this->db->get($this->_tableName); return $query; } // Return filtered records as an array of records function some($what, $which) { $this->db->order_by($this->_keyField, 'asc'); if (($what == 'period') && ($which < 9)) { $this->db->where($what, $which); // special treatment for period } else $this->db->where($what, $which); $query = $this->db->get($this->_tableName); return $query->result(); } // Determine the highest key used function highest() { $key = $this->_keyField; $this->db->select_max($key); $query = $this->db->get($this->_tableName); $result = $query->result(); if (count($result) > 0) return $result[0]->$key; else return null; } // Retrieve first record from a table. function first() { if ($this->size() < 1) return null; $query = $this->db->get($this->_tableName, 1, 1); return $query->result()[0]; } // Retrieve records from the beginning of a table. function head($count = 10) { $this->db->limit(10); $this->db->order_by($this->_keyField, 'asc'); $query = $this->db->get($this->_tableName); return $query->result(); } // Retrieve records from the end of a table. function tail($count = 10) { $start = $this->db->count_all($this->_tableName) - $count; if ($start < 0) $start = 0; $this->db->limit($count, $start); $this->db->order_by($this->_keyField, 'asc'); $query = $this->db->get($this->_tableName); return $query->result(); } // truncate the table backing this model function truncate() { $this->db->truncate($this->_tableName); } } /** * Support for RDB persistence with a compound (two column) key. */ class MY_Model2 extends MY_Model { protected $_keyField2; // second part of composite primary key // Constructor function __construct($tablename = null, $keyfield = 'id', $keyfield2 = 'part') { parent::__construct($tablename, $keyfield); $this->_keyField2 = $keyfield2; } //--------------------------------------------------------------------------- // Record-oriented functions //--------------------------------------------------------------------------- // Retrieve an existing DB record as an object function get($key1, $key2) { $this->db->where($this->_keyField, $key1); $this->db->where($this->_keyField2, $key2); $query = $this->db->get($this->_tableName); if ($query->num_rows() < 1) return null; return $query->row(); } // Update a record in the DB function update($record) { // convert object to associative array, if needed if (is_object($record)) { $data = get_object_vars($record); } else { $data = $record; } // update the DB table appropriately $key = $data[$this->_keyField]; $key2 = $data[$this->_keyField2]; $this->db->where($this->_keyField, $key); $this->db->where($this->_keyField2, $key2); $object = $this->db->update($this->_tableName, $data); } // Delete a record from the DB function delete($key1, $key2) { $this->db->where($this->_keyField, $key1); $this->db->where($this->_keyField2, $key2); $object = $this->db->delete($this->_tableName); } // Determine if a key exists function exists($key1, $key2) { $this->db->where($this->_keyField, $key1); $this->db->where($this->_keyField2, $key2); $query = $this->db->get($this->_tableName); if ($query->num_rows() < 1) return false; return true; } //--------------------------------------------------------------------------- // Composite functions //--------------------------------------------------------------------------- // Return all records associated with a member function group($key) { $this->db->where($this->_keyField, $key); $this->db->order_by($this->_keyField, 'asc'); $this->db->order_by($this->_keyField2, 'asc'); $query = $this->db->get($this->_tableName); return $query->result(); } // Delete all records associated with a member function delete_some($key) { $this->db->where($this->_keyField, $key); $object = $this->db->delete($this->_tableName); } // Determine the highest secondary key associated with a primary function highest_some($key) { $this->db->where($this->_keyField, $key); $query = $this->db->get($this->_tableName); $highest = -1; foreach ($query->result() as $record) { $key2 = $record->{$this->_keyField2}; if ($key2 > $highest) $highest = $key2; } return $highest; } //--------------------------------------------------------------------------- // Aggregate functions //--------------------------------------------------------------------------- // Return all records as an array of objects function all($primary = null) { $this->db->order_by($this->_keyField, 'asc'); $this->db->order_by($this->_keyField2, 'asc'); $query = $this->db->get($this->_tableName); return $query->result(); } } // Include any other persistence implementations, so that they can be used // as base models for any in a webapp. include_once 'RDB_Model.php'; // backed by an RDB include_once 'Memory_Model.php'; // In-memory only include_once 'CSV_Model.php'; // CSV persisted include_once 'XML_Model.php'; // xml persisted
mit
SkillsFundingAgency/das-employerapprenticeshipsservice
src/SFA.DAS.EmployerAccounts/Commands/UnsubscribeProviderEmail/UnsubscribeProviderEmailQuery.cs
228
using System; using MediatR; namespace SFA.DAS.EmployerAccounts.Commands.UnsubscribeProviderEmail { public class UnsubscribeProviderEmailQuery : IAsyncRequest { public Guid CorrelationId { get; set; } } }
mit
TheTastyCactus/CactusCoin
src/qt/locale/bitcoin_it.ts
116609
<?xml version="1.0" ?><!DOCTYPE TS><TS language="it" version="2.0"> <defaultcodec>UTF-8</defaultcodec> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About Cactuscoin</source> <translation>Info su Cactuscoin</translation> </message> <message> <location line="+39"/> <source>&lt;b&gt;Cactuscoin&lt;/b&gt; version</source> <translation>Versione di &lt;b&gt;Cactuscoin&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 ([email protected]) and UPnP software written by Thomas Bernard.</source> <translation> Questo è un software sperimentale. Distribuito sotto la licenza software MIT/X11, vedi il file COPYING incluso oppure su http://www.opensource.org/licenses/mit-license.php. Questo prodotto include software sviluppato dal progetto OpenSSL per l&apos;uso del Toolkit OpenSSL (http://www.openssl.org/), software crittografico scritto da Eric Young ([email protected]) e software UPnP scritto da Thomas Bernard.</translation> </message> <message> <location filename="../aboutdialog.cpp" line="+14"/> <source>Copyright</source> <translation>Copyright</translation> </message> <message> <location line="+0"/> <source>The Cactuscoin developers</source> <translation>Sviluppatori di Cactuscoin</translation> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation>Rubrica</translation> </message> <message> <location line="+19"/> <source>Double-click to edit address or label</source> <translation>Fai doppio click per modificare o cancellare l&apos;etichetta</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>Crea un nuovo indirizzo</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Copia l&apos;indirizzo attualmente selezionato nella clipboard</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation>&amp;Nuovo indirizzo</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+63"/> <source>These are your Cactuscoin 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>Questi sono i tuoi indirizzi Cactuscoin per ricevere pagamenti. Potrai darne uno diverso ad ognuno per tenere così traccia di chi ti sta pagando.</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>&amp;Copy Address</source> <translation>&amp;Copia l&apos;indirizzo</translation> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation>Mostra il codice &amp;QR</translation> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a Cactuscoin address</source> <translation>Firma un messaggio per dimostrare di possedere questo indirizzo</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>Firma il &amp;messaggio</translation> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation>Cancella l&apos;indirizzo attualmente selezionato dalla lista</translation> </message> <message> <location line="+27"/> <source>Export the data in the current tab to a file</source> <translation>Esporta i dati nella tabella corrente su un file</translation> </message> <message> <location line="+3"/> <source>&amp;Export</source> <translation>&amp;Esporta...</translation> </message> <message> <location line="-44"/> <source>Verify a message to ensure it was signed with a specified Cactuscoin address</source> <translation>Verifica un messaggio per accertarsi che sia firmato con un indirizzo Cactuscoin specifico</translation> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation>&amp;Verifica Messaggio</translation> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>&amp;Cancella</translation> </message> <message> <location filename="../addressbookpage.cpp" line="-5"/> <source>These are your Cactuscoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Copy &amp;Label</source> <translation>Copia &amp;l&apos;etichetta</translation> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation>&amp;Modifica</translation> </message> <message> <location line="+1"/> <source>Send &amp;Coins</source> <translation>Invia &amp;Cactuscoin</translation> </message> <message> <location line="+260"/> <source>Export Address Book Data</source> <translation>Esporta gli indirizzi della rubrica</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Testo CSV (*.csv)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation>Errore nell&apos;esportazione</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Impossibile scrivere sul file %1.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>Etichetta</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Indirizzo</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(nessuna etichetta)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation>Finestra passphrase</translation> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>Inserisci la passphrase</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>Nuova passphrase</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>Ripeti la passphrase</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>Inserisci la passphrase per il portamonete.&lt;br/&gt;Per piacere usare unapassphrase di &lt;b&gt;10 o più caratteri casuali&lt;/b&gt;, o &lt;b&gt;otto o più parole&lt;/b&gt;.</translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>Cifra il portamonete</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Quest&apos;operazione necessita della passphrase per sbloccare il portamonete.</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>Sblocca il portamonete</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Quest&apos;operazione necessita della passphrase per decifrare il portamonete,</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>Decifra il portamonete</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>Cambia la passphrase</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Inserisci la vecchia e la nuova passphrase per il portamonete.</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>Conferma la cifratura del portamonete</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 CACTUSCOINS&lt;/b&gt;!</source> <translation>Attenzione: se si cifra il portamonete e si perde la frase d&apos;ordine, &lt;b&gt;SI PERDERANNO TUTTI I PROPRI CACTUSCOIN&lt;/b&gt;!</translation> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation>Si è sicuri di voler cifrare il portamonete?</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: qualsiasi backup del portafoglio effettuato precedentemente dovrebbe essere sostituito con il file del portafoglio criptato appena generato. Per ragioni di sicurezza, i backup precedenti del file del portafoglio non criptato diventeranno inservibili non appena si inizi ad usare il nuovo portafoglio criptato.</translation> </message> <message> <location line="+100"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation>Attenzione: tasto Blocco maiuscole attivo.</translation> </message> <message> <location line="-130"/> <location line="+58"/> <source>Wallet encrypted</source> <translation>Portamonete cifrato</translation> </message> <message> <location line="-56"/> <source>Cactuscoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your cactuscoins from being stolen by malware infecting your computer.</source> <translation>Cactuscoin verrà ora chiuso per finire il processo di crittazione. Ricorda che criptare il tuo portamonete non può fornire una protezione totale contro furti causati da malware che dovessero infettare il tuo computer.</translation> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+42"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>Cifratura del portamonete fallita</translation> </message> <message> <location line="-54"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Cifratura del portamonete fallita a causa di un errore interno. Il portamonete non è stato cifrato.</translation> </message> <message> <location line="+7"/> <location line="+48"/> <source>The supplied passphrases do not match.</source> <translation>Le passphrase inserite non corrispondono.</translation> </message> <message> <location line="-37"/> <source>Wallet unlock failed</source> <translation>Sblocco del portamonete fallito</translation> </message> <message> <location line="+1"/> <location line="+11"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>La passphrase inserita per la decifrazione del portamonete è errata.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>Decifrazione del portamonete fallita</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation>Passphrase del portamonete modificata con successo.</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+233"/> <source>Sign &amp;message...</source> <translation>Firma il &amp;messaggio...</translation> </message> <message> <location line="+280"/> <source>Synchronizing with network...</source> <translation>Sto sincronizzando con la rete...</translation> </message> <message> <location line="-349"/> <source>&amp;Overview</source> <translation>&amp;Sintesi</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation>Mostra lo stato generale del portamonete</translation> </message> <message> <location line="+20"/> <source>&amp;Transactions</source> <translation>&amp;Transazioni</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>Cerca nelle transazioni</translation> </message> <message> <location line="+7"/> <source>Edit the list of stored addresses and labels</source> <translation>Modifica la lista degli indirizzi salvati e delle etichette</translation> </message> <message> <location line="-14"/> <source>Show the list of addresses for receiving payments</source> <translation>Mostra la lista di indirizzi su cui ricevere pagamenti</translation> </message> <message> <location line="+31"/> <source>E&amp;xit</source> <translation>&amp;Esci</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>Chiudi applicazione</translation> </message> <message> <location line="+4"/> <source>Show information about Cactuscoin</source> <translation>Mostra informazioni su Cactuscoin</translation> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>Informazioni su &amp;Qt</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>Mostra informazioni su Qt</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>&amp;Opzioni...</translation> </message> <message> <location line="+6"/> <source>&amp;Encrypt Wallet...</source> <translation>&amp;Cifra il portamonete...</translation> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation>&amp;Backup Portamonete...</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>&amp;Cambia la passphrase...</translation> </message> <message> <location line="+285"/> <source>Importing blocks from disk...</source> <translation>Importa blocchi dal disco...</translation> </message> <message> <location line="+3"/> <source>Reindexing blocks on disk...</source> <translation>Re-indicizzazione blocchi su disco...</translation> </message> <message> <location line="-347"/> <source>Send coins to a Cactuscoin address</source> <translation>Invia monete ad un indirizzo cactuscoin</translation> </message> <message> <location line="+49"/> <source>Modify configuration options for Cactuscoin</source> <translation>Modifica configurazione opzioni per cactuscoin</translation> </message> <message> <location line="+9"/> <source>Backup wallet to another location</source> <translation>Backup portamonete in un&apos;altra locazione</translation> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>Cambia la passphrase per la cifratura del portamonete</translation> </message> <message> <location line="+6"/> <source>&amp;Debug window</source> <translation>Finestra &amp;Debug</translation> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation>Apri la console di degugging e diagnostica</translation> </message> <message> <location line="-4"/> <source>&amp;Verify message...</source> <translation>&amp;Verifica messaggio...</translation> </message> <message> <location line="-165"/> <location line="+530"/> <source>Cactuscoin</source> <translation>Cactuscoin</translation> </message> <message> <location line="-530"/> <source>Wallet</source> <translation>Portamonete</translation> </message> <message> <location line="+101"/> <source>&amp;Send</source> <translation>&amp;Spedisci</translation> </message> <message> <location line="+7"/> <source>&amp;Receive</source> <translation>&amp;Ricevi</translation> </message> <message> <location line="+14"/> <source>&amp;Addresses</source> <translation>&amp;Indirizzi</translation> </message> <message> <location line="+22"/> <source>&amp;About Cactuscoin</source> <translation>&amp;Info su Cactuscoin</translation> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation>&amp;Mostra/Nascondi</translation> </message> <message> <location line="+1"/> <source>Show or hide the main Window</source> <translation>Mostra o nascondi la Finestra principale</translation> </message> <message> <location line="+3"/> <source>Encrypt the private keys that belong to your wallet</source> <translation>Crittografa le chiavi private che appartengono al tuo portafoglio</translation> </message> <message> <location line="+7"/> <source>Sign messages with your Cactuscoin addresses to prove you own them</source> <translation>Firma i messaggi con il tuo indirizzo Cactuscoin per dimostrare di possederli</translation> </message> <message> <location line="+2"/> <source>Verify messages to ensure they were signed with specified Cactuscoin addresses</source> <translation>Verifica i messaggi per accertarsi che siano stati firmati con gli indirizzi Cactuscoin specificati</translation> </message> <message> <location line="+28"/> <source>&amp;File</source> <translation>&amp;File</translation> </message> <message> <location line="+7"/> <source>&amp;Settings</source> <translation>&amp;Impostazioni</translation> </message> <message> <location line="+6"/> <source>&amp;Help</source> <translation>&amp;Aiuto</translation> </message> <message> <location line="+9"/> <source>Tabs toolbar</source> <translation>Barra degli strumenti &quot;Tabs&quot;</translation> </message> <message> <location line="+17"/> <location line="+10"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> <message> <location line="+47"/> <source>Cactuscoin client</source> <translation>Cactuscoin client</translation> </message> <message numerus="yes"> <location line="+141"/> <source>%n active connection(s) to Cactuscoin network</source> <translation><numerusform>%n connessione attiva alla rete Cactuscoin</numerusform><numerusform>%n connessioni attive alla rete Cactuscoin</numerusform></translation> </message> <message> <location line="+22"/> <source>No block source available...</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Processed %1 of %2 (estimated) blocks of transaction history.</source> <translation>Processati %1 di %2 (circa) blocchi della cronologia transazioni.</translation> </message> <message> <location line="+4"/> <source>Processed %1 blocks of transaction history.</source> <translation>Processati %1 blocchi della cronologia transazioni.</translation> </message> <message numerus="yes"> <location line="+20"/> <source>%n hour(s)</source> <translation><numerusform>%n ora</numerusform><numerusform>%n ore</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation><numerusform>%n giorno</numerusform><numerusform>%n giorni</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n week(s)</source> <translation><numerusform>%n settimana</numerusform><numerusform>%n settimane</numerusform></translation> </message> <message> <location line="+4"/> <source>%1 behind</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Last received block was generated %1 ago.</source> <translation>L&apos;ultimo blocco ricevuto è stato generato %1 fa.</translation> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Error</source> <translation>Errore</translation> </message> <message> <location line="+3"/> <source>Warning</source> <translation>Attenzione</translation> </message> <message> <location line="+3"/> <source>Information</source> <translation>Informazione</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>Questa transazione è superiore al limite di dimensione. È comunque possibile inviarla con una commissione di %1, che va ai nodi che processano la tua transazione e contribuisce a sostenere la rete. Vuoi pagare la commissione?</translation> </message> <message> <location line="-140"/> <source>Up to date</source> <translation>Aggiornato</translation> </message> <message> <location line="+31"/> <source>Catching up...</source> <translation>In aggiornamento...</translation> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation>Conferma compenso transazione</translation> </message> <message> <location line="+8"/> <source>Sent transaction</source> <translation>Transazione inviata</translation> </message> <message> <location line="+0"/> <source>Incoming transaction</source> <translation>Transazione ricevuta</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>Data: %1 Quantità: %2 Tipo: %3 Indirizzo: %4 </translation> </message> <message> <location line="+33"/> <location line="+23"/> <source>URI handling</source> <translation>Gestione URI</translation> </message> <message> <location line="-23"/> <location line="+23"/> <source>URI can not be parsed! This can be caused by an invalid Cactuscoin address or malformed URI parameters.</source> <translation>Impossibile interpretare l&apos;URI! Ciò può essere causato da un indirizzo Cactuscoin invalido o da parametri URI non corretti.</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>Il portamonete è &lt;b&gt;cifrato&lt;/b&gt; e attualmente &lt;b&gt;sbloccato&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>Il portamonete è &lt;b&gt;cifrato&lt;/b&gt; e attualmente &lt;b&gt;bloccato&lt;/b&gt;</translation> </message> <message> <location filename="../bitcoin.cpp" line="+111"/> <source>A fatal error occurred. Cactuscoin can no longer continue safely and will quit.</source> <translation>Riscontrato un errore irreversibile. Cactuscoin non può più continuare in sicurezza e verrà terminato.</translation> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+104"/> <source>Network Alert</source> <translation>Avviso di rete</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>Modifica l&apos;indirizzo</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>&amp;Etichetta</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation>L&apos;etichetta associata a questo indirizzo nella rubrica</translation> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>&amp;Indirizzo</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>L&apos;indirizzo associato a questa voce della rubrica. Si può modificare solo negli indirizzi di spedizione.</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation>Nuovo indirizzo di ricezione</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>Nuovo indirizzo d&apos;invio</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>Modifica indirizzo di ricezione</translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>Modifica indirizzo d&apos;invio</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>L&apos;indirizzo inserito &quot;%1&quot; è già in rubrica.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid Cactuscoin address.</source> <translation>L&apos;indirizzo inserito &quot;%1&quot; non è un indirizzo cactuscoin valido.</translation> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>Impossibile sbloccare il portamonete.</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>Generazione della nuova chiave non riuscita.</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+424"/> <location line="+12"/> <source>Cactuscoin-Qt</source> <translation>Cactuscoin-Qt</translation> </message> <message> <location line="-12"/> <source>version</source> <translation>versione</translation> </message> <message> <location line="+2"/> <source>Usage:</source> <translation>Utilizzo:</translation> </message> <message> <location line="+1"/> <source>command-line options</source> <translation>opzioni riga di comando</translation> </message> <message> <location line="+4"/> <source>UI options</source> <translation>UI opzioni</translation> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation>Imposta lingua, ad esempio &quot;it_IT&quot; (predefinita: lingua di sistema)</translation> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation>Parti in icona </translation> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation>Mostra finestra di presentazione all&apos;avvio (default: 1)</translation> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>Opzioni</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation>&amp;Principale</translation> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation>Paga la &amp;commissione</translation> </message> <message> <location line="+31"/> <source>Automatically start Cactuscoin after logging in to the system.</source> <translation>Avvia automaticamente Cactuscoin all&apos;accensione del computer</translation> </message> <message> <location line="+3"/> <source>&amp;Start Cactuscoin on system login</source> <translation>&amp;Fai partire Cactuscoin all&apos;avvio del sistema</translation> </message> <message> <location line="+35"/> <source>Reset all client options to default.</source> <translation>Ripristina tutte le opzioni del client alle predefinite.</translation> </message> <message> <location line="+3"/> <source>&amp;Reset Options</source> <translation>&amp;Ripristina Opzioni</translation> </message> <message> <location line="+13"/> <source>&amp;Network</source> <translation>Rete</translation> </message> <message> <location line="+6"/> <source>Automatically open the Cactuscoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation>Apri automaticamente la porta del client Cactuscoin sul router. Questo funziona solo se il router supporta UPnP ed è abilitato.</translation> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation>Mappa le porte tramite l&apos;&amp;UPnP</translation> </message> <message> <location line="+7"/> <source>Connect to the Cactuscoin network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation>Connettiti alla rete Bitcon attraverso un proxy SOCKS (ad esempio quando ci si collega via Tor)</translation> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation>&amp;Collegati tramite SOCKS proxy:</translation> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation>&amp;IP del proxy:</translation> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation>Indirizzo IP del proxy (ad esempio 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 del proxy (es. 9050)</translation> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation>SOCKS &amp;Version:</translation> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation>Versione SOCKS del proxy (es. 5)</translation> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation>&amp;Finestra</translation> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation>Mostra solo un&apos;icona nel tray quando si minimizza la finestra</translation> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>&amp;Minimizza sul tray invece che sulla barra delle applicazioni</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>Riduci ad icona, invece di uscire dall&apos;applicazione quando la finestra viene chiusa. Quando questa opzione è attivata, l&apos;applicazione verrà chiusa solo dopo aver selezionato Esci nel menu.</translation> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation>M&amp;inimizza alla chiusura</translation> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation>&amp;Mostra</translation> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation>&amp;Lingua Interfaccia Utente:</translation> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting Cactuscoin.</source> <translation>La lingua dell&apos;interfaccia utente può essere impostata qui. L&apos;impostazione avrà effetto dopo il riavvio di Cactuscoin.</translation> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation>&amp;Unità di misura degli importi in:</translation> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>Scegli l&apos;unità di suddivisione di default per l&apos;interfaccia e per l&apos;invio di monete</translation> </message> <message> <location line="+9"/> <source>Whether to show Cactuscoin addresses in the transaction list or not.</source> <translation>Se mostrare l&apos;indirizzo Cactuscoin nella transazione o meno.</translation> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation>&amp;Mostra gli indirizzi nella lista delle transazioni</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;Cancella</translation> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation>&amp;Applica</translation> </message> <message> <location filename="../optionsdialog.cpp" line="+53"/> <source>default</source> <translation>default</translation> </message> <message> <location line="+130"/> <source>Confirm options reset</source> <translation>Conferma ripristino opzioni</translation> </message> <message> <location line="+1"/> <source>Some settings may require a client restart to take effect.</source> <translation>Alcune modifiche necessitano del riavvio del programma per essere salvate.</translation> </message> <message> <location line="+0"/> <source>Do you want to proceed?</source> <translation>Vuoi procedere?</translation> </message> <message> <location line="+42"/> <location line="+9"/> <source>Warning</source> <translation>Attenzione</translation> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting Cactuscoin.</source> <translation>L&apos;impostazione avrà effetto dopo il riavvio di Cactuscoin.</translation> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation>L&apos;indirizzo proxy che hai fornito è invalido.</translation> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>Modulo</translation> </message> <message> <location line="+50"/> <location line="+166"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the Cactuscoin network after a connection is established, but this process has not completed yet.</source> <translation>Le informazioni visualizzate sono datate. Il tuo partafogli verrà sincronizzato automaticamente con il network Cactuscoin dopo che la connessione è stabilita, ma questo processo non può essere completato ora.</translation> </message> <message> <location line="-124"/> <source>Balance:</source> <translation>Saldo</translation> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation>Non confermato:</translation> </message> <message> <location line="-78"/> <source>Wallet</source> <translation>Portamonete</translation> </message> <message> <location line="+107"/> <source>Immature:</source> <translation>Immaturo:</translation> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation>Importo scavato che non è ancora maturato</translation> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Transazioni recenti&lt;/b&gt;</translation> </message> <message> <location line="-101"/> <source>Your current balance</source> <translation>Saldo attuale</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>Totale delle transazioni in corso di conferma, che non sono ancora incluse nel saldo attuale</translation> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation>fuori sincrono</translation> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+107"/> <source>Cannot start cactuscoin: click-to-pay handler</source> <translation type="unfinished"/> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation>Codice QR di dialogo</translation> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation>Richiedi pagamento</translation> </message> <message> <location line="+56"/> <source>Amount:</source> <translation>Importo:</translation> </message> <message> <location line="-44"/> <source>Label:</source> <translation>Etichetta:</translation> </message> <message> <location line="+19"/> <source>Message:</source> <translation>Messaggio:</translation> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation>&amp;Salva come...</translation> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation>Errore nella codifica URI nel codice QR</translation> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation>L&apos;importo specificato non è valido, prego verificare.</translation> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation>L&apos;URI risulta troppo lungo, prova a ridurre il testo nell&apos;etichetta / messaggio.</translation> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation>Salva codice QR</translation> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation>Immagini PNG (*.png)</translation> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation>Nome del client</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>Versione client</translation> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation>&amp;Informazione</translation> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation>Versione OpenSSL in uso</translation> </message> <message> <location line="+49"/> <source>Startup time</source> <translation>Tempo di avvio</translation> </message> <message> <location line="+29"/> <source>Network</source> <translation>Rete</translation> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation>Numero connessioni</translation> </message> <message> <location line="+23"/> <source>On testnet</source> <translation>Nel testnet</translation> </message> <message> <location line="+23"/> <source>Block chain</source> <translation>Block chain</translation> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation>Numero attuale di blocchi</translation> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation>Numero totale stimato di blocchi</translation> </message> <message> <location line="+23"/> <source>Last block time</source> <translation>Ora dell blocco piu recente</translation> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation>&amp;Apri</translation> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation>opzioni riga di comando</translation> </message> <message> <location line="+7"/> <source>Show the Cactuscoin-Qt help message to get a list with possible Cactuscoin command-line options.</source> <translation>Mostra il messaggio di aiuto di Cactuscoin-QT per avere la lista di tutte le opzioni della riga di comando di Cactuscoin.</translation> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation>&amp;Mostra</translation> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation>&amp;Console</translation> </message> <message> <location line="-260"/> <source>Build date</source> <translation>Data di creazione</translation> </message> <message> <location line="-104"/> <source>Cactuscoin - Debug window</source> <translation>Cactuscoin - Finestra debug</translation> </message> <message> <location line="+25"/> <source>Cactuscoin Core</source> <translation type="unfinished"/> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation>File log del Debug</translation> </message> <message> <location line="+7"/> <source>Open the Cactuscoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation>Apri il file di log del debug di Cactuscoin dalla cartella attuale. Può richiedere alcuni secondi per file di log grandi.</translation> </message> <message> <location line="+102"/> <source>Clear console</source> <translation>Svuota console</translation> </message> <message> <location filename="../rpcconsole.cpp" line="-30"/> <source>Welcome to the Cactuscoin RPC console.</source> <translation>Benvenuto nella console RPC di Cactuscoin</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>Usa le frecce direzionali per navigare la cronologia, and &lt;b&gt;Ctrl-L&lt;/b&gt; per cancellarla.</translation> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation>Scrivi &lt;b&gt;help&lt;/b&gt; per un riassunto dei comandi disponibili</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>Spedisci Cactuscoin</translation> </message> <message> <location line="+50"/> <source>Send to multiple recipients at once</source> <translation>Spedisci a diversi beneficiari in una volta sola</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation>&amp;Aggiungi beneficiario</translation> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation>Rimuovi tutti i campi della transazione</translation> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation>Cancella &amp;tutto</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>Conferma la spedizione</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>&amp;Spedisci</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; to %2 (%3)</translation> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation>Conferma la spedizione di cactuscoin</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation>Si è sicuri di voler spedire %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>L&apos;indirizzo del beneficiario non è valido, per cortesia controlla.</translation> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>L&apos;importo da pagare dev&apos;essere maggiore di 0.</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation>L&apos;importo è superiore al saldo attuale</translation> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>Il totale è superiore al saldo attuale includendo la commissione %1.</translation> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation>Trovato un indirizzo doppio, si può spedire solo una volta a ciascun indirizzo in una singola operazione.</translation> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed!</source> <translation>Errore: Creazione transazione fallita!</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>Errore: la transazione è stata rifiutata. Ciò accade se alcuni cactuscoin nel portamonete sono stati già spesi, ad esempio se è stata usata una copia del file wallet.dat e i cactuscoin sono stati spesi dalla copia ma non segnati come spesi qui.</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation>Modulo</translation> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>&amp;Importo:</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>Paga &amp;a:</translation> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>L&apos;indirizzo del beneficiario a cui inviare il pagamento (ad esempio 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>Inserisci un&apos;etichetta per questo indirizzo, per aggiungerlo nella rubrica</translation> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation>&amp;Etichetta</translation> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation>Scegli l&apos;indirizzo dalla rubrica</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>Incollare l&apos;indirizzo dagli appunti</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>Rimuovere questo beneficiario</translation> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a Cactuscoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Inserisci un indirizzo Cactuscoin (ad esempio Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation>Firme - Firma / Verifica un messaggio</translation> </message> <message> <location line="+13"/> <source>&amp;Sign Message</source> <translation>&amp;Firma il messaggio</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>Puoi firmare messeggi con i tuoi indirizzi per dimostrare che sono tuoi. Fai attenzione a non firmare niente di vago, visto che gli attacchi di phishing potrebbero cercare di spingerti a mettere la tua firma su di loro. Firma solo dichiarazioni completamente dettagliate con cui sei d&apos;accordo.</translation> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Inserisci un indirizzo Cactuscoin (ad esempio Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="+10"/> <location line="+213"/> <source>Choose an address from the address book</source> <translation>Scegli l&apos;indirizzo dalla rubrica</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>Incollare l&apos;indirizzo dagli appunti</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>Inserisci qui il messaggio che vuoi firmare</translation> </message> <message> <location line="+7"/> <source>Signature</source> <translation>Firma</translation> </message> <message> <location line="+27"/> <source>Copy the current signature to the system clipboard</source> <translation>Copia la firma corrente nella clipboard</translation> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this Cactuscoin address</source> <translation>Firma un messaggio per dimostrare di possedere questo indirizzo</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>Firma &amp;messaggio</translation> </message> <message> <location line="+14"/> <source>Reset all sign message fields</source> <translation>Reimposta tutti i campi della firma</translation> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation>Cancella &amp;tutto</translation> </message> <message> <location line="-87"/> <source>&amp;Verify Message</source> <translation>&amp;Verifica Messaggio</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 type="unfinished"/> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Inserisci un indirizzo Cactuscoin (ad esempio Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified Cactuscoin address</source> <translation>Verifica il messaggio per assicurarsi che sia stato firmato con l&apos;indirizzo Cactuscoin specificato</translation> </message> <message> <location line="+3"/> <source>Verify &amp;Message</source> <translation>&amp;Verifica Messaggio</translation> </message> <message> <location line="+14"/> <source>Reset all verify message fields</source> <translation>Reimposta tutti i campi della verifica messaggio</translation> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a Cactuscoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Inserisci un indirizzo Cactuscoin (ad esempio Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation>Clicca &quot;Firma il messaggio&quot; per ottenere la firma</translation> </message> <message> <location line="+3"/> <source>Enter Cactuscoin signature</source> <translation>Inserisci firma Cactuscoin</translation> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation>L&apos;indirizzo inserito non è valido.</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>Per favore controlla l&apos;indirizzo e prova ancora</translation> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation>L&apos;indirizzo cactuscoin inserito non è associato a nessuna chiave.</translation> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation>Sblocco del portafoglio annullato.</translation> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation>La chiave privata per l&apos;indirizzo inserito non è disponibile.</translation> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation>Firma messaggio fallita.</translation> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation>Messaggio firmato.</translation> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation>Non è stato possibile decodificare la firma.</translation> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation>Per favore controlla la firma e prova ancora.</translation> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation>La firma non corrisponde al sunto del messaggio.</translation> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation>Verifica messaggio fallita.</translation> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation>Messaggio verificato.</translation> </message> </context> <context> <name>SplashScreen</name> <message> <location filename="../splashscreen.cpp" line="+22"/> <source>The Cactuscoin developers</source> <translation>Sviluppatori di Cactuscoin</translation> </message> <message> <location line="+1"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+20"/> <source>Open until %1</source> <translation>Aperto fino a %1</translation> </message> <message> <location line="+6"/> <source>%1/offline</source> <translation>%1/offline</translation> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/non confermato</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 conferme</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation>Stato</translation> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation><numerusform>, trasmesso attraverso %n nodo</numerusform><numerusform>, trasmesso attraverso %n nodi</numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation>Sorgente</translation> </message> <message> <location line="+0"/> <source>Generated</source> <translation>Generato</translation> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation>Da</translation> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation>A</translation> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation>proprio indirizzo</translation> </message> <message> <location line="-2"/> <source>label</source> <translation>etichetta</translation> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation>Credito</translation> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation><numerusform>matura in %n ulteriore blocco</numerusform><numerusform>matura in altri %n blocchi</numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation>non accettate</translation> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation>Debito</translation> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation>Tranzakciós díj</translation> </message> <message> <location line="+16"/> <source>Net amount</source> <translation>Importo netto</translation> </message> <message> <location line="+6"/> <source>Message</source> <translation>Messaggio</translation> </message> <message> <location line="+2"/> <source>Comment</source> <translation>Commento</translation> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation>ID della transazione</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>Bisogna attendere 120 blocchi prima di spendere I cactuscoin generati. Quando è stato generato questo blocco, è stato trasmesso alla rete per aggiungerlo alla catena di blocchi. Se non riesce a entrare nella catena, verrà modificato in &quot;non accettato&quot; e non sarà spendibile. Questo può accadere a volte, se un altro nodo genera un blocco entro pochi secondi del tuo.</translation> </message> <message> <location line="+7"/> <source>Debug information</source> <translation>Informazione di debug</translation> </message> <message> <location line="+8"/> <source>Transaction</source> <translation>Transazione</translation> </message> <message> <location line="+3"/> <source>Inputs</source> <translation>Input</translation> </message> <message> <location line="+23"/> <source>Amount</source> <translation>Importo</translation> </message> <message> <location line="+1"/> <source>true</source> <translation>vero</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>, non è stato ancora trasmesso con successo</translation> </message> <message numerus="yes"> <location line="-35"/> <source>Open for %n more block(s)</source> <translation><numerusform>Aperto per %n altro blocco</numerusform><numerusform>Aperto per altri %n blocchi</numerusform></translation> </message> <message> <location line="+70"/> <source>unknown</source> <translation>sconosciuto</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>Dettagli sulla transazione</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>Questo pannello mostra una descrizione dettagliata della transazione</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>Indirizzo</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>Importo</translation> </message> <message numerus="yes"> <location line="+57"/> <source>Open for %n more block(s)</source> <translation><numerusform>Aperto per %n altro blocco</numerusform><numerusform>Aperto per altri %n blocchi</numerusform></translation> </message> <message> <location line="+3"/> <source>Open until %1</source> <translation>Aperto fino a %1</translation> </message> <message> <location line="+3"/> <source>Offline (%1 confirmations)</source> <translation>Offline (%1 conferme)</translation> </message> <message> <location line="+3"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation>Non confermati (%1 su %2 conferme)</translation> </message> <message> <location line="+3"/> <source>Confirmed (%1 confirmations)</source> <translation>Confermato (%1 conferme)</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>Il saldo generato sarà disponibile quando maturerà in %n altro blocco</numerusform><numerusform>Il saldo generato sarà disponibile quando maturerà in altri %n blocchi</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>Questo blocco non è stato ricevuto da altri nodi e probabilmente non sarà accettato!</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>Generati, ma non accettati</translation> </message> <message> <location line="+43"/> <source>Received with</source> <translation>Ricevuto tramite</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>Ricevuto da</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>Spedito a</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>Pagamento a te stesso</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>Ottenuto dal mining</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>(N / a)</translation> </message> <message> <location line="+199"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Stato della transazione. Passare con il mouse su questo campo per vedere il numero di conferme.</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>Data e ora in cui la transazione è stata ricevuta.</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>Tipo di transazione.</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>Indirizzo di destinazione della transazione.</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>Importo rimosso o aggiunto al saldo.</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+52"/> <location line="+16"/> <source>All</source> <translation>Tutti</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>Oggi</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>Questa settimana</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>Questo mese</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>Il mese scorso</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>Quest&apos;anno</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>Intervallo...</translation> </message> <message> <location line="+11"/> <source>Received with</source> <translation>Ricevuto tramite</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>Spedito a</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>A te</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>Ottenuto dal mining</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>Altro</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>Inserisci un indirizzo o un&apos;etichetta da cercare</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>Importo minimo</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>Copia l&apos;indirizzo</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Copia l&apos;etichetta</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Copia l&apos;importo</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>Modifica l&apos;etichetta</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation>Mostra i dettagli della transazione</translation> </message> <message> <location line="+139"/> <source>Export Transaction Data</source> <translation>Esporta i dati della transazione</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Testo CSV (*.csv)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>Confermato</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>Etichetta</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>Indirizzo</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>Importo</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>ID</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation>Errore nell&apos;esportazione</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Impossibile scrivere sul file %1.</translation> </message> <message> <location line="+100"/> <source>Range:</source> <translation>Intervallo:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>a</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+193"/> <source>Send Coins</source> <translation>Spedisci Cactuscoin</translation> </message> </context> <context> <name>WalletView</name> <message> <location filename="../walletview.cpp" line="+42"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Export the data in the current tab to a file</source> <translation>Esporta i dati nella tabella corrente su un file</translation> </message> <message> <location line="+193"/> <source>Backup Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation>Backup fallito</translation> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Backup Successful</source> <translation>Backup eseguito con successo</translation> </message> <message> <location line="+0"/> <source>The wallet data was successfully saved to the new location.</source> <translation>Il portafoglio è stato correttamente salvato nella nuova cartella.</translation> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+94"/> <source>Cactuscoin version</source> <translation>Versione di Cactuscoin</translation> </message> <message> <location line="+102"/> <source>Usage:</source> <translation>Utilizzo:</translation> </message> <message> <location line="-29"/> <source>Send command to -server or cactuscoind</source> <translation>Manda il comando a -server o cactuscoind </translation> </message> <message> <location line="-23"/> <source>List commands</source> <translation>Lista comandi </translation> </message> <message> <location line="-12"/> <source>Get help for a command</source> <translation>Aiuto su un comando </translation> </message> <message> <location line="+24"/> <source>Options:</source> <translation>Opzioni: </translation> </message> <message> <location line="+24"/> <source>Specify configuration file (default: cactuscoin.conf)</source> <translation>Specifica il file di configurazione (di default: cactuscoin.conf) </translation> </message> <message> <location line="+3"/> <source>Specify pid file (default: cactuscoind.pid)</source> <translation>Specifica il file pid (default: cactuscoind.pid) </translation> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>Specifica la cartella dati </translation> </message> <message> <location line="-9"/> <source>Set database cache size in megabytes (default: 25)</source> <translation>Imposta la dimensione cache del database in megabyte (default: 25)</translation> </message> <message> <location line="-28"/> <source>Listen for connections on &lt;port&gt; (default: 9333 or testnet: 19333)</source> <translation>Ascolta le connessioni JSON-RPC su &lt;porta&gt; (default: 9333 o testnet: 19333)</translation> </message> <message> <location line="+5"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>Mantieni al massimo &lt;n&gt; connessioni ai peer (default: 125)</translation> </message> <message> <location line="-48"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation>Connessione ad un nodo per ricevere l&apos;indirizzo del peer, e disconnessione</translation> </message> <message> <location line="+82"/> <source>Specify your own public address</source> <translation>Specifica il tuo indirizzo pubblico</translation> </message> <message> <location line="+3"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>Soglia di disconnessione dei peer di cattiva qualità (default: 100)</translation> </message> <message> <location line="-134"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>Numero di secondi di sospensione che i peer di cattiva qualità devono trascorrere prima di riconnettersi (default: 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>Errore riscontrato durante l&apos;impostazione della porta RPC %u per l&apos;ascolto su 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>Attendi le connessioni JSON-RPC su &lt;porta&gt; (default: 9332 or testnet: 19332)</translation> </message> <message> <location line="+37"/> <source>Accept command line and JSON-RPC commands</source> <translation>Accetta da linea di comando e da comandi JSON-RPC </translation> </message> <message> <location line="+76"/> <source>Run in the background as a daemon and accept commands</source> <translation>Esegui in background come demone e accetta i comandi </translation> </message> <message> <location line="+37"/> <source>Use the test network</source> <translation>Utilizza la rete di prova </translation> </message> <message> <location line="-112"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation>Accetta connessioni dall&apos;esterno (default: 1 se no -proxy o -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=cactuscoinrpc 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;Cactuscoin Alert&quot; [email protected] </source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation>Errore riscontrato durante l&apos;impostazione della porta RPC %u per l&apos;ascolto su IPv6, tornando su 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>Collega all&apos;indirizzo indicato e resta sempre in ascolto su questo. Usa la notazione [host]:porta per l&apos;IPv6</translation> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. Cactuscoin is probably already running.</source> <translation>Non è possibile ottenere i dati sulla cartella %s. Probabilmente Cactuscoin è già in esecuzione.</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>Errore: la transazione è stata rifiutata. Ciò accade se alcuni cactuscoin nel portamonete sono stati già spesi, ad esempio se è stata usata una copia del file wallet.dat e i cactuscoin sono stati spesi dalla copia ma non segnati come spesi qui.</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>Errore: questa transazione necessita di una commissione di almeno %s a causa del suo ammontare, della sua complessità, o dell&apos;uso di fondi recentemente ricevuti!</translation> </message> <message> <location line="+3"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation>Esegui comando quando una transazione del portafoglio cambia (%s in cmd è sostituito da TxID)</translation> </message> <message> <location line="+11"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation>Imposta dimensione massima delle transazioni ad alta priorità/bassa-tassa in bytes (predefinito: 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>Questa versione è una compilazione pre-rilascio - usala a tuo rischio - non utilizzarla per la generazione o per applicazioni di commercio</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>Attenzione: -paytxfee è molto alta. Questa è la commissione che si paga quando si invia una transazione.</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>Attenzione: le transazioni mostrate potrebbero essere sbagliate! Potresti aver bisogno di aggiornare, o altri nodi ne hanno bisogno.</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 Cactuscoin will not work properly.</source> <translation>Attenzione: si prega di controllare che la data del computer e l&apos;ora siano corrette. Se il vostro orologio è sbagliato Cactuscoin non funziona correttamente.</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>Attenzione: errore di lettura di wallet.dat! Tutte le chiave lette correttamente, ma i dati delle transazioni o le voci in rubrica potrebbero mancare o non essere corretti.</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>Attenzione: wallet.dat corrotto, dati salvati! Il wallet.dat originale salvato come wallet.{timestamp}.bak in %s; se il tuo bilancio o le transazioni non sono corrette dovresti ripristinare da un backup.</translation> </message> <message> <location line="+14"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation>Tenta di recuperare le chiavi private da un wallet.dat corrotto</translation> </message> <message> <location line="+2"/> <source>Block creation options:</source> <translation>Opzioni creazione blocco:</translation> </message> <message> <location line="+5"/> <source>Connect only to the specified node(s)</source> <translation>Connetti solo al nodo specificato</translation> </message> <message> <location line="+3"/> <source>Corrupted block database detected</source> <translation>Rilevato database blocchi corrotto</translation> </message> <message> <location line="+1"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation>Scopri proprio indirizzo IP (default: 1 se in ascolto e no -externalip)</translation> </message> <message> <location line="+1"/> <source>Do you want to rebuild the block database now?</source> <translation>Vuoi ricostruire ora il database dei blocchi?</translation> </message> <message> <location line="+2"/> <source>Error initializing block database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error initializing wallet database environment %s!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading block database</source> <translation>Errore caricamento database blocchi</translation> </message> <message> <location line="+4"/> <source>Error opening block database</source> <translation>Errore caricamento database blocchi</translation> </message> <message> <location line="+2"/> <source>Error: Disk space is low!</source> <translation>Errore: la spazio libero sul disco è poco!</translation> </message> <message> <location line="+1"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation>Errore: portafoglio bloccato, impossibile creare la transazione!</translation> </message> <message> <location line="+1"/> <source>Error: system error: </source> <translation>Errore: errore di sistema:</translation> </message> <message> <location line="+1"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation>Impossibile mettersi in ascolto su una porta. Usa -listen=0 se vuoi usare questa opzione.</translation> </message> <message> <location line="+1"/> <source>Failed to read block info</source> <translation>Lettura informazioni blocco fallita</translation> </message> <message> <location line="+1"/> <source>Failed to read block</source> <translation>Lettura blocco fallita</translation> </message> <message> <location line="+1"/> <source>Failed to sync block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block info</source> <translation>Scrittura informazioni blocco fallita</translation> </message> <message> <location line="+1"/> <source>Failed to write block</source> <translation>Scrittura blocco fallita</translation> </message> <message> <location line="+1"/> <source>Failed to write file info</source> <translation>Scrittura informazioni file fallita</translation> </message> <message> <location line="+1"/> <source>Failed to write to coin database</source> <translation>Scrittura nel database dei cactuscoin fallita</translation> </message> <message> <location line="+1"/> <source>Failed to write transaction index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write undo data</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation>Trova peer utilizzando la ricerca DNS (predefinito: 1 finché utilizzato -connect)</translation> </message> <message> <location line="+1"/> <source>Generate coins (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation>Quanti blocchi da controllare all&apos;avvio (predefinito: 288, 0 = tutti)</translation> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-4, default: 3)</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Not enough file descriptors available.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Rebuild block chain index from current blk000??.dat files</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation type="unfinished"/> </message> <message> <location line="+26"/> <source>Verifying blocks...</source> <translation>Verifica blocchi...</translation> </message> <message> <location line="+1"/> <source>Verifying wallet...</source> <translation>Verifica portafoglio...</translation> </message> <message> <location line="-69"/> <source>Imports blocks from external blk000??.dat file</source> <translation>Importa blocchi da un file blk000??.dat esterno</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 type="unfinished"/> </message> <message> <location line="+77"/> <source>Information</source> <translation>Informazione</translation> </message> <message> <location line="+3"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation>Indirizzo -tor non valido: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Maintain a full transaction index (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation>Buffer di ricezione massimo per connessione, &lt;n&gt;*1000 byte (default: 5000)</translation> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation>Buffer di invio massimo per connessione, &lt;n&gt;*1000 byte (default: 1000)</translation> </message> <message> <location line="+2"/> <source>Only accept block chain matching built-in checkpoints (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation>Connetti solo a nodi nella rete &lt;net&gt; (IPv4, IPv6 o Tor)</translation> </message> <message> <location line="+2"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation>Produci informazioni extra utili al debug. Implies all other -debug* options</translation> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation>Genera informazioni extra utili al debug della rete</translation> </message> <message> <location line="+2"/> <source>Prepend debug output with timestamp</source> <translation>Anteponi all&apos;output di debug una marca temporale</translation> </message> <message> <location line="+5"/> <source>SSL options: (see the Cactuscoin Wiki for SSL setup instructions)</source> <translation>Opzioni SSL: (vedi il wiki di Cactuscoin per le istruzioni di configurazione SSL)</translation> </message> <message> <location line="+1"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation>Selezionare la versione del proxy socks da usare (4-5, default: 5)</translation> </message> <message> <location line="+3"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>Invia le informazioni di trace/debug alla console invece che al file debug.log</translation> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation>Invia le informazioni di trace/debug al debugger</translation> </message> <message> <location line="+5"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation>Imposta dimensione massima del blocco in bytes (predefinito: 250000)</translation> </message> <message> <location line="+1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation>Imposta dimensione minima del blocco in bytes (predefinito: 0)</translation> </message> <message> <location line="+2"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation>Riduci il file debug.log all&apos;avvio del client (predefinito: 1 se non impostato -debug)</translation> </message> <message> <location line="+1"/> <source>Signing transaction failed</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation>Specifica il timeout di connessione in millisecondi (default: 5000)</translation> </message> <message> <location line="+4"/> <source>System error: </source> <translation>Errore di sistema:</translation> </message> <message> <location line="+4"/> <source>Transaction amount too small</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction amounts must be positive</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction too large</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation>UPnP-használat engedélyezése a figyelő port feltérképezésénél (default: 0)</translation> </message> <message> <location line="+1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation>UPnP-használat engedélyezése a figyelő port feltérképezésénél (default: 1 when listening)</translation> </message> <message> <location line="+1"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation>Usa un proxy per raggiungere servizi nascosti di tor (predefinito: uguale a -proxy)</translation> </message> <message> <location line="+2"/> <source>Username for JSON-RPC connections</source> <translation>Nome utente per connessioni JSON-RPC </translation> </message> <message> <location line="+4"/> <source>Warning</source> <translation>Attenzione</translation> </message> <message> <location line="+1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation>Attenzione: questa versione è obsoleta, aggiornamento necessario!</translation> </message> <message> <location line="+1"/> <source>You need to rebuild the databases using -reindex to change -txindex</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>wallet.dat corrupt, salvage failed</source> <translation>wallet.dat corrotto, salvataggio fallito</translation> </message> <message> <location line="-50"/> <source>Password for JSON-RPC connections</source> <translation>Password per connessioni JSON-RPC </translation> </message> <message> <location line="-67"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>Consenti connessioni JSON-RPC dall&apos;indirizzo IP specificato </translation> </message> <message> <location line="+76"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>Inviare comandi al nodo in esecuzione su &lt;ip&gt; (default: 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>Esegui il comando quando il miglior block cambia(%s nel cmd è sostituito dall&apos;hash del blocco)</translation> </message> <message> <location line="+147"/> <source>Upgrade wallet to latest format</source> <translation>Aggiorna il wallet all&apos;ultimo formato</translation> </message> <message> <location line="-21"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>Impostare la quantità di chiavi di riserva a &lt;n&gt; (default: 100) </translation> </message> <message> <location line="-12"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>Ripeti analisi della catena dei blocchi per cercare le transazioni mancanti dal portamonete </translation> </message> <message> <location line="+35"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>Utilizzare OpenSSL (https) per le connessioni JSON-RPC </translation> </message> <message> <location line="-26"/> <source>Server certificate file (default: server.cert)</source> <translation>File certificato del server (default: server.cert) </translation> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation>Chiave privata del server (default: server.pem) </translation> </message> <message> <location line="-151"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation>Cifrari accettabili (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH) </translation> </message> <message> <location line="+165"/> <source>This help message</source> <translation>Questo messaggio di aiuto </translation> </message> <message> <location line="+6"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation>Impossibile collegarsi alla %s su questo computer (bind returned error %d, %s)</translation> </message> <message> <location line="-91"/> <source>Connect through socks proxy</source> <translation>Connessione tramite socks proxy</translation> </message> <message> <location line="-10"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>Consenti ricerche DNS per aggiungere nodi e collegare </translation> </message> <message> <location line="+55"/> <source>Loading addresses...</source> <translation>Caricamento indirizzi...</translation> </message> <message> <location line="-35"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>Errore caricamento wallet.dat: Wallet corrotto</translation> </message> <message> <location line="+1"/> <source>Error loading wallet.dat: Wallet requires newer version of Cactuscoin</source> <translation>Errore caricamento wallet.dat: il wallet richiede una versione nuova di Cactuscoin</translation> </message> <message> <location line="+93"/> <source>Wallet needed to be rewritten: restart Cactuscoin to complete</source> <translation>Il portamonete deve essere riscritto: riavviare Cactuscoin per completare</translation> </message> <message> <location line="-95"/> <source>Error loading wallet.dat</source> <translation>Errore caricamento wallet.dat</translation> </message> <message> <location line="+28"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation>Indirizzo -proxy non valido: &apos;%s&apos;</translation> </message> <message> <location line="+56"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation>Rete sconosciuta specificata in -onlynet: &apos;%s&apos;</translation> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation>Versione -socks proxy sconosciuta richiesta: %i</translation> </message> <message> <location line="-96"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation>Impossibile risolvere -bind address: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation>Impossibile risolvere indirizzo -externalip: &apos;%s&apos;</translation> </message> <message> <location line="+44"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Importo non valido per -paytxfee=&lt;amount&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount</source> <translation>Importo non valido</translation> </message> <message> <location line="-6"/> <source>Insufficient funds</source> <translation>Fondi insufficienti</translation> </message> <message> <location line="+10"/> <source>Loading block index...</source> <translation>Caricamento dell&apos;indice del blocco...</translation> </message> <message> <location line="-57"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>Elérendő csomópont megadása and attempt to keep the connection open</translation> </message> <message> <location line="-25"/> <source>Unable to bind to %s on this computer. Cactuscoin is probably already running.</source> <translation>Impossibile collegarsi alla %s su questo computer. Probabilmente Cactuscoin è già in esecuzione.</translation> </message> <message> <location line="+64"/> <source>Fee per KB to add to transactions you send</source> <translation>Commissione per KB da aggiungere alle transazioni in uscita</translation> </message> <message> <location line="+19"/> <source>Loading wallet...</source> <translation>Caricamento portamonete...</translation> </message> <message> <location line="-52"/> <source>Cannot downgrade wallet</source> <translation>Non è possibile retrocedere il wallet</translation> </message> <message> <location line="+3"/> <source>Cannot write default address</source> <translation>Non è possibile scrivere l&apos;indirizzo di default</translation> </message> <message> <location line="+64"/> <source>Rescanning...</source> <translation>Ripetere la scansione...</translation> </message> <message> <location line="-57"/> <source>Done loading</source> <translation>Caricamento completato</translation> </message> <message> <location line="+82"/> <source>To use the %s option</source> <translation>Per usare la opzione %s</translation> </message> <message> <location line="-74"/> <source>Error</source> <translation>Errore</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>Devi settare rpcpassword=&lt;password&gt; nel file di configurazione: %s Se il file non esiste, crealo con i permessi di amministratore</translation> </message> </context> </TS>
mit
Dealtis/DMS_3
DMS_3/obj/Debug/android/src/mono/MonoPackageManager.java
3381
package mono; import java.io.*; import java.lang.String; import java.util.Locale; import java.util.HashSet; import java.util.zip.*; import android.content.Context; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.res.AssetManager; import android.util.Log; import mono.android.Runtime; public class MonoPackageManager { static Object lock = new Object (); static boolean initialized; static android.content.Context Context; public static void LoadApplication (Context context, ApplicationInfo runtimePackage, String[] apks) { synchronized (lock) { if (context instanceof android.app.Application) { Context = context; } if (!initialized) { android.content.IntentFilter timezoneChangedFilter = new android.content.IntentFilter ( android.content.Intent.ACTION_TIMEZONE_CHANGED ); context.registerReceiver (new mono.android.app.NotifyTimeZoneChanges (), timezoneChangedFilter); System.loadLibrary("monodroid"); Locale locale = Locale.getDefault (); String language = locale.getLanguage () + "-" + locale.getCountry (); String filesDir = context.getFilesDir ().getAbsolutePath (); String cacheDir = context.getCacheDir ().getAbsolutePath (); String dataDir = getNativeLibraryPath (context); ClassLoader loader = context.getClassLoader (); Runtime.init ( language, apks, getNativeLibraryPath (runtimePackage), new String[]{ filesDir, cacheDir, dataDir, }, loader, new java.io.File ( android.os.Environment.getExternalStorageDirectory (), "Android/data/" + context.getPackageName () + "/files/.__override__").getAbsolutePath (), MonoPackageManager_Resources.Assemblies, context.getPackageName ()); mono.android.app.ApplicationRegistration.registerApplications (); initialized = true; } } } public static void setContext (Context context) { // Ignore; vestigial } static String getNativeLibraryPath (Context context) { return getNativeLibraryPath (context.getApplicationInfo ()); } static String getNativeLibraryPath (ApplicationInfo ainfo) { if (android.os.Build.VERSION.SDK_INT >= 9) return ainfo.nativeLibraryDir; return ainfo.dataDir + "/lib"; } public static String[] getAssemblies () { return MonoPackageManager_Resources.Assemblies; } public static String[] getDependencies () { return MonoPackageManager_Resources.Dependencies; } public static String getApiPackageName () { return MonoPackageManager_Resources.ApiPackageName; } } class MonoPackageManager_Resources { public static final String[] Assemblies = new String[]{ /* We need to ensure that "DMS_3.dll" comes first in this list. */ "DMS_3.dll", "Java.Interop.dll", "AndHUD.dll", "NineOldAndroids.dll", "AndroidEasingFunctions.dll", "AutoFitTextView.dll", "FortySevenDeg.SwipeListView.dll", "Xamarin.Insights.dll", "Xamarin.Android.Support.v4.dll", "Xamarin.Android.Support.Vector.Drawable.dll", "Xamarin.Android.Support.Animated.Vector.Drawable.dll", "Xamarin.Android.Support.v7.AppCompat.dll", "System.ServiceModel.Internals.dll", }; public static final String[] Dependencies = new String[]{ }; public static final String ApiPackageName = "Mono.Android.Platform.ApiLevel_23"; }
mit
galetahub/sunrise-questions
spec/generators/install_generator_spec.rb
572
require 'spec_helper' describe Sunrise::Questions::InstallGenerator do include GeneratorSpec::TestCase destination File.expand_path("../../tmp", __FILE__) # arguments %w(something) before(:all) do prepare_destination run_generator end it "should create migration" do assert_migration "db/migrate/sunrise_create_questions.rb" do |migration| assert_class_method :up, migration do |up| assert_match /create_table/, up end end end it "should create question model" do assert_file "app/models/question.rb" end end
mit
sanger/asset_audits
db/migrate/20200617163340_add_metadata_to_process_plates.rb
167
# frozen_string_literal: true class AddMetadataToProcessPlates < ActiveRecord::Migration[5.2] def change add_column :process_plates, :metadata, :json end end
mit
gabz75/ember-cli-deploy-redis-publish
node_modules/testem/lib/reporters/dev/error_messages_panel.js
1395
'use strict'; const ScrollableTextPanel = require('./scrollable_text_panel'); const Chars = require('../../chars'); module.exports = ScrollableTextPanel.extend({ initialize(attrs) { this.updateVisibility(); this.on('change:text', () => this.updateVisibility()); ScrollableTextPanel.prototype.initialize.call(this, attrs); }, updateVisibility() { let text = this.get('text'); this.set('visible', !!text); }, render() { let visible = this.get('visible'); if (!visible) { return; } ScrollableTextPanel.prototype.render.call(this); // draw a box let line = this.get('line'); let col = this.get('col') - 1; let width = this.get('width') + 1; let height = this.get('height') + 1; // TODO Figure this out if (isNaN(width)) { return; } let screen = this.get('screen'); screen.foreground('red'); screen.position(col, line); screen.write(Chars.topLeft + new Array(width).join(Chars.horizontal) + Chars.topRight); for (let l = line + 1; l < line + height; l++) { screen.position(col, l); screen.write(Chars.vertical); screen.position(col + width, l); screen.write(Chars.vertical); } screen.position(col, line + height); screen.write(Chars.bottomLeft + new Array(width).join(Chars.horizontal) + Chars.bottomRight); screen.display('reset'); } });
mit
metarealm/foodX
src/app/shared/pipes/video-likes.pipe.ts
236
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'videoLikes' }) export class VideoLikesPipe implements PipeTransform { transform(value: any, args?: any[]): any { return parseInt(value).toLocaleString('en'); } }
mit
jsl/ListableApp-Web
config/deploy.rb
1296
set :stages, %w(staging production) set :default_stage, 'production' require 'capistrano/ext/multistage' set :application, "ListableApp" set :scm, :git set(:deploy_to) { "/var/projects/#{application}/#{stage}" } set(:shared_data_dir) { "#{deploy_to}/shared/data" } set :use_sudo, false set :local_project_path, "/Users/justin/Code/ListableWeb" set :repository, "[email protected]:jsl/ListableWeb.git" set :keep_releases, 5 set :repository_cache, "git_cache" set :deploy_via, :remote_cache # When we migrate, trace any errors set :migrate_env, "--trace" set :loglines, 200 namespace :passenger do desc "Restart Application" task :restart, :roles => :app do run "touch #{current_path}/tmp/restart.txt" end end namespace :deploy do after "deploy:update", "deploy:cleanup" after "deploy:update_code", :symlink_database_yml after "deploy:update_code", :install_gems desc "Restart the Passenger system." task :restart, :roles => :app do passenger.restart end end # Assumes that the correct database.yml has already been installed on the # slices. task :symlink_database_yml, :roles => :app do run "ln -nfs #{deploy_to}/#{shared_dir}/config/database.yml #{release_path}/config/database.yml" end task :install_gems do run "cd #{release_path} && bundle install" end
mit
linyows/pdns
lib/pdns/version.rb
37
module PDNS VERSION = '0.10.0' end
mit
brjmc/brjmc.github.io
ui_catalog/javascripts/bundle.js
1292
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ require('../node_modules/filter_list_demo/example/filter_list_demo.js'); },{"../node_modules/filter_list_demo/example/filter_list_demo.js":2}],2:[function(require,module,exports){ window.filterNames = function() { // Declare variables var input, filter, ul, li, a, i; input = document.getElementById('myInput'); filter = input.value.toUpperCase(); ul = document.getElementById("myUL"); li = ul.getElementsByTagName('li'); // Loop through all list items, and hide those who don't match the search query for (i = 0; i < li.length; i++) { a = li[i].getElementsByTagName("a")[0]; if (a.innerHTML.toUpperCase().indexOf(filter) > -1) { li[i].style.display = ""; } else { li[i].style.display = "none"; } } } },{}]},{},[1]);
mit
space-wizards/space-station-14
Content.Server/Roles/RoleAddedEvent.cs
159
namespace Content.Server.Roles { public sealed class RoleAddedEvent : RoleEvent { public RoleAddedEvent(Role role) : base(role) { } } }
mit
deaconu-sabin/das
src/include/das/IAlgorithm.hpp
514
/* * IAlgorithm.hpp * * Created on: Aug 15, 2016 * Author: sabin */ #ifndef IALGORITHM_HPP_ #define IALGORITHM_HPP_ namespace das { class IAlgorithm { public: virtual ~IAlgorithm(){} virtual bool setInitialData() = 0; virtual bool readInputData() = 0; virtual bool processData() = 0; virtual bool writeOutputData() = 0; virtual bool isFinished() = 0; }; } /* namespace das */ extern "C" das::IAlgorithm* Create(); #endif /* IALGORITHM_HPP_ */
mit
2016-Software-Reuse-Group-7/chat-room
src/main/java/TeamSeven/common/message/server/ServerPublicKeyMessage.java
583
package TeamSeven.common.message.server; import TeamSeven.common.enumerate.TransMessageTypeEnum; import TeamSeven.common.message.BaseMessage; import java.security.PublicKey; /** * Created by joshoy on 16/4/19. */ public class ServerPublicKeyMessage extends BaseMessage { protected PublicKey key; public ServerPublicKeyMessage(PublicKey key) { this.key = key; } public PublicKey getServerPublicKey() { return this.key; } @Override public TransMessageTypeEnum getType() { return TransMessageTypeEnum.SERVER_PUBKEY; } }
mit
NilsHolger/Expenser
app/js/app.js
703
'use strict'; // Declare app level module which depends on filters, and services angular.module('myApp', [ 'ngRoute', 'myApp.filters', 'myApp.services', 'myApp.directives', 'myApp.controllers', 'ngTouch', 'ngAnimate' ]). config(['$routeProvider', function($routeProvider) { $routeProvider.when('/',{ templateUrl: 'partials/home.html', controller: 'HomeCtrl' }); $routeProvider.when('/expense-add',{ templateUrl: 'partials/expense-add.html', controller: 'ExpenseAddCtrl' }); $routeProvider.when('/summary-view', { templateUrl: 'partials/summary-view.html', controller: 'SummaryViewCtrl' }); $routeProvider.otherwise({ redirectTo: '/' }); }]);
mit
plotly/plotly.py
packages/python/plotly/plotly/validators/layout/xaxis/_visible.py
402
import _plotly_utils.basevalidators class VisibleValidator(_plotly_utils.basevalidators.BooleanValidator): def __init__(self, plotly_name="visible", parent_name="layout.xaxis", **kwargs): super(VisibleValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "plot"), **kwargs )
mit
dchester/generator-async
lib/context.js
2509
var Context = function(generator, args, _this) { if (!generator) throw new Error("Context needs a generator function"); this.queue = []; this.callback = function() {}; this.pendingCount = 0; this.iterator = generator.apply(_this, args); }; Context.prototype = { run: function(callback) { this.callback = callback || this.callback; this.continue(); }, continue: function(payload, err) { try { Context.stack.set(this); var ret = err ? this.iterator.throw(err) : this.iterator.next(payload); var value = ret.value; if (ret.done) { this.callback(null, value); this._done = true; } else if (value && value instanceof Object && value._id == '__async') { // do nothing } else if (is_promise(value)) { var callback = this.cb(); value.then(function(resolution) { callback(null, resolution); }).catch(callback); } else if (value instanceof Function) { var transform = value.async ? value.async.transform : undefined; value.call(null, this.cb(transform)); } else if (this._cbinit) { // do nothing } else { throw new Error("Attempted to yield bad value: " + value); } Context.stack.clear(); } catch (e) { throw e && e.stack ? e.stack : e; } }, cb: function(transform) { this._cbinit = true; if (this._done) return; var placeholder = {}; this.pendingCount++; this.queue.push(placeholder); transform = transform || function(args) { return args }; return function() { var results = transform(arguments); var err = results[0]; var data = results[1]; if (err) { console.warn("WARN", err); err = new Error(err); } placeholder.value = data; if (--this.pendingCount !== 0) return; var len = this.queue.length; while (len--) { // push a dummy operation onto the next frame of the event loop setImmediate(function() {}); var d = this.queue.shift(); this.continue(d.value, err); } }.bind(this); } }; Context.stack = { stack: [], active: function() { return this.stack[this.stack.length - 1] }, set: function(context) { this.stack.push(context); }, clear: function() { this.stack.pop(); } }; function is_promise(fn) { return fn && typeof fn == "object" && typeof fn.then == "function"; } module.exports = Context;
mit
knuu/competitive-programming
codechef/snckel16_arithm.py
496
T = int(input()) for _ in range(T): N, C = map(int, input().split()) if 2 * C % N != 0: print("No") continue K = 2 * C // N if (K % 2 == 0 and (N - 1) % 2 == 0) or (K % 2 == 1 and (N - 1) % 2 == 1): a0 = K - (N - 1) assert(a0 % 2 == 0) print("Yes" if a0 > 0 else "No") elif K % 2 == 0 and (N - 1) % 2 == 1: a0 = K - (N - 1) * 2 assert(a0 % 2 == 0) print("Yes" if a0 > 0 else "No") else: print("No")
mit
mysociety/ruby-msg
test/test_msg.rb
1508
# -*- encoding : utf-8 -*- #! /usr/bin/ruby TEST_DIR = File.dirname __FILE__ $: << "#{TEST_DIR}/../lib" require 'test/unit' require 'mapi/msg' require 'mapi/convert' class TestMsg < Test::Unit::TestCase def test_blammo Mapi::Msg.open "#{TEST_DIR}/test_Blammo.msg" do |msg| assert_equal '"TripleNickel" <[email protected]>', msg.from assert_equal 'BlammoBlammo', msg.subject assert_equal 0, msg.recipients.length assert_equal 0, msg.attachments.length # this is all properties assert_equal 66, msg.properties.raw.length # this is unique named properties assert_equal 48, msg.properties.to_h.length # test accessing the named property keys - same name but different namespace assert_equal 'Yippee555', msg.props['Name4', Ole::Types::Clsid.parse('55555555-5555-5555-c000-000000000046')] assert_equal 'Yippee666', msg.props['Name4', Ole::Types::Clsid.parse('66666666-6666-6666-c000-000000000046')] end end def test_rtf_to_html_returns_valid_utf8 msg = Mapi::Msg.open "#{TEST_DIR}/multipart-with-html.msg" do |msg| assert_equal 1, msg.recipients.length assert_equal 3, msg.attachments.length html_part = msg.to_mime.parts[0].parts[1].to_s if html_part.respond_to?(:encoding) assert_equal 'UTF-8', html_part.encoding.to_s assert html_part.valid_encoding? end end end def test_embedded_msg_renders_as_string msg = Mapi::Msg.open "#{TEST_DIR}/embedded.msg" do |msg| assert_match "message/rfc822", msg.to_mime.to_s end end end
mit
sveltejs/svelte
src/compiler/compile/render_dom/wrappers/IfBlock.ts
16722
import Wrapper from './shared/Wrapper'; import Renderer from '../Renderer'; import Block from '../Block'; import EachBlock from '../../nodes/EachBlock'; import IfBlock from '../../nodes/IfBlock'; import create_debugging_comment from './shared/create_debugging_comment'; import ElseBlock from '../../nodes/ElseBlock'; import FragmentWrapper from './Fragment'; import { b, x } from 'code-red'; import { walk } from 'estree-walker'; import { is_head } from './shared/is_head'; import { Identifier, Node } from 'estree'; import { push_array } from '../../../utils/push_array'; function is_else_if(node: ElseBlock) { return ( node && node.children.length === 1 && node.children[0].type === 'IfBlock' ); } class IfBlockBranch extends Wrapper { block: Block; fragment: FragmentWrapper; dependencies?: string[]; condition?: any; snippet?: Node; is_dynamic: boolean; var = null; constructor( renderer: Renderer, block: Block, parent: IfBlockWrapper, node: IfBlock | ElseBlock, strip_whitespace: boolean, next_sibling: Wrapper ) { super(renderer, block, parent, node); const { expression } = (node as IfBlock); const is_else = !expression; if (expression) { this.dependencies = expression.dynamic_dependencies(); // TODO is this the right rule? or should any non-reference count? // const should_cache = !is_reference(expression.node, null) && dependencies.length > 0; let should_cache = false; walk(expression.node, { enter(node) { if (node.type === 'CallExpression' || node.type === 'NewExpression') { should_cache = true; } } }); if (should_cache) { this.condition = block.get_unique_name('show_if'); this.snippet = (expression.manipulate(block) as Node); } else { this.condition = expression.manipulate(block); } } this.block = block.child({ comment: create_debugging_comment(node, parent.renderer.component), name: parent.renderer.component.get_unique_name( is_else ? 'create_else_block' : 'create_if_block' ), type: (node as IfBlock).expression ? 'if' : 'else' }); this.fragment = new FragmentWrapper(renderer, this.block, node.children, parent, strip_whitespace, next_sibling); this.is_dynamic = this.block.dependencies.size > 0; } } export default class IfBlockWrapper extends Wrapper { node: IfBlock; branches: IfBlockBranch[]; needs_update = false; var: Identifier = { type: 'Identifier', name: 'if_block' }; constructor( renderer: Renderer, block: Block, parent: Wrapper, node: EachBlock, strip_whitespace: boolean, next_sibling: Wrapper ) { super(renderer, block, parent, node); this.cannot_use_innerhtml(); this.not_static_content(); this.branches = []; const blocks: Block[] = []; let is_dynamic = false; let has_intros = false; let has_outros = false; const create_branches = (node: IfBlock) => { const branch = new IfBlockBranch( renderer, block, this, node, strip_whitespace, next_sibling ); this.branches.push(branch); blocks.push(branch.block); block.add_dependencies(node.expression.dependencies); if (branch.block.dependencies.size > 0) { // the condition, or its contents, is dynamic is_dynamic = true; block.add_dependencies(branch.block.dependencies); } if (branch.dependencies && branch.dependencies.length > 0) { // the condition itself is dynamic this.needs_update = true; } if (branch.block.has_intros) has_intros = true; if (branch.block.has_outros) has_outros = true; if (is_else_if(node.else)) { create_branches(node.else.children[0] as IfBlock); } else if (node.else) { const branch = new IfBlockBranch( renderer, block, this, node.else, strip_whitespace, next_sibling ); this.branches.push(branch); blocks.push(branch.block); if (branch.block.dependencies.size > 0) { is_dynamic = true; block.add_dependencies(branch.block.dependencies); } if (branch.block.has_intros) has_intros = true; if (branch.block.has_outros) has_outros = true; } }; create_branches(this.node); blocks.forEach(block => { block.has_update_method = is_dynamic; block.has_intro_method = has_intros; block.has_outro_method = has_outros; }); push_array(renderer.blocks, blocks); } render( block: Block, parent_node: Identifier, parent_nodes: Identifier ) { const name = this.var; const needs_anchor = this.next ? !this.next.is_dom_node() : !parent_node || !this.parent.is_dom_node(); const anchor = needs_anchor ? block.get_unique_name(`${this.var.name}_anchor`) : (this.next && this.next.var) || 'null'; const has_else = !(this.branches[this.branches.length - 1].condition); const if_exists_condition = has_else ? null : name; const dynamic = this.branches[0].block.has_update_method; // can use [0] as proxy for all, since they necessarily have the same value const has_intros = this.branches[0].block.has_intro_method; const has_outros = this.branches[0].block.has_outro_method; const has_transitions = has_intros || has_outros; const vars = { name, anchor, if_exists_condition, has_else, has_transitions }; const detaching = parent_node && !is_head(parent_node) ? null : 'detaching'; if (this.node.else) { this.branches.forEach(branch => { if (branch.snippet) block.add_variable(branch.condition); }); if (has_outros) { this.render_compound_with_outros(block, parent_node, parent_nodes, dynamic, vars, detaching); block.chunks.outro.push(b`@transition_out(${name});`); } else { this.render_compound(block, parent_node, parent_nodes, dynamic, vars, detaching); } } else { this.render_simple(block, parent_node, parent_nodes, dynamic, vars, detaching); if (has_outros) { block.chunks.outro.push(b`@transition_out(${name});`); } } if (if_exists_condition) { block.chunks.create.push(b`if (${if_exists_condition}) ${name}.c();`); } else { block.chunks.create.push(b`${name}.c();`); } if (parent_nodes && this.renderer.options.hydratable) { if (if_exists_condition) { block.chunks.claim.push( b`if (${if_exists_condition}) ${name}.l(${parent_nodes});` ); } else { block.chunks.claim.push( b`${name}.l(${parent_nodes});` ); } } if (has_intros || has_outros) { block.chunks.intro.push(b`@transition_in(${name});`); } if (needs_anchor) { block.add_element( anchor as Identifier, x`@empty()`, parent_nodes && x`@empty()`, parent_node ); } this.branches.forEach(branch => { branch.fragment.render(branch.block, null, x`#nodes` as unknown as Identifier); }); } render_compound( block: Block, parent_node: Identifier, _parent_nodes: Identifier, dynamic, { name, anchor, has_else, if_exists_condition, has_transitions }, detaching ) { const select_block_type = this.renderer.component.get_unique_name('select_block_type'); const current_block_type = block.get_unique_name('current_block_type'); const get_block = has_else ? x`${current_block_type}(#ctx)` : x`${current_block_type} && ${current_block_type}(#ctx)`; if (this.needs_update) { block.chunks.init.push(b` function ${select_block_type}(#ctx, #dirty) { ${this.branches.map(({ dependencies, condition, snippet }) => { return b`${snippet && dependencies.length > 0 ? b`if (${block.renderer.dirty(dependencies)}) ${condition} = null;` : null}`; })} ${this.branches.map(({ condition, snippet, block }) => condition ? b` ${snippet && b`if (${condition} == null) ${condition} = !!${snippet}`} if (${condition}) return ${block.name};` : b`return ${block.name};` )} } `); } else { block.chunks.init.push(b` function ${select_block_type}(#ctx, #dirty) { ${this.branches.map(({ condition, snippet, block }) => condition ? b`if (${snippet || condition}) return ${block.name};` : b`return ${block.name};`)} } `); } block.chunks.init.push(b` let ${current_block_type} = ${select_block_type}(#ctx, ${this.renderer.get_initial_dirty()}); let ${name} = ${get_block}; `); const initial_mount_node = parent_node || '#target'; const anchor_node = parent_node ? 'null' : '#anchor'; if (if_exists_condition) { block.chunks.mount.push( b`if (${if_exists_condition}) ${name}.m(${initial_mount_node}, ${anchor_node});` ); } else { block.chunks.mount.push( b`${name}.m(${initial_mount_node}, ${anchor_node});` ); } if (this.needs_update) { const update_mount_node = this.get_update_mount_node(anchor); const change_block = b` ${if_exists_condition ? b`if (${if_exists_condition}) ${name}.d(1)` : b`${name}.d(1)`}; ${name} = ${get_block}; if (${name}) { ${name}.c(); ${has_transitions && b`@transition_in(${name}, 1);`} ${name}.m(${update_mount_node}, ${anchor}); } `; if (dynamic) { block.chunks.update.push(b` if (${current_block_type} === (${current_block_type} = ${select_block_type}(#ctx, #dirty)) && ${name}) { ${name}.p(#ctx, #dirty); } else { ${change_block} } `); } else { block.chunks.update.push(b` if (${current_block_type} !== (${current_block_type} = ${select_block_type}(#ctx, #dirty))) { ${change_block} } `); } } else if (dynamic) { if (if_exists_condition) { block.chunks.update.push(b`if (${if_exists_condition}) ${name}.p(#ctx, #dirty);`); } else { block.chunks.update.push(b`${name}.p(#ctx, #dirty);`); } } if (if_exists_condition) { block.chunks.destroy.push(b` if (${if_exists_condition}) { ${name}.d(${detaching}); } `); } else { block.chunks.destroy.push(b` ${name}.d(${detaching}); `); } } // if any of the siblings have outros, we need to keep references to the blocks // (TODO does this only apply to bidi transitions?) render_compound_with_outros( block: Block, parent_node: Identifier, _parent_nodes: Identifier, dynamic, { name, anchor, has_else, has_transitions, if_exists_condition }, detaching ) { const select_block_type = this.renderer.component.get_unique_name('select_block_type'); const current_block_type_index = block.get_unique_name('current_block_type_index'); const previous_block_index = block.get_unique_name('previous_block_index'); const if_block_creators = block.get_unique_name('if_block_creators'); const if_blocks = block.get_unique_name('if_blocks'); const if_current_block_type_index = has_else ? nodes => nodes : nodes => b`if (~${current_block_type_index}) { ${nodes} }`; block.add_variable(current_block_type_index); block.add_variable(name); block.chunks.init.push(b` const ${if_block_creators} = [ ${this.branches.map(branch => branch.block.name)} ]; const ${if_blocks} = []; ${this.needs_update ? b` function ${select_block_type}(#ctx, #dirty) { ${this.branches.map(({ dependencies, condition, snippet }) => { return b`${snippet && dependencies.length > 0 ? b`if (${block.renderer.dirty(dependencies)}) ${condition} = null;` : null}`; })} ${this.branches.map(({ condition, snippet }, i) => condition ? b` ${snippet && b`if (${condition} == null) ${condition} = !!${snippet}`} if (${condition}) return ${i};` : b`return ${i};`)} ${!has_else && b`return -1;`} } ` : b` function ${select_block_type}(#ctx, #dirty) { ${this.branches.map(({ condition, snippet }, i) => condition ? b`if (${snippet || condition}) return ${i};` : b`return ${i};`)} ${!has_else && b`return -1;`} } `} `); if (has_else) { block.chunks.init.push(b` ${current_block_type_index} = ${select_block_type}(#ctx, ${this.renderer.get_initial_dirty()}); ${name} = ${if_blocks}[${current_block_type_index}] = ${if_block_creators}[${current_block_type_index}](#ctx); `); } else { block.chunks.init.push(b` if (~(${current_block_type_index} = ${select_block_type}(#ctx, ${this.renderer.get_initial_dirty()}))) { ${name} = ${if_blocks}[${current_block_type_index}] = ${if_block_creators}[${current_block_type_index}](#ctx); } `); } const initial_mount_node = parent_node || '#target'; const anchor_node = parent_node ? 'null' : '#anchor'; block.chunks.mount.push( if_current_block_type_index( b`${if_blocks}[${current_block_type_index}].m(${initial_mount_node}, ${anchor_node});` ) ); if (this.needs_update) { const update_mount_node = this.get_update_mount_node(anchor); const destroy_old_block = b` @group_outros(); @transition_out(${if_blocks}[${previous_block_index}], 1, 1, () => { ${if_blocks}[${previous_block_index}] = null; }); @check_outros(); `; const create_new_block = b` ${name} = ${if_blocks}[${current_block_type_index}]; if (!${name}) { ${name} = ${if_blocks}[${current_block_type_index}] = ${if_block_creators}[${current_block_type_index}](#ctx); ${name}.c(); } else { ${dynamic && b`${name}.p(#ctx, #dirty);`} } ${has_transitions && b`@transition_in(${name}, 1);`} ${name}.m(${update_mount_node}, ${anchor}); `; const change_block = has_else ? b` ${destroy_old_block} ${create_new_block} ` : b` if (${name}) { ${destroy_old_block} } if (~${current_block_type_index}) { ${create_new_block} } else { ${name} = null; } `; block.chunks.update.push(b` let ${previous_block_index} = ${current_block_type_index}; ${current_block_type_index} = ${select_block_type}(#ctx, #dirty); `); if (dynamic) { block.chunks.update.push(b` if (${current_block_type_index} === ${previous_block_index}) { ${if_current_block_type_index(b`${if_blocks}[${current_block_type_index}].p(#ctx, #dirty);`)} } else { ${change_block} } `); } else { block.chunks.update.push(b` if (${current_block_type_index} !== ${previous_block_index}) { ${change_block} } `); } } else if (dynamic) { if (if_exists_condition) { block.chunks.update.push(b`if (${if_exists_condition}) ${name}.p(#ctx, #dirty);`); } else { block.chunks.update.push(b`${name}.p(#ctx, #dirty);`); } } block.chunks.destroy.push( if_current_block_type_index(b`${if_blocks}[${current_block_type_index}].d(${detaching});`) ); } render_simple( block: Block, parent_node: Identifier, _parent_nodes: Identifier, dynamic, { name, anchor, if_exists_condition, has_transitions }, detaching ) { const branch = this.branches[0]; if (branch.snippet) block.add_variable(branch.condition, branch.snippet); block.chunks.init.push(b` let ${name} = ${branch.condition} && ${branch.block.name}(#ctx); `); const initial_mount_node = parent_node || '#target'; const anchor_node = parent_node ? 'null' : '#anchor'; block.chunks.mount.push( b`if (${name}) ${name}.m(${initial_mount_node}, ${anchor_node});` ); if (branch.dependencies.length > 0) { const update_mount_node = this.get_update_mount_node(anchor); const enter = b` if (${name}) { ${dynamic && b`${name}.p(#ctx, #dirty);`} ${ has_transitions && b`if (${block.renderer.dirty(branch.dependencies)}) { @transition_in(${name}, 1); }` } } else { ${name} = ${branch.block.name}(#ctx); ${name}.c(); ${has_transitions && b`@transition_in(${name}, 1);`} ${name}.m(${update_mount_node}, ${anchor}); } `; if (branch.snippet) { block.chunks.update.push(b`if (${block.renderer.dirty(branch.dependencies)}) ${branch.condition} = ${branch.snippet}`); } // no `p()` here — we don't want to update outroing nodes, // as that will typically result in glitching if (branch.block.has_outro_method) { block.chunks.update.push(b` if (${branch.condition}) { ${enter} } else if (${name}) { @group_outros(); @transition_out(${name}, 1, 1, () => { ${name} = null; }); @check_outros(); } `); } else { block.chunks.update.push(b` if (${branch.condition}) { ${enter} } else if (${name}) { ${name}.d(1); ${name} = null; } `); } } else if (dynamic) { block.chunks.update.push(b` if (${branch.condition}) ${name}.p(#ctx, #dirty); `); } if (if_exists_condition) { block.chunks.destroy.push(b` if (${if_exists_condition}) ${name}.d(${detaching}); `); } else { block.chunks.destroy.push(b` ${name}.d(${detaching}); `); } } }
mit
engagementgamelab/hygiene-with-chhota-bheem
game/Assets/Scripts/LoadGame.cs
194
using UnityEngine; public class LoadGame : MonoBehaviour { // Use this for initialization void Start () { UnityEngine.SceneManagement.SceneManager.LoadScene("JohnnyScene"); } }
mit
Patternslib/pat-map-leaflet
src/pat/calendar/calendar.js
15702
/** * Patterns calendar - Calendar with different views for patterns. * * Copyright 2013-2014 Marko Durkovic * Copyright 2014 Florian Friesdorf */ define([ "jquery", "pat-logger", "pat-parser", "pat-store", "pat-utils", "pat-registry", "pat-calendar-dnd", "pat-calendar-moment-timezone-data", "jquery.fullcalendar" ], function($, logger, Parser, store, utils, registry, dnd) { "use strict"; var log = logger.getLogger("calendar"), parser = new Parser("calendar"); parser.add_argument("height", "auto"); parser.add_argument("start-date"); parser.add_argument("time-format", "h(:mm)t"); parser.add_argument("title-month", "MMMM YYYY"); parser.add_argument("title-week", "MMM D YYYY"); parser.add_argument("title-day", "dddd, MMM d, YYYY"); parser.add_argument("column-month", "ddd"); parser.add_argument("column-week", "ddd M/d"); parser.add_argument("column-day", "dddd M/d"); parser.add_argument("first-day", "0"); parser.add_argument("first-hour", "6"); parser.add_argument("calendar-controls", ""); parser.add_argument("category-controls", ""); parser.add_argument("default-view", "month", ["month", "basicWeek", "basicDay", "agendaWeek", "agendaDay"]); parser.add_argument("store", "none", ["none", "session", "local"]); parser.add_argument("ignore-url", false); var _ = { name: "calendar", trigger: ".pat-calendar", _parseSearchString: function() { var context = {}; window.location.search.substr(1).split("&").forEach(function(str) { if (str) { var keyValue = str.split("="), key = keyValue[0], value = decodeURIComponent(keyValue[1]); if (value && (value.match(/^\[.*\]$/) || value.match(/^\{.*\}$/))) { context[key] = JSON.parse(value); } else { context[key] = value; } } }); return context; }, init: function($el, opts) { opts = opts || {}; var cfg = store.updateOptions($el[0], parser.parse($el)), storage = cfg.store === "none" ? null : store[cfg.store](_.name + $el[0].id); cfg.defaultDate = storage.get("date") || cfg.defaultDate, cfg.defaultView = storage.get("view") || cfg.defaultView; if (!opts.ignoreUrl) { var search = _._parseSearchString(); if (search["default-date"]) { cfg.defaultDate = search["default-date"]; } if (search["default-view"]) { cfg.defaultView = search["default-view"]; } } var calOpts = { header: false, droppable: true, drop: function(date, event, undef, view) { var $this = $(this), $ev = $this.hasClass("cal-event") ? $this : $this.parents(".cal-event"), $cal = $(view.element).parents(".pat-calendar"); $ev.appendTo($cal.find(".cal-events")); var $start = $ev.find(".start"); if (!$start.length) { $("<time class='start'/>").attr("datetime", date.format()) .appendTo($ev); } var $end = $ev.find(".end"); if (!$end.length) { $("<time class='end'/>").appendTo($ev); } if (date.hasTime()) { $ev.addClass("all-day"); } else { $ev.removeClass("all-day"); } $cal.fullCalendar("refetchEvents"); $cal.find("a").each(function(a) { $(a).draggable = 1; }); }, events: function(start, end, timezone, callback) { var events = _.parseEvents($el, timezone); callback(events); }, firstHour: cfg.first.hour, axisFormat: cfg.timeFormat, timeFormat: cfg.timeFormat, titleFormat: cfg.title, columnFormat: cfg.column, viewRender: _.highlightButtons, defaultDate: cfg.defaultDate, defaultView: cfg.defaultView }; $el.__cfg = cfg; $el.__storage = storage; if (cfg.height !== "auto") { calOpts.height = cfg.height; } var dayNames = [ "su", "mo", "tu", "we", "th", "fr", "sa" ]; if (dayNames.indexOf(cfg.first.day) >= 0) { calOpts.firstDay = dayNames.indexOf(cfg.first.day); } var refetch = function() { $el.fullCalendar("refetchEvents"); }; var refetch_deb = utils.debounce(refetch, 400); $el.on("keyup.pat-calendar", ".filter .search-text", refetch_deb); $el.on("click.pat-calendar", ".filter .search-text[type=search]", refetch_deb); $el.on("change.pat-calendar", ".filter select[name=state]", refetch); $el.on("change.pat-calendar", ".filter .check-list", refetch); $el.categories = $el.find(".cal-events .cal-event") .map(function() { return this.className.split(" ").filter(function(cls) { return (/^cal-cat/).test(cls); }); }); var $categoryRoot = cfg.categoryControls ? $(cfg.categoryControls) : $el; $el.$catControls = $categoryRoot.find("input[type=checkbox]"); $el.$catControls.on("change.pat-calendar", refetch); var $controlRoot = cfg.calendarControls ? $(cfg.calendarControls) : $el; $el.$controlRoot = $controlRoot; calOpts.timezone = $controlRoot.find("select.timezone").val(); $el.fullCalendar(calOpts); // move to end of $el $el.find(".fc-content").appendTo($el); if (cfg.height === "auto") { $el.fullCalendar("option", "height", $el.find(".fc-content").height()); $(window).on("resize.pat-calendar", function() { $el.fullCalendar("option", "height", $el.find(".fc-content").height()); }); $(document).on("pat-update.pat-calendar", function() { $el.fullCalendar("option", "height", $el.find(".fc-content").height()); }); } // update title var $title = $el.find(".cal-title"); $title.text($el.fullCalendar("getView").title); var classMap = { month: ".view-month", agendaWeek: ".view-week", agendaDay: ".view-day" }; $controlRoot.find(classMap[calOpts.defaultView]).addClass("active"); $controlRoot.on("click.pat-calendar", ".jump-next", function() { $el.fullCalendar("next"); _._viewChanged($el); }); $controlRoot.on("click.pat-calendar", ".jump-prev", function() { $el.fullCalendar("prev"); _._viewChanged($el); }); $controlRoot.on("click.pat-calendar", ".jump-today", function() { $el.fullCalendar("today"); _._viewChanged($el); }); $controlRoot.on("click.pat-calendar", ".view-month", function() { $el.fullCalendar("changeView", "month"); _._viewChanged($el); }); $controlRoot.on("click.pat-calendar", ".view-week", function() { $el.fullCalendar("changeView", "agendaWeek"); _._viewChanged($el); }); $controlRoot.on("click.pat-calendar", ".view-day", function() { $el.fullCalendar("changeView", "agendaDay"); _._viewChanged($el); }); $controlRoot.on("change.pat-calendar", "select.timezone", function(ev) { _.destroy($el); _.init($el, {ignoreUrl: true}); }); $el.find(".cal-events").css("display", "none"); // make .cal-event elems draggable dnd.draggable($(".cal-events .cal-event")); // emulate jQueryUI dragstop and mousemove during drag. $(".cal-events .cal-event").on("dragend.pat-calendar", function() { $(this).trigger("dragstop"); }); $el.on("dragover.pat-calendar", function(event) { event.preventDefault(); event.type = "mousemove"; $(document).trigger(event); }); if (!$.fn.draggable) { $.fn.draggable = function(opts) { var start = opts.start, stop = opts.stop; this.on("dragstart", function(event) { start(event, null); }); this.on("dragend", function(event) { stop(event, null); }); }; } }, destroy: function($el) { $el.off(".pat-calendar"); $el.$catControls.off(".pat-calendar"); $el.$controlRoot.off(".pat-calendar"); $(window).off(".pat-calendar"); $(document).off(".pat-calendar"); $(".cal-events .cal-event").off(".pat-calendar"); $el.fullCalendar("destroy"); }, _viewChanged: function($el) { // update title var $title = $el.find(".cal-title"); $title.html($el.fullCalendar("getView").title); // adjust height if ($el.__cfg.height === "auto") { $el.fullCalendar("option", "height", $el.find(".fc-content").height()); } // store current date and view var date = $el.fullCalendar("getDate").format(), view = $el.fullCalendar("getView").name; $el.__storage.set("date", date); $el.__storage.set("view", view); }, highlightButtons: function(view, element) { var $el = element.parents(".pat-calendar").first(), $body = element.parents("body").first(), $today = $el.find(".jump-today"); $today.removeClass("active"); if (view.name === "agendaDay") { var calDate = $el.fullCalendar("getDate"), today = $.fullCalendar.moment(); if (calDate.date() === today.date() && calDate.month() === today.month() && calDate.year() === today.year()) { $today.addClass("active"); } } var classMap = { month: ".view-month", agendaWeek: ".view-week", agendaDay: ".view-day" }; $body.find(".view-month").removeClass("active"); $body.find(".view-week").removeClass("active"); $body.find(".view-day").removeClass("active"); $body.find(classMap[view.name]).addClass("active"); }, parseEvents: function($el, timezone) { var $events = $el.find(".cal-events"), $filter = $el.find(".filter"), searchText, regex; // parse filters if ($filter && $filter.length > 0) { searchText = $(".search-text", $filter).val(); regex = new RegExp(searchText, "i"); } var shownCats = $el.categories.filter(function() { var cat = this; return $el.$catControls.filter(function() { return this.checked && $(this) .parents() .andSelf() .hasClass(cat); }).length; }); var events = $events.find(".cal-event").filter(function() { var $event = $(this); if (searchText && !regex.test($event.find(".title").text())) { log.debug("remove due to search-text="+searchText, $event); return false; } return shownCats.filter(function() { return $event.hasClass(this); }).length; }).map(function(idx, event) { var attr, i; // classNames: all event classes without "event" + anchor classes var classNames = $(event).attr("class").split(/\s+/) .filter(function(cls) { return (cls !== "cal-event"); }) .concat($("a", event).attr("class").split(/\s+/)); // attrs: all "data-" attrs from anchor var allattrs = $("a", event)[0].attributes, attrs = {}; for (attr, i=0; i<allattrs.length; i++){ attr = allattrs.item(i); if (attr.nodeName.slice(0,5) === "data-") { attrs[attr.nodeName] = attr.nodeValue; } } var location = ($(".location", event).html() || "").trim(); var startstr = $(".start", event).attr("datetime"), endstr = $(".end", event).attr("datetime"), start = $.fullCalendar.moment.parseZone(startstr), end = $.fullCalendar.moment.parseZone(endstr); if (timezone) { start = start.tz(timezone); end = end.tz(timezone); } var ev = { title: $(".title", event).text().trim() + (location ? (" (" + location + ")") : ""), start: start.format(), end: end.format(), allDay: $(event).hasClass("all-day"), url: $("a", event).attr("href"), className: classNames, attrs: attrs, editable: $(event).hasClass("editable") }; if (!ev.title) { log.error("No event title for:", event); } if (!ev.start) { log.error("No event start for:", event); } if (!ev.url) { log.error("No event url for:", event); } return ev; }).toArray(); return events; } }; registry.register(_); }); // jshint indent: 4, browser: true, jquery: true, quotmark: double // vim: sw=4 expandtab
mit
JoselynRuiz/Programacion-III
Clase 9/app/__init__.py
483
from flask import Flask app = Flask(__name__) @app.route('/') def hola_mundo(): return 'Xopa Laope!' @app.route('/hola/<nombre>') def hola_laope(nombre): return 'Hola laope, %s!' % nombre @app.route('/blog/<int:idEntrada>') def mostrar_blog(idEntrada): return 'Entrada #%d' % idEntrada @app.route('/itbms/<float:subtotal>') def calcular_itbms(subtotal): return 'Impuesto de $%.2f, es $%.2f' % (subtotal, subtotal*0.07) if __name__ == '__main__': app.run()
mit
leancode-inc/kanban-angular-require
app/scripts/user-story/user-story-module.js
857
define([ 'angular', 'user-story/list/user-story-list-controller', 'user-story/view/user-story-controller', 'user-story/create/user-story-create-controller', 'user-story/user-story-service' ], function (angular, UserStoryListController, UserStoryController, UserStoryCreateController, UserStoryService ) { 'use strict'; var userStoryModule = angular.module('userStoryModule', ['ui.router']); userStoryModule.controller('UserStoryListController', UserStoryListController); userStoryModule.controller('UserStoryController', UserStoryController); userStoryModule.controller('UserStoryCreateController', UserStoryCreateController); userStoryModule.factory('UserStoryService', UserStoryService); });
mit
prepare/opencv.net
OpenCV.Net/Chain.cs
2244
using OpenCV.Net.Native; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace OpenCV.Net { /// <summary> /// Represents a Freeman chain where a polygon is specified as a sequence of steps in /// one of eight directions from a point origin. /// </summary> public class Chain : Seq { /// <summary> /// Gets the size of the <see cref="Chain"/> header, in bytes. /// </summary> public static new int HeaderSize { get { return SeqHelper.ChainHeaderSize; } } /// <summary> /// Gets the origin of the Freeman chain. /// </summary> public Point Origin { get { unsafe { return ((_CvChain*)handle.ToPointer())->origin; } } } /// <summary> /// Initializes a new <see cref="Chain"/> instance from a compatible /// <see cref="Seq"/>. /// </summary> /// <param name="seq">A <see cref="Seq"/> instance representing a Freeman chain.</param> /// <returns>A new <see cref="Chain"/> header for the specified <paramref name="seq"/>.</returns> public static Chain FromSeq(Seq seq) { if (seq == null) return null; var chain = new Chain(); chain.SetOwnerStorage(seq.Storage); chain.SetHandle(seq.DangerousGetHandle()); return chain; } /// <summary> /// Translates in sequence all of the points in the Freeman chain code. /// </summary> /// <returns> /// An <see cref="IEnumerable{Point}"/> whose elements are the result of translating /// the Freeman chain code into points. /// </returns> public IEnumerable<Point> ReadChainPoints() { _CvChainPtReader reader; NativeMethods.cvStartReadChainPoints(this, out reader); for (int i = 0; i < Count; i++) { yield return NativeMethods.cvReadChainPoint(ref reader); } } } }
mit
plzen/ebay
lib/ebay_trading/types/policy_compliance_status_code.rb
245
module EbayTrading # :nodoc: module Types # :nodoc: class PolicyComplianceStatusCode extend Enumerable extend Enumeration Good = 'Good' Fair = 'Fair' Poor = 'Poor' Failing = 'Failing' end end end
mit
chepeftw/WorldVolunteering
Web/src/World/UserBundle/Entity/User.php
5782
<?php // src/Acme/UserBundle/Entity/User.php namespace World\UserBundle\Entity; use FOS\UserBundle\Model\User as BaseUser; use Doctrine\ORM\Mapping as ORM; use Gedmo\Mapping\Annotation as Gedmo; use Symfony\Component\Validator\Constraints as Assert; /** * @ORM\Entity * @ORM\Table(name="fos_user") * @Gedmo\Loggable */ class User extends BaseUser { /** * @ORM\Id * @ORM\Column(type="integer") * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; /** * @var string * * @ORM\Column(name="first_name", type="string", length=255, nullable=true) * @Gedmo\Versioned */ protected $firstName; /** * @var string * * @ORM\Column(name="last_name", type="string", length=255, nullable=true) * @Gedmo\Versioned */ protected $lastName; /** * @var string * * @ORM\Column(name="phone", type="string", length=255, nullable=true) * @Gedmo\Versioned */ private $phone; /** * @var string * * @ORM\Column(name="type", type="string", length=255, nullable=true) * @Gedmo\Versioned */ private $type; /** * @var datetime $created * * @Gedmo\Timestampable(on="create") * @ORM\Column(type="datetime") */ private $created; /** * @var datetime $updated * * @Gedmo\Timestampable(on="update") * @ORM\Column(type="datetime") */ private $updated; /** * @var string $createdBy * * @Gedmo\Blameable(on="create") * @ORM\Column(type="string", nullable=true) */ private $createdBy; /** * @var string $updatedBy * * @Gedmo\Blameable(on="update") * @ORM\Column(type="string", nullable=true) */ private $updatedBy; /** * @var Association * * @ORM\OneToMany(targetEntity="World\VolunteerBundle\Entity\Association", mappedBy="user") */ protected $associations; public function __construct() { parent::__construct(); // your own logic } /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set firstName * * @param string $firstName * @return User */ public function setFirstName($firstName) { $this->firstName = $firstName; return $this; } /** * Get firstName * * @return string */ public function getFirstName() { return $this->firstName; } /** * Set lastName * * @param string $lastName * @return User */ public function setLastName($lastName) { $this->lastName = $lastName; return $this; } /** * Get lastName * * @return string */ public function getLastName() { return $this->lastName; } /** * Set phone * * @param string $phone * @return User */ public function setPhone($phone) { $this->phone = $phone; return $this; } /** * Get phone * * @return string */ public function getPhone() { return $this->phone; } /** * Set type * * @param string $type * @return User */ public function setType($type) { $this->type = $type; return $this; } /** * Get type * * @return string */ public function getType() { return $this->type; } /** * Set created * * @param \DateTime $created * @return User */ public function setCreated($created) { $this->created = $created; return $this; } /** * Get created * * @return \DateTime */ public function getCreated() { return $this->created; } /** * Set updated * * @param \DateTime $updated * @return User */ public function setUpdated($updated) { $this->updated = $updated; return $this; } /** * Get updated * * @return \DateTime */ public function getUpdated() { return $this->updated; } /** * Set createdBy * * @param string $createdBy * @return User */ public function setCreatedBy($createdBy) { $this->createdBy = $createdBy; return $this; } /** * Get createdBy * * @return string */ public function getCreatedBy() { return $this->createdBy; } /** * Set updatedBy * * @param string $updatedBy * @return User */ public function setUpdatedBy($updatedBy) { $this->updatedBy = $updatedBy; return $this; } /** * Get updatedBy * * @return string */ public function getUpdatedBy() { return $this->updatedBy; } /** * Add association * * @param \World\VolunteerBundle\Entity\Association $association * * @return User */ public function addAssociation(\World\VolunteerBundle\Entity\Association $association) { $this->associations[] = $association; return $this; } /** * Remove association * * @param \World\VolunteerBundle\Entity\Association $association */ public function removeAssociation(\World\VolunteerBundle\Entity\Association $association) { $this->associations->removeElement($association); } /** * Get associations * * @return \Doctrine\Common\Collections\Collection */ public function getAssociations() { return $this->associations; } }
mit
areleogitdev/areleofinish
areleo/app-assets/js/scripts/tables/datatables-extensions/datatable-responsive.js
5115
/*========================================================================================= File Name: datatables-responsive.js Description: Responsive Datatable ---------------------------------------------------------------------------------------- Item Name: Stack - Responsive Admin Theme Version: 1.1 Author: PIXINVENT Author URL: http://www.themeforest.net/user/pixinvent ==========================================================================================*/ $(document).ready(function() { /*********************************** * Configuration option * ***********************************/ $('.dataex-res-configuration').DataTable({ responsive: true }); /******************************** * `new` constructor * ********************************/ var tableConstructor = $('.dataex-res-constructor').DataTable(); new $.fn.dataTable.Responsive(tableConstructor); /********************************************** * Immediately show hidden details * **********************************************/ $('.dataex-res-immediately').DataTable({ responsive: { details: { display: $.fn.dataTable.Responsive.display.childRowImmediate, type: '' } } }); /************************************ * Modal details display * ************************************/ $('.dataex-res-modal').DataTable({ responsive: { details: { display: $.fn.dataTable.Responsive.display.modal({ header: function(row) { var data = row.data(); return 'Details for ' + data[0] + ' ' + data[1]; } }), renderer: function(api, rowIdx, columns) { var data = $.map(columns, function(col, i) { return '<tr>' + '<td>' + col.title + ':' + '</td> ' + '<td>' + col.data + '</td>' + '</tr>'; }).join(''); return $('<table/>').append(data); } } } }); /*********************************************** * With Buttons - Column visibility * ***********************************************/ $('.dataex-res-visibility').DataTable({ dom: 'Bfrtip', buttons: [ 'colvis' ] }); /******************************* * With FixedHeader * *******************************/ var tableFixedHeader = $('.dataex-res-fixedheader').DataTable({ responsive: true }); new $.fn.dataTable.FixedHeader(tableFixedHeader, { header: true, headerOffset: $('.header-navbar').outerHeight() }); /****************************** * With ColReorder * ******************************/ $('.dataex-res-colreorder').DataTable({ responsive: true, colReorder: true }); /******************************************* * Column controlled child rows * *******************************************/ $('.dataex-res-controlled').DataTable({ responsive: { details: { type: 'column' } }, columnDefs: [{ className: 'control', orderable: false, targets: 0 }], order: [1, 'asc'] }); /************************************* * Column control - right * *************************************/ $('.dataex-res-controlright').DataTable({ responsive: { details: { type: 'column', target: -1 } }, columnDefs: [{ className: 'control', orderable: false, targets: -1 }] }); /****************************************** * Whole row child row control * ******************************************/ $('.dataex-res-rowcontrol').DataTable({ responsive: { details: { type: 'column', target: 'tr' } }, columnDefs: [{ className: 'control', orderable: false, targets: 0 }], order: [1, 'asc'] }); /******************************** * Vertical scrolling * ********************************/ var table = $('.dataex-res-scrolling').DataTable({ scrollY: 300, paging: false }); // Resize datatable on menu width change and window resize $(function () { $(".menu-toggle").on('click', resize); // Resize function function resize() { setTimeout(function() { // ReDraw DataTable tableFixedHeader.draw(); }, 400); } }); });
mit
iassasin/wschatserver
client.cpp
2593
#include "client.hpp" #include "server.hpp" #include "algo.hpp" #include "packet.hpp" #include "packets.hpp" #include "logger.hpp" #include "utils.hpp" Client::Client(Server *srv, string tok) { server = srv; uid = 0; lastMessageTime = time(nullptr); lastPacketTime = lastMessageTime; messageCounter = 0; _isGirl = false; color = "gray"; token = std::move(tok); } Client::~Client() { } void Client::setConnection(ConnectionPtr conn) { connection = conn; if (conn) { lastClientIP = getRealClientIp(conn); } } void Client::onPacket(string msg) { auto pack = Packet::read(msg); if (pack) { lastPacketTime = time(nullptr); pack->process(*this); } else { Logger::warn("Dropped invalid packet: ", msg); } } void Client::onRevive() { auto ptr = self.lock(); for (RoomPtr room : rooms) { auto member = room->findMemberByClient(ptr); member->setStatus(Member::Status::online); sendPacket(PacketJoin(member, {})); sendPacket(PacketOnlineList(room, {})); // TODO: load_history flag? Or dedicated PacketHistory for (const string &s : room->getHistory()) { sendRawData(s); } if (!member->getNick().empty()) { room->sendPacketToAll(PacketStatus(member, Member::Status::back)); } } } void Client::onDisconnect() { setConnection(nullptr); auto ptr = self.lock(); for (RoomPtr room : rooms) { auto member = room->findMemberByClient(ptr); member->setStatus(Member::Status::orphan); if (!member->getNick().empty()) { room->sendPacketToAll(PacketStatus(member, Member::Status::orphan)); } } } void Client::onRemove() { auto ptr = self.lock(); for (RoomPtr room : rooms) { auto member = room->findMemberByClient(ptr); room->removeMember(ptr); } rooms.clear(); setConnection(nullptr); } void Client::onKick(RoomPtr room) { rooms.erase(room); } void Client::sendPacket(const Packet &pack) { // TODO: очередь сообщений, пока не вернулся? if (connection) { server->sendPacket(connection, pack); } } void Client::sendRawData(const string &data) { if (connection) { server->sendRawData(connection, data); } } MemberPtr Client::joinRoom(RoomPtr room) { auto ptr = self.lock(); auto member = room->addMember(ptr); if (member) { rooms.insert(room); member->setStatus(Member::Status::online); } return member; } void Client::leaveRoom(RoomPtr room) { if (rooms.erase(room) > 0) { room->removeMember(self.lock()); } } RoomPtr Client::getRoomByName(const string &name) { for (RoomPtr room : rooms) { if (room->getName() == name) { return room; } } return nullptr; }
mit
ray-di/Ray.Aop
src/VisitorFactory.php
1208
<?php declare(strict_types=1); namespace Ray\Aop; use PhpParser\NodeTraverser; use PhpParser\Parser; use Ray\Aop\Exception\InvalidSourceClassException; use ReflectionClass; use RuntimeException; use function file_get_contents; use function get_class; use function is_array; use function is_bool; final class VisitorFactory { /** @var Parser */ private $parser; public function __construct(Parser $parser) { $this->parser = $parser; } /** * @param ReflectionClass<object> $class */ public function __invoke(ReflectionClass $class): CodeVisitor { $traverser = new NodeTraverser(); $visitor = new CodeVisitor(); $traverser->addVisitor($visitor); $fileName = $class->getFileName(); if (is_bool($fileName)) { throw new InvalidSourceClassException(get_class($class)); } $file = file_get_contents($fileName); if ($file === false) { throw new RuntimeException($fileName); // @codeCoverageIgnore } $stmts = $this->parser->parse($file); if (is_array($stmts)) { $traverser->traverse($stmts); } return $visitor; } }
mit
takamin/aws-node-util
test/bnf.test.js
12863
"use strict"; var assert = require("chai").assert; var BNF = require("lex-bnf"); describe("BNF", function() { describe("Syntax definition allowing only 'A B','C D','X Y' or 'P Q'", () => { var bnf = new BNF("root", { "root": [ [ BNF.literal("A"), BNF.literal("B") ], [ "XX", "YY" ], [ BNF.literal("C"), BNF.literal("D") ], [ "PP", "QQ" ], ], "XX": [ [ BNF.literal("X") ] ], "YY": [ [ BNF.literal("Y") ] ], "PP": [ [ BNF.literal("P") ] ], "QQ": [ [ BNF.literal("Q") ] ], }); it("should match to 'A B'", () => { var result = bnf.parse("A B"); assert.equal(result.match, true); assert.equal(true, result.terms[0].match); assert.equal(true, result.terms[1].match); assert.deepEqual(["A","B"], result.getTermsList()); }); it("should match to 'X Y'", () => { var result = bnf.parse("X Y"); assert.equal(result.match, true); assert.equal(true, result.terms[0].match); assert.equal(true, result.terms[1].match); assert.deepEqual(["X","Y"], result.getTermsList()); }); it("should match to 'C D'", () => { var result = bnf.parse("C D"); assert.equal(result.match, true); assert.equal(true, result.terms[0].match); assert.equal(true, result.terms[1].match); assert.deepEqual(["C","D"], result.getTermsList()); }); it("should match to 'P Q'", () => { var result = bnf.parse("P Q"); assert.equal(result.match, true); assert.equal(true, result.terms[0].match); assert.equal(true, result.terms[1].match); assert.deepEqual(["P","Q"], result.getTermsList()); }); it("should not match to 'A'", () => { var result = bnf.parse("A"); assert.equal(result.match, false); }); it("should not match to 'C'", () => { var result = bnf.parse("C"); assert.equal(result.match, false); }); it("should not match to 'B A'", () => { var result = bnf.parse("B A"); assert.equal(result.match, false); }); it("should not match to 'X'", () => { var result = bnf.parse("X"); assert.equal(result.match, false); }); it("should not match to 'Q'", () => { var result = bnf.parse("Q"); assert.equal(result.match, false); }); it("should not match for 'Y X'", () => { var result = bnf.parse("Y X"); assert.equal(result.match, false); }); }); describe("SQLish BNF", () => { var SELECT = BNF.literal("SELECT"); var FROM = BNF.literal("FROM"); var WHERE = BNF.literal("WHERE"); var FILTER = BNF.literal("FILTER"); var LIMIT = BNF.literal("LIMIT"); var AND = BNF.literal("AND"); var OR = BNF.literal("OR"); var bnf = new BNF("sqlish-query", { "sqlish-query": [ [ "[select-clause]", "from-clause", "where-clause", "[filter-clause]", "[limit-clause]" ], ], "select-clause": [ [ SELECT, "key-list" ] ], "key-list": [ [ BNF.ident, BNF.comma, "key-list" ], [ BNF.ident ], ], "from-clause": [ [ FROM, BNF.ident ], ], "where-clause": [ [ WHERE, "condition-expression" ], ], "filter-clause": [ [ FILTER, "condition-expression" ], ], "condition-expression" : [ [ "and-expression", OR, "condition-expression" ], [ "and-expression" ], ], "and-expression" : [ [ "compare-expression", AND, "and-expression" ], [ "compare-expression" ], ], "compare-expression": [ [ BNF.ident, "compare-operator", "value" ], [ BNF.ident, BNF.literal("BETWEEN"), "between-range" ] ], "compare-operator": [ [BNF.literal("=") ], [BNF.literal("<") ], [BNF.literal("<=") ], [BNF.literal(">") ], [BNF.literal(">=") ], [BNF.literal("<>") ], ], "between-range": [ [ "value", AND, "value" ] ], "value": [ [ BNF.numlit ], [ BNF.ident ], ], "limit-clause": [ [ LIMIT, BNF.numlit ] ] }); describe("parse", function() { var result = bnf.parse( "FROM A WHERE B=0 AND C=DEF"); describe("result.term", function() { it("should has root BNF term", function() { assert.equal("sqlish-query", result.term); }); }); describe("result.lexCount", function() { it("should count lexical words", function() { assert.equal(10, result.lexCount); }); }); describe("result.match", function() { it("should set match", function() { assert.equal(true, result.match); }); }); describe("result.terms", function() { it("should be array", function() { assert.equal(true, Array.isArray(result.terms)); }); it("should not be affected by source", function() { var sources = [ "FROM A WHERE B=0 AND C=DEF", "SELECT X,Y,Z FROM A WHERE B=0 AND C=DEF", "FROM A WHERE B=0 LIMIT 123" ]; sources.forEach(function(source) { var result = bnf.parse(source); assert.equal(5, result.terms.length); assert.equal("select-clause", result.getTerm("select-clause").term); assert.equal("from-clause", result.getTerm("from-clause").term); assert.equal("where-clause", result.getTerm("where-clause").term); assert.equal("filter-clause", result.getTerm("filter-clause").term); assert.equal("limit-clause", result.getTerm("limit-clause").term); }); }); it("should be set false to match property", function() { var result = bnf.parse("FROM A WHERE B=0 AND C=DEF"); assert.equal(false, result.existsTerm("select-clause")); assert.equal(true, result.existsTerm("from-clause")); assert.equal(true, result.existsTerm("where-clause")); assert.equal(false, result.existsTerm("filter-clause")); assert.equal(false, result.existsTerm("limit-clause")); }); it("should be set valid information to optional term", function() { var result = bnf.parse("SELECT X,Y,Z FROM A WHERE B=0 AND C=DEF"); assert.equal(true, result.existsTerm("select-clause")); assert.equal(true, result.existsTerm("from-clause")); assert.equal(true, result.existsTerm("where-clause")); assert.equal(false, result.existsTerm("filter-clause")); assert.equal(false, result.existsTerm("limit-clause")); }); it("should be set false to match property", function() { var result = bnf.parse("FROM A WHERE B=0 LIMIT 123"); assert.equal(false, result.existsTerm("select-clause")); assert.equal(true, result.existsTerm("from-clause")); assert.equal(true, result.existsTerm("where-clause")); assert.equal(false, result.existsTerm("filter-clause")); assert.equal(true, result.existsTerm("limit-clause")); }); }); }); describe("BNF.ParseResult", function() { describe("#existTerm", function() { it("should not recognize the select-clause term undescribed", function() { var result = bnf.parse("FROM A WHERE B=0 LIMIT 123"); assert.equal(false, result.existsTerm("select-clause")); }); it("should not recognize the filter-clause term undescribed", function() { var result = bnf.parse("FROM A WHERE B=0 LIMIT 123"); assert.equal(false, result.existsTerm("filter-clause")); }); it("should recognize the from-clause term described", function() { var result = bnf.parse("FROM A WHERE B=0 LIMIT 123"); assert.equal(true, result.existsTerm("from-clause")); }); it("should recognize the where-clause term described", function() { var result = bnf.parse("FROM A WHERE B=0 LIMIT 123"); assert.equal(true, result.existsTerm("where-clause")); }); it("should recognize the limit-clause term described", function() { var result = bnf.parse("FROM A WHERE B=0 LIMIT 123"); assert.equal(true, result.existsTerm("limit-clause")); }); }); describe("#getWordsList", function() { it("should returns the token list of the compare-expression", function() { var result = bnf.parse("SELECT X,Y,Z FROM A WHERE B=0 AND C=DEF"); assert.deepEqual([ ["B", "=", "0"], ["C", "=", "DEF"], ], result.getWordsList("compare-expression")); }); it("should returns the tokens list of the from-clause", function() { var result = bnf.parse("SELECT X,Y,Z FROM A WHERE B=0 AND C=DEF"); assert.deepEqual(["FROM", "A"], result.getTerm("from-clause").getTermsList()); }); }); describe("#getTermsList", function() { it("should returns the tokens list of the select-clause", function() { var result = bnf.parse("SELECT X,Y,Z FROM A WHERE B=0 AND C=DEF"); assert.deepEqual(["X", ",", "Y", ",", "Z"], result.getTerm("select-clause") .getTerm("key-list").getTermsList()); }); it("should returns the tokens list of the from-clause", function() { var result = bnf.parse("SELECT X,Y,Z FROM A WHERE B=0 AND C=DEF"); assert.deepEqual(["FROM", "A"], result.getTerm("from-clause").getTermsList()); }); }); }); describe("lexical analysis", function() { describe("unexpected termination error", function() { it("should NOT be thrown for terminating with identifier", function() { assert.doesNotThrow(() => { var result = bnf.parse("FROM A WHERE B=0 AND C=DEF"); }); }); it("should NOT be thrown for terminating with number literal", function() { assert.doesNotThrow(() => { var result = bnf.parse("FROM A WHERE B=0 AND C=123"); }); }); it("should NOT be thrown for terminating with whitespace", function() { assert.doesNotThrow(() => { var result = bnf.parse("FROM A WHERE B=0 AND C=123 "); }); }); it("should NOT be thrown for terminating with punct", function() { assert.doesNotThrow(() => { var result = bnf.parse("FROM A WHERE B=0 AND C=123;"); }); }); it("should NOT be thrown for terminating in line comment", function() { assert.doesNotThrow(() => { var result = bnf.parse("FROM A WHERE B=0 AND C='DEF' // /* "); }); }); }); }); }); });
mit
leoarry/SpeedyMVVM
SpeedyMVVM.PCL/Navigation/Interfaces/IDialogBoxService.cs
548
using SpeedyMVVM.Utilities; using System.Threading.Tasks; namespace SpeedyMVVM.Navigation { /// <summary> /// Define a service for basic dialog boxes. /// </summary> public interface IDialogBoxService { Task<string> ShowInputBox(string message, string title, string iconPath); Task<bool?> ShowMessageBox(string message, string title, DialogBoxEnum BoxType, DialogBoxIconEnum icon); Task<bool?> ShowViewModel(IViewModelBase viewModel); Task<bool?> ShowDialogBox(IDialogBox dialogBox); } }
mit
cloudwu/ltask
examples/timer/user.lua
492
local ltask = require "ltask" local S = setmetatable({}, { __gc = function() print "User exit" end } ) print ("User init :", ...) function S.wait(ti) if ti < 10 then error("Error : " .. ti) end ltask.sleep(ti) return ti end function S.ping(...) ltask.timeout(10, function() print(1) end) ltask.timeout(20, function() print(2) end) ltask.timeout(30, function() print(3) end) ltask.sleep(40) -- sleep 0.4 sec return "PING", ... end function S.exit() ltask.quit() end return S
mit
juannfrancisco/adm-ceppi
ws/ceppi-core/src/main/java/cl/ml/ceppi/core/service/SocioService.java
320
package cl.ml.ceppi.core.service; import java.util.List; import cl.ml.ceppi.core.model.socio.Socio; /** * @author Maldonado León * */ public interface SocioService { void save(Socio socio); void update(Socio socio); void delete(Socio socio); List<Socio> listSocio(); Socio findSocioById(int id); }
mit
gubatron/openbazaar-go
vendor/github.com/OpenBazaar/spvwallet/sortsignsend.go
22289
// Copyright (C) 2015-2016 The Lightning Network Developers // Copyright (c) 2016-2017 The OpenBazaar Developers package spvwallet import ( "bytes" "crypto/sha256" "encoding/hex" "errors" "fmt" "github.com/OpenBazaar/wallet-interface" "github.com/btcsuite/btcd/blockchain" "github.com/btcsuite/btcd/btcec" "github.com/btcsuite/btcd/chaincfg/chainhash" "github.com/btcsuite/btcd/txscript" "github.com/btcsuite/btcd/wire" btc "github.com/btcsuite/btcutil" "github.com/btcsuite/btcutil/coinset" hd "github.com/btcsuite/btcutil/hdkeychain" "github.com/btcsuite/btcutil/txsort" "github.com/btcsuite/btcwallet/wallet/txauthor" "github.com/btcsuite/btcwallet/wallet/txrules" "time" ) func (s *SPVWallet) Broadcast(tx *wire.MsgTx) error { // Our own tx; don't keep track of false positives _, err := s.txstore.Ingest(tx, 0, time.Now()) if err != nil { return err } log.Debugf("Broadcasting tx %s to peers", tx.TxHash().String()) s.wireService.MsgChan() <- updateFiltersMsg{} for _, peer := range s.peerManager.ConnectedPeers() { peer.QueueMessageWithEncoding(tx, nil, wire.WitnessEncoding) } return nil } type Coin struct { TxHash *chainhash.Hash TxIndex uint32 TxValue btc.Amount TxNumConfs int64 ScriptPubKey []byte } func (c *Coin) Hash() *chainhash.Hash { return c.TxHash } func (c *Coin) Index() uint32 { return c.TxIndex } func (c *Coin) Value() btc.Amount { return c.TxValue } func (c *Coin) PkScript() []byte { return c.ScriptPubKey } func (c *Coin) NumConfs() int64 { return c.TxNumConfs } func (c *Coin) ValueAge() int64 { return int64(c.TxValue) * c.TxNumConfs } func NewCoin(txid []byte, index uint32, value btc.Amount, numConfs int64, scriptPubKey []byte) coinset.Coin { shaTxid, _ := chainhash.NewHash(txid) c := &Coin{ TxHash: shaTxid, TxIndex: index, TxValue: value, TxNumConfs: numConfs, ScriptPubKey: scriptPubKey, } return coinset.Coin(c) } func (w *SPVWallet) gatherCoins() map[coinset.Coin]*hd.ExtendedKey { height, _ := w.blockchain.db.Height() utxos, _ := w.txstore.Utxos().GetAll() m := make(map[coinset.Coin]*hd.ExtendedKey) for _, u := range utxos { if u.WatchOnly { continue } var confirmations int32 if u.AtHeight > 0 { confirmations = int32(height) - u.AtHeight } c := NewCoin(u.Op.Hash.CloneBytes(), u.Op.Index, btc.Amount(u.Value), int64(confirmations), u.ScriptPubkey) addr, err := w.ScriptToAddress(u.ScriptPubkey) if err != nil { continue } key, err := w.keyManager.GetKeyForScript(addr.ScriptAddress()) if err != nil { continue } m[c] = key } return m } func (w *SPVWallet) Spend(amount int64, addr btc.Address, feeLevel wallet.FeeLevel) (*chainhash.Hash, error) { tx, err := w.buildTx(amount, addr, feeLevel, nil) if err != nil { return nil, err } // Broadcast err = w.Broadcast(tx) if err != nil { return nil, err } ch := tx.TxHash() return &ch, nil } var BumpFeeAlreadyConfirmedError = errors.New("Transaction is confirmed, cannot bump fee") var BumpFeeTransactionDeadError = errors.New("Cannot bump fee of dead transaction") var BumpFeeNotFoundError = errors.New("Transaction either doesn't exist or has already been spent") func (w *SPVWallet) BumpFee(txid chainhash.Hash) (*chainhash.Hash, error) { txn, err := w.txstore.Txns().Get(txid) if err != nil { return nil, err } if txn.Height > 0 { return nil, BumpFeeAlreadyConfirmedError } if txn.Height < 0 { return nil, BumpFeeTransactionDeadError } // Check stxos for RBF opportunity /*stxos, _ := w.txstore.Stxos().GetAll() for _, s := range stxos { if s.SpendTxid.IsEqual(&txid) { r := bytes.NewReader(txn.Bytes) msgTx := wire.NewMsgTx(1) msgTx.BtcDecode(r, 1) for i, output := range msgTx.TxOut { key, err := w.txstore.GetKeyForScript(output.PkScript) if key != nil && err == nil { // This is our change output // Calculate change - additional fee feePerByte := w.GetFeePerByte(PRIOIRTY) estimatedSize := EstimateSerializeSize(len(msgTx.TxIn), msgTx.TxOut, false) fee := estimatedSize * int(feePerByte) newValue := output.Value - int64(fee) // Check if still above dust value if newValue <= 0 || txrules.IsDustAmount(btc.Amount(newValue), len(output.PkScript), txrules.DefaultRelayFeePerKb) { msgTx.TxOut = append(msgTx.TxOut[:i], msgTx.TxOut[i+1:]...) } else { output.Value = newValue } // Bump sequence number optInRBF := false for _, input := range msgTx.TxIn { if input.Sequence < 4294967294 { input.Sequence++ optInRBF = true } } if !optInRBF { break } //TODO: Re-sign transaction // Mark original tx as dead if err = w.txstore.markAsDead(txid); err != nil { return nil, err } // Broadcast new tx if err := w.Broadcast(msgTx); err != nil { return nil, err } newTxid := msgTx.TxHash() return &newTxid, nil } } } }*/ // Check utxos for CPFP utxos, _ := w.txstore.Utxos().GetAll() for _, u := range utxos { if u.Op.Hash.IsEqual(&txid) && u.AtHeight == 0 { addr, err := w.ScriptToAddress(u.ScriptPubkey) if err != nil { return nil, err } key, err := w.keyManager.GetKeyForScript(addr.ScriptAddress()) if err != nil { return nil, err } h, err := hex.DecodeString(u.Op.Hash.String()) if err != nil { return nil, err } in := wallet.TransactionInput{ LinkedAddress: addr, OutpointIndex: u.Op.Index, OutpointHash: h, Value: u.Value, } transactionID, err := w.SweepAddress([]wallet.TransactionInput{in}, nil, key, nil, wallet.FEE_BUMP) if err != nil { return nil, err } return transactionID, nil } } return nil, BumpFeeNotFoundError } func (w *SPVWallet) EstimateFee(ins []wallet.TransactionInput, outs []wallet.TransactionOutput, feePerByte uint64) uint64 { tx := new(wire.MsgTx) for _, out := range outs { scriptPubKey, _ := txscript.PayToAddrScript(out.Address) output := wire.NewTxOut(out.Value, scriptPubKey) tx.TxOut = append(tx.TxOut, output) } estimatedSize := EstimateSerializeSize(len(ins), tx.TxOut, false, P2PKH) fee := estimatedSize * int(feePerByte) return uint64(fee) } // Build a spend transaction for the amount and return the transaction fee func (w *SPVWallet) EstimateSpendFee(amount int64, feeLevel wallet.FeeLevel) (uint64, error) { // Since this is an estimate we can use a dummy output address. Let's use a long one so we don't under estimate. addr, err := btc.DecodeAddress("bc1qxtq7ha2l5qg70atpwp3fus84fx3w0v2w4r2my7gt89ll3w0vnlgspu349h", w.params) if err != nil { return 0, err } tx, err := w.buildTx(amount, addr, feeLevel, nil) if err != nil { return 0, err } var outval int64 for _, output := range tx.TxOut { outval += output.Value } var inval int64 utxos, err := w.txstore.Utxos().GetAll() if err != nil { return 0, err } for _, input := range tx.TxIn { for _, utxo := range utxos { if utxo.Op.Hash.IsEqual(&input.PreviousOutPoint.Hash) && utxo.Op.Index == input.PreviousOutPoint.Index { inval += utxo.Value break } } } if inval < outval { return 0, errors.New("Error building transaction: inputs less than outputs") } return uint64(inval - outval), err } func (w *SPVWallet) GenerateMultisigScript(keys []hd.ExtendedKey, threshold int, timeout time.Duration, timeoutKey *hd.ExtendedKey) (addr btc.Address, redeemScript []byte, err error) { if uint32(timeout.Hours()) > 0 && timeoutKey == nil { return nil, nil, errors.New("Timeout key must be non nil when using an escrow timeout") } if len(keys) < threshold { return nil, nil, fmt.Errorf("unable to generate multisig script with "+ "%d required signatures when there are only %d public "+ "keys available", threshold, len(keys)) } var ecKeys []*btcec.PublicKey for _, key := range keys { ecKey, err := key.ECPubKey() if err != nil { return nil, nil, err } ecKeys = append(ecKeys, ecKey) } builder := txscript.NewScriptBuilder() if uint32(timeout.Hours()) == 0 { builder.AddInt64(int64(threshold)) for _, key := range ecKeys { builder.AddData(key.SerializeCompressed()) } builder.AddInt64(int64(len(ecKeys))) builder.AddOp(txscript.OP_CHECKMULTISIG) } else { ecKey, err := timeoutKey.ECPubKey() if err != nil { return nil, nil, err } sequenceLock := blockchain.LockTimeToSequence(false, uint32(timeout.Hours()*6)) builder.AddOp(txscript.OP_IF) builder.AddInt64(int64(threshold)) for _, key := range ecKeys { builder.AddData(key.SerializeCompressed()) } builder.AddInt64(int64(len(ecKeys))) builder.AddOp(txscript.OP_CHECKMULTISIG) builder.AddOp(txscript.OP_ELSE). AddInt64(int64(sequenceLock)). AddOp(txscript.OP_CHECKSEQUENCEVERIFY). AddOp(txscript.OP_DROP). AddData(ecKey.SerializeCompressed()). AddOp(txscript.OP_CHECKSIG). AddOp(txscript.OP_ENDIF) } redeemScript, err = builder.Script() if err != nil { return nil, nil, err } witnessProgram := sha256.Sum256(redeemScript) addr, err = btc.NewAddressWitnessScriptHash(witnessProgram[:], w.params) if err != nil { return nil, nil, err } return addr, redeemScript, nil } func (w *SPVWallet) CreateMultisigSignature(ins []wallet.TransactionInput, outs []wallet.TransactionOutput, key *hd.ExtendedKey, redeemScript []byte, feePerByte uint64) ([]wallet.Signature, error) { var sigs []wallet.Signature tx := wire.NewMsgTx(1) for _, in := range ins { ch, err := chainhash.NewHashFromStr(hex.EncodeToString(in.OutpointHash)) if err != nil { return sigs, err } outpoint := wire.NewOutPoint(ch, in.OutpointIndex) input := wire.NewTxIn(outpoint, []byte{}, [][]byte{}) tx.TxIn = append(tx.TxIn, input) } for _, out := range outs { scriptPubKey, err := txscript.PayToAddrScript(out.Address) if err != nil { return sigs, err } output := wire.NewTxOut(out.Value, scriptPubKey) tx.TxOut = append(tx.TxOut, output) } // Subtract fee txType := P2SH_2of3_Multisig _, err := LockTimeFromRedeemScript(redeemScript) if err == nil { txType = P2SH_Multisig_Timelock_2Sigs } estimatedSize := EstimateSerializeSize(len(ins), tx.TxOut, false, txType) fee := estimatedSize * int(feePerByte) if len(tx.TxOut) > 0 { feePerOutput := fee / len(tx.TxOut) for _, output := range tx.TxOut { output.Value -= int64(feePerOutput) } } // BIP 69 sorting txsort.InPlaceSort(tx) signingKey, err := key.ECPrivKey() if err != nil { return sigs, err } hashes := txscript.NewTxSigHashes(tx) for i := range tx.TxIn { sig, err := txscript.RawTxInWitnessSignature(tx, hashes, i, ins[i].Value, redeemScript, txscript.SigHashAll, signingKey) if err != nil { continue } bs := wallet.Signature{InputIndex: uint32(i), Signature: sig} sigs = append(sigs, bs) } return sigs, nil } func (w *SPVWallet) Multisign(ins []wallet.TransactionInput, outs []wallet.TransactionOutput, sigs1 []wallet.Signature, sigs2 []wallet.Signature, redeemScript []byte, feePerByte uint64, broadcast bool) ([]byte, error) { tx := wire.NewMsgTx(1) for _, in := range ins { ch, err := chainhash.NewHashFromStr(hex.EncodeToString(in.OutpointHash)) if err != nil { return nil, err } outpoint := wire.NewOutPoint(ch, in.OutpointIndex) input := wire.NewTxIn(outpoint, []byte{}, [][]byte{}) tx.TxIn = append(tx.TxIn, input) } for _, out := range outs { scriptPubKey, err := txscript.PayToAddrScript(out.Address) if err != nil { return nil, err } output := wire.NewTxOut(out.Value, scriptPubKey) tx.TxOut = append(tx.TxOut, output) } // Subtract fee txType := P2SH_2of3_Multisig _, err := LockTimeFromRedeemScript(redeemScript) if err == nil { txType = P2SH_Multisig_Timelock_2Sigs } estimatedSize := EstimateSerializeSize(len(ins), tx.TxOut, false, txType) fee := estimatedSize * int(feePerByte) if len(tx.TxOut) > 0 { feePerOutput := fee / len(tx.TxOut) for _, output := range tx.TxOut { output.Value -= int64(feePerOutput) } } // BIP 69 sorting txsort.InPlaceSort(tx) // Check if time locked var timeLocked bool if redeemScript[0] == txscript.OP_IF { timeLocked = true } for i, input := range tx.TxIn { var sig1 []byte var sig2 []byte for _, sig := range sigs1 { if int(sig.InputIndex) == i { sig1 = sig.Signature break } } for _, sig := range sigs2 { if int(sig.InputIndex) == i { sig2 = sig.Signature break } } witness := wire.TxWitness{[]byte{}, sig1, sig2} if timeLocked { witness = append(witness, []byte{0x01}) } witness = append(witness, redeemScript) input.Witness = witness } // broadcast if broadcast { w.Broadcast(tx) } var buf bytes.Buffer tx.BtcEncode(&buf, wire.ProtocolVersion, wire.WitnessEncoding) return buf.Bytes(), nil } func (w *SPVWallet) SweepAddress(ins []wallet.TransactionInput, address *btc.Address, key *hd.ExtendedKey, redeemScript *[]byte, feeLevel wallet.FeeLevel) (*chainhash.Hash, error) { var internalAddr btc.Address if address != nil { internalAddr = *address } else { internalAddr = w.CurrentAddress(wallet.INTERNAL) } script, err := txscript.PayToAddrScript(internalAddr) if err != nil { return nil, err } var val int64 var inputs []*wire.TxIn additionalPrevScripts := make(map[wire.OutPoint][]byte) for _, in := range ins { val += in.Value ch, err := chainhash.NewHashFromStr(hex.EncodeToString(in.OutpointHash)) if err != nil { return nil, err } script, err := txscript.PayToAddrScript(in.LinkedAddress) if err != nil { return nil, err } outpoint := wire.NewOutPoint(ch, in.OutpointIndex) input := wire.NewTxIn(outpoint, []byte{}, [][]byte{}) inputs = append(inputs, input) additionalPrevScripts[*outpoint] = script } out := wire.NewTxOut(val, script) txType := P2PKH if redeemScript != nil { txType = P2SH_1of2_Multisig _, err := LockTimeFromRedeemScript(*redeemScript) if err == nil { txType = P2SH_Multisig_Timelock_1Sig } } estimatedSize := EstimateSerializeSize(len(ins), []*wire.TxOut{out}, false, txType) // Calculate the fee feePerByte := int(w.GetFeePerByte(feeLevel)) fee := estimatedSize * feePerByte outVal := val - int64(fee) if outVal < 0 { outVal = 0 } out.Value = outVal tx := &wire.MsgTx{ Version: wire.TxVersion, TxIn: inputs, TxOut: []*wire.TxOut{out}, LockTime: 0, } // BIP 69 sorting txsort.InPlaceSort(tx) // Sign tx privKey, err := key.ECPrivKey() if err != nil { return nil, err } pk := privKey.PubKey().SerializeCompressed() addressPub, err := btc.NewAddressPubKey(pk, w.params) getKey := txscript.KeyClosure(func(addr btc.Address) (*btcec.PrivateKey, bool, error) { if addressPub.EncodeAddress() == addr.EncodeAddress() { wif, err := btc.NewWIF(privKey, w.params, true) if err != nil { return nil, false, err } return wif.PrivKey, wif.CompressPubKey, nil } return nil, false, errors.New("Not found") }) getScript := txscript.ScriptClosure(func(addr btc.Address) ([]byte, error) { if redeemScript == nil { return []byte{}, nil } return *redeemScript, nil }) // Check if time locked var timeLocked bool if redeemScript != nil { rs := *redeemScript if rs[0] == txscript.OP_IF { timeLocked = true tx.Version = 2 for _, txIn := range tx.TxIn { locktime, err := LockTimeFromRedeemScript(*redeemScript) if err != nil { return nil, err } txIn.Sequence = locktime } } } hashes := txscript.NewTxSigHashes(tx) for i, txIn := range tx.TxIn { if redeemScript == nil { prevOutScript := additionalPrevScripts[txIn.PreviousOutPoint] script, err := txscript.SignTxOutput(w.params, tx, i, prevOutScript, txscript.SigHashAll, getKey, getScript, txIn.SignatureScript) if err != nil { return nil, errors.New("Failed to sign transaction") } txIn.SignatureScript = script } else { sig, err := txscript.RawTxInWitnessSignature(tx, hashes, i, ins[i].Value, *redeemScript, txscript.SigHashAll, privKey) if err != nil { return nil, err } var witness wire.TxWitness if timeLocked { witness = wire.TxWitness{sig, []byte{}} } else { witness = wire.TxWitness{[]byte{}, sig} } witness = append(witness, *redeemScript) txIn.Witness = witness } } // broadcast w.Broadcast(tx) txid := tx.TxHash() return &txid, nil } func (w *SPVWallet) buildTx(amount int64, addr btc.Address, feeLevel wallet.FeeLevel, optionalOutput *wire.TxOut) (*wire.MsgTx, error) { // Check for dust script, _ := txscript.PayToAddrScript(addr) if txrules.IsDustAmount(btc.Amount(amount), len(script), txrules.DefaultRelayFeePerKb) { return nil, wallet.ErrorDustAmount } var additionalPrevScripts map[wire.OutPoint][]byte var additionalKeysByAddress map[string]*btc.WIF // Create input source coinMap := w.gatherCoins() coins := make([]coinset.Coin, 0, len(coinMap)) for k := range coinMap { coins = append(coins, k) } inputSource := func(target btc.Amount) (total btc.Amount, inputs []*wire.TxIn, inputValues []btc.Amount, scripts [][]byte, err error) { coinSelector := coinset.MaxValueAgeCoinSelector{MaxInputs: 10000, MinChangeAmount: btc.Amount(0)} coins, err := coinSelector.CoinSelect(target, coins) if err != nil { return total, inputs, []btc.Amount{}, scripts, wallet.ErrorInsuffientFunds } additionalPrevScripts = make(map[wire.OutPoint][]byte) additionalKeysByAddress = make(map[string]*btc.WIF) for _, c := range coins.Coins() { total += c.Value() outpoint := wire.NewOutPoint(c.Hash(), c.Index()) in := wire.NewTxIn(outpoint, []byte{}, [][]byte{}) in.Sequence = 0 // Opt-in RBF so we can bump fees inputs = append(inputs, in) additionalPrevScripts[*outpoint] = c.PkScript() key := coinMap[c] addr, err := key.Address(w.params) if err != nil { continue } privKey, err := key.ECPrivKey() if err != nil { continue } wif, _ := btc.NewWIF(privKey, w.params, true) additionalKeysByAddress[addr.EncodeAddress()] = wif } return total, inputs, []btc.Amount{}, scripts, nil } // Get the fee per kilobyte feePerKB := int64(w.GetFeePerByte(feeLevel)) * 1000 // outputs out := wire.NewTxOut(amount, script) // Create change source changeSource := func() ([]byte, error) { addr := w.CurrentAddress(wallet.INTERNAL) script, err := txscript.PayToAddrScript(addr) if err != nil { return []byte{}, err } return script, nil } outputs := []*wire.TxOut{out} if optionalOutput != nil { outputs = append(outputs, optionalOutput) } authoredTx, err := NewUnsignedTransaction(outputs, btc.Amount(feePerKB), inputSource, changeSource) if err != nil { return nil, err } // BIP 69 sorting txsort.InPlaceSort(authoredTx.Tx) // Sign tx getKey := txscript.KeyClosure(func(addr btc.Address) (*btcec.PrivateKey, bool, error) { addrStr := addr.EncodeAddress() wif := additionalKeysByAddress[addrStr] return wif.PrivKey, wif.CompressPubKey, nil }) getScript := txscript.ScriptClosure(func( addr btc.Address) ([]byte, error) { return []byte{}, nil }) for i, txIn := range authoredTx.Tx.TxIn { prevOutScript := additionalPrevScripts[txIn.PreviousOutPoint] script, err := txscript.SignTxOutput(w.params, authoredTx.Tx, i, prevOutScript, txscript.SigHashAll, getKey, getScript, txIn.SignatureScript) if err != nil { return nil, errors.New("Failed to sign transaction") } txIn.SignatureScript = script } return authoredTx.Tx, nil } func NewUnsignedTransaction(outputs []*wire.TxOut, feePerKb btc.Amount, fetchInputs txauthor.InputSource, fetchChange txauthor.ChangeSource) (*txauthor.AuthoredTx, error) { var targetAmount btc.Amount for _, txOut := range outputs { targetAmount += btc.Amount(txOut.Value) } estimatedSize := EstimateSerializeSize(1, outputs, true, P2PKH) targetFee := txrules.FeeForSerializeSize(feePerKb, estimatedSize) for { inputAmount, inputs, _, scripts, err := fetchInputs(targetAmount + targetFee) if err != nil { return nil, err } if inputAmount < targetAmount+targetFee { return nil, errors.New("insufficient funds available to construct transaction") } maxSignedSize := EstimateSerializeSize(len(inputs), outputs, true, P2PKH) maxRequiredFee := txrules.FeeForSerializeSize(feePerKb, maxSignedSize) remainingAmount := inputAmount - targetAmount if remainingAmount < maxRequiredFee { targetFee = maxRequiredFee continue } unsignedTransaction := &wire.MsgTx{ Version: wire.TxVersion, TxIn: inputs, TxOut: outputs, LockTime: 0, } changeIndex := -1 changeAmount := inputAmount - targetAmount - maxRequiredFee if changeAmount != 0 && !txrules.IsDustAmount(changeAmount, P2PKHOutputSize, txrules.DefaultRelayFeePerKb) { changeScript, err := fetchChange() if err != nil { return nil, err } if len(changeScript) > P2PKHPkScriptSize { return nil, errors.New("fee estimation requires change " + "scripts no larger than P2PKH output scripts") } change := wire.NewTxOut(int64(changeAmount), changeScript) l := len(outputs) unsignedTransaction.TxOut = append(outputs[:l:l], change) changeIndex = l } return &txauthor.AuthoredTx{ Tx: unsignedTransaction, PrevScripts: scripts, TotalInput: inputAmount, ChangeIndex: changeIndex, }, nil } } func (w *SPVWallet) GetFeePerByte(feeLevel wallet.FeeLevel) uint64 { return w.feeProvider.GetFeePerByte(feeLevel) } func LockTimeFromRedeemScript(redeemScript []byte) (uint32, error) { if len(redeemScript) < 113 { return 0, errors.New("Redeem script invalid length") } if redeemScript[106] != 103 { return 0, errors.New("Invalid redeem script") } if redeemScript[107] == 0 { return 0, nil } if 81 <= redeemScript[107] && redeemScript[107] <= 96 { return uint32((redeemScript[107] - 81) + 1), nil } var v []byte op := redeemScript[107] if 1 <= op && op <= 75 { for i := 0; i < int(op); i++ { v = append(v, []byte{redeemScript[108+i]}...) } } else { return 0, errors.New("Too many bytes pushed for sequence") } var result int64 for i, val := range v { result |= int64(val) << uint8(8*i) } return uint32(result), nil }
mit