prompt
large_stringlengths
70
991k
completion
large_stringlengths
0
1.02k
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.db import models from django.contrib.auth.models import User from django.core.exceptions import ValidationError import datetime # Create your models here. class Article(models.Model): title = models.CharField(max_length=255)<|fim▁hole|> brief = models.CharField(null=True,blank=True,max_length=255) category = models.ForeignKey("Category") content = models.TextField(u"文章内容") author = models.ForeignKey("UserProfile") pub_date = models.DateTimeField(blank=True,null=True) last_modify = models.DateTimeField(auto_now=True) priority = models.IntegerField(u"优先级",default=1000) head_img = models.ImageField(u"文章标题图片",upload_to="uploads") status_choices = (('draft',u"草稿"), ('published',u"已发布"), ('hidden',u"隐藏"), ) status = models.CharField(choices=status_choices,default='published',max_length=32) def __str__(self): return self.title def clean(self): # Don't allow draft entries to have a pub_date. if self.status == 'draft' and self.pub_date is not None: raise ValidationError(('Draft entries may not have a publication date.')) # Set the pub_date for published items if it hasn't been set already. if self.status == 'published' and self.pub_date is None: self.pub_date = datetime.date.today() class Comment(models.Model): article = models.ForeignKey(Article,verbose_name=u"所属文章") parent_comment = models.ForeignKey('self',related_name='my_children',blank=True,null=True) comment_choices = ((1,u'评论'), (2,u"点赞")) comment_type = models.IntegerField(choices=comment_choices,default=1) user = models.ForeignKey("UserProfile") comment = models.TextField(blank=True,null=True) date = models.DateTimeField(auto_now_add=True) def clean(self): if self.comment_type == 1 and len(self.comment) ==0: raise ValidationError(u'评论内容不能为空,sb') def __str__(self): return "C:%s" %(self.comment) class Category(models.Model): name = models.CharField(max_length=64,unique=True) brief = models.CharField(null=True,blank=True,max_length=255) set_as_top_menu = models.BooleanField(default=False) position_index = models.SmallIntegerField() admins = models.ManyToManyField("UserProfile",blank=True) def __str__(self): return self.name class UserProfile(models.Model): user = models.OneToOneField(User) name =models.CharField(max_length=32) signature= models.CharField(max_length=255,blank=True,null=True) head_img = models.ImageField(height_field=150,width_field=150,blank=True,null=True) def __str__(self): return self.name<|fim▁end|>
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>use std::ops::Range; /// Return true if two ranges overlap. /// /// assert_eq!(ranges::overlap(0..7, 3..10), true); /// assert_eq!(ranges::overlap(1..5, 101..105), false); /// /// If either range is empty, they don't count as overlapping. ///<|fim▁hole|>pub fn overlap(r1: Range<usize>, r2: Range<usize>) -> bool { r1.start < r1.end && r2.start < r2.end && r1.start < r2.end && r2.start < r1.end }<|fim▁end|>
/// assert_eq!(ranges::overlap(0..0, 0..10), false); /// assert_eq!(ranges::overlap(0..10, 1..1), false); ///
<|file_name|>haproxy.go<|end_file_name|><|fim▁begin|>package configuration type HAProxy struct { TemplatePath string OutputPath string ReloadCommand string<|fim▁hole|><|fim▁end|>
}
<|file_name|>mocha.js<|end_file_name|><|fim▁begin|>;(function(){ // CommonJS require() function require(p){ var path = require.resolve(p) , mod = require.modules[path]; if (!mod) throw new Error('failed to require "' + p + '"'); if (!mod.exports) { mod.exports = {}; mod.call(mod.exports, mod, mod.exports, require.relative(path)); } return mod.exports; } require.modules = {}; require.resolve = function (path){ var orig = path , reg = path + '.js' , index = path + '/index.js'; return require.modules[reg] && reg || require.modules[index] && index || orig; }; require.register = function (path, fn){ require.modules[path] = fn; }; require.relative = function (parent) { return function(p){ if ('.' != p.charAt(0)) return require(p); var path = parent.split('/') , segs = p.split('/'); path.pop(); for (var i = 0; i < segs.length; i++) { var seg = segs[i]; if ('..' == seg) path.pop(); else if ('.' != seg) path.push(seg); } return require(path.join('/')); }; }; require.register("browser/debug.js", function(module, exports, require){ module.exports = function(type){ return function(){ } }; }); // module: browser/debug.js require.register("browser/diff.js", function(module, exports, require){ /* See LICENSE file for terms of use */ /* * Text diff implementation. * * This library supports the following APIS: * JsDiff.diffChars: Character by character diff * JsDiff.diffWords: Word (as defined by \b regex) diff which ignores whitespace * JsDiff.diffLines: Line based diff * * JsDiff.diffCss: Diff targeted at CSS content * * These methods are based on the implementation proposed in * "An O(ND) Difference Algorithm and its Variations" (Myers, 1986). * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927 */ var JsDiff = (function() { /*jshint maxparams: 5*/ function clonePath(path) { return { newPos: path.newPos, components: path.components.slice(0) }; } function removeEmpty(array) { var ret = []; for (var i = 0; i < array.length; i++) { if (array[i]) { ret.push(array[i]); } } return ret; } function escapeHTML(s) { var n = s; n = n.replace(/&/g, '&amp;'); n = n.replace(/</g, '&lt;'); n = n.replace(/>/g, '&gt;'); n = n.replace(/"/g, '&quot;'); return n; } var Diff = function(ignoreWhitespace) { this.ignoreWhitespace = ignoreWhitespace; }; Diff.prototype = { diff: function(oldString, newString) { // Handle the identity case (this is due to unrolling editLength == 0 if (newString === oldString) { return [{ value: newString }]; } if (!newString) { return [{ value: oldString, removed: true }]; } if (!oldString) { return [{ value: newString, added: true }]; } newString = this.tokenize(newString); oldString = this.tokenize(oldString); var newLen = newString.length, oldLen = oldString.length; var maxEditLength = newLen + oldLen; var bestPath = [{ newPos: -1, components: [] }]; // Seed editLength = 0 var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0); if (bestPath[0].newPos+1 >= newLen && oldPos+1 >= oldLen) { return bestPath[0].components; } for (var editLength = 1; editLength <= maxEditLength; editLength++) { for (var diagonalPath = -1*editLength; diagonalPath <= editLength; diagonalPath+=2) { var basePath; var addPath = bestPath[diagonalPath-1], removePath = bestPath[diagonalPath+1]; oldPos = (removePath ? removePath.newPos : 0) - diagonalPath; if (addPath) { // No one else is going to attempt to use this value, clear it bestPath[diagonalPath-1] = undefined; } var canAdd = addPath && addPath.newPos+1 < newLen; var canRemove = removePath && 0 <= oldPos && oldPos < oldLen; if (!canAdd && !canRemove) { bestPath[diagonalPath] = undefined; continue; } // Select the diagonal that we want to branch from. We select the prior // path whose position in the new string is the farthest from the origin // and does not pass the bounds of the diff graph if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) { basePath = clonePath(removePath); this.pushComponent(basePath.components, oldString[oldPos], undefined, true); } else { basePath = clonePath(addPath); basePath.newPos++; this.pushComponent(basePath.components, newString[basePath.newPos], true, undefined); } var oldPos = this.extractCommon(basePath, newString, oldString, diagonalPath); if (basePath.newPos+1 >= newLen && oldPos+1 >= oldLen) { return basePath.components; } else { bestPath[diagonalPath] = basePath; } } } }, pushComponent: function(components, value, added, removed) { var last = components[components.length-1]; if (last && last.added === added && last.removed === removed) { // We need to clone here as the component clone operation is just // as shallow array clone components[components.length-1] = {value: this.join(last.value, value), added: added, removed: removed }; } else { components.push({value: value, added: added, removed: removed }); } }, extractCommon: function(basePath, newString, oldString, diagonalPath) { var newLen = newString.length, oldLen = oldString.length, newPos = basePath.newPos, oldPos = newPos - diagonalPath; while (newPos+1 < newLen && oldPos+1 < oldLen && this.equals(newString[newPos+1], oldString[oldPos+1])) { newPos++; oldPos++; this.pushComponent(basePath.components, newString[newPos], undefined, undefined); } basePath.newPos = newPos; return oldPos; }, equals: function(left, right) { var reWhitespace = /\S/; if (this.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right)) { return true; } else { return left === right; } }, join: function(left, right) { return left + right; }, tokenize: function(value) { return value; } }; var CharDiff = new Diff(); var WordDiff = new Diff(true);<|fim▁hole|> }; var CssDiff = new Diff(true); CssDiff.tokenize = function(value) { return removeEmpty(value.split(/([{}:;,]|\s+)/)); }; var LineDiff = new Diff(); LineDiff.tokenize = function(value) { var retLines = [], lines = value.split(/^/m); for(var i = 0; i < lines.length; i++) { var line = lines[i], lastLine = lines[i - 1]; // Merge lines that may contain windows new lines if (line == '\n' && lastLine && lastLine[lastLine.length - 1] === '\r') { retLines[retLines.length - 1] += '\n'; } else if (line) { retLines.push(line); } } return retLines; }; return { Diff: Diff, diffChars: function(oldStr, newStr) { return CharDiff.diff(oldStr, newStr); }, diffWords: function(oldStr, newStr) { return WordDiff.diff(oldStr, newStr); }, diffWordsWithSpace: function(oldStr, newStr) { return WordWithSpaceDiff.diff(oldStr, newStr); }, diffLines: function(oldStr, newStr) { return LineDiff.diff(oldStr, newStr); }, diffCss: function(oldStr, newStr) { return CssDiff.diff(oldStr, newStr); }, createPatch: function(fileName, oldStr, newStr, oldHeader, newHeader) { var ret = []; ret.push('Index: ' + fileName); ret.push('==================================================================='); ret.push('--- ' + fileName + (typeof oldHeader === 'undefined' ? '' : '\t' + oldHeader)); ret.push('+++ ' + fileName + (typeof newHeader === 'undefined' ? '' : '\t' + newHeader)); var diff = LineDiff.diff(oldStr, newStr); if (!diff[diff.length-1].value) { diff.pop(); // Remove trailing newline add } diff.push({value: '', lines: []}); // Append an empty value to make cleanup easier function contextLines(lines) { return lines.map(function(entry) { return ' ' + entry; }); } function eofNL(curRange, i, current) { var last = diff[diff.length-2], isLast = i === diff.length-2, isLastOfType = i === diff.length-3 && (current.added !== last.added || current.removed !== last.removed); // Figure out if this is the last line for the given file and missing NL if (!/\n$/.test(current.value) && (isLast || isLastOfType)) { curRange.push('\\ No newline at end of file'); } } var oldRangeStart = 0, newRangeStart = 0, curRange = [], oldLine = 1, newLine = 1; for (var i = 0; i < diff.length; i++) { var current = diff[i], lines = current.lines || current.value.replace(/\n$/, '').split('\n'); current.lines = lines; if (current.added || current.removed) { if (!oldRangeStart) { var prev = diff[i-1]; oldRangeStart = oldLine; newRangeStart = newLine; if (prev) { curRange = contextLines(prev.lines.slice(-4)); oldRangeStart -= curRange.length; newRangeStart -= curRange.length; } } curRange.push.apply(curRange, lines.map(function(entry) { return (current.added?'+':'-') + entry; })); eofNL(curRange, i, current); if (current.added) { newLine += lines.length; } else { oldLine += lines.length; } } else { if (oldRangeStart) { // Close out any changes that have been output (or join overlapping) if (lines.length <= 8 && i < diff.length-2) { // Overlapping curRange.push.apply(curRange, contextLines(lines)); } else { // end the range and output var contextSize = Math.min(lines.length, 4); ret.push( '@@ -' + oldRangeStart + ',' + (oldLine-oldRangeStart+contextSize) + ' +' + newRangeStart + ',' + (newLine-newRangeStart+contextSize) + ' @@'); ret.push.apply(ret, curRange); ret.push.apply(ret, contextLines(lines.slice(0, contextSize))); if (lines.length <= 4) { eofNL(ret, i, current); } oldRangeStart = 0; newRangeStart = 0; curRange = []; } } oldLine += lines.length; newLine += lines.length; } } return ret.join('\n') + '\n'; }, applyPatch: function(oldStr, uniDiff) { var diffstr = uniDiff.split('\n'); var diff = []; var remEOFNL = false, addEOFNL = false; for (var i = (diffstr[0][0]==='I'?4:0); i < diffstr.length; i++) { if(diffstr[i][0] === '@') { var meh = diffstr[i].split(/@@ -(\d+),(\d+) \+(\d+),(\d+) @@/); diff.unshift({ start:meh[3], oldlength:meh[2], oldlines:[], newlength:meh[4], newlines:[] }); } else if(diffstr[i][0] === '+') { diff[0].newlines.push(diffstr[i].substr(1)); } else if(diffstr[i][0] === '-') { diff[0].oldlines.push(diffstr[i].substr(1)); } else if(diffstr[i][0] === ' ') { diff[0].newlines.push(diffstr[i].substr(1)); diff[0].oldlines.push(diffstr[i].substr(1)); } else if(diffstr[i][0] === '\\') { if (diffstr[i-1][0] === '+') { remEOFNL = true; } else if(diffstr[i-1][0] === '-') { addEOFNL = true; } } } var str = oldStr.split('\n'); for (var i = diff.length - 1; i >= 0; i--) { var d = diff[i]; for (var j = 0; j < d.oldlength; j++) { if(str[d.start-1+j] !== d.oldlines[j]) { return false; } } Array.prototype.splice.apply(str,[d.start-1,+d.oldlength].concat(d.newlines)); } if (remEOFNL) { while (!str[str.length-1]) { str.pop(); } } else if (addEOFNL) { str.push(''); } return str.join('\n'); }, convertChangesToXML: function(changes){ var ret = []; for ( var i = 0; i < changes.length; i++) { var change = changes[i]; if (change.added) { ret.push('<ins>'); } else if (change.removed) { ret.push('<del>'); } ret.push(escapeHTML(change.value)); if (change.added)<|fim▁end|>
var WordWithSpaceDiff = new Diff(); WordDiff.tokenize = WordWithSpaceDiff.tokenize = function(value) { return removeEmpty(value.split(/(\s+|\b)/));
<|file_name|>AssessmentRounded.js<|end_file_name|><|fim▁begin|>import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon( /*#__PURE__*/_jsx("path", { d: "M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM8 17c-.55 0-1-.45-1-1v-5c0-.55.45-1 1-1s1 .45 1 1v5c0 .55-.45 1-1 1zm4 0c-.55 0-1-.45-1-1V8c0-.55.45-1 1-1s1 .45 1 1v8c0 .55-.45 1-1 1zm4 0c-.55 0-1-.45-1-1v-2c0-.55.45-1 1-1s1 .45 1 1v2c0 .55-.45 1-1 1z"<|fim▁hole|><|fim▁end|>
}), 'AssessmentRounded');
<|file_name|>hr_language.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*- ############################################################################### # # OpenERP, Open Source Management Solution # Copyright (C) 2013 Savoir-faire Linux (<http://www.savoirfairelinux.com>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################### import tools from openerp.osv import fields, orm class hr_language(orm.Model): _name = 'hr.language' _columns = { 'name': fields.selection(tools.scan_languages(), 'Language', required=True), 'description': fields.char('Description', size=64, required=True, translate=True), 'employee_id': fields.many2one('hr.employee', 'Employee', required=True), 'read': fields.boolean('Read'), 'write': fields.boolean('Write'), 'speak': fields.boolean('Speak'), } _defaults = { 'read': True, 'write': True,<|fim▁hole|> } class hr_employee(orm.Model): _inherit = 'hr.employee' _columns = { 'language_ids': fields.one2many('hr.language', 'employee_id', 'Languages'), } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:<|fim▁end|>
'speak': True,
<|file_name|>jobs.py<|end_file_name|><|fim▁begin|>from __future__ import unicode_literals from django.db import models from django.utils.timezone import now, timedelta Q = models.Q class LogisticJob(models.Model): LOCK_FOR = ( (60*15, '15 minutes'), (60*30, '30 minutes'), (60*45, '45 minutes'), (60*60, '1 hour'), (60*60*3, '3 hours'), (60*60*6, '6 hours'), (60*60*9, '9 hours'), (60*60*12, '12 hours'), (60*60*18, '18 hours'), (60*60*24, '24 hours'), ) RESOURCE = ( ('wood', 'Wood'),<|fim▁hole|> # ('cole', 'Cole'), ) SPEED = ( ('-1', 'Keine Pferde'), ('1001', 'Gold Pferde (test)'), ('1004', 'Rubi Pferde 1 (test)'), ('1007', 'Rubi Pferde 2 (test)'), ) player = models.ForeignKey("gge_proxy_manager.Player", related_name='logistic_jobs') castle = models.ForeignKey("gge_proxy_manager.Castle", related_name='outgoing_logistic_jobs') receiver = models.ForeignKey("gge_proxy_manager.Castle", related_name='incoming_logistic_jobs') speed = models.CharField(max_length=5, choices=SPEED) is_active = models.BooleanField(default=True) resource = models.CharField(max_length=6, choices=RESOURCE) gold_limit = models.PositiveIntegerField(null=True, blank=True, default=None) resource_limit = models.PositiveIntegerField() lock_for = models.PositiveIntegerField(choices=LOCK_FOR, default=60*45) locked_till = models.DateTimeField(default=now, db_index=True) class Meta: app_label = 'gge_proxy_manager' def delay(self): self.locked_till = now() + timedelta(seconds=self.lock_for) self.save() def last_succeed(self): from .log import LogisticLog log = LogisticLog.objects.filter(castle=self.castle, receiver=self.receiver, resource=self.resource).order_by('-sent').first() if log: return log.sent return None class ProductionJob(models.Model): player = models.ForeignKey("gge_proxy_manager.Player", related_name='production_jobs') castle = models.ForeignKey("gge_proxy_manager.Castle", related_name='production_jobs') unit = models.ForeignKey("gge_proxy_manager.Unit") valid_until = models.PositiveIntegerField(null=True, blank=True, default=None, help_text='Bis zu welcher Menge ist der Auftrag gueltig') is_active = models.BooleanField(default=True) gold_limit = models.PositiveIntegerField(null=True, blank=True, default=None) food_balance_limit = models.IntegerField(null=True, blank=True, default=None) wood_limit = models.PositiveIntegerField(null=True, blank=True, default=None) stone_limit = models.PositiveIntegerField(null=True, blank=True, default=None) burst_mode = models.BooleanField(default=False, help_text='Ignoriert Nahrungsbilanz') locked_till = models.DateTimeField(default=now, db_index=True) last_fault_reason = models.CharField(null=True, default=None, max_length=128) last_fault_date = models.DateTimeField(default=None, null=True) class Meta: app_label = 'gge_proxy_manager' def last_succeed(self): from .log import ProductionLog log = ProductionLog.objects.filter(castle=self.castle, unit=self.unit).order_by('-produced').first() if log: return log.produced return None<|fim▁end|>
('stone', 'Stone'), ('food', 'Food'),
<|file_name|>import_rewrite_visitor.ts<|end_file_name|><|fim▁begin|>/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {AotCompilerHost} from '@angular/compiler'; import {dirname, resolve} from 'path'; import * as ts from 'typescript'; import {Import, getImportOfIdentifier} from '../../../utils/typescript/imports'; import {getValueSymbolOfDeclaration} from '../../../utils/typescript/symbol'; import {ImportManager} from '../import_manager'; import {getPosixPath} from './path_format'; import {ResolvedExport, getExportSymbolsOfFile} from './source_file_exports'; /** * Factory that creates a TypeScript transformer which ensures that * referenced identifiers are available at the target file location. * * Imports cannot be just added as sometimes identifiers collide in the * target source file and the identifier needs to be aliased. */ export class ImportRewriteTransformerFactory { private sourceFileExports = new Map<ts.SourceFile, ResolvedExport[]>(); constructor( private importManager: ImportManager, private typeChecker: ts.TypeChecker, private compilerHost: AotCompilerHost) {} create<T extends ts.Node>(ctx: ts.TransformationContext, newSourceFile: ts.SourceFile): ts.Transformer<T> { const visitNode: ts.Visitor = (node: ts.Node) => { if (ts.isIdentifier(node)) { // Record the identifier reference and return the new identifier. The identifier // name can change if the generated import uses an namespaced import or aliased // import identifier (to avoid collisions). return this._recordIdentifierReference(node, newSourceFile); } return ts.visitEachChild(node, visitNode, ctx); }; return (node: T) => ts.visitNode(node, visitNode); } private _recordIdentifierReference(node: ts.Identifier, targetSourceFile: ts.SourceFile): ts.Node { // For object literal elements we don't want to check identifiers that describe the // property name. These identifiers do not refer to a value but rather to a property // name and therefore don't need to be imported. The exception is that for shorthand // property assignments the "name" identifier is both used as value and property name. if (ts.isObjectLiteralElementLike(node.parent) && !ts.isShorthandPropertyAssignment(node.parent) && node.parent.name === node) { return node; } const resolvedImport = getImportOfIdentifier(this.typeChecker, node); const sourceFile = node.getSourceFile(); if (resolvedImport) {<|fim▁hole|> this.compilerHost.moduleNameToFileName(resolvedImport.importModule, sourceFile.fileName); // In case the identifier refers to an export in the target source file, we need to use // the local identifier in the scope of the target source file. This is necessary because // the export could be aliased and the alias is not available to the target source file. if (moduleFileName && resolve(moduleFileName) === resolve(targetSourceFile.fileName)) { const resolvedExport = this._getSourceFileExports(targetSourceFile).find(e => e.exportName === symbolName); if (resolvedExport) { return resolvedExport.identifier; } } return this.importManager.addImportToSourceFile( targetSourceFile, symbolName, this._rewriteModuleImport(resolvedImport, targetSourceFile)); } else { let symbol = getValueSymbolOfDeclaration(node, this.typeChecker); if (symbol) { // If the symbol refers to a shorthand property assignment, we want to resolve the // value symbol of the shorthand property assignment. This is necessary because the // value symbol is ambiguous for shorthand property assignment identifiers as the // identifier resolves to both property name and property value. if (symbol.valueDeclaration && ts.isShorthandPropertyAssignment(symbol.valueDeclaration)) { symbol = this.typeChecker.getShorthandAssignmentValueSymbol(symbol.valueDeclaration); } const resolvedExport = this._getSourceFileExports(sourceFile).find(e => e.symbol === symbol); if (resolvedExport) { return this.importManager.addImportToSourceFile( targetSourceFile, resolvedExport.exportName, getPosixPath(this.compilerHost.fileNameToModuleName( sourceFile.fileName, targetSourceFile.fileName))); } } // The referenced identifier cannot be imported. In that case we throw an exception // which can be handled outside of the transformer. throw new UnresolvedIdentifierError(); } } /** * Gets the resolved exports of a given source file. Exports are cached * for subsequent calls. */ private _getSourceFileExports(sourceFile: ts.SourceFile): ResolvedExport[] { if (this.sourceFileExports.has(sourceFile)) { return this.sourceFileExports.get(sourceFile) !; } const sourceFileExports = getExportSymbolsOfFile(sourceFile, this.typeChecker); this.sourceFileExports.set(sourceFile, sourceFileExports); return sourceFileExports; } /** Rewrites a module import to be relative to the target file location. */ private _rewriteModuleImport(resolvedImport: Import, newSourceFile: ts.SourceFile): string { if (!resolvedImport.importModule.startsWith('.')) { return resolvedImport.importModule; } const importFilePath = resolvedImport.node.getSourceFile().fileName; const resolvedModulePath = resolve(dirname(importFilePath), resolvedImport.importModule); const relativeModuleName = this.compilerHost.fileNameToModuleName(resolvedModulePath, newSourceFile.fileName); return getPosixPath(relativeModuleName); } } /** Error that will be thrown if a given identifier cannot be resolved. */ export class UnresolvedIdentifierError extends Error {}<|fim▁end|>
const symbolName = resolvedImport.name; const moduleFileName =
<|file_name|>siphash.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright (c) 2016 The nealcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Specialized SipHash-2-4 implementations. This implements SipHash-2-4 for 256-bit integers. """ def rotl64(n, b): return n >> (64 - b) | (n & ((1 << (64 - b)) - 1)) << b def siphash_round(v0, v1, v2, v3): v0 = (v0 + v1) & ((1 << 64) - 1) v1 = rotl64(v1, 13) v1 ^= v0 v0 = rotl64(v0, 32) v2 = (v2 + v3) & ((1 << 64) - 1) v3 = rotl64(v3, 16) v3 ^= v2 v0 = (v0 + v3) & ((1 << 64) - 1) v3 = rotl64(v3, 21) v3 ^= v0 v2 = (v2 + v1) & ((1 << 64) - 1) v1 = rotl64(v1, 17) v1 ^= v2 v2 = rotl64(v2, 32) return (v0, v1, v2, v3) def siphash256(k0, k1, h): n0 = h & ((1 << 64) - 1) n1 = (h >> 64) & ((1 << 64) - 1) n2 = (h >> 128) & ((1 << 64) - 1) n3 = (h >> 192) & ((1 << 64) - 1) v0 = 0x736f6d6570736575 ^ k0 v1 = 0x646f72616e646f6d ^ k1 v2 = 0x6c7967656e657261 ^ k0 v3 = 0x7465646279746573 ^ k1 ^ n0 v0, v1, v2, v3 = siphash_round(v0, v1, v2, v3) v0, v1, v2, v3 = siphash_round(v0, v1, v2, v3) v0 ^= n0 v3 ^= n1 v0, v1, v2, v3 = siphash_round(v0, v1, v2, v3) v0, v1, v2, v3 = siphash_round(v0, v1, v2, v3) v0 ^= n1 v3 ^= n2 v0, v1, v2, v3 = siphash_round(v0, v1, v2, v3) v0, v1, v2, v3 = siphash_round(v0, v1, v2, v3) v0 ^= n2 v3 ^= n3 v0, v1, v2, v3 = siphash_round(v0, v1, v2, v3) v0, v1, v2, v3 = siphash_round(v0, v1, v2, v3) v0 ^= n3 v3 ^= 0x2000000000000000 v0, v1, v2, v3 = siphash_round(v0, v1, v2, v3) v0, v1, v2, v3 = siphash_round(v0, v1, v2, v3)<|fim▁hole|> v0, v1, v2, v3 = siphash_round(v0, v1, v2, v3) v0, v1, v2, v3 = siphash_round(v0, v1, v2, v3) v0, v1, v2, v3 = siphash_round(v0, v1, v2, v3) return v0 ^ v1 ^ v2 ^ v3<|fim▁end|>
v0 ^= 0x2000000000000000 v2 ^= 0xFF v0, v1, v2, v3 = siphash_round(v0, v1, v2, v3)
<|file_name|>decorate-enum.rs<|end_file_name|><|fim▁begin|>#![feature(plugin)] #![plugin(rocket_codegen)] extern crate rocket; #[get("")] //~ ERROR can only be used on functions enum B { } //~ ERROR but was applied fn main() { let _ = routes![get];<|fim▁hole|><|fim▁end|>
}
<|file_name|>suite_clang_cindex.py<|end_file_name|><|fim▁begin|>import sys import unittest import cbind cbind.choose_cindex_impl(cbind.CLANG_CINDEX) import suite_all if __name__ == '__main__':<|fim▁hole|> runner = unittest.TextTestRunner() sys.exit(not runner.run(suite_all.suite_all).wasSuccessful())<|fim▁end|>
<|file_name|>Ram20140214GetUserRequest.py<|end_file_name|><|fim▁begin|>''' Created by auto_sdk on 2015.06.23 ''' from aliyun.api.base import RestApi class Ram20140214GetUserRequest(RestApi): def __init__(self,domain='ram.aliyuncs.com',port=80):<|fim▁hole|> self.UserName = None def getapiname(self): return 'ram.aliyuncs.com.GetUser.2014-02-14'<|fim▁end|>
RestApi.__init__(self,domain, port) self.AccountSpace = None
<|file_name|>legacy-road.ts<|end_file_name|><|fim▁begin|>import * as proceduralTexture from "../road"; /** * This is the entry point for the UMD module. * The entry point for a future ESM package should be index.ts */ var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : undefined); if (typeof globalObject !== "undefined") { for (var key in proceduralTexture) { (<any>globalObject).BABYLON[key] = (<any>proceduralTexture)[key]; } } <|fim▁hole|><|fim▁end|>
export * from "../road";
<|file_name|>procesoxml.py<|end_file_name|><|fim▁begin|>__author__ = 'fer' from xml.etree import ElementTree from xml.etree.ElementTree import Element from xml.etree.ElementTree import SubElement from core.tableObjects import Table, Column class Xml: archivo = None<|fim▁hole|> self.archivo = ruta def get_doc(self) -> ElementTree: doc = ElementTree.parse(self.archivo) return doc def mapper_xml_to_objects(self): doc = self.get_doc() tablas = dict() tb = None for xmltabla in doc._root: #decimos a python que es un elemento assert isinstance(xmltabla, Element) #si exsiste el objeto lo eliminamos if tb is not None: del tb tb = Table() tb.table_name = xmltabla.attrib['name'] for xmlcolumna in list(xmltabla): assert isinstance(xmlcolumna, Element) col = Column() col.colname = xmlcolumna.attrib['name'] col.type = xmlcolumna.attrib['type'] if 'key' in xmlcolumna.attrib.keys(): clave = bool(xmlcolumna.attrib['key']) if clave is True: col.is_key = True if 'auto_increment' in xmlcolumna.attrib.keys(): auto_increment = bool(xmlcolumna.attrib['auto_increment']) if auto_increment is True: col.is_autoIncrement = True tb.columns.append(col) tablas[tb.table_name] = tb ''' for nombre, objeto in tablas.items(): assert isinstance(objeto, Table) print(objeto.__str__()) ''' return tablas def print_table_structure(self): ''' Imprime por pantalla la estructura de la base de datos detectada ''' doc = self.get_doc() for tabla in doc._root: #decimos a python que es un elemento assert isinstance(tabla, Element) print('Tabla: ' + tabla.attrib['name']) for columna in list(tabla): assert isinstance(columna, Element) print('\t' + columna.attrib['name'] + '\t' + columna.attrib['type'], end='') if 'key' in columna.attrib.keys(): clave = bool(columna.attrib['key']) if clave is True: print('\t[clave]', end='') print('') print('\r\n')<|fim▁end|>
def __init__(self, ruta=None):
<|file_name|>observation_preprocessor_test.py<|end_file_name|><|fim▁begin|># Copyright 2021 Google LLC # # 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. # Lint as: python3 """Tests for observation_preprocessor.""" import math from absl.testing import absltest from absl.testing import parameterized from google.protobuf import text_format from learner import test_data from learner.brains import observation_preprocessor from learner.brains import tfa_specs import numpy as np import tensorflow as tf # pylint: disable=g-bad-import-order import common.generate_protos # pylint: disable=unused-import import brain_pb2 import observation_pb2 def get_hparams(feelers_version): return dict( always_compute_egocentric=True, feelers_version=feelers_version, feelers_v2_output_channels=3, feelers_v2_kernel_size=5) class ObservationPreprocessorTest(parameterized.TestCase): @parameterized.parameters([ ('v1', 'default'), ('v2', 'default'), ('v2', 'wrap')]) def test_preproc(self, feelers_version, yaw_range): spec_proto = test_data.brain_spec() if yaw_range == 'wrap': # Force yaw_angles to loop around 360 degrees. for field in spec_proto.observation_spec.player.entity_fields: if field.HasField('feeler'): for i, yaw in enumerate( np.linspace(0, math.pi, len(field.feeler.yaw_angles))): field.feeler.yaw_angles[i] = yaw spec = tfa_specs.BrainSpec(spec_proto) obs_preproc = observation_preprocessor.ObservationPreprocessor( spec, get_hparams(feelers_version)) data = test_data.observation_data(50, [0.0, 0.0, 0.0]) # Set camera position / rotation. data.camera.position.x = data.player.position.x data.camera.position.y = data.player.position.y data.camera.position.z = data.player.position.z data.camera.rotation.x = 0 data.camera.rotation.y = 0 data.camera.rotation.z = 1 # 180 degrees rotated around z data.camera.rotation.w = 0 tfa_val = spec.observation_spec.tfa_value(data) # Apply preprocessing layers to tf_val preprocessed, _ = obs_preproc(tfa_val) # Ignore state component. preprocessed = preprocessed.numpy().tolist() def _dist(d): """Preprocess distances to match observation preprocessor.""" return np.log(d + 1) want = [ 0.0, # global_entities/0/drink - one-hot, category 0 0.0, # global_entities/0/drink - one-hot, category 1 1.0, # global_entities/0/drink - one-hot, category 2 2 * (66 / 100) - 1, # global_entities/0/evilness 1, # player/feeler 1.1, # player/feeler 2, # player/feeler 2.1, # player/feeler 3, # player/feeler 3.1, # player/feeler 2 * (50 / 100) - 1, # player/health 0.0, # XZ-angle camera to entity1 0.0, # YZ-angle camera to entity1 _dist(1.0), # distance camera to entity1 0.0, # XZ-angle camera to entity2 -math.pi/2, # YZ-angle camera to entity2 _dist(1.0), # distance camera to entity2 math.pi/2, # XZ-angle camera to entity3 0.0, # YZ-angle camera to entity3 _dist(2.0), # distance camera to entity3 0.0, # XZ-angle player to entity1 0.0, # YZ-angle player to entity1 _dist(1.0), # distance player to entity1 0.0, # XZ-angle player to entity2 math.pi/2, # YZ-angle player to entity2 _dist(1.0), # distance player to entity2 -math.pi/2, # XZ-angle player to entity3 0.0, # YZ-angle player to entity3 _dist(2.0) # distance player to entity3 ] # We're rounding aggressively because batch norm adds noise. self.assertSequenceAlmostEqual(preprocessed, want, delta=0.05) @parameterized.parameters(['v1', 'v2']) def test_preproc_batch(self, feelers_version): spec = tfa_specs.BrainSpec(test_data.brain_spec()) obs_preproc = observation_preprocessor.ObservationPreprocessor( spec, get_hparams(feelers_version)) tfa_val = spec.observation_spec.tfa_value( test_data.observation_data(50, [0.0, 0.0, 0.0])) # Create batch of nested observations of size 5 tfa_val = tf.nest.map_structure( lambda x: tf.stack([x, x, x, x, x]), tfa_val) # Apply preprocessing layers to tf_val preprocessed, _ = obs_preproc(tfa_val) # Ignore state component. self.assertEqual(preprocessed.shape, (5, 29)) @parameterized.parameters(['v1', 'v2']) def test_preproc_missing_player(self, feelers_version): proto_obs_spec = test_data.observation_spec() proto_obs_spec.ClearField('player') # Delete player pos from spec. proto_act_spec = test_data.action_spec() # Delete player references. # Remove joystick actions since they reference the player and camera. # The last 3 actions in the example model are joystick actions, so we # remove them from the list. del proto_act_spec.actions[-3:] brain_spec = test_data.brain_spec() brain_spec.observation_spec.CopyFrom(proto_obs_spec) brain_spec.action_spec.CopyFrom(proto_act_spec) spec = tfa_specs.BrainSpec(brain_spec) obs_preproc = observation_preprocessor.ObservationPreprocessor( spec, get_hparams(feelers_version)) proto_data = test_data.observation_data(50, [0.0, 0.0, 0.0]) proto_data.ClearField('player') # Delete player from data. tfa_val = spec.observation_spec.tfa_value(proto_data) # Apply preprocessing layers to tf_val preprocessed, _ = obs_preproc(tfa_val) # Ignore state component. preprocessed = preprocessed.numpy().tolist() want = [ 0.0, # global_entities/0/drink - one-hot, categpry 0 0.0, # global_entities/0/drink - one-hot, category 1 1.0, # global_entities/0/drink - one-hot, category 2 2 * (66.0 / 100.0) - 1, # global_entities/0/evilness ] self.assertSequenceAlmostEqual(preprocessed, want, delta=0.05) @parameterized.product(dir_mode=['angle', 'unit_circle'], dist_mode=['linear', 'log_plus_one'], num_batch_dims=[0, 1, 2]) def test_egocentric_modes(self, dir_mode, dist_mode, num_batch_dims): brain_spec = brain_pb2.BrainSpec() text_format.Parse( """ observation_spec { player { position {} rotation {} } global_entities { position {} rotation {} } } action_spec { actions { name: "joy_pitch_yaw" joystick { axes_mode: DELTA_PITCH_YAW controlled_entity: "player" }<|fim▁hole|> hparams = { 'egocentric_direction_mode': dir_mode, 'egocentric_distance_mode': dist_mode, } spec = tfa_specs.BrainSpec(brain_spec) obs_preproc = observation_preprocessor.ObservationPreprocessor( spec, hparams) observation_data = observation_pb2.ObservationData() text_format.Parse( """ player { position {} rotation {} } global_entities { position { x: 1 y: -1 z: 1 } rotation {} } """, observation_data) tfa_val = spec.observation_spec.tfa_value(observation_data) # Stack into a batch of the requested size. for _ in range(num_batch_dims): tfa_val = tf.nest.map_structure( lambda x: tf.stack([x, x]), tfa_val) preprocessed, _ = obs_preproc(tfa_val) # Ignore state component. preprocessed = preprocessed.numpy() # Unpack result of first batch. for _ in range(num_batch_dims): preprocessed = preprocessed[0] if dir_mode == 'angle': want = [-math.pi/4, math.pi/4] # -45, 45 degree in radians. self.assertSequenceAlmostEqual(preprocessed[:len(want)], want, delta=0.05) preprocessed = preprocessed[len(want):] else: assert dir_mode == 'unit_circle' v = 1 / math.sqrt(2) # X and Y component of 45 degree 2D unit vec. want = [v, v, -v, v] self.assertSequenceAlmostEqual(preprocessed[:len(want)], want, delta=0.05) preprocessed = preprocessed[len(want):] if dist_mode == 'linear': want = [math.sqrt(3)] # diagonal of the unit cube. self.assertSequenceAlmostEqual(want, preprocessed, delta=0.05) else: assert dist_mode == 'log_plus_one' want = [math.log(math.sqrt(3) + 1)] self.assertSequenceAlmostEqual(want, preprocessed, delta=0.05) if __name__ == '__main__': absltest.main()<|fim▁end|>
} } """, brain_spec)
<|file_name|>gyptest-errors.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Test that two targets with the same name generates an error. """ import os import sys import TestGyp import TestCmd # TODO(sbc): Remove the use of match_re below, done because scons # error messages were not consistent with other generators. # Also remove input.py:generator_wants_absolute_build_file_paths. test = TestGyp.TestGyp()<|fim▁hole|> '.*duplicate_targets.gyp:foo#target\n') test.run_gyp('duplicate_targets.gyp', status=1, stderr=stderr, match=TestCmd.match_re) stderr = ('.*: Unable to find targets in build file .*missing_targets.gyp.*') test.run_gyp('missing_targets.gyp', status=1, stderr=stderr, match=TestCmd.match_re_dotall) stderr = ('gyp: rule bar exists in duplicate, target ' '.*duplicate_rule.gyp:foo#target\n') test.run_gyp('duplicate_rule.gyp', status=1, stderr=stderr, match=TestCmd.match_re) stderr = ("gyp: Key 'targets' repeated at level 1 with key path '' while " "reading .*duplicate_node.gyp.*") test.run_gyp('duplicate_node.gyp', '--check', status=1, stderr=stderr, match=TestCmd.match_re_dotall) stderr = (".*target0.*target1.*target2.*target0.*") test.run_gyp('dependency_cycle.gyp', status=1, stderr=stderr, match=TestCmd.match_re_dotall) stderr = (".*file_cycle0.*file_cycle1.*file_cycle0.*") test.run_gyp('file_cycle0.gyp', status=1, stderr=stderr, match=TestCmd.match_re_dotall) stderr = 'gyp: Duplicate basenames in sources section, see list above\n' test.run_gyp('duplicate_basenames.gyp', status=1, stderr=stderr) # Check if '--no-duplicate-basename-check' works. if ((test.format == 'make' and sys.platform == 'darwin') or (test.format == 'msvs' and int(os.environ.get('GYP_MSVS_VERSION', 2010)) < 2010)): stderr = 'gyp: Duplicate basenames in sources section, see list above\n' test.run_gyp('duplicate_basenames.gyp', '--no-duplicate-basename-check', status=1, stderr=stderr) else: test.run_gyp('duplicate_basenames.gyp', '--no-duplicate-basename-check') stderr = ("gyp: Dependency '.*missing_dep.gyp:missing.gyp#target' not found " "while trying to load target .*missing_dep.gyp:foo#target\n") test.run_gyp('missing_dep.gyp', status=1, stderr=stderr, match=TestCmd.match_re) test.pass_test()<|fim▁end|>
stderr = ('gyp: Duplicate target definitions for '
<|file_name|>surface_tracking.cpp<|end_file_name|><|fim▁begin|>#include "Copter.h" // adjust_climb_rate - hold copter at the desired distance above the // ground; returns climb rate (in cm/s) which should be passed to // the position controller float Copter::SurfaceTracking::adjust_climb_rate(float target_rate) { #if RANGEFINDER_ENABLED == ENABLED // check tracking state and that range finders are healthy if ((surface == Surface::NONE) || ((surface == Surface::GROUND) && (!copter.rangefinder_alt_ok() || (copter.rangefinder_state.glitch_count != 0))) || ((surface == Surface::CEILING) && !copter.rangefinder_up_ok()) || (copter.rangefinder_up_state.glitch_count != 0)) { return target_rate; } // calculate current ekf based altitude error const float current_alt_error = copter.pos_control->get_alt_target() - copter.inertial_nav.get_altitude(); // init based on tracking direction/state RangeFinderState &rf_state = (surface == Surface::GROUND) ? copter.rangefinder_state : copter.rangefinder_up_state; const float dir = (surface == Surface::GROUND) ? 1.0f : -1.0f; // reset target altitude if this controller has just been engaged // target has been changed between upwards vs downwards // or glitch has cleared const uint32_t now = millis(); if ((now - last_update_ms > SURFACE_TRACKING_TIMEOUT_MS) || reset_target || (last_glitch_cleared_ms != rf_state.glitch_cleared_ms)) { target_dist_cm = rf_state.alt_cm + (dir * current_alt_error); reset_target = false; last_glitch_cleared_ms = rf_state.glitch_cleared_ms;\ } last_update_ms = now; // adjust rangefinder target alt if motors have not hit their limits if ((target_rate<0 && !copter.motors->limit.throttle_lower) || (target_rate>0 && !copter.motors->limit.throttle_upper)) { target_dist_cm += dir * target_rate * copter.G_Dt; } valid_for_logging = true; #if AC_AVOID_ENABLED == ENABLED // upward facing terrain following never gets closer than avoidance margin if (surface == Surface::CEILING) { const float margin_cm = copter.avoid.enabled() ? copter.avoid.get_margin() * 100.0f : 0.0f; target_dist_cm = MAX(target_dist_cm, margin_cm); } #endif // calc desired velocity correction from target rangefinder alt vs actual rangefinder alt (remove the error already passed to Altitude controller to avoid oscillations) const float distance_error = (target_dist_cm - rf_state.alt_cm) - (dir * current_alt_error); float velocity_correction = dir * distance_error * copter.g.rangefinder_gain; velocity_correction = constrain_float(velocity_correction, -SURFACE_TRACKING_VELZ_MAX, SURFACE_TRACKING_VELZ_MAX); // return combined pilot climb rate + rate to correct rangefinder alt error return (target_rate + velocity_correction); #else return target_rate; #endif } // get target altitude (in cm) above ground // returns true if there is a valid target bool Copter::SurfaceTracking::get_target_alt_cm(float &_target_alt_cm) const { // fail if we are not tracking downwards if (surface != Surface::GROUND) { return false; } // check target has been updated recently if (AP_HAL::millis() - last_update_ms > SURFACE_TRACKING_TIMEOUT_MS) { return false; } _target_alt_cm = target_dist_cm; return true; } <|fim▁hole|> // fail if we are not tracking downwards if (surface != Surface::GROUND) { return; } target_dist_cm = _target_alt_cm; last_update_ms = AP_HAL::millis(); } bool Copter::SurfaceTracking::get_target_dist_for_logging(float &target_dist) const { if (!valid_for_logging || (surface == Surface::NONE)) { return false; } target_dist = target_dist_cm * 0.01f; return true; } float Copter::SurfaceTracking::get_dist_for_logging() const { return ((surface == Surface::CEILING) ? copter.rangefinder_up_state.alt_cm : copter.rangefinder_state.alt_cm) * 0.01f; } // set direction void Copter::SurfaceTracking::set_surface(Surface new_surface) { if (surface == new_surface) { return; } // check we have a range finder in the correct direction if ((new_surface == Surface::GROUND) && !copter.rangefinder.has_orientation(ROTATION_PITCH_270)) { copter.gcs().send_text(MAV_SEVERITY_WARNING, "SurfaceTracking: no downward rangefinder"); AP_Notify::events.user_mode_change_failed = 1; return; } if ((new_surface == Surface::CEILING) && !copter.rangefinder.has_orientation(ROTATION_PITCH_90)) { copter.gcs().send_text(MAV_SEVERITY_WARNING, "SurfaceTracking: no upward rangefinder"); AP_Notify::events.user_mode_change_failed = 1; return; } surface = new_surface; reset_target = true; }<|fim▁end|>
// set target altitude (in cm) above ground void Copter::SurfaceTracking::set_target_alt_cm(float _target_alt_cm) {
<|file_name|>TestMTStmtTwoPatternsStartStop.java<|end_file_name|><|fim▁begin|>/* * ************************************************************************************* * Copyright (C) 2008 EsperTech, Inc. All rights reserved. * * http://esper.codehaus.org * * http://www.espertech.com * * ---------------------------------------------------------------------------------- * * The software in this package is published under the terms of the GPL license * * a copy of which has been included with this distribution in the license.txt file. * * ************************************************************************************* */ package com.espertech.esper.multithread; import junit.framework.TestCase; import com.espertech.esper.client.EPServiceProvider; import com.espertech.esper.client.EPServiceProviderManager; import com.espertech.esper.client.EPStatement; import com.espertech.esper.client.Configuration; import com.espertech.esper.support.bean.SupportTradeEvent; import com.espertech.esper.multithread.TwoPatternRunnable; /** * Test for multithread-safety for case of 2 patterns: * 1. Thread 1 starts pattern "every event1=SupportEvent(userID in ('100','101'), amount>=1000)" * 2. Thread 1 repeats sending 100 events and tests 5% received * 3. Main thread starts pattern: * ( every event1=SupportEvent(userID in ('100','101')) -> (SupportEvent(userID in ('100','101'), direction = event1.direction ) -> SupportEvent(userID in ('100','101'), direction = event1.direction ) ) where timer:within(8 hours) and not eventNC=SupportEvent(userID in ('100','101'), direction!= event1.direction ) ) -> eventFinal=SupportEvent(userID in ('100','101'), direction != event1.direction ) where timer:within(1 hour) * 4. Main thread waits for 2 seconds and stops all threads */ public class TestMTStmtTwoPatternsStartStop extends TestCase { private EPServiceProvider engine; public void setUp() { Configuration config = new Configuration(); config.addEventType("SupportEvent", SupportTradeEvent.class); engine = EPServiceProviderManager.getDefaultProvider(config); engine.initialize(); } public void tearDown() { engine.initialize(); } public void test2Patterns() throws Exception <|fim▁hole|> { String statementTwo = "( every event1=SupportEvent(userId in ('100','101')) ->\n" + " (SupportEvent(userId in ('100','101'), direction = event1.direction ) ->\n" + " SupportEvent(userId in ('100','101'), direction = event1.direction )\n" + " ) where timer:within(8 hours)\n" + " and not eventNC=SupportEvent(userId in ('100','101'), direction!= event1.direction )\n" + " ) -> eventFinal=SupportEvent(userId in ('100','101'), direction != event1.direction ) where timer:within(1 hour)"; TwoPatternRunnable runnable = new TwoPatternRunnable(engine); Thread t = new Thread(runnable); t.start(); Thread.sleep(200); // Create a second pattern, wait 200 msec, destroy second pattern in a loop for (int i = 0; i < 10; i++) { EPStatement statement = engine.getEPAdministrator().createPattern(statementTwo); Thread.sleep(200); statement.destroy(); } runnable.setShutdown(true); Thread.sleep(1000); assertFalse(t.isAlive()); } }<|fim▁end|>
<|file_name|>0527.py<|end_file_name|><|fim▁begin|># -*- coding: UTF-8 -*- import logging unicode_string = u"Татьяна"<|fim▁hole|>utf8_string = "'Татьяна' is an invalid string value" logging.warning(unicode_string) logging.warning(utf8_string) try: raise Exception(utf8_string) except Exception,e: print "--- (Log a traceback of the exception):" logging.exception(e) print "--- Everything okay until here, but now we run into trouble:" logging.warning(u"1 Deferred %s : %s",unicode_string,e) logging.warning(u"2 Deferred %s : %s",unicode_string,utf8_string) print "--- some workarounds:" logging.warning(u"3 Deferred %s : %s",unicode_string,utf8_string.decode('UTF-8')) from django.utils.encoding import force_unicode logging.warning(u"4 Deferred %s : %s",unicode_string,force_unicode(utf8_string))<|fim▁end|>
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>//! This module defines the trait necessary for a session storage struct. use self::session::Session; pub mod session; /// A default implementation of `SessionStore`: `Session`. pub mod hashsession; /// This `Trait` defines a session storage struct. It must be implemented on any store passed to `Sessions`. pub trait SessionStore<K, V>: Clone + Send + Sync { #[doc(hidden)] fn select_session(&mut self, key: K) -> Session<K, V> { Session::new(key, box self.clone()) } /// Set the value of the session belonging to `key`, replacing any previously set value. fn insert(&self, key: &K, value: V); /// Retrieve the value of this session. /// /// Returns `None` if the session belonging to `key` has not been set. fn find(&self, key: &K) -> Option<V>; /// Swap the given value with the current value of the session belonging to `key`. /// /// Returns the value being replaced, or `None` if this session was not yet set. fn swap(&self, key: &K, value: V) -> Option<V>; /// Insert value, if not yet set, or update the current value of the session belonging to `key`. /// /// Returns an owned copy of the value that was set. /// /// This is analagous to the `insert_or_update_with` method of `HashMap`. fn upsert(&self, key: &K, value: V, mutator: |&mut V|) -> V; /// Remove the session stored at this key.<|fim▁hole|><|fim▁end|>
fn remove(&self, key: &K) -> bool; }
<|file_name|>issue-4764.ts<|end_file_name|><|fim▁begin|>import { expect } from "chai"; import "reflect-metadata"; import { Connection } from "../../../src/index"; import { closeTestingConnections, createTestingConnections, reloadTestingDatabases, } from "../../utils/test-utils"; import { User } from "./entity/User"; import { Cart } from "./entity/Cart"; import { CartItems } from "./entity/CartItems"; describe("mssql > add lock clause for MSSQL select with join clause", () => { // ------------------------------------------------------------------------- // Configuration // ------------------------------------------------------------------------- // connect to db let connections: Connection[]; before( async () => (connections = await createTestingConnections({ enabledDrivers: ["mssql"], entities: [__dirname + "/entity/*{.js,.ts}"], schemaCreate: true, dropSchema: true, })) ); beforeEach(() => reloadTestingDatabases(connections)); after(() => closeTestingConnections(connections)); // ------------------------------------------------------------------------- // Specifications // ------------------------------------------------------------------------- it("should not have Lock clause", async () => { Promise.all( connections.map(async (connection) => { const lock = " WITH (NOLOCK)"; const selectQuery = connection .createQueryBuilder() .select("cart") .from(Cart, "cart") .where("1=1") .getQuery(); console.log(selectQuery); expect(selectQuery.includes(lock)).not.to.equal(true); await connection.query(selectQuery); }) ); }); it("should have WITH (NOLOCK) clause", async () => { Promise.all( connections.map(async (connection) => { const lock = " WITH (NOLOCK)"; const selectQuery = connection .createQueryBuilder() .select("cart") .from(Cart, "cart") .setLock("dirty_read") .where("1=1") .getQuery(); console.log(selectQuery); expect(selectQuery.includes(lock)).to.equal(true); await connection.query(selectQuery); }) ); }); it("should have two WITH (NOLOCK) clause", async () => { Promise.all( connections.map(async (connection) => { const lock = " WITH (NOLOCK)"; const selectQuery = connection .createQueryBuilder() .select("cart") .from(Cart, "cart") .innerJoinAndSelect("cart.CartItems", "cartItems") .setLock("dirty_read") .where("1=1") .getQuery(); console.log(selectQuery); expect(countInstances(selectQuery, lock)).to.equal(2); await connection.query(selectQuery); }) ); }); it("should have three WITH (NOLOCK) clause", async () => { Promise.all( connections.map(async (connection) => { const lock = " WITH (NOLOCK)"; const selectQuery = connection .createQueryBuilder() .select("cart") .from(Cart, "cart") .innerJoinAndSelect("cart.User", "user") .innerJoinAndSelect("cart.CartItems", "cartItems") .setLock("dirty_read") .where("1=1") .getQuery(); console.log(selectQuery); expect(countInstances(selectQuery, lock)).to.equal(3); await connection.query(selectQuery); }) ); }); it("should have three WITH (NOLOCK) clause (without relation)", async () => { Promise.all( connections.map(async (connection) => { const lock = " WITH (NOLOCK)"; const selectQuery = connection .createQueryBuilder() .select("cart") .from(Cart, "cart") .innerJoin(User, "user", "user.ID=cart.UNID") .innerJoin( CartItems, "cartItems", "cart.ID=cartItems.CartID" ) .setLock("dirty_read") .where("cart.ID=1") .getQuery(); console.log(selectQuery); expect(countInstances(selectQuery, lock)).to.equal(3); await connection.query(selectQuery); }) ); }); it("should have WITH (HOLDLOCK, ROWLOCK) clause", async () => { Promise.all( connections.map(async (connection) => { const lock = " WITH (HOLDLOCK, ROWLOCK)"; const selectQuery = connection .createQueryBuilder() .select("cart") .from(Cart, "cart") .setLock("pessimistic_read") .where("1=1") .getQuery(); console.log(selectQuery); expect(selectQuery.includes(lock)).to.equal(true); await connection.query(selectQuery); }) ); }); it("should have WITH (UPLOCK, ROWLOCK) clause", async () => { Promise.all( connections.map(async (connection) => { const lock = " WITH (UPDLOCK, ROWLOCK)"; const selectQuery = connection .createQueryBuilder() .select("cart") .from(Cart, "cart") .setLock("pessimistic_write") .where("1=1") .getQuery(); console.log(selectQuery); expect(selectQuery.includes(lock)).to.equal(true); await connection.query(selectQuery); }) );<|fim▁hole|> }); it("should have two WITH (UPDLOCK, ROWLOCK) clause", async () => { Promise.all( connections.map(async (connection) => { const lock = " WITH (UPDLOCK, ROWLOCK)"; const selectQuery = connection .createQueryBuilder() .select("cart") .from(Cart, "cart") .innerJoinAndSelect("cart.CartItems", "cartItems") .setLock("pessimistic_write") .where("1=1") .getQuery(); console.log(selectQuery); expect(countInstances(selectQuery, lock)).to.equal(2); await connection.query(selectQuery); }) ); }); function countInstances(str: string, word: string) { return str.split(word).length - 1; } });<|fim▁end|>
<|file_name|>mlperf_test.py<|end_file_name|><|fim▁begin|># Copyright 2018 The TensorFlow 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. # ============================================================================== """Contains tests related to MLPerf. Note this test only passes if the MLPerf compliance library is installed. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from collections import Counter import logging import re import six import tensorflow.compat.v1 as tf import benchmark_cnn import datasets import mlperf import test_util from models import model from mlperf_compliance import mlperf_log class _MlPerfTestModel(model.CNNModel): """A model to test the MLPerf compliance logging on.""" def __init__(self): super(_MlPerfTestModel, self).__init__( 'mlperf_test_model', image_size=224, batch_size=2, learning_rate=1) def add_inference(self, cnn): assert cnn.top_layer.shape[1:] == (3, 224, 224) cnn.conv(1, 1, 1, 1, 1, use_batch_norm=True) cnn.mpool(1, 1, 1, 1, num_channels_in=1) cnn.reshape([-1, 224 * 224]) cnn.affine(1, activation=None) # Assert that the batch norm variables are filtered out for L2 loss. variables = tf.global_variables() + tf.local_variables() assert len(variables) > len(self.filter_l2_loss_vars(variables)) class MlPerfComplianceTest(tf.test.TestCase):<|fim▁hole|> compliance checker will be. """ def setUp(self): super(MlPerfComplianceTest, self).setUp() benchmark_cnn.setup(benchmark_cnn.make_params()) # Map between regex and the number of times we expect to see that regex in the # logs. Entry commented out with the comment FIXME indicate that # tf_cnn_benchmarks currently fails compliance in that regard, and needs to be # fixed to be MLPerf compliant. EXPECTED_LOG_REGEXES = { # Preprocessing tags mlperf.tags.INPUT_ORDER: 2, # 1 for training, 1 for eval # We pass --tf_random_seed=9876 in the test. r'%s: 9876' % mlperf.tags.RUN_SET_RANDOM_SEED: 2, # The Numpy random seed is hardcoded to 4321. r'%s: 4321' % mlperf.tags.RUN_SET_RANDOM_SEED: 2, r'%s: %d' % (mlperf.tags.PREPROC_NUM_TRAIN_EXAMPLES, datasets.IMAGENET_NUM_TRAIN_IMAGES): 1, r'%s: %d' % (mlperf.tags.PREPROC_NUM_EVAL_EXAMPLES, datasets.IMAGENET_NUM_VAL_IMAGES): 1, mlperf.tags.PREPROC_NUM_EVAL_EXAMPLES + '.*': 1, mlperf.tags.INPUT_DISTORTED_CROP_MIN_OBJ_COV + '.*': 1, mlperf.tags.INPUT_DISTORTED_CROP_RATIO_RANGE + '.*': 1, mlperf.tags.INPUT_DISTORTED_CROP_AREA_RANGE + '.*': 1, mlperf.tags.INPUT_DISTORTED_CROP_MAX_ATTEMPTS + '.*': 1, mlperf.tags.INPUT_RANDOM_FLIP + '.*': 1, r'%s: \[224, 224\].*' % mlperf.tags.INPUT_CENTRAL_CROP: 1, r'%s: \[123.68, 116.78, 103.94\].*' % mlperf.tags.INPUT_MEAN_SUBTRACTION: 2, r'%s: {"min": 256}.*' % mlperf.tags.INPUT_RESIZE_ASPECT_PRESERVING: 1, # 1 for training, 1 for eval r'%s: \[224, 224\].*' % mlperf.tags.INPUT_RESIZE: 2, # Resnet model tags mlperf.tags.MODEL_HP_BATCH_NORM + '.*': 2, # 2 for training, 2 for eval. Although there's only 1 conv2d, each conv2d # produces 2 logs. mlperf.tags.MODEL_HP_CONV2D_FIXED_PADDING + '.*': 4, mlperf.tags.MODEL_HP_RELU + '.*': 2, mlperf.tags.MODEL_HP_INITIAL_MAX_POOL + '.*': 2, mlperf.tags.MODEL_HP_DENSE + '.*': 4, mlperf.tags.MODEL_HP_DENSE + '.*': 4, # Note that tags our test model does not emit, like MODEL_HP_SHORTCUT_ADD, # are omitted here. r'%s: "categorical_cross_entropy".*' % mlperf.tags.MODEL_HP_LOSS_FN: 1, # 1 for training, 2 because the _MlPerfTestModel calls this when building # the model for both training and eval r'%s: true' % mlperf.tags.MODEL_EXCLUDE_BN_FROM_L2: 3, r'%s: 0.5.*' % mlperf.tags.MODEL_L2_REGULARIZATION: 1, # Note we do not handle OPT_LR, since that is printed to stderr using # tf.Print, which we cannot easily intercept. # Other tags '%s: "%s"' % (mlperf.tags.OPT_NAME, mlperf.tags.SGD_WITH_MOMENTUM): 1, '%s: 0.5' % mlperf.tags.OPT_MOMENTUM: 1, mlperf.tags.RUN_START: 1, '%s: 2' % mlperf.tags.INPUT_BATCH_SIZE: 1, mlperf.tags.TRAIN_LOOP: 1, mlperf.tags.TRAIN_EPOCH + '.*': 1, '%s: 2' % mlperf.tags.INPUT_SIZE: 2, mlperf.tags.EVAL_START: 2, mlperf.tags.EVAL_STOP: 2, '%s: 6' % mlperf.tags.EVAL_SIZE: 2, mlperf.tags.EVAL_ACCURACY + '.*': 2, '%s: 2.0' % mlperf.tags.EVAL_TARGET: 2, mlperf.tags.RUN_STOP + '.*': 1, mlperf.tags.RUN_FINAL: 1 } EXPECTED_LOG_REGEXES = Counter({re.compile(k): v for k, v in EXPECTED_LOG_REGEXES.items()}) def testMlPerfCompliance(self): string_io = six.StringIO() handler = logging.StreamHandler(string_io) data_dir = test_util.create_black_and_white_images() try: mlperf_log.LOGGER.addHandler(handler) params = benchmark_cnn.make_params(data_dir=data_dir, data_name='imagenet', batch_size=2, num_warmup_batches=0, num_batches=2, num_eval_batches=3, eval_during_training_every_n_steps=1, distortions=False, weight_decay=0.5, optimizer='momentum', momentum=0.5, stop_at_top_1_accuracy=2.0, tf_random_seed=9876, ml_perf=True) with mlperf.mlperf_logger(use_mlperf_logger=True, model='resnet50_v1.5'): bench_cnn = benchmark_cnn.BenchmarkCNN(params, model=_MlPerfTestModel()) bench_cnn.run() logs = string_io.getvalue().splitlines() log_regexes = Counter() for log in logs: for regex in self.EXPECTED_LOG_REGEXES: if regex.search(log): log_regexes[regex] += 1 if log_regexes != self.EXPECTED_LOG_REGEXES: diff_counter = Counter(log_regexes) diff_counter.subtract(self.EXPECTED_LOG_REGEXES) differences = [] for regex in (k for k in diff_counter.keys() if diff_counter[k]): found_count = log_regexes[regex] expected_count = self.EXPECTED_LOG_REGEXES[regex] differences.append(' For regex %s: Found %d lines matching but ' 'expected to find %d' % (regex.pattern, found_count, expected_count)) raise AssertionError('Logs did not match expected logs. Differences:\n' '%s' % '\n'.join(differences)) finally: mlperf_log.LOGGER.removeHandler(handler) if __name__ == '__main__': tf.disable_v2_behavior() tf.test.main()<|fim▁end|>
"""Tests the MLPerf compliance logs. This serves as a quick check that we probably didn't break the compliance logging. It is not mean to be as comprehensive as the official MLPerf
<|file_name|>dock.py<|end_file_name|><|fim▁begin|>import docker from cargo.container import Container from cargo.image import Image # this is a hack to get `__getattribute__` working for a few reserved properties RESERVED_METHODS = ['containers', '_client', 'images', 'info', 'start', 'stop'] class Dock(object): """Wrapper class for `docker-py` Client instances""" def __init__(self, *args, **kw): super(Dock, self).__init__() self._client = docker.Client(*args, **kw) def __repr__(self): return '<Dock [%s] (%s)>' % (self.base_url, self.version().get('Version')) def __getattribute__(self, x): client = super(Dock, self).__getattribute__('_client') # return client attribute if not a magic method or reserved attr legal = not x.startswith('_') and not(x in RESERVED_METHODS) if hasattr(client, x) and legal: return client.__getattribute__(x) return super(Dock, self).__getattribute__(x) @property def containers(self, *args, **kw): return [Container(x) for x in self._client.containers(*args, **kw)] @property def _containers(self, *args, **kw): return [x for x in self._client.containers(*args, **kw)] @property def images(self, *args, **kw): return [Image(x) for x in self._client.images(*args, **kw)] @property def _images(self, *args, **kw): return [x for x in self._client.images(*args, **kw)] @property def info(self): return self._client.info() @property def total_num_containers(self): info = self.info return int(info.get('Containers')) @property def total_num_images(self): info = self.info return int(info.get('Images')) @property def total_num_goroutines(self): info = self.info return int(info.get('NGoroutines')) @property def memory_limit(self): info = self.info return info.get('MemoryLimit') @property def debug(self): info = self.info return info.get('Debug') def running(self, container): """Returns True if dock is running container, else False Accepts container id's and Container objects """ container_ids = [x.container_id for x in self.containers] if isinstance(container, Container): return container.container_id in containder_ids elif isinstance(container, basestring): return container in container_ids raise TypeError('expected container id as string or Container object.') def start(self, container, *args, **kw): if isinstance(container, Container): cid = container.container_id<|fim▁hole|> return self._client.start(cid, *args, **kw) def stop(self, container, *args, **kw): if isinstance(container, Container): cid = container.container_id elif isinstance(container, basestring): cid = container return self._client.stop(cid, *args, **kw)<|fim▁end|>
elif isinstance(container, basestring): cid = container
<|file_name|>enquire-client-portal.component.ts<|end_file_name|><|fim▁begin|>import { Component, OnInit } from '@angular/core'; import { GalleryService } from 'ng-gallery'; import { fadeInAnimation } from '../../animation-fade-in'; @Component({ moduleId: module.id, selector: 'sd-enquire-client-portal', templateUrl: 'enquire-client-portal.component.html', animations: [fadeInAnimation], host: { '[@fadeInAnimation]': '', 'class': 'animate-router' } }) export class EnquireClientPortalComponent implements OnInit { images = [ { src: 'images/portfolio/enquire-client-portal/register.gif', }, { src: 'images/portfolio/enquire-client-portal/cp-1.png', }, { src: 'images/portfolio/enquire-client-portal/cp-2.png', }, { src: 'images/portfolio/enquire-client-portal/cp-3.png',<|fim▁hole|> { src: 'images/portfolio/enquire-client-portal/cp-4.png', }, ]; constructor(private gallery: GalleryService) { } ngOnInit() { this.gallery.load(this.images); } }<|fim▁end|>
},
<|file_name|>60_command-line-flags.go<|end_file_name|><|fim▁begin|>// [_Command-line flags_](http://en.wikipedia.org/wiki/Command-line_interface#Command-line_option) // are a common way to specify options for command-line // programs. For example, in `wc -l` the `-l` is a // command-line flag. package lessons // Go provides a `flag` package supporting basic <|fim▁hole|> "fmt" "flag" ) func CommandLineFlags() { // Basic flag declarations are available for string, // integer, and boolean options. Here we declare a // string flag `word` with a default value `"foo"` // and a short description. This `flag.String` function // returns a string pointer (not a string value); // we'll see how to use this pointer below. wordPtr := flag.String("word", "foo", "a string") // This declares `numb` and `fork` flags, using a // similar approach to the `word` flag. numbPtr := flag.Int("numb", 42, "an int") boolPtr := flag.Bool("fork", false, "a bool") // It's also possible to declare an option that uses an // existing var declared elsewhere in the program. // Note that we need to pass in a pointer to the flag // declaration function. var svar string flag.StringVar(&svar, "svar", "bar", "a string value") // Once all flags are declared, call `flag.Parse()` // to execute the command-line parsing. flag.Parse() // Here we'll just dump out the parsed options and // any trailing positional arguments. Note that we // need to dereference the pointers with e.g. `*wordPtr` // to get the actual option values. fmt.Println("word:", *wordPtr) fmt.Println("numb:", *numbPtr) fmt.Println("fork:", *boolPtr) fmt.Println("svar:", svar) fmt.Println("tail:", flag.Args()) }<|fim▁end|>
// command-line flag parsing. We'll use this package to // implement our example command-line program. import(
<|file_name|>associated-types-cc.rs<|end_file_name|><|fim▁begin|>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // run-pass #![allow(unused_variables)] // aux-build:associated-types-cc-lib.rs // Test that we are able to reference cross-crate traits that employ // associated types. <|fim▁hole|>fn foo<B:Bar>(b: B) -> <B as Bar>::T { Bar::get(None::<B>) } fn main() { println!("{}", foo(3)); }<|fim▁end|>
extern crate associated_types_cc_lib as bar; use bar::Bar;
<|file_name|>2043.js<|end_file_name|><|fim▁begin|>{<|fim▁hole|>}<|fim▁end|>
var x = f; x = items[0]; x = items[1];
<|file_name|>test_hue_api.py<|end_file_name|><|fim▁begin|>"""The tests for the emulated Hue component.""" import asyncio import json from unittest.mock import patch import pytest from homeassistant import bootstrap, const, core import homeassistant.components as core_components from homeassistant.components import ( emulated_hue, http, light, script, media_player, fan ) from homeassistant.const import STATE_ON, STATE_OFF from homeassistant.components.emulated_hue.hue_api import ( HUE_API_STATE_ON, HUE_API_STATE_BRI, HueUsernameView, HueAllLightsStateView, HueOneLightStateView, HueOneLightChangeView) from homeassistant.components.emulated_hue import Config from tests.common import ( get_test_instance_port, mock_http_component_app) HTTP_SERVER_PORT = get_test_instance_port() BRIDGE_SERVER_PORT = get_test_instance_port() BRIDGE_URL_BASE = 'http://127.0.0.1:{}'.format(BRIDGE_SERVER_PORT) + '{}' JSON_HEADERS = {const.HTTP_HEADER_CONTENT_TYPE: const.CONTENT_TYPE_JSON} @pytest.fixture def hass_hue(loop, hass): """Setup a hass instance for these tests.""" # We need to do this to get access to homeassistant/turn_(on,off) loop.run_until_complete( core_components.async_setup(hass, {core.DOMAIN: {}})) loop.run_until_complete(bootstrap.async_setup_component( hass, http.DOMAIN, {http.DOMAIN: {http.CONF_SERVER_PORT: HTTP_SERVER_PORT}})) with patch('homeassistant.components' '.emulated_hue.UPNPResponderThread'): loop.run_until_complete( bootstrap.async_setup_component(hass, emulated_hue.DOMAIN, { emulated_hue.DOMAIN: { emulated_hue.CONF_LISTEN_PORT: BRIDGE_SERVER_PORT, emulated_hue.CONF_EXPOSE_BY_DEFAULT: True } })) loop.run_until_complete( bootstrap.async_setup_component(hass, light.DOMAIN, { 'light': [ { 'platform': 'demo', } ] })) loop.run_until_complete( bootstrap.async_setup_component(hass, script.DOMAIN, { 'script': { 'set_kitchen_light': { 'sequence': [ { 'service_template': "light.turn_{{ requested_state }}", 'data_template': { 'entity_id': 'light.kitchen_lights', 'brightness': "{{ requested_level }}" } } ] } } })) loop.run_until_complete( bootstrap.async_setup_component(hass, media_player.DOMAIN, { 'media_player': [ { 'platform': 'demo', } ] })) loop.run_until_complete( bootstrap.async_setup_component(hass, fan.DOMAIN, { 'fan': [ { 'platform': 'demo', } ] })) # Kitchen light is explicitly excluded from being exposed kitchen_light_entity = hass.states.get('light.kitchen_lights') attrs = dict(kitchen_light_entity.attributes) attrs[emulated_hue.ATTR_EMULATED_HUE] = False hass.states.async_set( kitchen_light_entity.entity_id, kitchen_light_entity.state, attributes=attrs) # Expose the script script_entity = hass.states.get('script.set_kitchen_light') attrs = dict(script_entity.attributes) attrs[emulated_hue.ATTR_EMULATED_HUE] = True hass.states.async_set( script_entity.entity_id, script_entity.state, attributes=attrs ) return hass @pytest.fixture def hue_client(loop, hass_hue, test_client): """Create web client for emulated hue api.""" web_app = mock_http_component_app(hass_hue) config = Config(None, {'type': 'alexa'}) HueUsernameView().register(web_app.router) HueAllLightsStateView(config).register(web_app.router) HueOneLightStateView(config).register(web_app.router) HueOneLightChangeView(config).register(web_app.router) return loop.run_until_complete(test_client(web_app)) @asyncio.coroutine def test_discover_lights(hue_client): """Test the discovery of lights.""" result = yield from hue_client.get('/api/username/lights') assert result.status == 200 assert 'application/json' in result.headers['content-type'] result_json = yield from result.json() devices = set(val['uniqueid'] for val in result_json.values()) # Make sure the lights we added to the config are there assert 'light.ceiling_lights' in devices assert 'light.bed_light' in devices assert 'script.set_kitchen_light' in devices assert 'light.kitchen_lights' not in devices assert 'media_player.living_room' in devices assert 'media_player.bedroom' in devices assert 'media_player.walkman' in devices assert 'media_player.lounge_room' in devices assert 'fan.living_room_fan' in devices @asyncio.coroutine def test_get_light_state(hass_hue, hue_client): """Test the getting of light state.""" # Turn office light on and set to 127 brightness yield from hass_hue.services.async_call( light.DOMAIN, const.SERVICE_TURN_ON, { const.ATTR_ENTITY_ID: 'light.ceiling_lights', light.ATTR_BRIGHTNESS: 127 }, blocking=True) office_json = yield from perform_get_light_state( hue_client, 'light.ceiling_lights', 200) assert office_json['state'][HUE_API_STATE_ON] is True assert office_json['state'][HUE_API_STATE_BRI] == 127 # Check all lights view result = yield from hue_client.get('/api/username/lights') assert result.status == 200 assert 'application/json' in result.headers['content-type'] result_json = yield from result.json() assert 'light.ceiling_lights' in result_json assert result_json['light.ceiling_lights']['state'][HUE_API_STATE_BRI] == \ 127 # Turn bedroom light off yield from hass_hue.services.async_call( light.DOMAIN, const.SERVICE_TURN_OFF, { const.ATTR_ENTITY_ID: 'light.bed_light' }, blocking=True) bedroom_json = yield from perform_get_light_state( hue_client, 'light.bed_light', 200) assert bedroom_json['state'][HUE_API_STATE_ON] is False assert bedroom_json['state'][HUE_API_STATE_BRI] == 0 # Make sure kitchen light isn't accessible yield from perform_get_light_state( hue_client, 'light.kitchen_lights', 404) @asyncio.coroutine def test_put_light_state(hass_hue, hue_client): """Test the seeting of light states.""" yield from perform_put_test_on_ceiling_lights(hass_hue, hue_client) # Turn the bedroom light on first yield from hass_hue.services.async_call( light.DOMAIN, const.SERVICE_TURN_ON, {const.ATTR_ENTITY_ID: 'light.bed_light', light.ATTR_BRIGHTNESS: 153}, blocking=True) bed_light = hass_hue.states.get('light.bed_light') assert bed_light.state == STATE_ON assert bed_light.attributes[light.ATTR_BRIGHTNESS] == 153 # Go through the API to turn it off bedroom_result = yield from perform_put_light_state( hass_hue, hue_client, 'light.bed_light', False) bedroom_result_json = yield from bedroom_result.json() assert bedroom_result.status == 200 assert 'application/json' in bedroom_result.headers['content-type'] assert len(bedroom_result_json) == 1 # Check to make sure the state changed bed_light = hass_hue.states.get('light.bed_light') assert bed_light.state == STATE_OFF # Make sure we can't change the kitchen light state kitchen_result = yield from perform_put_light_state( hass_hue, hue_client, 'light.kitchen_light', True) assert kitchen_result.status == 404 @asyncio.coroutine def test_put_light_state_script(hass_hue, hue_client): """Test the setting of script variables.""" # Turn the kitchen light off first yield from hass_hue.services.async_call( light.DOMAIN, const.SERVICE_TURN_OFF, {const.ATTR_ENTITY_ID: 'light.kitchen_lights'}, blocking=True) # Emulated hue converts 0-100% to 0-255. level = 23 brightness = round(level * 255 / 100) script_result = yield from perform_put_light_state( hass_hue, hue_client, 'script.set_kitchen_light', True, brightness) script_result_json = yield from script_result.json() assert script_result.status == 200 assert len(script_result_json) == 2 kitchen_light = hass_hue.states.get('light.kitchen_lights') assert kitchen_light.state == 'on' assert kitchen_light.attributes[light.ATTR_BRIGHTNESS] == level @asyncio.coroutine def test_put_light_state_media_player(hass_hue, hue_client): """Test turning on media player and setting volume.""" # Turn the music player off first yield from hass_hue.services.async_call( media_player.DOMAIN, const.SERVICE_TURN_OFF, {const.ATTR_ENTITY_ID: 'media_player.walkman'}, blocking=True) # Emulated hue converts 0.0-1.0 to 0-255. level = 0.25 brightness = round(level * 255) mp_result = yield from perform_put_light_state( hass_hue, hue_client, 'media_player.walkman', True, brightness) mp_result_json = yield from mp_result.json() assert mp_result.status == 200 assert len(mp_result_json) == 2 walkman = hass_hue.states.get('media_player.walkman') assert walkman.state == 'playing' assert walkman.attributes[media_player.ATTR_MEDIA_VOLUME_LEVEL] == level @asyncio.coroutine def test_put_light_state_fan(hass_hue, hue_client): """Test turning on fan and setting speed.""" # Turn the fan off first yield from hass_hue.services.async_call( fan.DOMAIN, const.SERVICE_TURN_OFF, {const.ATTR_ENTITY_ID: 'fan.living_room_fan'}, blocking=True) # Emulated hue converts 0-100% to 0-255. level = 23 brightness = round(level * 255 / 100) fan_result = yield from perform_put_light_state( hass_hue, hue_client, 'fan.living_room_fan', True, brightness) fan_result_json = yield from fan_result.json() assert fan_result.status == 200 assert len(fan_result_json) == 2 living_room_fan = hass_hue.states.get('fan.living_room_fan') assert living_room_fan.state == 'on' assert living_room_fan.attributes[fan.ATTR_SPEED] == fan.SPEED_MEDIUM # pylint: disable=invalid-name @asyncio.coroutine def test_put_with_form_urlencoded_content_type(hass_hue, hue_client): """Test the form with urlencoded content.""" # Needed for Alexa yield from perform_put_test_on_ceiling_lights( hass_hue, hue_client, 'application/x-www-form-urlencoded') # Make sure we fail gracefully when we can't parse the data data = {'key1': 'value1', 'key2': 'value2'} result = yield from hue_client.put( '/api/username/lights/light.ceiling_lights/state', headers={ 'content-type': 'application/x-www-form-urlencoded' }, data=data, ) <|fim▁hole|>@asyncio.coroutine def test_entity_not_found(hue_client): """Test for entity which are not found.""" result = yield from hue_client.get( '/api/username/lights/not.existant_entity') assert result.status == 404 result = yield from hue_client.put( '/api/username/lights/not.existant_entity/state') assert result.status == 404 @asyncio.coroutine def test_allowed_methods(hue_client): """Test the allowed methods.""" result = yield from hue_client.get( '/api/username/lights/light.ceiling_lights/state') assert result.status == 405 result = yield from hue_client.put( '/api/username/lights/light.ceiling_lights') assert result.status == 405 result = yield from hue_client.put( '/api/username/lights') assert result.status == 405 @asyncio.coroutine def test_proper_put_state_request(hue_client): """Test the request to set the state.""" # Test proper on value parsing result = yield from hue_client.put( '/api/username/lights/{}/state'.format( 'light.ceiling_lights'), data=json.dumps({HUE_API_STATE_ON: 1234})) assert result.status == 400 # Test proper brightness value parsing result = yield from hue_client.put( '/api/username/lights/{}/state'.format( 'light.ceiling_lights'), data=json.dumps({ HUE_API_STATE_ON: True, HUE_API_STATE_BRI: 'Hello world!' })) assert result.status == 400 # pylint: disable=invalid-name def perform_put_test_on_ceiling_lights(hass_hue, hue_client, content_type='application/json'): """Test the setting of a light.""" # Turn the office light off first yield from hass_hue.services.async_call( light.DOMAIN, const.SERVICE_TURN_OFF, {const.ATTR_ENTITY_ID: 'light.ceiling_lights'}, blocking=True) ceiling_lights = hass_hue.states.get('light.ceiling_lights') assert ceiling_lights.state == STATE_OFF # Go through the API to turn it on office_result = yield from perform_put_light_state( hass_hue, hue_client, 'light.ceiling_lights', True, 56, content_type) assert office_result.status == 200 assert 'application/json' in office_result.headers['content-type'] office_result_json = yield from office_result.json() assert len(office_result_json) == 2 # Check to make sure the state changed ceiling_lights = hass_hue.states.get('light.ceiling_lights') assert ceiling_lights.state == STATE_ON assert ceiling_lights.attributes[light.ATTR_BRIGHTNESS] == 56 @asyncio.coroutine def perform_get_light_state(client, entity_id, expected_status): """Test the gettting of a light state.""" result = yield from client.get('/api/username/lights/{}'.format(entity_id)) assert result.status == expected_status if expected_status == 200: assert 'application/json' in result.headers['content-type'] return (yield from result.json()) return None @asyncio.coroutine def perform_put_light_state(hass_hue, client, entity_id, is_on, brightness=None, content_type='application/json'): """Test the setting of a light state.""" req_headers = {'Content-Type': content_type} data = {HUE_API_STATE_ON: is_on} if brightness is not None: data[HUE_API_STATE_BRI] = brightness result = yield from client.put( '/api/username/lights/{}/state'.format(entity_id), headers=req_headers, data=json.dumps(data).encode()) # Wait until state change is complete before continuing yield from hass_hue.async_block_till_done() return result<|fim▁end|>
assert result.status == 400
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // //! The arena, a fast but limited type of allocator. //! //! Arenas are a type of allocator that destroy the objects within, all at //! once, once the arena itself is destroyed. They do not support deallocation //! of individual objects while the arena itself is still alive. The benefit //! of an arena is very fast allocation; just a pointer bump. #![crate_id = "arena#0.10"] #![crate_type = "rlib"] #![crate_type = "dylib"] #![license = "MIT/ASL2"] #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://static.rust-lang.org/doc/master")] #![allow(missing_doc)] #![feature(managed_boxes)] extern crate collections; use std::cast::{transmute, transmute_mut, transmute_mut_region}; use std::cast; use std::cell::{Cell, RefCell}; use std::mem; use std::ptr::read; use std::cmp; use std::num; use std::rc::Rc; use std::rt::global_heap; use std::intrinsics::{TyDesc, get_tydesc}; use std::intrinsics; // The way arena uses arrays is really deeply awful. The arrays are // allocated, and have capacities reserved, but the fill for the array // will always stay at 0. #[deriving(Clone, Eq)] struct Chunk { data: Rc<RefCell<Vec<u8> >>, fill: Cell<uint>, is_copy: Cell<bool>, } impl Chunk { fn capacity(&self) -> uint { self.data.borrow().capacity() } unsafe fn as_ptr(&self) -> *u8 { self.data.borrow().as_ptr() } } // Arenas are used to quickly allocate objects that share a // lifetime. The arena uses ~[u8] vectors as a backing store to // allocate objects from. For each allocated object, the arena stores // a pointer to the type descriptor followed by the // object. (Potentially with alignment padding after each of them.) // When the arena is destroyed, it iterates through all of its chunks, // and uses the tydesc information to trace through the objects, // calling the destructors on them. // One subtle point that needs to be addressed is how to handle // failures while running the user provided initializer function. It // is important to not run the destructor on uninitialized objects, but // how to detect them is somewhat subtle. Since alloc() can be invoked // recursively, it is not sufficient to simply exclude the most recent // object. To solve this without requiring extra space, we use the low // order bit of the tydesc pointer to encode whether the object it // describes has been fully initialized. // As an optimization, objects with destructors are stored in // different chunks than objects without destructors. This reduces // overhead when initializing plain-old-data and means we don't need // to waste time running the destructors of POD. pub struct Arena { // The head is separated out from the list as a unbenchmarked // microoptimization, to avoid needing to case on the list to // access the head. priv head: Chunk, priv copy_head: Chunk, priv chunks: RefCell<Vec<Chunk>>, } impl Arena { pub fn new() -> Arena { Arena::new_with_size(32u) } pub fn new_with_size(initial_size: uint) -> Arena { Arena { head: chunk(initial_size, false), copy_head: chunk(initial_size, true), chunks: RefCell::new(Vec::new()), } } } fn chunk(size: uint, is_copy: bool) -> Chunk { Chunk { data: Rc::new(RefCell::new(Vec::with_capacity(size))), fill: Cell::new(0u), is_copy: Cell::new(is_copy), } } #[unsafe_destructor] impl Drop for Arena { fn drop(&mut self) { unsafe { destroy_chunk(&self.head); for chunk in self.chunks.borrow().iter() { if !chunk.is_copy.get() { destroy_chunk(chunk); } } } } } #[inline] fn round_up(base: uint, align: uint) -> uint { (base.checked_add(&(align - 1))).unwrap() & !(&(align - 1)) } // Walk down a chunk, running the destructors for any objects stored // in it. unsafe fn destroy_chunk(chunk: &Chunk) { let mut idx = 0; let buf = chunk.as_ptr(); let fill = chunk.fill.get(); while idx < fill { let tydesc_data: *uint = transmute(buf.offset(idx as int)); let (tydesc, is_done) = un_bitpack_tydesc_ptr(*tydesc_data); let (size, align) = ((*tydesc).size, (*tydesc).align); let after_tydesc = idx + mem::size_of::<*TyDesc>(); let start = round_up(after_tydesc, align); //debug!("freeing object: idx = {}, size = {}, align = {}, done = {}", // start, size, align, is_done); if is_done { ((*tydesc).drop_glue)(buf.offset(start as int) as *i8); } // Find where the next tydesc lives idx = round_up(start + size, mem::pref_align_of::<*TyDesc>()); } } // We encode whether the object a tydesc describes has been // initialized in the arena in the low bit of the tydesc pointer. This // is necessary in order to properly do cleanup if a failure occurs // during an initializer. #[inline] fn bitpack_tydesc_ptr(p: *TyDesc, is_done: bool) -> uint { p as uint | (is_done as uint) } #[inline] fn un_bitpack_tydesc_ptr(p: uint) -> (*TyDesc, bool) { ((p & !1) as *TyDesc, p & 1 == 1) } impl Arena { fn chunk_size(&self) -> uint { self.copy_head.capacity() } // Functions for the POD part of the arena fn alloc_copy_grow(&mut self, n_bytes: uint, align: uint) -> *u8 { // Allocate a new chunk. let new_min_chunk_size = cmp::max(n_bytes, self.chunk_size()); self.chunks.borrow_mut().push(self.copy_head.clone()); self.copy_head = chunk(num::next_power_of_two(new_min_chunk_size + 1u), true); return self.alloc_copy_inner(n_bytes, align); } #[inline] fn alloc_copy_inner(&mut self, n_bytes: uint, align: uint) -> *u8 { unsafe { let this = transmute_mut_region(self); let start = round_up(this.copy_head.fill.get(), align); let end = start + n_bytes; if end > self.chunk_size() { return this.alloc_copy_grow(n_bytes, align); } this.copy_head.fill.set(end); //debug!("idx = {}, size = {}, align = {}, fill = {}", // start, n_bytes, align, head.fill.get()); this.copy_head.as_ptr().offset(start as int) } } #[inline] fn alloc_copy<'a, T>(&'a mut self, op: || -> T) -> &'a T { unsafe { let ptr = self.alloc_copy_inner(mem::size_of::<T>(), mem::min_align_of::<T>()); let ptr: *mut T = transmute(ptr); mem::move_val_init(&mut (*ptr), op()); return transmute(ptr); } } // Functions for the non-POD part of the arena fn alloc_noncopy_grow(&mut self, n_bytes: uint, align: uint) -> (*u8, *u8) { // Allocate a new chunk. let new_min_chunk_size = cmp::max(n_bytes, self.chunk_size()); self.chunks.borrow_mut().push(self.head.clone()); self.head = chunk(num::next_power_of_two(new_min_chunk_size + 1u), false); return self.alloc_noncopy_inner(n_bytes, align); } #[inline] fn alloc_noncopy_inner(&mut self, n_bytes: uint, align: uint) -> (*u8, *u8) { unsafe { let start; let end; let tydesc_start; let after_tydesc; { let head = transmute_mut_region(&mut self.head); tydesc_start = head.fill.get(); after_tydesc = head.fill.get() + mem::size_of::<*TyDesc>(); start = round_up(after_tydesc, align); end = start + n_bytes; } if end > self.head.capacity() { return self.alloc_noncopy_grow(n_bytes, align); } let head = transmute_mut_region(&mut self.head); head.fill.set(round_up(end, mem::pref_align_of::<*TyDesc>())); //debug!("idx = {}, size = {}, align = {}, fill = {}", // start, n_bytes, align, head.fill); let buf = self.head.as_ptr(); return (buf.offset(tydesc_start as int), buf.offset(start as int)); } } #[inline] fn alloc_noncopy<'a, T>(&'a mut self, op: || -> T) -> &'a T { unsafe { let tydesc = get_tydesc::<T>(); let (ty_ptr, ptr) = self.alloc_noncopy_inner(mem::size_of::<T>(), mem::min_align_of::<T>()); let ty_ptr: *mut uint = transmute(ty_ptr); let ptr: *mut T = transmute(ptr); // Write in our tydesc along with a bit indicating that it // has *not* been initialized yet. *ty_ptr = transmute(tydesc); // Actually initialize it mem::move_val_init(&mut(*ptr), op()); // Now that we are done, update the tydesc to indicate that // the object is there. *ty_ptr = bitpack_tydesc_ptr(tydesc, true); return transmute(ptr); } } // The external interface #[inline] pub fn alloc<'a, T>(&'a self, op: || -> T) -> &'a T { unsafe { // FIXME: Borrow check let this = transmute_mut(self); if intrinsics::needs_drop::<T>() { this.alloc_noncopy(op) } else { this.alloc_copy(op) } } } } #[test] fn test_arena_destructors() { let arena = Arena::new(); for i in range(0u, 10) { // Arena allocate something with drop glue to make sure it // doesn't leak. arena.alloc(|| @i); // Allocate something with funny size and alignment, to keep // things interesting. arena.alloc(|| [0u8, 1u8, 2u8]); } } #[test] #[should_fail] fn test_arena_destructors_fail() { let arena = Arena::new(); // Put some stuff in the arena. for i in range(0u, 10) { // Arena allocate something with drop glue to make sure it // doesn't leak. arena.alloc(|| { @i }); // Allocate something with funny size and alignment, to keep // things interesting. arena.alloc(|| { [0u8, 1u8, 2u8] }); } // Now, fail while allocating arena.alloc::<@int>(|| { // Now fail. fail!(); }); } /// An arena that can hold objects of only one type. /// /// Safety note: Modifying objects in the arena that have already had their /// `drop` destructors run can cause leaks, because the destructor will not /// run again for these objects. pub struct TypedArena<T> { /// A pointer to the next object to be allocated. priv ptr: *T, /// A pointer to the end of the allocated area. When this pointer is /// reached, a new chunk is allocated. priv end: *T, /// A pointer to the first arena segment. priv first: Option<~TypedArenaChunk<T>>, } struct TypedArenaChunk<T> { /// Pointer to the next arena segment. next: Option<~TypedArenaChunk<T>>, /// The number of elements that this chunk can hold. capacity: uint, // Objects follow here, suitably aligned. } impl<T> TypedArenaChunk<T> { #[inline] fn new(next: Option<~TypedArenaChunk<T>>, capacity: uint) -> ~TypedArenaChunk<T> { let mut size = mem::size_of::<TypedArenaChunk<T>>(); size = round_up(size, mem::min_align_of::<T>()); let elem_size = mem::size_of::<T>(); let elems_size = elem_size.checked_mul(&capacity).unwrap(); size = size.checked_add(&elems_size).unwrap(); <|fim▁hole|> let chunk = global_heap::exchange_malloc(size); let mut chunk: ~TypedArenaChunk<T> = cast::transmute(chunk); mem::move_val_init(&mut chunk.next, next); chunk }; chunk.capacity = capacity; chunk } /// Destroys this arena chunk. If the type descriptor is supplied, the /// drop glue is called; otherwise, drop glue is not called. #[inline] unsafe fn destroy(&mut self, len: uint) { // Destroy all the allocated objects. if intrinsics::needs_drop::<T>() { let mut start = self.start(); for _ in range(0, len) { read(start as *T); // run the destructor on the pointer start = start.offset(mem::size_of::<T>() as int) } } // Destroy the next chunk. let next_opt = mem::replace(&mut self.next, None); match next_opt { None => {} Some(mut next) => { // We assume that the next chunk is completely filled. next.destroy(next.capacity) } } } // Returns a pointer to the first allocated object. #[inline] fn start(&self) -> *u8 { let this: *TypedArenaChunk<T> = self; unsafe { cast::transmute(round_up(this.offset(1) as uint, mem::min_align_of::<T>())) } } // Returns a pointer to the end of the allocated space. #[inline] fn end(&self) -> *u8 { unsafe { let size = mem::size_of::<T>().checked_mul(&self.capacity).unwrap(); self.start().offset(size as int) } } } impl<T> TypedArena<T> { /// Creates a new arena with preallocated space for 8 objects. #[inline] pub fn new() -> TypedArena<T> { TypedArena::with_capacity(8) } /// Creates a new arena with preallocated space for the given number of /// objects. #[inline] pub fn with_capacity(capacity: uint) -> TypedArena<T> { let chunk = TypedArenaChunk::<T>::new(None, capacity); TypedArena { ptr: chunk.start() as *T, end: chunk.end() as *T, first: Some(chunk), } } /// Allocates an object into this arena. #[inline] pub fn alloc<'a>(&'a self, object: T) -> &'a T { unsafe { let this = cast::transmute_mut(self); if this.ptr == this.end { this.grow() } let ptr: &'a mut T = cast::transmute(this.ptr); mem::move_val_init(ptr, object); this.ptr = this.ptr.offset(1); let ptr: &'a T = ptr; ptr } } /// Grows the arena. #[inline(never)] fn grow(&mut self) { let chunk = self.first.take_unwrap(); let new_capacity = chunk.capacity.checked_mul(&2).unwrap(); let chunk = TypedArenaChunk::<T>::new(Some(chunk), new_capacity); self.ptr = chunk.start() as *T; self.end = chunk.end() as *T; self.first = Some(chunk) } } #[unsafe_destructor] impl<T> Drop for TypedArena<T> { fn drop(&mut self) { // Determine how much was filled. let start = self.first.get_ref().start() as uint; let end = self.ptr as uint; let diff = (end - start) / mem::size_of::<T>(); // Pass that to the `destroy` method. unsafe { self.first.get_mut_ref().destroy(diff) } } } #[cfg(test)] mod tests { extern crate test; use self::test::BenchHarness; use super::{Arena, TypedArena}; struct Point { x: int, y: int, z: int, } #[test] pub fn test_copy() { let arena = TypedArena::new(); for _ in range(0, 100000) { arena.alloc(Point { x: 1, y: 2, z: 3, }); } } #[bench] pub fn bench_copy(bh: &mut BenchHarness) { let arena = TypedArena::new(); bh.iter(|| { arena.alloc(Point { x: 1, y: 2, z: 3, }) }) } #[bench] pub fn bench_copy_nonarena(bh: &mut BenchHarness) { bh.iter(|| { ~Point { x: 1, y: 2, z: 3, } }) } #[bench] pub fn bench_copy_old_arena(bh: &mut BenchHarness) { let arena = Arena::new(); bh.iter(|| { arena.alloc(|| { Point { x: 1, y: 2, z: 3, } }) }) } struct Noncopy { string: ~str, array: Vec<int> , } #[test] pub fn test_noncopy() { let arena = TypedArena::new(); for _ in range(0, 100000) { arena.alloc(Noncopy { string: ~"hello world", array: vec!( 1, 2, 3, 4, 5 ), }); } } #[bench] pub fn bench_noncopy(bh: &mut BenchHarness) { let arena = TypedArena::new(); bh.iter(|| { arena.alloc(Noncopy { string: ~"hello world", array: vec!( 1, 2, 3, 4, 5 ), }) }) } #[bench] pub fn bench_noncopy_nonarena(bh: &mut BenchHarness) { bh.iter(|| { ~Noncopy { string: ~"hello world", array: vec!( 1, 2, 3, 4, 5 ), } }) } #[bench] pub fn bench_noncopy_old_arena(bh: &mut BenchHarness) { let arena = Arena::new(); bh.iter(|| { arena.alloc(|| Noncopy { string: ~"hello world", array: vec!( 1, 2, 3, 4, 5 ), }) }) } }<|fim▁end|>
let mut chunk = unsafe {
<|file_name|>setup.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from distutils.core import setup import os.path classifiers = [ "Programming Language :: Python", "Programming Language :: Python :: 3", "Development Status :: 4 - Beta", "Intended Audience :: Developers", "License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)",<|fim▁hole|>def read(fname): fname = os.path.join(os.path.dirname(__file__), fname) return open(fname).read().strip() def read_files(*fnames): return '\r\n\r\n\r\n'.join(map(read, fnames)) setup( name = 'icall', version = '0.3.4', py_modules = ['icall'], description = 'Parameters call function, :-)', long_description = read_files('README.rst', 'CHANGES.rst'), author = 'huyx', author_email = '[email protected]', url = 'https://github.com/huyx/icall', keywords = ['functools', 'function', 'call'], classifiers = classifiers, )<|fim▁end|>
"Operating System :: OS Independent", "Topic :: Software Development :: Libraries :: Python Modules", ]
<|file_name|>MdbInvoker.java<|end_file_name|><|fim▁begin|>/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.openejb.core.mdb; import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageListener; import javax.jms.MessageProducer; import javax.jms.ObjectMessage; import javax.jms.Session; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Map; import java.util.TreeMap; public class MdbInvoker implements MessageListener { private final Map<String, Method> signatures = new TreeMap<String, Method>(); private final Object target; private Connection connection; private Session session;<|fim▁hole|> private ConnectionFactory connectionFactory; public MdbInvoker(ConnectionFactory connectionFactory, Object target) throws JMSException { this.target = target; this.connectionFactory = connectionFactory; for (Method method : target.getClass().getMethods()) { String signature = MdbUtil.getSignature(method); signatures.put(signature, method); } } public synchronized void destroy() { MdbUtil.close(session); session = null; MdbUtil.close(connection); connection = null; } private synchronized Session getSession() throws JMSException { connection = connectionFactory.createConnection(); connection.start(); session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); return session; } public void onMessage(Message message) { if (!(message instanceof ObjectMessage)) return; try { Session session = getSession(); if (session == null) throw new IllegalStateException("Invoker has been destroyed"); if (message == null) throw new NullPointerException("request message is null"); if (!(message instanceof ObjectMessage)) throw new IllegalArgumentException("Expected a ObjectMessage request but got a " + message.getClass().getName()); ObjectMessage objectMessage = (ObjectMessage) message; Serializable object = objectMessage.getObject(); if (object == null) throw new NullPointerException("object in ObjectMessage is null"); if (!(object instanceof Map)) { if (message instanceof ObjectMessage) throw new IllegalArgumentException("Expected a Map contained in the ObjectMessage request but got a " + object.getClass().getName()); } Map request = (Map) object; String signature = (String) request.get("method"); Method method = signatures.get(signature); Object[] args = (Object[]) request.get("args"); boolean exception = false; Object result = null; try { result = method.invoke(target, args); } catch (IllegalAccessException e) { result = e; exception = true; } catch (InvocationTargetException e) { result = e.getCause(); if (result == null) result = e; exception = true; } MessageProducer producer = null; try { // create response Map<String, Object> response = new TreeMap<String, Object>(); if (exception) { response.put("exception", "true"); } response.put("return", result); // create response message ObjectMessage resMessage = session.createObjectMessage(); resMessage.setJMSCorrelationID(objectMessage.getJMSCorrelationID()); resMessage.setObject((Serializable) response); // send response message producer = session.createProducer(objectMessage.getJMSReplyTo()); producer.send(resMessage); } catch (Exception e) { e.printStackTrace(); } finally { MdbUtil.close(producer); destroy(); } } catch (Throwable e) { e.printStackTrace(); } } }<|fim▁end|>
<|file_name|>0005_auto_20161103_0856.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Generated by Django 1.10.3 on 2016-11-03 08:56 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('snapventure', '0004_auto_20161102_2043'), ] operations = [ migrations.CreateModel( name='Inscription', fields=[<|fim▁hole|> ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255)), ('created', models.DateTimeField(auto_now_add=True)), ('last_updated', models.DateTimeField(auto_now=True)), ('journey', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='snapventure.Journey')), ], ), migrations.CreateModel( name='Profile', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('bio', models.TextField(blank=True, max_length=500)), ('location', models.CharField(blank=True, max_length=30)), ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), migrations.AddField( model_name='inscription', name='user', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='snapventure.Profile'), ), migrations.AddField( model_name='journey', name='inscriptions', field=models.ManyToManyField(through='snapventure.Inscription', to='snapventure.Profile'), ), ]<|fim▁end|>
<|file_name|>test_tctototal_streaming.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra # # This file is part of Essentia # # Essentia is free software: you can redistribute it and/or modify it under # the terms of the GNU Affero General Public License as published by the Free # Software Foundation (FSF), either version 3 of the License, or (at your # option) any later version. # <|fim▁hole|># ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the Affero GNU General Public License # version 3 along with this program. If not, see http://www.gnu.org/licenses/ from essentia_test import * from essentia.streaming import TCToTotal as sTCToTotal class TestTCToTotal(TestCase): def testEmpty(self): gen = VectorInput([]) tcToTotal = sTCToTotal() p = Pool() gen.data >> tcToTotal.envelope tcToTotal.TCToTotal >> (p, 'lowlevel.tctototal') run(gen) self.assertRaises(KeyError, lambda: p['lowlevel.tctototal']) def testOneValue(self): gen = VectorInput([1]) tcToTotal = sTCToTotal() p = Pool() gen.data >> tcToTotal.envelope tcToTotal.TCToTotal >> (p, 'lowlevel.tctototal') self.assertRaises(RuntimeError, lambda: run(gen)) def testRegression(self): envelope = range(22050) envelope.reverse() envelope = range(22050) + envelope gen = VectorInput(envelope) tcToTotal = sTCToTotal() p = Pool() gen.data >> tcToTotal.envelope tcToTotal.TCToTotal >> (p, 'lowlevel.tctototal') run(gen) self.assertAlmostEqual(p['lowlevel.tctototal'], TCToTotal()(envelope)) suite = allTests(TestTCToTotal) if __name__ == '__main__': TextTestRunner(verbosity=2).run(suite)<|fim▁end|>
# This program is distributed in the hope that it will be useful, but WITHOUT
<|file_name|>MidiOutputEventHandler.java<|end_file_name|><|fim▁begin|>package com.pingdynasty.blipbox; import java.util.Map; import java.util.HashMap; import javax.sound.midi.*; import com.pingdynasty.midi.ScaleMapper; import org.apache.log4j.Logger; public class MidiOutputEventHandler extends MultiModeKeyPressManager { private static final Logger log = Logger.getLogger(MidiOutputEventHandler.class); private static final int OCTAVE_SHIFT = 6; private MidiPlayer midiPlayer; private int lastNote = 0; public class MidiConfigurationMode extends ConfigurationMode { private ScaleMapper mapper; private int basenote = 40; public MidiConfigurationMode(String name, String follow){ super(name, follow); mapper = new ScaleMapper(); mapper.setScale("Mixolydian Mode"); // setScale("Chromatic Scale"); // setScale("C Major"); // setScale("Dorian Mode"); } public ScaleMapper getScaleMapper(){ return mapper; } public int getBaseNote(){ return basenote; } public void setBaseNote(int basenote){ this.basenote = basenote; } } public ConfigurationMode createConfigurationMode(String mode, String follow){ return new MidiConfigurationMode(mode, follow); } public ScaleMapper getScaleMapper(){<|fim▁hole|> } public ScaleMapper getScaleMapper(String mode){ MidiConfigurationMode config = (MidiConfigurationMode)getConfigurationMode(mode); return config.getScaleMapper(); } public int getBaseNote(){ MidiConfigurationMode mode = (MidiConfigurationMode)getCurrentConfigurationMode(); return mode.getBaseNote(); } public void setBaseNote(int basenote){ MidiConfigurationMode mode = (MidiConfigurationMode)getCurrentConfigurationMode(); mode.setBaseNote(basenote); } public void setBaseNote(String modename, int basenote){ MidiConfigurationMode mode = (MidiConfigurationMode)getConfigurationMode(modename); mode.setBaseNote(basenote); } public void holdOff(){ super.holdOff(); sendMidiNoteOff(lastNote); } public void init(){ super.init(); setSensorEventHandler("Cross", SensorType.BUTTON2_SENSOR, new OctaveShiftUpEventHandler()); setSensorEventHandler("Cross", SensorType.BUTTON3_SENSOR, new OctaveShiftDownEventHandler()); setSensorEventHandler("Criss", SensorType.BUTTON2_SENSOR, new OctaveShiftUpEventHandler()); setSensorEventHandler("Criss", SensorType.BUTTON3_SENSOR, new OctaveShiftDownEventHandler()); } public class OctaveShiftUpEventHandler implements SensorEventHandler { public void sensorChange(SensorDefinition sensor){ if(sensor.value != 0){ int basenote = getBaseNote(); log.debug("octave up"); basenote += OCTAVE_SHIFT; if(basenote + OCTAVE_SHIFT <= 127) setBaseNote(basenote); log.debug("new basenote "+basenote); } } } public class OctaveShiftDownEventHandler implements SensorEventHandler { public void sensorChange(SensorDefinition sensor){ if(sensor.value != 0){ int basenote = getBaseNote(); log.debug("octave down"); basenote -= OCTAVE_SHIFT; if(basenote > 0) setBaseNote(basenote); log.debug("new basenote "+basenote); } } } public class BaseNoteChangeEventHandler implements SensorEventHandler { private int min, max; public BaseNoteChangeEventHandler(){ this(0, 127); } public BaseNoteChangeEventHandler(int min, int max){ this.min = min; this.max = max; } public void sensorChange(SensorDefinition sensor){ int basenote = sensor.scale(min, max); log.debug("basenote: "+basenote); setBaseNote(basenote); } } public class ScaleChangeEventHandler implements SensorEventHandler { public void sensorChange(SensorDefinition sensor){ ScaleMapper mapper = getScaleMapper(); int val = sensor.scale(mapper.getScaleNames().length); if(val < mapper.getScaleNames().length){ mapper.setScale(val); log.debug("set scale "+mapper.getScaleNames()[val]); } } } public class ControlChangeEventHandler implements SensorEventHandler { private int from; private int to; private int cc; public ControlChangeEventHandler(int cc){ this(cc, 0, 127); } public ControlChangeEventHandler(int cc, int from, int to){ this.from = from; this.to = to; this.cc = cc; } public void sensorChange(SensorDefinition sensor){ int val = sensor.scale(from, to); sendMidiCC(cc, val); } } public class NonRegisteredParameterEventHandler implements SensorEventHandler { private int from; private int to; private int cc; public NonRegisteredParameterEventHandler(int cc, int from, int to){ this.from = from; this.to = to; this.cc = cc; } public void sensorChange(SensorDefinition sensor){ int val = sensor.scale(from, to); sendMidiNRPN(cc, val); } } public class PitchBendEventHandler implements SensorEventHandler { private int from; private int to; public PitchBendEventHandler(){ this(-8191, 8192); } public PitchBendEventHandler(int from, int to){ this.from = from; this.to = to; } public void sensorChange(SensorDefinition sensor){ int val = sensor.scale(from, to); sendMidiPitchBend(val); } } public class NotePlayer implements KeyEventHandler { private int lastnote; public void sensorChange(SensorDefinition sensor){} protected int getVelocity(int row){ // int velocity = ((row+1)*127/8); // int velocity = (row*127/8)+1; int velocity = ((row+1)*127/9); return velocity; } public void keyDown(int col, int row){ lastNote = getScaleMapper().getNote(col+getBaseNote()); sendMidiNoteOn(lastNote, getVelocity(row)); } public void keyUp(int col, int row){ sendMidiNoteOff(lastNote); } public void keyChange(int oldCol, int oldRow, int newCol, int newRow){ int newNote = getScaleMapper().getNote(newCol+getBaseNote()); if(newNote != lastNote){ sendMidiNoteOff(lastNote); sendMidiNoteOn(newNote, getVelocity(newRow)); } lastNote = newNote; } } public MidiOutputEventHandler(BlipBox sender){ super(sender); } public void configureControlChange(String mode, SensorType type, int channel, int cc, int min, int max){ log.debug("Setting "+mode+":"+type+" to CC "+cc+" ("+min+"-"+max+")"); setSensorEventHandler(mode, type, new ControlChangeEventHandler(cc, min, max)); } public void configureNRPN(String mode, SensorType type, int channel, int cc, int min, int max){ log.debug("Setting "+mode+":"+type+" to NRPN "+cc+" ("+min+"-"+max+")"); setSensorEventHandler(mode, type, new NonRegisteredParameterEventHandler(cc, min, max)); } public void configurePitchBend(String mode, SensorType type, int channel, int min, int max){ setSensorEventHandler(mode, type, new PitchBendEventHandler(min, max)); } public void configureBaseNoteChange(String mode, SensorType type, int min, int max){ log.debug("Setting "+mode+":"+type+" to control base note"); setSensorEventHandler(mode, type, new BaseNoteChangeEventHandler(min, max)); } public void configureScaleChange(String mode, SensorType type){ log.debug("Setting "+mode+":"+type+" to control scale changes"); setSensorEventHandler(mode, type, new ScaleChangeEventHandler()); } public void configureNotePlayer(String mode, boolean notes, boolean pb, boolean at){ log.debug("Setting "+mode+" mode to play notes ("+notes+") pitch bend ("+pb+") aftertouch ("+at+")"); if(notes){ setKeyEventHandler(mode, new NotePlayer()); }else{ setKeyEventHandler(mode, null); } // todo: honour pb and at } // public String[] getScaleNames(){ // return mapper.getScaleNames(); // } // public void setScale(int index){ // mapper.setScale(index); // } public String getCurrentScale(){ ScaleMapper mapper = getScaleMapper(); return mapper.getScaleNames()[mapper.getScaleIndex()]; } public void setMidiPlayer(MidiPlayer midiPlayer){ this.midiPlayer = midiPlayer; } public void sendMidiNoteOn(int note, int velocity){ log.debug("note on:\t "+note+"\t "+velocity); if(note > 127 || note < 0){ log.error("MIDI note on "+note+"/"+velocity+" value out of range"); return; } if(velocity > 127 || velocity < 0){ log.error("MIDI note on "+note+"/"+velocity+" value out of range"); velocity = velocity < 0 ? 0 : 127; } try { if(midiPlayer != null) midiPlayer.noteOn(note, velocity); }catch(Exception exc){ log.error(exc, exc); } } public void sendMidiNoteOff(int note){ // note = mapper.getNote(note); log.debug("note off:\t "+note); if(note > 127 || note < 0){ log.error("MIDI note off "+note+" value out of range"); return; } try { if(midiPlayer != null) midiPlayer.noteOff(note); }catch(Exception exc){ log.error(exc, exc); } } public void sendMidiNRPN(int parameter, int value){ // log.debug("nrpn ("+parameter+") :\t "+value); sendMidiCC(99, 3); sendMidiCC(98, parameter & 0x7f); // NRPN LSB sendMidiCC(6, value); // sendMidiCC(99, parameter >> 7); // NRPN MSB // sendMidiCC(98, parameter & 0x7f); // NRPN LSB // sendMidiCC(6, value >> 7); // Data Entry MSB // if((value & 0x7f) != 0) // sendMidiCC(38, value & 0x7f); // Data Entry LSB } public void sendMidiCC(int cc, int value){ // log.debug("midi cc:\t "+cc+"\t "+value); if(value > 127 || value < 0){ log.error("MIDI CC "+cc+" value out of range: "+value); return; } try { if(midiPlayer != null) midiPlayer.controlChange(cc, value); }catch(Exception exc){ log.error(exc, exc); } } public void sendMidiPitchBend(int degree){ // send midi pitch bend in the range -8192 to 8191 inclusive if(degree < -8192 || degree > 8191){ log.error("MIDI pitch bend value out of range: "+degree); return; } // setPitchBend() expects a value in the range 0 to 16383 degree += 8192; try { if(midiPlayer != null) midiPlayer.pitchBend(degree); }catch(Exception exc){ log.error(exc, exc); } } public void setChannel(int channel){ midiPlayer.setChannel(channel); } public class SensitiveNotePlayer implements KeyEventHandler { private int lastnote; private int velocity; // todo : velocity could be set by row rather than sensor position public void sensorChange(SensorDefinition sensor){ velocity = sensor.scale(127); } public void keyDown(int col, int row){ lastNote = getScaleMapper().getNote(col+getBaseNote()); sendMidiNoteOn(lastNote, velocity); } public void keyUp(int col, int row){ sendMidiNoteOff(lastNote); } public void keyChange(int oldCol, int oldRow, int newCol, int newRow){ int newNote = getScaleMapper().getNote(newCol+getBaseNote()); if(newNote != lastNote){ sendMidiNoteOff(lastNote); sendMidiNoteOn(newNote, velocity); // }else{ // // todo: aftertouch, bend } lastNote = newNote; } } }<|fim▁end|>
MidiConfigurationMode mode = (MidiConfigurationMode)getCurrentConfigurationMode(); return mode.getScaleMapper();
<|file_name|>bitset_test.go<|end_file_name|><|fim▁begin|>// Copyright 2014 Will Fitzgerald. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // This file tests bit sets package sparsebitset import ( "math" "math/rand" "testing" ) func TestEmptyBitSet(t *testing.T) { defer func() { if r := recover(); r != nil { t.Error("A zero-length bitset should be fine") } }() b := New(0) if b.Len() != 0 { t.Errorf("Empty set should have capacity 0, not %d", b.Len()) } } func TestZeroValueBitSet(t *testing.T) { defer func() { if r := recover(); r != nil { t.Error("A zero-length bitset should be fine") } }() var b BitSet if b.Len() != 0 { t.Errorf("Empty set should have capacity 0, not %d", b.Len()) } } func TestBitSetNew(t *testing.T) { v := New(16) if v.Test(0) != false { t.Errorf("Unable to make a bit set and read its 0th value.") } } func TestBitSetHuge(t *testing.T) { v := New(uint64(math.MaxUint32)) if v.Test(0) != false { t.Errorf("Unable to make a huge bit set and read its 0th value.") } } // func TestLen(t *testing.T) { // v := New(1000) // if v.Len() != 1000 { // t.Errorf("Len should be 1000, but is %d.", v.Len()) // } // } func TestBitSetIsClear(t *testing.T) { v := New(1000) for i := uint64(0); i < 1000; i++ { if v.Test(i) != false { t.Errorf("Bit %d is set, and it shouldn't be.", i) } } } func TestExendOnBoundary(t *testing.T) { v := New(32) defer func() { if r := recover(); r != nil { t.Error("Border out of index error should not have caused a panic") } }() v.Set(32) } func TestExpand(t *testing.T) { v := New(0) defer func() { if r := recover(); r != nil { t.Error("Expansion should not have caused a panic") } }() for i := uint64(0); i < 1000; i++ { v.Set(i) } } func TestBitSetAndGet(t *testing.T) { v := New(1000) v.Set(100) if v.Test(100) != true { t.Errorf("Bit %d is clear, and it shouldn't be.", 100) } } func TestIterate(t *testing.T) { v := New(10000) v.Set(0) v.Set(1) v.Set(2) data := make([]uint64, 3) c := 0 for i, e := v.NextSet(0); e; i, e = v.NextSet(i + 1) { data[c] = i c++ } if data[0] != 0 { t.Errorf("bug 0") } if data[1] != 1 { t.Errorf("bug 1") } if data[2] != 2 { t.Errorf("bug 2") } v.Set(10) v.Set(2000) data = make([]uint64, 5) c = 0 for i, e := v.NextSet(0); e; i, e = v.NextSet(i + 1) { data[c] = i c++ } if data[0] != 0 { t.Errorf("bug 0") } if data[1] != 1 { t.Errorf("bug 1") } if data[2] != 2 { t.Errorf("bug 2") } if data[3] != 10 { t.Errorf("bug 3") } if data[4] != 2000 { t.Errorf("bug 4") } } func TestSetTo(t *testing.T) { v := New(1000) v.SetTo(100, true) if v.Test(100) != true { t.Errorf("Bit %d is clear, and it shouldn't be.", 100) } v.SetTo(100, false) if v.Test(100) != false { t.Errorf("Bit %d is set, and it shouldn't be.", 100) } } func TestChain(t *testing.T) { if New(1000).Set(100).Set(99).Clear(99).Test(100) != true { t.Errorf("Bit %d is clear, and it shouldn't be.", 100) } } func TestOutOfBoundsLong(t *testing.T) { v := New(64) defer func() { if r := recover(); r != nil { t.Error("Long distance out of index error should not have caused a panic") } }() v.Set(1000) } func TestOutOfBoundsClose(t *testing.T) { v := New(65) defer func() { if r := recover(); r != nil { t.Error("Local out of index error should not have caused a panic") } }() v.Set(66) } func TestCount(t *testing.T) { tot := uint64(64*4 + 11) // just some multi unit64 number v := New(tot) checkLast := true for i := uint64(0); i < tot; i++ { sz := uint64(v.Count()) if sz != i { t.Errorf("Count reported as %d, but it should be %d", sz, i) checkLast = false break } v.Set(i) } if checkLast { sz := uint64(v.Count()) if sz != tot { t.Errorf("After all bits set, size reported as %d, but it should be %d", sz, tot) } } } // test setting every 3rd bit, just in case something odd is happening func TestCount2(t *testing.T) { tot := uint64(64*4 + 11) // just some multi unit64 number v := New(tot) for i := uint64(0); i < tot; i += 3 { sz := uint64(v.Count()) if sz != i/3 { t.Errorf("Count reported as %d, but it should be %d", sz, i) break } v.Set(i) } } // nil tests func TestNullTest(t *testing.T) { var v *BitSet defer func() { if r := recover(); r == nil { t.Error("Checking bit of null reference should have caused a panic") } }() v.Test(66) } func TestNullSet(t *testing.T) { var v *BitSet defer func() { if r := recover(); r == nil { t.Error("Setting bit of null reference should have caused a panic") } }() v.Set(66) } func TestNullClear(t *testing.T) { var v *BitSet defer func() { if r := recover(); r == nil { t.Error("Clearning bit of null reference should have caused a panic") } }() v.Clear(66) } func TestPanicDifferenceBNil(t *testing.T) { var b *BitSet var compare = New(10) defer func() { if r := recover(); r == nil { t.Error("Nil First should should have caused a panic") } }() b.Difference(compare) } func TestPanicDifferenceCompareNil(t *testing.T) { var compare *BitSet var b = New(10) defer func() { if r := recover(); r == nil { t.Error("Nil Second should should have caused a panic") } }() if b.Difference(compare) == nil { panic("empty bitset given") } } func TestPanicUnionBNil(t *testing.T) { var b *BitSet var compare = New(10) defer func() { if r := recover(); r == nil { t.Error("Nil First should should have caused a panic") } }() b.Union(compare) } func TestPanicUnionCompareNil(t *testing.T) { var compare *BitSet var b = New(10) defer func() { if r := recover(); r == nil { t.Error("Nil Second should should have caused a panic") } }() if b.Union(compare) == nil { panic("empty bitset given") } } func TestPanicIntersectionBNil(t *testing.T) { var b *BitSet var compare = New(10) defer func() { if r := recover(); r == nil { t.Error("Nil First should should have caused a panic") } }() b.Intersection(compare) } func TestPanicIntersectionCompareNil(t *testing.T) { var compare *BitSet var b = New(10) defer func() { if r := recover(); r == nil { t.Error("Nil Second should should have caused a panic") } }() if b.Intersection(compare) == nil { panic("empty bitset given") } } func TestPanicSymmetricDifferenceBNil(t *testing.T) { var b *BitSet var compare = New(10) defer func() { if r := recover(); r == nil { t.Error("Nil First should should have caused a panic") } }() b.SymmetricDifference(compare) } func TestPanicSymmetricDifferenceCompareNil(t *testing.T) { var compare *BitSet var b = New(10) defer func() { if r := recover(); r == nil { t.Error("Nil Second should should have caused a panic") } }() if b.SymmetricDifference(compare) == nil { panic("empty bitset given") } } func TestPanicComplementBNil(t *testing.T) { var b *BitSet defer func() { if r := recover(); r == nil { t.Error("Nil should should have caused a panic") } }() b.Complement() } func TestPanicAnytBNil(t *testing.T) { var b *BitSet defer func() { if r := recover(); r == nil { t.Error("Nil should should have caused a panic") } }() b.Any() } func TestPanicNonetBNil(t *testing.T) { var b *BitSet defer func() { if r := recover(); r == nil { t.Error("Nil should should have caused a panic") } }() b.None() } func TestPanicAlltBNil(t *testing.T) { var b *BitSet defer func() { if r := recover(); r == nil { t.Error("Nil should should have caused a panic") } }() b.All() } func TestEqual(t *testing.T) { a := New(100)<|fim▁hole|> // if a.Equal(b) { // t.Error("Sets of different sizes should be not be equal") // } // if !a.Equal(c) { // t.Error("Two empty sets of the same size should be equal") // } a.Set(99) c.Set(0) if a.Equal(c) { t.Error("Two sets with differences should not be equal") } c.Set(99) a.Set(0) if !a.Equal(c) { t.Error("Two sets with the same bits set should be equal") } } func TestUnion(t *testing.T) { a := New(100) b := New(200) for i := uint64(1); i < 100; i += 2 { a.Set(i) b.Set(i - 1) } for i := uint64(100); i < 200; i++ { b.Set(i) } na, _ := a.UnionCardinality(b) if na != 200 { t.Errorf("Union should have 200 bits set, but had %d", na) } nb, _ := b.UnionCardinality(a) if na != nb { t.Errorf("Union should be symmetric") } c := a.Union(b) d := b.Union(a) if c.Count() != 200 { t.Errorf("Union should have 200 bits set, but had %d", c.Count()) } if !c.Equal(d) { t.Errorf("Union should be symmetric") } } func TestInPlaceUnion(t *testing.T) { a := New(100) b := New(200) for i := uint64(1); i < 100; i += 2 { a.Set(i) b.Set(i - 1) } for i := uint64(100); i < 200; i++ { b.Set(i) } c := a.Clone() c.InPlaceUnion(b) d := b.Clone() d.InPlaceUnion(a) if c.Count() != 200 { t.Errorf("Union should have 200 bits set, but had %d", c.Count()) } if d.Count() != 200 { t.Errorf("Union should have 200 bits set, but had %d", d.Count()) } if !c.Equal(d) { t.Errorf("Union should be symmetric") } } func TestIntersection(t *testing.T) { a := New(100) b := New(200) for i := uint64(1); i < 100; i += 2 { a.Set(i) b.Set(i - 1).Set(i) } for i := uint64(100); i < 200; i++ { b.Set(i) } na, _ := a.IntersectionCardinality(b) if na != 50 { t.Errorf("Intersection should have 50 bits set, but had %d", na) } nb, _ := b.IntersectionCardinality(a) if na != nb { t.Errorf("Intersection should be symmetric") } c := a.Intersection(b) d := b.Intersection(a) if c.Count() != 50 { t.Errorf("Intersection should have 50 bits set, but had %d", c.Count()) } if !c.Equal(d) { t.Errorf("Intersection should be symmetric") } } func TestInplaceIntersection(t *testing.T) { a := New(100) b := New(200) for i := uint64(1); i < 100; i += 2 { a.Set(i) b.Set(i - 1).Set(i) } for i := uint64(100); i < 200; i++ { b.Set(i) } c := a.Clone() c.InPlaceIntersection(b) d := b.Clone() d.InPlaceIntersection(a) e := New(100) for i := uint64(76); i < 100; i++ { e.Set(i) } f := a.Clone() f.InPlaceIntersection(e) if c.Count() != 50 { t.Errorf("Intersection should have 50 bits set, but had %d", c.Count()) } if d.Count() != 50 { t.Errorf("Intersection should have 50 bits set, but had %d", d.Count()) } if !c.Equal(d) { t.Errorf("Intersection should be symmetric") } if f.Count() != 12 { t.Errorf("Intersection should have 12 bits set, but had %d", f.Count()) } } func TestDifference(t *testing.T) { a := New(100) b := New(200) for i := uint64(1); i < 100; i += 2 { a.Set(i) b.Set(i - 1) } for i := uint64(100); i < 200; i++ { b.Set(i) } na, _ := a.DifferenceCardinality(b) if na != 50 { t.Errorf("a-b Difference should have 50 bits set, but had %d", na) } nb, _ := b.DifferenceCardinality(a) if nb != 150 { t.Errorf("b-a Difference should have 150 bits set, but had %d", nb) } c := a.Difference(b) d := b.Difference(a) if c.Count() != 50 { t.Errorf("a-b Difference should have 50 bits set, but had %d", c.Count()) } if d.Count() != 150 { t.Errorf("b-a Difference should have 150 bits set, but had %d", d.Count()) } if c.Equal(d) { t.Errorf("Difference, here, should not be symmetric") } } func TestInPlaceDifference(t *testing.T) { a := New(100) b := New(200) for i := uint64(1); i < 100; i += 2 { a.Set(i) b.Set(i - 1) } for i := uint64(100); i < 200; i++ { b.Set(i) } c := a.Clone() c.InPlaceDifference(b) d := b.Clone() d.InPlaceDifference(a) e := a.Clone() for i := uint64(0); i < 100; i += 2 { e.Set(i) } e.InPlaceDifference(b) if c.Count() != 50 { t.Errorf("a-b Difference should have 50 bits set, but had %d", c.Count()) } if d.Count() != 150 { t.Errorf("b-a Difference should have 150 bits set, but had %d", d.Count()) } if c.Equal(d) { t.Errorf("Difference, here, should not be symmetric") } if e.Count() != 50 { t.Errorf("e-b Difference should have 50 bits set, but had %d", e.Count()) } } func TestSymmetricDifference(t *testing.T) { a := New(100) b := New(200) for i := uint64(1); i < 100; i += 2 { a.Set(i) // 01010101010 ... 0000000 b.Set(i - 1).Set(i) // 11111111111111111000000 } for i := uint64(100); i < 200; i++ { b.Set(i) } na, _ := a.SymmetricDifferenceCardinality(b) if na != 150 { t.Errorf("a^b Difference should have 150 bits set, but had %d", na) } nb, _ := b.SymmetricDifferenceCardinality(a) if nb != 150 { t.Errorf("b^a Difference should have 150 bits set, but had %d", nb) } c := a.SymmetricDifference(b) d := b.SymmetricDifference(a) if c.Count() != 150 { t.Errorf("a^b Difference should have 150 bits set, but had %d", c.Count()) } if d.Count() != 150 { t.Errorf("b^a Difference should have 150 bits set, but had %d", d.Count()) } if !c.Equal(d) { t.Errorf("SymmetricDifference should be symmetric") } } func TestInPlaceSymmetricDifference(t *testing.T) { a := New(100) b := New(200) for i := uint64(1); i < 100; i += 2 { a.Set(i) // 01010101010 ... 0000000 b.Set(i - 1).Set(i) // 11111111111111111000000 } for i := uint64(100); i < 200; i++ { b.Set(i) } c := a.Clone() c.InPlaceSymmetricDifference(b) d := b.Clone() d.InPlaceSymmetricDifference(a) if c.Count() != 150 { t.Errorf("a^b Difference should have 150 bits set, but had %d", c.Count()) } if d.Count() != 150 { t.Errorf("b^a Difference should have 150 bits set, but had %d", d.Count()) } if !c.Equal(d) { t.Errorf("SymmetricDifference should be symmetric") } } func TestIsSuperSet(t *testing.T) { a := New(500) b := New(300) c := New(200) // Setup bitsets // a and b overlap // only c is (strict) super set for i := uint64(0); i < 100; i++ { a.Set(i) } for i := uint64(50); i < 150; i++ { b.Set(i) } for i := uint64(0); i < 200; i++ { c.Set(i) } if a.IsSuperSet(b) == true { t.Errorf("IsSuperSet fails") } if a.IsSuperSet(c) == true { t.Errorf("IsSuperSet fails") } if b.IsSuperSet(a) == true { t.Errorf("IsSuperSet fails") } if b.IsSuperSet(c) == true { t.Errorf("IsSuperSet fails") } if c.IsSuperSet(a) != true { t.Errorf("IsSuperSet fails") } if c.IsSuperSet(b) != true { t.Errorf("IsSuperSet fails") } if a.IsStrictSuperSet(b) == true { t.Errorf("IsStrictSuperSet fails") } if a.IsStrictSuperSet(c) == true { t.Errorf("IsStrictSuperSet fails") } if b.IsStrictSuperSet(a) == true { t.Errorf("IsStrictSuperSet fails") } if b.IsStrictSuperSet(c) == true { t.Errorf("IsStrictSuperSet fails") } if c.IsStrictSuperSet(a) != true { t.Errorf("IsStrictSuperSet fails") } if c.IsStrictSuperSet(b) != true { t.Errorf("IsStrictSuperSet fails") } } // BENCHMARKS func BenchmarkSet(b *testing.B) { b.StopTimer() r := rand.New(rand.NewSource(0)) sz := 100000 s := New(uint64(sz)) b.StartTimer() for i := 0; i < b.N; i++ { s.Set(uint64(r.Int31n(int32(sz)))) } } func BenchmarkGetTest(b *testing.B) { b.StopTimer() r := rand.New(rand.NewSource(0)) sz := 100000 s := New(uint64(sz)) b.StartTimer() for i := 0; i < b.N; i++ { s.Test(uint64(r.Int31n(int32(sz)))) } } func BenchmarkSetExpand(b *testing.B) { b.StopTimer() sz := uint64(100000) b.StartTimer() for i := 0; i < b.N; i++ { var s BitSet s.Set(sz) } } // go test -bench=Count func BenchmarkCount(b *testing.B) { b.StopTimer() s := New(100000) for i := 0; i < 100000; i += 100 { s.Set(uint64(i)) } b.StartTimer() for i := 0; i < b.N; i++ { s.Count() } } // go test -bench=Iterate func BenchmarkIterate(b *testing.B) { b.StopTimer() s := New(10000) for i := 0; i < 10000; i += 3 { s.Set(uint64(i)) } b.StartTimer() for j := 0; j < b.N; j++ { c := uint(0) for i, e := s.NextSet(0); e; i, e = s.NextSet(i + 1) { c++ } } } // go test -bench=SparseIterate func BenchmarkSparseIterate(b *testing.B) { b.StopTimer() s := New(100000) for i := 0; i < 100000; i += 30 { s.Set(uint64(i)) } b.StartTimer() for j := 0; j < b.N; j++ { c := uint(0) for i, e := s.NextSet(0); e; i, e = s.NextSet(i + 1) { c++ } } }<|fim▁end|>
// b := New(99) c := New(100)
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from .circumcision_model_mixin import CircumcisionModelMixin from .crf_model_mixin import CrfModelManager, CrfModelMixin # CrfModelMixinNonUniqueVisit from .detailed_sexual_history_mixin import DetailedSexualHistoryMixin from .hiv_testing_supplemental_mixin import HivTestingSupplementalMixin from .mobile_test_model_mixin import MobileTestModelMixin from .pregnancy_model_mixin import PregnancyModelMixin from .search_slug_model_mixin import SearchSlugModelMixin<|fim▁hole|><|fim▁end|>
from .sexual_partner_model_mixin import SexualPartnerMixin
<|file_name|>profile.py<|end_file_name|><|fim▁begin|># Monary - Copyright 2011-2013 David J. C. Beach # Please see the included LICENSE.TXT and NOTICE.TXT for licensing information. from time import time<|fim▁hole|> def __init__(self, name): self._name = name def __enter__(self): self._start = time() def __exit__(self, *args): stop = time() print "%s took %6.2f s" % (self._name, stop - self._start)<|fim▁end|>
class profile(object):
<|file_name|>kickstarter_service.py<|end_file_name|><|fim▁begin|>from .service import Service<|fim▁hole|> class KickstarterService(Service): def get_supporters(self): r = self.get('kickstarter/') self.print_supporters(r) def print_supporters(self, s): for supporter in s: print("%-40s %s" % (str(supporter['name']), str(supporter['message']))) kick = KickstarterService()<|fim▁end|>
<|file_name|>mainandprojects.py<|end_file_name|><|fim▁begin|>from locust import HttpLocust, TaskSet, task class UserBehavior(TaskSet): def on_start(self): """ on_start is called when a Locust start before any task is scheduled """ self.login() def login(self):<|fim▁hole|> @task(2) def index(self): self.client.get("/") @task(1) def project1(self): self.client.get("/app/category/featured/") class WebsiteUser(HttpLocust): task_set = UserBehavior min_wait=5000 max_wait=9000<|fim▁end|>
# do a login here # self.client.post("/login", {"username":"ellen_key", "password":"education"}) pass
<|file_name|>0046_auto__add_field_issue_status.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Issue.status' db.add_column('core_issue', 'status', self.gf('django.db.models.fields.CharField')(default='EMPTY', max_length=40), keep_default=False) def backwards(self, orm): # Deleting field 'Issue.status' db.delete_column('core_issue', 'status') models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'bitcoin_frespo.moneysent': { 'Meta': {'object_name': 'MoneySent'}, 'creationDate': ('django.db.models.fields.DateTimeField', [], {}), 'from_address': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'lastChangeDate': ('django.db.models.fields.DateTimeField', [], {}), 'status': ('django.db.models.fields.CharField', [], {'max_length': '30'}), 'to_address': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'transaction_hash': ('django.db.models.fields.CharField', [], {'max_length': '128', 'null': 'True'}), 'value': ('django.db.models.fields.DecimalField', [], {'max_digits': '16', 'decimal_places': '8'}) }, 'bitcoin_frespo.receiveaddress': { 'Meta': {'object_name': 'ReceiveAddress'}, 'address': ('django.db.models.fields.CharField', [], {'max_length': '128', 'blank': 'True'}), 'available': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'core.actionlog': { 'Meta': {'object_name': 'ActionLog'}, 'action': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'creationDate': ('django.db.models.fields.DateTimeField', [], {}), 'entity': ('django.db.models.fields.CharField', [], {'max_length': '30'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'issue': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.Issue']", 'null': 'True'}), 'issue_comment': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.IssueComment']", 'null': 'True'}), 'new_json': ('django.db.models.fields.TextField', [], {}), 'offer': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.Offer']", 'null': 'True'}), 'old_json': ('django.db.models.fields.TextField', [], {}), 'project': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.Project']", 'null': 'True'}), 'solution': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.Solution']", 'null': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True'}) }, 'core.issue': { 'Meta': {'object_name': 'Issue'}, 'createdByUser': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}), 'creationDate': ('django.db.models.fields.DateTimeField', [], {}), 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_feedback': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_public_suggestion': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'key': ('django.db.models.fields.CharField', [], {'max_length': '30', 'null': 'True', 'blank': 'True'}), 'project': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.Project']", 'null': 'True', 'blank': 'True'}), 'status': ('django.db.models.fields.CharField', [], {'max_length': '40'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '400'}), 'trackerURL': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'trackerURL_noprotocol': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'updatedDate': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}) }, 'core.issuecomment': { 'Meta': {'object_name': 'IssueComment'}, 'author': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}), 'content': ('django.db.models.fields.TextField', [], {}), 'creationDate': ('django.db.models.fields.DateTimeField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'issue': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.Issue']"}) }, 'core.issuecommenthistevent': { 'Meta': {'object_name': 'IssueCommentHistEvent'}, 'comment': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.IssueComment']"}), 'content': ('django.db.models.fields.TextField', [], {}), 'event': ('django.db.models.fields.CharField', [], {'max_length': '30'}), 'eventDate': ('django.db.models.fields.DateTimeField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'core.issuewatch': { 'Meta': {'object_name': 'IssueWatch'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'issue': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.Issue']"}), 'reason': ('django.db.models.fields.CharField', [], {'max_length': '30'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}) }, 'core.offer': { 'Meta': {'object_name': 'Offer'}, 'acceptanceCriteria': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'creationDate': ('django.db.models.fields.DateTimeField', [], {}), 'currency': ('django.db.models.fields.CharField', [], {'max_length': '10'}), 'expirationDate': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'issue': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.Issue']"}), 'lastChangeDate': ('django.db.models.fields.DateTimeField', [], {}), 'no_forking': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'price': ('django.db.models.fields.DecimalField', [], {'max_digits': '9', 'decimal_places': '2'}), 'require_release': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'sponsor': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}), 'status': ('django.db.models.fields.CharField', [], {'max_length': '30'}) }, 'core.offercomment': { 'Meta': {'object_name': 'OfferComment'}, 'author': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}), 'content': ('django.db.models.fields.TextField', [], {}), 'creationDate': ('django.db.models.fields.DateTimeField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'offer': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.Offer']"}) }, 'core.offercommenthistevent': { 'Meta': {'object_name': 'OfferCommentHistEvent'}, 'comment': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.OfferComment']"}), 'content': ('django.db.models.fields.TextField', [], {}), 'event': ('django.db.models.fields.CharField', [], {'max_length': '30'}), 'eventDate': ('django.db.models.fields.DateTimeField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'core.offerhistevent': { 'Meta': {'object_name': 'OfferHistEvent'}, 'acceptanceCriteria': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'event': ('django.db.models.fields.CharField', [], {'max_length': '30'}), 'eventDate': ('django.db.models.fields.DateTimeField', [], {}), 'expirationDate': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'no_forking': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'offer': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.Offer']"}), 'price': ('django.db.models.fields.DecimalField', [], {'max_digits': '9', 'decimal_places': '2'}), 'require_release': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'status': ('django.db.models.fields.CharField', [], {'max_length': '30'}) }, 'core.offerwatch': { 'Meta': {'object_name': 'OfferWatch'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'offer': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.Offer']"}), 'reason': ('django.db.models.fields.CharField', [], {'max_length': '30'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}) }, 'core.payment': { 'Meta': {'object_name': 'Payment'}, 'bitcoin_fee': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '16', 'decimal_places': '8'}), 'bitcoin_receive_address': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['bitcoin_frespo.ReceiveAddress']", 'null': 'True'}), 'bitcoin_transaction_hash': ('django.db.models.fields.CharField', [], {'max_length': '128', 'null': 'True'}), 'confirm_key': ('django.db.models.fields.CharField', [], {'max_length': '128', 'null': 'True', 'blank': 'True'}), 'creationDate': ('django.db.models.fields.DateTimeField', [], {}), 'currency': ('django.db.models.fields.CharField', [], {'max_length': '10'}), 'fee': ('django.db.models.fields.DecimalField', [], {'max_digits': '16', 'decimal_places': '8'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'lastChangeDate': ('django.db.models.fields.DateTimeField', [], {}), 'offer': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.Offer']"}), 'offer2payment_suggested_rate': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '16', 'decimal_places': '8'}), 'offer_currency': ('django.db.models.fields.CharField', [], {'max_length': '10', 'null': 'True'}), 'paykey': ('django.db.models.fields.CharField', [], {'max_length': '128', 'null': 'True', 'blank': 'True'}), 'status': ('django.db.models.fields.CharField', [], {'max_length': '30'}), 'total': ('django.db.models.fields.DecimalField', [], {'max_digits': '16', 'decimal_places': '8'}), 'total_bitcoin_received': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '16', 'decimal_places': '8'}), 'usd2payment_rate': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '16', 'decimal_places': '8'}) }, 'core.paymenthistevent': { 'Meta': {'object_name': 'PaymentHistEvent'}, 'event': ('django.db.models.fields.CharField', [], {'max_length': '30'}), 'eventDate': ('django.db.models.fields.DateTimeField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'payment': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.Payment']"}), 'status': ('django.db.models.fields.CharField', [], {'max_length': '30'}) }, 'core.paymentpart': { 'Meta': {'object_name': 'PaymentPart'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'money_sent': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['bitcoin_frespo.MoneySent']", 'null': 'True'}), 'payment': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.Payment']"}), 'paypalEmail': ('django.db.models.fields.EmailField', [], {'max_length': '256', 'null': 'True'}), 'price': ('django.db.models.fields.DecimalField', [], {'max_digits': '16', 'decimal_places': '8'}), 'programmer': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}), 'solution': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.Solution']"}) },<|fim▁hole|> 'homeURL': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'image3x1': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'trackerURL': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}) }, 'core.solution': { 'Meta': {'object_name': 'Solution'}, 'accepting_payments': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'creationDate': ('django.db.models.fields.DateTimeField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'issue': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.Issue']"}), 'lastChangeDate': ('django.db.models.fields.DateTimeField', [], {}), 'programmer': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}), 'status': ('django.db.models.fields.CharField', [], {'max_length': '30'}) }, 'core.solutionhistevent': { 'Meta': {'object_name': 'SolutionHistEvent'}, 'event': ('django.db.models.fields.CharField', [], {'max_length': '30'}), 'eventDate': ('django.db.models.fields.DateTimeField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'solution': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.Solution']"}), 'status': ('django.db.models.fields.CharField', [], {'max_length': '30'}) }, 'core.userinfo': { 'Meta': {'object_name': 'UserInfo'}, 'about': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'bitcoin_receive_address': ('django.db.models.fields.CharField', [], {'max_length': '128', 'blank': 'True'}), 'brazilianPaypal': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'hide_from_userlist': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_paypal_email_verified': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_primary_email_verified': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'paypalEmail': ('django.db.models.fields.EmailField', [], {'max_length': '256'}), 'paypal_verified': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'preferred_language_code': ('django.db.models.fields.CharField', [], {'max_length': '10', 'null': 'True', 'blank': 'True'}), 'realName': ('django.db.models.fields.CharField', [], {'max_length': '256'}), 'receiveAllEmail': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'receiveEmail_announcements': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'receiveEmail_issue_comments': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'receiveEmail_issue_offer': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'receiveEmail_issue_payment': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'receiveEmail_issue_work': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'screenName': ('django.db.models.fields.CharField', [], {'max_length': '64'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}), 'website': ('django.db.models.fields.CharField', [], {'max_length': '128', 'null': 'True', 'blank': 'True'}) } } complete_apps = ['core']<|fim▁end|>
'core.project': { 'Meta': {'object_name': 'Project'}, 'createdByUser': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}), 'creationDate': ('django.db.models.fields.DateTimeField', [], {}),
<|file_name|>cc-prereq.js<|end_file_name|><|fim▁begin|>// <![CDATA[ /** * Creative Commons has made the contents of this file * available under a CC-GNU-GPL license: * * http://creativecommons.org/licenses/GPL/2.0/ * * A copy of the full license can be found as part of this * distribution in the file COPYING. * * You may use this software in accordance with the * terms of that license. You agree that you are solely * responsible for your use of this software and you * represent and warrant to Creative Commons that your use * of this software will comply with the CC-GNU-GPL.<|fim▁hole|> * * $Id: $ * * Copyright 2006, Creative Commons, www.creativecommons.org. * * This is code that is used to generate licenses. * */ function cc_js_$F(id) { if (cc_js_$(id)) { return cc_js_$(id).value; } return null; // if we can't find the form element, pretend it has no contents } function cc_js_$(id) { return document.getElementById("cc_js_" + id); } /* Inspired by Django. Thanks, guys. * http://code.djangoproject.com/browser/django/trunk/django/views/i18n.py * Our use of gettext is incomplete, so I'm just grabbing the one function. * And I've modified it, anyway. * Here is their license - it applies only to the following function: Copyright (c) 2005, the Lawrence Journal-World All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Django nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ function cc_js_gettext_style_interpolate(fmt, obj) { return fmt.replace(/\${\w+}/g, function(match){return String(obj[match.slice(2,-1)])}); }<|fim▁end|>
<|file_name|>device.go<|end_file_name|><|fim▁begin|>/* * Copyright © 2012 go-opencl authors *<|fim▁hole|> * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * go-opencl is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with go-opencl. If not, see <http://www.gnu.org/licenses/>. */ package cl /* #cgo CFLAGS: -I CL #cgo LDFLAGS: -lOpenCL #include "CL/opencl.h" */ import "C" import ( "unsafe" ) type DeviceType C.cl_device_type const ( DEVICE_TYPE_DEFAULT DeviceType = C.CL_DEVICE_TYPE_DEFAULT DEVICE_TYPE_CPU DeviceType = C.CL_DEVICE_TYPE_CPU DEVICE_TYPE_GPU DeviceType = C.CL_DEVICE_TYPE_GPU DEVICE_TYPE_ACCELERATOR DeviceType = C.CL_DEVICE_TYPE_ACCELERATOR //DEVICE_TYPE_CUSTOM DeviceType = C.CL_DEVICE_TYPE_CUSTOM DEVICE_TYPE_ALL DeviceType = C.CL_DEVICE_TYPE_ALL ) func (t DeviceType) String() string { mesg := deviceTypeMesg[t] if mesg == "" { return t.String() } return mesg } var deviceTypeMesg = map[DeviceType]string{ DEVICE_TYPE_CPU: "CPU", DEVICE_TYPE_GPU: "GPU", DEVICE_TYPE_ACCELERATOR: "Accelerator", //DEVICE_TYPE_CUSTOM: "Custom", } type DeviceProperty C.cl_device_info const ( DEVICE_ADDRESS_BITS DeviceProperty = C.CL_DEVICE_ADDRESS_BITS DEVICE_AVAILABLE DeviceProperty = C.CL_DEVICE_AVAILABLE //DEVICE_BUILT_IN_KERNELS DeviceProperty = C.CL_DEVICE_BUILT_IN_KERNELS DEVICE_COMPILER_AVAILABLE DeviceProperty = C.CL_DEVICE_COMPILER_AVAILABLE //DEVICE_DOUBLE_FP_CONFIG DeviceProperty = C.CL_DEVICE_DOUBLE_FP_CONFIG DEVICE_ENDIAN_LITTLE DeviceProperty = C.CL_DEVICE_ENDIAN_LITTLE DEVICE_ERROR_CORRECTION_SUPPORT DeviceProperty = C.CL_DEVICE_ERROR_CORRECTION_SUPPORT DEVICE_EXECUTION_CAPABILITIES DeviceProperty = C.CL_DEVICE_EXECUTION_CAPABILITIES DEVICE_EXTENSIONS DeviceProperty = C.CL_DEVICE_EXTENSIONS DEVICE_GLOBAL_MEM_CACHE_SIZE DeviceProperty = C.CL_DEVICE_GLOBAL_MEM_CACHE_SIZE DEVICE_GLOBAL_MEM_CACHE_TYPE DeviceProperty = C.CL_DEVICE_GLOBAL_MEM_CACHE_TYPE DEVICE_GLOBAL_MEM_CACHELINE_SIZE DeviceProperty = C.CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE DEVICE_GLOBAL_MEM_SIZE DeviceProperty = C.CL_DEVICE_GLOBAL_MEM_SIZE //DEVICE_HALF_FP_CONFIG DeviceProperty = C.CL_DEVICE_HALF_FP_CONFIG DEVICE_HOST_UNIFIED_MEMORY DeviceProperty = C.CL_DEVICE_HOST_UNIFIED_MEMORY DEVICE_IMAGE_SUPPORT DeviceProperty = C.CL_DEVICE_IMAGE_SUPPORT DEVICE_IMAGE2D_MAX_HEIGHT DeviceProperty = C.CL_DEVICE_IMAGE2D_MAX_HEIGHT DEVICE_IMAGE2D_MAX_WIDTH DeviceProperty = C.CL_DEVICE_IMAGE2D_MAX_WIDTH DEVICE_IMAGE3D_MAX_DEPTH DeviceProperty = C.CL_DEVICE_IMAGE3D_MAX_DEPTH DEVICE_IMAGE3D_MAX_HEIGHT DeviceProperty = C.CL_DEVICE_IMAGE3D_MAX_HEIGHT DEVICE_IMAGE3D_MAX_WIDTH DeviceProperty = C.CL_DEVICE_IMAGE3D_MAX_WIDTH //DEVICE_IMAGE_MAX_BUFFER_SIZE DeviceProperty = C.CL_DEVICE_IMAGE_MAX_BUFFER_SIZE //DEVICE_IMAGE_MAX_ARRAY_SIZE DeviceProperty = C.CL_DEVICE_IMAGE_MAX_ARRAY_SIZE //DEVICE_LINKER_AVAILABLE DeviceProperty = C.CL_DEVICE_LINKER_AVAILABLE DEVICE_LOCAL_MEM_SIZE DeviceProperty = C.CL_DEVICE_LOCAL_MEM_SIZE DEVICE_LOCAL_MEM_TYPE DeviceProperty = C.CL_DEVICE_LOCAL_MEM_TYPE DEVICE_MAX_CLOCK_FREQUENCY DeviceProperty = C.CL_DEVICE_MAX_CLOCK_FREQUENCY DEVICE_MAX_COMPUTE_UNITS DeviceProperty = C.CL_DEVICE_MAX_COMPUTE_UNITS DEVICE_MAX_CONSTANT_ARGS DeviceProperty = C.CL_DEVICE_MAX_CONSTANT_ARGS DEVICE_MAX_CONSTANT_BUFFER_SIZE DeviceProperty = C.CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE DEVICE_MAX_MEM_ALLOC_SIZE DeviceProperty = C.CL_DEVICE_MAX_MEM_ALLOC_SIZE DEVICE_MAX_PARAMETER_SIZE DeviceProperty = C.CL_DEVICE_MAX_PARAMETER_SIZE DEVICE_MAX_READ_IMAGE_ARGS DeviceProperty = C.CL_DEVICE_MAX_READ_IMAGE_ARGS DEVICE_MAX_SAMPLERS DeviceProperty = C.CL_DEVICE_MAX_SAMPLERS DEVICE_MAX_WORK_GROUP_SIZE DeviceProperty = C.CL_DEVICE_MAX_WORK_GROUP_SIZE DEVICE_MAX_WORK_ITEM_DIMENSIONS DeviceProperty = C.CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS DEVICE_MAX_WORK_ITEM_SIZES DeviceProperty = C.CL_DEVICE_MAX_WORK_ITEM_SIZES DEVICE_MAX_WRITE_IMAGE_ARGS DeviceProperty = C.CL_DEVICE_MAX_WRITE_IMAGE_ARGS DEVICE_MEM_BASE_ADDR_ALIGN DeviceProperty = C.CL_DEVICE_MEM_BASE_ADDR_ALIGN DEVICE_MIN_DATA_TYPE_ALIGN_SIZE DeviceProperty = C.CL_DEVICE_MIN_DATA_TYPE_ALIGN_SIZE DEVICE_NAME DeviceProperty = C.CL_DEVICE_NAME DEVICE_NATIVE_VECTOR_WIDTH_CHAR DeviceProperty = C.CL_DEVICE_NATIVE_VECTOR_WIDTH_CHAR DEVICE_NATIVE_VECTOR_WIDTH_SHORT DeviceProperty = C.CL_DEVICE_NATIVE_VECTOR_WIDTH_SHORT DEVICE_NATIVE_VECTOR_WIDTH_INT DeviceProperty = C.CL_DEVICE_NATIVE_VECTOR_WIDTH_INT DEVICE_NATIVE_VECTOR_WIDTH_LONG DeviceProperty = C.CL_DEVICE_NATIVE_VECTOR_WIDTH_LONG DEVICE_NATIVE_VECTOR_WIDTH_FLOAT DeviceProperty = C.CL_DEVICE_NATIVE_VECTOR_WIDTH_FLOAT DEVICE_NATIVE_VECTOR_WIDTH_DOUBLE DeviceProperty = C.CL_DEVICE_NATIVE_VECTOR_WIDTH_DOUBLE DEVICE_NATIVE_VECTOR_WIDTH_HALF DeviceProperty = C.CL_DEVICE_NATIVE_VECTOR_WIDTH_HALF DEVICE_OPENCL_C_VERSION DeviceProperty = C.CL_DEVICE_OPENCL_C_VERSION //DEVICE_PARENT_DEVICE DeviceProperty = C.CL_DEVICE_PARENT_DEVICE //DEVICE_PARTITION_MAX_SUB_DEVICES DeviceProperty = C.CL_DEVICE_PARTITION_MAX_SUB_DEVICES //DEVICE_PARTITION_PROPERTIES DeviceProperty = C.CL_DEVICE_PARTITION_PROPERTIES //DEVICE_PARTITION_AFFINITY_DOMAIN DeviceProperty = C.CL_DEVICE_PARTITION_AFFINITY_DOMAIN //DEVICE_PARTITION_TYPE DeviceProperty = C.CL_DEVICE_PARTITION_TYPE DEVICE_PLATFORM DeviceProperty = C.CL_DEVICE_PLATFORM DEVICE_PREFERRED_VECTOR_WIDTH_CHAR DeviceProperty = C.CL_DEVICE_PREFERRED_VECTOR_WIDTH_CHAR DEVICE_PREFERRED_VECTOR_WIDTH_SHORT DeviceProperty = C.CL_DEVICE_PREFERRED_VECTOR_WIDTH_SHORT DEVICE_PREFERRED_VECTOR_WIDTH_INT DeviceProperty = C.CL_DEVICE_PREFERRED_VECTOR_WIDTH_INT DEVICE_PREFERRED_VECTOR_WIDTH_LONG DeviceProperty = C.CL_DEVICE_PREFERRED_VECTOR_WIDTH_LONG DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT DeviceProperty = C.CL_DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT DEVICE_PREFERRED_VECTOR_WIDTH_DOUBLE DeviceProperty = C.CL_DEVICE_PREFERRED_VECTOR_WIDTH_DOUBLE DEVICE_PREFERRED_VECTOR_WIDTH_HALF DeviceProperty = C.CL_DEVICE_PREFERRED_VECTOR_WIDTH_HALF //DEVICE_PRINTF_BUFFER_SIZE DeviceProperty = C.CL_DEVICE_PRINTF_BUFFER_SIZE //DEVICE_PREFERRED_INTEROP_USER_SYNC DeviceProperty = C.CL_DEVICE_PREFERRED_INTEROP_USER_SYNC DEVICE_PROFILE DeviceProperty = C.CL_DEVICE_PROFILE DEVICE_PROFILING_TIMER_RESOLUTION DeviceProperty = C.CL_DEVICE_PROFILING_TIMER_RESOLUTION DEVICE_QUEUE_PROPERTIES DeviceProperty = C.CL_DEVICE_QUEUE_PROPERTIES //DEVICE_REFERENCE_COUNT DeviceProperty = C.CL_DEVICE_REFERENCE_COUNT DEVICE_SINGLE_FP_CONFIG DeviceProperty = C.CL_DEVICE_SINGLE_FP_CONFIG DEVICE_TYPE DeviceProperty = C.CL_DEVICE_TYPE DEVICE_VENDOR DeviceProperty = C.CL_DEVICE_VENDOR DEVICE_VENDOR_ID DeviceProperty = C.CL_DEVICE_VENDOR_ID DEVICE_VERSION DeviceProperty = C.CL_DEVICE_VERSION DRIVER_VERSION DeviceProperty = C.CL_DRIVER_VERSION ) type Device struct { id C.cl_device_id properties map[DeviceProperty]interface{} } func (d *Device) Property(prop DeviceProperty) interface{} { if value, ok := d.properties[prop]; ok { return value } var data interface{} var length C.size_t var ret C.cl_int switch prop { case DEVICE_AVAILABLE, DEVICE_COMPILER_AVAILABLE, DEVICE_ENDIAN_LITTLE, DEVICE_ERROR_CORRECTION_SUPPORT, DEVICE_HOST_UNIFIED_MEMORY, DEVICE_IMAGE_SUPPORT: //DEVICE_LINKER_AVAILABLE, //DEVICE_PREFERRED_INTEROP_USER_SYNC: var val C.cl_bool ret = C.clGetDeviceInfo(d.id, C.cl_device_info(prop), C.size_t(unsafe.Sizeof(val)), unsafe.Pointer(&val), &length) data = val == C.CL_TRUE case DEVICE_ADDRESS_BITS, DEVICE_MAX_CLOCK_FREQUENCY, DEVICE_MAX_COMPUTE_UNITS, DEVICE_MAX_CONSTANT_ARGS, DEVICE_MAX_READ_IMAGE_ARGS, DEVICE_MAX_SAMPLERS, DEVICE_MAX_WORK_ITEM_DIMENSIONS, DEVICE_MAX_WRITE_IMAGE_ARGS, DEVICE_MEM_BASE_ADDR_ALIGN, DEVICE_MIN_DATA_TYPE_ALIGN_SIZE, DEVICE_NATIVE_VECTOR_WIDTH_CHAR, DEVICE_NATIVE_VECTOR_WIDTH_SHORT, DEVICE_NATIVE_VECTOR_WIDTH_INT, DEVICE_NATIVE_VECTOR_WIDTH_LONG, DEVICE_NATIVE_VECTOR_WIDTH_FLOAT, DEVICE_NATIVE_VECTOR_WIDTH_DOUBLE, DEVICE_NATIVE_VECTOR_WIDTH_HALF, //DEVICE_PARTITION_MAX_SUB_DEVICES, DEVICE_PREFERRED_VECTOR_WIDTH_CHAR, DEVICE_PREFERRED_VECTOR_WIDTH_SHORT, DEVICE_PREFERRED_VECTOR_WIDTH_INT, DEVICE_PREFERRED_VECTOR_WIDTH_LONG, DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT, DEVICE_PREFERRED_VECTOR_WIDTH_DOUBLE, DEVICE_PREFERRED_VECTOR_WIDTH_HALF, //DEVICE_REFERENCE_COUNT, DEVICE_VENDOR_ID: var val C.cl_uint ret = C.clGetDeviceInfo(d.id, C.cl_device_info(prop), C.size_t(unsafe.Sizeof(val)), unsafe.Pointer(&val), &length) data = val case DEVICE_IMAGE2D_MAX_HEIGHT, DEVICE_IMAGE2D_MAX_WIDTH, DEVICE_IMAGE3D_MAX_DEPTH, DEVICE_IMAGE3D_MAX_HEIGHT, DEVICE_IMAGE3D_MAX_WIDTH, //DEVICE_IMAGE_MAX_BUFFER_SIZE, //DEVICE_IMAGE_MAX_ARRAY_SIZE, DEVICE_MAX_PARAMETER_SIZE, DEVICE_MAX_WORK_GROUP_SIZE, //DEVICE_PRINTF_BUFFER_SIZE, DEVICE_PROFILING_TIMER_RESOLUTION: var val C.size_t ret = C.clGetDeviceInfo(d.id, C.cl_device_info(prop), C.size_t(unsafe.Sizeof(val)), unsafe.Pointer(&val), &length) data = val case DEVICE_GLOBAL_MEM_CACHE_SIZE, DEVICE_GLOBAL_MEM_SIZE, DEVICE_LOCAL_MEM_SIZE, DEVICE_MAX_CONSTANT_BUFFER_SIZE, DEVICE_MAX_MEM_ALLOC_SIZE: var val C.cl_ulong ret = C.clGetDeviceInfo(d.id, C.cl_device_info(prop), C.size_t(unsafe.Sizeof(val)), unsafe.Pointer(&val), &length) data = val /*case DEVICE_PLATFORM: var val C.cl_platform_id ret = C.clGetDeviceInfo(d.id, C.cl_device_info(prop), C.size_t(unsafe.Sizeof(val)), unsafe.Pointer(&val), &length) data = Platform{id: val}*/ /*case DEVICE_PARENT_DEVICE: var val C.cl_device_id ret = C.clGetDeviceInfo(d.id, C.cl_device_info(prop), C.size_t(unsafe.Sizeof(val)), unsafe.Pointer(&val), &length) data = Device{id: val}*/ case DEVICE_TYPE: var val C.cl_device_type ret = C.clGetDeviceInfo(d.id, C.cl_device_info(prop), C.size_t(unsafe.Sizeof(val)), unsafe.Pointer(&val), &length) data = DeviceType(val) case //DEVICE_BUILT_IN_KERNELS, DEVICE_EXTENSIONS, DEVICE_NAME, DEVICE_OPENCL_C_VERSION, DEVICE_PROFILE, DEVICE_VENDOR, DEVICE_VERSION, DRIVER_VERSION: if ret = C.clGetDeviceInfo(d.id, C.cl_device_info(prop), 0, nil, &length); ret != C.CL_SUCCESS || length < 1 { data = "" break } buf := make([]C.char, length) if ret = C.clGetDeviceInfo(d.id, C.cl_device_info(prop), length, unsafe.Pointer(&buf[0]), &length); ret != C.CL_SUCCESS || length < 1 { data = "" break } data = C.GoStringN(&buf[0], C.int(length-1)) default: return nil } if ret != C.CL_SUCCESS { return nil } d.properties[prop] = data return d.properties[prop] }<|fim▁end|>
* This file is part of go-opencl. * * go-opencl is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by
<|file_name|>fd_multidrop_tests.cpp<|end_file_name|><|fim▁begin|>/* Copyright 2022 (C) Alexey Dynda This file is part of Tiny Protocol Library. GNU General Public License Usage Protocol Library is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Protocol Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with Protocol Library. If not, see <http://www.gnu.org/licenses/>. Commercial License Usage Licensees holding valid commercial Tiny Protocol licenses may use this file in accordance with the commercial license agreement provided in accordance with the terms contained in a written agreement between you and Alexey Dynda. For further information contact via email on github account. */ #include <functional> #include <CppUTest/TestHarness.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <thread> #include "helpers/tiny_fd_helper.h" #include "helpers/fake_connection.h" TEST_GROUP(FD_MULTI) { void setup() { // ... // fprintf(stderr, "======== START =======\n" ); } void teardown() { // ... // fprintf(stderr, "======== END =======\n" ); } }; TEST(FD_MULTI, send_to_secondary) { FakeSetup conn; FakeEndpoint &endpoint1 = conn.endpoint1(); FakeEndpoint &endpoint2 = conn.endpoint2(); TinyHelperFd primary(&endpoint1, 4096, TINY_FD_MODE_NRM, nullptr); TinyHelperFd secondary(&endpoint2, 4096, TINY_FD_MODE_NRM, nullptr); primary.setAddress( TINY_FD_PRIMARY_ADDR ); primary.setTimeout( 250 ); primary.init(); secondary.setAddress( 1 ); secondary.setTimeout( 250 ); secondary.init(); // Run secondary station first, as it doesn't transmit until primary sends a marker secondary.run(true); primary.run(true); CHECK_EQUAL(TINY_SUCCESS, primary.registerPeer( 1 ) ); // send 1 small packets uint8_t txbuf[4] = {0xAA, 0xFF, 0xCC, 0x66}; int result = primary.sendto(1, txbuf, sizeof(txbuf)); CHECK_EQUAL(TINY_SUCCESS, result); result = primary.sendto(2, txbuf, sizeof(txbuf)); CHECK_EQUAL(TINY_ERR_UNKNOWN_PEER, result); // wait until last frame arrives secondary.wait_until_rx_count(1, 250); CHECK_EQUAL(1, secondary.rx_count()); } TEST(FD_MULTI, send_to_secondary_dual) { FakeSetup conn; FakeEndpoint &endpoint1 = conn.endpoint1(); FakeEndpoint &endpoint2 = conn.endpoint2(); FakeEndpoint endpoint3(conn.line2(), conn.line1(), 256, 256); TinyHelperFd primary(&endpoint1, 4096, TINY_FD_MODE_NRM, nullptr); TinyHelperFd secondary(&endpoint2, 4096, TINY_FD_MODE_NRM, nullptr); TinyHelperFd secondary2(&endpoint3, 4096, TINY_FD_MODE_NRM, nullptr);<|fim▁hole|> primary.setAddress( TINY_FD_PRIMARY_ADDR ); primary.setTimeout( 250 ); primary.setPeersCount( 2 ); primary.init(); secondary.setAddress( 1 ); secondary.setTimeout( 250 ); secondary.init(); secondary2.setAddress( 2 ); secondary2.setTimeout( 250 ); secondary2.init(); // Run secondary station first, as it doesn't transmit until primary sends a marker secondary.run(true); secondary2.run(true); primary.run(true); CHECK_EQUAL(TINY_SUCCESS, primary.registerPeer( 1 ) ); CHECK_EQUAL(TINY_SUCCESS, primary.registerPeer( 2 ) ); // send 1 small packets uint8_t txbuf[4] = {0xAA, 0xFF, 0xCC, 0x66}; int result = primary.sendto(1, txbuf, sizeof(txbuf)); CHECK_EQUAL(TINY_SUCCESS, result); // wait until last frame arrives secondary.wait_until_rx_count(1, 250); CHECK_EQUAL(1, secondary.rx_count()); CHECK_EQUAL(0, secondary2.rx_count()); result = primary.sendto(2, txbuf, sizeof(txbuf)); secondary2.wait_until_rx_count(1, 250); CHECK_EQUAL(TINY_SUCCESS, result); CHECK_EQUAL(1, secondary.rx_count()); CHECK_EQUAL(1, secondary2.rx_count()); }<|fim▁end|>
<|file_name|>converter_test.js<|end_file_name|><|fim▁begin|>/* global Converter, probandDatav2 */ describe('Converter', function() { describe('load', function() { it('should load proband data', function() { var converter = new Converter(); converter.load(probandDatav2); expect(converter.data).to.deep.equal(probandDatav2); }); it('sould create empty comments object', function() { var converter = new Converter(); converter.load(probandDatav2); expect(converter.comments).to.deep.equal({}); }); it('sould create empty diary array', function() { var converter = new Converter(); converter.load(probandDatav2); expect(converter.diary).to.deep.equal([]); }); it('sould create empty interactions array', function() { var converter = new Converter(); converter.load(probandDatav2); expect(converter.interactions).to.deep.equal([]); }); }); describe('convertComments', function() { it('sould convert v2 diary format to v1 diary format', function() { var commentsDatav1 = { "3c92a4df": "1389823488 ~ ein Freund von mir hat ein Scherz über Bundeswehr gepostet, ich fand es sehr witzig ", "0a81f271": "1389823819 ~ ich habe ein Link von einer Kommilitonin kommentiert, es ging um \"52 Places to go in 2014\" von NY-Times, obwohl München und Berlin nicht dabei sind, ist Frankfurt dabei, naja ich persönlich finde es gibt schönere Plätze in Deutschland ", "7bcddf87": "1389911628 ~ es geht um eine online Umfrage bezüglich unserer Kantine im Niederrad, gepostet hat ein Mitlied des Studentenrates", "13901343": "1390134335 ~ Ich kommentiere einen Zeitungsartikel, den ich selbst geteilt habe. Es wurde in der Rhein-Neckar-Zeitung veröffentlicht und geht darum, dass das Kino in der Altstadt schleißt. Ich finde es sehr traurig, viele Erinnerungen hängen daran, deswegen habe ich mich entschieden es mit meinen Freunden zu teilen. ", "75019456": "1390134527 ~ Es handelt sich dabei um eine bezahlte Werbung von Watchever, einen \"online video stream\" Anbieter. Es geht um ein Gewinnspiel. Mich nerven diese Werbeanzeigen...", "70e816cf": "1390328184 ~ ", "ba5dfbdb": "1390341915 ~ Ich kommentiere einen Videoclip, welches von einer Gruppe gepostet wurde. Es handelt sich dabei um ein Musikvideo von David Guetta, sehr cool, gefällt mir." }; var converter = new Converter(); converter.load(probandDatav2); converter.convertComments(); expect(converter.comments).to.deep.equal(commentsDatav1); }); }); describe('convertInteractions', function() { it('should convert v2 interactions format to v1 interactions format', function() { var interactionsDatav1 = [{ "nr": 0, "interaction_type": "openFacebook", "time": "2014-01-15T19:45:49.374Z", "network": "Facebook"<|fim▁hole|> }, { "nr": 1, "interaction_type": "closeFacebook", "time": "2014-01-15T21:24:14.670Z", "network": "Facebook" }, { "nr": 2, "interaction_type": "openFacebook", "time": "2014-01-15T21:24:14.761Z", "network": "Facebook" }, { "nr": 3, "interaction_type": "like", "time": "2014-01-15T21:45:57.751Z", "network": "Facebook", "object_id": "3e799b96", "object_owner": "9cb2fda2", "object_type": "status" }, { "nr": 4, "interaction_type": "like", "time": "2014-01-15T21:58:48.983Z", "network": "Facebook", "object_id": "3c92a4df", "object_owner": "1abcc45b", "object_type": "status" }]; var converter = new Converter(); converter.load(probandDatav2); converter.convertInteractions(); var convertedInteractions = converter.interactions.splice(0, 5); expect(convertedInteractions).to.deep.equal(interactionsDatav1); }); }); describe('convertDiary', function() { it('sould convert v2 diary format to v1 diary format', function() { var diaryDatav1 = [ ["2014-01-15T22:02:33.565Z", "habe eine Freundschaftsanfrage geschickt"], ["2014-01-16T22:13:34.870Z", "Ein guter Freund von mir ist wieder bei Facebook. Anfang September hat er sein Facebook-Account deaktiviert wegen Staatsexamen, jetzt ist er wieder da. "], ["2014-01-19T12:33:18.834Z", "gestern wurde ich wieder in eine Gruppe der \"Studenten Karlsruhe\" eingeladen, obwohl ich schon mal eingeladen wurde und ich ausgetreten bin...\nwas ich nicht verstehe, dass obwohl ich nirgendswo zugestimmt habe, war ich automatisch ein Mitglied der Gruppe und konnte alles sehen...\njetzt bin ich wieder ausgetreten, und so eingestellt, dass mich Leute nicht wieder einladen können!"], ["2014-01-21T22:37:24.245Z", "was mich zur Zeit nervt, ist das Häkchen bei einer gelesener Nachricht, leider klicke ich manchmal auf eine neue Nachricht und der Absender weißt sofort, dass ich es gesehen habe...\ngenau das wollte ich heute in den Einstellungen ändern, leider fand ich nichts... "], ["2014-01-22T22:35:26.653Z", "Eine Freundin wollte heute in Facebook wissen, wie man es so einstellen kann, dass z. B. Google deine Facebook-Seite nicht als Ergebnis anzeigt, wenn man den Namen eingetippt..."] ]; var converter = new Converter(); converter.load(probandDatav2); converter.convertDiary(); expect(converter.diary).to.deep.equal(diaryDatav1); }); }); });<|fim▁end|>
<|file_name|>players.js<|end_file_name|><|fim▁begin|>$(document).ready(function() { $(document).on('submit', '.status-button', function(e) { e.preventDefault(); var joinButton = e.target $.ajax(joinButton.action, { method: 'PATCH', data: $(this).serialize() })<|fim▁hole|> .fail(function() { alert("Failure!"); }); }); });<|fim▁end|>
.done(function(data) { gameDiv = $(joinButton).parent(); gameDiv.replaceWith(data); })
<|file_name|>bitcoin_lt.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" ?><!DOCTYPE TS><TS language="lt" version="2.1"> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About Litedoge</source> <translation type="unfinished"/> </message> <message> <location line="+39"/> <source>&lt;b&gt;Litedoge&lt;/b&gt; version</source> <translation type="unfinished"/> </message> <message> <location line="+41"/> <source>Copyright © 2009-2014 The Bitcoin developers Copyright © 2012-2014 The NovaCoin developers Copyright © 2014 The Litedoge developers</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or &lt;a href=&quot;http://www.opensource.org/licenses/mit-license.php&quot;&gt;http://www.opensource.org/licenses/mit-license.php&lt;/a&gt;. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (&lt;a href=&quot;https://www.openssl.org/&quot;&gt;https://www.openssl.org/&lt;/a&gt;) and cryptographic software written by Eric Young (&lt;a href=&quot;mailto:[email protected]&quot;&gt;[email protected]&lt;/a&gt;) and UPnP software written by Thomas Bernard.</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Double-click to edit address or label</source> <translation>Spragtelėkite, kad pakeistumėte adresą arba žymę</translation> </message> <message> <location line="+24"/> <source>Create a new address</source> <translation>Sukurti naują adresą</translation> </message> <message> <location line="+10"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Kopijuoti esamą adresą į mainų atmintį</translation> </message> <message> <location line="-7"/> <source>&amp;New Address</source> <translation type="unfinished"/> </message> <message> <location line="-43"/> <source>These are your Litedoge addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation type="unfinished"/> </message> <message> <location line="+53"/> <source>&amp;Copy Address</source> <translation>&amp;Kopijuoti adresą</translation> </message> <message> <location line="+7"/> <source>Show &amp;QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Sign a message to prove you own a Litedoge address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Delete the currently selected address from the list</source> <translation type="unfinished"/> </message> <message> <location line="-10"/> <source>Verify a message to ensure it was signed with a specified Litedoge address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>&amp;Delete</source> <translation>&amp;Trinti</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+65"/> <source>Copy &amp;Label</source> <translation>Kopijuoti ž&amp;ymę</translation> </message> <message> <location line="+2"/> <source>&amp;Edit</source> <translation>&amp;Keisti</translation> </message> <message> <location line="+250"/> <source>Export Address Book Data</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Kableliais išskirtas failas (*.csv)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+145"/> <source>Label</source> <translation>Žymė</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Adresas</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(nėra žymės)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation>Slaptafrazės dialogas</translation> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>Įvesti slaptafrazę</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>Nauja slaptafrazė</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>Pakartokite naują slaptafrazę</translation> </message> <message> <location line="+33"/> <source>Serves to disable the trivial sendmoney when OS account compromised. Provides no real security.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>For staking only</source> <translation type="unfinished"/> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+38"/> <source>Encrypt wallet</source> <translation>Užšifruoti piniginę</translation> </message> <message> <location line="+7"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Ši operacija reikalauja jūsų piniginės slaptafrazės jai atrakinti.</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>Atrakinti piniginę</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Ši operacija reikalauja jūsų piniginės slaptafrazės jai iššifruoti.</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>Iššifruoti piniginę</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>Pakeisti slaptafrazę</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Įveskite seną ir naują piniginės slaptafrazes.</translation> </message> <message> <location line="+45"/> <source>Confirm wallet encryption</source> <translation>Patvirtinkite piniginės užšifravimą</translation> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR COINS&lt;/b&gt;!</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation>Ar tikrai norite šifruoti savo piniginę?</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 type="unfinished"/> </message> <message> <location line="+103"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation>Įspėjimas: įjungtas Caps Lock klavišas!</translation> </message> <message> <location line="-133"/> <location line="+60"/> <source>Wallet encrypted</source> <translation>Piniginė užšifruota</translation> </message> <message> <location line="-140"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;ten or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <source>Litedoge will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your coins from being stolen by malware infecting your computer.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+44"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>Nepavyko užšifruoti piniginę</translation> </message> <message> <location line="-56"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Dėl vidinės klaidos nepavyko užšifruoti piniginę.Piniginė neužšifruota.</translation> </message> <message> <location line="+7"/> <location line="+50"/> <source>The supplied passphrases do not match.</source> <translation>Įvestos slaptafrazės nesutampa.</translation> </message> <message> <location line="-38"/> <source>Wallet unlock failed</source> <translation>Nepavyko atrakinti piniginę</translation> </message> <message> <location line="+1"/> <location line="+12"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>Neteisingai įvestas slaptažodis piniginės iššifravimui.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>Nepavyko iššifruoti piniginės</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation>Piniginės slaptažodis sėkmingai pakeistas.</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+297"/> <source>Sign &amp;message...</source> <translation>Pasirašyti ži&amp;nutę...</translation> </message> <message> <location line="-64"/> <source>Show general overview of wallet</source> <translation>Rodyti piniginės bendrą apžvalgą</translation> </message> <message> <location line="+17"/> <source>&amp;Transactions</source> <translation>&amp;Sandoriai</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>Apžvelgti sandorių istoriją</translation> </message> <message> <location line="+5"/> <source>&amp;Address Book</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit the list of stored addresses and labels</source> <translation type="unfinished"/> </message> <message> <location line="-18"/> <source>Show the list of addresses for receiving payments</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>E&amp;xit</source> <translation>&amp;Išeiti</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>Išjungti programą</translation> </message> <message> <location line="+4"/> <source>Show information about Litedoge</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>Apie &amp;Qt</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>Rodyti informaciją apie Qt</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>&amp;Parinktys...</translation> </message> <message> <location line="+4"/> <source>&amp;Encrypt Wallet...</source> <translation>&amp;Užšifruoti piniginę...</translation> </message> <message> <location line="+2"/> <source>&amp;Backup Wallet...</source> <translation>&amp;Backup piniginę...</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>&amp;Keisti slaptafrazę...</translation> </message> <message> <location line="+9"/> <source>&amp;Export...</source> <translation type="unfinished"/> </message> <message> <location line="-55"/> <source>Send coins to a Litedoge address</source> <translation type="unfinished"/> </message> <message> <location line="+39"/> <source>Modify configuration options for Litedoge</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="-13"/> <source>Encrypt or decrypt wallet</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Backup wallet to another location</source> <translation>Daryti piniginės atsarginę kopiją</translation> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>Pakeisti slaptafrazę naudojamą piniginės užšifravimui</translation> </message> <message> <location line="+10"/> <source>&amp;Debug window</source> <translation>&amp;Derinimo langas</translation> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation>Atverti derinimo ir diagnostikos konsolę</translation> </message> <message> <location line="-5"/> <source>&amp;Verify message...</source> <translation>&amp;Tikrinti žinutę...</translation> </message> <message> <location line="-214"/> <location line="+551"/> <source>Litedoge</source> <translation type="unfinished"/> </message> <message> <location line="-551"/> <source>Wallet</source> <translation>Piniginė</translation> </message> <message> <location line="+193"/> <source>&amp;About Litedoge</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation>&amp;Rodyti / Slėpti</translation> </message> <message> <location line="+8"/> <source>Unlock wallet</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>&amp;Lock Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Lock wallet</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>&amp;File</source> <translation>&amp;Failas</translation> </message> <message> <location line="+8"/> <source>&amp;Settings</source> <translation>&amp;Nustatymai</translation> </message> <message> <location line="+8"/> <source>&amp;Help</source> <translation>&amp;Pagalba</translation> </message> <message> <location line="+17"/> <source>Tabs toolbar</source> <translation>Kortelių įrankinė</translation> </message> <message> <location line="+46"/> <location line="+9"/> <source>[testnet]</source> <translation>[testavimotinklas]</translation> </message> <message> <location line="+0"/> <location line="+58"/> <source>Litedoge client</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+70"/> <source>%n active connection(s) to Litedoge network</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+488"/> <source>Staking.&lt;br&gt;Your weight is %1&lt;br&gt;Network weight is %2&lt;br&gt;Expected time to earn reward is %3</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Not staking because wallet is locked</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because wallet is offline</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because wallet is syncing</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because you don&apos;t have mature coins</source> <translation type="unfinished"/> </message> <message> <location line="-808"/> <source>&amp;Dashboard</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>&amp;Receive</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>&amp;Send</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>&amp;Unlock Wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+273"/> <source>Up to date</source> <translation>Atnaujinta</translation> </message> <message> <location line="+43"/> <source>Catching up...</source> <translation>Vejamasi...</translation> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Sent transaction</source> <translation>Sandoris nusiųstas</translation> </message> <message> <location line="+1"/> <source>Incoming transaction</source> <translation>Ateinantis sandoris</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>Data: %1 Suma: %2 Tipas: %3 Adresas: %4</translation> </message> <message> <location line="+100"/> <location line="+15"/> <source>URI handling</source> <translation type="unfinished"/> </message> <message> <location line="-15"/> <location line="+15"/> <source>URI can not be parsed! This can be caused by an invalid Litedoge address or malformed URI parameters.</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Wallet is &lt;b&gt;not encrypted&lt;/b&gt;</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>Piniginė &lt;b&gt;užšifruota&lt;/b&gt; ir šiuo metu &lt;b&gt;atrakinta&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>Piniginė &lt;b&gt;užšifruota&lt;/b&gt; ir šiuo metu &lt;b&gt;užrakinta&lt;/b&gt;</translation> </message> <message> <location line="+24"/> <source>Backup Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+91"/> <source>%n second(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n minute(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="-429"/> <location line="+433"/> <source>%n hour(s)</source> <translation><numerusform>%n valanda</numerusform><numerusform>%n valandos</numerusform><numerusform>%n valandų</numerusform></translation> </message> <message> <location line="-456"/> <source>Processed %1 blocks of transaction history.</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+27"/> <location line="+433"/> <source>%n day(s)</source> <translation><numerusform>%n diena</numerusform><numerusform>%n dienos</numerusform><numerusform>%n dienų</numerusform></translation> </message> <message numerus="yes"> <location line="-429"/> <location line="+6"/> <source>%n week(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+0"/> <source>%1 and %2</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+0"/> <source>%n year(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+5"/> <source>%1 behind</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Last received block was generated %1 ago.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Error</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="+69"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation type="unfinished"/> </message> <message> <location line="+324"/> <source>Not staking</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoin.cpp" line="+104"/> <source>A fatal error occurred. Litedoge can no longer continue safely and will quit.</source> <translation type="unfinished"/> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+110"/> <source>Network Alert</source> <translation>Tinklo įspėjimas</translation> </message> </context> <context> <name>CoinControlDialog</name> <message> <location filename="../forms/coincontroldialog.ui" line="+14"/> <source>Coin Control</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Quantity:</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Bytes:</source> <translation type="unfinished"/> </message> <message> <location line="+48"/> <source>Amount:</source> <translation>Suma:</translation> </message> <message> <location line="+32"/> <source>Priority:</source> <translation type="unfinished"/> </message> <message> <location line="+48"/> <source>Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Low Output:</source> <translation type="unfinished"/> </message> <message> <location filename="../coincontroldialog.cpp" line="+552"/> <source>no</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/coincontroldialog.ui" line="+51"/> <source>After Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Change:</source> <translation type="unfinished"/> </message> <message> <location line="+69"/> <source>(un)select all</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Tree mode</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>List mode</source> <translation type="unfinished"/> </message> <message> <location line="+45"/> <source>Amount</source> <translation>Suma</translation> </message> <message> <location line="+5"/> <source>Label</source> <translation type="unfinished"/> </message><|fim▁hole|> <message> <location line="+5"/> <source>Address</source> <translation>Adresas</translation> </message> <message> <location line="+5"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+5"/> <source>Confirmations</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Confirmed</source> <translation>Patvirtintas</translation> </message> <message> <location line="+5"/> <source>Priority</source> <translation type="unfinished"/> </message> <message> <location filename="../coincontroldialog.cpp" line="-515"/> <source>Copy address</source> <translation>Kopijuoti adresą</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Kopijuoti žymę</translation> </message> <message> <location line="+1"/> <location line="+26"/> <source>Copy amount</source> <translation>Kopijuoti sumą</translation> </message> <message> <location line="-25"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>Copy quantity</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Copy fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy after fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy bytes</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy priority</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy low output</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy change</source> <translation type="unfinished"/> </message> <message> <location line="+317"/> <source>highest</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>high</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>medium-high</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>medium</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>low-medium</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>low</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>lowest</source> <translation type="unfinished"/> </message> <message> <location line="+155"/> <source>DUST</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>yes</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>This label turns red, if the transaction size is bigger than 10000 bytes. This means a fee of at least %1 per kb is required. Can vary +/- 1 Byte per input.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transactions with higher priority get more likely into a block. This label turns red, if the priority is smaller than &quot;medium&quot;. This means a fee of at least %1 per kb is required.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This label turns red, if any recipient receives an amount smaller than %1. This means a fee of at least %2 is required. Amounts below 0.546 times the minimum relay fee are shown as DUST.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This label turns red, if the change is smaller than %1. This means a fee of at least %2 is required.</source> <translation type="unfinished"/> </message> <message> <location line="+36"/> <location line="+66"/> <source>(no label)</source> <translation>(nėra žymės)</translation> </message> <message> <location line="-9"/> <source>change from %1 (%2)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>(change)</source> <translation type="unfinished"/> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>Keisti adresą</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>Ž&amp;ymė</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>&amp;Adresas</translation> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation type="unfinished"/> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation>Naujas gavimo adresas</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>Naujas siuntimo adresas</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>Keisti gavimo adresą</translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>Keisti siuntimo adresą</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>Įvestas adresas „%1“ jau yra adresų knygelėje.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid Litedoge address.</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>Nepavyko atrakinti piniginės.</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>Naujo rakto generavimas nepavyko.</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+426"/> <location line="+12"/> <source>Litedoge-Qt</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>version</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Usage:</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>UI options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation type="unfinished"/> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>Parinktys</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation>&amp;Pagrindinės</translation> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation>&amp;Mokėti sandorio mokestį</translation> </message> <message> <location line="+31"/> <source>Reserved amount does not participate in staking and is therefore spendable at any time.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Reserve</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Automatically start Litedoge after logging in to the system.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Start Litedoge on system login</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>&amp;Network</source> <translation>&amp;Tinklas</translation> </message> <message> <location line="+6"/> <source>Automatically open the Litedoge client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation>Persiųsti prievadą naudojant &amp;UPnP</translation> </message> <message> <location line="+7"/> <source>Connect to the Litedoge network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation>Tarpinio serverio &amp;IP:</translation> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation>&amp;Prievadas:</translation> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation>Tarpinio serverio preivadas (pvz, 9050)</translation> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation>SOCKS &amp;versija:</translation> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation>Tarpinio serverio SOCKS versija (pvz., 5)</translation> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation>&amp;Langas</translation> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation>Po programos lango sumažinimo rodyti tik programos ikoną.</translation> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>&amp;M sumažinti langą bet ne užduočių juostą</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>Uždarant langą neuždaryti programos. Kai ši parinktis įjungta, programa bus uždaryta tik pasirinkus meniu komandą Baigti.</translation> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation>&amp;Sumažinti uždarant</translation> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation>&amp;Rodymas</translation> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation>Naudotojo sąsajos &amp;kalba:</translation> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting Litedoge.</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation>&amp;Vienetai, kuriais rodyti sumas:</translation> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>Rodomų ir siunčiamų monetų kiekio matavimo vienetai</translation> </message> <message> <location line="+9"/> <source>Whether to show coin control features or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Display coin &amp;control features (experts only!)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Whether to select the coin outputs randomly or with minimal coin age.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Minimize weight consumption (experimental)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Use black visual theme (requires restart)</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation>&amp;Gerai</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>&amp;Atšaukti</translation> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="+53"/> <source>default</source> <translation>numatyta</translation> </message> <message> <location line="+149"/> <location line="+9"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting Litedoge.</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation>Nurodytas tarpinio serverio adresas negalioja.</translation> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>Forma</translation> </message> <message> <location line="+46"/> <location line="+247"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the Litedoge network after a connection is established, but this process has not completed yet.</source> <translation type="unfinished"/> </message> <message> <location line="-173"/> <source>Stake:</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Unconfirmed:</source> <translation type="unfinished"/> </message> <message> <location line="-113"/> <source>Wallet</source> <translation>Piniginė</translation> </message> <message> <location line="+49"/> <source>Spendable:</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Your current spendable balance</source> <translation type="unfinished"/> </message> <message> <location line="+80"/> <source>Immature:</source> <translation>Nepribrendę:</translation> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Total:</source> <translation>Viso:</translation> </message> <message> <location line="+16"/> <source>Your current total balance</source> <translation>Jūsų balansas</translation> </message> <message> <location line="+50"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Naujausi sandoriai&lt;/b&gt;</translation> </message> <message> <location line="-118"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation type="unfinished"/> </message> <message> <location line="-32"/> <source>Total of coins that was staked, and do not yet count toward the current balance</source> <translation type="unfinished"/> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation>nesinchronizuota</translation> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+107"/> <source>Cannot start litedoge: click-to-pay handler</source> <translation type="unfinished"/> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation type="unfinished"/> </message> <message> <location line="+56"/> <source>Amount:</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>Label:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Message:</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation type="unfinished"/> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation type="unfinished"/> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation>Kliento pavadinimas</translation> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <source>N/A</source> <translation>nėra</translation> </message> <message> <location line="-194"/> <source>Client version</source> <translation>Kliento versija</translation> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation>&amp;Informacija</translation> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation>Naudojama OpenSSL versija</translation> </message> <message> <location line="+49"/> <source>Startup time</source> <translation>Paleidimo laikas</translation> </message> <message> <location line="+29"/> <source>Network</source> <translation>Tinklas</translation> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation>Prisijungimų kiekis</translation> </message> <message> <location line="+23"/> <source>On testnet</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Block chain</source> <translation>Blokų grandinė</translation> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation>Dabartinis blokų skaičius</translation> </message> <message> <location line="+197"/> <source>&amp;Network Traffic</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>&amp;Clear</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Totals</source> <translation type="unfinished"/> </message> <message> <location line="+64"/> <source>In:</source> <translation type="unfinished"/> </message> <message> <location line="+80"/> <source>Out:</source> <translation type="unfinished"/> </message> <message> <location line="-383"/> <source>Last block time</source> <translation>Paskutinio bloko laikas</translation> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation>&amp;Atverti</translation> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Show the Litedoge-Qt help message to get a list with possible Litedoge command-line options.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation>&amp;Konsolė</translation> </message> <message> <location line="-237"/> <source>Build date</source> <translation>Kompiliavimo data</translation> </message> <message> <location line="-104"/> <source>Litedoge - Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Litedoge Core</source> <translation type="unfinished"/> </message> <message> <location line="+256"/> <source>Debug log file</source> <translation>Derinimo žurnalo failas</translation> </message> <message> <location line="+7"/> <source>Open the Litedoge debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation type="unfinished"/> </message> <message> <location line="+102"/> <source>Clear console</source> <translation>Išvalyti konsolę</translation> </message> <message> <location filename="../rpcconsole.cpp" line="+325"/> <source>Welcome to the Litedoge RPC console.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation type="unfinished"/> </message> <message> <location line="+127"/> <source>%1 B</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 KB</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 MB</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 GB</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>%1 m</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>%1 h</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 h %2 m</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+181"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation>Siųsti monetas</translation> </message> <message> <location line="+76"/> <source>Coin Control Features</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>Inputs...</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>automatically selected</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Insufficient funds!</source> <translation type="unfinished"/> </message> <message> <location line="+77"/> <source>Quantity:</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <location line="+35"/> <source>0</source> <translation type="unfinished"/> </message> <message> <location line="-19"/> <source>Bytes:</source> <translation type="unfinished"/> </message> <message> <location line="+51"/> <source>Amount:</source> <translation>Suma:</translation> </message> <message> <location line="+22"/> <location line="+86"/> <location line="+86"/> <location line="+32"/> <source>0.00 BC</source> <translation type="unfinished"/> </message> <message> <location line="-191"/> <source>Priority:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>medium</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Low Output:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>no</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>After Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Change</source> <translation type="unfinished"/> </message> <message> <location line="+50"/> <source>custom change address</source> <translation type="unfinished"/> </message> <message> <location line="+106"/> <source>Send to multiple recipients at once</source> <translation>Siųsti keliems gavėjams vienu metu</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation>&amp;A Pridėti gavėją</translation> </message> <message> <location line="+16"/> <source>Remove all transaction fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation>Išvalyti &amp;viską</translation> </message> <message> <location line="+24"/> <source>Balance:</source> <translation>Balansas:</translation> </message> <message> <location line="+16"/> <source>123.456 BC</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation>Patvirtinti siuntimo veiksmą</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>&amp;Siųsti</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-173"/> <source>Enter a Litedoge address (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Copy quantity</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Kopijuoti sumą</translation> </message> <message> <location line="+1"/> <source>Copy fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy after fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy bytes</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy priority</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy low output</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy change</source> <translation type="unfinished"/> </message> <message> <location line="+86"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation>Patvirtinti monetų siuntimą</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source> and </source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The recipient address is not valid, please recheck.</source> <translation>Negaliojantis gavėjo adresas. Patikrinkite.</translation> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>Apmokėjimo suma turi būti didesnė nei 0.</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation>Suma viršija jūsų balansą.</translation> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>Jei pridedame sandorio mokestį %1 bendra suma viršija jūsų balansą.</translation> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation>Rastas adreso dublikatas.</translation> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed!</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="+247"/> <source>WARNING: Invalid Litedoge address</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>(no label)</source> <translation>(nėra žymės)</translation> </message> <message> <location line="+4"/> <source>WARNING: unknown change address</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>Su&amp;ma:</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>Mokėti &amp;gavėjui:</translation> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source> <translation type="unfinished"/> </message> <message> <location line="+60"/> <location filename="../sendcoinsentry.cpp" line="+26"/> <source>Enter a label for this address to add it to your address book</source> <translation>Įveskite žymę šiam adresui kad galėtumėte įtraukti ją į adresų knygelę</translation> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation>Ž&amp;ymė:</translation> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation>Įvesti adresą iš mainų atminties</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a Litedoge address (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source> <translation type="unfinished"/> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+124"/> <source>&amp;Sign Message</source> <translation>&amp;Pasirašyti žinutę</translation> </message> <message> <location line="-118"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+203"/> <source>Choose an address from the address book</source> <translation type="unfinished"/> </message> <message> <location line="-193"/> <location line="+203"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="-193"/> <source>Paste address from clipboard</source> <translation>Įvesti adresą iš mainų atminties</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>Įveskite pranešimą, kurį norite pasirašyti čia</translation> </message> <message> <location line="+24"/> <source>Copy the current signature to the system clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this Litedoge address</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Reset all sign message fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation>Išvalyti &amp;viską</translation> </message> <message> <location line="-87"/> <location line="+70"/> <source>&amp;Verify Message</source> <translation>&amp;Patikrinti žinutę</translation> </message> <message> <location line="-64"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified Litedoge address</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Reset all verify message fields</source> <translation type="unfinished"/> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a Litedoge address (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation>Spragtelėkite &quot;Registruotis žinutę&quot; tam, kad gauti parašą</translation> </message> <message> <location line="+3"/> <source>Enter Litedoge signature</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation>Įvestas adresas negalioja.</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>Prašom patikrinti adresą ir bandyti iš naujo.</translation> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation type="unfinished"/> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation>Piniginės atrakinimas atšauktas.</translation> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation>Žinutės pasirašymas nepavyko.</translation> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation>Žinutė pasirašyta.</translation> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation>Nepavyko iškoduoti parašo.</translation> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation>Prašom patikrinti parašą ir bandyti iš naujo.</translation> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation>Parašas neatitinka žinutės.</translation> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation>Žinutės tikrinimas nepavyko.</translation> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation>Žinutė patikrinta.</translation> </message> </context> <context> <name>TrafficGraphWidget</name> <message> <location filename="../trafficgraphwidget.cpp" line="+75"/> <source>KB/s</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+25"/> <source>Open until %1</source> <translation>Atidaryta iki %1</translation> </message> <message> <location line="+6"/> <source>conflicted</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1/offline</source> <translation>%1/neprisijungęs</translation> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/nepatvirtintas</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 patvirtinimų</translation> </message> <message> <location line="+17"/> <source>Status</source> <translation>Būsena</translation> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation>Šaltinis</translation> </message> <message> <location line="+0"/> <source>Generated</source> <translation>Sugeneruotas</translation> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation>Nuo</translation> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation>Kam</translation> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation>savo adresas</translation> </message> <message> <location line="-2"/> <source>label</source> <translation>žymė</translation> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation>Kreditas</translation> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation>nepriimta</translation> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation>Debitas</translation> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation>Sandorio mokestis</translation> </message> <message> <location line="+16"/> <source>Net amount</source> <translation>Neto suma</translation> </message> <message> <location line="+6"/> <source>Message</source> <translation>Žinutė</translation> </message> <message> <location line="+2"/> <source>Comment</source> <translation>Komentaras</translation> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation>Sandorio ID</translation> </message> <message> <location line="+3"/> <source>Generated coins must mature 510 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Debug information</source> <translation>Derinimo informacija</translation> </message> <message> <location line="+8"/> <source>Transaction</source> <translation>Sandoris</translation> </message> <message> <location line="+5"/> <source>Inputs</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Amount</source> <translation>Suma</translation> </message> <message> <location line="+1"/> <source>true</source> <translation>tiesa</translation> </message> <message> <location line="+0"/> <source>false</source> <translation>netiesa</translation> </message> <message> <location line="-209"/> <source>, has not been successfully broadcast yet</source> <translation>, transliavimas dar nebuvo sėkmingas</translation> </message> <message numerus="yes"> <location line="-36"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+71"/> <source>unknown</source> <translation>nežinomas</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>Sandorio detelės</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>Šis langas sandorio detalų aprašymą</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+231"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>Tipas</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Adresas</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>Suma</translation> </message> <message> <location line="+52"/> <source>Open until %1</source> <translation>Atidaryta iki %1</translation> </message> <message> <location line="+12"/> <source>Confirmed (%1 confirmations)</source> <translation>Patvirtinta (%1 patvirtinimai)</translation> </message> <message numerus="yes"> <location line="-15"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+6"/> <source>Offline</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Unconfirmed</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Confirming (%1 of %2 recommended confirmations)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Conflicted</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Immature (%1 confirmations, will be available after %2)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>Šis blokas negautas nė vienu iš mazgų ir matomai nepriimtas</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>Išgauta bet nepriimta</translation> </message> <message> <location line="+42"/> <source>Received with</source> <translation>Gauta su</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>Gauta iš</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>Siųsta </translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>Mokėjimas sau</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>Išgauta</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>nepasiekiama</translation> </message> <message> <location line="+194"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Sandorio būklė. Užvedus pelės žymeklį ant šios srities matysite patvirtinimų skaičių.</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>Sandorio gavimo data ir laikas</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>Sandorio tipas.</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>Sandorio paskirties adresas</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>Suma pridėta ar išskaičiuota iš balanso</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+54"/> <location line="+17"/> <source>All</source> <translation>Visi</translation> </message> <message> <location line="-16"/> <source>Today</source> <translation>Šiandien</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>Šią savaitę</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>Šį mėnesį</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>Paskutinį mėnesį</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>Šiais metais</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>Intervalas...</translation> </message> <message> <location line="+12"/> <source>Received with</source> <translation>Gauta su</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>Išsiųsta</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>Skirta sau</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>Išgauta</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>Kita</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>Įveskite adresą ar žymę į paiešką</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>Minimali suma</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>Kopijuoti adresą</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Kopijuoti žymę</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Kopijuoti sumą</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>Taisyti žymę</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation>Rodyti sandėrio detales</translation> </message> <message> <location line="+138"/> <source>Export Transaction Data</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Kableliais atskirtų duomenų failas (*.csv)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>Patvirtintas</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>Tipas</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>Žymė</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>Adresas</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>Suma</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>ID</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <source>Range:</source> <translation>Grupė:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>skirta</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+208"/> <source>Sending...</source> <translation type="unfinished"/> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+173"/> <source>Litedoge version</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Usage:</source> <translation>Naudojimas:</translation> </message> <message> <location line="+1"/> <source>Send command to -server or litedoged</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>List commands</source> <translation>Komandų sąrašas</translation> </message> <message> <location line="+1"/> <source>Get help for a command</source> <translation>Suteikti pagalba komandai</translation> </message> <message> <location line="-147"/> <source>Options:</source> <translation>Parinktys:</translation> </message> <message> <location line="+2"/> <source>Specify configuration file (default: litedoge.conf)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Specify pid file (default: litedoged.pid)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify wallet file (within data directory)</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>Nustatyti duomenų aplanką</translation> </message> <message> <location line="-25"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=litedogerpc 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;Litedoge Alert&quot; [email protected] </source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Set database cache size in megabytes (default: 25)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set database disk log size in megabytes (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Listen for connections on &lt;port&gt; (default: 15714 or testnet: 25714)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>Palaikyti ne daugiau &lt;n&gt; jungčių kolegoms (pagal nutylėjimą: 125)</translation> </message> <message> <location line="+3"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Specify your own public address</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Bind to given address. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Always query for peer addresses via DNS lookup (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>Atjungimo dėl netinkamo kolegų elgesio riba (pagal nutylėjimą: 100)</translation> </message> <message> <location line="+1"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>Sekundžių kiekis eikiamas palaikyti ryšį dėl lygiarangių nestabilumo (pagal nutylėjimą: 86.400)</translation> </message> <message> <location line="-37"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+65"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 15715 or testnet: 25715)</source> <translation type="unfinished"/> </message> <message> <location line="-17"/> <source>Accept command line and JSON-RPC commands</source> <translation>Priimti komandinę eilutę ir JSON-RPC komandas</translation> </message> <message> <location line="+1"/> <source>Run in the background as a daemon and accept commands</source> <translation>Dirbti fone kaip šešėlyje ir priimti komandas</translation> </message> <message> <location line="+1"/> <source>Use the test network</source> <translation>Naudoti testavimo tinklą</translation> </message> <message> <location line="-24"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation type="unfinished"/> </message> <message> <location line="-29"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+96"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation>Įspėjimas: -paytxfee yra nustatytas per didelis. Tai sandorio mokestis, kurį turėsite mokėti, jei siųsite sandorį.</translation> </message> <message> <location line="-103"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong Litedoge will not work properly.</source> <translation type="unfinished"/> </message> <message> <location line="+132"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation type="unfinished"/> </message> <message> <location line="-18"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation type="unfinished"/> </message> <message> <location line="-31"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Block creation options:</source> <translation type="unfinished"/> </message> <message> <location line="-69"/> <source>Connect only to the specified node(s)</source> <translation>Prisijungti tik prie nurodyto mazgo</translation> </message> <message> <location line="+4"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation type="unfinished"/> </message> <message> <location line="+101"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation type="unfinished"/> </message> <message> <location line="-91"/> <source>Sync checkpoints policy (default: strict)</source> <translation type="unfinished"/> </message> <message> <location line="+89"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Invalid amount for -reservebalance=&lt;amount&gt;</source> <translation type="unfinished"/> </message> <message> <location line="-88"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation>Maksimalus buferis priėmimo sujungimui &lt;n&gt;*1000 bitų (pagal nutylėjimą: 5000)</translation> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation>Maksimalus buferis siuntimo sujungimui &lt;n&gt;*1000 bitų (pagal nutylėjimą: 1000)</translation> </message> <message> <location line="-17"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Prepend debug output with timestamp</source> <translation type="unfinished"/> </message> <message> <location line="+41"/> <source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source> <translation>SSL opcijos (žr.e Bitcoin Wiki for SSL setup instructions)</translation> </message> <message> <location line="-81"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation type="unfinished"/> </message> <message> <location line="+42"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>Siųsti atsekimo/derinimo info į konsolę vietoj debug.log failo</translation> </message> <message> <location line="+5"/> <source>Send trace/debug info to debugger</source> <translation type="unfinished"/> </message> <message> <location line="+30"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="-35"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation type="unfinished"/> </message> <message> <location line="-43"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation>Nustatyti sujungimo trukmę milisekundėmis (pagal nutylėjimą: 5000)</translation> </message> <message> <location line="+116"/> <source>Unable to sign checkpoint, wrong checkpointkey? </source> <translation type="unfinished"/> </message> <message> <location line="-86"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation>Bandymas naudoti UPnP struktūra klausymosi prievadui (default: 0)</translation> </message> <message> <location line="-1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation>Bandymas naudoti UPnP struktūra klausymosi prievadui (default: 1 when listening)</translation> </message> <message> <location line="-26"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation type="unfinished"/> </message> <message> <location line="+47"/> <source>Username for JSON-RPC connections</source> <translation>Vartotojo vardas JSON-RPC jungimuisi</translation> </message> <message> <location line="+51"/> <source>Verifying database integrity...</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Error: Transaction creation failed!</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>WARNING: syncronized checkpoint violation detected, but skipped!</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation type="unfinished"/> </message> <message> <location line="-54"/> <source>wallet.dat corrupt, salvage failed</source> <translation type="unfinished"/> </message> <message> <location line="-56"/> <source>Password for JSON-RPC connections</source> <translation>Slaptažodis JSON-RPC sujungimams</translation> </message> <message> <location line="-32"/> <source>Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>When creating transactions, ignore inputs with value less than this (default: 0.01)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Output debugging information (default: 0, supplying &lt;category&gt; is optional)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>If &lt;category&gt; is not supplied, output all debugging information.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>&lt;category&gt; can be:</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Enter regression test mode, which uses a special chain in which blocks can be solved instantly. This is intended for regression testing tools and app development.</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>Leisti JSON-RPC tik iš nurodytų IP adresų</translation> </message> <message> <location line="+1"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>Siųsti komandą mazgui dirbančiam &lt;ip&gt; (pagal nutylėjimą: 127.0.0.1)</translation> </message> <message> <location line="+1"/> <source>Wait for RPC server to start</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Require a confirmations for change (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Upgrade wallet to latest format</source> <translation>Atnaujinti piniginę į naujausią formatą</translation> </message> <message> <location line="+1"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>Nustatyti rakto apimties dydį &lt;n&gt; (pagal nutylėjimą: 100)</translation> </message> <message> <location line="+1"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>Ieškoti prarastų piniginės sandorių blokų grandinėje</translation> </message> <message> <location line="+3"/> <source>How thorough the block verification is (0-6, default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Imports blocks from external blk000?.dat file</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>Naudoti OpenSSL (https) jungimuisi JSON-RPC </translation> </message> <message> <location line="+1"/> <source>Server certificate file (default: server.cert)</source> <translation>Serverio sertifikato failas (pagal nutylėjimą: server.cert)</translation> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation>Serverio privatus raktas (pagal nutylėjimą: server.pem)</translation> </message> <message> <location line="+10"/> <source>Initialization sanity check failed. Litedoge is shutting down.</source> <translation type="unfinished"/> </message> <message> <location line="+50"/> <source>Error: Wallet unlocked for staking only, unable to create transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Error: Disk space is low!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.</source> <translation type="unfinished"/> </message> <message> <location line="-174"/> <source>This help message</source> <translation>Pagelbos žinutė</translation> </message> <message> <location line="+104"/> <source>Wallet %s resides outside data directory %s.</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation>Nepavyko susieti šiame kompiuteryje prievado %s (bind returned error %d, %s)</translation> </message> <message> <location line="-133"/> <source>Connect through socks proxy</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>Leisti DNS paiešką sujungimui ir mazgo pridėjimui</translation> </message> <message> <location line="+126"/> <source>Loading addresses...</source> <translation>Užkraunami adresai...</translation> </message> <message> <location line="-12"/> <source>Error loading blkindex.dat</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation> wallet.dat pakrovimo klaida, wallet.dat sugadintas</translation> </message> <message> <location line="+4"/> <source>Error loading wallet.dat: Wallet requires newer version of Litedoge</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Wallet needed to be rewritten: restart Litedoge to complete</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading wallet.dat</source> <translation> wallet.dat pakrovimo klaida</translation> </message> <message> <location line="-16"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation>Neteisingas proxy adresas: &apos;%s&apos;</translation> </message> <message> <location line="-1"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="-23"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Neteisinga suma -paytxfee=&lt;amount&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+60"/> <source>Sending...</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Invalid amount</source> <translation>Neteisinga suma</translation> </message> <message> <location line="+1"/> <source>Insufficient funds</source> <translation>Nepakanka lėšų</translation> </message> <message> <location line="-40"/> <source>Loading block index...</source> <translation>Įkeliamas blokų indeksas...</translation> </message> <message> <location line="-110"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>Pridėti mazgą prie sujungti su and attempt to keep the connection open</translation> </message> <message> <location line="+125"/> <source>Unable to bind to %s on this computer. Litedoge is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="-101"/> <source>Fee per KB to add to transactions you send</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>Minimize weight consumption (experimental) (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>How many blocks to check at startup (default: 500, 0 = all)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Keep at most &lt;n&gt; unconnectable blocks in memory (default: %u)</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Acceptable ciphers (default: TLSv1.2+HIGH:TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: Deprecated argument -debugnet ignored, use -debug=net</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Invalid amount for -mininput=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. Litedoge is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error initializing wallet database environment %s!</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Loading wallet...</source> <translation>Užkraunama piniginė...</translation> </message> <message> <location line="+8"/> <source>Cannot downgrade wallet</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot write default address</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Rescanning...</source> <translation>Peržiūra</translation> </message> <message> <location line="+2"/> <source>Done loading</source> <translation>Įkėlimas baigtas</translation> </message> <message> <location line="-161"/> <source>To use the %s option</source> <translation type="unfinished"/> </message> <message> <location line="+188"/> <source>Error</source> <translation>Klaida</translation> </message> <message> <location line="-18"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation type="unfinished"/> </message> </context> </TS><|fim▁end|>
<|file_name|>gcp_compute_instance_group_facts.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2017 Google # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # ---------------------------------------------------------------------------- # # *** AUTO GENERATED CODE *** AUTO GENERATED CODE *** # # ---------------------------------------------------------------------------- # # This file is automatically generated by Magic Modules and manual # changes will be clobbered when the file is regenerated. # # Please read more about how to change this file at # https://www.github.com/GoogleCloudPlatform/magic-modules # # ---------------------------------------------------------------------------- from __future__ import absolute_import, division, print_function __metaclass__ = type ################################################################################ # Documentation ################################################################################ ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ["preview"], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: gcp_compute_instance_group_facts description: - Gather facts for GCP InstanceGroup short_description: Gather facts for GCP InstanceGroup version_added: 2.7 author: Google Inc. (@googlecloudplatform) requirements: - python >= 2.6 - requests >= 2.18.4 - google-auth >= 1.3.0 options: filters: description: - A list of filter value pairs. Available filters are listed here U(https://cloud.google.com/sdk/gcloud/reference/topic/filters.) - Each additional filter in the list will act be added as an AND condition (filter1 and filter2) . zone: description: - A reference to the zone where the instance group resides. required: true extends_documentation_fragment: gcp ''' EXAMPLES = ''' - name: a instance group facts gcp_compute_instance_group_facts: zone: us-central1-a filters: - name = test_object project: test_project auth_kind: serviceaccount service_account_file: "/tmp/auth.pem" ''' RETURN = ''' items: description: List of items returned: always type: complex contains: creationTimestamp: description: - Creation timestamp in RFC3339 text format. returned: success type: str description: description: - An optional description of this resource. Provide this property when you create the resource. returned: success type: str id: description: - A unique identifier for this instance group. returned: success type: int name: description: - The name of the instance group. - The name must be 1-63 characters long, and comply with RFC1035. returned: success type: str namedPorts: description: - Assigns a name to a port number. - 'For example: {name: "http", port: 80}.' - This allows the system to reference ports by the assigned name instead of a port number. Named ports can also contain multiple ports. - 'For example: [{name: "http", port: 80},{name: "http", port: 8080}] Named ports apply to all instances in this instance group.' returned: success type: complex contains: name: description: - The name for this named port. - The name must be 1-63 characters long, and comply with RFC1035. returned: success type: str port: description: - The port number, which can be a value between 1 and 65535. returned: success type: int network: description: - The network to which all instances in the instance group belong. returned: success type: str region: description: - The region where the instance group is located (for regional resources). returned: success type: str subnetwork: description: - The subnetwork to which all instances in the instance group belong. returned: success type: str zone: description: - A reference to the zone where the instance group resides. returned: success type: str instances: description: - The list of instances associated with this InstanceGroup. - All instances must be created before being added to an InstanceGroup. - All instances not in this list will be removed from the InstanceGroup and will not be deleted. - Only the full identifier of the instance will be returned. returned: success type: list ''' ################################################################################ # Imports ################################################################################ from ansible.module_utils.gcp_utils import navigate_hash, GcpSession, GcpModule, GcpRequest import json ################################################################################ # Main ################################################################################ def main(): module = GcpModule(argument_spec=dict(filters=dict(type='list', elements='str'), zone=dict(required=True, type='str'))) if not module.params['scopes']: module.params['scopes'] = ['https://www.googleapis.com/auth/compute'] items = fetch_list(module, collection(module), query_options(module.params['filters'])) if items.get('items'): items = items.get('items') else: items = [] return_value = {'items': items} module.exit_json(**return_value) def collection(module): return "https://www.googleapis.com/compute/v1/projects/{project}/zones/{zone}/instanceGroups".format(**module.params) def fetch_list(module, link, query): auth = GcpSession(module, 'compute') response = auth.get(link, params={'filter': query}) return return_if_object(module, response) def query_options(filters): if not filters: return '' if len(filters) == 1: return filters[0] else: queries = [] for f in filters: # For multiple queries, all queries should have () if f[0] != '(' and f[-1] != ')': queries.append("(%s)" % ''.join(f)) else: queries.append(f) return ' '.join(queries) def return_if_object(module, response): # If not found, return nothing. if response.status_code == 404: return None # If no content, return nothing. if response.status_code == 204: return None try: module.raise_for_status(response) result = response.json() except getattr(json.decoder, 'JSONDecodeError', ValueError) as inst: module.fail_json(msg="Invalid JSON response with error: %s" % inst) if navigate_hash(result, ['error', 'errors']): module.fail_json(msg=navigate_hash(result, ['error', 'errors'])) return result if __name__ == "__main__":<|fim▁hole|><|fim▁end|>
main()
<|file_name|>filesystem.py<|end_file_name|><|fim▁begin|>import os from segments import Segment, theme from utils import colors, glyphs class CurrentDir(Segment): bg = colors.background(theme.CURRENTDIR_BG) fg = colors.foreground(theme.CURRENTDIR_FG) def init(self, cwd): home = os.path.expanduser('~') self.text = cwd.replace(home, '~') class ReadOnly(Segment): bg = colors.background(theme.READONLY_BG) fg = colors.foreground(theme.READONLY_FG) def init(self, cwd): self.text = ' ' + glyphs.WRITE_ONLY + ' ' if os.access(cwd, os.W_OK): self.active = False <|fim▁hole|>class Venv(Segment): bg = colors.background(theme.VENV_BG) fg = colors.foreground(theme.VENV_FG) def init(self): env = os.getenv('VIRTUAL_ENV') if env is None: self.active = False return env_name = os.path.basename(env) self.text = glyphs.VIRTUAL_ENV + ' ' + env_name<|fim▁end|>
<|file_name|>menus.ts<|end_file_name|><|fim▁begin|>/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import * as nls from 'vs/nls'; import * as os from 'os'; import * as platform from 'vs/base/common/platform'; import * as arrays from 'vs/base/common/arrays'; import * as env from 'vs/code/electron-main/env'; import { ipcMain as ipc, app, shell, dialog, Menu, MenuItem } from 'electron'; import { IWindowsService, WindowsManager, IOpenedPathsList } from 'vs/code/electron-main/windows'; import { IPath, VSCodeWindow } from 'vs/code/electron-main/window'; import { IStorageService } from 'vs/code/electron-main/storage'; import { IUpdateService, State as UpdateState } from 'vs/code/electron-main/update-manager'; import { Keybinding } from 'vs/base/common/keyCodes'; import product from 'vs/platform/product'; import pkg from 'vs/platform/package'; export function generateNewIssueUrl(baseUrl: string, name: string, version: string, commit: string, date: string): string { const osVersion = `${ os.type() } ${ os.arch() } ${ os.release() }`; const queryStringPrefix = baseUrl.indexOf('?') === -1 ? '?' : '&'; const body = encodeURIComponent( `- VSCode Version: ${name} ${version} (${product.commit || 'Commit unknown'}, ${product.date || 'Date unknown'}) - OS Version: ${osVersion} Steps to Reproduce: 1. 2.` ); return `${ baseUrl }${queryStringPrefix}body=${body}`; } interface IResolvedKeybinding { id: string; binding: number; } export class VSCodeMenu { private static lastKnownKeybindingsMapStorageKey = 'lastKnownKeybindings'; private static MAX_RECENT_ENTRIES = 10; private isQuitting: boolean; private appMenuInstalled: boolean; private actionIdKeybindingRequests: string[]; private mapLastKnownKeybindingToActionId: { [id: string]: string; }; private mapResolvedKeybindingToActionId: { [id: string]: string; }; private keybindingsResolved: boolean; constructor( @IStorageService private storageService: IStorageService, @IUpdateService private updateService: IUpdateService, @IWindowsService private windowsService: IWindowsService, @env.IEnvironmentService private envService: env.IEnvironmentService ) { this.actionIdKeybindingRequests = []; this.mapResolvedKeybindingToActionId = Object.create(null); this.mapLastKnownKeybindingToActionId = this.storageService.getItem<{ [id: string]: string; }>(VSCodeMenu.lastKnownKeybindingsMapStorageKey) || Object.create(null); } public ready(): void { this.registerListeners(); this.install(); } private registerListeners(): void { // Keep flag when app quits app.on('will-quit', () => { this.isQuitting = true; }); // Listen to "open" & "close" event from window service this.windowsService.onOpen((paths) => this.onOpen(paths)); this.windowsService.onClose(_ => this.onClose(this.windowsService.getWindowCount())); // Resolve keybindings when any first workbench is loaded this.windowsService.onReady((win) => this.resolveKeybindings(win)); // Listen to resolved keybindings ipc.on('vscode:keybindingsResolved', (event, rawKeybindings) => { let keybindings: IResolvedKeybinding[] = []; try { keybindings = JSON.parse(rawKeybindings); } catch (error) { // Should not happen } // Fill hash map of resolved keybindings<|fim▁hole|> let accelerator = new Keybinding(keybinding.binding)._toElectronAccelerator(); if (accelerator) { this.mapResolvedKeybindingToActionId[keybinding.id] = accelerator; if (this.mapLastKnownKeybindingToActionId[keybinding.id] !== accelerator) { needsMenuUpdate = true; // we only need to update when something changed! } } }); // A keybinding might have been unassigned, so we have to account for that too if (Object.keys(this.mapLastKnownKeybindingToActionId).length !== Object.keys(this.mapResolvedKeybindingToActionId).length) { needsMenuUpdate = true; } if (needsMenuUpdate) { this.storageService.setItem(VSCodeMenu.lastKnownKeybindingsMapStorageKey, this.mapResolvedKeybindingToActionId); // keep to restore instantly after restart this.mapLastKnownKeybindingToActionId = this.mapResolvedKeybindingToActionId; // update our last known map this.updateMenu(); } }); // Listen to update service this.updateService.on('change', () => this.updateMenu()); } private resolveKeybindings(win: VSCodeWindow): void { if (this.keybindingsResolved) { return; // only resolve once } this.keybindingsResolved = true; // Resolve keybindings when workbench window is up if (this.actionIdKeybindingRequests.length) { win.send('vscode:resolveKeybindings', JSON.stringify(this.actionIdKeybindingRequests)); } } private updateMenu(): void { // Due to limitations in Electron, it is not possible to update menu items dynamically. The suggested // workaround from Electron is to set the application menu again. // See also https://github.com/electron/electron/issues/846 // // Run delayed to prevent updating menu while it is open if (!this.isQuitting) { setTimeout(() => { if (!this.isQuitting) { this.install(); } }, 10 /* delay this because there is an issue with updating a menu when it is open */); } } private onOpen(path: IPath): void { this.addToOpenedPathsList(path.filePath || path.workspacePath, !!path.filePath); this.updateMenu(); } private onClose(remainingWindowCount: number): void { if (remainingWindowCount === 0 && platform.isMacintosh) { this.updateMenu(); } } private install(): void { // Menus let menubar = new Menu(); // Mac: Application let macApplicationMenuItem: Electron.MenuItem; if (platform.isMacintosh) { let applicationMenu = new Menu(); macApplicationMenuItem = new MenuItem({ label: this.envService.product.nameShort, submenu: applicationMenu }); this.setMacApplicationMenu(applicationMenu); } // File let fileMenu = new Menu(); let fileMenuItem = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'mFile', comment: ['&& denotes a mnemonic'] }, "&&File")), submenu: fileMenu }); this.setFileMenu(fileMenu); // Edit let editMenu = new Menu(); let editMenuItem = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'mEdit', comment: ['&& denotes a mnemonic'] }, "&&Edit")), submenu: editMenu }); this.setEditMenu(editMenu); // View let viewMenu = new Menu(); let viewMenuItem = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'mView', comment: ['&& denotes a mnemonic'] }, "&&View")), submenu: viewMenu }); this.setViewMenu(viewMenu); // Goto let gotoMenu = new Menu(); let gotoMenuItem = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'mGoto', comment: ['&& denotes a mnemonic'] }, "&&Go")), submenu: gotoMenu }); this.setGotoMenu(gotoMenu); // Mac: Window let macWindowMenuItem: Electron.MenuItem; if (platform.isMacintosh) { let windowMenu = new Menu(); macWindowMenuItem = new MenuItem({ label: mnemonicLabel(nls.localize('mWindow', "Window")), submenu: windowMenu, role: 'window' }); this.setMacWindowMenu(windowMenu); } // Help let helpMenu = new Menu(); let helpMenuItem = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'mHelp', comment: ['&& denotes a mnemonic'] }, "&&Help")), submenu: helpMenu, role: 'help' }); this.setHelpMenu(helpMenu); // Menu Structure if (macApplicationMenuItem) { menubar.append(macApplicationMenuItem); } menubar.append(fileMenuItem); menubar.append(editMenuItem); menubar.append(viewMenuItem); menubar.append(gotoMenuItem); if (macWindowMenuItem) { menubar.append(macWindowMenuItem); } menubar.append(helpMenuItem); Menu.setApplicationMenu(menubar); // Dock Menu if (platform.isMacintosh && !this.appMenuInstalled) { this.appMenuInstalled = true; let dockMenu = new Menu(); dockMenu.append(new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miNewWindow', comment: ['&& denotes a mnemonic'] }, "&&New Window")), click: () => this.windowsService.openNewWindow() })); app.dock.setMenu(dockMenu); } } private addToOpenedPathsList(path?: string, isFile?: boolean): void { if (!path) { return; } let mru = this.getOpenedPathsList(); if (isFile) { mru.files.unshift(path); mru.files = arrays.distinct(mru.files, (f) => platform.isLinux ? f : f.toLowerCase()); } else { mru.folders.unshift(path); mru.folders = arrays.distinct(mru.folders, (f) => platform.isLinux ? f : f.toLowerCase()); } // Make sure its bounded mru.folders = mru.folders.slice(0, VSCodeMenu.MAX_RECENT_ENTRIES); mru.files = mru.files.slice(0, VSCodeMenu.MAX_RECENT_ENTRIES); this.storageService.setItem(WindowsManager.openedPathsListStorageKey, mru); } private removeFromOpenedPathsList(path: string): void { let mru = this.getOpenedPathsList(); let index = mru.files.indexOf(path); if (index >= 0) { mru.files.splice(index, 1); } index = mru.folders.indexOf(path); if (index >= 0) { mru.folders.splice(index, 1); } this.storageService.setItem(WindowsManager.openedPathsListStorageKey, mru); } private clearOpenedPathsList(): void { this.storageService.setItem(WindowsManager.openedPathsListStorageKey, { folders: [], files: [] }); app.clearRecentDocuments(); this.updateMenu(); } private getOpenedPathsList(): IOpenedPathsList { let mru = this.storageService.getItem<IOpenedPathsList>(WindowsManager.openedPathsListStorageKey); if (!mru) { mru = { folders: [], files: [] }; } return mru; } private setMacApplicationMenu(macApplicationMenu: Electron.Menu): void { let about = new MenuItem({ label: nls.localize('mAbout', "About {0}", this.envService.product.nameLong), role: 'about' }); let checkForUpdates = this.getUpdateMenuItems(); let preferences = this.getPreferencesMenu(); let hide = new MenuItem({ label: nls.localize('mHide', "Hide {0}", this.envService.product.nameLong), role: 'hide', accelerator: 'Command+H' }); let hideOthers = new MenuItem({ label: nls.localize('mHideOthers', "Hide Others"), role: 'hideothers', accelerator: 'Command+Alt+H' }); let showAll = new MenuItem({ label: nls.localize('mShowAll', "Show All"), role: 'unhide' }); let quit = new MenuItem({ label: nls.localize('miQuit', "Quit {0}", this.envService.product.nameLong), click: () => this.quit(), accelerator: 'Command+Q' }); let actions = [about]; actions.push(...checkForUpdates); actions.push(...[ __separator__(), preferences, __separator__(), hide, hideOthers, showAll, __separator__(), quit ]); actions.forEach(i => macApplicationMenu.append(i)); } private setFileMenu(fileMenu: Electron.Menu): void { let hasNoWindows = (this.windowsService.getWindowCount() === 0); let newFile: Electron.MenuItem; if (hasNoWindows) { newFile = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miNewFile', comment: ['&& denotes a mnemonic'] }, "&&New File")), accelerator: this.getAccelerator('workbench.action.files.newUntitledFile'), click: () => this.windowsService.openNewWindow() }); } else { newFile = this.createMenuItem(nls.localize({ key: 'miNewFile', comment: ['&& denotes a mnemonic'] }, "&&New File"), 'workbench.action.files.newUntitledFile'); } let open = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miOpen', comment: ['&& denotes a mnemonic'] }, "&&Open...")), accelerator: this.getAccelerator('workbench.action.files.openFileFolder'), click: () => this.windowsService.openFileFolderPicker() }); let openFolder = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miOpenFolder', comment: ['&& denotes a mnemonic'] }, "Open &&Folder...")), accelerator: this.getAccelerator('workbench.action.files.openFolder'), click: () => this.windowsService.openFolderPicker() }); let openFile: Electron.MenuItem; if (hasNoWindows) { openFile = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miOpenFile', comment: ['&& denotes a mnemonic'] }, "&&Open File...")), accelerator: this.getAccelerator('workbench.action.files.openFile'), click: () => this.windowsService.openFilePicker() }); } else { openFile = this.createMenuItem(nls.localize({ key: 'miOpenFile', comment: ['&& denotes a mnemonic'] }, "&&Open File..."), 'workbench.action.files.openFile'); } let openRecentMenu = new Menu(); this.setOpenRecentMenu(openRecentMenu); let openRecent = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miOpenRecent', comment: ['&& denotes a mnemonic'] }, "Open &&Recent")), submenu: openRecentMenu, enabled: openRecentMenu.items.length > 0 }); let saveFile = this.createMenuItem(nls.localize({ key: 'miSave', comment: ['&& denotes a mnemonic'] }, "&&Save"), 'workbench.action.files.save', this.windowsService.getWindowCount() > 0); let saveFileAs = this.createMenuItem(nls.localize({ key: 'miSaveAs', comment: ['&& denotes a mnemonic'] }, "Save &&As..."), 'workbench.action.files.saveAs', this.windowsService.getWindowCount() > 0); let saveAllFiles = this.createMenuItem(nls.localize({ key: 'miSaveAll', comment: ['&& denotes a mnemonic'] }, "Save A&&ll"), 'workbench.action.files.saveAll', this.windowsService.getWindowCount() > 0); let preferences = this.getPreferencesMenu(); let newWindow = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miNewWindow', comment: ['&& denotes a mnemonic'] }, "&&New Window")), accelerator: this.getAccelerator('workbench.action.newWindow'), click: () => this.windowsService.openNewWindow() }); let revertFile = this.createMenuItem(nls.localize({ key: 'miRevert', comment: ['&& denotes a mnemonic'] }, "Revert F&&ile"), 'workbench.action.files.revert', this.windowsService.getWindowCount() > 0); let closeWindow = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miCloseWindow', comment: ['&& denotes a mnemonic'] }, "Close &&Window")), accelerator: this.getAccelerator('workbench.action.closeWindow'), click: () => this.windowsService.getLastActiveWindow().win.close(), enabled: this.windowsService.getWindowCount() > 0 }); let closeFolder = this.createMenuItem(nls.localize({ key: 'miCloseFolder', comment: ['&& denotes a mnemonic'] }, "Close &&Folder"), 'workbench.action.closeFolder'); let closeEditor = this.createMenuItem(nls.localize({ key: 'miCloseEditor', comment: ['&& denotes a mnemonic'] }, "Close &&Editor"), 'workbench.action.closeActiveEditor'); let exit = this.createMenuItem(nls.localize({ key: 'miExit', comment: ['&& denotes a mnemonic'] }, "E&&xit"), () => this.quit()); arrays.coalesce([ newFile, newWindow, __separator__(), platform.isMacintosh ? open : null, !platform.isMacintosh ? openFile : null, !platform.isMacintosh ? openFolder : null, openRecent, __separator__(), saveFile, saveFileAs, saveAllFiles, __separator__(), !platform.isMacintosh ? preferences : null, !platform.isMacintosh ? __separator__() : null, revertFile, closeEditor, closeFolder, !platform.isMacintosh ? closeWindow : null, !platform.isMacintosh ? __separator__() : null, !platform.isMacintosh ? exit : null ]).forEach((item) => fileMenu.append(item)); } private getPreferencesMenu(): Electron.MenuItem { let userSettings = this.createMenuItem(nls.localize({ key: 'miOpenSettings', comment: ['&& denotes a mnemonic'] }, "&&User Settings"), 'workbench.action.openGlobalSettings'); let workspaceSettings = this.createMenuItem(nls.localize({ key: 'miOpenWorkspaceSettings', comment: ['&& denotes a mnemonic'] }, "&&Workspace Settings"), 'workbench.action.openWorkspaceSettings'); let kebindingSettings = this.createMenuItem(nls.localize({ key: 'miOpenKeymap', comment: ['&& denotes a mnemonic'] }, "&&Keyboard Shortcuts"), 'workbench.action.openGlobalKeybindings'); let snippetsSettings = this.createMenuItem(nls.localize({ key: 'miOpenSnippets', comment: ['&& denotes a mnemonic'] }, "User &&Snippets"), 'workbench.action.openSnippets'); let themeSelection = this.createMenuItem(nls.localize({ key: 'miSelectTheme', comment: ['&& denotes a mnemonic'] }, "&&Color Theme"), 'workbench.action.selectTheme'); let preferencesMenu = new Menu(); preferencesMenu.append(userSettings); preferencesMenu.append(workspaceSettings); preferencesMenu.append(__separator__()); preferencesMenu.append(kebindingSettings); preferencesMenu.append(__separator__()); preferencesMenu.append(snippetsSettings); preferencesMenu.append(__separator__()); preferencesMenu.append(themeSelection); return new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miPreferences', comment: ['&& denotes a mnemonic'] }, "&&Preferences")), submenu: preferencesMenu }); } private quit(): void { // If the user selected to exit from an extension development host window, do not quit, but just // close the window unless this is the last window that is opened. let vscodeWindow = this.windowsService.getFocusedWindow(); if (vscodeWindow && vscodeWindow.isPluginDevelopmentHost && this.windowsService.getWindowCount() > 1) { vscodeWindow.win.close(); } // Otherwise: normal quit else { setTimeout(() => { this.isQuitting = true; app.quit(); }, 10 /* delay this because there is an issue with quitting while the menu is open */); } } private setOpenRecentMenu(openRecentMenu: Electron.Menu): void { openRecentMenu.append(this.createMenuItem(nls.localize({ key: 'miReopenClosedEditor', comment: ['&& denotes a mnemonic'] }, "&&Reopen Closed Editor"), 'workbench.action.reopenClosedEditor')); let recentList = this.getOpenedPathsList(); // Folders if (recentList.folders.length > 0) { openRecentMenu.append(__separator__()); recentList.folders.forEach((folder, index) => { if (index < VSCodeMenu.MAX_RECENT_ENTRIES) { openRecentMenu.append(this.createOpenRecentMenuItem(folder)); } }); } // Files let files = recentList.files; if (files.length > 0) { openRecentMenu.append(__separator__()); files.forEach((file, index) => { if (index < VSCodeMenu.MAX_RECENT_ENTRIES) { openRecentMenu.append(this.createOpenRecentMenuItem(file)); } }); } if (recentList.folders.length || files.length) { openRecentMenu.append(__separator__()); openRecentMenu.append(new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miClearItems', comment: ['&& denotes a mnemonic'] }, "&&Clear Items")), click: () => this.clearOpenedPathsList() })); } } private createOpenRecentMenuItem(path: string): Electron.MenuItem { return new MenuItem({ label: path, click: () => { let success = !!this.windowsService.open({ cli: this.envService.cliArgs, pathsToOpen: [path] }); if (!success) { this.removeFromOpenedPathsList(path); this.updateMenu(); } } }); } private createRoleMenuItem(label: string, actionId: string, role: Electron.MenuItemRole): Electron.MenuItem { let options: Electron.MenuItemOptions = { label: mnemonicLabel(label), accelerator: this.getAccelerator(actionId), role, enabled: true }; return new MenuItem(options); } private setEditMenu(winLinuxEditMenu: Electron.Menu): void { let undo: Electron.MenuItem; let redo: Electron.MenuItem; let cut: Electron.MenuItem; let copy: Electron.MenuItem; let paste: Electron.MenuItem; let selectAll: Electron.MenuItem; if (platform.isMacintosh) { undo = this.createDevToolsAwareMenuItem(nls.localize({ key: 'miUndo', comment: ['&& denotes a mnemonic'] }, "&&Undo"), 'undo', (devTools) => devTools.undo()); redo = this.createDevToolsAwareMenuItem(nls.localize({ key: 'miRedo', comment: ['&& denotes a mnemonic'] }, "&&Redo"), 'redo', (devTools) => devTools.redo()); cut = this.createRoleMenuItem(nls.localize({ key: 'miCut', comment: ['&& denotes a mnemonic'] }, "&&Cut"), 'editor.action.clipboardCutAction', 'cut'); copy = this.createRoleMenuItem(nls.localize({ key: 'miCopy', comment: ['&& denotes a mnemonic'] }, "C&&opy"), 'editor.action.clipboardCopyAction', 'copy'); paste = this.createRoleMenuItem(nls.localize({ key: 'miPaste', comment: ['&& denotes a mnemonic'] }, "&&Paste"), 'editor.action.clipboardPasteAction', 'paste'); selectAll = this.createDevToolsAwareMenuItem(nls.localize({ key: 'miSelectAll', comment: ['&& denotes a mnemonic'] }, "&&Select All"), 'editor.action.selectAll', (devTools) => devTools.selectAll()); } else { undo = this.createMenuItem(nls.localize({ key: 'miUndo', comment: ['&& denotes a mnemonic'] }, "&&Undo"), 'undo'); redo = this.createMenuItem(nls.localize({ key: 'miRedo', comment: ['&& denotes a mnemonic'] }, "&&Redo"), 'redo'); cut = this.createMenuItem(nls.localize({ key: 'miCut', comment: ['&& denotes a mnemonic'] }, "&&Cut"), 'editor.action.clipboardCutAction'); copy = this.createMenuItem(nls.localize({ key: 'miCopy', comment: ['&& denotes a mnemonic'] }, "C&&opy"), 'editor.action.clipboardCopyAction'); paste = this.createMenuItem(nls.localize({ key: 'miPaste', comment: ['&& denotes a mnemonic'] }, "&&Paste"), 'editor.action.clipboardPasteAction'); selectAll = this.createMenuItem(nls.localize({ key: 'miSelectAll', comment: ['&& denotes a mnemonic'] }, "&&Select All"), 'editor.action.selectAll'); } let find = this.createMenuItem(nls.localize({ key: 'miFind', comment: ['&& denotes a mnemonic'] }, "&&Find"), 'actions.find'); let replace = this.createMenuItem(nls.localize({ key: 'miReplace', comment: ['&& denotes a mnemonic'] }, "&&Replace"), 'editor.action.startFindReplaceAction'); let findInFiles = this.createMenuItem(nls.localize({ key: 'miFindInFiles', comment: ['&& denotes a mnemonic'] }, "Find &&in Files"), 'workbench.view.search'); let replaceInFiles = this.createMenuItem(nls.localize({ key: 'miReplaceInFiles', comment: ['&& denotes a mnemonic'] }, "Replace &&in Files"), 'workbench.action.replaceInFiles'); [ undo, redo, __separator__(), cut, copy, paste, selectAll, __separator__(), find, replace, __separator__(), findInFiles, replaceInFiles ].forEach(item => winLinuxEditMenu.append(item)); } private setViewMenu(viewMenu: Electron.Menu): void { let explorer = this.createMenuItem(nls.localize({ key: 'miViewExplorer', comment: ['&& denotes a mnemonic'] }, "&&Explorer"), 'workbench.view.explorer'); let search = this.createMenuItem(nls.localize({ key: 'miViewSearch', comment: ['&& denotes a mnemonic'] }, "&&Search"), 'workbench.view.search'); let git = this.createMenuItem(nls.localize({ key: 'miViewGit', comment: ['&& denotes a mnemonic'] }, "&&Git"), 'workbench.view.git'); let debug = this.createMenuItem(nls.localize({ key: 'miViewDebug', comment: ['&& denotes a mnemonic'] }, "&&Debug"), 'workbench.view.debug'); let extensions = this.createMenuItem(nls.localize({ key: 'miViewExtensions', comment: ['&& denotes a mnemonic'] }, "E&&xtensions"), 'workbench.view.extensions'); let output = this.createMenuItem(nls.localize({ key: 'miToggleOutput', comment: ['&& denotes a mnemonic'] }, "&&Output"), 'workbench.action.output.toggleOutput'); let debugConsole = this.createMenuItem(nls.localize({ key: 'miToggleDebugConsole', comment: ['&& denotes a mnemonic'] }, "De&&bug Console"), 'workbench.debug.action.toggleRepl'); let integratedTerminal = this.createMenuItem(nls.localize({ key: 'miToggleIntegratedTerminal', comment: ['&& denotes a mnemonic'] }, "&&Integrated Terminal"), 'workbench.action.terminal.toggleTerminal'); let problems = this.createMenuItem(nls.localize({ key: 'miMarker', comment: ['&& denotes a mnemonic'] }, "&&Problems"), 'workbench.actions.view.problems'); let commands = this.createMenuItem(nls.localize({ key: 'miCommandPalette', comment: ['&& denotes a mnemonic'] }, "&&Command Palette..."), 'workbench.action.showCommands'); let fullscreen = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miToggleFullScreen', comment: ['&& denotes a mnemonic'] }, "Toggle &&Full Screen")), accelerator: this.getAccelerator('workbench.action.toggleFullScreen'), click: () => this.windowsService.getLastActiveWindow().toggleFullScreen(), enabled: this.windowsService.getWindowCount() > 0 }); let toggleMenuBar = this.createMenuItem(nls.localize({ key: 'miToggleMenuBar', comment: ['&& denotes a mnemonic'] }, "Toggle Menu &&Bar"), 'workbench.action.toggleMenuBar'); let splitEditor = this.createMenuItem(nls.localize({ key: 'miSplitEditor', comment: ['&& denotes a mnemonic'] }, "Split &&Editor"), 'workbench.action.splitEditor'); let toggleSidebar = this.createMenuItem(nls.localize({ key: 'miToggleSidebar', comment: ['&& denotes a mnemonic'] }, "&&Toggle Side Bar"), 'workbench.action.toggleSidebarVisibility'); let moveSidebar = this.createMenuItem(nls.localize({ key: 'miMoveSidebar', comment: ['&& denotes a mnemonic'] }, "&&Move Side Bar"), 'workbench.action.toggleSidebarPosition'); let togglePanel = this.createMenuItem(nls.localize({ key: 'miTogglePanel', comment: ['&& denotes a mnemonic'] }, "Toggle &&Panel"), 'workbench.action.togglePanel'); let toggleStatusbar = this.createMenuItem(nls.localize({ key: 'miToggleStatusbar', comment: ['&& denotes a mnemonic'] }, "&&Toggle Status Bar"), 'workbench.action.toggleStatusbarVisibility'); const toggleWordWrap = this.createMenuItem(nls.localize({ key: 'miToggleWordWrap', comment: ['&& denotes a mnemonic'] }, "Toggle &&Word Wrap"), 'editor.action.toggleWordWrap'); const toggleRenderWhitespace = this.createMenuItem(nls.localize({ key: 'miToggleRenderWhitespace', comment: ['&& denotes a mnemonic'] }, "Toggle &&Render Whitespace"), 'editor.action.toggleRenderWhitespace'); const toggleRenderControlCharacters = this.createMenuItem(nls.localize({ key: 'miToggleRenderControlCharacters', comment: ['&& denotes a mnemonic'] }, "Toggle &&Control Characters"), 'editor.action.toggleRenderControlCharacter'); let zoomIn = this.createMenuItem(nls.localize({ key: 'miZoomIn', comment: ['&& denotes a mnemonic'] }, "&&Zoom In"), 'workbench.action.zoomIn'); let zoomOut = this.createMenuItem(nls.localize({ key: 'miZoomOut', comment: ['&& denotes a mnemonic'] }, "Zoom O&&ut"), 'workbench.action.zoomOut'); let resetZoom = this.createMenuItem(nls.localize({ key: 'miZoomReset', comment: ['&& denotes a mnemonic'] }, "&&Reset Zoom"), 'workbench.action.zoomReset'); arrays.coalesce([ explorer, search, git, debug, extensions, __separator__(), output, problems, debugConsole, integratedTerminal, __separator__(), commands, __separator__(), fullscreen, platform.isWindows || platform.isLinux ? toggleMenuBar : void 0, __separator__(), splitEditor, moveSidebar, toggleSidebar, togglePanel, toggleStatusbar, __separator__(), toggleWordWrap, toggleRenderWhitespace, toggleRenderControlCharacters, __separator__(), zoomIn, zoomOut, resetZoom ]).forEach((item) => viewMenu.append(item)); } private setGotoMenu(gotoMenu: Electron.Menu): void { let back = this.createMenuItem(nls.localize({ key: 'miBack', comment: ['&& denotes a mnemonic'] }, "&&Back"), 'workbench.action.navigateBack'); let forward = this.createMenuItem(nls.localize({ key: 'miForward', comment: ['&& denotes a mnemonic'] }, "&&Forward"), 'workbench.action.navigateForward'); let switchEditorMenu = new Menu(); let nextEditor = this.createMenuItem(nls.localize({ key: 'miNextEditor', comment: ['&& denotes a mnemonic'] }, "&&Next Editor"), 'workbench.action.nextEditor'); let previousEditor = this.createMenuItem(nls.localize({ key: 'miPreviousEditor', comment: ['&& denotes a mnemonic'] }, "&&Previous Editor"), 'workbench.action.previousEditor'); let nextEditorInGroup = this.createMenuItem(nls.localize({ key: 'miNextEditorInGroup', comment: ['&& denotes a mnemonic'] }, "&&Next Used Editor in Group"), 'workbench.action.openNextRecentlyUsedEditorInGroup'); let previousEditorInGroup = this.createMenuItem(nls.localize({ key: 'miPreviousEditorInGroup', comment: ['&& denotes a mnemonic'] }, "&&Previous Used Editor in Group"), 'workbench.action.openPreviousRecentlyUsedEditorInGroup'); [ nextEditor, previousEditor, __separator__(), nextEditorInGroup, previousEditorInGroup ].forEach(item => switchEditorMenu.append(item)); let switchEditor = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miSwitchEditor', comment: ['&& denotes a mnemonic'] }, "Switch &&Editor")), submenu: switchEditorMenu, enabled: true }); let switchGroupMenu = new Menu(); let focusFirstGroup = this.createMenuItem(nls.localize({ key: 'miFocusFirstGroup', comment: ['&& denotes a mnemonic'] }, "&&Left Group"), 'workbench.action.focusFirstEditorGroup'); let focusSecondGroup = this.createMenuItem(nls.localize({ key: 'miFocusSecondGroup', comment: ['&& denotes a mnemonic'] }, "&&Side Group"), 'workbench.action.focusSecondEditorGroup'); let focusThirdGroup = this.createMenuItem(nls.localize({ key: 'miFocusThirdGroup', comment: ['&& denotes a mnemonic'] }, "&&Right Group"), 'workbench.action.focusThirdEditorGroup'); let nextGroup = this.createMenuItem(nls.localize({ key: 'miNextGroup', comment: ['&& denotes a mnemonic'] }, "&&Next Group"), 'workbench.action.focusNextGroup'); let previousGroup = this.createMenuItem(nls.localize({ key: 'miPreviousGroup', comment: ['&& denotes a mnemonic'] }, "&&Previous Group"), 'workbench.action.focusPreviousGroup'); [ focusFirstGroup, focusSecondGroup, focusThirdGroup, __separator__(), nextGroup, previousGroup ].forEach(item => switchGroupMenu.append(item)); let switchGroup = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miSwitchGroup', comment: ['&& denotes a mnemonic'] }, "Switch &&Group")), submenu: switchGroupMenu, enabled: true }); let gotoFile = this.createMenuItem(nls.localize({ key: 'miGotoFile', comment: ['&& denotes a mnemonic'] }, "Go to &&File..."), 'workbench.action.quickOpen'); let gotoSymbol = this.createMenuItem(nls.localize({ key: 'miGotoSymbol', comment: ['&& denotes a mnemonic'] }, "Go to &&Symbol..."), 'workbench.action.gotoSymbol'); let gotoDefinition = this.createMenuItem(nls.localize({ key: 'miGotoDefinition', comment: ['&& denotes a mnemonic'] }, "Go to &&Definition"), 'editor.action.goToDeclaration'); let gotoLine = this.createMenuItem(nls.localize({ key: 'miGotoLine', comment: ['&& denotes a mnemonic'] }, "Go to &&Line..."), 'workbench.action.gotoLine'); [ back, forward, __separator__(), switchEditor, switchGroup, __separator__(), gotoFile, gotoSymbol, gotoDefinition, gotoLine ].forEach(item => gotoMenu.append(item)); } private setMacWindowMenu(macWindowMenu: Electron.Menu): void { let minimize = new MenuItem({ label: nls.localize('mMinimize', "Minimize"), role: 'minimize', accelerator: 'Command+M', enabled: this.windowsService.getWindowCount() > 0 }); let close = new MenuItem({ label: nls.localize('mClose', "Close"), role: 'close', accelerator: 'Command+W', enabled: this.windowsService.getWindowCount() > 0 }); let bringAllToFront = new MenuItem({ label: nls.localize('mBringToFront', "Bring All to Front"), role: 'front', enabled: this.windowsService.getWindowCount() > 0 }); [ minimize, close, __separator__(), bringAllToFront ].forEach(item => macWindowMenu.append(item)); } private toggleDevTools(): void { let w = this.windowsService.getFocusedWindow(); if (w && w.win) { w.win.webContents.toggleDevTools(); } } private setHelpMenu(helpMenu: Electron.Menu): void { let toggleDevToolsItem = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miToggleDevTools', comment: ['&& denotes a mnemonic'] }, "&&Toggle Developer Tools")), accelerator: this.getAccelerator('workbench.action.toggleDevTools'), click: () => this.toggleDevTools(), enabled: (this.windowsService.getWindowCount() > 0) }); const issueUrl = generateNewIssueUrl(product.reportIssueUrl, pkg.name, pkg.version, product.commit, product.date); arrays.coalesce([ this.envService.product.documentationUrl ? new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miDocumentation', comment: ['&& denotes a mnemonic'] }, "&&Documentation")), click: () => this.openUrl(this.envService.product.documentationUrl, 'openDocumentationUrl') }) : null, this.envService.product.releaseNotesUrl ? new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miReleaseNotes', comment: ['&& denotes a mnemonic'] }, "&&Release Notes")), click: () => this.openUrl(this.envService.product.releaseNotesUrl, 'openReleaseNotesUrl') }) : null, (this.envService.product.documentationUrl || this.envService.product.releaseNotesUrl) ? __separator__() : null, this.envService.product.twitterUrl ? new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miTwitter', comment: ['&& denotes a mnemonic'] }, "&&Join us on Twitter")), click: () => this.openUrl(this.envService.product.twitterUrl, 'openTwitterUrl') }) : null, this.envService.product.requestFeatureUrl ? new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miUserVoice', comment: ['&& denotes a mnemonic'] }, "&&Request Features")), click: () => this.openUrl(this.envService.product.requestFeatureUrl, 'openUserVoiceUrl') }) : null, this.envService.product.reportIssueUrl ? new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miReportIssues', comment: ['&& denotes a mnemonic'] }, "Report &&Issues")), click: () => this.openUrl(issueUrl, 'openReportIssues') }) : null, (this.envService.product.twitterUrl || this.envService.product.requestFeatureUrl || this.envService.product.reportIssueUrl) ? __separator__() : null, this.envService.product.licenseUrl ? new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miLicense', comment: ['&& denotes a mnemonic'] }, "&&View License")), click: () => { if (platform.language) { let queryArgChar = this.envService.product.licenseUrl.indexOf('?') > 0 ? '&' : '?'; this.openUrl(`${this.envService.product.licenseUrl}${queryArgChar}lang=${platform.language}`, 'openLicenseUrl'); } else { this.openUrl(this.envService.product.licenseUrl, 'openLicenseUrl'); } } }) : null, this.envService.product.privacyStatementUrl ? new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miPrivacyStatement', comment: ['&& denotes a mnemonic'] }, "&&Privacy Statement")), click: () => { if (platform.language) { let queryArgChar = this.envService.product.licenseUrl.indexOf('?') > 0 ? '&' : '?'; this.openUrl(`${this.envService.product.privacyStatementUrl}${queryArgChar}lang=${platform.language}`, 'openPrivacyStatement'); } else { this.openUrl(this.envService.product.privacyStatementUrl, 'openPrivacyStatement'); } } }) : null, (this.envService.product.licenseUrl || this.envService.product.privacyStatementUrl) ? __separator__() : null, toggleDevToolsItem, ]).forEach((item) => helpMenu.append(item)); if (!platform.isMacintosh) { const updateMenuItems = this.getUpdateMenuItems(); if (updateMenuItems.length) { helpMenu.append(__separator__()); updateMenuItems.forEach(i => helpMenu.append(i)); } helpMenu.append(__separator__()); helpMenu.append(new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miAbout', comment: ['&& denotes a mnemonic'] }, "&&About")), click: () => this.openAboutDialog() })); } } private getUpdateMenuItems(): Electron.MenuItem[] { switch (this.updateService.state) { case UpdateState.Uninitialized: return []; case UpdateState.UpdateDownloaded: let update = this.updateService.availableUpdate; return [new MenuItem({ label: nls.localize('miRestartToUpdate', "Restart To Update..."), click: () => { this.reportMenuActionTelemetry('RestartToUpdate'); update.quitAndUpdate(); } })]; case UpdateState.CheckingForUpdate: return [new MenuItem({ label: nls.localize('miCheckingForUpdates', "Checking For Updates..."), enabled: false })]; case UpdateState.UpdateAvailable: if (platform.isLinux) { const update = this.updateService.availableUpdate; return [new MenuItem({ label: nls.localize('miDownloadUpdate', "Download Available Update"), click: () => { update.quitAndUpdate(); } })]; } let updateAvailableLabel = platform.isWindows ? nls.localize('miDownloadingUpdate', "Downloading Update...") : nls.localize('miInstallingUpdate', "Installing Update..."); return [new MenuItem({ label: updateAvailableLabel, enabled: false })]; default: let result = [new MenuItem({ label: nls.localize('miCheckForUpdates', "Check For Updates..."), click: () => setTimeout(() => { this.reportMenuActionTelemetry('CheckForUpdate'); this.updateService.checkForUpdates(true); }, 0) })]; return result; } } private createMenuItem(label: string, actionId: string, enabled?: boolean): Electron.MenuItem; private createMenuItem(label: string, click: () => void, enabled?: boolean): Electron.MenuItem; private createMenuItem(arg1: string, arg2: any, arg3?: boolean): Electron.MenuItem { let label = mnemonicLabel(arg1); let click: () => void = (typeof arg2 === 'function') ? arg2 : () => this.windowsService.sendToFocused('vscode:runAction', arg2); let enabled = typeof arg3 === 'boolean' ? arg3 : this.windowsService.getWindowCount() > 0; let actionId: string; if (typeof arg2 === 'string') { actionId = arg2; } let options: Electron.MenuItemOptions = { label: label, accelerator: this.getAccelerator(actionId), click: click, enabled: enabled }; return new MenuItem(options); } private createDevToolsAwareMenuItem(label: string, actionId: string, devToolsFocusedFn: (contents: Electron.WebContents) => void): Electron.MenuItem { return new MenuItem({ label: mnemonicLabel(label), accelerator: this.getAccelerator(actionId), enabled: this.windowsService.getWindowCount() > 0, click: () => { let windowInFocus = this.windowsService.getFocusedWindow(); if (!windowInFocus) { return; } if (windowInFocus.win.webContents.isDevToolsFocused()) { devToolsFocusedFn(windowInFocus.win.webContents.devToolsWebContents); } else { this.windowsService.sendToFocused('vscode:runAction', actionId); } } }); } private getAccelerator(actionId: string): string { if (actionId) { let resolvedKeybinding = this.mapResolvedKeybindingToActionId[actionId]; if (resolvedKeybinding) { return resolvedKeybinding; // keybinding is fully resolved } if (!this.keybindingsResolved) { this.actionIdKeybindingRequests.push(actionId); // keybinding needs to be resolved } let lastKnownKeybinding = this.mapLastKnownKeybindingToActionId[actionId]; return lastKnownKeybinding; // return the last known keybining (chance of mismatch is very low unless it changed) } return void (0); } private openAboutDialog(): void { let lastActiveWindow = this.windowsService.getFocusedWindow() || this.windowsService.getLastActiveWindow(); dialog.showMessageBox(lastActiveWindow && lastActiveWindow.win, { title: this.envService.product.nameLong, type: 'info', message: this.envService.product.nameLong, detail: nls.localize('aboutDetail', "\nVersion {0}\nCommit {1}\nDate {2}\nShell {3}\nRenderer {4}\nNode {5}", app.getVersion(), this.envService.product.commit || 'Unknown', this.envService.product.date || 'Unknown', process.versions['electron'], process.versions['chrome'], process.versions['node'] ), buttons: [nls.localize('okButton', "OK")], noLink: true }, (result) => null); this.reportMenuActionTelemetry('showAboutDialog'); } private openUrl(url: string, id: string): void { shell.openExternal(url); this.reportMenuActionTelemetry(id); } private reportMenuActionTelemetry(id: string): void { this.windowsService.sendToFocused('vscode:telemetry', { eventName: 'workbenchActionExecuted', data: { id, from: 'menu' } }); } } function __separator__(): Electron.MenuItem { return new MenuItem({ type: 'separator' }); } function mnemonicLabel(label: string): string { if (platform.isMacintosh) { return label.replace(/\(&&\w\)|&&/g, ''); // no mnemonic support on mac/linux } return label.replace(/&&/g, '&'); }<|fim▁end|>
let needsMenuUpdate = false; keybindings.forEach((keybinding) => {
<|file_name|>index.js<|end_file_name|><|fim▁begin|><|fim▁hole|> * Pipe audio streams to your ears * Dan Motzenbecker <[email protected]> * MIT Licensed */ "use strict"; var spawn = require('child_process').spawn, util = require('util'), Duplex = require('stream').Duplex, apply = function(obj, method, args) { return obj[method].apply(obj, args); } var EarPipe = function(type, bits, transcode) { var params; if (!(this instanceof EarPipe)) { return new EarPipe(type, bits, transcode); } Duplex.apply(this); params = ['-q', '-b', bits || 16, '-t', type || 'mp3', '-']; if (transcode) { this.process = spawn('sox', params.concat(['-t', typeof transcode === 'string' ? transcode : 'wav', '-'])); } else { this.process = spawn('play', params); } } util.inherits(EarPipe, Duplex); EarPipe.prototype._read = function() { return apply(this.process.stdout, 'read', arguments); } EarPipe.prototype._write = function() { return apply(this.process.stdin, 'write', arguments); } EarPipe.prototype.pipe = function() { return apply(this.process.stdout, 'pipe', arguments); } EarPipe.prototype.end = function() { return apply(this.process.stdin, 'end', arguments); } EarPipe.prototype.kill = function() { return apply(this.process, 'kill', arguments); } module.exports = EarPipe;<|fim▁end|>
/*! * ear-pipe
<|file_name|>test_loaders.py<|end_file_name|><|fim▁begin|>from unittest import TestCase from pydigmips import instructions, loaders class HexaLoaderTestCase(TestCase): def testAdd(self): i = ['1510', # 000 101 010 001 0000 '1C60', '2C60'] # 001 011 000 110 0000 o = [instructions.Add(5, 2, 1), instructions.Add(7, 0, 6), instructions.Sub(3, 0, 6)] prog = loaders.load_hexa(i) self.assertEqual(prog, o) def testLd(self): i = ['4EAA', # 010 011 101 0101010 '6EAA'] # 011 011 101 0101010 o = [instructions.Ld(3, (5, 42)), instructions.St(3, (5, 42))] prog = loaders.load_hexa(i) self.assertEqual(prog, o)<|fim▁hole|> def testBle(self): i = ['8EAA'] # 100 011 101 0101010 o = [instructions.Ble(3, 5, 42)] prog = loaders.load_hexa(i) self.assertEqual(prog, o) def testLdi(self): i = ['B0AA'] # 101 100 00 10101010 o = [instructions.Ldi(4, 170)] prog = loaders.load_hexa(i) self.assertEqual(prog, o) def testJa(self): i = ['CE80'] # 110 011 101 0000000 o = [instructions.Ja(3, 5)] prog = loaders.load_hexa(i) self.assertEqual(prog, o) def testJ(self): i = ['EAAA'] # 111 0101010101010 o = [instructions.J(2730)] prog = loaders.load_hexa(i) self.assertEqual(prog, o)<|fim▁end|>
<|file_name|>qsub.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 import sys import os import random <|fim▁hole|>job_properties = read_job_properties(jobscript) with open("qsub.log", "w") as log: print(job_properties, file=log) print(random.randint(1, 100)) os.system("sh {}".format(jobscript))<|fim▁end|>
from snakemake.utils import read_job_properties jobscript = sys.argv[1]
<|file_name|>errors.py<|end_file_name|><|fim▁begin|>from __future__ import unicode_literals import six from rbtools.utils.encoding import force_unicode class APIError(Exception): def __init__(self, http_status, error_code, rsp=None, *args, **kwargs): Exception.__init__(self, *args, **kwargs) self.http_status = http_status self.error_code = error_code self.rsp = rsp def __str__(self): code_str = 'HTTP %d' % self.http_status if self.error_code: code_str += ', API Error %d' % self.error_code if self.rsp and 'err' in self.rsp: return '%s (%s)' % (self.rsp['err']['msg'], code_str) else: return code_str class AuthorizationError(APIError): pass class BadRequestError(APIError): def __str__(self): lines = [super(BadRequestError, self).__str__()] if self.rsp and 'fields' in self.rsp: lines.append('') for field, error in six.iteritems(self.rsp['fields']): lines.append(' %s: %s' % (field, '; '.join(error))) return '\n'.join(lines) class CacheError(Exception): """An exception for caching errors.""" class ServerInterfaceError(Exception): def __init__(self, msg, *args, **kwargs): Exception.__init__(self, *args, **kwargs) self.msg = msg def __str__(self): """Return the error message as a unicode string. Returns: unicode: The error message as a unicode string. """ return force_unicode(self.msg) API_ERROR_TYPE = { 400: BadRequestError,<|fim▁hole|> 401: AuthorizationError, } def create_api_error(http_status, *args, **kwargs): error_type = API_ERROR_TYPE.get(http_status, APIError) return error_type(http_status, *args, **kwargs)<|fim▁end|>
<|file_name|>AEtestNodeATemplate.py<|end_file_name|><|fim▁begin|>""" To create an Attribute Editor template using python, do the following: 1. create a subclass of `uitypes.AETemplate` 2. set its ``_nodeType`` class attribute to the name of the desired node type, or name the class using the convention ``AE<nodeType>Template`` 3. import the module AETemplates which do not meet one of the two requirements listed in step 2 will be ignored. To ensure that your Template's node type is being detected correctly, use the ``AETemplate.nodeType()`` class method:: import AETemplates AETemplates.AEmib_amb_occlusionTemplate.nodeType() As a convenience, when pymel is imported it will automatically import the module ``AETemplates``, if it exists, thereby causing any AETemplates within it or its sub-modules to be registered. Be sure to import pymel or modules containing your ``AETemplate`` classes before opening the Atrribute Editor for the node types in question. To check which python templates are loaded:: from pymel.core.uitypes import AELoader print AELoader.loadedTemplates() The example below demonstrates the simplest case, which is the first. It provides a layout for the mib_amb_occlusion mental ray shader. """ import pymel.core as pm import mymagicbox.AETemplateBase as AETemplateBase import mymagicbox.log as log class AEtestNodeATemplate(AETemplateBase.mmbTemplateBase): def buildBody(self, nodeName): log.debug("building AETemplate for node: %s", nodeName) self.AEswatchDisplay(nodeName) self.beginLayout("Common Material Attributes",collapse=0)<|fim▁hole|> self.addControl("mmbversion") self.endLayout() pm.mel.AEdependNodeTemplate(self.nodeName) self.addExtraControls()<|fim▁end|>
self.addControl("attribute0") self.endLayout() self.beginLayout("Version",collapse=0)
<|file_name|>ignored_params.rs<|end_file_name|><|fim▁begin|>#![feature(plugin)] #![plugin(rocket_codegen)] #[get("/<name>")] //~ ERROR 'name' is declared fn get(other: usize) -> &'static str { "hi" } //~ ERROR isn't in the function #[get("/a?<r>")] //~ ERROR 'r' is declared fn get1() -> &'static str { "hi" } //~ ERROR isn't in the function #[post("/a", data = "<test>")] //~ ERROR 'test' is declared fn post() -> &'static str { "hi" } //~ ERROR isn't in the function<|fim▁hole|>fn get2(r: usize) -> &'static str { "hi" } //~ ERROR isn't in the function fn main() { }<|fim▁end|>
#[get("/<_r>")] //~ ERROR '_r' is declared
<|file_name|>mechanicalturk.py<|end_file_name|><|fim▁begin|># Copyright (c) 2012-2021, Mark Peek <[email protected]> # All rights reserved. # # See LICENSE file for full license. from .aws import Action as BaseAction<|fim▁hole|>prefix = "mechanicalturk" class Action(BaseAction): def __init__(self, action: str = None) -> None: super().__init__(prefix, action) class ARN(BaseARN): def __init__(self, resource: str = "", region: str = "", account: str = "") -> None: super().__init__( service=prefix, resource=resource, region=region, account=account ) AcceptQualificationRequest = Action("AcceptQualificationRequest") ApproveAssignment = Action("ApproveAssignment") ApproveRejectedAssignment = Action("ApproveRejectedAssignment") AssignQualification = Action("AssignQualification") AssociateQualificationWithWorker = Action("AssociateQualificationWithWorker") BlockWorker = Action("BlockWorker") ChangeHITTypeOfHIT = Action("ChangeHITTypeOfHIT") CreateAdditionalAssignmentsForHIT = Action("CreateAdditionalAssignmentsForHIT") CreateHIT = Action("CreateHIT") CreateHITType = Action("CreateHITType") CreateHITWithHITType = Action("CreateHITWithHITType") CreateQualificationType = Action("CreateQualificationType") CreateWorkerBlock = Action("CreateWorkerBlock") DeleteHIT = Action("DeleteHIT") DeleteQualificationType = Action("DeleteQualificationType") DeleteWorkerBlock = Action("DeleteWorkerBlock") DisableHIT = Action("DisableHIT") DisassociateQualificationFromWorker = Action("DisassociateQualificationFromWorker") DisposeHIT = Action("DisposeHIT") DisposeQualificationType = Action("DisposeQualificationType") ExtendHIT = Action("ExtendHIT") ForceExpireHIT = Action("ForceExpireHIT") GetAccountBalance = Action("GetAccountBalance") GetAssignment = Action("GetAssignment") GetAssignmentsForHIT = Action("GetAssignmentsForHIT") GetBlockedWorkers = Action("GetBlockedWorkers") GetBonusPayments = Action("GetBonusPayments") GetFileUploadURL = Action("GetFileUploadURL") GetHIT = Action("GetHIT") GetHITsForQualificationType = Action("GetHITsForQualificationType") GetQualificationRequests = Action("GetQualificationRequests") GetQualificationScore = Action("GetQualificationScore") GetQualificationType = Action("GetQualificationType") GetQualificationsForQualificationType = Action("GetQualificationsForQualificationType") GetRequesterStatistic = Action("GetRequesterStatistic") GetRequesterWorkerStatistic = Action("GetRequesterWorkerStatistic") GetReviewResultsForHIT = Action("GetReviewResultsForHIT") GetReviewableHITs = Action("GetReviewableHITs") GrantBonus = Action("GrantBonus") GrantQualification = Action("GrantQualification") ListAssignmentsForHIT = Action("ListAssignmentsForHIT") ListBonusPayments = Action("ListBonusPayments") ListHITs = Action("ListHITs") ListHITsForQualificationType = Action("ListHITsForQualificationType") ListQualificationRequests = Action("ListQualificationRequests") ListQualificationTypes = Action("ListQualificationTypes") ListReviewPolicyResultsForHIT = Action("ListReviewPolicyResultsForHIT") ListReviewableHITs = Action("ListReviewableHITs") ListWorkerBlocks = Action("ListWorkerBlocks") ListWorkersWithQualificationType = Action("ListWorkersWithQualificationType") NotifyWorkers = Action("NotifyWorkers") RegisterHITType = Action("RegisterHITType") RejectAssignment = Action("RejectAssignment") RejectQualificationRequest = Action("RejectQualificationRequest") RevokeQualification = Action("RevokeQualification") SearchHITs = Action("SearchHITs") SearchQualificationTypes = Action("SearchQualificationTypes") SendBonus = Action("SendBonus") SendTestEventNotification = Action("SendTestEventNotification") SetHITAsReviewing = Action("SetHITAsReviewing") SetHITTypeNotification = Action("SetHITTypeNotification") UnblockWorker = Action("UnblockWorker") UpdateExpirationForHIT = Action("UpdateExpirationForHIT") UpdateHITReviewStatus = Action("UpdateHITReviewStatus") UpdateHITTypeOfHIT = Action("UpdateHITTypeOfHIT") UpdateNotificationSettings = Action("UpdateNotificationSettings") UpdateQualificationScore = Action("UpdateQualificationScore") UpdateQualificationType = Action("UpdateQualificationType")<|fim▁end|>
from .aws import BaseARN service_name = "Amazon Mechanical Turk"
<|file_name|>other.py<|end_file_name|><|fim▁begin|>""" accounts FILE: forms.py Created: 6/21/15 8:31 PM """ __author__ = 'Mark Scrimshire:@ekivemark' from django.conf import settings from django import forms from django.utils.safestring import mark_safe from registration.forms import (RegistrationFormUniqueEmail, RegistrationFormTermsOfService) from accounts.models import User class Email(forms.EmailField): def clean(self, value): if settings.DEBUG: print("email is ", value) value = value.lower() super(Email, self).clean(value) try:<|fim▁hole|> except User.DoesNotExist: if settings.DEBUG: print("no match on user:", value) return value class UserRegistrationForm(forms.ModelForm): """ A form for creating new users. Includes all the required fields, plus a repeated password. """ # email will be become username email = Email() password1 = forms.CharField(widget=forms.PasswordInput(), label="Password") password2 = forms.CharField(widget=forms.PasswordInput(), label="Repeat your password") fields = ['user', 'email', 'password1', 'password2' ] def clean_user(self): """ We need to check that user is not containing spaces. We also need to make sure it is lower case :return: self """ data = self.cleaned_data['user'] # remove spaces data = data.replace(" ", "") # Convert to lowercase data = data.lower() if data == "": raise forms.ValidationError("User name is required") if settings.DEBUG: print("User: ", self.cleaned_data['user'], " = [",data, "]" ) return data def clean_password(self): if self.data['password1'] != self.data['password2']: raise forms.ValidationError('Passwords are not the same') return self.data['password1'] class RegistrationFormUserTOSAndEmail(UserRegistrationForm, RegistrationFormUniqueEmail, RegistrationFormTermsOfService, ): class Meta: model = User fields = ['user', 'email', 'first_name', 'last_name'] # exclude = ['user'] # pass class RegistrationFormTOSAndEmail( RegistrationFormUniqueEmail, RegistrationFormTermsOfService, ): pass<|fim▁end|>
User.objects.get(email=value) raise forms.ValidationError(mark_safe( "This email is already registered. <br/>Use <a href='/password/reset'>this forgot password</a> link or on the <a href ='/accounts/login?next=/'>login page</a>."))
<|file_name|>associated-types-normalize-in-bounds-ufcs.rs<|end_file_name|><|fim▁begin|>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that we normalize associated types that appear in bounds; if // we didn't, the call to `self.split2()` fails to type check. // pretty-expanded FIXME #23616 use std::marker::PhantomData; struct Splits<'a, T:'a, P>(PhantomData<(&'a T, P)>); struct SplitsN<I>(PhantomData<I>); trait SliceExt2 { type Item; fn split2<'a, P>(&'a self, pred: P) -> Splits<'a, Self::Item, P> where P: FnMut(&Self::Item) -> bool; fn splitn2<'a, P>(&'a self, n: u32, pred: P) -> SplitsN<Splits<'a, Self::Item, P>> where P: FnMut(&Self::Item) -> bool; } impl<T> SliceExt2 for [T] { type Item = T; fn split2<P>(&self, pred: P) -> Splits<T, P> where P: FnMut(&T) -> bool { loop {} } fn splitn2<P>(&self, n: u32, pred: P) -> SplitsN<Splits<T, P>> where P: FnMut(&T) -> bool { SliceExt2::split2(self, pred); loop {} } }<|fim▁hole|>fn main() { }<|fim▁end|>
<|file_name|>mux_twists.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 from functools import partial import math from threading import Lock import rospy from geometry_msgs.msg import Twist from lg_common.helpers import run_with_influx_exception_handler NODE_NAME = 'mux_twists' DEFAULT_TICK_RATE = 65.0 DEFAULT_AXIS_LIMIT = math.sqrt(2) / 2 DEFAULT_AGE_LIMIT = 1.0 def clamp(val, lo, hi): return min(max(val, lo), hi) def clamp_twist(twist, lo, hi): twist.linear.x = clamp(twist.linear.x, lo, hi) twist.linear.y = clamp(twist.linear.y, lo, hi) twist.linear.z = clamp(twist.linear.z, lo, hi) twist.angular.x = clamp(twist.angular.x, lo, hi) twist.angular.y = clamp(twist.angular.y, lo, hi) twist.angular.z = clamp(twist.angular.z, lo, hi) class TwistMuxer: def __init__(self, twist_pub, axis_limit, age_limit): self._lock = Lock() self.twist_pub = twist_pub self.axis_limit = axis_limit self.age_limit = rospy.Duration(age_limit) self.samples = {} self.sample_stamps = {} def handle_twist(self, topic, twist): with self._lock: self._handle_twist(topic, twist) def _handle_twist(self, topic, twist): self.samples[topic] = twist self.sample_stamps[topic] = rospy.Time.now() def tick(self, tev): with self._lock: self._tick(tev) def _tick(self, tev): t = rospy.Time.now() result = Twist() for topic in list(self.samples.keys()):<|fim▁hole|> twist = self.samples[topic] result.linear.x += twist.linear.x result.linear.y += twist.linear.y result.linear.z += twist.linear.z result.angular.x += twist.angular.x result.angular.y += twist.angular.y result.angular.z += twist.angular.z clamp_twist(result, -self.axis_limit, self.axis_limit) self.twist_pub.publish(result) def main(): rospy.init_node(NODE_NAME) tick_rate = float(rospy.get_param('~tick_rate', DEFAULT_TICK_RATE)) sources = [ s.strip() for s in rospy.get_param('~sources').split(',') ] axis_limit = float(rospy.get_param('~axis_limit', DEFAULT_AXIS_LIMIT)) age_limit = float(rospy.get_param('~age_limit', DEFAULT_AGE_LIMIT)) twist_pub = rospy.Publisher('/lg_twister/twist', Twist, queue_size=10) muxer = TwistMuxer(twist_pub, axis_limit, age_limit) for source in sources: handler = partial(muxer.handle_twist, source) rospy.Subscriber(source, Twist, handler) rospy.Timer(rospy.Duration(1.0 / tick_rate), muxer.tick) rospy.spin() if __name__ == '__main__': run_with_influx_exception_handler(main, NODE_NAME)<|fim▁end|>
stamp = self.sample_stamps[topic] if t - stamp > self.age_limit: continue
<|file_name|>let.js<|end_file_name|><|fim▁begin|>/** * @param func<|fim▁hole|> */ export function letProto(func) { return func(this); } //# sourceMappingURL=let.js.map<|fim▁end|>
* @return {Observable<R>} * @method let * @owner Observable
<|file_name|>update.go<|end_file_name|><|fim▁begin|>package postactions import ( "net/http" "github.com/fragmenta/auth/can" "github.com/fragmenta/mux" "github.com/fragmenta/server" "github.com/fragmenta/view" "github.com/fragmenta/fragmenta-cms/src/lib/session" "github.com/fragmenta/fragmenta-cms/src/posts" "github.com/fragmenta/fragmenta-cms/src/users" ) // HandleUpdateShow renders the form to update a post. func HandleUpdateShow(w http.ResponseWriter, r *http.Request) error { // Fetch the params params, err := mux.Params(r) if err != nil { return server.InternalError(err) } // Find the post post, err := posts.Find(params.GetInt(posts.KeyName)) if err != nil { return server.NotFoundError(err) } <|fim▁hole|> return server.NotAuthorizedError(err) } // Fetch the users authors, err := users.FindAll(users.Where("role=?", users.Admin)) if err != nil { return server.InternalError(err) } // Render the template view := view.NewRenderer(w, r) view.AddKey("currentUser", user) view.AddKey("post", post) view.AddKey("authors", authors) return view.Render() } // HandleUpdate handles the POST of the form to update a post func HandleUpdate(w http.ResponseWriter, r *http.Request) error { // Fetch the params params, err := mux.Params(r) if err != nil { return server.InternalError(err) } // Find the post post, err := posts.Find(params.GetInt(posts.KeyName)) if err != nil { return server.NotFoundError(err) } // Check the authenticity token err = session.CheckAuthenticity(w, r) if err != nil { return err } // Authorise update post user := session.CurrentUser(w, r) err = can.Update(post, user) if err != nil { return server.NotAuthorizedError(err) } // Validate the params, removing any we don't accept postParams := post.ValidateParams(params.Map(), posts.AllowedParams()) err = post.Update(postParams) if err != nil { return server.InternalError(err) } // Redirect to post return server.Redirect(w, r, post.ShowURL()) }<|fim▁end|>
// Authorise update post user := session.CurrentUser(w, r) err = can.Update(post, user) if err != nil {
<|file_name|>split_file.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python """ split_file.py [-o <dir>] <path> Take the file at <path> and write it to multiple files, switching to a new file every time an annotation of the form "// BEGIN file1.swift" is encountered. If <dir> is specified, place the files in <dir>; otherwise, put them in the current directory. """ import getopt import os import re import sys def usage(): sys.stderr.write(__doc__.strip() + "\n") sys.exit(1) fp_out = None dest_dir = '.' try: opts, args = getopt.getopt(sys.argv[1:], 'o:h') for (opt, arg) in opts: if opt == '-o': dest_dir = arg elif opt == '-h': usage() except getopt.GetoptError: usage() if len(args) != 1: usage() fp_in = open(args[0], 'r')<|fim▁hole|> if m: if fp_out: fp_out.close() fp_out = open(os.path.join(dest_dir, m.group(1)), 'w') elif fp_out: fp_out.write(line) fp_in.close() if fp_out: fp_out.close()<|fim▁end|>
for line in fp_in: m = re.match(r'^//\s*BEGIN\s+([^\s]+)\s*$', line)
<|file_name|>WebSocket.py<|end_file_name|><|fim▁begin|>try: from tornado.websocket import WebSocketHandler import tornado.ioloop tornadoAvailable = True except ImportError: class WebSocketHandler(object): pass tornadoAvailable = False from json import loads as fromJS, dumps as toJS from threading import Thread from Log import console import Settings from utils import * PORT = Settings.PORT + 1 handlers = [] channels = {} class WebSocket: @staticmethod def available(): return tornadoAvailable @staticmethod def start(): if WebSocket.available(): WSThread().start() @staticmethod def broadcast(data): for handler in handlers: handler.write_message(toJS(data)) @staticmethod def sendChannel(channel, data): if not 'channel' in data: data['channel'] = channel for handler in channels.get(channel, []): handler.write_message(toJS(data)) class WSThread(Thread): def __init__(self): Thread.__init__(self) self.name = 'websocket' self.daemon = True def run(self): app = tornado.web.Application([('/', WSHandler)]) app.listen(PORT, '0.0.0.0') tornado.ioloop.IOLoop.instance().start() class WSHandler(WebSocketHandler): def __init__(self, *args, **kw):<|fim▁hole|> super(WSHandler, self).__init__(*args, **kw) self.channels = set() def check_origin(self, origin): return True def open(self): handlers.append(self) console('websocket', "Opened") def on_message(self, message): console('websocket', "Message received: %s" % message) try: data = fromJS(message) except: return if 'subscribe' in data and isinstance(data['subscribe'], list): addChannels = (set(data['subscribe']) - self.channels) self.channels |= addChannels for channel in addChannels: if channel not in channels: channels[channel] = set() channels[channel].add(self) if 'unsubscribe' in data and isinstance(data['unsubscribe'], list): rmChannels = (self.channels & set(data['unsubscribe'])) self.channels -= rmChannels for channel in rmChannels: channels[channel].remove(self) if len(channels[channel]) == 0: del channels[channel] def on_close(self): for channel in self.channels: channels[channel].remove(self) if len(channels[channel]) == 0: del channels[channel] handlers.remove(self) console('websocket', "Closed") verbs = { 'status': "Status set", 'name': "Renamed", 'goal': "Goal set", 'assigned': "Reassigned", 'hours': "Hours updated", } from Event import EventHandler, addEventHandler class ShareTaskChanges(EventHandler): def newTask(self, handler, task): WebSocket.sendChannel("backlog#%d" % task.sprint.id, {'type': 'new'}); #TODO def taskUpdate(self, handler, task, field, value): if field == 'assigned': # Convert set of Users to list of usernames value = [user.username for user in value] elif field == 'goal': # Convert Goal to goal ID value = value.id if value else 0 description = ("%s by %s" % (verbs[field], task.creator)) if field in verbs else None WebSocket.sendChannel("backlog#%d" % task.sprint.id, {'type': 'update', 'id': task.id, 'revision': task.revision, 'field': field, 'value': value, 'description': description, 'creator': task.creator.username}) addEventHandler(ShareTaskChanges())<|fim▁end|>
<|file_name|>image.rs<|end_file_name|><|fim▁begin|>#![allow(dead_code)] use std; use rgb::*; use imgref::*; /// RGBA, but: premultiplied alpha, linear, f32 unit scale 0..1 pub type RGBAPLU = RGBA<f32>; /// RGB, but linear, f32 unit scale 0..1 pub type RGBLU = RGB<f32>; /// L\*a\*b\*b, but using float units (values are 100× smaller than in usual integer representation) #[derive(Debug, Copy, Clone)] pub struct LAB { pub l: f32, pub a: f32, pub b: f32, } impl std::ops::Mul<LAB> for LAB { type Output = LAB; fn mul(self, other: LAB) -> Self::Output { LAB { l: self.l * other.l, a: self.a * other.a,<|fim▁hole|> } } impl std::ops::Mul<LAB> for f32 { type Output = LAB; fn mul(self, other: LAB) -> Self::Output { LAB { l: self * other.l, a: self * other.a, b: self * other.b, } } } impl std::ops::Mul<f32> for LAB { type Output = LAB; fn mul(self, other: f32) -> Self::Output { LAB { l: self.l * other, a: self.a * other, b: self.b * other, } } } impl std::ops::Add<LAB> for LAB { type Output = LAB; fn add(self, other: Self::Output) -> Self::Output { LAB { l: self.l + other.l, a: self.a + other.a, b: self.b + other.b, } } } impl std::ops::Add<f32> for LAB { type Output = LAB; fn add(self, other: f32) -> Self::Output { LAB { l: self.l + other, a: self.a + other, b: self.b + other, } } } impl std::ops::Sub<LAB> for LAB { type Output = LAB; fn sub(self, other: LAB) -> Self::Output { LAB { l: self.l - other.l, a: self.a - other.a, b: self.b - other.b, } } } impl LAB { pub(crate) fn avg(&self) -> f32 { (self.l + self.a + self.b) / 3.0 } } impl From<LAB> for f64 { fn from(other: LAB) -> f64 { other.avg() as f64 } } impl From<LAB> for f32 { fn from(other: LAB) -> f32 { other.avg() } } impl std::ops::Div<LAB> for LAB { type Output = LAB; fn div(self, other: Self::Output) -> Self::Output { LAB { l: self.l / other.l, a: self.a / other.a, b: self.b / other.b, } } } /// Component-wise averaging of pixel values used by `Downsample` to support arbitrary pixel types /// /// Used to naively resample 4 high-res pixels into one low-res pixel pub trait Average4 { fn average4(a: Self, b: Self, c: Self, d: Self) -> Self; } impl Average4 for f32 { fn average4(a: Self, b: Self, c: Self, d: Self) -> Self { (a + b + c + d) * 0.25 } } impl Average4 for RGBAPLU { fn average4(a: Self, b: Self, c: Self, d: Self) -> Self { RGBAPLU { r: Average4::average4(a.r, b.r, c.r, d.r), g: Average4::average4(a.g, b.g, c.g, d.g), b: Average4::average4(a.b, b.b, c.b, d.b), a: Average4::average4(a.a, b.a, c.a, d.a), } } } impl Average4 for RGBLU { fn average4(a: Self, b: Self, c: Self, d: Self) -> Self { RGBLU { r: Average4::average4(a.r, b.r, c.r, d.r), g: Average4::average4(a.g, b.g, c.g, d.g), b: Average4::average4(a.b, b.b, c.b, d.b), } } } pub(crate) trait ToRGB { fn to_rgb(self, n: usize) -> RGBLU; } impl ToRGB for RGBAPLU { fn to_rgb(self, n: usize) -> RGBLU { let mut r = self.r; let mut g = self.g; let mut b = self.b; let a = self.a; if a < 255.0 { if (n & 16) != 0 { r += 1.0 - a; } if (n & 8) != 0 { g += 1.0 - a; // assumes premultiplied alpha } if (n & 32) != 0 { b += 1.0 - a; } } RGBLU { r: r, g: g, b: b, } } } /// You can customize how images are downsampled /// /// Multi-scale DSSIM needs to scale images down. This is it. It's supposed to return the same type of image, but half the size. /// /// There is a default implementation that just averages 4 neighboring pixels. pub trait Downsample { type Output; fn downsample(&self) -> Option<Self::Output>; } impl<T> Downsample for ImgVec<T> where T: Average4 + Copy + Sync + Send { type Output = ImgVec<T>; fn downsample(&self) -> Option<Self::Output> { self.as_ref().downsample() } } impl<'a, T> Downsample for ImgRef<'a, T> where T: Average4 + Copy + Sync + Send { type Output = ImgVec<T>; fn downsample(&self) -> Option<Self::Output> { let stride = self.stride(); let width = self.width(); let height = self.height(); if width < 8 || height < 8 { return None; } let half_height = height / 2; let half_width = width / 2; let mut scaled = Vec::with_capacity(half_width * half_height); scaled.extend(self.buf.chunks(stride * 2).take(half_height).flat_map(|pair|{ let (top, bot) = pair.split_at(stride); let top = &top[0..half_width * 2]; let bot = &bot[0..half_width * 2]; return top.chunks(2).zip(bot.chunks(2)).map(|(a,b)| Average4::average4(a[0], a[1], b[0], b[1])) })); assert_eq!(half_width * half_height, scaled.len()); return Some(Img::new(scaled, half_width, half_height)); } } #[allow(dead_code)] pub(crate) fn worst(input: ImgRef<'_, f32>) -> ImgVec<f32> { let stride = input.stride(); let half_height = input.height() / 2; let half_width = input.width() / 2; if half_height < 4 || half_width < 4 { return input.new_buf(input.buf.to_owned()); } let mut scaled = Vec::with_capacity(half_width * half_height); scaled.extend(input.buf.chunks(stride * 2).take(half_height).flat_map(|pair|{ let (top, bot) = pair.split_at(stride); let top = &top[0..half_width * 2]; let bot = &bot[0..half_width * 2]; return top.chunks(2).zip(bot.chunks(2)).map(|(a,b)| { a[0].min(a[1]).min(b[0].min(b[1])) }); })); assert_eq!(half_width * half_height, scaled.len()); Img::new(scaled, half_width, half_height) } #[allow(dead_code)] pub(crate) fn avgworst(input: ImgRef<'_, f32>) -> ImgVec<f32> { let stride = input.stride(); let half_height = input.height() / 2; let half_width = input.width() / 2; if half_height < 4 || half_width < 4 { return input.new_buf(input.buf.to_owned()); } let mut scaled = Vec::with_capacity(half_width * half_height); scaled.extend(input.buf.chunks(stride * 2).take(half_height).flat_map(|pair|{ let (top, bot) = pair.split_at(stride); let top = &top[0..half_width * 2]; let bot = &bot[0..half_width * 2]; return top.chunks(2).zip(bot.chunks(2)).map(|(a,b)| { (a[0].min(a[1]).min(b[0].min(b[1])) + ((a[0] + a[1] + b[0] + b[1]) * 0.25))*0.5 }); })); assert_eq!(half_width * half_height, scaled.len()); Img::new(scaled, half_width, half_height) } #[allow(dead_code)] pub(crate) fn avg(input: ImgRef<'_, f32>) -> ImgVec<f32> { let stride = input.stride(); let half_height = input.height() / 2; let half_width = input.width() / 2; if half_height < 4 || half_width < 4 { return input.new_buf(input.buf.to_owned()); } let mut scaled = Vec::with_capacity(half_width * half_height); scaled.extend(input.buf.chunks(stride * 2).take(half_height).flat_map(|pair|{ let (top, bot) = pair.split_at(stride); let top = &top[0..half_width * 2]; let bot = &bot[0..half_width * 2]; return top.chunks(2).zip(bot.chunks(2)).map(|(a,b)| { (a[0] + a[1] + b[0] + b[1]) * 0.25 }); })); assert_eq!(half_width * half_height, scaled.len()); Img::new(scaled, half_width, half_height) }<|fim▁end|>
b: self.b * other.b, }
<|file_name|>text_documents.rs<|end_file_name|><|fim▁begin|>/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ //! Utilities related to LSP text document syncing use crate::{lsp_runtime_error::LSPRuntimeResult, server::GlobalState}; use lsp_types::{ notification::{ Cancel, DidChangeTextDocument, DidCloseTextDocument, DidOpenTextDocument, DidSaveTextDocument, Notification, }, DidChangeTextDocumentParams, DidOpenTextDocumentParams, TextDocumentItem, }; <|fim▁hole|>pub fn on_did_open_text_document( lsp_state: &impl GlobalState, params: <DidOpenTextDocument as Notification>::Params, ) -> LSPRuntimeResult<()> { let DidOpenTextDocumentParams { text_document } = params; let TextDocumentItem { text, uri, .. } = text_document; if !uri .path() .starts_with(lsp_state.root_dir().to_string_lossy().as_ref()) { return Ok(()); } lsp_state.document_opened(&uri, &text) } #[allow(clippy::unnecessary_wraps)] pub fn on_did_close_text_document( lsp_state: &impl GlobalState, params: <DidCloseTextDocument as Notification>::Params, ) -> LSPRuntimeResult<()> { let uri = params.text_document.uri; if !uri .path() .starts_with(lsp_state.root_dir().to_string_lossy().as_ref()) { return Ok(()); } lsp_state.document_closed(&uri) } pub fn on_did_change_text_document( lsp_state: &impl GlobalState, params: <DidChangeTextDocument as Notification>::Params, ) -> LSPRuntimeResult<()> { let DidChangeTextDocumentParams { content_changes, text_document, } = params; let uri = text_document.uri; if !uri .path() .starts_with(lsp_state.root_dir().to_string_lossy().as_ref()) { return Ok(()); } // We do full text document syncing, so the new text will be in the first content change event. let content_change = content_changes .first() .expect("content_changes should always be non-empty"); lsp_state.document_changed(&uri, &content_change.text) } #[allow(clippy::unnecessary_wraps)] pub(crate) fn on_did_save_text_document( _lsp_state: &impl GlobalState, _params: <DidSaveTextDocument as Notification>::Params, ) -> LSPRuntimeResult<()> { Ok(()) } #[allow(clippy::unnecessary_wraps)] pub fn on_cancel( _lsp_state: &impl GlobalState, _params: <Cancel as Notification>::Params, ) -> LSPRuntimeResult<()> { Ok(()) }<|fim▁end|>
<|file_name|>firehose.rs<|end_file_name|><|fim▁begin|>#![cfg(feature = "firehose")]<|fim▁hole|>use rusoto::{DefaultCredentialsProvider, Region}; #[test] fn should_list_delivery_streams() { let credentials = DefaultCredentialsProvider::new().unwrap(); let client = KinesisFirehoseClient::new(credentials, Region::UsEast1); let request = ListDeliveryStreamsInput::default(); client.list_delivery_streams(&request).unwrap(); }<|fim▁end|>
extern crate rusoto; use rusoto::firehose::{KinesisFirehoseClient, ListDeliveryStreamsInput};
<|file_name|>example_test.go<|end_file_name|><|fim▁begin|>// Copyright 2018, OpenCensus Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package jaeger_test import ( "log" "go.opencensus.io/exporter/jaeger" "go.opencensus.io/trace" ) func ExampleNewExporter_collector() { // Register the Jaeger exporter to be able to retrieve // the collected spans. exporter, err := jaeger.NewExporter(jaeger.Options{ Endpoint: "http://localhost:14268", Process: jaeger.Process{ ServiceName: "trace-demo", }, }) if err != nil { log.Fatal(err) } trace.RegisterExporter(exporter) } func ExampleNewExporter_agent() { // Register the Jaeger exporter to be able to retrieve // the collected spans. exporter, err := jaeger.NewExporter(jaeger.Options{ AgentEndpoint: "localhost:6831", Process: jaeger.Process{ ServiceName: "trace-demo",<|fim▁hole|> }, }) if err != nil { log.Fatal(err) } trace.RegisterExporter(exporter) } // ExampleNewExporter_processTags shows how to set ProcessTags // on a Jaeger exporter. These tags will be added to the exported // Jaeger process. func ExampleNewExporter_processTags() { // Register the Jaeger exporter to be able to retrieve // the collected spans. exporter, err := jaeger.NewExporter(jaeger.Options{ AgentEndpoint: "localhost:6831", Process: jaeger.Process{ ServiceName: "trace-demo", Tags: []jaeger.Tag{ jaeger.StringTag("ip", "127.0.0.1"), jaeger.BoolTag("demo", true), }, }, }) if err != nil { log.Fatal(err) } trace.RegisterExporter(exporter) }<|fim▁end|>
<|file_name|>local_transactions.rs<|end_file_name|><|fim▁begin|>// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. //! Local Transactions List. use linked_hash_map::LinkedHashMap; use transaction::SignedTransaction; use error::TransactionError; use util::{U256, H256}; /// Status of local transaction. /// Can indicate that the transaction is currently part of the queue (`Pending/Future`) /// or gives a reason why the transaction was removed. #[derive(Debug, PartialEq, Clone)] pub enum Status { /// The transaction is currently in the transaction queue. Pending, /// The transaction is in future part of the queue. Future, /// Transaction is already mined. Mined(SignedTransaction), /// Transaction is dropped because of limit Dropped(SignedTransaction), /// Replaced because of higher gas price of another transaction. Replaced(SignedTransaction, U256, H256), /// Transaction was never accepted to the queue. Rejected(SignedTransaction, TransactionError), /// Transaction is invalid. Invalid(SignedTransaction), } impl Status { fn is_current(&self) -> bool { *self == Status::Pending || *self == Status::Future } } /// Keeps track of local transactions that are in the queue or were mined/dropped recently. #[derive(Debug)] pub struct LocalTransactionsList { max_old: usize, transactions: LinkedHashMap<H256, Status>, } impl Default for LocalTransactionsList { fn default() -> Self { Self::new(10) } } impl LocalTransactionsList { pub fn new(max_old: usize) -> Self { LocalTransactionsList { max_old: max_old, transactions: Default::default(), } } pub fn mark_pending(&mut self, hash: H256) { self.clear_old(); self.transactions.insert(hash, Status::Pending); } pub fn mark_future(&mut self, hash: H256) { self.transactions.insert(hash, Status::Future); self.clear_old(); } pub fn mark_rejected(&mut self, tx: SignedTransaction, err: TransactionError) { self.transactions.insert(tx.hash(), Status::Rejected(tx, err)); self.clear_old(); } pub fn mark_replaced(&mut self, tx: SignedTransaction, gas_price: U256, hash: H256) { self.transactions.insert(tx.hash(), Status::Replaced(tx, gas_price, hash)); self.clear_old(); } pub fn mark_invalid(&mut self, tx: SignedTransaction) { self.transactions.insert(tx.hash(), Status::Invalid(tx)); self.clear_old(); } pub fn mark_dropped(&mut self, tx: SignedTransaction) { self.transactions.insert(tx.hash(), Status::Dropped(tx)); self.clear_old(); } pub fn mark_mined(&mut self, tx: SignedTransaction) { self.transactions.insert(tx.hash(), Status::Mined(tx)); self.clear_old(); } pub fn contains(&self, hash: &H256) -> bool { self.transactions.contains_key(hash) } pub fn all_transactions(&self) -> &LinkedHashMap<H256, Status> { &self.transactions } fn clear_old(&mut self) { let number_of_old = self.transactions .values() .filter(|status| !status.is_current()) .count(); if self.max_old >= number_of_old { return; } let to_remove = self.transactions .iter() .filter(|&(_, status)| !status.is_current()) .map(|(hash, _)| *hash) .take(number_of_old - self.max_old) .collect::<Vec<_>>();<|fim▁hole|> } } } #[cfg(test)] mod tests { use util::U256; use ethkey::{Random, Generator}; use transaction::{Action, Transaction, SignedTransaction}; use super::{LocalTransactionsList, Status}; #[test] fn should_add_transaction_as_pending() { // given let mut list = LocalTransactionsList::default(); // when list.mark_pending(10.into()); list.mark_future(20.into()); // then assert!(list.contains(&10.into()), "Should contain the transaction."); assert!(list.contains(&20.into()), "Should contain the transaction."); let statuses = list.all_transactions().values().cloned().collect::<Vec<Status>>(); assert_eq!(statuses, vec![Status::Pending, Status::Future]); } #[test] fn should_clear_old_transactions() { // given let mut list = LocalTransactionsList::new(1); let tx1 = new_tx(10.into()); let tx1_hash = tx1.hash(); let tx2 = new_tx(50.into()); let tx2_hash = tx2.hash(); list.mark_pending(10.into()); list.mark_invalid(tx1); list.mark_dropped(tx2); assert!(list.contains(&tx2_hash)); assert!(!list.contains(&tx1_hash)); assert!(list.contains(&10.into())); // when list.mark_future(15.into()); // then assert!(list.contains(&10.into())); assert!(list.contains(&15.into())); } fn new_tx(nonce: U256) -> SignedTransaction { let keypair = Random.generate().unwrap(); Transaction { action: Action::Create, value: U256::from(100), data: Default::default(), gas: U256::from(10), gas_price: U256::from(1245), nonce: nonce }.sign(keypair.secret(), None) } }<|fim▁end|>
for hash in to_remove { self.transactions.remove(&hash);
<|file_name|>ensure_test.go<|end_file_name|><|fim▁begin|>// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package main import ( "errors" "go/build" "testing" "github.com/golang/dep/internal/gps" "github.com/golang/dep/internal/gps/pkgtree" ) func TestInvalidEnsureFlagCombinations(t *testing.T) { ec := &ensureCommand{ update: true, add: true, } if err := ec.validateFlags(); err == nil { t.Error("-add and -update together should fail validation") } ec.vendorOnly, ec.add = true, false if err := ec.validateFlags(); err == nil { t.Error("-vendor-only with -update should fail validation") } ec.add, ec.update = true, false if err := ec.validateFlags(); err == nil { t.Error("-vendor-only with -add should fail validation") } ec.noVendor, ec.add = true, false if err := ec.validateFlags(); err == nil { t.Error("-vendor-only with -no-vendor should fail validation") } ec.noVendor = false // Also verify that the plain ensure path takes no args. This is a shady // test, as lots of other things COULD return errors, and we don't check // anything other than the error being non-nil. For now, it works well // because a panic will quickly result if the initial arg length validation // checks are incorrectly handled. if err := ec.runDefault(nil, []string{"foo"}, nil, nil, gps.SolveParameters{}); err == nil {<|fim▁hole|> t.Errorf("no args to plain ensure") } } func TestCheckErrors(t *testing.T) { tt := []struct { name string fatal bool pkgOrErrMap map[string]pkgtree.PackageOrErr }{ { name: "noErrors", fatal: false, pkgOrErrMap: map[string]pkgtree.PackageOrErr{ "mypkg": { P: pkgtree.Package{}, }, }, }, { name: "hasErrors", fatal: true, pkgOrErrMap: map[string]pkgtree.PackageOrErr{ "github.com/me/pkg": { Err: &build.NoGoError{}, }, "github.com/someone/pkg": { Err: errors.New("code is busted"), }, }, }, { name: "onlyGoErrors", fatal: false, pkgOrErrMap: map[string]pkgtree.PackageOrErr{ "github.com/me/pkg": { Err: &build.NoGoError{}, }, "github.com/someone/pkg": { P: pkgtree.Package{}, }, }, }, { name: "onlyBuildErrors", fatal: false, pkgOrErrMap: map[string]pkgtree.PackageOrErr{ "github.com/me/pkg": { Err: &build.NoGoError{}, }, "github.com/someone/pkg": { P: pkgtree.Package{}, }, }, }, { name: "allGoErrors", fatal: true, pkgOrErrMap: map[string]pkgtree.PackageOrErr{ "github.com/me/pkg": { Err: &build.NoGoError{}, }, }, }, { name: "allMixedErrors", fatal: true, pkgOrErrMap: map[string]pkgtree.PackageOrErr{ "github.com/me/pkg": { Err: &build.NoGoError{}, }, "github.com/someone/pkg": { Err: errors.New("code is busted"), }, }, }, } for _, tc := range tt { t.Run(tc.name, func(t *testing.T) { fatal, err := checkErrors(tc.pkgOrErrMap) if tc.fatal != fatal { t.Fatalf("expected fatal flag to be %T, got %T", tc.fatal, fatal) } if err == nil && fatal { t.Fatal("unexpected fatal flag value while err is nil") } }) } }<|fim▁end|>
t.Errorf("no args to plain ensure with -vendor-only") } ec.vendorOnly = false if err := ec.runDefault(nil, []string{"foo"}, nil, nil, gps.SolveParameters{}); err == nil {
<|file_name|>searchService.ts<|end_file_name|><|fim▁begin|>/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as arrays from 'vs/base/common/arrays'; import { DeferredPromise } from 'vs/base/common/async'; import { CancellationToken } from 'vs/base/common/cancellation'; import { canceled } from 'vs/base/common/errors'; import { Disposable, IDisposable, toDisposable } from 'vs/base/common/lifecycle'; import { ResourceMap } from 'vs/base/common/map'; import { Schemas } from 'vs/base/common/network'; import { StopWatch } from 'vs/base/common/stopwatch'; import { URI, URI as uri } from 'vs/base/common/uri'; import { IModelService } from 'vs/editor/common/services/modelService'; import { IFileService } from 'vs/platform/files/common/files'; import { ILogService } from 'vs/platform/log/common/log'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { EditorResourceAccessor, SideBySideEditor } from 'vs/workbench/common/editor'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; import { deserializeSearchError, FileMatch, ICachedSearchStats, IFileMatch, IFileQuery, IFileSearchStats, IFolderQuery, IProgressMessage, ISearchComplete, ISearchEngineStats, ISearchProgressItem, ISearchQuery, ISearchResultProvider, ISearchService, isFileMatch, isProgressMessage, ITextQuery, pathIncludedInQuery, QueryType, SearchError, SearchErrorCode, SearchProviderType } from 'vs/workbench/services/search/common/search'; import { addContextToEditorMatches, editorMatchesToTextSearchResults } from 'vs/workbench/services/search/common/searchHelpers'; import { IUriIdentityService } from 'vs/workbench/services/uriIdentity/common/uriIdentity'; export class SearchService extends Disposable implements ISearchService { declare readonly _serviceBrand: undefined; protected diskSearch: ISearchResultProvider | null = null; private readonly fileSearchProviders = new Map<string, ISearchResultProvider>(); private readonly textSearchProviders = new Map<string, ISearchResultProvider>(); private deferredFileSearchesByScheme = new Map<string, DeferredPromise<ISearchResultProvider>>(); private deferredTextSearchesByScheme = new Map<string, DeferredPromise<ISearchResultProvider>>(); constructor( private readonly modelService: IModelService, private readonly editorService: IEditorService, private readonly telemetryService: ITelemetryService, private readonly logService: ILogService, private readonly extensionService: IExtensionService, private readonly fileService: IFileService, private readonly uriIdentityService: IUriIdentityService, ) { super(); } registerSearchResultProvider(scheme: string, type: SearchProviderType, provider: ISearchResultProvider): IDisposable { let list: Map<string, ISearchResultProvider>; let deferredMap: Map<string, DeferredPromise<ISearchResultProvider>>; if (type === SearchProviderType.file) { list = this.fileSearchProviders; deferredMap = this.deferredFileSearchesByScheme; } else if (type === SearchProviderType.text) { list = this.textSearchProviders; deferredMap = this.deferredTextSearchesByScheme; } else { throw new Error('Unknown SearchProviderType'); } list.set(scheme, provider); if (deferredMap.has(scheme)) { deferredMap.get(scheme)!.complete(provider); deferredMap.delete(scheme); } return toDisposable(() => { list.delete(scheme); }); } async textSearch(query: ITextQuery, token?: CancellationToken, onProgress?: (item: ISearchProgressItem) => void): Promise<ISearchComplete> { // Get local results from dirty/untitled const localResults = this.getLocalResults(query); if (onProgress) { arrays.coalesce([...localResults.results.values()]).forEach(onProgress); } const onProviderProgress = (progress: ISearchProgressItem) => { if (isFileMatch(progress)) { // Match if (!localResults.results.has(progress.resource) && onProgress) { // don't override local results onProgress(progress); } } else if (onProgress) { // Progress onProgress(<IProgressMessage>progress); } if (isProgressMessage(progress)) { this.logService.debug('SearchService#search', progress.message); } }; const otherResults = await this.doSearch(query, token, onProviderProgress); return { ...otherResults, ...{ limitHit: otherResults.limitHit || localResults.limitHit }, results: [...otherResults.results, ...arrays.coalesce([...localResults.results.values()])] }; } fileSearch(query: IFileQuery, token?: CancellationToken): Promise<ISearchComplete> { return this.doSearch(query, token); } private doSearch(query: ISearchQuery, token?: CancellationToken, onProgress?: (item: ISearchProgressItem) => void): Promise<ISearchComplete> { this.logService.trace('SearchService#search', JSON.stringify(query)); const schemesInQuery = this.getSchemesInQuery(query); const providerActivations: Promise<any>[] = [Promise.resolve(null)]; schemesInQuery.forEach(scheme => providerActivations.push(this.extensionService.activateByEvent(`onSearch:${scheme}`))); providerActivations.push(this.extensionService.activateByEvent('onSearch:file')); const providerPromise = (async () => { await Promise.all(providerActivations); this.extensionService.whenInstalledExtensionsRegistered(); // Cancel faster if search was canceled while waiting for extensions if (token && token.isCancellationRequested) { return Promise.reject(canceled()); } const progressCallback = (item: ISearchProgressItem) => { if (token && token.isCancellationRequested) { return; } if (onProgress) { onProgress(item); } };<|fim▁hole|> let completes = await this.searchWithProviders(query, progressCallback, token); completes = arrays.coalesce(completes); if (!completes.length) { return { limitHit: false, results: [], messages: [], }; } return { limitHit: completes[0] && completes[0].limitHit, stats: completes[0].stats, messages: arrays.coalesce(arrays.flatten(completes.map(i => i.messages))).filter(arrays.uniqueFilter(message => message.type + message.text + message.trusted)), results: arrays.flatten(completes.map((c: ISearchComplete) => c.results)) }; })(); return new Promise((resolve, reject) => { if (token) { token.onCancellationRequested(() => { reject(canceled()); }); } providerPromise.then(resolve, reject); }); } private getSchemesInQuery(query: ISearchQuery): Set<string> { const schemes = new Set<string>(); if (query.folderQueries) { query.folderQueries.forEach(fq => schemes.add(fq.folder.scheme)); } if (query.extraFileResources) { query.extraFileResources.forEach(extraFile => schemes.add(extraFile.scheme)); } return schemes; } private async waitForProvider(queryType: QueryType, scheme: string): Promise<ISearchResultProvider> { const deferredMap: Map<string, DeferredPromise<ISearchResultProvider>> = queryType === QueryType.File ? this.deferredFileSearchesByScheme : this.deferredTextSearchesByScheme; if (deferredMap.has(scheme)) { return deferredMap.get(scheme)!.p; } else { const deferred = new DeferredPromise<ISearchResultProvider>(); deferredMap.set(scheme, deferred); return deferred.p; } } private async searchWithProviders(query: ISearchQuery, onProviderProgress: (progress: ISearchProgressItem) => void, token?: CancellationToken) { const e2eSW = StopWatch.create(false); const diskSearchQueries: IFolderQuery[] = []; const searchPs: Promise<ISearchComplete>[] = []; const fqs = this.groupFolderQueriesByScheme(query); await Promise.all([...fqs.keys()].map(async scheme => { const schemeFQs = fqs.get(scheme)!; let provider = query.type === QueryType.File ? this.fileSearchProviders.get(scheme) : this.textSearchProviders.get(scheme); if (!provider && scheme === Schemas.file) { diskSearchQueries.push(...schemeFQs); } else { if (!provider) { if (scheme !== Schemas.vscodeRemote) { console.warn(`No search provider registered for scheme: ${scheme}`); return; } console.warn(`No search provider registered for scheme: ${scheme}, waiting`); provider = await this.waitForProvider(query.type, scheme); } const oneSchemeQuery: ISearchQuery = { ...query, ...{ folderQueries: schemeFQs } }; searchPs.push(query.type === QueryType.File ? provider.fileSearch(<IFileQuery>oneSchemeQuery, token) : provider.textSearch(<ITextQuery>oneSchemeQuery, onProviderProgress, token)); } })); const diskSearchExtraFileResources = query.extraFileResources && query.extraFileResources.filter(res => res.scheme === Schemas.file); if (diskSearchQueries.length || diskSearchExtraFileResources) { const diskSearchQuery: ISearchQuery = { ...query, ...{ folderQueries: diskSearchQueries }, extraFileResources: diskSearchExtraFileResources }; if (this.diskSearch) { searchPs.push(diskSearchQuery.type === QueryType.File ? this.diskSearch.fileSearch(diskSearchQuery, token) : this.diskSearch.textSearch(diskSearchQuery, onProviderProgress, token)); } } return Promise.all(searchPs).then(completes => { const endToEndTime = e2eSW.elapsed(); this.logService.trace(`SearchService#search: ${endToEndTime}ms`); completes.forEach(complete => { this.sendTelemetry(query, endToEndTime, complete); }); return completes; }, err => { const endToEndTime = e2eSW.elapsed(); this.logService.trace(`SearchService#search: ${endToEndTime}ms`); const searchError = deserializeSearchError(err); this.logService.trace(`SearchService#searchError: ${searchError.message}`); this.sendTelemetry(query, endToEndTime, undefined, searchError); throw searchError; }); } private groupFolderQueriesByScheme(query: ISearchQuery): Map<string, IFolderQuery[]> { const queries = new Map<string, IFolderQuery[]>(); query.folderQueries.forEach(fq => { const schemeFQs = queries.get(fq.folder.scheme) || []; schemeFQs.push(fq); queries.set(fq.folder.scheme, schemeFQs); }); return queries; } private sendTelemetry(query: ISearchQuery, endToEndTime: number, complete?: ISearchComplete, err?: SearchError): void { const fileSchemeOnly = query.folderQueries.every(fq => fq.folder.scheme === Schemas.file); const otherSchemeOnly = query.folderQueries.every(fq => fq.folder.scheme !== Schemas.file); const scheme = fileSchemeOnly ? Schemas.file : otherSchemeOnly ? 'other' : 'mixed'; if (query.type === QueryType.File && complete && complete.stats) { const fileSearchStats = complete.stats as IFileSearchStats; if (fileSearchStats.fromCache) { const cacheStats: ICachedSearchStats = fileSearchStats.detailStats as ICachedSearchStats; type CachedSearchCompleteClassifcation = { reason?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; resultCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; workspaceFolderCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; type: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; endToEndTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; sortingTime?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; cacheWasResolved: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; cacheLookupTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; cacheFilterTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; cacheEntryCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; scheme: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; }; type CachedSearchCompleteEvent = { reason?: string; resultCount: number; workspaceFolderCount: number; type: 'fileSearchProvider' | 'searchProcess'; endToEndTime: number; sortingTime?: number; cacheWasResolved: boolean; cacheLookupTime: number; cacheFilterTime: number; cacheEntryCount: number; scheme: string; }; this.telemetryService.publicLog2<CachedSearchCompleteEvent, CachedSearchCompleteClassifcation>('cachedSearchComplete', { reason: query._reason, resultCount: fileSearchStats.resultCount, workspaceFolderCount: query.folderQueries.length, type: fileSearchStats.type, endToEndTime: endToEndTime, sortingTime: fileSearchStats.sortingTime, cacheWasResolved: cacheStats.cacheWasResolved, cacheLookupTime: cacheStats.cacheLookupTime, cacheFilterTime: cacheStats.cacheFilterTime, cacheEntryCount: cacheStats.cacheEntryCount, scheme }); } else { const searchEngineStats: ISearchEngineStats = fileSearchStats.detailStats as ISearchEngineStats; type SearchCompleteClassification = { reason?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; resultCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; workspaceFolderCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; type: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; endToEndTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; sortingTime?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; fileWalkTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; directoriesWalked: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; filesWalked: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; cmdTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; cmdResultCount?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; scheme: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; }; type SearchCompleteEvent = { reason?: string; resultCount: number; workspaceFolderCount: number; type: 'fileSearchProvider' | 'searchProcess'; endToEndTime: number; sortingTime?: number; fileWalkTime: number directoriesWalked: number; filesWalked: number; cmdTime: number; cmdResultCount?: number; scheme: string; }; this.telemetryService.publicLog2<SearchCompleteEvent, SearchCompleteClassification>('searchComplete', { reason: query._reason, resultCount: fileSearchStats.resultCount, workspaceFolderCount: query.folderQueries.length, type: fileSearchStats.type, endToEndTime: endToEndTime, sortingTime: fileSearchStats.sortingTime, fileWalkTime: searchEngineStats.fileWalkTime, directoriesWalked: searchEngineStats.directoriesWalked, filesWalked: searchEngineStats.filesWalked, cmdTime: searchEngineStats.cmdTime, cmdResultCount: searchEngineStats.cmdResultCount, scheme }); } } else if (query.type === QueryType.Text) { let errorType: string | undefined; if (err) { errorType = err.code === SearchErrorCode.regexParseError ? 'regex' : err.code === SearchErrorCode.unknownEncoding ? 'encoding' : err.code === SearchErrorCode.globParseError ? 'glob' : err.code === SearchErrorCode.invalidLiteral ? 'literal' : err.code === SearchErrorCode.other ? 'other' : err.code === SearchErrorCode.canceled ? 'canceled' : 'unknown'; } type TextSearchCompleteClassification = { reason?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; workspaceFolderCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; endToEndTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; scheme: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; error?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; usePCRE2: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; }; type TextSearchCompleteEvent = { reason?: string; workspaceFolderCount: number; endToEndTime: number; scheme: string; error?: string; usePCRE2: boolean; }; this.telemetryService.publicLog2<TextSearchCompleteEvent, TextSearchCompleteClassification>('textSearchComplete', { reason: query._reason, workspaceFolderCount: query.folderQueries.length, endToEndTime: endToEndTime, scheme, error: errorType, usePCRE2: !!query.usePCRE2 }); } } private getLocalResults(query: ITextQuery): { results: ResourceMap<IFileMatch | null>; limitHit: boolean } { const localResults = new ResourceMap<IFileMatch | null>(uri => this.uriIdentityService.extUri.getComparisonKey(uri)); let limitHit = false; if (query.type === QueryType.Text) { const canonicalToOriginalResources = new ResourceMap<URI>(); for (let editorInput of this.editorService.editors) { const canonical = EditorResourceAccessor.getCanonicalUri(editorInput, { supportSideBySide: SideBySideEditor.PRIMARY }); const original = EditorResourceAccessor.getOriginalUri(editorInput, { supportSideBySide: SideBySideEditor.PRIMARY }); if (canonical) { canonicalToOriginalResources.set(canonical, original ?? canonical); } } const models = this.modelService.getModels(); models.forEach((model) => { const resource = model.uri; if (!resource) { return; } if (limitHit) { return; } const originalResource = canonicalToOriginalResources.get(resource); if (!originalResource) { return; } // Skip search results if (model.getModeId() === 'search-result' && !(query.includePattern && query.includePattern['**/*.code-search'])) { // TODO: untitled search editors will be excluded from search even when include *.code-search is specified return; } // Block walkthrough, webview, etc. if (originalResource.scheme !== Schemas.untitled && !this.fileService.canHandleResource(originalResource)) { return; } // Exclude files from the git FileSystemProvider, e.g. to prevent open staged files from showing in search results if (originalResource.scheme === 'git') { return; } if (!this.matches(originalResource, query)) { return; // respect user filters } // Use editor API to find matches const askMax = typeof query.maxResults === 'number' ? query.maxResults + 1 : undefined; let matches = model.findMatches(query.contentPattern.pattern, false, !!query.contentPattern.isRegExp, !!query.contentPattern.isCaseSensitive, query.contentPattern.isWordMatch ? query.contentPattern.wordSeparators! : null, false, askMax); if (matches.length) { if (askMax && matches.length >= askMax) { limitHit = true; matches = matches.slice(0, askMax - 1); } const fileMatch = new FileMatch(originalResource); localResults.set(originalResource, fileMatch); const textSearchResults = editorMatchesToTextSearchResults(matches, model, query.previewOptions); fileMatch.results = addContextToEditorMatches(textSearchResults, model, query); } else { localResults.set(originalResource, null); } }); } return { results: localResults, limitHit }; } private matches(resource: uri, query: ITextQuery): boolean { return pathIncludedInQuery(query, resource.fsPath); } clearCache(cacheKey: string): Promise<void> { const clearPs = [ this.diskSearch, ...Array.from(this.fileSearchProviders.values()) ].map(provider => provider && provider.clearCache(cacheKey)); return Promise.all(clearPs) .then(() => { }); } }<|fim▁end|>
const exists = await Promise.all(query.folderQueries.map(query => this.fileService.exists(query.folder))); query.folderQueries = query.folderQueries.filter((_, i) => exists[i]);
<|file_name|>settings.py<|end_file_name|><|fim▁begin|>import os test_dir = os.path.dirname(__file__) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(test_dir, 'db.sqlite3'), } } INSTALLED_APPS = [ 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.auth', 'django.contrib.messages', 'django.contrib.admin', 'django.contrib.sites', 'django.contrib.staticfiles', 'imperavi', 'tinymce', 'newsletter' ] # Imperavi is not compatible with Django 1.9+ import django if django.VERSION > (1, 8): INSTALLED_APPS.remove('imperavi') MIDDLEWARE = [<|fim▁hole|> 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ] ROOT_URLCONF = 'test_project.urls' FIXTURE_DIRS = [os.path.join(test_dir, 'fixtures'), ] SITE_ID = 1 TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, 'DIRS': [os.path.join(test_dir, 'templates')], 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] # Enable time-zone support USE_TZ = True TIME_ZONE = 'UTC' # Required for django-webtest to work STATIC_URL = '/static/' # Random secret key import random key_chars = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)' SECRET_KEY = ''.join([ random.SystemRandom().choice(key_chars) for i in range(50) ]) # Logs all newsletter app messages to the console LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, }, 'loggers': { 'newsletter': { 'handlers': ['console'], 'propagate': True, }, }, } DEFAULT_AUTO_FIELD = "django.db.models.AutoField"<|fim▁end|>
<|file_name|>setup.py<|end_file_name|><|fim▁begin|># Copyright (c) Matt Haggard. # See LICENSE for details. from distutils.core import setup import os, re<|fim▁hole|> base_init = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'norm/__init__.py') guts = open(base_init, 'r').read() m = r_version.search(guts) if not m: raise Exception("Could not find version information") return m.groups()[0] setup( url='https://github.com/iffy/norm', author='Matt Haggard', author_email='[email protected]', name='norm', version=getVersion(), packages=[ 'norm', 'norm.test', 'norm.orm', 'norm.orm.test', ], requires = [ 'Twisted', ] )<|fim▁end|>
def getVersion(): r_version = re.compile(r"__version__\s*=\s*'(.*?)'")
<|file_name|>unique-send-2.rs<|end_file_name|><|fim▁begin|>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use core::comm::*; fn child(c: &SharedChan<~uint>, i: uint) {<|fim▁hole|> c.send(~i); } pub fn main() { let (p, ch) = stream(); let ch = SharedChan::new(ch); let n = 100u; let mut expected = 0u; for uint::range(0u, n) |i| { let ch = ch.clone(); task::spawn(|| child(&ch, i) ); expected += i; } let mut actual = 0u; for uint::range(0u, n) |_i| { let j = p.recv(); actual += *j; } assert!(expected == actual); }<|fim▁end|>
<|file_name|>netmhc_cons.py<|end_file_name|><|fim▁begin|># Copyright (c) 2014-2017. Mount Sinai School of Medicine # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import print_function, division, absolute_import from .base_commandline_predictor import BaseCommandlinePredictor from .parsing import parse_netmhccons_stdout class NetMHCcons(BaseCommandlinePredictor): def __init__( self, alleles, program_name="netMHCcons", process_limit=0, default_peptide_lengths=[9]): BaseCommandlinePredictor.__init__( self, program_name=program_name, alleles=alleles, parse_output_fn=parse_netmhccons_stdout, # netMHCcons does not have a supported allele flag supported_alleles_flag=None, length_flag="-length",<|fim▁hole|> allele_flag="-a", peptide_mode_flags=["-inptype", "1"], tempdir_flag="-tdir", process_limit=process_limit, default_peptide_lengths=default_peptide_lengths, group_peptides_by_length=True)<|fim▁end|>
input_file_flag="-f",
<|file_name|>vcview.py<|end_file_name|><|fim▁begin|>### Copyright (C) 2002-2006 Stephen Kennedy <[email protected]> ### Copyright (C) 2010-2012 Kai Willadsen <[email protected]> ### This program is free software; you can redistribute it and/or modify ### it under the terms of the GNU General Public License as published by ### the Free Software Foundation; either version 2 of the License, or ### (at your option) any later version. ### This program is distributed in the hope that it will be useful, ### but WITHOUT ANY WARRANTY; without even the implied warranty of ### MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ### GNU General Public License for more details. ### You should have received a copy of the GNU General Public License ### along with this program; if not, write to the Free Software ### Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, ### USA. from __future__ import print_function import atexit import tempfile import shutil import os import sys from gettext import gettext as _ import gtk import pango from . import melddoc from . import misc from . import paths from . import recent from . import tree from . import vc from .ui import emblemcellrenderer from .ui import gnomeglade ################################################################################ # # Local Functions # ################################################################################ def _commonprefix(files): if len(files) != 1: workdir = misc.commonprefix(files) else: workdir = os.path.dirname(files[0]) or "." return workdir def cleanup_temp(): temp_location = tempfile.gettempdir() # The strings below will probably end up as debug log, and are deliberately # not marked for translation. for f in _temp_files: try: assert os.path.exists(f) and os.path.isabs(f) and \ os.path.dirname(f) == temp_location os.remove(f) except: except_str = "{0[0]}: \"{0[1]}\"".format(sys.exc_info()) print("File \"{0}\" not removed due to".format(f), except_str, file=sys.stderr) for f in _temp_dirs: try: assert os.path.exists(f) and os.path.isabs(f) and \ os.path.dirname(f) == temp_location shutil.rmtree(f, ignore_errors=1) except: except_str = "{0[0]}: \"{0[1]}\"".format(sys.exc_info()) print("Directory \"{0}\" not removed due to".format(f), except_str, file=sys.stderr) _temp_dirs, _temp_files = [], [] atexit.register(cleanup_temp) ################################################################################ # # CommitDialog # ################################################################################ class CommitDialog(gnomeglade.Component): def __init__(self, parent): gnomeglade.Component.__init__(self, paths.ui_dir("vcview.ui"), "commitdialog") self.parent = parent self.widget.set_transient_for( parent.widget.get_toplevel() ) selected = parent._get_selected_files() topdir = _commonprefix(selected) selected = [ s[len(topdir):] for s in selected ] self.changedfiles.set_text( ("(in %s) "%topdir) + " ".join(selected) ) self.widget.show_all() def run(self): self.previousentry.child.set_editable(False) self.previousentry.set_active(0) self.textview.grab_focus() buf = self.textview.get_buffer() buf.place_cursor( buf.get_start_iter() ) buf.move_mark( buf.get_selection_bound(), buf.get_end_iter() ) response = self.widget.run() msg = buf.get_text(buf.get_start_iter(), buf.get_end_iter(), 0) if response == gtk.RESPONSE_OK: self.parent._command_on_selected( self.parent.vc.commit_command(msg) ) if len(msg.strip()): self.previousentry.prepend_text(msg) self.widget.destroy() def on_previousentry_activate(self, gentry): buf = self.textview.get_buffer() buf.set_text( gentry.child.get_text() ) COL_LOCATION, COL_STATUS, COL_REVISION, COL_TAG, COL_OPTIONS, COL_END = \ list(range(tree.COL_END, tree.COL_END+6)) class VcTreeStore(tree.DiffTreeStore): def __init__(self): tree.DiffTreeStore.__init__(self, 1, [str] * 5) ################################################################################ # filters ################################################################################ entry_modified = lambda x: (x.state >= tree.STATE_NEW) or (x.isdir and (x.state > tree.STATE_NONE)) entry_normal = lambda x: (x.state == tree.STATE_NORMAL) entry_nonvc = lambda x: (x.state == tree.STATE_NONE) or (x.isdir and (x.state > tree.STATE_IGNORED)) entry_ignored = lambda x: (x.state == tree.STATE_IGNORED) or x.isdir ################################################################################ # # VcView # ################################################################################ class VcView(melddoc.MeldDoc, gnomeglade.Component): # Map action names to VC commands and required arguments list action_vc_cmds_map = { "VcCompare": ("diff_command", ()), "VcCommit": ("commit_command", ("",)), "VcUpdate": ("update_command", ()), "VcAdd": ("add_command", ()), "VcResolved": ("resolved_command", ()), "VcRemove": ("remove_command", ()), "VcRevert": ("revert_command", ()), } state_actions = { "flatten": ("VcFlatten", None), "modified": ("VcShowModified", entry_modified), "normal": ("VcShowNormal", entry_normal), "unknown": ("VcShowNonVC", entry_nonvc), "ignored": ("VcShowIgnored", entry_ignored), } def __init__(self, prefs): melddoc.MeldDoc.__init__(self, prefs) gnomeglade.Component.__init__(self, paths.ui_dir("vcview.ui"), "vcview") actions = ( ("VcCompare", gtk.STOCK_DIALOG_INFO, _("_Compare"), None, _("Compare selected"), self.on_button_diff_clicked), ("VcCommit", "vc-commit-24", _("Co_mmit"), None, _("Commit"), self.on_button_commit_clicked), ("VcUpdate", "vc-update-24", _("_Update"), None, _("Update"), self.on_button_update_clicked), ("VcAdd", "vc-add-24", _("_Add"), None, _("Add to VC"), self.on_button_add_clicked), ("VcRemove", "vc-remove-24", _("_Remove"), None, _("Remove from VC"), self.on_button_remove_clicked), ("VcResolved", "vc-resolve-24", _("_Resolved"), None, _("Mark as resolved for VC"), self.on_button_resolved_clicked), ("VcRevert", gtk.STOCK_REVERT_TO_SAVED, None, None, _("Revert to original"), self.on_button_revert_clicked), ("VcDeleteLocally", gtk.STOCK_DELETE, None, None, _("Delete locally"), self.on_button_delete_clicked), ) toggleactions = ( ("VcFlatten", gtk.STOCK_GOTO_BOTTOM, _("_Flatten"), None, _("Flatten directories"), self.on_button_flatten_toggled, False), ("VcShowModified","filter-modified-24", _("_Modified"), None, _("Show modified"), self.on_filter_state_toggled, False), ("VcShowNormal", "filter-normal-24", _("_Normal"), None, _("Show normal"), self.on_filter_state_toggled, False), ("VcShowNonVC", "filter-nonvc-24", _("Non _VC"), None, _("Show unversioned files"), self.on_filter_state_toggled, False), ("VcShowIgnored", "filter-ignored-24", _("Ignored"), None, _("Show ignored files"), self.on_filter_state_toggled, False), ) self.ui_file = paths.ui_dir("vcview-ui.xml") self.actiongroup = gtk.ActionGroup('VcviewActions') self.actiongroup.set_translation_domain("meld") self.actiongroup.add_actions(actions) self.actiongroup.add_toggle_actions(toggleactions) for action in ("VcCompare", "VcFlatten", "VcShowModified", "VcShowNormal", "VcShowNonVC", "VcShowIgnored"): self.actiongroup.get_action(action).props.is_important = True for action in ("VcCommit", "VcUpdate", "VcAdd", "VcRemove", "VcShowModified", "VcShowNormal", "VcShowNonVC", "VcShowIgnored", "VcResolved"): button = self.actiongroup.get_action(action) button.props.icon_name = button.props.stock_id self.model = VcTreeStore() self.widget.connect("style-set", self.model.on_style_set) self.treeview.set_model(self.model) selection = self.treeview.get_selection() selection.set_mode(gtk.SELECTION_MULTIPLE) selection.connect("changed", self.on_treeview_selection_changed) self.treeview.set_headers_visible(1) self.treeview.set_search_equal_func(self.treeview_search_cb) self.current_path, self.prev_path, self.next_path = None, None, None column = gtk.TreeViewColumn( _("Name") ) renicon = emblemcellrenderer.EmblemCellRenderer() rentext = gtk.CellRendererText() column.pack_start(renicon, expand=0) column.pack_start(rentext, expand=1) col_index = self.model.column_index column.set_attributes(renicon, icon_name=col_index(tree.COL_ICON, 0), icon_tint=col_index(tree.COL_TINT, 0)) column.set_attributes(rentext, text=col_index(tree.COL_TEXT, 0), foreground_gdk=col_index(tree.COL_FG, 0), style=col_index(tree.COL_STYLE, 0), weight=col_index(tree.COL_WEIGHT, 0), strikethrough=col_index(tree.COL_STRIKE, 0)) self.treeview.append_column(column) def addCol(name, num): column = gtk.TreeViewColumn(name) rentext = gtk.CellRendererText() column.pack_start(rentext, expand=0) column.set_attributes(rentext, markup=self.model.column_index(num, 0)) self.treeview.append_column(column) return column self.treeview_column_location = addCol( _("Location"), COL_LOCATION) addCol(_("Status"), COL_STATUS) addCol(_("Rev"), COL_REVISION) addCol(_("Tag"), COL_TAG) addCol(_("Options"), COL_OPTIONS) self.state_filters = [] for s in self.state_actions: if s in self.prefs.vc_status_filters: action_name = self.state_actions[s][0] self.state_filters.append(s) self.actiongroup.get_action(action_name).set_active(True) class ConsoleStream(object): def __init__(self, textview): self.textview = textview b = textview.get_buffer() self.mark = b.create_mark("END", b.get_end_iter(), 0) def write(self, s): if s: b = self.textview.get_buffer() b.insert(b.get_end_iter(), s) self.textview.scroll_mark_onscreen( self.mark ) self.consolestream = ConsoleStream(self.consoleview) self.location = None self.treeview_column_location.set_visible(self.actiongroup.get_action("VcFlatten").get_active()) if not self.prefs.vc_console_visible: self.on_console_view_toggle(self.console_hide_box) self.vc = None self.valid_vc_actions = tuple() # VC ComboBox self.combobox_vcs = gtk.ComboBox() self.combobox_vcs.lock = True self.combobox_vcs.set_model(gtk.ListStore(str, object, bool)) cell = gtk.CellRendererText() self.combobox_vcs.pack_start(cell, False) self.combobox_vcs.add_attribute(cell, 'text', 0) self.combobox_vcs.add_attribute(cell, 'sensitive', 2) self.combobox_vcs.lock = False self.hbox2.pack_end(self.combobox_vcs, expand=False) self.combobox_vcs.show() self.combobox_vcs.connect("changed", self.on_vc_change) def on_container_switch_in_event(self, ui): melddoc.MeldDoc.on_container_switch_in_event(self, ui) self.scheduler.add_task(self.on_treeview_cursor_changed) def update_actions_sensitivity(self): """Disable actions that use not implemented VC plugin methods """ valid_vc_actions = ["VcDeleteLocally"] for action_name, (meth_name, args) in self.action_vc_cmds_map.items(): action = self.actiongroup.get_action(action_name) try: getattr(self.vc, meth_name)(*args) action.props.sensitive = True valid_vc_actions.append(action_name) except NotImplementedError: action.props.sensitive = False self.valid_vc_actions = tuple(valid_vc_actions) def choose_vc(self, vcs): """Display VC plugin(s) that can handle the location""" self.combobox_vcs.lock = True self.combobox_vcs.get_model().clear() tooltip_texts = [_("Choose one Version Control"), _("Only one Version Control in this directory")] default_active = -1 valid_vcs = [] # Try to keep the same VC plugin active on refresh() for idx, avc in enumerate(vcs): # See if the necessary version control command exists. If so, # make sure what we're diffing is a valid respository. If either # check fails don't let the user select the that version control # tool and display a basic error message in the drop-down menu. err_str = "" if vc._vc.call(["which", avc.CMD]): # TRANSLATORS: this is an error message when a version control # application isn't installed or can't be found err_str = _("%s Not Installed" % avc.CMD) elif not avc.valid_repo(): # TRANSLATORS: this is an error message when a version # controlled repository is invalid or corrupted err_str = _("Invalid Repository") else: valid_vcs.append(idx) if (self.vc is not None and self.vc.__class__ == avc.__class__): default_active = idx if err_str: self.combobox_vcs.get_model().append( \ [_("%s (%s)") % (avc.NAME, err_str), avc, False]) else: self.combobox_vcs.get_model().append([avc.NAME, avc, True]) if valid_vcs and default_active == -1: default_active = min(valid_vcs) self.combobox_vcs.set_tooltip_text(tooltip_texts[len(vcs) == 1]) self.combobox_vcs.set_sensitive(len(vcs) > 1) self.combobox_vcs.lock = False self.combobox_vcs.set_active(default_active) def on_vc_change(self, cb): if not cb.lock: self.vc = cb.get_model()[cb.get_active_iter()][1] self._set_location(self.vc.location) self.update_actions_sensitivity() def set_location(self, location): self.choose_vc(vc.get_vcs(os.path.abspath(location or "."))) def _set_location(self, location): self.location = location self.current_path = None self.model.clear() self.fileentry.set_filename(location) self.fileentry.prepend_history(location) it = self.model.add_entries( None, [location] ) self.treeview.grab_focus() self.treeview.get_selection().select_iter(it) self.model.set_path_state(it, 0, tree.STATE_NORMAL, isdir=1) self.recompute_label() self.scheduler.remove_all_tasks() # If the user is just diffing a file (ie not a directory), there's no # need to scan the rest of the repository if os.path.isdir(self.vc.location): root = self.model.get_iter_root() self.scheduler.add_task(self._search_recursively_iter(root)) self.scheduler.add_task(self.on_treeview_cursor_changed) def get_comparison(self): return recent.TYPE_VC, [self.location]<|fim▁hole|> # TRANSLATORS: This is the location of the directory the user is diffing self.tooltip_text = _("%s: %s") % (_("Location"), self.location) self.label_changed() def _search_recursively_iter(self, iterstart): yield _("[%s] Scanning %s") % (self.label_text,"") rootpath = self.model.get_path( iterstart ) rootname = self.model.value_path( self.model.get_iter(rootpath), 0 ) prefixlen = 1 + len( self.model.value_path( self.model.get_iter_root(), 0 ) ) todo = [ (rootpath, rootname) ] active_action = lambda a: self.actiongroup.get_action(a).get_active() filters = [a[1] for a in self.state_actions.values() if \ active_action(a[0]) and a[1]] def showable(entry): for f in filters: if f(entry): return 1 recursive = self.actiongroup.get_action("VcFlatten").get_active() self.vc.cache_inventory(rootname) while len(todo): todo.sort() # depth first path, name = todo.pop(0) if path: it = self.model.get_iter( path ) root = self.model.value_path( it, 0 ) else: it = self.model.get_iter_root() root = name yield _("[%s] Scanning %s") % (self.label_text, root[prefixlen:]) entries = [f for f in self.vc.listdir(root) if showable(f)] differences = 0 for e in entries: differences |= (e.state != tree.STATE_NORMAL) if e.isdir and recursive: todo.append( (None, e.path) ) continue child = self.model.add_entries(it, [e.path]) self._update_item_state( child, e, root[prefixlen:] ) if e.isdir: todo.append( (self.model.get_path(child), None) ) if not recursive: # expand parents if len(entries) == 0: self.model.add_empty(it, _("(Empty)")) if differences or len(path)==1: self.treeview.expand_to_path(path) else: # just the root self.treeview.expand_row( (0,), 0) self.vc.uncache_inventory() def on_fileentry_activate(self, fileentry): path = fileentry.get_full_path() self.set_location(path) def on_delete_event(self, appquit=0): self.scheduler.remove_all_tasks() return gtk.RESPONSE_OK def on_row_activated(self, treeview, path, tvc): it = self.model.get_iter(path) if self.model.iter_has_child(it): if self.treeview.row_expanded(path): self.treeview.collapse_row(path) else: self.treeview.expand_row(path,0) else: path = self.model.value_path(it, 0) self.run_diff( [path] ) def run_diff_iter(self, path_list): silent_error = hasattr(self.vc, 'switch_to_external_diff') retry_diff = True while retry_diff: retry_diff = False yield _("[%s] Fetching differences") % self.label_text diffiter = self._command_iter(self.vc.diff_command(), path_list, 0) diff = None while type(diff) != type(()): diff = next(diffiter) yield 1 prefix, patch = diff[0], diff[1] try: patch = self.vc.clean_patch(patch) except AttributeError: pass yield _("[%s] Applying patch") % self.label_text if patch: applied = self.show_patch(prefix, patch, silent=silent_error) if not applied and silent_error: silent_error = False self.vc.switch_to_external_diff() retry_diff = True else: for path in path_list: self.emit("create-diff", [path]) def run_diff(self, path_list): try: for path in path_list: comp_path = self.vc.get_path_for_repo_file(path) os.chmod(comp_path, 0o444) _temp_files.append(comp_path) self.emit("create-diff", [comp_path, path]) except NotImplementedError: for path in path_list: self.scheduler.add_task(self.run_diff_iter([path]), atfront=1) def on_treeview_popup_menu(self, treeview): time = gtk.get_current_event_time() self.popup_menu.popup(None, None, None, 0, time) return True def on_button_press_event(self, treeview, event): if event.button == 3: path = treeview.get_path_at_pos(int(event.x), int(event.y)) if path is None: return False selection = treeview.get_selection() model, rows = selection.get_selected_rows() if path[0] not in rows: selection.unselect_all() selection.select_path(path[0]) treeview.set_cursor(path[0]) self.popup_menu.popup(None, None, None, event.button, event.time) return True return False def on_button_flatten_toggled(self, button): action = self.actiongroup.get_action("VcFlatten") self.treeview_column_location.set_visible(action.get_active()) self.on_filter_state_toggled(button) def on_filter_state_toggled(self, button): active_action = lambda a: self.actiongroup.get_action(a).get_active() active_filters = [a for a in self.state_actions if \ active_action(self.state_actions[a][0])] if set(active_filters) == set(self.state_filters): return self.state_filters = active_filters self.prefs.vc_status_filters = active_filters self.refresh() def on_treeview_selection_changed(self, selection): model, rows = selection.get_selected_rows() have_selection = bool(rows) for action in self.valid_vc_actions: self.actiongroup.get_action(action).set_sensitive(have_selection) def _get_selected_files(self): model, rows = self.treeview.get_selection().get_selected_rows() sel = [self.model.value_path(self.model.get_iter(r), 0) for r in rows] # Remove empty entries and trailing slashes return [x[-1] != "/" and x or x[:-1] for x in sel if x is not None] def _command_iter(self, command, files, refresh): """Run 'command' on 'files'. Return a tuple of the directory the command was executed in and the output of the command. """ msg = misc.shelljoin(command) yield "[%s] %s" % (self.label_text, msg.replace("\n", "\t")) def relpath(pbase, p): kill = 0 if len(pbase) and p.startswith(pbase): kill = len(pbase) + 1 return p[kill:] or "." if len(files) == 1 and os.path.isdir(files[0]): workdir = self.vc.get_working_directory(files[0]) else: workdir = self.vc.get_working_directory( _commonprefix(files) ) files = [ relpath(workdir, f) for f in files ] r = None self.consolestream.write( misc.shelljoin(command+files) + " (in %s)\n" % workdir) readiter = misc.read_pipe_iter(command + files, self.consolestream, workdir=workdir) try: while r is None: r = next(readiter) self.consolestream.write(r) yield 1 except IOError as e: misc.run_dialog("Error running command.\n'%s'\n\nThe error was:\n%s" % ( misc.shelljoin(command), e), parent=self, messagetype=gtk.MESSAGE_ERROR) if refresh: self.refresh_partial(workdir) yield workdir, r def _command(self, command, files, refresh=1): """Run 'command' on 'files'. """ self.scheduler.add_task(self._command_iter(command, files, refresh)) def _command_on_selected(self, command, refresh=1): files = self._get_selected_files() if len(files): self._command(command, files, refresh) def on_button_update_clicked(self, obj): self._command_on_selected(self.vc.update_command()) def on_button_commit_clicked(self, obj): CommitDialog(self).run() def on_button_add_clicked(self, obj): self._command_on_selected(self.vc.add_command()) def on_button_remove_clicked(self, obj): self._command_on_selected(self.vc.remove_command()) def on_button_resolved_clicked(self, obj): self._command_on_selected(self.vc.resolved_command()) def on_button_revert_clicked(self, obj): self._command_on_selected(self.vc.revert_command()) def on_button_delete_clicked(self, obj): files = self._get_selected_files() for name in files: try: if os.path.isfile(name): os.remove(name) elif os.path.isdir(name): if misc.run_dialog(_("'%s' is a directory.\nRemove recursively?") % os.path.basename(name), parent = self, buttonstype=gtk.BUTTONS_OK_CANCEL) == gtk.RESPONSE_OK: shutil.rmtree(name) except OSError as e: misc.run_dialog(_("Error removing %s\n\n%s.") % (name,e), parent = self) workdir = _commonprefix(files) self.refresh_partial(workdir) def on_button_diff_clicked(self, obj): files = self._get_selected_files() if len(files): self.run_diff(files) def open_external(self): self._open_files(self._get_selected_files()) def show_patch(self, prefix, patch, silent=False): if vc._vc.call(["which", "patch"]): primary = _("Patch tool not found") secondary = _("Meld needs the <i>patch</i> tool to be installed " "to perform comparisons in %s repositories. Please " "install <i>patch</i> and try again.") % self.vc.NAME msgarea = self.msgarea_mgr.new_from_text_and_icon( gtk.STOCK_DIALOG_ERROR, primary, secondary) msgarea.add_button(_("Hi_de"), gtk.RESPONSE_CLOSE) msgarea.connect("response", lambda *args: self.msgarea_mgr.clear()) msgarea.show_all() return False tmpdir = tempfile.mkdtemp("-meld") _temp_dirs.append(tmpdir) diffs = [] for fname in self.vc.get_patch_files(patch): destfile = os.path.join(tmpdir,fname) destdir = os.path.dirname( destfile ) if not os.path.exists(destdir): os.makedirs(destdir) pathtofile = os.path.join(prefix, fname) try: shutil.copyfile( pathtofile, destfile) except IOError: # it is missing, create empty file open(destfile,"w").close() diffs.append( (destfile, pathtofile) ) patchcmd = self.vc.patch_command(tmpdir) try: result = misc.write_pipe(patchcmd, patch, error=misc.NULL) except OSError: result = 1 if result == 0: for d in diffs: os.chmod(d[0], 0o444) self.emit("create-diff", d) return True elif not silent: primary = _("Error fetching original comparison file") secondary = _("Meld couldn't obtain the original version of your " "comparison file. If you are using the most recent " "version of Meld, please report a bug, including as " "many details as possible.") msgarea = self.msgarea_mgr.new_from_text_and_icon( gtk.STOCK_DIALOG_ERROR, primary, secondary) msgarea.add_button(_("Hi_de"), gtk.RESPONSE_CLOSE) msgarea.add_button(_("Report a bug"), gtk.RESPONSE_OK) def patch_error_cb(msgarea, response): if response == gtk.RESPONSE_OK: bug_url = "https://bugzilla.gnome.org/enter_bug.cgi?" + \ "product=meld" misc.open_uri(bug_url) else: self.msgarea_mgr.clear() msgarea.connect("response", patch_error_cb) msgarea.show_all() return False def refresh(self): self.set_location( self.model.value_path( self.model.get_iter_root(), 0 ) ) def refresh_partial(self, where): if not self.actiongroup.get_action("VcFlatten").get_active(): it = self.find_iter_by_name( where ) if it: newiter = self.model.insert_after( None, it) self.model.set_value(newiter, self.model.column_index( tree.COL_PATH, 0), where) self.model.set_path_state(newiter, 0, tree.STATE_NORMAL, True) self.model.remove(it) self.scheduler.add_task(self._search_recursively_iter(newiter)) else: # XXX fixme self.refresh() def _update_item_state(self, it, vcentry, location): e = vcentry self.model.set_path_state(it, 0, e.state, e.isdir) def setcol(col, val): self.model.set_value(it, self.model.column_index(col, 0), val) setcol(COL_LOCATION, location) setcol(COL_STATUS, e.get_status()) setcol(COL_REVISION, e.rev) setcol(COL_TAG, e.tag) setcol(COL_OPTIONS, e.options) def on_file_changed(self, filename): it = self.find_iter_by_name(filename) if it: path = self.model.value_path(it, 0) self.vc.update_file_state(path) files = self.vc.lookup_files([], [(os.path.basename(path), path)])[1] for e in files: if e.path == path: prefixlen = 1 + len( self.model.value_path( self.model.get_iter_root(), 0 ) ) self._update_item_state( it, e, e.parent[prefixlen:]) return def find_iter_by_name(self, name): it = self.model.get_iter_root() path = self.model.value_path(it, 0) while it: if name == path: return it elif name.startswith(path): child = self.model.iter_children( it ) while child: path = self.model.value_path(child, 0) if name == path: return child elif name.startswith(path): break else: child = self.model.iter_next( child ) it = child else: break return None def on_console_view_toggle(self, box, event=None): if box == self.console_hide_box: self.prefs.vc_console_visible = 0 self.console_hbox.hide() self.console_show_box.show() else: self.prefs.vc_console_visible = 1 self.console_hbox.show() self.console_show_box.hide() def on_consoleview_populate_popup(self, text, menu): item = gtk.ImageMenuItem(gtk.STOCK_CLEAR) def activate(*args): buf = text.get_buffer() buf.delete( buf.get_start_iter(), buf.get_end_iter() ) item.connect("activate", activate) item.show() menu.insert( item, 0 ) item = gtk.SeparatorMenuItem() item.show() menu.insert( item, 1 ) def on_treeview_cursor_changed(self, *args): cursor_path, cursor_col = self.treeview.get_cursor() if not cursor_path: self.emit("next-diff-changed", False, False) self.current_path = cursor_path return # If invoked directly rather than through a callback, we always check if not args: skip = False else: try: old_cursor = self.model.get_iter(self.current_path) except (ValueError, TypeError): # An invalid path gives ValueError; None gives a TypeError skip = False else: # We can skip recalculation if the new cursor is between # the previous/next bounds, and we weren't on a changed row state = self.model.get_state(old_cursor, 0) if state not in (tree.STATE_NORMAL, tree.STATE_EMPTY): skip = False else: if self.prev_path is None and self.next_path is None: skip = True elif self.prev_path is None: skip = cursor_path < self.next_path elif self.next_path is None: skip = self.prev_path < cursor_path else: skip = self.prev_path < cursor_path < self.next_path if not skip: prev, next = self.model._find_next_prev_diff(cursor_path) self.prev_path, self.next_path = prev, next have_next_diffs = (prev is not None, next is not None) self.emit("next-diff-changed", *have_next_diffs) self.current_path = cursor_path def next_diff(self, direction): if direction == gtk.gdk.SCROLL_UP: path = self.prev_path else: path = self.next_path if path: self.treeview.expand_to_path(path) self.treeview.set_cursor(path) def on_reload_activate(self, *extra): self.on_fileentry_activate(self.fileentry) def on_find_activate(self, *extra): self.treeview.emit("start-interactive-search") def treeview_search_cb(self, model, column, key, it): """Callback function for searching in VcView treeview""" path = model.get_value(it, tree.COL_PATH) # if query text contains slash, search in full path if key.find('/') >= 0: lineText = path else: lineText = os.path.basename(path) # Perform case-insensitive matching if query text is all lower-case if key.islower(): lineText = lineText.lower() if lineText.find(key) >= 0: # line matches return False else: return True<|fim▁end|>
def recompute_label(self): self.label_text = os.path.basename(self.location)
<|file_name|>sync_mutex_owned.rs<|end_file_name|><|fim▁begin|>#![warn(rust_2018_idioms)] #![cfg(feature = "sync")] #[cfg(target_arch = "wasm32")] use wasm_bindgen_test::wasm_bindgen_test as test; #[cfg(target_arch = "wasm32")] use wasm_bindgen_test::wasm_bindgen_test as maybe_tokio_test; #[cfg(not(target_arch = "wasm32"))] use tokio::test as maybe_tokio_test; use tokio::sync::Mutex; use tokio_test::task::spawn; use tokio_test::{assert_pending, assert_ready}; use std::sync::Arc; #[test] fn straight_execution() { let l = Arc::new(Mutex::new(100)); { let mut t = spawn(l.clone().lock_owned()); let mut g = assert_ready!(t.poll()); assert_eq!(&*g, &100); *g = 99; } { let mut t = spawn(l.clone().lock_owned()); let mut g = assert_ready!(t.poll()); assert_eq!(&*g, &99); *g = 98; } { let mut t = spawn(l.lock_owned()); let g = assert_ready!(t.poll()); assert_eq!(&*g, &98); } } #[test] fn readiness() { let l = Arc::new(Mutex::new(100)); let mut t1 = spawn(l.clone().lock_owned()); let mut t2 = spawn(l.lock_owned()); let g = assert_ready!(t1.poll()); // We can't now acquire the lease since it's already held in g assert_pending!(t2.poll()); // But once g unlocks, we can acquire it drop(g); assert!(t2.is_woken()); assert_ready!(t2.poll()); } /// Ensure a mutex is unlocked if a future holding the lock /// is aborted prematurely. #[tokio::test] #[cfg(feature = "full")] async fn aborted_future_1() { use std::time::Duration; use tokio::time::{interval, timeout}; let m1: Arc<Mutex<usize>> = Arc::new(Mutex::new(0)); { let m2 = m1.clone(); // Try to lock mutex in a future that is aborted prematurely timeout(Duration::from_millis(1u64), async move { let iv = interval(Duration::from_millis(1000)); tokio::pin!(iv); m2.lock_owned().await; iv.as_mut().tick().await; iv.as_mut().tick().await; }) .await .unwrap_err(); } // This should succeed as there is no lock left for the mutex. timeout(Duration::from_millis(1u64), async move { m1.lock_owned().await; }) .await .expect("Mutex is locked"); } /// This test is similar to `aborted_future_1` but this time the /// aborted future is waiting for the lock. #[tokio::test] #[cfg(feature = "full")] async fn aborted_future_2() { use std::time::Duration; use tokio::time::timeout; let m1: Arc<Mutex<usize>> = Arc::new(Mutex::new(0)); { // Lock mutex let _lock = m1.clone().lock_owned().await; { let m2 = m1.clone(); // Try to lock mutex in a future that is aborted prematurely timeout(Duration::from_millis(1u64), async move { m2.lock_owned().await; }) .await .unwrap_err(); } } // This should succeed as there is no lock left for the mutex. timeout(Duration::from_millis(1u64), async move { m1.lock_owned().await;<|fim▁hole|> #[test] fn try_lock_owned() { let m: Arc<Mutex<usize>> = Arc::new(Mutex::new(0)); { let g1 = m.clone().try_lock_owned(); assert!(g1.is_ok()); let g2 = m.clone().try_lock_owned(); assert!(!g2.is_ok()); } let g3 = m.try_lock_owned(); assert!(g3.is_ok()); } #[maybe_tokio_test] async fn debug_format() { let s = "debug"; let m = Arc::new(Mutex::new(s.to_string())); assert_eq!(format!("{:?}", s), format!("{:?}", m.lock_owned().await)); }<|fim▁end|>
}) .await .expect("Mutex is locked"); }
<|file_name|>EventController.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from datetime import datetime from datetime import date from datetime import timedelta import re import Entity.User as User import Entity.Event as Event import Entity.RepeatingEvent as RepeatingEvent import Responder def createSingleEvent(name, place, date): event = Event.getByDate(date) if event: return u'Am gegebenen Datum existiert bereits ein Event: \n' + event.toString() event = Event.create(name, place, date) return u'Event erstellt: \n' + event.toString() def createRepeatingEvent(name, place , day, time, endDate): rep = RepeatingEvent.create(name, place, day, time, endDate) events = rep.createEvents() answer = u'Events an diesen Daten erstellt:' for created in events[0]: answer = answer + u'\n' + created.strftime("%d.%m.%Y") if events[1]: answer = answer + u'\nFolgende Daten übersprungen, da an diesen schon ein Event existiert:' for skipped in events[1]: answer = answer + u'\n' + skipped.strftime("%d.%m.%Y") return answer def updateRepeating(user, additional): rep = RepeatingEvent.get(int(additional.split()[0])) events = Event.getByRepeating(rep.key) i = 0 for event in events: event.date = event.date + timedelta(minutes=int(additional.split()[1])) event.put() i = i +1 return str(i) + ' events updated' def create(user, additional): if not additional: return u'Um ein Event zu erstellen müssen entsprechende Angaben gemacht werden: Name;[Ort];Datum/Tag;Zeit;[EndDatum])' split = additional.split(';') if (len(split) != 4) and (len(split) != 5): return u'Anzahl der Argumente ist Falsch! Es müssen 4 oder 5 sein. (erstelle Name;[Ort];Datum/Tag;Zeit;[EndDatum])' if not split[0]: return u'Es muss ein Name angegeben werden' name = split[0].strip()<|fim▁hole|> try: time = datetime.strptime(timeString, "%H:%M").time() except ValueError as err: return u'Die Zeitangabe ' + timeString + u'hat das falsche Format (HH:MM).' dateOrDayString = split[2].strip() try: date = datetime.strptime(dateOrDayString, "%d.%m.%Y").date() return createSingleEvent(name, place, datetime.combine(date, time)) except ValueError as err: try: if dateOrDayString: dateOrDayString = dateOrDayString.lower() day = Event.DAY_DICT[dateOrDayString] try: endDateString = split[4] if endDateString: endDate = datetime.strptime(endDateString, "%d.%m.%Y").date() return createRepeatingEvent(name, place, day, time, endDate) except ValueError as err2: return u'EndDatum hat falsches Format.' except KeyError: return u'Als drittes Argument muss entweder ein Datum(TT.MM.JJJJ) oder ein Wochentag eingegeben werden' def delete(user, additional): result = Responder.parseEvent(user, additional) if isinstance(result,Event.Event): date = result.date name = result.name result.key.delete() return u' Event ' + name + u' am ' + date.strftime("%d.%m.%Y %H:%M") + u' gelöscht.' if isinstance(result,basestring): return result<|fim▁end|>
place = split[1].strip() timeString = split[3].strip() time = None
<|file_name|>transitioner.ts<|end_file_name|><|fim▁begin|>import Key from './key'; import SubscriberPayload from './subscriber-payload'; import Transition from './transition'; import TransitionHistory from './transition-history'; import TransitionSet from './transition-set'; /** * A class responsible for performing the transition between states. */ export default class Transitioner { private history: TransitionHistory; private transitions: TransitionSet; /** * @param transitions - The set of transitions to manage */ constructor(transitions: TransitionSet, history: TransitionHistory) { this.transitions = transitions; this.history = history; } /** * Check if it is possible to transition to a state from another state * @param toState - The state to transition to * @param fromState - The state to transition from * @return True if it is possible to transition */ canTransition(toState: Key, fromState: Key): boolean { return this.findExecutableTransition(toState, fromState) !== undefined; } /** * Check if it is possible to perform an undo * @return True if it is possible to undo */ canUndo(): boolean { return this.getTransitionForUndo() !== undefined; } /** * Check if it is possible to perform a redo * @return True if it is possible to redo */ canRedo(): boolean { return this.getTransitionForRedo() !== undefined; } /** * Transition to a state from another state. Fire the callback once the * transition is completed. If the to/from state does not exist, an error * will be thrown. * @param toState - The state to transition to * @param fromState - The state to transition from * @param [data] - The meta data associated with the transition * @param [callback] - The callback to fire once the transition is completed */ transition(toState: Key, fromState: Key, data?: any, callback?: (payload: SubscriberPayload) => void): void { if (!this.transitions.hasTransition({ from: fromState }) || !this.transitions.hasTransition({ to: toState })) { throw new Error(`Unable to transition from "${fromState}" to "${toState}"`); } const transition = this.findExecutableTransition(toState, fromState); if (transition) { this.history.addRecord({ data, state: transition.to }); if (callback) { callback({ from: transition.from, to: transition.to }); } } } /** * Transition to a new state by triggering an event. If the event or state * does not exist, an error will be thrown. * @param event - The event to trigger * @param fromState - The state to transition from * @param [data] - The meta data associated with the transition * @param [callback] - The callback to fire once the transition is completed */ triggerEvent(event: Key, fromState: Key, data?: any, callback?: (payload: SubscriberPayload) => void): void { if (!this.transitions.hasEvent(event) || !this.transitions.hasTransition({ from: fromState })) { throw new Error(`Unable to trigger "${event}" and transition from "${fromState}"`); } const transition = this.findExecutableTransitionByEvent(event, fromState); if (transition) { this.history.addRecord({ data, event, state: transition.to }); if (callback) { callback({ event: transition.event, from: transition.from, to: transition.to }); } } } /** * Undo a state transition. Fire the callback if it is possible to undo * @param [callback] - The callback to fire once the transition is completed */ undoTransition(callback?: (payload: SubscriberPayload) => void): void { const transition = this.getTransitionForUndo(); const record = this.history.getPreviousRecord(); if (!transition || !record) { return; } <|fim▁hole|> this.history.rewindHistory(); if (callback) { callback({ data: record.data, event: transition.event, from: transition.to, to: transition.from, }); } } /** * Redo a state transition. Fire the callback if it is possible to redo * @param [callback] - The callback to fire once the transition is completed */ redoTransition(callback?: (payload: SubscriberPayload) => void): void { const transition = this.getTransitionForRedo(); const record = this.history.getNextRecord(); if (!transition || !record) { return; } this.history.forwardHistory(); if (callback) { callback({ data: record.data, event: transition.event, from: transition.from, to: transition.to, }); } } /** * Find the first executable transition based on to/from state * @param toState - The state to transition to * @param fromState - The state to transition from * @return The executable transition */ private findExecutableTransition(toState: Key, fromState: Key): Transition | undefined { const transitions = this.transitions.filterExecutableTransitions({ from: fromState, to: toState, }); return transitions[0]; } /** * Find the first executable transition by event * @param toState - The state to transition to * @param fromState - The state to transition from * @return The executable transition */ private findExecutableTransitionByEvent(event: Key, fromState: Key): Transition | undefined { const transitions = this.transitions.filterExecutableTransitions({ event, from: fromState, }); return transitions[0]; } /** * Get a transition that can undo the current state * @return The undoable transition */ private getTransitionForUndo(): Transition | undefined { if (!this.history.getPreviousRecord()) { return; } const currentState = this.history.getCurrentRecord().state; const { state } = this.history.getPreviousRecord()!; const transition = this.findExecutableTransition(currentState, state); if (!transition || !transition.undoable) { return; } return transition; } /** * Get a transition that can redo the previous state * @return The redoable transition */ private getTransitionForRedo(): Transition | undefined { if (!this.history.getNextRecord()) { return; } const currentState = this.history.getCurrentRecord().state; const { state } = this.history.getNextRecord()!; const transition = this.findExecutableTransition(state, currentState); if (!transition || !transition.undoable) { return; } return transition; } }<|fim▁end|>
<|file_name|>jquery.overscroll.js<|end_file_name|><|fim▁begin|>/** * Overscroll v1.6.3 * A jQuery Plugin that emulates the iPhone scrolling experience in a browser. * http://azoffdesign.com/overscroll * * Intended for use with the latest jQuery * http://code.jquery.com/jquery-latest.js * * Copyright 2012, Jonathan Azoff * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * For API documentation, see the README file * http://azof.fr/pYCzuM * * Date: Thursday, May 17th 2012 */ /*jslint onevar: true, strict: true */ /*global window, document, setTimeout, clearTimeout, jQuery */ (function(global, dom, browser, math, wait, cancel, namespace, $, none){ // We want to run this plug-in in strict-mode // so that we may benefit from any optimizations // strict execution 'use strict'; // The key used to bind-instance specific data to an object var datakey = 'overscroll', // runs feature detection for overscroll compat = (function(){ var b = $.browser, fallback, agent = browser.userAgent, style = dom.createElement(datakey).style, prefix = b.webkit ? 'webkit' : (b.mozilla ? 'moz' : (b.msie ? 'ms' : (b.opera ? 'o' : ''))), cssprefix = prefix ? ['-','-'].join(prefix) : ''; compat = { prefix: prefix, overflowScrolling: false }; $.each(prefix ? [prefix, ''] : [prefix], function(i, prefix){ var animator = prefix ? (prefix + 'RequestAnimationFrame') : 'requestAnimationFrame', scroller = prefix ? (prefix + 'OverflowScrolling') : 'overflowScrolling'; // check to see if requestAnimationFrame is available if (global[animator] !== none) { compat.animate = function(callback){ global[animator].call(global, callback); }; } // check to see if overflowScrolling is available if (style[scroller] !== none) { // Chrome 19 introduced overflow scrolling. Unfortunately, their touch // implementation is incomplete. Hence, we act like it is not supported // for chrome. #59 if (agent.indexOf('Chrome') < 0) { compat.overflowScrolling = cssprefix + 'overflow-scrolling'; } } }); // check to see if the client supports touch compat.touchEvents = 'ontouchstart' in global; // fallback to set timeout for no animation support if (!compat.animate) { compat.animate = function(callback) { wait(callback, 1000/60); }; } // firefox and webkit browsers support native grabbing cursors<|fim▁hole|> compat.cursorGrab = cssprefix + 'grab'; compat.cursorGrabbing = cssprefix + 'grabbing'; // other browsers can user google's assets } else { fallback = 'https://mail.google.com/mail/images/2/'; compat.cursorGrab = 'url('+fallback+'openhand.cur), default'; compat.cursorGrabbing = 'url('+fallback+'closedhand.cur), default'; } return compat; })(), // These are all the events that could possibly // be used by the plug-in events = { drag: 'mousemove touchmove', end: 'mouseup mouseleave click touchend touchcancel', hover: 'mouseenter mouseleave', ignored: 'select dragstart drag', scroll: 'scroll', start: 'mousedown touchstart', wheel: 'mousewheel DOMMouseScroll' }, // These settings are used to tweak drift settings // for the plug-in settings = { captureThreshold: 3, driftDecay: 1.1, driftSequences: 22, driftTimeout: 100, scrollDelta: 15, thumbOpacity: 0.7, thumbThickness: 6, thumbTimeout: 400, wheelDelta: 20 }, // These defaults are used to complement any options // passed into the plug-in entry point defaults = { cancelOn: '', direction: 'multi', dragHold: false, hoverThumbs: false, scrollDelta: settings.scrollDelta, showThumbs: true, persistThumbs: false, wheelDelta: settings.wheelDelta, wheelDirection: 'vertical', zIndex: 999 }, // Triggers a DOM event on the overscrolled element. // All events are namespaced under the overscroll name triggerEvent = function (event, target) { target.trigger('overscroll:' + event); }, // Utility function to return a timestamp time = function() { return (new Date()).getTime(); }, // Captures the position from an event, modifies the properties // of the second argument to persist the position, and then // returns the modified object capturePosition = function (event, position, index) { position.x = event.pageX; position.y = event.pageY; position.time = time(); position.index = index; return position; }, // Used to move the thumbs around an overscrolled element moveThumbs = function (thumbs, sizing, left, top) { var ml, mt; if (thumbs && thumbs.added) { if (thumbs.horizontal) { ml = left * (1 + sizing.container.width / sizing.container.scrollWidth); mt = top + sizing.thumbs.horizontal.top; thumbs.horizontal.css('margin', mt + 'px 0 0 ' + ml + 'px'); } if (thumbs.vertical) { ml = left + sizing.thumbs.vertical.left; mt = top * (1 + sizing.container.height / sizing.container.scrollHeight); thumbs.vertical.css('margin', mt + 'px 0 0 ' + ml + 'px'); } } }, // Used to toggle the thumbs on and off // of an overscrolled element toggleThumbs = function (thumbs, options, dragging) { if (thumbs && thumbs.added && !options.persistThumbs) { if (dragging) { if (thumbs.vertical) { thumbs.vertical.stop(true, true).fadeTo('fast', settings.thumbOpacity); } if (thumbs.horizontal) { thumbs.horizontal.stop(true, true).fadeTo('fast', settings.thumbOpacity); } } else { if (thumbs.vertical) { thumbs.vertical.fadeTo('fast', 0); } if (thumbs.horizontal) { thumbs.horizontal.fadeTo('fast', 0); } } } }, // Defers click event listeners to after a mouseup event. // Used to avoid unintentional clicks deferClick = function (target) { var events = target.data('events'), click = events && events.click ? events.click.slice() : []; if (events) { delete events.click; } target.one('mouseup touchend touchcancel', function () { $.each(click, function(i, event){ target.click(event); }); return false; }); }, // Toggles thumbs on hover. This event is only triggered // if the hoverThumbs option is set hover = function (event) { var data = event.data, thumbs = data.thumbs, options = data.options, dragging = event.type === 'mouseenter'; toggleThumbs(thumbs, options, dragging); }, // This function is only ever used when the overscrolled element // scrolled outside of the scope of this plugin. scroll = function (event) { var data = event.data; if (!data.flags.dragged) { moveThumbs(data.thumbs, data.sizing, this.scrollLeft, this.scrollTop); } }, // handles mouse wheel scroll events wheel = function (event) { // prevent any default wheel behavior event.preventDefault(); var data = event.data, options = data.options, sizing = data.sizing, thumbs = data.thumbs, wheel = data.wheel, flags = data.flags, delta, original = event.originalEvent; // stop any drifts flags.drifting = false; // calculate how much to move the viewport by // TODO: let's base this on some fact somewhere... if (original.wheelDelta) { delta = original.wheelDelta / (compat.prefix === 'o' ? -120 : 120); } if (original.detail) { delta = -original.detail / 3; } delta *= options.wheelDelta; // initialize flags if this is the first tick if (!wheel) { data.target.data(datakey).dragging = flags.dragging = true; data.wheel = wheel = { timeout: null }; toggleThumbs(thumbs, options, true); } // actually modify scroll offsets if (options.wheelDirection === 'horizontal') { this.scrollLeft -= delta; } else { this.scrollTop -= delta; } if (wheel.timeout) { cancel(wheel.timeout); } moveThumbs(thumbs, sizing, this.scrollLeft, this.scrollTop); wheel.timeout = wait(function() { data.target.data(datakey).dragging = flags.dragging = false; toggleThumbs(thumbs, options, data.wheel = null); }, settings.thumbTimeout); }, // updates the current scroll offset during a mouse move drag = function (event) { event.preventDefault(); var data = event.data, touches = event.originalEvent.touches, options = data.options, sizing = data.sizing, thumbs = data.thumbs, position = data.position, flags = data.flags, target = data.target.get(0); // correct page coordinates for touch devices if (compat.touchEvents && touches && touches.length) { event = touches[0]; } if (!flags.dragged) { toggleThumbs(thumbs, options, true); } flags.dragged = true; if (options.direction !== 'vertical') { target.scrollLeft -= (event.pageX - position.x); } if (data.options.direction !== 'horizontal') { target.scrollTop -= (event.pageY - position.y); } capturePosition(event, data.position); if (--data.capture.index <= 0) { data.target.data(datakey).dragging = flags.dragging = true; capturePosition(event, data.capture, settings.captureThreshold); } moveThumbs(thumbs, sizing, target.scrollLeft, target.scrollTop); triggerEvent('dragging', data.target); }, // sends the overscrolled element into a drift drift = function (target, event, callback) { var data = event.data, dx, dy, xMod, yMod, capture = data.capture, options = data.options, sizing = data.sizing, thumbs = data.thumbs, elapsed = time() - capture.time, scrollLeft = target.scrollLeft, scrollTop = target.scrollTop, decay = settings.driftDecay; // only drift if enough time has passed since // the last capture event if (elapsed > settings.driftTimeout) { return callback(data); } // determine offset between last capture and current time dx = options.scrollDelta * (event.pageX - capture.x); dy = options.scrollDelta * (event.pageY - capture.y); // update target scroll offsets if (options.direction !== 'vertical') { scrollLeft -= dx; } if (options.direction !== 'horizontal') { scrollTop -= dy; } // split the distance to travel into a set of sequences xMod = dx / settings.driftSequences; yMod = dy / settings.driftSequences; triggerEvent('driftstart', data.target); data.drifting = true; // animate the drift sequence compat.animate(function render() { if (data.drifting) { var min = 1, max = -1; data.drifting = false; if (yMod > min && target.scrollTop > scrollTop || yMod < max && target.scrollTop < scrollTop) { data.drifting = true; target.scrollTop -= yMod; yMod /= decay; } if (xMod > min && target.scrollLeft > scrollLeft || xMod < max && target.scrollLeft < scrollLeft) { data.drifting = true; target.scrollLeft -= xMod; xMod /= decay; } moveThumbs(thumbs, sizing, target.scrollLeft, target.scrollTop); compat.animate(render); triggerEvent('drifting', data.target); } else { triggerEvent('driftend', data.target); callback(data); } }); }, // starts the drag operation and binds the mouse move handler start = function (event) { var data = event.data, target = data.target, start = data.start = $(event.target), flags = data.flags; // stop any drifts flags.drifting = false; // only start drag if the user has not explictly banned it. if (start.size() && !start.is(data.options.cancelOn)) { // without this the simple "click" event won't be recognized on touch clients if (!compat.touchEvents) { event.preventDefault(); } target.css('cursor', compat.cursorGrabbing); target.data(datakey).dragging = flags.dragging = flags.dragged = false; // apply the drag listeners to the doc or target if(data.options.dragHold) { $(document).on(events.drag, data, drag); } else { target.on(events.drag, data, drag); } data.position = capturePosition(event, {}); data.capture = capturePosition(event, {}, settings.captureThreshold); triggerEvent('dragstart', target); } }, // ends the drag operation and unbinds the mouse move handler stop = function (event) { var data = event.data, target = data.target, options = data.options, flags = data.flags, thumbs = data.thumbs, // hides the thumbs after the animation is done done = function () { if (thumbs && !options.hoverThumbs) { toggleThumbs(thumbs, options, false); } }; // remove drag listeners from doc or target if(options.dragHold) { $(document).unbind(events.drag, drag); } else { target.unbind(events.drag, drag); } // only fire events and drift if we started with a // valid position if (data.position) { triggerEvent('dragend', target); // only drift if a drag passed our threshold if (flags.dragging) { drift(target.get(0), event, done); } else { done(); } } // only if we moved, and the mouse down is the same as // the mouse up target do we defer the event if (flags.dragging && data.start.is(event.target)) { deferClick(data.start); } // clear all internal flags and settings target.data(datakey).dragging = data.start = data.capture = data.position = flags.dragged = flags.dragging = false; // set the cursor back to normal target.css('cursor', compat.cursorGrab); }, // Ensures that a full set of options are provided // for the plug-in. Also does some validation getOptions = function(options) { // fill in missing values with defaults options = $.extend({}, defaults, options); // check for inconsistent directional restrictions if (options.direction !== 'multi' && options.direction !== options.wheelDirection) { options.wheelDirection = options.direction; } // ensure positive values for deltas options.scrollDelta = math.abs(options.scrollDelta); options.wheelDelta = math.abs(options.wheelDelta); // fix values for scroll offset options.scrollLeft = options.scrollLeft === none ? null : math.abs(options.scrollLeft); options.scrollTop = options.scrollTop === none ? null : math.abs(options.scrollTop); return options; }, // Returns the sizing information (bounding box) for the // target DOM element getSizing = function (target) { var $target = $(target), width = $target.width(), height = $target.height(), scrollWidth = width >= target.scrollWidth ? width : target.scrollWidth, scrollHeight = height >= target.scrollHeight ? height : target.scrollHeight, hasScroll = scrollWidth > width || scrollHeight > height; return { valid: hasScroll, container: { width: width, height: height, scrollWidth: scrollWidth, scrollHeight: scrollHeight }, thumbs: { horizontal: { width: width * width / scrollWidth, height: settings.thumbThickness, corner: settings.thumbThickness / 2, left: 0, top: height - settings.thumbThickness }, vertical: { width: settings.thumbThickness, height: height * height / scrollHeight, corner: settings.thumbThickness / 2, left: width - settings.thumbThickness, top: 0 } } }; }, // Attempts to get (or implicitly creates) the // remover function for the target passed // in as an argument getRemover = function (target, orCreate) { var $target = $(target), thumbs, data = $target.data(datakey) || {}, style = $target.attr('style'), fallback = orCreate ? function () { data = $target.data(datakey); thumbs = data.thumbs; // restore original styles (if any) if (style) { $target.attr('style', style); } else { $target.removeAttr('style'); } // remove any created thumbs if (thumbs) { if (thumbs.horizontal) { thumbs.horizontal.remove(); } if (thumbs.vertical) { thumbs.vertical.remove(); } } // remove any bound overscroll events and data $target .removeData(datakey) .off(events.wheel, wheel) .off(events.start, start) .off(events.end, stop) .off(events.ignored, false); } : $.noop; return $.isFunction(data.remover) ? data.remover : fallback; }, // Genterates CSS specific to a particular thumb. // It requires sizing data and options getThumbCss = function(size, options) { return { position: 'absolute', opacity: options.persistThumbs ? settings.thumbOpacity : 0, 'background-color': 'black', width: size.width + 'px', height: size.height + 'px', 'border-radius': size.corner + 'px', 'margin': size.top + 'px 0 0 ' + size.left + 'px', 'z-index': options.zIndex }; }, // Creates the DOM elements used as "thumbs" within // the target container. createThumbs = function(target, sizing, options) { var div = '<div/>', thumbs = {}, css = false; if (sizing.container.scrollWidth > 0 && options.direction !== 'vertical') { css = getThumbCss(sizing.thumbs.horizontal, options); thumbs.horizontal = $(div).css(css).prependTo(target); } if (sizing.container.scrollHeight > 0 && options.direction !== 'horizontal') { css = getThumbCss(sizing.thumbs.vertical, options); thumbs.vertical = $(div).css(css).prependTo(target); } thumbs.added = !!css; return thumbs; }, // This function takes a jQuery element, some // (optional) options, and sets up event metadata // for each instance the plug-in affects setup = function(target, options) { // create initial data properties for this instance options = getOptions(options); var sizing = getSizing(target), thumbs, data = { options: options, sizing: sizing, flags: { dragging: false }, remover: getRemover(target, true) }; // only apply handlers if the overscrolled element // actually has an area to scroll if (sizing.valid) { // provide a circular-reference, enable events, and // apply any required CSS data.target = target = $(target).css({ position: 'relative', overflow: 'hidden', cursor: compat.cursorGrab }).on(events.wheel, data, wheel) .on(events.start, data, start) .on(events.end, data, stop) .on(events.scroll, data, scroll) .on(events.ignored, false); // apply the stop listeners for drag end if(options.dragHold) { $(document).on(events.end, data, stop); } else { data.target.on(events.end, data, stop); } // apply any user-provided scroll offsets if (options.scrollLeft !== null) { target.scrollLeft(options.scrollLeft); } if (options.scrollTop !== null) { target.scrollTop(options.scrollTop); } // add thumbs and listeners (if we're showing them) if (options.showThumbs) { data.thumbs = thumbs = createThumbs(target, sizing, options); if (thumbs.added) { moveThumbs(thumbs, sizing, target.scrollLeft(), target.scrollTop()); if (options.hoverThumbs) { target.on(events.hover, data, hover); } } } target.data(datakey, data); } }, // Removes any event listeners and other instance-specific // data from the target. It attempts to leave the target // at the state it found it. teardown = function(target) { getRemover(target)(); }, // This is the entry-point for enabling the plug-in; // You can find it's exposure point at the end // of this closure overscroll = function(options) { return this.removeOverscroll().each(function() { setup(this, options); }); }, // This function applies touch-specific CSS to enable // the behavior that Overscroll emulates. This function // is called instead of overscroll if the device supports // it touchscroll = function() { return this.removeOverscroll().each(function() { $(this).data(datakey, { remover: getRemover(this) }) .css(compat.overflowScrolling, 'touch') .css('overflow', 'auto'); }); }, // This is the entry-point for disabling the plug-in; // You can find it's exposure point at the end // of this closure removeOverscroll = function() { return this.each(function () { teardown(this); }); }; // Extend overscroll to expose settings to the user overscroll.settings = settings; // Extend jQuery's prototype to expose the plug-in. // If the supports native overflowScrolling, overscroll will not // attempt to override the browser's built in support $.extend(namespace, { overscroll: compat.overflowScrolling ? touchscroll : overscroll, removeOverscroll: removeOverscroll }); })(window, document, navigator, Math, setTimeout, clearTimeout, jQuery.fn, jQuery);<|fim▁end|>
if (prefix === 'moz' || prefix === 'webkit') {
<|file_name|>constructor.js<|end_file_name|><|fim▁begin|>import _size from './_size'; export default class MapObject { constructor() { this._data = new Map();<|fim▁hole|> get size() { return _size(); } }<|fim▁end|>
}
<|file_name|>GenericEventContext.java<|end_file_name|><|fim▁begin|>package io.github.phantamanta44.botah.core.context; import io.github.phantamanta44.botah.core.rate.RateLimitedChannel; import io.github.phantamanta44.botah.util.MessageUtils; import sx.blah.discord.api.Event; import sx.blah.discord.handle.obj.IChannel; import sx.blah.discord.handle.obj.IGuild; import sx.blah.discord.handle.obj.IMessage; import sx.blah.discord.handle.obj.IUser; import java.lang.reflect.Method; public class GenericEventContext implements IEventContext { private Class<? extends Event> clazz; private long timestamp; private IGuild guild; private IChannel channel; private IUser user; private IMessage msg; public GenericEventContext(Event event) { timestamp = System.currentTimeMillis(); clazz = event.getClass(); Method[] methods = clazz.getMethods(); for (Method m : methods) { try { if (m.getName().equalsIgnoreCase("getUser")) user = (IUser)m.invoke(event); else if (m.getName().equalsIgnoreCase("getChannel")) { channel = new RateLimitedChannel((IChannel)m.invoke(event)); guild = channel.getGuild(); } else if (m.getName().equalsIgnoreCase("getMessage")) { msg = (IMessage)m.invoke(event); user = msg.getAuthor(); channel = new RateLimitedChannel(msg.getChannel()); guild = channel.getGuild(); } } catch (Exception ex) { ex.printStackTrace(); } } } @Override public void sendMessage(String msg) { if (channel != null) MessageUtils.sendMessage(channel, msg); else throw new UnsupportedOperationException(); } @Override public void sendMessage(String format, Object... args) { sendMessage(String.format(format, args)); } @Override public long getTimestamp() { return timestamp; } @Override public Class<? extends Event> getType() { return clazz; } @Override public IGuild getGuild() { return guild; } @Override public IChannel getChannel() { return channel; } @Override<|fim▁hole|> } @Override public IMessage getMessage() { return msg; } }<|fim▁end|>
public IUser getUser() { return user;
<|file_name|>break-alignment-interface.cc<|end_file_name|><|fim▁begin|>/* break-align-interface.cc -- implement Break_alignment_interface source file of the GNU LilyPond music typesetter (c) 1997--2007 Han-Wen Nienhuys <[email protected]> */ #include "break-align-interface.hh" #include "align-interface.hh" #include "axis-group-interface.hh" #include "dimensions.hh" #include "international.hh" #include "output-def.hh" #include "paper-column.hh" #include "pointer-group-interface.hh" #include "self-alignment-interface.hh" #include "side-position-interface.hh" #include "warn.hh" /* This is tricky: we cannot modify 'elements, since callers are iterating the same list. Reordering the list in-place, or resetting 'elements will skip elements in the loops of callers. So we return the correct order as an array. */ SCM Break_alignment_interface::break_align_order (Item *me) { SCM order_vec = me->get_property ("break-align-orders"); if (!scm_is_vector (order_vec) || scm_c_vector_length (order_vec) < 3) return SCM_BOOL_F; SCM order = scm_vector_ref (order_vec, scm_from_int (me->break_status_dir () + 1)); return order; } vector<Grob*> Break_alignment_interface::ordered_elements (Grob *grob) { Item *me = dynamic_cast<Item *> (grob); extract_grob_set (me, "elements", elts); SCM order = break_align_order (me); if (order == SCM_BOOL_F) return elts; vector<Grob*> writable_elts (elts); /* Copy in order specified in BREAK-ALIGN-ORDER. */ vector<Grob*> new_elts; for (; scm_is_pair (order); order = scm_cdr (order)) { SCM sym = scm_car (order); for (vsize i = writable_elts.size (); i--;) { Grob *g = writable_elts[i];<|fim▁hole|> } } } return new_elts; } void Break_alignment_interface::add_element (Grob *me, Grob *toadd) { Align_interface::add_element (me, toadd); } MAKE_SCHEME_CALLBACK (Break_alignment_interface, calc_positioning_done, 1) SCM Break_alignment_interface::calc_positioning_done (SCM smob) { Grob *grob = unsmob_grob (smob); Item *me = dynamic_cast<Item *> (grob); me->set_property ("positioning-done", SCM_BOOL_T); vector<Grob*> elems = ordered_elements (me); vector<Interval> extents; int last_nonempty = -1; for (vsize i = 0; i < elems.size (); i++) { Interval y = elems[i]->extent (elems[i], X_AXIS); extents.push_back (y); if (!y.is_empty ()) last_nonempty = i; } vsize idx = 0; while (idx < extents.size () && extents[idx].is_empty ()) idx++; vector<Real> offsets; offsets.resize (elems.size ()); for (vsize i = 0; i < offsets.size ();i++) offsets[i] = 0.0; Real extra_right_space = 0.0; vsize edge_idx = VPOS; while (idx < elems.size ()) { vsize next_idx = idx + 1; while (next_idx < elems.size () && extents[next_idx].is_empty ()) next_idx++; Grob *l = elems[idx]; Grob *r = 0; if (next_idx < elems.size ()) r = elems[next_idx]; SCM alist = SCM_EOL; /* Find the first grob with a space-alist entry. */ extract_grob_set (l, "elements", elts); for (vsize i = elts.size (); i--;) { Grob *elt = elts[i]; if (edge_idx == VPOS && (elt->get_property ("break-align-symbol") == ly_symbol2scm ("left-edge"))) edge_idx = idx; SCM l = elt->get_property ("space-alist"); if (scm_is_pair (l)) { alist = l; break; } } SCM rsym = r ? SCM_EOL : ly_symbol2scm ("right-edge"); /* We used to use #'cause to find out the symbol and the spacing table, but that gets icky when that grob is suicided for some reason. */ if (r) { extract_grob_set (r, "elements", elts); for (vsize i = elts.size (); !scm_is_symbol (rsym) && i--;) { Grob *elt = elts[i]; rsym = elt->get_property ("break-align-symbol"); } } if (rsym == ly_symbol2scm ("left-edge")) edge_idx = next_idx; SCM entry = SCM_EOL; if (scm_is_symbol (rsym)) entry = scm_assq (rsym, alist); bool entry_found = scm_is_pair (entry); if (!entry_found) { string sym_string; if (scm_is_symbol (rsym)) sym_string = ly_symbol2string (rsym); string orig_string; if (unsmob_grob (l->get_property ("cause"))) orig_string = unsmob_grob (l->get_property ("cause"))->name (); programming_error (_f ("No spacing entry from %s to `%s'", orig_string.c_str (), sym_string.c_str ())); } Real distance = 1.0; SCM type = ly_symbol2scm ("extra-space"); if (entry_found) { entry = scm_cdr (entry); distance = scm_to_double (scm_cdr (entry)); type = scm_car (entry); } if (r) { if (type == ly_symbol2scm ("extra-space")) offsets[next_idx] = extents[idx][RIGHT] + distance - extents[next_idx][LEFT]; /* should probably junk minimum-space */ else if (type == ly_symbol2scm ("minimum-space")) offsets[next_idx] = max (extents[idx][RIGHT], distance); } else { extra_right_space = distance; if (idx + 1 < offsets.size ()) offsets[idx+1] = extents[idx][RIGHT] + distance; } idx = next_idx; } Real here = 0.0; Interval total_extent; Real alignment_off = 0.0; for (vsize i = 0; i < offsets.size (); i++) { here += offsets[i]; if (i == edge_idx) alignment_off = -here; total_extent.unite (extents[i] + here); } if (total_extent.is_empty ()) return SCM_BOOL_T; if (me->break_status_dir () == LEFT) alignment_off = -total_extent[RIGHT] - extra_right_space; else if (edge_idx == VPOS) alignment_off = -total_extent[LEFT]; here = alignment_off; for (vsize i = 0; i < offsets.size (); i++) { here += offsets[i]; elems[i]->translate_axis (here, X_AXIS); } return SCM_BOOL_T; } MAKE_SCHEME_CALLBACK (Break_alignable_interface, self_align_callback, 1) SCM Break_alignable_interface::self_align_callback (SCM grob) { Grob *me = unsmob_grob (grob); Item *alignment = dynamic_cast<Item*> (me->get_parent (X_AXIS)); if (!Break_alignment_interface::has_interface (alignment)) return scm_from_int (0); SCM symbol_list = me->get_property ("break-align-symbols"); vector<Grob*> elements = Break_alignment_interface::ordered_elements (alignment); if (elements.size () == 0) return scm_from_int (0); int break_aligned_grob = -1; for (; scm_is_pair (symbol_list); symbol_list = scm_cdr (symbol_list)) { SCM sym = scm_car (symbol_list); for (vsize i = 0; i < elements.size (); i++) { if (elements[i]->get_property ("break-align-symbol") == sym) { if (Item::break_visible (elements[i]) && !elements[i]->extent (elements[i], X_AXIS).is_empty ()) { break_aligned_grob = i; goto found_break_aligned_grob; /* ugh. need to break out of 2 loops */ } else if (break_aligned_grob == -1) break_aligned_grob = i; } } } found_break_aligned_grob: if (break_aligned_grob == -1) return scm_from_int (0); Grob *alignment_parent = elements[break_aligned_grob]; Grob *common = me->common_refpoint (alignment_parent, X_AXIS); Real anchor = robust_scm2double (alignment_parent->get_property ("break-align-anchor"), 0); return scm_from_double (alignment_parent->relative_coordinate (common, X_AXIS) - me->relative_coordinate (common, X_AXIS) + anchor); } MAKE_SCHEME_CALLBACK (Break_aligned_interface, calc_average_anchor, 1) SCM Break_aligned_interface::calc_average_anchor (SCM grob) { Grob *me = unsmob_grob (grob); Real avg = 0.0; int count = 0; /* average the anchors of those children that have it set */ extract_grob_set (me, "elements", elts); for (vsize i = 0; i < elts.size (); i++) { SCM anchor = elts[i]->get_property ("break-align-anchor"); if (scm_is_number (anchor)) { count++; avg += scm_to_double (anchor); } } return scm_from_double (count > 0 ? avg / count : 0); } MAKE_SCHEME_CALLBACK (Break_aligned_interface, calc_extent_aligned_anchor, 1) SCM Break_aligned_interface::calc_extent_aligned_anchor (SCM smob) { Grob *me = unsmob_grob (smob); Real alignment = robust_scm2double (me->get_property ("break-align-anchor-alignment"), 0.0); Interval iv = me->extent (me, X_AXIS); if (isinf (iv[LEFT]) && isinf (iv[RIGHT])) /* avoid NaN */ return scm_from_double (0.0); return scm_from_double (iv.linear_combination (alignment)); } MAKE_SCHEME_CALLBACK (Break_aligned_interface, calc_break_visibility, 1) SCM Break_aligned_interface::calc_break_visibility (SCM smob) { /* a BreakAlignGroup is break-visible iff it has one element that is break-visible */ Grob *me = unsmob_grob (smob); SCM ret = scm_c_make_vector (3, SCM_EOL); extract_grob_set (me, "elements", elts); for (int dir = 0; dir <= 2; dir++) { bool visible = false; for (vsize i = 0; i < elts.size (); i++) { SCM vis = elts[i]->get_property ("break-visibility"); if (scm_is_vector (vis) && to_boolean (scm_c_vector_ref (vis, dir))) visible = true; } scm_c_vector_set_x (ret, dir, scm_from_bool (visible)); } return ret; } ADD_INTERFACE (Break_alignable_interface, "Object that is aligned on a break aligment.", /* properties */ "break-align-symbols " ); ADD_INTERFACE (Break_aligned_interface, "Items that are aligned in prefatory matter.\n" "\n" "The spacing of these items is controlled by the" " @code{space-alist} property. It contains a list" " @code{break-align-symbol}s with a specification of the" " associated space. The space specification can be\n" "\n" "@table @code\n" "@item (minimum-space . @var{spc}))\n" "Pad space until the distance is @var{spc}.\n" "@item (fixed-space . @var{spc})\n" "Set a fixed space.\n" "@item (semi-fixed-space . @var{spc})\n" "Set a space. Half of it is fixed and half is stretchable." " (does not work at start of line. fixme)\n" "@item (extra-space . @var{spc})\n" "Add @var{spc} amount of space.\n" "@end table\n" "\n" "Special keys for the alist are @code{first-note} and" " @code{next-note}, signifying the first note on a line, and" " the next note halfway a line.\n" "\n" "Rules for this spacing are much more complicated than this." " See [Wanske] page 126--134, [Ross] page 143--147.", /* properties */ "break-align-anchor " "break-align-anchor-alignment " "break-align-symbol " "space-alist " ); ADD_INTERFACE (Break_alignment_interface, "The object that performs break aligment. See" " @ref{break-aligned-interface}.", /* properties */ "positioning-done " "break-align-orders " );<|fim▁end|>
if (g && sym == g->get_property ("break-align-symbol")) { new_elts.push_back (g); writable_elts.erase (writable_elts.begin () + i);
<|file_name|>schedule_generator_tests.py<|end_file_name|><|fim▁begin|>from django.utils.unittest.case import TestCase from scheduler.models import ScheduleGenerator from uni_info.models import Semester, Course class ScheduleGeneratorTest(TestCase): """ Test class for schedule generator, try different courses """ fixtures = ['/scheduler/fixtures/initial_data.json'] def setUp(self): """ Setup common data needed in each unit test """ self.fall_2013_semester = [sem for sem in Semester.objects.all() if sem.name == 'Fall 2013'][0] def test_should_generate_empty_schedule(self): """ Test generator does not crash with empty list as edge case """ course_list = [] generator = ScheduleGenerator(course_list, self.fall_2013_semester) result = generator.generate_schedules() self.assertIsNotNone(result) self.assertEqual(0, len(result)) def test_should_generate_with_1_course(self): """ Test generator with only 1 course as edge case """ soen341 = [s for s in Course.objects.all() if s.course_letters == 'SOEN' and s.course_numbers == '341'][0] course_list = [soen341] generator = ScheduleGenerator(course_list, self.fall_2013_semester) result = generator.generate_schedules() <|fim▁hole|> self.assertEqual(2, len(result)) def test_should_generate_schedule_for_2_course(self): """ Test generator with more than 1 course """ soen341 = [s for s in Course.objects.all() if s.course_letters == 'SOEN' and s.course_numbers == '341'][0] soen287 = [s for s in Course.objects.all() if s.course_letters == 'SOEN' and s.course_numbers == '287'][0] course_list = [soen287, soen341] generator = ScheduleGenerator(course_list, self.fall_2013_semester) result = generator.generate_schedules() self.assertIsNotNone(result) self.assertEqual(4, len(result)) def test_should_not_generate_schedule_for_3_course_conflict(self): """ Test generator with three conflicting courses """ soen341 = [s for s in Course.objects.all() if s.course_letters == 'SOEN' and s.course_numbers == '341'][0] soen342 = [s for s in Course.objects.all() if s.course_letters == 'SOEN' and s.course_numbers == '342'][0] soen287 = [s for s in Course.objects.all() if s.course_letters == 'SOEN' and s.course_numbers == '287'][0] course_list = [soen287, soen341, soen342] generator = ScheduleGenerator(course_list, self.fall_2013_semester) result = generator.generate_schedules() self.assertIsNotNone(result) self.assertEqual(0, len(result)) def test_should_generate_schedule_for_3_course_no_conflict(self): """ Test generator with three courses that has no conflicts """ soen341 = [s for s in Course.objects.all() if s.course_letters == 'SOEN' and s.course_numbers == '341'][0] soen343 = [s for s in Course.objects.all() if s.course_letters == 'SOEN' and s.course_numbers == '343'][0] soen287 = [s for s in Course.objects.all() if s.course_letters == 'SOEN' and s.course_numbers == '287'][0] course_list = [soen287, soen341, soen343] generator = ScheduleGenerator(course_list, self.fall_2013_semester) result = generator.generate_schedules() self.assertIsNotNone(result) self.assertEqual(4, len(result))<|fim▁end|>
self.assertIsNotNone(result)
<|file_name|>robotTestData.js<|end_file_name|><|fim▁begin|>module.exports = { dimension: 'overworld', config: { robotName: 'rob', accountName: 'admin', serverIP: '127.0.0.1', serverPort: 8080, tcpPort: 3001, posX: 4, posY: 4, posZ: 4, orient: 0, raw: true, }, internalInventory: { meta: { 'size': 64, 'side': -1, 'selected': 1 }, slots: [ { side: -1, slotNum: 1, contents: { 'damage': 0, 'hasTag': false, 'label': "Dirt", 'maxDamage': 0, 'maxSize': 64, 'name': "minecraft:dirt", 'size': 64 } }, { side: -1, slotNum: 2, contents: { 'damage': 0, 'hasTag': false, 'label': "Dirt", 'maxDamage': 0, 'maxSize': 64, 'name': "minecraft:dirt", 'size': 37 } }, { side: -1, slotNum: 5, contents: { 'damage': 0, 'hasTag': false, 'label': "Stone", 'maxDamage': 0, 'maxSize': 64, 'name': "minecraft:stone", 'size': 3 } }, { side: -1, slotNum: 7, contents: { 'damage': 0, 'hasTag': false, 'label': "Wooden Sword?", 'maxDamage': 100, 'maxSize': 1, 'name': "minecraft:wooden_sword?", 'size': 1 } }, { side: -1, slotNum: 9, contents: { 'damage': 0, 'hasTag': false, 'label': "Netherrack", 'maxDamage': 0, 'maxSize': 64, 'name': "minecraft:netherrack", 'size': 23 } } ], }, externalInventory: { meta: { 'size': 27, 'side': 3 }, slots: [ { side: 3, slotNum: 1, contents: { 'damage': 0, 'hasTag': false, 'label': "Dirt", 'maxDamage': 0, 'maxSize': 64, 'name': "minecraft:dirt", 'size': 4 } }, { side: 3, slotNum: 2, contents: { 'damage': 0, 'hasTag': false, 'label': "Dirt", 'maxDamage': 0, 'maxSize': 64, 'name': "minecraft:dirt", 'size': 7 } }, { side: 3, slotNum: 5, contents: { 'damage': 0, 'hasTag': false, 'label': "Stone", 'maxDamage': 0, 'maxSize': 64, 'name': "minecraft:stone", 'size': 25 } } ], }, map: { [-2]: { 0: { [-2]: { "hardness": .5, "name": "minecraft:dirt", }, } }, [-1]: { 0: { [-1]: { "hardness": .5, "name": "minecraft:dirt", }, } }, 0: { 0: { 0: { "hardness": .5, "name": "minecraft:dirt", }, 1: { "hardness": .5, "name": "minecraft:dirt", }, 2: { "hardness": .5, "name": "minecraft:dirt", }, }, 1: { 0: { "hardness": .5, "name": "minecraft:dirt", }, 1: { "hardness": .5, "name": "minecraft:dirt", }, 2: { "hardness": .5, "name": "minecraft:dirt", }, }, 2: { 0: { "hardness": .5, "name": "minecraft:dirt", }, 1: { "hardness": .5, "name": "minecraft:dirt", }, 2: { "hardness": .5, "name": "minecraft:dirt", }, }, }, 1: { 0: { 0: { "hardness": .5, "name": "minecraft:dirt", }, 1: { "hardness": .5, "name": "minecraft:dirt", }, 2: { "hardness": .5, "name": "minecraft:dirt", }, }, 1: { 0: { "hardness": .5, "name": "minecraft:dirt", }, 1: { "hardness": 2.5, "name": "minecraft:chest", }, 2: { "hardness": .5, "name": "minecraft:dirt", }, }, 2: { 0: { "hardness": .5, "name": "minecraft:dirt", }, 2: { "hardness": .5, "name": "minecraft:dirt", }, }, }, 2: { 0: { 0: { "hardness": .5, "name": "minecraft:dirt", }, 1: { "hardness": .5, "name": "minecraft:dirt", }, 2: { "hardness": .5, "name": "minecraft:dirt", }, }, 1: { 0: { "hardness": .5, "name": "minecraft:dirt", }, 1: { "hardness": .5, "name": "minecraft:dirt", }, 2: { "hardness": .5, "name": "minecraft:dirt", }, }, 2: { 0: { "hardness": .5, "name": "minecraft:dirt", }, 1: { "hardness": .5, "name": "minecraft:dirt", }, 2: { "hardness": .5,<|fim▁hole|> }, 3: { 0: { 3: { "hardness": .5, "name": "minecraft:dirt", }, } }, 4: { 0: { 4: { "hardness": .5, "name": "minecraft:dirt", }, } }, 5: { 0: { 5: { "hardness": .5, "name": "minecraft:dirt", }, } }, }, components: { '0c9a47e1-d211-4d73-ad9d-f3f88a6d0ee9': 'keyboard', '25945f78-9f94-4bd5-9211-cb37b352ebf7': 'filesystem', '2a2da751-3baa-4feb-9fa1-df76016ff390': 'inventory_controller', '5d48c968-e6f5-474e-865f-524e803678a7': 'filesystem', '5f6a65bd-98c1-4cf5-bbe5-3e0b8b23662d': 'internet', '5fffe6b3-e619-4f4f-bc9f-3ddb028afe02': 'filesystem', '73aedc53-517d-4844-9cb2-645c8d7667fc': 'screen', '8be5872b-9a01-4403-b853-d88fe6f17fc3': 'eeprom', '9d40d271-718e-45cc-9522-dc562320a78b': 'crafting', 'c8181ac9-9cc2-408e-b214-3acbce9fe1c6': 'chunkloader', 'c8fe2fde-acb0-4188-86ef-4340de011e25': 'robot', 'ce229fd1-d63d-4778-9579-33f05fd6af9a': 'gpu', 'fdc85abb-316d-4aca-a1be-b7f947016ba1': 'computer', 'ff1699a6-ae72-4f74-bf1c-88ac6901d56e': 'geolyzer' }, };<|fim▁end|>
"name": "minecraft:dirt", }, },
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.core.urlresolvers import reverse from django.db import models from midnight_main.models import BaseTree, Base, BreadCrumbsMixin, BaseComment from ckeditor.fields import RichTextField from django.utils.translation import ugettext_lazy as _ from sorl.thumbnail import ImageField from mptt.fields import TreeManyToManyField class Section(BreadCrumbsMixin, BaseTree): """ Модель категории новостей """ title = models.CharField(max_length=255, verbose_name=_('Title')) slug = models.SlugField(max_length=255, unique=True, verbose_name=_('Slug')) sort = models.IntegerField(default=500, verbose_name=_('Sort')) metatitle = models.CharField(max_length=2000, blank=True, verbose_name=_('Title')) keywords = models.CharField(max_length=2000, blank=True, verbose_name=_('Keywords')) description = models.CharField(max_length=2000, blank=True, verbose_name=_('Description')) def get_absolute_url(self): return reverse('midnight_news:news_list', kwargs={'slug': self.slug}) def __str__(self): return self.title class MPTTMeta: order_insertion_by = ['sort'] class Meta: verbose_name = _('NewsSection') verbose_name_plural = _('NewsSections') class News(Base): """ Модель новости """ title = models.CharField(max_length=255, verbose_name=_('Title')) slug = models.SlugField(max_length=255, unique=True, verbose_name=_('Slug')) date = models.DateField(verbose_name=_('Date'), blank=False) sections = TreeManyToManyField(Section, verbose_name=_('Sections')) image = ImageField(upload_to='news', verbose_name=_('Image'), blank=True) annotation = models.TextField(blank=True, verbose_name=_('Annotation')) text = RichTextField(blank=True, verbose_name=_('Text'))<|fim▁hole|> metatitle = models.CharField(max_length=2000, blank=True, verbose_name=_('Title')) keywords = models.CharField(max_length=2000, blank=True, verbose_name=_('Keywords')) description = models.CharField(max_length=2000, blank=True, verbose_name=_('Description')) def get_absolute_url(self): return reverse('midnight_news:news_detail', kwargs={'section_slug': self.sections.all()[0].slug, 'slug': self.slug}) def __str__(self): return self.title class Meta: verbose_name = _('NewsItem') verbose_name_plural = _('News') class NewsComment(BaseComment): """ Модель комментария к новости """ obj = models.ForeignKey(News) class Meta: verbose_name = _('NewsComment') verbose_name_plural = _('NewsComments')<|fim▁end|>
comments = models.BooleanField(default=False, verbose_name=_('Comments'))
<|file_name|>settings.js<|end_file_name|><|fim▁begin|>const initialState = { country: 'es', language: 'es-ES' } const settings = (state = initialState, action) => { switch (action.type) { default:<|fim▁hole|> } } export default settings<|fim▁end|>
return state
<|file_name|>courseware.py<|end_file_name|><|fim▁begin|>""" Courseware page. """ from bok_choy.page_object import PageObject, unguarded from bok_choy.promise import EmptyPromise import re from selenium.webdriver.common.action_chains import ActionChains from common.test.acceptance.pages.lms.bookmarks import BookmarksPage from common.test.acceptance.pages.lms.course_page import CoursePage class CoursewarePage(CoursePage): """ Course info. """ url_path = "courseware/" xblock_component_selector = '.vert .xblock' # TODO: TNL-6546: Remove sidebar selectors section_selector = '.chapter' subsection_selector = '.chapter-content-container a' def __init__(self, browser, course_id): super(CoursewarePage, self).__init__(browser, course_id) self.nav = CourseNavPage(browser, self) def is_browser_on_page(self): return self.q(css='.course-content').present @property def chapter_count_in_navigation(self): """ Returns count of chapters available on LHS navigation. """ return len(self.q(css='nav.course-navigation a.chapter')) # TODO: TNL-6546: Remove and find callers. @property def num_sections(self): """ Return the number of sections in the sidebar on the page """ return len(self.q(css=self.section_selector)) # TODO: TNL-6546: Remove and find callers. @property def num_subsections(self): """ Return the number of subsections in the sidebar on the page, including in collapsed sections """ return len(self.q(css=self.subsection_selector)) @property def xblock_components(self): """ Return the xblock components within the unit on the page. """ return self.q(css=self.xblock_component_selector) @property def num_xblock_components(self): """ Return the number of rendered xblocks within the unit on the page """ return len(self.xblock_components) def xblock_component_type(self, index=0): """ Extract rendered xblock component type. Returns: str: xblock module type index: which xblock to query, where the index is the vertical display within the page (default is 0) """ return self.q(css=self.xblock_component_selector).attrs('data-block-type')[index] def xblock_component_html_content(self, index=0): """ Extract rendered xblock component html content. Returns: str: xblock module html content index: which xblock to query, where the index is the vertical display within the page (default is 0) """ # When Student Notes feature is enabled, it looks for the content inside # `.edx-notes-wrapper-content` element (Otherwise, you will get an # additional html related to Student Notes). element = self.q(css='{} .edx-notes-wrapper-content'.format(self.xblock_component_selector)) if element.first: return element.attrs('innerHTML')[index].strip() else: return self.q(css=self.xblock_component_selector).attrs('innerHTML')[index].strip() def verify_tooltips_displayed(self): """ Verify that all sequence navigation bar tooltips are being displayed upon mouse hover. If a tooltip does not appear, raise a BrokenPromise. """ for index, tab in enumerate(self.q(css='#sequence-list > li')): ActionChains(self.browser).move_to_element(tab).perform() self.wait_for_element_visibility( '#tab_{index} > .sequence-tooltip'.format(index=index), 'Tab {index} should appear'.format(index=index) ) @property def course_license(self): """ Returns the course license text, if present. Else returns None. """ element = self.q(css="#content .container-footer .course-license") if element.is_present(): return element.text[0] return None def go_to_sequential_position(self, sequential_position): """ Within a section/subsection navigate to the sequential position specified by `sequential_position`. Arguments: sequential_position (int): position in sequential bar """ def is_at_new_position(): """ Returns whether the specified tab has become active. It is defensive against the case where the page is still being loaded. """ active_tab = self._active_sequence_tab try: return active_tab and int(active_tab.attrs('data-element')[0]) == sequential_position except IndexError: return False sequential_position_css = '#sequence-list #tab_{0}'.format(sequential_position - 1) self.q(css=sequential_position_css).first.click() EmptyPromise(is_at_new_position, "Position navigation fulfilled").fulfill() @property def sequential_position(self): """ Returns the position of the active tab in the sequence. """ tab_id = self._active_sequence_tab.attrs('id')[0] return int(tab_id.split('_')[1]) @property def _active_sequence_tab(self): # pylint: disable=missing-docstring return self.q(css='#sequence-list .nav-item.active') @property def is_next_button_enabled(self): # pylint: disable=missing-docstring return not self.q(css='.sequence-nav > .sequence-nav-button.button-next.disabled').is_present() @property def is_previous_button_enabled(self): # pylint: disable=missing-docstring return not self.q(css='.sequence-nav > .sequence-nav-button.button-previous.disabled').is_present() def click_next_button_on_top(self): # pylint: disable=missing-docstring self._click_navigation_button('sequence-nav', 'button-next') def click_next_button_on_bottom(self): # pylint: disable=missing-docstring self._click_navigation_button('sequence-bottom', 'button-next') def click_previous_button_on_top(self): # pylint: disable=missing-docstring self._click_navigation_button('sequence-nav', 'button-previous') def click_previous_button_on_bottom(self): # pylint: disable=missing-docstring self._click_navigation_button('sequence-bottom', 'button-previous') def _click_navigation_button(self, top_or_bottom_class, next_or_previous_class): """ Clicks the navigation button, given the respective CSS classes. """ previous_tab_id = self._active_sequence_tab.attrs('data-id')[0] def is_at_new_tab_id(): """ Returns whether the active tab has changed. It is defensive against the case where the page is still being loaded. """ active_tab = self._active_sequence_tab try: return active_tab and previous_tab_id != active_tab.attrs('data-id')[0] except IndexError: return False self.q( css='.{} > .sequence-nav-button.{}'.format(top_or_bottom_class, next_or_previous_class) ).first.click() EmptyPromise(is_at_new_tab_id, "Button navigation fulfilled").fulfill() @property def can_start_proctored_exam(self): """ Returns True if the timed/proctored exam timer bar is visible on the courseware. """ return self.q(css='button.start-timed-exam[data-start-immediately="false"]').is_present() def start_timed_exam(self): """ clicks the start this timed exam link """ self.q(css=".xblock-student_view .timed-exam .start-timed-exam").first.click() self.wait_for_element_presence(".proctored_exam_status .exam-timer", "Timer bar") def stop_timed_exam(self): """ clicks the stop this timed exam link """ self.q(css=".proctored_exam_status button.exam-button-turn-in-exam").first.click() self.wait_for_element_absence(".proctored_exam_status .exam-button-turn-in-exam", "End Exam Button gone") self.wait_for_element_presence("button[name='submit-proctored-exam']", "Submit Exam Button") self.q(css="button[name='submit-proctored-exam']").first.click() self.wait_for_element_absence(".proctored_exam_status .exam-timer", "Timer bar") def start_proctored_exam(self): """ clicks the start this timed exam link """ self.q(css='button.start-timed-exam[data-start-immediately="false"]').first.click() # Wait for the unique exam code to appear. # self.wait_for_element_presence(".proctored-exam-code", "unique exam code") def has_submitted_exam_message(self): """ Returns whether the "you have submitted your exam" message is present. This being true implies "the exam contents and results are hidden". """ return self.q(css="div.proctored-exam.completed").visible def content_hidden_past_due_date(self): """ Returns whether the "the due date for this ___ has passed" message is present. ___ is the type of the hidden content, and defaults to subsection. This being true implies "the ___ contents are hidden because their due date has passed". """ message = "this assignment is no longer available" if self.q(css="div.seq_content").is_present(): return False for html in self.q(css="div.hidden-content").html: if message in html: return True return False @property def entrance_exam_message_selector(self): """ Return the entrance exam status message selector on the top of courseware page. """ return self.q(css='#content .container section.course-content .sequential-status-message') def has_entrance_exam_message(self): """ Returns boolean indicating presence entrance exam status message container div. """ return self.entrance_exam_message_selector.is_present() def has_passed_message(self): """ Returns boolean indicating presence of passed message. """ return self.entrance_exam_message_selector.is_present() \ and "You have passed the entrance exam" in self.entrance_exam_message_selector.text[0] def has_banner(self): """ Returns boolean indicating presence of banner """ return self.q(css='.pattern-library-shim').is_present() @property def is_timer_bar_present(self): """ Returns True if the timed/proctored exam timer bar is visible on the courseware. """ return self.q(css=".proctored_exam_status .exam-timer").is_present() def active_usage_id(self): """ Returns the usage id of active sequence item """ get_active = lambda el: 'active' in el.get_attribute('class') attribute_value = lambda el: el.get_attribute('data-id') return self.q(css='#sequence-list .nav-item').filter(get_active).map(attribute_value).results[0] @property def breadcrumb(self): """ Return the course tree breadcrumb shown above the sequential bar """ return [part.strip() for part in self.q(css='.path .position').text[0].split('>')] def unit_title_visible(self): """ Check if unit title is visible """ return self.q(css='.unit-title').visible def bookmark_button_visible(self): """ Check if bookmark button is visible """ EmptyPromise(lambda: self.q(css='.bookmark-button').visible, "Bookmark button visible").fulfill() return True @property def bookmark_button_state(self): """ Return `bookmarked` if button is in bookmarked state else '' """ return 'bookmarked' if self.q(css='.bookmark-button.bookmarked').present else '' @property def bookmark_icon_visible(self): """ Check if bookmark icon is visible on active sequence nav item """ return self.q(css='.active .bookmark-icon').visible def click_bookmark_unit_button(self): """ Bookmark a unit by clicking on Bookmark button """ previous_state = self.bookmark_button_state self.q(css='.bookmark-button').first.click() EmptyPromise(lambda: self.bookmark_button_state != previous_state, "Bookmark button toggled").fulfill() # TODO: TNL-6546: Remove this helper function def click_bookmarks_button(self): """ Click on Bookmarks button """ self.q(css='.bookmarks-list-button').first.click() bookmarks_page = BookmarksPage(self.browser, self.course_id) bookmarks_page.visit() class CoursewareSequentialTabPage(CoursePage): """ Courseware Sequential page """ def __init__(self, browser, course_id, chapter, subsection, position): super(CoursewareSequentialTabPage, self).__init__(browser, course_id) self.url_path = "courseware/{}/{}/{}".format(chapter, subsection, position) def is_browser_on_page(self): return self.q(css='nav.sequence-list-wrapper').present def get_selected_tab_content(self): """ return the body of the sequential currently selected """ return self.q(css='#seq_content .xblock').text[0] class CourseNavPage(PageObject): """ Handles navigation on the courseware pages, including sequence navigation and breadcrumbs. """ url = None def __init__(self, browser, parent_page): super(CourseNavPage, self).__init__(browser) self.parent_page = parent_page # TODO: TNL-6546: Remove the following self.unified_course_view = False def is_browser_on_page(self): return self.parent_page.is_browser_on_page # TODO: TNL-6546: Remove method, outline no longer on courseware page @property def sections(self): """ Return a dictionary representation of sections and subsections. Example: { 'Introduction': ['Course Overview'], 'Week 1': ['Lesson 1', 'Lesson 2', 'Homework'] 'Final Exam': ['Final Exam'] }<|fim▁hole|> # Dict to store the result nav_dict = dict() section_titles = self._section_titles() # Get the section titles for each chapter for sec_index, sec_title in enumerate(section_titles): if len(section_titles) < 1: self.warning("Could not find subsections for '{0}'".format(sec_title)) else: # Add one to convert list index (starts at 0) to CSS index (starts at 1) nav_dict[sec_title] = self._subsection_titles(sec_index + 1) return nav_dict @property def sequence_items(self): """ Return a list of sequence items on the page. Sequence items are one level below subsections in the course nav. Example return value: ['Chemical Bonds Video', 'Practice Problems', 'Homework'] """ seq_css = 'ol#sequence-list>li>.nav-item>.sequence-tooltip' return self.q(css=seq_css).map(self._clean_seq_titles).results # TODO: TNL-6546: Remove method, outline no longer on courseware page def go_to_section(self, section_title, subsection_title): """ Go to the section in the courseware. Every section must have at least one subsection, so specify both the section and subsection title. Example: go_to_section("Week 1", "Lesson 1") """ # For test stability, disable JQuery animations (opening / closing menus) self.browser.execute_script("jQuery.fx.off = true;") # Get the section by index try: sec_index = self._section_titles().index(section_title) except ValueError: self.warning("Could not find section '{0}'".format(section_title)) return # Click the section to ensure it's open (no harm in clicking twice if it's already open) # Add one to convert from list index to CSS index section_css = '.course-navigation .chapter:nth-of-type({0})'.format(sec_index + 1) self.q(css=section_css).first.click() # Get the subsection by index try: subsec_index = self._subsection_titles(sec_index + 1).index(subsection_title) except ValueError: msg = "Could not find subsection '{0}' in section '{1}'".format(subsection_title, section_title) self.warning(msg) return # Convert list indices (start at zero) to CSS indices (start at 1) subsection_css = ( ".course-navigation .chapter-content-container:nth-of-type({0}) " ".menu-item:nth-of-type({1})" ).format(sec_index + 1, subsec_index + 1) # Click the subsection and ensure that the page finishes reloading self.q(css=subsection_css).first.click() self._on_section_promise(section_title, subsection_title).fulfill() def go_to_vertical(self, vertical_title): """ Within a section/subsection, navigate to the vertical with `vertical_title`. """ # Get the index of the item in the sequence all_items = self.sequence_items try: seq_index = all_items.index(vertical_title) except ValueError: msg = "Could not find sequential '{0}'. Available sequentials: [{1}]".format( vertical_title, ", ".join(all_items) ) self.warning(msg) else: # Click on the sequence item at the correct index # Convert the list index (starts at 0) to a CSS index (starts at 1) seq_css = "ol#sequence-list>li:nth-of-type({0})>.nav-item".format(seq_index + 1) self.q(css=seq_css).first.click() # Click triggers an ajax event self.wait_for_ajax() # TODO: TNL-6546: Remove method, outline no longer on courseware page def _section_titles(self): """ Return a list of all section titles on the page. """ chapter_css = '.course-navigation .chapter .group-heading' return self.q(css=chapter_css).map(lambda el: el.text.strip()).results # TODO: TNL-6546: Remove method, outline no longer on courseware page def _subsection_titles(self, section_index): """ Return a list of all subsection titles on the page for the section at index `section_index` (starts at 1). """ # Retrieve the subsection title for the section # Add one to the list index to get the CSS index, which starts at one subsection_css = ( ".course-navigation .chapter-content-container:nth-of-type({0}) " ".menu-item a p:nth-of-type(1)" ).format(section_index) # If the element is visible, we can get its text directly # Otherwise, we need to get the HTML # It *would* make sense to always get the HTML, but unfortunately # the open tab has some child <span> tags that we don't want. return self.q( css=subsection_css ).map( lambda el: el.text.strip().split('\n')[0] if el.is_displayed() else el.get_attribute('innerHTML').strip() ).results # TODO: TNL-6546: Remove method, outline no longer on courseware page def _on_section_promise(self, section_title, subsection_title): """ Return a `Promise` that is fulfilled when the user is on the correct section and subsection. """ desc = "currently at section '{0}' and subsection '{1}'".format(section_title, subsection_title) return EmptyPromise( lambda: self.is_on_section(section_title, subsection_title), desc ) def go_to_outline(self): """ Navigates using breadcrumb to the course outline on the course home page. Returns CourseHomePage page object. """ # To avoid circular dependency, importing inside the function from common.test.acceptance.pages.lms.course_home import CourseHomePage course_home_page = CourseHomePage(self.browser, self.parent_page.course_id) self.q(css='.path a').click() course_home_page.wait_for_page() return course_home_page @unguarded def is_on_section(self, section_title, subsection_title): """ Return a boolean indicating whether the user is on the section and subsection with the specified titles. """ # TODO: TNL-6546: Remove if/else; always use unified_course_view version (if) if self.unified_course_view: # breadcrumb location of form: "SECTION_TITLE > SUBSECTION_TITLE > SEQUENTIAL_TITLE" bread_crumb_current = self.q(css='.position').text if len(bread_crumb_current) != 1: self.warning("Could not find the current bread crumb with section and subsection.") return False return bread_crumb_current[0].strip().startswith(section_title + ' > ' + subsection_title + ' > ') else: # This assumes that the currently expanded section is the one we're on # That's true right after we click the section/subsection, but not true in general # (the user could go to a section, then expand another tab). current_section_list = self.q(css='.course-navigation .chapter.is-open .group-heading').text current_subsection_list = self.q(css='.course-navigation .chapter-content-container .menu-item.active a p').text if len(current_section_list) == 0: self.warning("Could not find the current section") return False elif len(current_subsection_list) == 0: self.warning("Could not find current subsection") return False else: return ( current_section_list[0].strip() == section_title and current_subsection_list[0].strip().split('\n')[0] == subsection_title ) # Regular expression to remove HTML span tags from a string REMOVE_SPAN_TAG_RE = re.compile(r'</span>(.+)<span') def _clean_seq_titles(self, element): """ Clean HTML of sequence titles, stripping out span tags and returning the first line. """ return self.REMOVE_SPAN_TAG_RE.search(element.get_attribute('innerHTML')).groups()[0].strip() # TODO: TNL-6546: Remove. This is no longer needed. @property def active_subsection_url(self): """ return the url of the active subsection in the left nav """ return self.q(css='.chapter-content-container .menu-item.active a').attrs('href')[0] # TODO: TNL-6546: Remove all references to self.unified_course_view # TODO: TNL-6546: Remove the following function def visit_unified_course_view(self): # use unified_course_view version of the nav self.unified_course_view = True # reload the same page with the unified course view self.browser.get(self.browser.current_url + "&unified_course_view=1") self.wait_for_page()<|fim▁end|>
You can use these titles in `go_to_section` to navigate to the section. """
<|file_name|>bitcoin_hi_IN.ts<|end_file_name|><|fim▁begin|><TS language="hi_IN" version="2.1"> <context> <name>AddressBookPage</name> <message> <source>Create a new address</source> <translation>नया पता लिखिए !</translation> </message> <message> <source>Copy the currently selected address to the system clipboard</source> <translation>चुनिन्दा पते को सिस्टम क्लिपबोर्ड पर कापी करे !</translation> </message> <message> <source>&amp;Copy Address</source> <translation>&amp;पता कॉपी करे</translation> </message> <message> <source>&amp;Delete</source> <translation>&amp;मिटाए !!</translation> </message> <message> <source>Copy &amp;Label</source> <translation>&amp;लेबल कॉपी करे </translation> </message> <message> <source>&amp;Edit</source> <translation>&amp;एडिट</translation> </message> <message> <source>Comma separated file (*.csv)</source> <translation>Comma separated file (*.csv)</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <source>Label</source> <translation>लेबल</translation> </message> <message> <source>Address</source> <translation>पता</translation> </message> <message> <source>(no label)</source> <translation>(कोई लेबल नही !)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <source>Enter passphrase</source> <translation>पहचान शब्द/अक्षर डालिए !</translation> </message> <message> <source>New passphrase</source> <translation>नया पहचान शब्द/अक्षर डालिए !</translation> </message> <message> <source>Repeat new passphrase</source> <translation>दोबारा नया पहचान शब्द/अक्षर डालिए !</translation> </message> <message> <source>Encrypt wallet</source> <translation>एनक्रिप्ट वॉलेट !</translation> </message> <message> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>वॉलेट खोलने के आपका वॉलेट पहचान शब्द्‌/अक्षर चाईए !</translation> </message> <message> <source>Unlock wallet</source> <translation>वॉलेट खोलिए</translation> </message> <message> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>वॉलेट डीक्रिप्ट( विकोड) करने के लिए आपका वॉलेट पहचान शब्द्‌/अक्षर चाईए !</translation> </message> <message> <source>Decrypt wallet</source> <translation> डीक्रिप्ट वॉलेट</translation> </message> <message> <source>Change passphrase</source> <translation>पहचान शब्द/अक्षर बदलिये !</translation> </message> <message> <source>Confirm wallet encryption</source> <translation>वॉलेट एनक्रिपशन को प्रमाणित कीजिए !</translation> </message> <message> <source>Wallet encrypted</source> <translation>वॉलेट एनक्रिप्ट हो गया !</translation> </message> <message> <source>Wallet encryption failed</source> <translation>वॉलेट एनक्रिप्ट नही हुआ!</translation> </message> <message> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>वॉलेट एनक्रिपशन नाकाम हो गया इंटर्नल एरर की वजह से! आपका वॉलेट एनक्रीपत नही हुआ है!</translation> </message> <message> <source>The supplied passphrases do not match.</source> <translation>आपके द्वारा डाले गये पहचान शब्द/अक्षर मिलते नही है !</translation> </message> <message> <source>Wallet unlock failed</source> <translation>वॉलेट का लॉक नही खुला !</translation> </message> <message> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>वॉलेट डीक्रिप्ट करने के लिए जो पहचान शब्द/अक्षर डाले गये है वो सही नही है!</translation> </message> <message> <source>Wallet decryption failed</source> <translation>वॉलेट का डीक्रिप्ट-ष्ण असफल !</translation> </message> </context> <context> <name>BanTableModel</name> </context> <context> <name>BitcoinGUI</name> <message> <source>Synchronizing with network...</source> <translation>नेटवर्क से समकालिक (मिल) रहा है ...</translation> </message> <message> <source>&amp;Overview</source> <translation>&amp;विवरण</translation> </message> <message> <source>Show general overview of wallet</source> <translation>वॉलेट का सामानया विवरण दिखाए !</translation> </message> <message> <source>&amp;Transactions</source> <translation>&amp; लेन-देन </translation> </message> <message> <source>Browse transaction history</source> <translation>देखिए पुराने लेन-देन के विवरण !</translation> </message> <message> <source>E&amp;xit</source> <translation>बाहर जायें</translation> </message> <message> <source>Quit application</source> <translation>अप्लिकेशन से बाहर निकलना !</translation> </message> <message> <source>&amp;Options...</source> <translation>&amp;विकल्प</translation> </message> <message> <source>&amp;Backup Wallet...</source> <translation>&amp;बैकप वॉलेट</translation> </message> <message> <source>Change the passphrase used for wallet encryption</source> <translation>पहचान शब्द/अक्षर जो वॉलेट एनक्रिपशन के लिए इस्तेमाल किया है उसे बदलिए!</translation> </message> <message> <source>FairCoin</source> <translation>बीटकोइन</translation> </message> <message> <source>Wallet</source> <translation>वॉलेट</translation> </message> <message> <source>&amp;File</source> <translation>&amp;फाइल</translation> </message> <message> <source>&amp;Settings</source> <translation>&amp;सेट्टिंग्स</translation> </message> <message> <source>&amp;Help</source> <translation>&amp;मदद</translation> </message> <message> <source>Tabs toolbar</source> <translation>टैबस टूलबार</translation> </message> <message> <source>%1 behind</source> <translation>%1 पीछे</translation> </message> <message> <source>Error</source> <translation>भूल</translation> </message> <message> <source>Warning</source> <translation>चेतावनी</translation> </message> <message> <source>Information</source> <translation>जानकारी</translation> </message> <message> <source>Up to date</source> <translation>नवीनतम</translation> </message> <message> <source>Sent transaction</source> <translation>भेजी ट्रांजक्शन</translation> </message> <message> <source>Incoming transaction</source> <translation>प्राप्त हुई ट्रांजक्शन</translation> </message> <message> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>वॉलेट एन्क्रिप्टेड है तथा अभी लॉक्ड नहीं है</translation> </message> <message> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>वॉलेट एन्क्रिप्टेड है तथा अभी लॉक्ड है</translation> </message> </context> <context> <name>ClientModel</name> </context> <context> <name>CoinControlDialog</name> <message> <source>Amount:</source> <translation>राशि :</translation> </message> <message> <source>Amount</source> <translation>राशि</translation> </message> <message> <source>Date</source> <translation>taareek</translation> </message> <message> <source>Confirmed</source> <translation>पक्का</translation> </message> <message> <source>Copy address</source> <translation>पता कॉपी करे</translation> </message> <message> <source>Copy label</source> <translation>लेबल कॉपी करे </translation> </message> <message> <source>Copy amount</source> <translation>कॉपी राशि</translation> </message> <message> <source>(no label)</source> <translation>(कोई लेबल नही !)</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <source>Edit Address</source> <translation>पता एडिट करना</translation> </message> <message> <source>&amp;Label</source> <translation>&amp;लेबल</translation> </message> <message> <source>&amp;Address</source> <translation>&amp;पता</translation> </message> <message> <source>New receiving address</source> <translation>नया स्वीकार्य पता</translation> </message> <message> <source>New sending address</source> <translation>नया भेजने वाला पता</translation> </message> <message> <source>Edit receiving address</source> <translation>एडिट स्वीकार्य पता </translation> </message> <message> <source>Edit sending address</source> <translation>एडिट भेजने वाला पता</translation> </message> <message> <source>The entered address "%1" is already in the address book.</source> <translation>डाला गया पता "%1" एड्रेस बुक में पहले से ही मोजूद है|</translation> </message> <message> <source>Could not unlock wallet.</source> <translation>वॉलेट को unlock नहीं किया जा सकता|</translation> </message> <message> <source>New key generation failed.</source> <translation>नयी कुंजी का निर्माण असफल रहा|</translation> </message> </context> <context> <name>FreespaceChecker</name> </context> <context> <name>HelpMessageDialog</name> <message> <source>version</source> <translation>संस्करण</translation> </message> <message> <source>Usage:</source> <translation>खपत :</translation> </message> </context> <context> <name>Intro</name> <message> <source>Error</source> <translation>भूल</translation> </message> </context> <context> <name>OpenURIDialog</name> </context> <context> <name>OptionsDialog</name> <message> <source>Options</source> <translation>विकल्प</translation> </message> <message> <source>W&amp;allet</source> <translation>वॉलेट</translation> </message> <message> <source>&amp;OK</source> <translation>&amp;ओके</translation> </message> <message> <source>&amp;Cancel</source> <translation>&amp;कैन्सल</translation> </message> </context> <context> <name>OverviewPage</name> <message> <source>Form</source> <translation>फार्म</translation> </message> </context> <context> <name>PaymentServer</name> </context> <context> <name>PeerTableModel</name> </context> <context> <name>QObject</name> <message> <source>Amount</source> <translation>राशि</translation> </message> <message> <source>N/A</source> <translation>लागू नही </translation> </message> </context> <context> <name>QRImageWidget</name> </context> <context> <name>RPCConsole</name> <message> <source>N/A</source> <translation>लागू नही </translation> </message> <message> <source>&amp;Information</source> <translation>जानकारी</translation> </message> </context> <context> <name>ReceiveCoinsDialog</name> <message> <source>&amp;Amount:</source> <translation>राशि :</translation> </message> <message> <source>&amp;Label:</source> <translation>लेबल:</translation> </message> <message> <source>Copy label</source> <translation>लेबल कॉपी करे </translation> </message> <message> <source>Copy amount</source> <translation>कॉपी राशि</translation> </message> </context> <context> <name>ReceiveRequestDialog</name> <message> <source>Copy &amp;Address</source> <translation>&amp;पता कॉपी करे</translation> </message> <message> <source>Address</source> <translation>पता</translation> </message> <message> <source>Amount</source> <translation>राशि</translation> </message> <message> <source>Label</source> <translation>लेबल</translation> </message><|fim▁hole|><context> <name>RecentRequestsTableModel</name> <message> <source>Date</source> <translation>taareek</translation> </message> <message> <source>Label</source> <translation>लेबल</translation> </message> <message> <source>Amount</source> <translation>राशि</translation> </message> <message> <source>(no label)</source> <translation>(कोई लेबल नही !)</translation> </message> </context> <context> <name>SendCoinsDialog</name> <message> <source>Send Coins</source> <translation>सिक्के भेजें|</translation> </message> <message> <source>Amount:</source> <translation>राशि :</translation> </message> <message> <source>Send to multiple recipients at once</source> <translation>एक साथ कई प्राप्तकर्ताओं को भेजें</translation> </message> <message> <source>Balance:</source> <translation>बाकी रकम :</translation> </message> <message> <source>Confirm the send action</source> <translation>भेजने की पुष्टि करें</translation> </message> <message> <source>Confirm send coins</source> <translation>सिक्के भेजने की पुष्टि करें</translation> </message> <message> <source>Copy amount</source> <translation>कॉपी राशि</translation> </message> <message> <source>The amount to pay must be larger than 0.</source> <translation>भेजा गया अमाउंट शुन्य से अधिक होना चाहिए|</translation> </message> <message> <source>(no label)</source> <translation>(कोई लेबल नही !)</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <source>A&amp;mount:</source> <translation>अमाउंट:</translation> </message> <message> <source>Pay &amp;To:</source> <translation>प्राप्तकर्ता:</translation> </message> <message> <source>Enter a label for this address to add it to your address book</source> <translation>आपकी एड्रेस बुक में इस एड्रेस के लिए एक लेबल लिखें</translation> </message> <message> <source>&amp;Label:</source> <translation>लेबल:</translation> </message> <message> <source>Alt+A</source> <translation>Alt-A</translation> </message> <message> <source>Paste address from clipboard</source> <translation>Clipboard से एड्रेस paste करें</translation> </message> <message> <source>Alt+P</source> <translation>Alt-P</translation> </message> <message> <source>Pay To:</source> <translation>प्राप्तकर्ता:</translation> </message> </context> <context> <name>ShutdownWindow</name> </context> <context> <name>SignVerifyMessageDialog</name> <message> <source>Alt+A</source> <translation>Alt-A</translation> </message> <message> <source>Paste address from clipboard</source> <translation>Clipboard से एड्रेस paste करें</translation> </message> <message> <source>Alt+P</source> <translation>Alt-P</translation> </message> <message> <source>Signature</source> <translation>हस्ताक्षर</translation> </message> </context> <context> <name>SplashScreen</name> <message> <source>[testnet]</source> <translation>[टेस्टनेट]</translation> </message> </context> <context> <name>TrafficGraphWidget</name> </context> <context> <name>TransactionDesc</name> <message> <source>Open until %1</source> <translation>खुला है जबतक %1</translation> </message> <message> <source>%1/unconfirmed</source> <translation>%1/अपुष्ट</translation> </message> <message> <source>%1 confirmations</source> <translation>%1 पुष्टियाँ</translation> </message> <message> <source>Date</source> <translation>taareek</translation> </message> <message> <source>Transaction ID</source> <translation>ID</translation> </message> <message> <source>Amount</source> <translation>राशि</translation> </message> <message> <source>true</source> <translation>सही</translation> </message> <message> <source>false</source> <translation>ग़लत</translation> </message> <message> <source>, has not been successfully broadcast yet</source> <translation>, अभी तक सफलतापूर्वक प्रसारित नहीं किया गया है</translation> </message> <message> <source>unknown</source> <translation>अज्ञात</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <source>Transaction details</source> <translation>लेन-देन का विवरण</translation> </message> <message> <source>This pane shows a detailed description of the transaction</source> <translation> ये खिड़की आपको लेन-देन का विस्तृत विवरण देगी !</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <source>Date</source> <translation>taareek</translation> </message> <message> <source>Type</source> <translation>टाइप</translation> </message> <message> <source>Open until %1</source> <translation>खुला है जबतक %1</translation> </message> <message> <source>Confirmed (%1 confirmations)</source> <translation>पक्के ( %1 पक्का करना)</translation> </message> <message> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>यह ब्लॉक किसी भी और नोड को मिला नही है ! शायद यह ब्लॉक कोई भी नोड स्वीकारे गा नही !</translation> </message> <message> <source>Generated but not accepted</source> <translation>जेनरेट किया गया किंतु स्वीकारा नही गया !</translation> </message> <message> <source>Label</source> <translation>लेबल</translation> </message> <message> <source>Received with</source> <translation>स्वीकार करना</translation> </message> <message> <source>Received from</source> <translation>स्वीकार्य ओर से</translation> </message> <message> <source>Sent to</source> <translation>भेजा गया</translation> </message> <message> <source>Payment to yourself</source> <translation>भेजा खुद को भुगतान</translation> </message> <message> <source>Mined</source> <translation>माइंड</translation> </message> <message> <source>(n/a)</source> <translation>(लागू नहीं)</translation> </message> <message> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>ट्रांसेक्शन स्तिथि| पुष्टियों की संख्या जानने के लिए इस जगह पर माउस लायें|</translation> </message> <message> <source>Date and time that the transaction was received.</source> <translation>तारीख तथा समय जब ये ट्रांसेक्शन प्राप्त हुई थी|</translation> </message> <message> <source>Type of transaction.</source> <translation>ट्रांसेक्शन का प्रकार|</translation> </message> <message> <source>Amount removed from or added to balance.</source> <translation>अमाउंट बैलेंस से निकला या जमा किया गया |</translation> </message> </context> <context> <name>TransactionView</name> <message> <source>All</source> <translation>सभी</translation> </message> <message> <source>Today</source> <translation>आज</translation> </message> <message> <source>This week</source> <translation>इस हफ्ते</translation> </message> <message> <source>This month</source> <translation>इस महीने</translation> </message> <message> <source>Last month</source> <translation>पिछले महीने</translation> </message> <message> <source>This year</source> <translation>इस साल</translation> </message> <message> <source>Range...</source> <translation>विस्तार...</translation> </message> <message> <source>Received with</source> <translation>स्वीकार करना</translation> </message> <message> <source>Sent to</source> <translation>भेजा गया</translation> </message> <message> <source>To yourself</source> <translation>अपनेआप को</translation> </message> <message> <source>Mined</source> <translation>माइंड</translation> </message> <message> <source>Other</source> <translation>अन्य</translation> </message> <message> <source>Enter address or label to search</source> <translation>ढूँदने के लिए कृपा करके पता या लेबल टाइप करे !</translation> </message> <message> <source>Min amount</source> <translation>लघुत्तम राशि</translation> </message> <message> <source>Copy address</source> <translation>पता कॉपी करे</translation> </message> <message> <source>Copy label</source> <translation>लेबल कॉपी करे </translation> </message> <message> <source>Copy amount</source> <translation>कॉपी राशि</translation> </message> <message> <source>Edit label</source> <translation>एडिट लेबल</translation> </message> <message> <source>Comma separated file (*.csv)</source> <translation>Comma separated file (*.csv)</translation> </message> <message> <source>Confirmed</source> <translation>पक्का</translation> </message> <message> <source>Date</source> <translation>taareek</translation> </message> <message> <source>Type</source> <translation>टाइप</translation> </message> <message> <source>Label</source> <translation>लेबल</translation> </message> <message> <source>Address</source> <translation>पता</translation> </message> <message> <source>ID</source> <translation>ID</translation> </message> <message> <source>Range:</source> <translation>विस्तार:</translation> </message> <message> <source>to</source> <translation>तक</translation> </message> </context> <context> <name>UnitDisplayStatusBarControl</name> </context> <context> <name>WalletFrame</name> </context> <context> <name>WalletModel</name> <message> <source>Send Coins</source> <translation>सिक्के भेजें|</translation> </message> </context> <context> <name>WalletView</name> <message> <source>Backup Wallet</source> <translation>बैकप वॉलेट</translation> </message> <message> <source>Wallet Data (*.dat)</source> <translation>वॉलेट डेटा (*.dat)</translation> </message> <message> <source>Backup Failed</source> <translation>बैकप असफल</translation> </message> <message> <source>Backup Successful</source> <translation>बैकप सफल</translation> </message> </context> <context> <name>FairCoin-core</name> <message> <source>Options:</source> <translation>विकल्प:</translation> </message> <message> <source>Specify data directory</source> <translation>डेटा डायरेक्टरी बताएं </translation> </message> <message> <source>Run in the background as a daemon and accept commands</source> <translation>बैकग्राउंड में डेमॉन बन कर रन करे तथा कमांड्स स्वीकार करें </translation> </message> <message> <source>Verifying blocks...</source> <translation>ब्लॉक्स जाँचे जा रहा है...</translation> </message> <message> <source>Verifying wallet...</source> <translation>वॉलेट जाँचा जा रहा है...</translation> </message> <message> <source>Information</source> <translation>जानकारी</translation> </message> <message> <source>Warning</source> <translation>चेतावनी</translation> </message> <message> <source>Loading addresses...</source> <translation>पता पुस्तक आ रही है...</translation> </message> <message> <source>Loading block index...</source> <translation>ब्लॉक इंडेक्स आ रहा है...</translation> </message> <message> <source>Loading wallet...</source> <translation>वॉलेट आ रहा है...</translation> </message> <message> <source>Rescanning...</source> <translation>रि-स्केनी-इंग...</translation> </message> <message> <source>Done loading</source> <translation>लोड हो गया|</translation> </message> <message> <source>Error</source> <translation>भूल</translation> </message> </context> </TS><|fim▁end|>
</context>
<|file_name|>connection.py<|end_file_name|><|fim▁begin|># -*- coding: UTF-8 -*- import ldap class Connection: def __init__(self, url='ldap://annuaire.math.univ-paris-diderot.fr:389', \ base='ou=users,dc=chevaleret,dc=univ-paris-diderot,dc=fr'): self.base = base self.url = url<|fim▁hole|> self.con.unbind() def search(self, kw, field='cn'): """ Search someone in the LDAP directory using a keyword """ qry = "%s=*%s*" % (field, kw) return self.con.search_s(self.base, ldap.SCOPE_SUBTREE, qry, None)<|fim▁end|>
self.con = ldap.initialize(self.url) self.con.bind_s('', '') def __del__(self):
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>extern crate rustc_serialize; mod json_flex; pub use json_flex::decode; pub use json_flex::Unwrap; pub use json_flex::JFObject; <|fim▁hole|>mod test;<|fim▁end|>
#[cfg(test)]
<|file_name|>LocalStorageNode.ts<|end_file_name|><|fim▁begin|>/* * #%L * %% * Copyright (C) 2019 BMW Car IT GmbH<|fim▁hole|> * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import { Persistency, PersistencySettings } from "./interface/Persistency"; import JoynrStorage from "./JoynrPersist"; import LoggingManager from "../joynr/system/LoggingManager"; const log = LoggingManager.getLogger("joynr.global.localStorageNode"); class LocalStorageWrapper implements Persistency { private settings: any; private promiseChain: any; private map: Map<string, any>; private storage: JoynrStorage; /** * LocalStorage constructor (node wrapper for LocalStorage) * @constructor LocalStorageWrapper * @classdesc node wrapper for LocalStorage * * @param settings the settings object * @param settings.clearPersistency localStorage is cleared if set to true * @param settings.location optional, passed on to node-persist LocalStorage constructor */ public constructor(settings: PersistencySettings) { settings = settings || {}; this.storage = new JoynrStorage({ dir: settings.location || "./localStorageStorage" }); this.map = new Map(); this.promiseChain = Promise.resolve(); this.settings = settings; } public setItem(key: string, value: any): void { this.map.set(key, value); this.wrapFunction(this.storage.setItem.bind(this.storage), key, value); } public getItem(key: string): any { return this.map.get(key); } public removeItem(key: string): void { this.map.delete(key); this.wrapFunction(this.storage.removeItem.bind(this.storage), key); } public clear(): void { this.map.clear(); this.wrapFunction(this.storage.clear.bind(this.storage)); } public async init(): Promise<void> { const storageData = await this.storage.init(); if (this.settings.clearPersistency) { return await this.storage.clear(); } for (let i = 0, length = storageData.length; i < length; i++) { const storageObject = storageData[i]; if (storageObject && storageObject.key) { this.map.set(storageObject.key, storageObject.value); } } } public async shutdown(): Promise<void> { await this.promiseChain; } private wrapFunction(cb: Function, ...args: any[]): void { this.promiseChain = this.promiseChain .then(() => { // eslint-disable-next-line promise/no-callback-in-promise return cb(...args); }) .catch((e: any) => { log.error(`failure executing ${cb} with args ${JSON.stringify(args)} error: ${e}`); }); } } export = LocalStorageWrapper;<|fim▁end|>
<|file_name|>config.js<|end_file_name|><|fim▁begin|>module.exports = { // Token you get from discord "token": "", // Prefix before your commands "prefix": "", // Port for webserver (Not working)<|fim▁hole|> // Mongodb stuff "mongodb": { // Mongodb uri "uri": "" }, // Channel IDs "channelIDs": { // Where to announce the events in ACCF "events": "", // Where to announce online towns "onlineTowns": "", // Where to log the logs "logs": "" } }<|fim▁end|>
"port": 8080,
<|file_name|>io_ops_test.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Copyright 2015 The TensorFlow 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. # ============================================================================== """Tests for tensorflow.python.ops.io_ops.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import tempfile import tensorflow as tf class IoOpsTest(tf.test.TestCase): def testReadFile(self): cases = ['', 'Some contents', 'Неки садржаји на српском'] for contents in cases: contents = tf.compat.as_bytes(contents) with tempfile.NamedTemporaryFile(prefix='ReadFileTest', dir=self.get_temp_dir(), delete=False) as temp: temp.write(contents) with self.test_session(): read = tf.read_file(temp.name) self.assertEqual([], read.get_shape()) self.assertEqual(read.eval(), contents) os.remove(temp.name) def testWriteFile(self): cases = ['', 'Some contents'] for contents in cases: contents = tf.compat.as_bytes(contents) with tempfile.NamedTemporaryFile(prefix='WriteFileTest', dir=self.get_temp_dir(), delete=False) as temp: pass with self.test_session() as sess: w = tf.write_file(temp.name, contents) sess.run(w) with open(temp.name, 'rb') as f: file_contents = f.read() self.assertEqual(file_contents, contents) os.remove(temp.name) def _subset(self, files, indices): return set(tf.compat.as_bytes(files[i].name) for i in range(len(files)) if i in indices) def testMatchingFiles(self): cases = ['ABcDEF.GH', 'ABzDEF.GH', 'ABasdfjklDEF.GH', 'AB3DEF.GH', 'AB4DEF.GH', 'ABDEF.GH', 'XYZ'] files = [tempfile.NamedTemporaryFile( prefix=c, dir=self.get_temp_dir(), delete=True) for c in cases] with self.test_session():<|fim▁hole|> for f in files: self.assertEqual(tf.matching_files(f.name).eval(), tf.compat.as_bytes(f.name)) # We will look for files matching "ABxDEF.GH*" where "x" is some wildcard. pos = files[0].name.find(cases[0]) pattern = files[0].name[:pos] + 'AB%sDEF.GH*' self.assertEqual(set(tf.matching_files(pattern % 'z').eval()), self._subset(files, [1])) self.assertEqual(set(tf.matching_files(pattern % '?').eval()), self._subset(files, [0, 1, 3, 4])) self.assertEqual(set(tf.matching_files(pattern % '*').eval()), self._subset(files, [0, 1, 2, 3, 4, 5])) # NOTE(mrry): Windows uses PathMatchSpec to match file patterns, which # does not support the following expressions. if os.name != 'nt': self.assertEqual(set(tf.matching_files(pattern % '[cxz]').eval()), self._subset(files, [0, 1])) self.assertEqual(set(tf.matching_files(pattern % '[0-9]').eval()), self._subset(files, [3, 4])) for f in files: f.close() if __name__ == '__main__': tf.test.main()<|fim▁end|>
# Test exact match without wildcards.
<|file_name|>editor_plugin.js<|end_file_name|><|fim▁begin|>/** * @package JCE * @copyright Copyright (c) 2009-2015 Ryan Demmer. All rights reserved. * @license GNU/GPL 2 or later - http://www.gnu.org/licenses/old-licenses/gpl-2.0.html * JCE is free software. This version may have been modified pursuant * to the GNU General Public License, and as distributed it includes or * is derivative of works licensed under the GNU General Public License or * other free or open source software licenses. */ (function(){ tinymce.create('tinymce.plugins.Browser', { init: function(ed, url){ this.ed = ed; }, browse: function(name, url, type, win){ var ed = this.ed; ed.windowManager.open({ file: ed.getParam('site_url') + 'index.php?option=com_jce&view=editor&layout=plugin&plugin=browser&type=' + type, width : 780 + ed.getLang('browser.delta_width', 0), height : 480 + ed.getLang('browser.delta_height', 0), resizable: "yes", inline: "yes", close_previous: "no", popup_css : false }, { window: win, input: name, url: url, type: type }); return false; }, getInfo: function(){ return { longname: 'Browser', author: 'Ryan Demmer', authorurl: 'http://www.joomlacontenteditor.net', infourl: 'http://www.joomlacontenteditor.net/index.php?option=com_content&amp;view=article&amp;task=findkey&amp;tmpl=component&amp;lang=en&amp;keyref=browser.about', version: '@@version@@' <|fim▁hole|> // Register plugin tinymce.PluginManager.add('browser', tinymce.plugins.Browser); })();<|fim▁end|>
}; } });
<|file_name|>length_feet_and_inches_to_metric.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8; -*- # # This file is part of Superdesk. # # Copyright 2013, 2014 Sourcefabric z.u. and contributors. # # For the full copyright and license information, please see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/superdesk/license import re from . import unit_base from decimal import Decimal from flask_babel import lazy_gettext def convert(feet, inches): """Converts from feet and inches to cm or m If feet contains '-' then inches won't have '-' If inches contains '-' then feet value will be 0 :param feet: Feet value in string<|fim▁hole|> :return: cm or m value in string, and the symbol as 'm' or 'cm' """ foot_to_cm_rate = Decimal(30.48) inch_to_cm_rate = Decimal(2.54) total_centimeters = [] symbol = "cm" if "-" in feet: feet_list = feet.split("-") total_centimeters = [(Decimal(m) * foot_to_cm_rate) + (Decimal(inches) * inch_to_cm_rate) for m in feet_list] elif "-" in inches: inches_list = inches.split("-") total_centimeters = [(Decimal(i) * inch_to_cm_rate) for i in inches_list] else: # no multi values total_centimeters = [(Decimal(feet) * foot_to_cm_rate) + (Decimal(inches) * inch_to_cm_rate)] if any(c for c in total_centimeters if c > Decimal(100)): # if the value is greater than 100 then convert it to meter total_centimeters = [unit_base.format_converted((c / Decimal(100)), precision=2) for c in total_centimeters] symbol = "m" else: total_centimeters = [unit_base.format_converted(c, precision=2) for c in total_centimeters] return "-".join(total_centimeters), symbol def do_conversion(item, converter, formatter, search_param): """Performs the conversion""" diff = {} # Group indexes match_index = 0 # Index of complete match i.e. 5' 10" value_index = 1 # Index of the value: contains feet if feet is in the match else inches if there's no feet feet_symbol_index = 7 # Index of feet symbol ', ft, feet, foot inches_with_feet_value_index = 11 # When there is a feet and inch value matched together inches_symbol_index = 5 # Index of inches symbol ", in, inch(es) def convert(match): match_item = match.group(match_index).strip() from_value = match.group(value_index) inches_from_value = "0" feet_symbol = match.group(feet_symbol_index) inches_symbol = match.group(inches_symbol_index) multi_values = "-" in from_value and from_value[-1:] != "-" if match_item and from_value: if feet_symbol: # check if any inches matched inches_from_value = match.group(inches_with_feet_value_index) or "0" elif inches_symbol: # no feet matching inches_from_value = from_value from_value = "0" else: return {} if not multi_values: from_value = re.sub(r"[^\d.]", "", from_value) inches_from_value = re.sub(r"[^\d.]", "", inches_from_value) to_value, symbol = converter(from_value, inches_from_value) diff.setdefault(match_item.strip(), formatter(match_item.strip(), to_value, symbol)) return diff[match_item] for field in unit_base.macro_replacement_fields: if item.get(field, None): re.sub(search_param, convert, item[field]) return (item, diff) def feet_inches_to_metric(item, **kwargs): """Converts distance values from feet and inches to metric""" regex = ( r"(\d+-?,?\.?\d*)((\s*)|(-))(((\'|ft\.?|[fF]eet|[fF]oot)" r'((-)|(\s*))(\d+)?\s?("|in)?)|(\"|[iI]nches|[iI]nch|in))' ) return do_conversion(item, convert, unit_base.format_output, regex) name = "feet_inches_to_metric" label = lazy_gettext("Length feet-inches to metric") callback = feet_inches_to_metric access_type = "frontend" action_type = "interactive" group = lazy_gettext("length")<|fim▁end|>
:param inches: Inch value in string
<|file_name|>ExampleEchoGinjector.java<|end_file_name|><|fim▁begin|>/* * ((e)) emite: A pure Google Web Toolkit XMPP library * Copyright (c) 2008-2011 The Emite development team * * This file is part of Emite. * * Emite is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 * of the License, or (at your option) any later version. * * Emite is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with Emite. If not, see <http://www.gnu.org/licenses/>. */ package com.calclab.emite.example.echo.client; import com.calclab.emite.browser.EmiteBrowserModule; import com.calclab.emite.core.EmiteCoreModule; <|fim▁hole|>import com.google.gwt.inject.client.GinModules; import com.google.gwt.inject.client.Ginjector; @GinModules({ EmiteCoreModule.class, EmiteIMModule.class, EmiteBrowserModule.class }) interface ExampleEchoGinjector extends Ginjector { XmppSession getXmppSession(); PairChatManager getPairChatManager(); }<|fim▁end|>
import com.calclab.emite.core.session.XmppSession; import com.calclab.emite.im.EmiteIMModule; import com.calclab.emite.im.chat.PairChatManager;
<|file_name|>net.cpp<|end_file_name|><|fim▁begin|>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "chainparams.h" #include "db.h" #include "net.h" #include "main.h" #include "addrman.h" #include "ui_interface.h" #ifdef WIN32 #include <string.h> #endif #ifdef USE_UPNP #include <miniupnpc/miniwget.h> #include <miniupnpc/miniupnpc.h> #include <miniupnpc/upnpcommands.h> #include <miniupnpc/upnperrors.h> #endif // Dump addresses to peers.dat every 15 minutes (900s) #define DUMP_ADDRESSES_INTERVAL 900 using namespace std; using namespace boost; static const int MAX_OUTBOUND_CONNECTIONS = 16; bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound = NULL, const char *strDest = NULL, bool fOneShot = false); struct LocalServiceInfo { int nScore; int nPort; }; // // Global state variables // bool fDiscover = true; uint64_t nLocalServices = NODE_NETWORK; static CCriticalSection cs_mapLocalHost; static map<CNetAddr, LocalServiceInfo> mapLocalHost; static bool vfReachable[NET_MAX] = {}; static bool vfLimited[NET_MAX] = {}; static CNode* pnodeLocalHost = NULL; static CNode* pnodeSync = NULL; uint64_t nLocalHostNonce = 0; static std::vector<SOCKET> vhListenSocket; CAddrMan addrman; vector<CNode*> vNodes; CCriticalSection cs_vNodes; map<CInv, CDataStream> mapRelay; deque<pair<int64_t, CInv> > vRelayExpiration; CCriticalSection cs_mapRelay; map<CInv, int64_t> mapAlreadyAskedFor; static deque<string> vOneShots; CCriticalSection cs_vOneShots; set<CNetAddr> setservAddNodeAddresses; CCriticalSection cs_setservAddNodeAddresses; vector<std::string> vAddedNodes; CCriticalSection cs_vAddedNodes; static CSemaphore *semOutbound = NULL; // Signals for message handling static CNodeSignals g_signals; CNodeSignals& GetNodeSignals() { return g_signals; } void AddOneShot(string strDest) { LOCK(cs_vOneShots); vOneShots.push_back(strDest); } unsigned short GetListenPort() { return (unsigned short)(GetArg("-port", Params().GetDefaultPort())); } // find 'best' local address for a particular peer bool GetLocal(CService& addr, const CNetAddr *paddrPeer) { if (fNoListen) return false; int nBestScore = -1; int nBestReachability = -1; { LOCK(cs_mapLocalHost); for (map<CNetAddr, LocalServiceInfo>::iterator it = mapLocalHost.begin(); it != mapLocalHost.end(); it++) { int nScore = (*it).second.nScore; int nReachability = (*it).first.GetReachabilityFrom(paddrPeer); if (nReachability > nBestReachability || (nReachability == nBestReachability && nScore > nBestScore)) { addr = CService((*it).first, (*it).second.nPort); nBestReachability = nReachability; nBestScore = nScore; } } } return nBestScore >= 0; } // get best local address for a particular peer as a CAddress // Otherwise, return the unroutable 0.0.0.0 but filled in with // the normal parameters, since the IP may be changed to a useful // one by discovery. CAddress GetLocalAddress(const CNetAddr *paddrPeer) { CAddress ret(CService("0.0.0.0",GetListenPort()),0); CService addr; if (GetLocal(addr, paddrPeer)) { ret = CAddress(addr); } ret.nServices = nLocalServices; ret.nTime = GetAdjustedTime(); return ret; } bool RecvLine(SOCKET hSocket, string& strLine) { strLine = ""; while (true) { char c; int nBytes = recv(hSocket, &c, 1, 0); if (nBytes > 0) { if (c == '\n') continue; if (c == '\r') return true; strLine += c; if (strLine.size() >= 9000) return true; } else if (nBytes <= 0) { boost::this_thread::interruption_point(); if (nBytes < 0) { int nErr = WSAGetLastError(); if (nErr == WSAEMSGSIZE) continue; if (nErr == WSAEWOULDBLOCK || nErr == WSAEINTR || nErr == WSAEINPROGRESS) { MilliSleep(10); continue; } } if (!strLine.empty()) return true; if (nBytes == 0) { // socket closed LogPrint("net", "socket closed\n"); return false; } else { // socket error int nErr = WSAGetLastError(); LogPrint("net", "recv failed: %d\n", nErr); return false; } } } } int GetnScore(const CService& addr) { LOCK(cs_mapLocalHost); if (mapLocalHost.count(addr) == LOCAL_NONE) return 0; return mapLocalHost[addr].nScore; } // Is our peer's addrLocal potentially useful as an external IP source? bool IsPeerAddrLocalGood(CNode *pnode) { return fDiscover && pnode->addr.IsRoutable() && pnode->addrLocal.IsRoutable() && !IsLimited(pnode->addrLocal.GetNetwork()); } // pushes our own address to a peer void AdvertizeLocal(CNode *pnode) { if (!fNoListen && pnode->fSuccessfullyConnected) { CAddress addrLocal = GetLocalAddress(&pnode->addr); // If discovery is enabled, sometimes give our peer the address it // tells us that it sees us as in case it has a better idea of our // address than we do. if (IsPeerAddrLocalGood(pnode) && (!addrLocal.IsRoutable() || GetRand((GetnScore(addrLocal) > LOCAL_MANUAL) ? 8:2) == 0)) { addrLocal.SetIP(pnode->addrLocal); } if (addrLocal.IsRoutable()) { pnode->PushAddress(addrLocal); } } } void SetReachable(enum Network net, bool fFlag) { LOCK(cs_mapLocalHost); vfReachable[net] = fFlag; if (net == NET_IPV6 && fFlag) vfReachable[NET_IPV4] = true; } // learn a new local address bool AddLocal(const CService& addr, int nScore) { if (!addr.IsRoutable()) return false; if (!fDiscover && nScore < LOCAL_MANUAL) return false; if (IsLimited(addr)) return false; LogPrintf("AddLocal(%s,%i)\n", addr.ToString(), nScore); { LOCK(cs_mapLocalHost); bool fAlready = mapLocalHost.count(addr) > 0; LocalServiceInfo &info = mapLocalHost[addr]; if (!fAlready || nScore >= info.nScore) { info.nScore = nScore + (fAlready ? 1 : 0); info.nPort = addr.GetPort(); } SetReachable(addr.GetNetwork()); } return true; } bool AddLocal(const CNetAddr &addr, int nScore) { return AddLocal(CService(addr, GetListenPort()), nScore); } /** Make a particular network entirely off-limits (no automatic connects to it) */ void SetLimited(enum Network net, bool fLimited) { if (net == NET_UNROUTABLE) return; LOCK(cs_mapLocalHost); vfLimited[net] = fLimited; } bool IsLimited(enum Network net) { LOCK(cs_mapLocalHost); return vfLimited[net]; } bool IsLimited(const CNetAddr &addr) { return IsLimited(addr.GetNetwork()); } /** vote for a local address */ bool SeenLocal(const CService& addr) { { LOCK(cs_mapLocalHost); if (mapLocalHost.count(addr) == 0) return false; mapLocalHost[addr].nScore++; } return true; } /** check whether a given address is potentially local */ bool IsLocal(const CService& addr) { LOCK(cs_mapLocalHost); return mapLocalHost.count(addr) > 0; } /** check whether a given address is in a network we can probably connect to */ bool IsReachable(const CNetAddr& addr) { LOCK(cs_mapLocalHost); enum Network net = addr.GetNetwork(); return vfReachable[net] && !vfLimited[net]; } void AddressCurrentlyConnected(const CService& addr) { addrman.Connected(addr); } uint64_t CNode::nTotalBytesRecv = 0; uint64_t CNode::nTotalBytesSent = 0; CCriticalSection CNode::cs_totalBytesRecv; CCriticalSection CNode::cs_totalBytesSent; CNode* FindNode(const CNetAddr& ip) { { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) if ((CNetAddr)pnode->addr == ip) return (pnode); } return NULL; } CNode* FindNode(const std::string& addrName) { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) if (pnode->addrName == addrName) return (pnode); return NULL; } CNode* FindNode(const CService& addr) { { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) if ((CService)pnode->addr == addr) return (pnode); } return NULL; } CNode* ConnectNode(CAddress addrConnect, const char *pszDest) { if (pszDest == NULL) { if (IsLocal(addrConnect)) return NULL; // Look for an existing connection CNode* pnode = FindNode((CService)addrConnect); if (pnode) { pnode->AddRef(); return pnode; } } /// debug print LogPrint("net", "trying connection %s lastseen=%.1fhrs\n", pszDest ? pszDest : addrConnect.ToString(), pszDest ? 0 : (double)(GetAdjustedTime() - addrConnect.nTime)/3600.0); // Connect SOCKET hSocket; bool proxyConnectionFailed = false; if (pszDest ? ConnectSocketByName(addrConnect, hSocket, pszDest, Params().GetDefaultPort(), nConnectTimeout, &proxyConnectionFailed) : ConnectSocket(addrConnect, hSocket, nConnectTimeout, &proxyConnectionFailed)) { addrman.Attempt(addrConnect); LogPrint("net", "connected %s\n", pszDest ? pszDest : addrConnect.ToString()); // Set to non-blocking #ifdef WIN32 u_long nOne = 1; if (ioctlsocket(hSocket, FIONBIO, &nOne) == SOCKET_ERROR) LogPrintf("ConnectSocket() : ioctlsocket non-blocking setting failed, error %d\n", WSAGetLastError()); #else if (fcntl(hSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR) LogPrintf("ConnectSocket() : fcntl non-blocking setting failed, error %d\n", errno); #endif // Add node CNode* pnode = new CNode(hSocket, addrConnect, pszDest ? pszDest : "", false); pnode->AddRef(); { LOCK(cs_vNodes); vNodes.push_back(pnode); } pnode->nTimeConnected = GetTime(); return pnode; } else if (!proxyConnectionFailed) { // If connecting to the node failed, and failure is not caused by a problem connecting to // the proxy, mark this as an attempt. addrman.Attempt(addrConnect); } return NULL; } void CNode::CloseSocketDisconnect() { fDisconnect = true; if (hSocket != INVALID_SOCKET) { LogPrint("net", "disconnecting node %s\n", addrName); closesocket(hSocket); hSocket = INVALID_SOCKET; } // in case this fails, we'll empty the recv buffer when the CNode is deleted TRY_LOCK(cs_vRecvMsg, lockRecv); if (lockRecv) vRecvMsg.clear(); // if this was the sync node, we'll need a new one if (this == pnodeSync) pnodeSync = NULL; } void CNode::PushVersion() { /// when NTP implemented, change to just nTime = GetAdjustedTime() int64_t nTime = (fInbound ? GetAdjustedTime() : GetTime()); CAddress addrYou = (addr.IsRoutable() && !IsProxy(addr) ? addr : CAddress(CService("0.0.0.0",0))); CAddress addrMe = GetLocalAddress(&addr); RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce)); LogPrint("net", "send version message: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", PROTOCOL_VERSION, nBestHeight, addrMe.ToString(), addrYou.ToString(), addr.ToString()); PushMessage("version", PROTOCOL_VERSION, nLocalServices, nTime, addrYou, addrMe, nLocalHostNonce, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<string>()), nBestHeight); } std::map<CNetAddr, int64_t> CNode::setBanned; CCriticalSection CNode::cs_setBanned; void CNode::ClearBanned() { setBanned.clear(); } bool CNode::IsBanned(CNetAddr ip) { bool fResult = false; { LOCK(cs_setBanned); std::map<CNetAddr, int64_t>::iterator i = setBanned.find(ip); if (i != setBanned.end()) { int64_t t = (*i).second; if (GetTime() < t) fResult = true; } } return fResult; } bool CNode::Misbehaving(int howmuch) { if (addr.IsLocal()) { LogPrintf("Warning: Local node %s misbehaving (delta: %d)!\n", addrName, howmuch); return false; } nMisbehavior += howmuch; if (nMisbehavior >= GetArg("-banscore", 100)) { int64_t banTime = GetTime()+GetArg("-bantime", 60*60*24); // Default 24-hour ban LogPrintf("Misbehaving: %s (%d -> %d) DISCONNECTING\n", addr.ToString(), nMisbehavior-howmuch, nMisbehavior); { LOCK(cs_setBanned); if (setBanned[addr] < banTime) setBanned[addr] = banTime; } CloseSocketDisconnect(); return true; } else LogPrintf("Misbehaving: %s (%d -> %d)\n", addr.ToString(), nMisbehavior-howmuch, nMisbehavior); return false; } #undef X #define X(name) stats.name = name void CNode::copyStats(CNodeStats &stats) { X(nServices); X(nLastSend); X(nLastRecv); X(nTimeConnected); X(nTimeOffset); X(addrName); X(nVersion); X(strSubVer); X(fInbound); X(nStartingHeight); X(nMisbehavior); X(nSendBytes); X(nRecvBytes); stats.fSyncNode = (this == pnodeSync); // It is common for nodes with good ping times to suddenly become lagged, // due to a new block arriving or other large transfer. // Merely reporting pingtime might fool the caller into thinking the node was still responsive, // since pingtime does not update until the ping is complete, which might take a while. // So, if a ping is taking an unusually long time in flight, // the caller can immediately detect that this is happening. int64_t nPingUsecWait = 0; if ((0 != nPingNonceSent) && (0 != nPingUsecStart)) { nPingUsecWait = GetTimeMicros() - nPingUsecStart; } // Raw ping time is in microseconds, but show it to user as whole seconds (Bitcoin users should be well used to small numbers with many decimal places by now :) stats.dPingTime = (((double)nPingUsecTime) / 1e6); stats.dPingWait = (((double)nPingUsecWait) / 1e6); // Leave string empty if addrLocal invalid (not filled in yet) stats.addrLocal = addrLocal.IsValid() ? addrLocal.ToString() : ""; } #undef X // requires LOCK(cs_vRecvMsg) bool CNode::ReceiveMsgBytes(const char *pch, unsigned int nBytes) { while (nBytes > 0) { // get current incomplete message, or create a new one if (vRecvMsg.empty() || vRecvMsg.back().complete()) vRecvMsg.push_back(CNetMessage(SER_NETWORK, nRecvVersion)); CNetMessage& msg = vRecvMsg.back(); // absorb network data int handled; if (!msg.in_data) handled = msg.readHeader(pch, nBytes); else handled = msg.readData(pch, nBytes); if (handled < 0) return false; pch += handled; nBytes -= handled; if (msg.complete()) msg.nTime = GetTimeMicros(); } return true; } int CNetMessage::readHeader(const char *pch, unsigned int nBytes) { // copy data to temporary parsing buffer unsigned int nRemaining = 24 - nHdrPos; unsigned int nCopy = std::min(nRemaining, nBytes); memcpy(&hdrbuf[nHdrPos], pch, nCopy); nHdrPos += nCopy; // if header incomplete, exit if (nHdrPos < 24) return nCopy; // deserialize to CMessageHeader try { hdrbuf >> hdr; } catch (std::exception &e) { return -1; } // reject messages larger than MAX_SIZE if (hdr.nMessageSize > MAX_SIZE) return -1; // switch state to reading message data in_data = true; return nCopy; } int CNetMessage::readData(const char *pch, unsigned int nBytes) { unsigned int nRemaining = hdr.nMessageSize - nDataPos; unsigned int nCopy = std::min(nRemaining, nBytes); if (vRecv.size() < nDataPos + nCopy) { // Allocate up to 256 KiB ahead, but never more than the total message size. vRecv.resize(std::min(hdr.nMessageSize, nDataPos + nCopy + 256 * 1024)); } memcpy(&vRecv[nDataPos], pch, nCopy); nDataPos += nCopy; return nCopy; } // requires LOCK(cs_vSend) void SocketSendData(CNode *pnode) { std::deque<CSerializeData>::iterator it = pnode->vSendMsg.begin(); while (it != pnode->vSendMsg.end()) { const CSerializeData &data = *it; assert(data.size() > pnode->nSendOffset); int nBytes = send(pnode->hSocket, &data[pnode->nSendOffset], data.size() - pnode->nSendOffset, MSG_NOSIGNAL | MSG_DONTWAIT); if (nBytes > 0) { pnode->nLastSend = GetTime(); pnode->nSendBytes += nBytes; pnode->nSendOffset += nBytes; pnode->RecordBytesSent(nBytes); if (pnode->nSendOffset == data.size()) { pnode->nSendOffset = 0; pnode->nSendSize -= data.size(); it++; } else { // could not send full message; stop sending more break; } } else { if (nBytes < 0) { // error int nErr = WSAGetLastError(); if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS) { LogPrintf("socket send error %d\n", nErr); pnode->CloseSocketDisconnect(); } } // couldn't send anything at all break; } } if (it == pnode->vSendMsg.end()) { assert(pnode->nSendOffset == 0); assert(pnode->nSendSize == 0); } pnode->vSendMsg.erase(pnode->vSendMsg.begin(), it); } static list<CNode*> vNodesDisconnected; void ThreadSocketHandler() { unsigned int nPrevNodeCount = 0; while (true) { // // Disconnect nodes // { LOCK(cs_vNodes); // Disconnect unused nodes vector<CNode*> vNodesCopy = vNodes; BOOST_FOREACH(CNode* pnode, vNodesCopy) { if (pnode->fDisconnect || (pnode->GetRefCount() <= 0 && pnode->vRecvMsg.empty() && pnode->nSendSize == 0 && pnode->ssSend.empty())) { // remove from vNodes vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end()); // release outbound grant (if any) pnode->grantOutbound.Release(); // close socket and cleanup pnode->CloseSocketDisconnect(); // hold in disconnected pool until all refs are released if (pnode->fNetworkNode || pnode->fInbound) pnode->Release(); vNodesDisconnected.push_back(pnode); } } } { // Delete disconnected nodes list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected; BOOST_FOREACH(CNode* pnode, vNodesDisconnectedCopy) { // wait until threads are done using it if (pnode->GetRefCount() <= 0) { bool fDelete = false; { TRY_LOCK(pnode->cs_vSend, lockSend); if (lockSend) { TRY_LOCK(pnode->cs_vRecvMsg, lockRecv); if (lockRecv) { TRY_LOCK(pnode->cs_inventory, lockInv); if (lockInv) fDelete = true; } } } if (fDelete) { vNodesDisconnected.remove(pnode); delete pnode; } } } } if(vNodes.size() != nPrevNodeCount) { nPrevNodeCount = vNodes.size(); uiInterface.NotifyNumConnectionsChanged(nPrevNodeCount); } // // Find which sockets have data to receive // struct timeval timeout; timeout.tv_sec = 0; timeout.tv_usec = 50000; // frequency to poll pnode->vSend fd_set fdsetRecv; fd_set fdsetSend; fd_set fdsetError; FD_ZERO(&fdsetRecv); FD_ZERO(&fdsetSend); FD_ZERO(&fdsetError); SOCKET hSocketMax = 0; bool have_fds = false; BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket) { FD_SET(hListenSocket, &fdsetRecv); hSocketMax = max(hSocketMax, hListenSocket); have_fds = true; } { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) { if (pnode->hSocket == INVALID_SOCKET) continue; { TRY_LOCK(pnode->cs_vSend, lockSend); if (lockSend) { // do not read, if draining write queue if (!pnode->vSendMsg.empty()) FD_SET(pnode->hSocket, &fdsetSend); else FD_SET(pnode->hSocket, &fdsetRecv); FD_SET(pnode->hSocket, &fdsetError); hSocketMax = max(hSocketMax, pnode->hSocket); have_fds = true; } } } } int nSelect = select(have_fds ? hSocketMax + 1 : 0, &fdsetRecv, &fdsetSend, &fdsetError, &timeout); boost::this_thread::interruption_point(); if (nSelect == SOCKET_ERROR) { if (have_fds) { int nErr = WSAGetLastError(); LogPrintf("socket select error %d\n", nErr); for (unsigned int i = 0; i <= hSocketMax; i++) FD_SET(i, &fdsetRecv); } FD_ZERO(&fdsetSend); FD_ZERO(&fdsetError); MilliSleep(timeout.tv_usec/1000); } // // Accept new connections // BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket) if (hListenSocket != INVALID_SOCKET && FD_ISSET(hListenSocket, &fdsetRecv)) { struct sockaddr_storage sockaddr; socklen_t len = sizeof(sockaddr); SOCKET hSocket = accept(hListenSocket, (struct sockaddr*)&sockaddr, &len); CAddress addr; int nInbound = 0; if (hSocket != INVALID_SOCKET) if (!addr.SetSockAddr((const struct sockaddr*)&sockaddr)) LogPrintf("Warning: Unknown socket family\n"); { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) if (pnode->fInbound) nInbound++; } if (hSocket == INVALID_SOCKET) { int nErr = WSAGetLastError(); if (nErr != WSAEWOULDBLOCK) LogPrintf("socket error accept failed: %d\n", nErr); } else if (nInbound >= GetArg("-maxconnections", 125) - MAX_OUTBOUND_CONNECTIONS) { closesocket(hSocket); } else if (CNode::IsBanned(addr)) { LogPrintf("connection from %s dropped (banned)\n", addr.ToString()); closesocket(hSocket); } else { LogPrint("net", "accepted connection %s\n", addr.ToString()); CNode* pnode = new CNode(hSocket, addr, "", true); pnode->AddRef(); { LOCK(cs_vNodes); vNodes.push_back(pnode); } } } // // Service each socket // vector<CNode*> vNodesCopy; { LOCK(cs_vNodes); vNodesCopy = vNodes; BOOST_FOREACH(CNode* pnode, vNodesCopy) pnode->AddRef(); } BOOST_FOREACH(CNode* pnode, vNodesCopy) { boost::this_thread::interruption_point(); // // Receive // if (pnode->hSocket == INVALID_SOCKET) continue; if (FD_ISSET(pnode->hSocket, &fdsetRecv) || FD_ISSET(pnode->hSocket, &fdsetError)) { TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);<|fim▁hole|> { if (pnode->GetTotalRecvSize() > ReceiveFloodSize()) { if (!pnode->fDisconnect) LogPrintf("socket recv flood control disconnect (%u bytes)\n", pnode->GetTotalRecvSize()); pnode->CloseSocketDisconnect(); } else { // typical socket buffer is 8K-64K char pchBuf[0x10000]; int nBytes = recv(pnode->hSocket, pchBuf, sizeof(pchBuf), MSG_DONTWAIT); if (nBytes > 0) { if (!pnode->ReceiveMsgBytes(pchBuf, nBytes)) pnode->CloseSocketDisconnect(); pnode->nLastRecv = GetTime(); pnode->nRecvBytes += nBytes; pnode->RecordBytesRecv(nBytes); } else if (nBytes == 0) { // socket closed gracefully if (!pnode->fDisconnect) LogPrint("net", "socket closed\n"); pnode->CloseSocketDisconnect(); } else if (nBytes < 0) { // error int nErr = WSAGetLastError(); if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS) { if (!pnode->fDisconnect) LogPrintf("socket recv error %d\n", nErr); pnode->CloseSocketDisconnect(); } } } } } // // Send // if (pnode->hSocket == INVALID_SOCKET) continue; if (FD_ISSET(pnode->hSocket, &fdsetSend)) { TRY_LOCK(pnode->cs_vSend, lockSend); if (lockSend) SocketSendData(pnode); } // // Inactivity checking // int64_t nTime = GetTime(); if (nTime - pnode->nTimeConnected > 60) { if (pnode->nLastRecv == 0 || pnode->nLastSend == 0) { LogPrint("net", "socket no message in first 60 seconds, %d %d\n", pnode->nLastRecv != 0, pnode->nLastSend != 0); pnode->fDisconnect = true; } else if (nTime - pnode->nLastSend > TIMEOUT_INTERVAL) { LogPrintf("socket sending timeout: %ds\n", nTime - pnode->nLastSend); pnode->fDisconnect = true; } else if (nTime - pnode->nLastRecv > (pnode->nVersion > BIP0031_VERSION ? TIMEOUT_INTERVAL : 90*60)) { LogPrintf("socket receive timeout: %ds\n", nTime - pnode->nLastRecv); pnode->fDisconnect = true; } else if (pnode->nPingNonceSent && pnode->nPingUsecStart + TIMEOUT_INTERVAL * 1000000 < GetTimeMicros()) { LogPrintf("ping timeout: %fs\n", 0.000001 * (GetTimeMicros() - pnode->nPingUsecStart)); pnode->fDisconnect = true; } } } { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodesCopy) pnode->Release(); } } } #ifdef USE_UPNP void ThreadMapPort() { std::string port = strprintf("%u", GetListenPort()); const char * multicastif = 0; const char * minissdpdpath = 0; struct UPNPDev * devlist = 0; char lanaddr[64]; #ifndef UPNPDISCOVER_SUCCESS /* miniupnpc 1.5 */ devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0); #elif MINIUPNPC_API_VERSION < 14 /* miniupnpc 1.6 */ int error = 0; devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, &error); #else /* miniupnpc 1.9.20150730 */ int error = 0; devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, 2, &error); #endif struct UPNPUrls urls; struct IGDdatas data; int r; r = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr)); if (r == 1) { if (fDiscover) { char externalIPAddress[40]; r = UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, externalIPAddress); if(r != UPNPCOMMAND_SUCCESS) LogPrintf("UPnP: GetExternalIPAddress() returned %d\n", r); else { if(externalIPAddress[0]) { LogPrintf("UPnP: ExternalIPAddress = %s\n", externalIPAddress); AddLocal(CNetAddr(externalIPAddress), LOCAL_UPNP); } else LogPrintf("UPnP: GetExternalIPAddress failed.\n"); } } string strDesc = "altcommunitycoin " + FormatFullVersion(); try { while (true) { #ifndef UPNPDISCOVER_SUCCESS /* miniupnpc 1.5 */ r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype, port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0); #else /* miniupnpc 1.6 */ r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype, port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0, "0"); #endif if(r!=UPNPCOMMAND_SUCCESS) LogPrintf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n", port, port, lanaddr, r, strupnperror(r)); else LogPrintf("UPnP Port Mapping successful.\n");; MilliSleep(20*60*1000); // Refresh every 20 minutes } } catch (boost::thread_interrupted) { r = UPNP_DeletePortMapping(urls.controlURL, data.first.servicetype, port.c_str(), "TCP", 0); LogPrintf("UPNP_DeletePortMapping() returned : %d\n", r); freeUPNPDevlist(devlist); devlist = 0; FreeUPNPUrls(&urls); throw; } } else { LogPrintf("No valid UPnP IGDs found\n"); freeUPNPDevlist(devlist); devlist = 0; if (r != 0) FreeUPNPUrls(&urls); } } void MapPort(bool fUseUPnP) { static boost::thread* upnp_thread = NULL; if (fUseUPnP) { if (upnp_thread) { upnp_thread->interrupt(); upnp_thread->join(); delete upnp_thread; } upnp_thread = new boost::thread(boost::bind(&TraceThread<void (*)()>, "upnp", &ThreadMapPort)); } else if (upnp_thread) { upnp_thread->interrupt(); upnp_thread->join(); delete upnp_thread; upnp_thread = NULL; } } #else void MapPort(bool) { // Intentionally left blank. } #endif void ThreadDNSAddressSeed() { // goal: only query DNS seeds if address need is acute if ((addrman.size() > 0) && (!GetBoolArg("-forcednsseed", false))) { MilliSleep(11 * 1000); LOCK(cs_vNodes); if (vNodes.size() >= 2) { LogPrintf("P2P peers available. Skipped DNS seeding.\n"); return; } } const vector<CDNSSeedData> &vSeeds = Params().DNSSeeds(); int found = 0; LogPrintf("Loading addresses from DNS seeds (could take a while)\n"); BOOST_FOREACH(const CDNSSeedData &seed, vSeeds) { if (HaveNameProxy()) { AddOneShot(seed.host); } else { vector<CNetAddr> vIPs; vector<CAddress> vAdd; if (LookupHost(seed.host.c_str(), vIPs)) { BOOST_FOREACH(CNetAddr& ip, vIPs) { int nOneDay = 24*3600; CAddress addr = CAddress(CService(ip, Params().GetDefaultPort())); addr.nTime = GetTime() - 3*nOneDay - GetRand(4*nOneDay); // use a random age between 3 and 7 days old vAdd.push_back(addr); found++; } } addrman.Add(vAdd, CNetAddr(seed.name, true)); } } LogPrintf("%d addresses found from DNS seeds\n", found); } void DumpAddresses() { int64_t nStart = GetTimeMillis(); CAddrDB adb; adb.Write(addrman); LogPrint("net", "Flushed %d addresses to peers.dat %dms\n", addrman.size(), GetTimeMillis() - nStart); } void static ProcessOneShot() { string strDest; { LOCK(cs_vOneShots); if (vOneShots.empty()) return; strDest = vOneShots.front(); vOneShots.pop_front(); } CAddress addr; CSemaphoreGrant grant(*semOutbound, true); if (grant) { if (!OpenNetworkConnection(addr, &grant, strDest.c_str(), true)) AddOneShot(strDest); } } void ThreadOpenConnections() { // Connect to specific addresses if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) { for (int64_t nLoop = 0;; nLoop++) { ProcessOneShot(); BOOST_FOREACH(string strAddr, mapMultiArgs["-connect"]) { CAddress addr; OpenNetworkConnection(addr, NULL, strAddr.c_str()); for (int i = 0; i < 10 && i < nLoop; i++) { MilliSleep(500); } } MilliSleep(500); } } // Initiate network connections int64_t nStart = GetTime(); while (true) { ProcessOneShot(); MilliSleep(500); CSemaphoreGrant grant(*semOutbound); boost::this_thread::interruption_point(); // Add seed nodes if DNS seeds are all down (an infrastructure attack?). if (addrman.size() == 0 && (GetTime() - nStart > 60)) { static bool done = false; if (!done) { LogPrintf("Adding fixed seed nodes as DNS doesn't seem to be available.\n"); addrman.Add(Params().FixedSeeds(), CNetAddr("127.0.0.1")); done = true; } } // // Choose an address to connect to based on most recently seen // CAddress addrConnect; // Only connect out to one peer per network group (/16 for IPv4). // Do this here so we don't have to critsect vNodes inside mapAddresses critsect. int nOutbound = 0; set<vector<unsigned char> > setConnected; { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) { if (!pnode->fInbound) { setConnected.insert(pnode->addr.GetGroup()); nOutbound++; } } } int64_t nANow = GetAdjustedTime(); int nTries = 0; while (true) { CAddress addr = addrman.Select(); // if we selected an invalid address, restart if (!addr.IsValid() || setConnected.count(addr.GetGroup()) || IsLocal(addr)) break; // If we didn't find an appropriate destination after trying 100 addresses fetched from addrman, // stop this loop, and let the outer loop run again (which sleeps, adds seed nodes, recalculates // already-connected network ranges, ...) before trying new addrman addresses. nTries++; if (nTries > 100) break; if (IsLimited(addr)) continue; // only consider very recently tried nodes after 30 failed attempts if (nANow - addr.nLastTry < 600 && nTries < 30) continue; // do not allow non-default ports, unless after 50 invalid addresses selected already if (addr.GetPort() != Params().GetDefaultPort() && nTries < 50) continue; addrConnect = addr; break; } if (addrConnect.IsValid()) OpenNetworkConnection(addrConnect, &grant); } } void ThreadOpenAddedConnections() { { LOCK(cs_vAddedNodes); vAddedNodes = mapMultiArgs["-addnode"]; } if (HaveNameProxy()) { while(true) { list<string> lAddresses(0); { LOCK(cs_vAddedNodes); BOOST_FOREACH(string& strAddNode, vAddedNodes) lAddresses.push_back(strAddNode); } BOOST_FOREACH(string& strAddNode, lAddresses) { CAddress addr; CSemaphoreGrant grant(*semOutbound); OpenNetworkConnection(addr, &grant, strAddNode.c_str()); MilliSleep(500); } MilliSleep(120000); // Retry every 2 minutes } } for (unsigned int i = 0; true; i++) { list<string> lAddresses(0); { LOCK(cs_vAddedNodes); BOOST_FOREACH(string& strAddNode, vAddedNodes) lAddresses.push_back(strAddNode); } list<vector<CService> > lservAddressesToAdd(0); BOOST_FOREACH(string& strAddNode, lAddresses) { vector<CService> vservNode(0); if(Lookup(strAddNode.c_str(), vservNode, Params().GetDefaultPort(), fNameLookup, 0)) { lservAddressesToAdd.push_back(vservNode); { LOCK(cs_setservAddNodeAddresses); BOOST_FOREACH(CService& serv, vservNode) setservAddNodeAddresses.insert(serv); } } } // Attempt to connect to each IP for each addnode entry until at least one is successful per addnode entry // (keeping in mind that addnode entries can have many IPs if fNameLookup) { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) for (list<vector<CService> >::iterator it = lservAddressesToAdd.begin(); it != lservAddressesToAdd.end(); it++) BOOST_FOREACH(CService& addrNode, *(it)) if (pnode->addr == addrNode) { it = lservAddressesToAdd.erase(it); it--; break; } } BOOST_FOREACH(vector<CService>& vserv, lservAddressesToAdd) { CSemaphoreGrant grant(*semOutbound); OpenNetworkConnection(CAddress(vserv[i % vserv.size()]), &grant); MilliSleep(500); } MilliSleep(120000); // Retry every 2 minutes } } // if successful, this moves the passed grant to the constructed node bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound, const char *strDest, bool fOneShot) { // // Initiate outbound network connection // boost::this_thread::interruption_point(); if (!strDest) if (IsLocal(addrConnect) || FindNode((CNetAddr)addrConnect) || CNode::IsBanned(addrConnect) || FindNode(addrConnect.ToStringIPPort().c_str())) return false; if (strDest && FindNode(strDest)) return false; CNode* pnode = ConnectNode(addrConnect, strDest); boost::this_thread::interruption_point(); if (!pnode) return false; if (grantOutbound) grantOutbound->MoveTo(pnode->grantOutbound); pnode->fNetworkNode = true; if (fOneShot) pnode->fOneShot = true; return true; } // for now, use a very simple selection metric: the node from which we received // most recently static int64_t NodeSyncScore(const CNode *pnode) { return pnode->nLastRecv; } void static StartSync(const vector<CNode*> &vNodes) { CNode *pnodeNewSync = NULL; int64_t nBestScore = 0; // fImporting and fReindex are accessed out of cs_main here, but only // as an optimization - they are checked again in SendMessages. if (fImporting || fReindex) return; // Iterate over all nodes BOOST_FOREACH(CNode* pnode, vNodes) { // check preconditions for allowing a sync if (!pnode->fClient && !pnode->fOneShot && !pnode->fDisconnect && pnode->fSuccessfullyConnected && (pnode->nStartingHeight > (nBestHeight - 144)) && (pnode->nVersion < NOSTRAS_VERSION_START || pnode->nVersion >= NOSTRAS_VERSION_END)) { // if ok, compare node's score with the best so far int64_t nScore = NodeSyncScore(pnode); if (pnodeNewSync == NULL || nScore > nBestScore) { pnodeNewSync = pnode; nBestScore = nScore; } } } // if a new sync candidate was found, start sync! if (pnodeNewSync) { pnodeNewSync->fStartSync = true; pnodeSync = pnodeNewSync; } } void ThreadMessageHandler() { SetThreadPriority(THREAD_PRIORITY_BELOW_NORMAL); while (true) { bool fHaveSyncNode = false; vector<CNode*> vNodesCopy; { LOCK(cs_vNodes); vNodesCopy = vNodes; BOOST_FOREACH(CNode* pnode, vNodesCopy) { pnode->AddRef(); if (pnode == pnodeSync) fHaveSyncNode = true; } } if (!fHaveSyncNode) StartSync(vNodesCopy); // Poll the connected nodes for messages CNode* pnodeTrickle = NULL; if (!vNodesCopy.empty()) pnodeTrickle = vNodesCopy[GetRand(vNodesCopy.size())]; bool fSleep = true; BOOST_FOREACH(CNode* pnode, vNodesCopy) { if (pnode->fDisconnect) continue; // Receive messages { TRY_LOCK(pnode->cs_vRecvMsg, lockRecv); if (lockRecv) { if (!g_signals.ProcessMessages(pnode)) pnode->CloseSocketDisconnect(); if (pnode->nSendSize < SendBufferSize()) { if (!pnode->vRecvGetData.empty() || (!pnode->vRecvMsg.empty() && pnode->vRecvMsg[0].complete())) { fSleep = false; } } } } boost::this_thread::interruption_point(); // Send messages { TRY_LOCK(pnode->cs_vSend, lockSend); if (lockSend) g_signals.SendMessages(pnode, pnode == pnodeTrickle); } boost::this_thread::interruption_point(); } { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodesCopy) pnode->Release(); } if (fSleep) MilliSleep(100); } } bool BindListenPort(const CService &addrBind, string& strError) { strError = ""; int nOne = 1; // Create socket for listening for incoming connections struct sockaddr_storage sockaddr; socklen_t len = sizeof(sockaddr); if (!addrBind.GetSockAddr((struct sockaddr*)&sockaddr, &len)) { strError = strprintf("Error: bind address family for %s not supported", addrBind.ToString()); LogPrintf("%s\n", strError); return false; } SOCKET hListenSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP); if (hListenSocket == INVALID_SOCKET) { strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %d)", WSAGetLastError()); LogPrintf("%s\n", strError); return false; } #ifdef SO_NOSIGPIPE // Different way of disabling SIGPIPE on BSD setsockopt(hListenSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&nOne, sizeof(int)); #endif #ifndef WIN32 // Allow binding if the port is still in TIME_WAIT state after // the program was closed and restarted. Not an issue on windows. setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (void*)&nOne, sizeof(int)); #endif #ifdef WIN32 // Set to non-blocking, incoming connections will also inherit this if (ioctlsocket(hListenSocket, FIONBIO, (u_long*)&nOne) == SOCKET_ERROR) #else if (fcntl(hListenSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR) #endif { strError = strprintf("Error: Couldn't set properties on socket for incoming connections (error %d)", WSAGetLastError()); LogPrintf("%s\n", strError); return false; } // some systems don't have IPV6_V6ONLY but are always v6only; others do have the option // and enable it by default or not. Try to enable it, if possible. if (addrBind.IsIPv6()) { #ifdef IPV6_V6ONLY #ifdef WIN32 setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&nOne, sizeof(int)); #else setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&nOne, sizeof(int)); #endif #endif #ifdef WIN32 int nProtLevel = 10 /* PROTECTION_LEVEL_UNRESTRICTED */; int nParameterId = 23 /* IPV6_PROTECTION_LEVEl */; // this call is allowed to fail setsockopt(hListenSocket, IPPROTO_IPV6, nParameterId, (const char*)&nProtLevel, sizeof(int)); #endif } if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR) { int nErr = WSAGetLastError(); if (nErr == WSAEADDRINUSE) strError = strprintf(_("Unable to bind to %s on this computer. altcommunitycoin is probably already running."), addrBind.ToString()); else strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %d, %s)"), addrBind.ToString(), nErr, strerror(nErr)); LogPrintf("%s\n", strError); return false; } LogPrintf("Bound to %s\n", addrBind.ToString()); // Listen for incoming connections if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR) { strError = strprintf("Error: Listening for incoming connections failed (listen returned error %d)", WSAGetLastError()); LogPrintf("%s\n", strError); return false; } vhListenSocket.push_back(hListenSocket); if (addrBind.IsRoutable() && fDiscover) AddLocal(addrBind, LOCAL_BIND); return true; } void static Discover(boost::thread_group& threadGroup) { if (!fDiscover) return; #ifdef WIN32 // Get local host IP char pszHostName[1000] = ""; if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR) { vector<CNetAddr> vaddr; if (LookupHost(pszHostName, vaddr)) { BOOST_FOREACH (const CNetAddr &addr, vaddr) { AddLocal(addr, LOCAL_IF); } } } #else // Get local host ip struct ifaddrs* myaddrs; if (getifaddrs(&myaddrs) == 0) { for (struct ifaddrs* ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next) { if (ifa->ifa_addr == NULL) continue; if ((ifa->ifa_flags & IFF_UP) == 0) continue; if (strcmp(ifa->ifa_name, "lo") == 0) continue; if (strcmp(ifa->ifa_name, "lo0") == 0) continue; if (ifa->ifa_addr->sa_family == AF_INET) { struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr); CNetAddr addr(s4->sin_addr); if (AddLocal(addr, LOCAL_IF)) LogPrintf("IPv4 %s: %s\n", ifa->ifa_name, addr.ToString()); } else if (ifa->ifa_addr->sa_family == AF_INET6) { struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr); CNetAddr addr(s6->sin6_addr); if (AddLocal(addr, LOCAL_IF)) LogPrintf("IPv6 %s: %s\n", ifa->ifa_name, addr.ToString()); } } freeifaddrs(myaddrs); } #endif } void StartNode(boost::thread_group& threadGroup) { if (semOutbound == NULL) { // initialize semaphore int nMaxOutbound = min(MAX_OUTBOUND_CONNECTIONS, (int)GetArg("-maxconnections", 125)); semOutbound = new CSemaphore(nMaxOutbound); } if (pnodeLocalHost == NULL) pnodeLocalHost = new CNode(INVALID_SOCKET, CAddress(CService("127.0.0.1", 0), nLocalServices)); Discover(threadGroup); // // Start threads // if (!GetBoolArg("-dnsseed", true)) LogPrintf("DNS seeding disabled\n"); else threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "dnsseed", &ThreadDNSAddressSeed)); #ifdef USE_UPNP // Map ports with UPnP MapPort(GetBoolArg("-upnp", USE_UPNP)); #endif // Send and receive from sockets, accept connections threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "net", &ThreadSocketHandler)); // Initiate outbound connections from -addnode threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "addcon", &ThreadOpenAddedConnections)); // Initiate outbound connections threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "opencon", &ThreadOpenConnections)); // Process messages threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "msghand", &ThreadMessageHandler)); // Dump network addresses threadGroup.create_thread(boost::bind(&LoopForever<void (*)()>, "dumpaddr", &DumpAddresses, DUMP_ADDRESSES_INTERVAL * 1000)); } bool StopNode() { LogPrintf("StopNode()\n"); MapPort(false); mempool.AddTransactionsUpdated(1); if (semOutbound) for (int i=0; i<MAX_OUTBOUND_CONNECTIONS; i++) semOutbound->post(); DumpAddresses(); return true; } class CNetCleanup { public: CNetCleanup() { } ~CNetCleanup() { // Close sockets BOOST_FOREACH(CNode* pnode, vNodes) if (pnode->hSocket != INVALID_SOCKET) closesocket(pnode->hSocket); BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket) if (hListenSocket != INVALID_SOCKET) if (closesocket(hListenSocket) == SOCKET_ERROR) LogPrintf("closesocket(hListenSocket) failed with error %d\n", WSAGetLastError()); #ifdef WIN32 // Shutdown Windows Sockets WSACleanup(); #endif } } instance_of_cnetcleanup; void RelayTransaction(const CTransaction& tx, const uint256& hash) { CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss.reserve(10000); ss << tx; RelayTransaction(tx, hash, ss); } void RelayTransaction(const CTransaction& tx, const uint256& hash, const CDataStream& ss) { CInv inv(MSG_TX, hash); { LOCK(cs_mapRelay); // Expire old relay messages while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime()) { mapRelay.erase(vRelayExpiration.front().second); vRelayExpiration.pop_front(); } // Save original serialized message so newer versions are preserved mapRelay.insert(std::make_pair(inv, ss)); vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv)); } RelayInventory(inv); } void CNode::RecordBytesRecv(uint64_t bytes) { LOCK(cs_totalBytesRecv); nTotalBytesRecv += bytes; } void CNode::RecordBytesSent(uint64_t bytes) { LOCK(cs_totalBytesSent); nTotalBytesSent += bytes; } uint64_t CNode::GetTotalBytesRecv() { LOCK(cs_totalBytesRecv); return nTotalBytesRecv; } uint64_t CNode::GetTotalBytesSent() { LOCK(cs_totalBytesSent); return nTotalBytesSent; } // // CAddrDB // CAddrDB::CAddrDB() { pathAddr = GetDataDir() / "peers.dat"; } bool CAddrDB::Write(const CAddrMan& addr) { // Generate random temporary filename unsigned short randv = 0; RAND_bytes((unsigned char *)&randv, sizeof(randv)); std::string tmpfn = strprintf("peers.dat.%04x", randv); // serialize addresses, checksum data up to that point, then append csum CDataStream ssPeers(SER_DISK, CLIENT_VERSION); ssPeers << FLATDATA(Params().MessageStart()); ssPeers << addr; uint256 hash = Hash(ssPeers.begin(), ssPeers.end()); ssPeers << hash; // open temp output file, and associate with CAutoFile boost::filesystem::path pathTmp = GetDataDir() / tmpfn; FILE *file = fopen(pathTmp.string().c_str(), "wb"); CAutoFile fileout = CAutoFile(file, SER_DISK, CLIENT_VERSION); if (!fileout) return error("CAddrman::Write() : open failed"); // Write and commit header, data try { fileout << ssPeers; } catch (std::exception &e) { return error("CAddrman::Write() : I/O error"); } FileCommit(fileout); fileout.fclose(); // replace existing peers.dat, if any, with new peers.dat.XXXX if (!RenameOver(pathTmp, pathAddr)) return error("CAddrman::Write() : Rename-into-place failed"); return true; } bool CAddrDB::Read(CAddrMan& addr) { // open input file, and associate with CAutoFile FILE *file = fopen(pathAddr.string().c_str(), "rb"); CAutoFile filein = CAutoFile(file, SER_DISK, CLIENT_VERSION); if (!filein) return error("CAddrman::Read() : open failed"); // use file size to size memory buffer int fileSize = boost::filesystem::file_size(pathAddr); int dataSize = fileSize - sizeof(uint256); // Don't try to resize to a negative number if file is small if ( dataSize < 0 ) dataSize = 0; vector<unsigned char> vchData; vchData.resize(dataSize); uint256 hashIn; // read data and checksum from file try { filein.read((char *)&vchData[0], dataSize); filein >> hashIn; } catch (std::exception &e) { return error("CAddrman::Read() 2 : I/O error or stream data corrupted"); } filein.fclose(); CDataStream ssPeers(vchData, SER_DISK, CLIENT_VERSION); // verify stored checksum matches input data uint256 hashTmp = Hash(ssPeers.begin(), ssPeers.end()); if (hashIn != hashTmp) return error("CAddrman::Read() : checksum mismatch; data corrupted"); unsigned char pchMsgTmp[4]; try { // de-serialize file header (network specific magic number) and .. ssPeers >> FLATDATA(pchMsgTmp); // ... verify the network matches ours if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp))) return error("CAddrman::Read() : invalid network magic number"); // de-serialize address data into one CAddrMan object ssPeers >> addr; } catch (std::exception &e) { return error("CAddrman::Read() : I/O error or stream data corrupted"); } return true; }<|fim▁end|>
if (lockRecv)
<|file_name|>token_aware_policy.hpp<|end_file_name|><|fim▁begin|>/*<|fim▁hole|> Copyright (c) 2014-2016 DataStax 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. */ #ifndef __CASS_TOKEN_AWARE_POLICY_HPP_INCLUDED__ #define __CASS_TOKEN_AWARE_POLICY_HPP_INCLUDED__ #include "token_map.hpp" #include "load_balancing.hpp" #include "host.hpp" #include "scoped_ptr.hpp" namespace cass { class TokenAwarePolicy : public ChainedLoadBalancingPolicy { public: TokenAwarePolicy(LoadBalancingPolicy* child_policy) : ChainedLoadBalancingPolicy(child_policy) , index_(0) {} virtual ~TokenAwarePolicy() {} virtual void init(const Host::Ptr& connected_host, const HostMap& hosts, Random* random); virtual QueryPlan* new_query_plan(const std::string& connected_keyspace, RequestHandler* request_handler, const TokenMap* token_map); LoadBalancingPolicy* new_instance() { return new TokenAwarePolicy(child_policy_->new_instance()); } private: class TokenAwareQueryPlan : public QueryPlan { public: TokenAwareQueryPlan(LoadBalancingPolicy* child_policy, QueryPlan* child_plan, const CopyOnWriteHostVec& replicas, size_t start_index) : child_policy_(child_policy) , child_plan_(child_plan) , replicas_(replicas) , index_(start_index) , remaining_(replicas->size()) {} Host::Ptr compute_next(); private: LoadBalancingPolicy* child_policy_; ScopedPtr<QueryPlan> child_plan_; CopyOnWriteHostVec replicas_; size_t index_; size_t remaining_; }; size_t index_; private: DISALLOW_COPY_AND_ASSIGN(TokenAwarePolicy); }; } // namespace cass #endif<|fim▁end|>
<|file_name|>ManageIssueType.js<|end_file_name|><|fim▁begin|>var ManageIssueTypePage = new Ext.Panel({<|fim▁hole|> id : 'ezTrack_Manage_IssueType_Page', layout : 'fit', autoScroll : true, items: [ ManageIssueTypePanelEvent ] });<|fim▁end|>
<|file_name|>custom_metrics_stackdriver.go<|end_file_name|><|fim▁begin|>/* Copyright 2017 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package monitoring import ( "context" "time" gcm "google.golang.org/api/monitoring/v3" "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/selection" "k8s.io/client-go/discovery" cacheddiscovery "k8s.io/client-go/discovery/cached/memory" clientset "k8s.io/client-go/kubernetes" "k8s.io/client-go/restmapper" "k8s.io/kubernetes/test/e2e/framework" e2eskipper "k8s.io/kubernetes/test/e2e/framework/skipper" instrumentation "k8s.io/kubernetes/test/e2e/instrumentation/common" customclient "k8s.io/metrics/pkg/client/custom_metrics" externalclient "k8s.io/metrics/pkg/client/external_metrics" "github.com/onsi/ginkgo" "golang.org/x/oauth2/google" "google.golang.org/api/option" ) const ( stackdriverExporterPod1 = "stackdriver-exporter-1" stackdriverExporterPod2 = "stackdriver-exporter-2" stackdriverExporterLabel = "stackdriver-exporter" ) var _ = instrumentation.SIGDescribe("Stackdriver Monitoring", func() { ginkgo.BeforeEach(func() { e2eskipper.SkipUnlessProviderIs("gce", "gke") }) f := framework.NewDefaultFramework("stackdriver-monitoring") ginkgo.It("should run Custom Metrics - Stackdriver Adapter for old resource model [Feature:StackdriverCustomMetrics]", func() { kubeClient := f.ClientSet config, err := framework.LoadConfig() if err != nil { framework.Failf("Failed to load config: %s", err) } discoveryClient := discovery.NewDiscoveryClientForConfigOrDie(config) cachedDiscoClient := cacheddiscovery.NewMemCacheClient(discoveryClient) restMapper := restmapper.NewDeferredDiscoveryRESTMapper(cachedDiscoClient) restMapper.Reset() apiVersionsGetter := customclient.NewAvailableAPIsGetter(discoveryClient) customMetricsClient := customclient.NewForConfig(config, restMapper, apiVersionsGetter) testCustomMetrics(f, kubeClient, customMetricsClient, discoveryClient, AdapterForOldResourceModel) }) ginkgo.It("should run Custom Metrics - Stackdriver Adapter for new resource model [Feature:StackdriverCustomMetrics]", func() { kubeClient := f.ClientSet config, err := framework.LoadConfig() if err != nil { framework.Failf("Failed to load config: %s", err) } discoveryClient := discovery.NewDiscoveryClientForConfigOrDie(config) cachedDiscoClient := cacheddiscovery.NewMemCacheClient(discoveryClient) restMapper := restmapper.NewDeferredDiscoveryRESTMapper(cachedDiscoClient) restMapper.Reset() apiVersionsGetter := customclient.NewAvailableAPIsGetter(discoveryClient) customMetricsClient := customclient.NewForConfig(config, restMapper, apiVersionsGetter) testCustomMetrics(f, kubeClient, customMetricsClient, discoveryClient, AdapterForNewResourceModel) }) ginkgo.It("should run Custom Metrics - Stackdriver Adapter for external metrics [Feature:StackdriverExternalMetrics]", func() { kubeClient := f.ClientSet config, err := framework.LoadConfig() if err != nil { framework.Failf("Failed to load config: %s", err) } externalMetricsClient := externalclient.NewForConfigOrDie(config) testExternalMetrics(f, kubeClient, externalMetricsClient) }) })<|fim▁hole|>func testCustomMetrics(f *framework.Framework, kubeClient clientset.Interface, customMetricsClient customclient.CustomMetricsClient, discoveryClient *discovery.DiscoveryClient, adapterDeployment string) { projectID := framework.TestContext.CloudConfig.ProjectID ctx := context.Background() client, err := google.DefaultClient(ctx, gcm.CloudPlatformScope) framework.ExpectNoError(err) gcmService, err := gcm.NewService(ctx, option.WithHTTPClient(client)) if err != nil { framework.Failf("Failed to create gcm service, %v", err) } // Set up a cluster: create a custom metric and set up k8s-sd adapter err = CreateDescriptors(gcmService, projectID) if err != nil { framework.Failf("Failed to create metric descriptor: %s", err) } defer CleanupDescriptors(gcmService, projectID) err = CreateAdapter(f.Namespace.Name, adapterDeployment) if err != nil { framework.Failf("Failed to set up: %s", err) } defer CleanupAdapter(f.Namespace.Name, adapterDeployment) _, err = kubeClient.RbacV1().ClusterRoleBindings().Create(context.TODO(), HPAPermissions, metav1.CreateOptions{}) if err != nil { framework.Failf("Failed to create ClusterRoleBindings: %v", err) } defer kubeClient.RbacV1().ClusterRoleBindings().Delete(context.TODO(), HPAPermissions.Name, &metav1.DeleteOptions{}) // Run application that exports the metric _, err = createSDExporterPods(f, kubeClient) if err != nil { framework.Failf("Failed to create stackdriver-exporter pod: %s", err) } defer cleanupSDExporterPod(f, kubeClient) // Wait a short amount of time to create a pod and export some metrics // TODO: add some events to wait for instead of fixed amount of time // i.e. pod creation, first time series exported time.Sleep(60 * time.Second) verifyResponsesFromCustomMetricsAPI(f, customMetricsClient, discoveryClient) } // TODO(kawych): migrate this test to new resource model func testExternalMetrics(f *framework.Framework, kubeClient clientset.Interface, externalMetricsClient externalclient.ExternalMetricsClient) { projectID := framework.TestContext.CloudConfig.ProjectID ctx := context.Background() client, err := google.DefaultClient(ctx, gcm.CloudPlatformScope) framework.ExpectNoError(err) gcmService, err := gcm.NewService(ctx, option.WithHTTPClient(client)) if err != nil { framework.Failf("Failed to create gcm service, %v", err) } // Set up a cluster: create a custom metric and set up k8s-sd adapter err = CreateDescriptors(gcmService, projectID) if err != nil { framework.Failf("Failed to create metric descriptor: %s", err) } defer CleanupDescriptors(gcmService, projectID) // Both deployments - for old and new resource model - expose External Metrics API. err = CreateAdapter(f.Namespace.Name, AdapterForOldResourceModel) if err != nil { framework.Failf("Failed to set up: %s", err) } defer CleanupAdapter(f.Namespace.Name, AdapterForOldResourceModel) _, err = kubeClient.RbacV1().ClusterRoleBindings().Create(context.TODO(), HPAPermissions, metav1.CreateOptions{}) if err != nil { framework.Failf("Failed to create ClusterRoleBindings: %v", err) } defer kubeClient.RbacV1().ClusterRoleBindings().Delete(context.TODO(), HPAPermissions.Name, &metav1.DeleteOptions{}) // Run application that exports the metric pod, err := createSDExporterPods(f, kubeClient) if err != nil { framework.Failf("Failed to create stackdriver-exporter pod: %s", err) } defer cleanupSDExporterPod(f, kubeClient) // Wait a short amount of time to create a pod and export some metrics // TODO: add some events to wait for instead of fixed amount of time // i.e. pod creation, first time series exported time.Sleep(60 * time.Second) verifyResponseFromExternalMetricsAPI(f, externalMetricsClient, pod) } func verifyResponsesFromCustomMetricsAPI(f *framework.Framework, customMetricsClient customclient.CustomMetricsClient, discoveryClient *discovery.DiscoveryClient) { resources, err := discoveryClient.ServerResourcesForGroupVersion("custom.metrics.k8s.io/v1beta1") if err != nil { framework.Failf("Failed to retrieve a list of supported metrics: %s", err) } if !containsResource(resources.APIResources, "*/custom.googleapis.com|"+CustomMetricName) { framework.Failf("Metric '%s' expected but not received", CustomMetricName) } if !containsResource(resources.APIResources, "*/custom.googleapis.com|"+UnusedMetricName) { framework.Failf("Metric '%s' expected but not received", UnusedMetricName) } value, err := customMetricsClient.NamespacedMetrics(f.Namespace.Name).GetForObject(schema.GroupKind{Group: "", Kind: "Pod"}, stackdriverExporterPod1, CustomMetricName, labels.NewSelector()) if err != nil { framework.Failf("Failed query: %s", err) } if value.Value.Value() != CustomMetricValue { framework.Failf("Unexpected metric value for metric %s: expected %v but received %v", CustomMetricName, CustomMetricValue, value.Value) } filter, err := labels.NewRequirement("name", selection.Equals, []string{stackdriverExporterLabel}) if err != nil { framework.Failf("Couldn't create a label filter") } values, err := customMetricsClient.NamespacedMetrics(f.Namespace.Name).GetForObjects(schema.GroupKind{Group: "", Kind: "Pod"}, labels.NewSelector().Add(*filter), CustomMetricName, labels.NewSelector()) if err != nil { framework.Failf("Failed query: %s", err) } if len(values.Items) != 1 { framework.Failf("Expected results for exactly 1 pod, but %v results received", len(values.Items)) } if values.Items[0].DescribedObject.Name != stackdriverExporterPod1 || values.Items[0].Value.Value() != CustomMetricValue { framework.Failf("Unexpected metric value for metric %s and pod %s: %v", CustomMetricName, values.Items[0].DescribedObject.Name, values.Items[0].Value.Value()) } } func containsResource(resourcesList []metav1.APIResource, resourceName string) bool { for _, resource := range resourcesList { if resource.Name == resourceName { return true } } return false } func verifyResponseFromExternalMetricsAPI(f *framework.Framework, externalMetricsClient externalclient.ExternalMetricsClient, pod *v1.Pod) { req1, _ := labels.NewRequirement("resource.type", selection.Equals, []string{"gke_container"}) // It's important to filter out only metrics from the right namespace, since multiple e2e tests // may run in the same project concurrently. "dummy" is added to test req2, _ := labels.NewRequirement("resource.labels.pod_id", selection.In, []string{string(pod.UID), "dummy"}) req3, _ := labels.NewRequirement("resource.labels.namespace_id", selection.Exists, []string{}) req4, _ := labels.NewRequirement("resource.labels.zone", selection.NotEquals, []string{"dummy"}) req5, _ := labels.NewRequirement("resource.labels.cluster_name", selection.NotIn, []string{"foo", "bar"}) values, err := externalMetricsClient. NamespacedMetrics("dummy"). List("custom.googleapis.com|"+CustomMetricName, labels.NewSelector().Add(*req1, *req2, *req3, *req4, *req5)) if err != nil { framework.Failf("Failed query: %s", err) } if len(values.Items) != 1 { framework.Failf("Expected exactly one external metric value, but % values received", len(values.Items)) } if values.Items[0].MetricName != "custom.googleapis.com|"+CustomMetricName || values.Items[0].Value.Value() != CustomMetricValue || // Check one label just to make sure labels are included values.Items[0].MetricLabels["resource.labels.pod_id"] != string(pod.UID) { framework.Failf("Unexpected result for metric %s: %v", CustomMetricName, values.Items[0]) } } func cleanupSDExporterPod(f *framework.Framework, cs clientset.Interface) { err := cs.CoreV1().Pods(f.Namespace.Name).Delete(context.TODO(), stackdriverExporterPod1, &metav1.DeleteOptions{}) if err != nil { framework.Logf("Failed to delete %s pod: %v", stackdriverExporterPod1, err) } err = cs.CoreV1().Pods(f.Namespace.Name).Delete(context.TODO(), stackdriverExporterPod2, &metav1.DeleteOptions{}) if err != nil { framework.Logf("Failed to delete %s pod: %v", stackdriverExporterPod2, err) } } func createSDExporterPods(f *framework.Framework, cs clientset.Interface) (*v1.Pod, error) { pod, err := cs.CoreV1().Pods(f.Namespace.Name).Create(context.TODO(), StackdriverExporterPod(stackdriverExporterPod1, f.Namespace.Name, stackdriverExporterLabel, CustomMetricName, CustomMetricValue), metav1.CreateOptions{}) if err != nil { return nil, err } _, err = cs.CoreV1().Pods(f.Namespace.Name).Create(context.TODO(), StackdriverExporterPod(stackdriverExporterPod2, f.Namespace.Name, stackdriverExporterLabel, UnusedMetricName, UnusedMetricValue), metav1.CreateOptions{}) return pod, err }<|fim▁end|>