prompt
large_stringlengths 70
991k
| completion
large_stringlengths 0
1.02k
|
---|---|
<|file_name|>problemdao.py<|end_file_name|><|fim▁begin|>'''
mysql> desc problem;
+-------------+---------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+---------------+------+-----+---------+----------------+
| pid | int(11) | NO | PRI | NULL | auto_increment |
| title | varchar(255) | YES | | NULL | |
| source | varchar(255) | YES | | NULL | |
| url | varchar(1024) | YES | | NULL | |
| originOJ | varchar(255) | YES | | NULL | |
| originProb | varchar(45) | YES | | NULL | |
| memorylimit | varchar(45) | YES | | NULL | |
| timelimit | varchar(45) | YES | | NULL | |
+-------------+---------------+------+-----+---------+----------------+
mysql> desc problemdetail;
+--------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+--------------+------+-----+---------+----------------+
| did | int(11) | NO | PRI | NULL | auto_increment |
| pid | int(11) | YES | MUL | NULL | |
| description | text | YES | | NULL | |
| input | text | YES | | NULL | |
| output | text | YES | | NULL | |
| sampleinput | text | YES | | NULL | |
| sampleoutput | text | YES | | NULL | |
| hint | text | YES | | NULL | |
| author | varchar(255) | YES | | NULL | |
| source | varchar(255) | YES | | NULL | |
| updateTime | datetime | YES | | NULL | |
+--------------+--------------+------+-----+---------+----------------+
'''
import pickle
import time
from tools.encode import Base64StrToUTF8Str, UTF8StrToBase64Str
from tools.dbcore import ConnPool
from tools.dbtools import getQuerySQL,getInserSQL, getUpdateSQL,FetchAll,FetchOne,ExeSQL
def GetProblemID(orj, orid):
sql = 'SELECT problem.pid FROM problem WHERE ' \
'( problem.originOJ LIKE "{}" AND problem.originProb LIKE "{}" )'.format(orj, orid)
conn = ConnPool.connect()
cur = conn.cursor()
cur.execute(sql)
tp = cur.fetchall()
cur.close()
conn.close()
if tp.__len__() == 0:
return 0
else:
return tp[0][0]
def pretreat_Problem(problem):
pass
'''
if 'source' in problem :
problem['source'] = UTF8StrToBase64Str(problem['source'])
'''
def InsertProblem(problem):
pretreat_Problem(problem)
sql = getInserSQL('problem', problem)
ExeSQL(sql)
def UpdateProblem(problem, pid):
pretreat_Problem(problem)
cluse = 'pid = {}'.format(pid)
sql = getUpdateSQL('problem', data=problem, clause=cluse)
#print('Update',sql)
ExeSQL(sql)
def pretreat_ProblemDetail(problem):
baselist = ['description', 'input', 'output', 'sampleinput', 'sampleoutput',
'hint', 'author', 'source']
for key in problem:
if problem[key] is None:
continue
if key in baselist:
problem[key] = UTF8StrToBase64Str(problem[key])
def InsertProblemDetail(problem):
pretreat_ProblemDetail(problem)
sql = getInserSQL('problemdetail', problem)
ExeSQL(sql)
def UpdateProblemDetail(problem, pid):
pretreat_ProblemDetail(problem)<|fim▁hole|> rs = FetchOne(sql)
if rs is None :
InsertProblemDetail(problem)
else :
clause = 'problemdetail.pid = %d' % pid
sql = getUpdateSQL('problemdetail', data=problem, clause=clause)
ExeSQL(sql)
problem = dict(
title=None,
source=None,
url=None,
originOJ=None,
originProb=None,
virtualOJ=None,
virtualProb=None,
)
problemdetail = dict(
pid=None,
description=None,
input=None,
output=None,
sampleinput=None,
sampleoutput=None,
hint=None,
author=None,
source=None,
updatetime=None,
memorylimit=None,
timelimit=None,
specialjudge=False,
)
def InsertOrUpdateProblem(kwargs):
pd = problem.copy()
pdd = problemdetail.copy()
for key in kwargs:
if key in pd:
pd[key] = kwargs[key]
if key in pdd:
pdd[key] = kwargs[key]
pid = GetProblemID(pd['originOJ'], pd['originProb'])
print('pid ---> ',pid)
if pid == 0:
# Insert problem table
InsertProblem(pd)
pid = GetProblemID(pd['originOJ'], pd['originProb'])
pdd['pid'] = pid
# Insert problemDetail title
InsertProblemDetail(pdd)
else:
pdd['pid'] = pid
# Update problem table
print('Update problem table')
UpdateProblem(pd, pid)
# Update problemDetail table
print('Update problemDetail table')
UpdateProblemDetail(pdd, pid)
'''
print('-'*30)
print(pd)
print('-'*30)
print(pdd)
print('-'*30)
'''
def test1():
print(time.strftime('%Y-%m-%d %H:%M:%S'))
def main():
f = open('/home/ckboss/Desktop/Development/testData/POJ/POJ_4050.pkl', 'rb')
data = pickle.load(f)
data['updatetime'] = time.strftime('%Y-%m-%d %H:%M:%S')
InsertOrUpdateProblem(data)
'''
f = open('/tmp/HDOJ5011.pkl','rb')
data = pickle.load(f)
InsertOrUpdateProblem(data)
'''
if __name__ == '__main__':
#main()
test1()<|fim▁end|>
|
sql = getQuerySQL('problemdetail',' pid={} '.format(pid),' did ')
|
<|file_name|>SystemTrainingPlugin.java<|end_file_name|><|fim▁begin|>/*
* Encog(tm) Core v3.1 - Java Version
* http://www.heatonresearch.com/encog/
* http://code.google.com/p/encog-java/
* Copyright 2008-2012 Heaton Research, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information on Heaton Research copyrights, licenses
* and trademarks visit:
* http://www.heatonresearch.com/copyright
*/
package org.encog.plugin.system;
import org.encog.EncogError;
import org.encog.engine.network.activation.ActivationFunction;
import org.encog.ml.MLMethod;
import org.encog.ml.data.MLDataSet;
import org.encog.ml.factory.MLTrainFactory;<|fim▁hole|>import org.encog.ml.factory.train.LMAFactory;
import org.encog.ml.factory.train.ManhattanFactory;
import org.encog.ml.factory.train.NeighborhoodSOMFactory;
import org.encog.ml.factory.train.NelderMeadFactory;
import org.encog.ml.factory.train.PNNTrainFactory;
import org.encog.ml.factory.train.PSOFactory;
import org.encog.ml.factory.train.QuickPropFactory;
import org.encog.ml.factory.train.RBFSVDFactory;
import org.encog.ml.factory.train.RPROPFactory;
import org.encog.ml.factory.train.SCGFactory;
import org.encog.ml.factory.train.SVMFactory;
import org.encog.ml.factory.train.SVMSearchFactory;
import org.encog.ml.factory.train.TrainBayesianFactory;
import org.encog.ml.train.MLTrain;
import org.encog.plugin.EncogPluginBase;
import org.encog.plugin.EncogPluginService1;
public class SystemTrainingPlugin implements EncogPluginService1 {
/**
* The factory for K2
*/
private final TrainBayesianFactory bayesianFactory = new TrainBayesianFactory();
/**
* The factory for backprop.
*/
private final BackPropFactory backpropFactory = new BackPropFactory();
/**
* The factory for LMA.
*/
private final LMAFactory lmaFactory = new LMAFactory();
/**
* The factory for RPROP.
*/
private final RPROPFactory rpropFactory = new RPROPFactory();
/**
* THe factory for basic SVM.
*/
private final SVMFactory svmFactory = new SVMFactory();
/**
* The factory for SVM-Search.
*/
private final SVMSearchFactory svmSearchFactory = new SVMSearchFactory();
/**
* The factory for SCG.
*/
private final SCGFactory scgFactory = new SCGFactory();
/**
* The factory for simulated annealing.
*/
private final AnnealFactory annealFactory = new AnnealFactory();
/**
* Nelder Mead Factory.
*/
private final NelderMeadFactory nmFactory = new NelderMeadFactory();
/**
* The factory for neighborhood SOM.
*/
private final NeighborhoodSOMFactory neighborhoodFactory
= new NeighborhoodSOMFactory();
/**
* The factory for SOM cluster.
*/
private final ClusterSOMFactory somClusterFactory = new ClusterSOMFactory();
/**
* The factory for genetic.
*/
private final GeneticFactory geneticFactory = new GeneticFactory();
/**
* The factory for Manhattan networks.
*/
private final ManhattanFactory manhattanFactory = new ManhattanFactory();
/**
* Factory for SVD.
*/
private final RBFSVDFactory svdFactory = new RBFSVDFactory();
/**
* Factory for PNN.
*/
private final PNNTrainFactory pnnFactory = new PNNTrainFactory();
/**
* Factory for quickprop.
*/
private final QuickPropFactory qpropFactory = new QuickPropFactory();
private final PSOFactory psoFactory = new PSOFactory();
/**
* {@inheritDoc}
*/
@Override
public final String getPluginDescription() {
return "This plugin provides the built in training " +
"methods for Encog.";
}
/**
* {@inheritDoc}
*/
@Override
public final String getPluginName() {
return "HRI-System-Training";
}
/**
* @return This is a type-1 plugin.
*/
@Override
public final int getPluginType() {
return 1;
}
/**
* This plugin does not support activation functions, so it will
* always return null.
* @return Null, because this plugin does not support activation functions.
*/
@Override
public ActivationFunction createActivationFunction(String name) {
return null;
}
@Override
public MLMethod createMethod(String methodType, String architecture,
int input, int output) {
// TODO Auto-generated method stub
return null;
}
@Override
public MLTrain createTraining(MLMethod method, MLDataSet training,
String type, String args) {
String args2 = args;
if (args2 == null) {
args2 = "";
}
if (MLTrainFactory.TYPE_RPROP.equalsIgnoreCase(type)) {
return this.rpropFactory.create(method, training, args2);
} else if (MLTrainFactory.TYPE_BACKPROP.equalsIgnoreCase(type)) {
return this.backpropFactory.create(method, training, args2);
} else if (MLTrainFactory.TYPE_SCG.equalsIgnoreCase(type)) {
return this.scgFactory.create(method, training, args2);
} else if (MLTrainFactory.TYPE_LMA.equalsIgnoreCase(type)) {
return this.lmaFactory.create(method, training, args2);
} else if (MLTrainFactory.TYPE_SVM.equalsIgnoreCase(type)) {
return this.svmFactory.create(method, training, args2);
} else if (MLTrainFactory.TYPE_SVM_SEARCH.equalsIgnoreCase(type)) {
return this.svmSearchFactory.create(method, training, args2);
} else if (MLTrainFactory.TYPE_SOM_NEIGHBORHOOD.equalsIgnoreCase(
type)) {
return this.neighborhoodFactory.create(method, training, args2);
} else if (MLTrainFactory.TYPE_ANNEAL.equalsIgnoreCase(type)) {
return this.annealFactory.create(method, training, args2);
} else if (MLTrainFactory.TYPE_GENETIC.equalsIgnoreCase(type)) {
return this.geneticFactory.create(method, training, args2);
} else if (MLTrainFactory.TYPE_SOM_CLUSTER.equalsIgnoreCase(type)) {
return this.somClusterFactory.create(method, training, args2);
} else if (MLTrainFactory.TYPE_MANHATTAN.equalsIgnoreCase(type)) {
return this.manhattanFactory.create(method, training, args2);
} else if (MLTrainFactory.TYPE_SVD.equalsIgnoreCase(type)) {
return this.svdFactory.create(method, training, args2);
} else if (MLTrainFactory.TYPE_PNN.equalsIgnoreCase(type)) {
return this.pnnFactory.create(method, training, args2);
} else if (MLTrainFactory.TYPE_QPROP.equalsIgnoreCase(type)) {
return this.qpropFactory.create(method, training, args2);
} else if (MLTrainFactory.TYPE_BAYESIAN.equals(type) ) {
return this.bayesianFactory.create(method, training, args2);
} else if (MLTrainFactory.TYPE_NELDER_MEAD.equals(type) ) {
return this.nmFactory.create(method, training, args2);
} else if (MLTrainFactory.TYPE_PSO.equals(type) ) {
return this.psoFactory.create(method, training, args2);
}
else {
throw new EncogError("Unknown training type: " + type);
}
}
/**
* {@inheritDoc}
*/
@Override
public int getPluginServiceType() {
return EncogPluginBase.TYPE_SERVICE;
}
}<|fim▁end|>
|
import org.encog.ml.factory.train.AnnealFactory;
import org.encog.ml.factory.train.BackPropFactory;
import org.encog.ml.factory.train.ClusterSOMFactory;
import org.encog.ml.factory.train.GeneticFactory;
|
<|file_name|>ScrollStrategy.js<|end_file_name|><|fim▁begin|>/**
enyo.ScrollStrategy is a helper kind which implements a default scrolling strategy for an <a href="#enyo.Scroller">enyo.Scroller</a>.
enyo.ScrollStrategy is not typically created in application code.
*/
enyo.kind({
name: "enyo.ScrollStrategy",
noDom: true,
events: {
onScroll: "doScroll"
},
published: {
/**
Specifies how to horizontally scroll. Acceptable values are:
* "scroll": always shows a scrollbar; sets overflow: scroll
* "auto": scrolls only if needed; sets overflow: auto
* "hidden": never scrolls; sets overflow: hidden
* "default": same as auto.
*/
vertical: "default",
/**
Specifies how to vertically scroll. Acceptable values are:
* "scroll": always shows a scrollbar; sets overflow: scroll
* "auto": scrolls only if needed; sets overflow: auto
* "hidden": never scrolls; sets overflow: hidden
* "default": same as auto.
*/
horizontal: "default",
scrollLeft: 0,
scrollTop: 0
},
//* @protected
handlers: {
onscroll: "scroll",
ondown: "down",
onmove: "move"
},
create: function() {
this.inherited(arguments);
this.horizontalChanged();
this.verticalChanged();
this.container.setAttribute("onscroll", enyo.bubbler);
},
rendered: function() {
this.inherited(arguments);
this.scrollNode = this.calcScrollNode();
},
teardownRender: function() {
this.inherited(arguments);
this.scrollNode = null;
},
calcScrollNode: function() {
return this.container.hasNode();
},
horizontalChanged: function() {
this.container.applyStyle("overflow-x", this.horizontal == "default" ? "auto" : this.horizontal);
},<|fim▁hole|> this.container.applyStyle("overflow-y", this.vertical == "default" ? "auto" : this.vertical);
},
scroll: function(inSender, e) {
return this.doScroll(e);
},
scrollTo: function(inX, inY) {
if (this.scrollNode) {
this.setScrollLeft(inX);
this.setScrollTop(inY);
}
},
scrollIntoView: function(inControl, inAlignWithTop) {
if (inControl.hasNode()) {
inControl.node.scrollIntoView(inAlignWithTop);
}
},
setScrollTop: function(inTop) {
this.scrollTop = inTop;
if (this.scrollNode) {
this.scrollNode.scrollTop = this.scrollTop;
}
},
setScrollLeft: function(inLeft) {
this.scrollLeft = inLeft;
if (this.scrollNode) {
this.scrollNode.scrollLeft = this.scrollLeft;
}
},
getScrollLeft: function() {
return this.scrollNode ? this.scrollNode.scrollLeft : this.scrollLeft;
},
getScrollTop: function() {
return this.scrollNode ? this.scrollNode.scrollTop : this.scrollTop;
},
getScrollBounds: function() {
var n = this.scrollNode;
var b = {
left: this.getScrollLeft(),
top: this.getScrollTop(),
height: n ? n.scrollHeight : 0,
width: n ? n.scrollWidth : 0
};
b.maxLeft = Math.max(0, b.width - n.clientWidth);
b.maxTop = Math.max(0, b.height - n.clientHeight);
return b;
},
// NOTE: down, move handlers are needed only for native touch scrollers
// avoid allowing scroll when starting at a vertical boundary to prevent ios from window scrolling.
down: function(inSender, inEvent) {
// if we start on a boundary, need to check direction of first move
var y = this.getScrollTop();
this.atTopEdge = (y == 0);
var sb = this.getScrollBounds();
this.atBottomEdge = y == sb.maxTop;
this.downY = inEvent.pageY;
this.downX = inEvent.pageX;
this.canVertical = sb.maxTop > 0 && this.vertical != "hidden";
this.canHorizontal = sb.maxLeft > 0 && this.horizontal != "hidden";
},
// NOTE: mobile native scrollers need touchmove. Indicate this by
// setting the requireTouchmove property to true (must do this in move event
// because must respond to first move or native action fails).
move: function(inSender, inEvent) {
var dy = inEvent.pageY - this.downY;
var dx = inEvent.pageX - this.downX;
var v = this.canVertical, h = this.canHorizontal;
// check to see if it is dragging vertically which would trigger window scrolling
var isV = (Math.abs(dy) > 10) && (Math.abs(dy) > Math.abs(dx));
// abort scroll if dragging oob from vertical edge
if (isV && (v || h) && (this.atTopEdge || this.atBottomEdge)) {
var oob = (this.atTopEdge && (dy >= 0) || this.atBottomEdge && (dy <= 0));
// we only need to abort 1 event to prevent window native scrolling, but we
// perform oob check around a small radius because a small in bounds move may
// not trigger scrolling for this scroller meaning the window might still scroll.
if (Math.abs(dy) > 25) {
this.atTopEdge = this.atBottomEdge = false;
}
if (oob) {
return;
}
}
inEvent.requireTouchmove = (v || h);
}
});<|fim▁end|>
|
verticalChanged: function() {
|
<|file_name|>populate.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
from datetime import timedelta
import os
import random
from django.utils.dateparse import parse_date
from faker import Faker
test_email = '[email protected]'
fake = Faker('de')<|fim▁hole|>random.seed(1)
def get_random_date():
return parse_date('1983-03-31') + timedelta(days=random.randint(-5000,
1000))
def populate():
for _ in range(100):
candidate = add_candidate(first_name=fake.first_name(),
last_name=fake.last_name(),
date_of_birth=get_random_date())
add_registration(candidate=candidate,
bicycle_kind=random.randint(1, 4),
email=fake.email())
def add_candidate(first_name, last_name, date_of_birth):
return Candidate.objects.create(first_name=first_name,
last_name=last_name,
date_of_birth=date_of_birth)
def add_registration(candidate, bicycle_kind, email):
return UserRegistration.objects.create(candidate=candidate,
bicycle_kind=bicycle_kind,
email=email)
def add_event(due_date):
return HandoutEvent.objects.create(due_date=due_date)
def add_bicycle():
b = Bicycle.objects.create()
return b
# Start execution here!
if __name__ == '__main__':
print("Starting FIRST_APP population script...")
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bwb.settings')
import django
django.setup()
from register.models import UserRegistration, Candidate, Bicycle
from register.models import HandoutEvent
populate()<|fim▁end|>
|
fake.seed(1)
|
<|file_name|>apInv.py<|end_file_name|><|fim▁begin|>#!usr/bin/env python
from pysnmp.entity.rfc3413.oneliner import cmdgen
import shlex
import subprocess
import re
import os
import sys
import smtplib
from devices.models import AP as AccessPoint
## This file is used to update the access point inventory data. Use the
## updateAccessPoints function to run the update. The function
## updateStatus will only check if the APs are up or down, and send an
## email report on APs that are currently down or that have recovered.
## Do an snmpwalk using cmdgen from PySNMP to get data about each AP.
## Takes a dictionary of OIDs and a list of controller IPs.
def snmpwalk(OIDs, controllers):
APs = dict()
cmdGen = cmdgen.CommandGenerator()
for key in OIDs:
for controller in controllers:
errorIndication, errorStatus, errorIndex, varBindTable = cmdGen.bulkCmd(
cmdgen.CommunityData('spa'),<|fim▁hole|> cmdgen.UdpTransportTarget((controller, 161)),
0, 1000, OIDs[key]
)
for varBindTableRow in varBindTable:
for name, val in varBindTableRow:
## make a unique identifier for each AP
num = str(name)[len(OIDs["mac"]):].strip('.')
try:
if key not in APs[num]:
APs[num][key] = str(val.prettyPrint())
except:
APs[num] = {key: str(val.prettyPrint())}
return APs
## Add or update all access points using Django.
def updateAccessPoints(path, AP_OIDs, controller_IPs):
APs = snmpwalk(AP_OIDs, controller_IPs)
for AP in APs:
if APs[AP]["serial"] != "0":
## make a new AP object if necessary
try:
new_AP = AccessPoint(serialno=APs[AP]["serial"], ip=APs[AP]["ip"])
new_AP.save()
except:
pass
## Update the AP's data
update_AP = AccessPoint.objects.get(serialno=APs[AP]["serial"], autoupdate=1)
update_AP.ip = APs[AP]["ip"]
update_AP.mac = APs[AP]["mac"].lower()[2:]
update_AP.name = APs[AP]["name"]
update_AP.model = APs[AP]["model"]
update_AP.save()
## Get the names of all the access points which are currently up and connected to
## a controller. Compare to the names in the database to find the APs that are down.
def updateStatus(controller_IPs, status_oid, email):
AP_command = []
for controller in controller_IPs:
AP_command.append("snmpwalk -v2c -c spa " + controller + " " + status_oid)
# Get the names of the APs connected to each controller.
# Compare to APs stored in the database to determine which are down and
# which have recovered.
upAPs = []
for cmd in AP_command:
upAPs.extend(runCommand(cmd))
storedAPs = AccessPoint.objects.all()
downAPs = []
recoveredAPs = []
for ap in storedAPs:
if ap.name not in upAPs:
ap.laststatus = "down"
if ap.checkstatus == True:
downAPs.append(ap)
else:
if ap.laststatus == "down" and ap.checkstatus == True:
recoveredAPs.append(ap)
ap.laststatus = "up"
ap.save()
# Send emails about down or recovered access points.
if len(downAPs) > 0:
message = '\nThe following access points are not responding:\n'
subject = 'APs are not responding'
sendEmail(message, subject, downAPs, email)
if len(recoveredAPs) > 0:
message = '\nThe following access points were down but have recovered:\n'
subject = 'APs have recovered'
sendEmail(message, subject, recoveredAPs, email)
#takes a string "com" and runs the command, returning a list of AP names
def runCommand(com):
args = shlex.split(com) #separates com into indv. args
p = subprocess.Popen(args, stdout=subprocess.PIPE) #runs command, saves stdout
#communicate() returns a tuple (stdout,stderr) but we only want stdout
stdout = p.communicate()[0]
#clean the data
stdout = stdout.replace("SNMPv2-SMI::enterprises.","")
stdout = stdout.replace("Hex-STRING:","")
stdout = stdout.replace("STRING:","")
stdout = stdout.replace("IpAddress:","")
stdout = stdout.replace("\"", "")
stdout = stdout.replace(" ", "")
#split stdout into lines
stdoutLines = stdout.split("\n")
stdoutLines = stdoutLines[:-1] #removes last empty row
#parse stdout into list
names = []
for line in stdoutLines:
names.append(line.split("=")[1])
return names
## Send an email report on access point status.
def sendEmail(messageBody, subject, APs, email):
for ap in APs:
messageBody += "\t" + ap.ip + "\t" + ap.name + "\n"
toHeaderBuild = []
for to in email["to"]:
toHeaderBuild.append("<" + to + ">")
msg = "From: <" + email["from"] + "> \nTo: " + ', '.join(toHeaderBuild) + " \nSubject: " + subject + " \n" + messageBody
s = smtplib.SMTP(email["server"])
s.sendmail(email["from"], email["to"], msg)
s.quit()<|fim▁end|>
| |
<|file_name|>NewFileBase.py<|end_file_name|><|fim▁begin|>import sublime
import sublime_plugin
import re
import os
import datetime
TMLP_DIR = 'templates'
KEY_SYNTAX = 'syntax'
KEY_FILE_EXT = 'extension'
IS_GTE_ST3 = int(sublime.version()) >= 3000
PACKAGE_NAME = 'new-file-pro'
PACKAGES_PATH = sublime.packages_path()
BASE_PATH = os.path.abspath(os.path.dirname(__file__))
class NewFileBase(sublime_plugin.WindowCommand):
def __init__(self, window):
super(NewFileBase, self).__init__(window)
def appendFileExtension(self, name, t):
tmp = name.split('.')
length = len(tmp)
s_ext = tmp[length - 1]
exts = {'css': 'css', 'html': 'html', 'js': 'js', 'json': 'json', 'php': 'php', 'php-class': 'php', 'php-interface': 'php', 'xml':'xml', 'python': 'python', 'ruby': 'ruby'}
try:
t_ext = exts[t]
if (s_ext == t_ext and length == 1) or s_ext != t_ext:
return name + '.' + t_ext
except KeyError:
pass
return name;
def appendPHPExtension(self, name):
t = name.split('.')
length = len(t)
ext = t[length - 1]
if ext != "php":
return name + '.php'
return name;
def get_code(self, type='text' ):
code = ''
file_name = "%s.tmpl" % type
isIOError = False
if IS_GTE_ST3:
tmpl_dir = 'Packages/' + PACKAGE_NAME + '/' + TMLP_DIR + '/'
user_tmpl_dir = 'Packages/User/' + PACKAGE_NAME + '/' + TMLP_DIR + '/'
else:
tmpl_dir = os.path.join(PACKAGES_PATH, PACKAGE_NAME, TMLP_DIR)
user_tmpl_dir = os.path.join(PACKAGES_PATH, 'User', PACKAGE_NAME, TMLP_DIR)
self.user_tmpl_path = os.path.join(user_tmpl_dir, file_name)
self.tmpl_path = os.path.join(tmpl_dir, file_name)
if IS_GTE_ST3:
try:
code = sublime.load_resource(self.user_tmpl_path)
except IOError:
try:
code = sublime.load_resource(self.tmpl_path)
except IOError:
isIOError = True
else:
if os.path.isfile(self.user_tmpl_path):
code = self.open_file(self.user_tmpl_path)
elif os.path.isfile(self.tmpl_path):
code = self.open_file(self.tmpl_path)
else:
isIOError = True
if isIOError:
sublime.message_dialog('[Warning] No such file: ' + self.tmpl_path + ' or ' + self.user_tmpl_path)
return self.format_tag(code)
def format_tag(self, code):
win = sublime.active_window()
code = code.replace('\r', '') # replace \r\n -> \n
# format
settings = self.get_settings()
format = settings.get('date_format', '%Y-%m-%d')
date = datetime.datetime.now().strftime(format)
if not IS_GTE_ST3:
code = code.decode('utf8') # for st2 && Chinese characters
code = code.replace('${date}', date)
attr = settings.get('attr', {})
for key in attr:
code = code.replace('${%s}' % key, attr.get(key, ''))
if settings.get('enable_project_variables', False) and hasattr(win, 'extract_variables'):
variables = win.extract_variables()
for key in ['project_base_name', 'project_path', 'platform']:
code = code.replace('${%s}' % key, variables.get(key, ''))
code = re.sub(r"(?<!\\)\${(?!\d)", '\${', code)
return code
def open_file(self, path, mode='r'):
fp = open(path, mode)
code = fp.read()
fp.close()
return code<|fim▁hole|> if not type:
return settings
opts = settings.get(type, [])
return opts<|fim▁end|>
|
def get_settings(self, type=None):
settings = sublime.load_settings(PACKAGE_NAME + '.sublime-settings')
|
<|file_name|>wwa_camera.ts<|end_file_name|><|fim▁begin|>import { WWAConsts, Position, Direction, speedList } from "./wwa_data";
import { Player } from "./wwa_parts_player";
export class Camera {
private _player: Player;
private _position: Position;
private _positionPrev: Position;
private _transitionStep: number;
private _isResetting: boolean;
/**
現在のプレイヤー座標が含まれるカメラ位置(表示画面左上)を含むカメラを作ります.
@param position: Position 現在のプレイヤー座標
*/
constructor(position: Position) {
this._position = null;
this.reset(position);
}
public setPlayer(player: Player): void {
this._player = player;
}
public isResetting(): boolean {
return this._isResetting;
}
public getPosition(): Position {
return this._position;
}
public getPreviousPosition(): Position {
return this._positionPrev;
}
public resetPreviousPosition(): void {
this._positionPrev = null;
}
// throws OutOfWWAMapRangeError;
public move(dir: Direction): void {
var speed = speedList[this._player.getSpeedIndex()];
this._position = this._position.getNextFramePosition(
dir, speed * (WWAConsts.H_PARTS_NUM_IN_WINDOW - 1), speed * (WWAConsts.V_PARTS_NUM_IN_WINDOW - 1));
}
public getTransitionStepNum(): number {
return this._transitionStep;
}
public advanceTransitionStepNum(): number {
++this._transitionStep;
if (this._transitionStep === WWAConsts.V_PARTS_NUM_IN_WINDOW) {
this._isResetting = false;
this._transitionStep = 0;
}
return this._transitionStep;
}
public isFinalStep(): boolean {<|fim▁hole|> if (this._isResetting === false) {
throw new Error("リセット中ではありません。");
}
return this._transitionStep === WWAConsts.V_PARTS_NUM_IN_WINDOW - 1;
}
public reset(position: Position): void {
this._positionPrev = this._position;
this._position = position.getDefaultCameraPosition();
this._transitionStep = 0;
this._isResetting = true;
}
}<|fim▁end|>
| |
<|file_name|>bluetooth_control.go<|end_file_name|><|fim▁begin|>// -*- Mode: Go; indent-tabs-mode: t -*-
/*
* Copyright (C) 2016-2017 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package builtin
const bluetoothControlSummary = `allows managing the kernel bluetooth stack`
const bluetoothControlBaseDeclarationSlots = `
bluetooth-control:
allow-installation:
slot-snap-type:
- core
deny-auto-connection: true
`
const bluetoothControlConnectedPlugAppArmor = `
# Description: Allow managing the kernel side Bluetooth stack. Reserved
# because this gives privileged access to the system.
network bluetooth,
# For crypto functionality the kernel offers
network alg,
capability net_admin,
# File accesses
/sys/bus/usb/drivers/btusb/ r,
/sys/bus/usb/drivers/btusb/** r,
/sys/module/btusb/ r,
/sys/module/btusb/** r,
/sys/class/bluetooth/ r,
/sys/devices/**/bluetooth/ rw,
/sys/devices/**/bluetooth/** rw,
# Requires CONFIG_BT_VHCI to be loaded
/dev/vhci rw,
`
const bluetoothControlConnectedPlugSecComp = `
# Description: Allow managing the kernel side Bluetooth stack. Reserved<|fim▁hole|>var bluetoothControlConnectedPlugUDev = []string{`SUBSYSTEM=="bluetooth"`}
func init() {
registerIface(&commonInterface{
name: "bluetooth-control",
summary: bluetoothControlSummary,
implicitOnCore: true,
implicitOnClassic: true,
baseDeclarationSlots: bluetoothControlBaseDeclarationSlots,
connectedPlugAppArmor: bluetoothControlConnectedPlugAppArmor,
connectedPlugSecComp: bluetoothControlConnectedPlugSecComp,
connectedPlugUDev: bluetoothControlConnectedPlugUDev,
reservedForOS: true,
})
}<|fim▁end|>
|
# because this gives privileged access to the system.
bind
`
|
<|file_name|>index.ts<|end_file_name|><|fim▁begin|>// This file is generated automatically by `scripts/build/fp.js`. Please, don't change it.<|fim▁hole|>export default convertToFP(fn, 2)<|fim▁end|>
|
import fn from '../../subQuarters/index'
import convertToFP from '../_lib/convertToFP/index'
|
<|file_name|>configuration.py<|end_file_name|><|fim▁begin|>from logger import log
import os
import gconf<|fim▁hole|>
class Configuration(object):
def __init__(self):
self._config = {}
self._file_path = os.path.join(os.path.dirname(__file__), 'config',
'config.ini')
# Read Files
self._read_file()
def get_value(self, key):
if key in self._config:
log.debug("[Config] Getting Value for %s" % key)
value = self._config[key]
if value == "True":
return True
elif value == "False":
return False
return value
else:
return None
def set_value(self, key, value):
self._config[key] = value
self._write_file()
def _write_file(self):
f = file(self._file_path, "wb")
config_list = [("%s=%s\n" % (key, value)) for key,
value in self._config.iteritems()]
f.writelines(config_list)
f.close()
def _read_file(self):
f = file(self._file_path, "rb")
file_list = f.readlines()
f.close()
self._config = {} # reset config
for line in file_list:
line = line.strip()
if len(line) > 0:
name, value = line.split("=")
value = value.strip()
value = value.replace("[", "")
value = value.replace("]", "")
value = value.replace("'", "")
if value.find(",") > -1:
self.set_value(name, [v.strip() for v in value.split(',')])
else:
self.set_value(name, value)
log.info("[Config] Config Map = %s", self._config)<|fim▁end|>
|
import urllib
|
<|file_name|>run_experiment_cluster.py<|end_file_name|><|fim▁begin|>import os, sys, re
import ConfigParser
import optparse
import shutil
import subprocess
import difflib
import collections
#import numpy as np
# Alberto Meseguer file; 18/11/2016
# Modified by Quim Aguirre; 13/03/2017
# This file is the master coordinator of the DIANA project. It is used to run multiple DIANA commands in parallel in the cluster
#-------------#
# Functions #
#-------------#
#-------------#
# Options #
#-------------#
def parse_options():
'''
This function parses the command line arguments and returns an optparse object.
'''
parser = optparse.OptionParser("pddi.py [--dummy=DUMMY_DIR] -i INPUT_FILE [-o OUTPUT_DIR] [-v]")
# Directory arguments
parser.add_option("-i", action="store", type="string", dest="input_file", help="Input crossings file", metavar="INPUT_FILE")
parser.add_option("-s", action="store", type="string", dest="sif_file", help="Input SIF file")
parser.add_option("-t", action="store", type="string", dest="type_of_analysis", help="Type of analysis: 'profile_creation' or 'comparison'")
parser.add_option("--dummy_dir", default="dummy/", action="store", type="string", dest="dummy_dir", help="Dummy directory (default = ./)", metavar="DUMMY_DIR")
parser.add_option('-ws','--worspace',dest='workspace',action = 'store',default=os.path.join(os.path.dirname(__file__), 'workspace'),
help = """Define the workspace directory where the data directory and the results directory will be created""")
(options, args) = parser.parse_args()
if options.input_file is None or options.sif_file is None or options.type_of_analysis is None:
parser.error("missing arguments: type option \"-h\" for help")
return options
#-------------#
# Main #
#-------------#
# Add "." to sys.path #
src_path = os.path.abspath(os.path.dirname(__file__))
sys.path.append(src_path)
# Read configuration file #
config = ConfigParser.ConfigParser()
config_file = os.path.join(src_path, "config_marvin.ini")
config.read(config_file)
import hashlib
# Imports my functions #
import functions
# Define which python to be used #
python = os.path.join(config.get("Paths", "python_path"), "python")
# Arguments & Options #
options = parse_options()
# Directory arguments
input_file = os.path.abspath(options.input_file)
dummy_dir = os.path.abspath(options.dummy_dir)
# Create directories if necessary
logs_dir = src_path + "/logs"
if not os.path.exists(logs_dir):
os.mkdir(logs_dir)
f = open(input_file, "r")
# Depending on the type of analysis, we will submit different commands
if options.type_of_analysis == 'profile_creation':
analysis = '-prof'
all_drugs = set()
for line in f:
(drug1, drug2) = line.strip().split('---')
all_drugs.add(drug1)
all_drugs.add(drug2)
f.close()
for drug in all_drugs:
# Check if the p-value file is already created. If so, skip
pvalue_file = data_dir + "/" + drug + "/guild_results_using_sif/output_scores.sif.netcombo.pval"
if os.path.exists(pvalue_file):
continue
guild_path = '/gpfs42/robbyfs/homes/users/qaguirre/guild/scoreN'
command = 'python {}/diana_cluster/scripts/generate_profiles.py -d {} -pt geneid -sif {} -gu {}'.format( src_path, drug, options.sif_file, guild_path )
print(command)
# python /home/quim/project/diana_cluster/scripts/generate_profiles.py -d 'DCC0303' -pt 'geneid' -sif /home/quim/project/diana_cluster/workspace/sif/human_eAFF_geneid_2017.sif -gu /home/quim/project/diana_cluster/diana/toolbox/scoreN
# To run the command at the local machine
#os.system(command)
#To run in the cluster submitting files to queues
functions.submit_command_to_queue(command, max_jobs_in_queue=int(config.get("Cluster", "max_jobs_in_queue")), queue_file="command_queues_marvin.txt", dummy_dir=dummy_dir)
elif options.type_of_analysis == 'comparison':
analysis = '-comp'
for line in f:
(drug1, drug2) = line.strip().split('---')
# Check if the results are already done
comp_results_dir = res_dir + "/results_" + drug1 + "_" + drug2
table_file = comp_results_dir + '/table_results_' + drug1 + '_' + drug2 + '.txt'
if os.path.exists(table_file):
continue
command = 'python {}/diana_cluster/scripts/compare_profiles.py -d1 {} -d2 {} -pt geneid'.format( src_path, drug1, drug2 )
print(command)
# python /home/quim/project/diana_cluster/scripts/compare_profiles.py -d1 'DCC0303' -d2 'DCC1743' -pt 'geneid'
<|fim▁hole|> #os.system(command)
#To run in the cluster submitting files to queues
functions.submit_command_to_queue(command, max_jobs_in_queue=int(config.get("Cluster", "max_jobs_in_queue")), queue_file="command_queues_marvin.txt", dummy_dir=dummy_dir)
f.close()
else:
print('The type of analysis has been wrongly defined. Introduce \'profile_creation\' or \'comparison\'')
sys.exit(10)<|fim▁end|>
|
# To run the command at the local machine
|
<|file_name|>seq2seq_model.py<|end_file_name|><|fim▁begin|># 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.
# ==============================================================================
"""Sequence-to-sequence model with an attention mechanism."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import random
import numpy as np
from six.moves import xrange # pylint: disable=redefined-builtin
import tensorflow as tf
from tensorflow.models.rnn.translate import data_utils
class Seq2SeqModel(object):
"""Sequence-to-sequence model with attention and for multiple buckets.
This class implements a multi-layer recurrent neural network as encoder,
and an attention-based decoder. This is the same as the model described in
this paper: http://arxiv.org/abs/1412.7449 - please look there for details,
or into the seq2seq library for complete model implementation.
This class also allows to use GRU cells in addition to LSTM cells, and
sampled softmax to handle large output vocabulary size. A single-layer
version of this model, but with bi-directional encoder, was presented in
http://arxiv.org/abs/1409.0473
and sampled softmax is described in Section 3 of the following paper.
http://arxiv.org/abs/1412.2007
"""
def __init__(self,
source_vocab_size,
target_vocab_size,
buckets,
size,
num_layers,
max_gradient_norm,
batch_size,
learning_rate,
learning_rate_decay_factor,
use_lstm=True,
num_samples=512,
forward_only=False,
dtype=tf.float32):
"""Create the model.
Args:
source_vocab_size: size of the source vocabulary.
target_vocab_size: size of the target vocabulary.
buckets: a list of pairs (I, O), where I specifies maximum input length
that will be processed in that bucket, and O specifies maximum output
length. Training instances that have inputs longer than I or outputs
longer than O will be pushed to the next bucket and padded accordingly.
We assume that the list is sorted, e.g., [(2, 4), (8, 16)].
size: number of units in each layer of the model.
num_layers: number of layers in the model.
max_gradient_norm: gradients will be clipped to maximally this norm.
batch_size: the size of the batches used during training;
the model construction is independent of batch_size, so it can be
changed after initialization if this is convenient, e.g., for decoding.
learning_rate: learning rate to start with.
learning_rate_decay_factor: decay learning rate by this much when needed.
use_lstm: if true, we use LSTM cells instead of GRU cells.
num_samples: number of samples for sampled softmax.
forward_only: if set, we do not construct the backward pass in the model.
dtype: the data type to use to store internal variables.
"""
self.source_vocab_size = source_vocab_size
self.target_vocab_size = target_vocab_size
self.buckets = buckets
self.batch_size = batch_size
self.learning_rate = tf.Variable(
float(learning_rate), trainable=False, dtype=dtype)
self.learning_rate_decay_op = self.learning_rate.assign(
self.learning_rate * learning_rate_decay_factor)<|fim▁hole|>
# If we use sampled softmax, we need an output projection.
output_projection = None
softmax_loss_function = None
# Sampled softmax only makes sense if we sample less than vocabulary size.
if num_samples > 0 and num_samples < self.target_vocab_size:
w_t = tf.get_variable("proj_w", [self.target_vocab_size, size], dtype=dtype)
w = tf.transpose(w_t)
b = tf.get_variable("proj_b", [self.target_vocab_size], dtype=dtype)
output_projection = (w, b)
def sampled_loss(inputs, labels):
labels = tf.reshape(labels, [-1, 1])
# We need to compute the sampled_softmax_loss using 32bit floats to
# avoid numerical instabilities.
local_w_t = tf.cast(w_t, tf.float32)
local_b = tf.cast(b, tf.float32)
local_inputs = tf.cast(inputs, tf.float32)
return tf.cast(
tf.nn.sampled_softmax_loss(local_w_t, local_b, local_inputs, labels,
num_samples, self.target_vocab_size),
dtype)
softmax_loss_function = sampled_loss
# Create the internal multi-layer cell for our RNN.
single_cell = tf.nn.rnn_cell.GRUCell(size)
if use_lstm:
single_cell = tf.nn.rnn_cell.BasicLSTMCell(size)
cell = single_cell
if num_layers > 1:
cell = tf.nn.rnn_cell.MultiRNNCell([single_cell] * num_layers)
# The seq2seq function: we use embedding for the input and attention.
def seq2seq_f(encoder_inputs, decoder_inputs, do_decode):
return tf.nn.seq2seq.embedding_attention_seq2seq(
encoder_inputs,
decoder_inputs,
cell,
num_encoder_symbols=source_vocab_size,
num_decoder_symbols=target_vocab_size,
embedding_size=size,
output_projection=output_projection,
feed_previous=do_decode,
dtype=dtype)
# Feeds for inputs.
self.encoder_inputs = []
self.decoder_inputs = []
self.target_weights = []
for i in xrange(buckets[-1][0]): # Last bucket is the biggest one.
self.encoder_inputs.append(tf.placeholder(tf.int32, shape=[None],
name="encoder{0}".format(i)))
for i in xrange(buckets[-1][1] + 1):
self.decoder_inputs.append(tf.placeholder(tf.int32, shape=[None],
name="decoder{0}".format(i)))
self.target_weights.append(tf.placeholder(dtype, shape=[None],
name="weight{0}".format(i)))
# Our targets are decoder inputs shifted by one.
targets = [self.decoder_inputs[i + 1]
for i in xrange(len(self.decoder_inputs) - 1)]
# Training outputs and losses.
if forward_only:
self.outputs, self.losses = tf.nn.seq2seq.model_with_buckets(
self.encoder_inputs, self.decoder_inputs, targets,
self.target_weights, buckets, lambda x, y: seq2seq_f(x, y, True),
softmax_loss_function=softmax_loss_function)
# If we use output projection, we need to project outputs for decoding.
if output_projection is not None:
for b in xrange(len(buckets)):
self.outputs[b] = [
tf.matmul(output, output_projection[0]) + output_projection[1]
for output in self.outputs[b]
]
else:
self.outputs, self.losses = tf.nn.seq2seq.model_with_buckets(
self.encoder_inputs, self.decoder_inputs, targets,
self.target_weights, buckets,
lambda x, y: seq2seq_f(x, y, False),
softmax_loss_function=softmax_loss_function)
# Gradients and SGD update operation for training the model.
params = tf.trainable_variables()
if not forward_only:
self.gradient_norms = []
self.updates = []
opt = tf.train.GradientDescentOptimizer(self.learning_rate)
for b in xrange(len(buckets)):
gradients = tf.gradients(self.losses[b], params)
clipped_gradients, norm = tf.clip_by_global_norm(gradients,
max_gradient_norm)
self.gradient_norms.append(norm)
self.updates.append(opt.apply_gradients(
zip(clipped_gradients, params), global_step=self.global_step))
self.saver = tf.train.Saver(tf.all_variables())
def step(self, session, encoder_inputs, decoder_inputs, target_weights,
bucket_id, forward_only):
"""Run a step of the model feeding the given inputs.
Args:
session: tensorflow session to use.
encoder_inputs: list of numpy int vectors to feed as encoder inputs.
decoder_inputs: list of numpy int vectors to feed as decoder inputs.
target_weights: list of numpy float vectors to feed as target weights.
bucket_id: which bucket of the model to use.
forward_only: whether to do the backward step or only forward.
Returns:
A triple consisting of gradient norm (or None if we did not do backward),
average perplexity, and the outputs.
Raises:
ValueError: if length of encoder_inputs, decoder_inputs, or
target_weights disagrees with bucket size for the specified bucket_id.
"""
# Check if the sizes match.
encoder_size, decoder_size = self.buckets[bucket_id]
if len(encoder_inputs) != encoder_size:
raise ValueError("Encoder length must be equal to the one in bucket,"
" %d != %d." % (len(encoder_inputs), encoder_size))
if len(decoder_inputs) != decoder_size:
raise ValueError("Decoder length must be equal to the one in bucket,"
" %d != %d." % (len(decoder_inputs), decoder_size))
if len(target_weights) != decoder_size:
raise ValueError("Weights length must be equal to the one in bucket,"
" %d != %d." % (len(target_weights), decoder_size))
# Input feed: encoder inputs, decoder inputs, target_weights, as provided.
input_feed = {}
for l in xrange(encoder_size):
input_feed[self.encoder_inputs[l].name] = encoder_inputs[l]
for l in xrange(decoder_size):
input_feed[self.decoder_inputs[l].name] = decoder_inputs[l]
input_feed[self.target_weights[l].name] = target_weights[l]
# Since our targets are decoder inputs shifted by one, we need one more.
last_target = self.decoder_inputs[decoder_size].name
input_feed[last_target] = np.zeros([self.batch_size], dtype=np.int32)
# Output feed: depends on whether we do a backward step or not.
if not forward_only:
output_feed = [self.updates[bucket_id], # Update Op that does SGD.
self.gradient_norms[bucket_id], # Gradient norm.
self.losses[bucket_id]] # Loss for this batch.
else:
output_feed = [self.losses[bucket_id]] # Loss for this batch.
for l in xrange(decoder_size): # Output logits.
output_feed.append(self.outputs[bucket_id][l])
outputs = session.run(output_feed, input_feed)
if not forward_only:
return outputs[1], outputs[2], None # Gradient norm, loss, no outputs.
else:
return None, outputs[0], outputs[1:] # No gradient norm, loss, outputs.
def get_batch(self, data, bucket_id):
"""Get a random batch of data from the specified bucket, prepare for step.
To feed data in step(..) it must be a list of batch-major vectors, while
data here contains single length-major cases. So the main logic of this
function is to re-index data cases to be in the proper format for feeding.
Args:
data: a tuple of size len(self.buckets) in which each element contains
lists of pairs of input and output data that we use to create a batch.
bucket_id: integer, which bucket to get the batch for.
Returns:
The triple (encoder_inputs, decoder_inputs, target_weights) for
the constructed batch that has the proper format to call step(...) later.
"""
encoder_size, decoder_size = self.buckets[bucket_id]
encoder_inputs, decoder_inputs = [], []
# Get a random batch of encoder and decoder inputs from data,
# pad them if needed, reverse encoder inputs and add GO to decoder.
for _ in xrange(self.batch_size):
encoder_input, decoder_input = random.choice(data[bucket_id])
# Encoder inputs are padded and then reversed.
encoder_pad = [data_utils.PAD_ID] * (encoder_size - len(encoder_input))
encoder_inputs.append(list(reversed(encoder_input + encoder_pad)))
# Decoder inputs get an extra "GO" symbol, and are padded then.
decoder_pad_size = decoder_size - len(decoder_input) - 1
decoder_inputs.append([data_utils.GO_ID] + decoder_input +
[data_utils.PAD_ID] * decoder_pad_size)
# Now we create batch-major vectors from the data selected above.
batch_encoder_inputs, batch_decoder_inputs, batch_weights = [], [], []
# Batch encoder inputs are just re-indexed encoder_inputs.
for length_idx in xrange(encoder_size):
batch_encoder_inputs.append(
np.array([encoder_inputs[batch_idx][length_idx]
for batch_idx in xrange(self.batch_size)], dtype=np.int32))
# Batch decoder inputs are re-indexed decoder_inputs, we create weights.
for length_idx in xrange(decoder_size):
batch_decoder_inputs.append(
np.array([decoder_inputs[batch_idx][length_idx]
for batch_idx in xrange(self.batch_size)], dtype=np.int32))
# Create target_weights to be 0 for targets that are padding.
batch_weight = np.ones(self.batch_size, dtype=np.float32)
for batch_idx in xrange(self.batch_size):
# We set weight to 0 if the corresponding target is a PAD symbol.
# The corresponding target is decoder_input shifted by 1 forward.
if length_idx < decoder_size - 1:
target = decoder_inputs[batch_idx][length_idx + 1]
if length_idx == decoder_size - 1 or target == data_utils.PAD_ID:
batch_weight[batch_idx] = 0.0
batch_weights.append(batch_weight)
return batch_encoder_inputs, batch_decoder_inputs, batch_weights<|fim▁end|>
|
self.global_step = tf.Variable(0, trainable=False)
|
<|file_name|>permutations_of_string.go<|end_file_name|><|fim▁begin|>// Part of Cosmos by OpenGenus Foundation
package main
import "fmt"
<|fim▁hole|> } else {
for i := start; i <= end; i++ {
data[start], data[i] = data[i], data[start]
permutation(data, start+1, end)
data[start], data[i] = data[i], data[start]
}
}
}
func main() {
data := string("ABC")
byteArray := []byte(data)
permutation(byteArray, 0, len(byteArray)-1)
}<|fim▁end|>
|
func permutation(data []byte, start, end int) {
if start == end {
fmt.Println(string(data))
|
<|file_name|>pt.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.0" language="pt_BR">
<context>
<name>AVForm</name>
<message>
<source>Audio/Video</source>
<translation>Áudio/Vídeo</translation>
</message>
<message>
<source>Default resolution</source>
<translation>Resolução padrão</translation>
</message>
<message>
<source>Disabled</source>
<translation>Desabilitado</translation>
</message>
<message>
<source>Play a test sound while changing the output volume.</source>
<translation>Reproduzir um som ao mudar de volume.</translation>
</message>
<message>
<source>Use slider to set the gain of your input device ranging from %1dB to %2dB.</source>
<translation>Use o controle deslizante para definir o ganho do seu dispositivo de entrada entre % 1dB e % 2dB.</translation>
</message>
<message>
<source>Select region</source>
<translation>Selecionar região</translation>
</message>
<message>
<source>Screen %1</source>
<translation>Tela %1</translation>
</message>
<message>
<source>Audio Settings</source>
<translation type="unfinished">Configurações de Áudio</translation>
</message>
<message>
<source>Gain</source>
<translation type="unfinished">Ganho</translation>
</message>
<message>
<source>Playback device</source>
<translation>Dispositivo de Reprodução</translation>
</message>
<message>
<source>Use slider to set volume of your speakers.</source>
<translation>Deslize para ajustar o volume dos auto-falantes.</translation>
</message>
<message>
<source>Capture device</source>
<translation>Dispositivo de Captura</translation>
</message>
<message>
<source>Volume</source>
<translation>Volume</translation>
</message>
<message>
<source>Video Settings</source>
<translation>Configurações de Vídeo</translation>
</message>
<message>
<source>Video device</source>
<translation>Dispositivo de Vídeo</translation>
</message>
<message>
<source>Set resolution of your camera.
The higher values, the better video quality your friends may get.
Note though that with better video quality there is needed better internet connection.
Sometimes your connection may not be good enough to handle higher video quality,
which may lead to problems with video calls.</source>
<translation>Define a resolução da sua câmera.
Valores mais altos fornecem uma qualidade melhor.
Observe no entanto que uma qualidade de vídeo maior exige uma conexão melhor com a internet.
Eventualmente sua conexão pode não ser suficiente para uma qualidade de vídeo maior, que pode acarretar em problemas nas chamadas de vídeo.</translation>
</message>
<message>
<source>Resolution</source>
<translation>Resolução</translation>
</message>
<message>
<source>Rescan devices</source>
<translation>Re-escanear dispositivos</translation>
</message>
<message>
<source>Test Sound</source>
<translation>Testar Som</translation>
</message>
<message>
<source>Enables the experimental audio backend with echo cancelling support, needs qTox restart to take effect.</source>
<translation>Habilita o backend de áudio experimental com suporte a cancelamento de eco, necessita reiniciar o qTox para ser ativado.</translation>
</message>
<message>
<source>Enable experimental audio backend</source>
<translation>Habilita backend de audio experimental</translation>
</message>
<message>
<source>Audio quality</source>
<translation>Qualidade de áudio</translation>
</message>
<message>
<source>Transmitted audio quality. Lower this setting if your bandwidth is not high enough or if you want to lower the internet usage.</source>
<translation>Qualidade de audio transmitida. Reduza essa configuração se sua largura de banda não é alta o suficiente ou se você deseja reduzir seu uso de internet. </translation>
</message>
<message>
<source>High (64 kbps)</source>
<translation>Alto (64 kbps)</translation>
</message>
<message>
<source>Medium (32 kbps)</source>
<translation>Médio (32 kbps)</translation>
</message>
<message>
<source>Low (16 kbps)</source>
<translation>Baixo (16 kbps)</translation>
</message>
<message>
<source>Very low (8 kbps)</source>
<translation>Muito baixo (8 kbps)</translation>
</message>
</context>
<context>
<name>AboutForm</name>
<message>
<source>About</source>
<translation>Sobre</translation>
</message>
<message>
<source>Restart qTox to install version %1</source>
<translation>Reinicie o qTox para instalar a versão %1</translation>
</message>
<message>
<source>qTox is downloading update %1</source>
<comment>%1 is the version of the update</comment>
<translation>qTox está baixando a atualização %1</translation>
</message>
<message>
<source>Original author: %1</source>
<translation>Autor original: %1</translation>
</message>
<message>
<source>You are using qTox version %1.</source>
<translation>Você está usando a versão %1 do qTox.</translation>
</message>
<message>
<source>Commit hash: %1</source>
<translation>Hash do commit: %1</translation>
</message>
<message>
<source>toxcore version: %1</source>
<translation>versão do toxcore: %1</translation>
</message>
<message>
<source>Qt version: %1</source>
<translation>Versão do Qt: %1</translation>
</message>
<message>
<source>A list of all known issues may be found at our %1 at Github. If you discover a bug or security vulnerability within qTox, please report it according to the guidelines in our %2 wiki article.</source>
<comment>`%1` is replaced by translation of `bug tracker`
`%2` is replaced by translation of `Writing Useful Bug Reports`</comment>
<translation>Uma lista de todos os problemas conhecidos pode ser encontrada no nosso % 1 no Github. Se você descobrir um bug ou vulnerabilidade de segurança no qTox, informe-o de acordo com as diretrizes em nosso artigo wiki % 2.</translation>
</message>
<message>
<source>bug-tracker</source>
<comment>Replaces `%1` in the `A list of all knownâ¦`</comment>
<translation type="unfinished">bug-tracker</translation>
</message>
<message>
<source>Writing Useful Bug Reports</source>
<comment>Replaces `%2` in the `A list of all knownâ¦`</comment>
<translation type="unfinished">Escrevendo reportagem de bug útil</translation>
</message>
<message>
<source>Click here to report a bug.</source>
<translation>Clique aqui para comunicar um bug.</translation>
</message>
<message>
<source>See a full list of %1 at Github</source>
<comment>`%1` is replaced with translation of word `contributors`</comment>
<translation type="unfinished">Veja uma lista completa de %1 no Github</translation>
</message>
<message>
<source>contributors</source>
<comment>Replaces `%1` in `See a full list ofâ¦`</comment>
<translation type="unfinished">contribuidores</translation>
</message>
</context>
<context>
<name>AboutFriendForm</name>
<message>
<source>Dialog</source>
<translation type="unfinished">Diálogo</translation>
</message>
<message>
<source>username</source>
<translation type="unfinished">nome de usuário</translation>
</message>
<message>
<source>status message</source>
<translation type="unfinished">mensagem de status</translation>
</message>
<message>
<source>Public key:</source>
<translation type="unfinished">Chave pública:</translation>
</message>
<message>
<source>Used aliases:</source>
<translation type="unfinished">Alias usados:</translation>
</message>
<message>
<source>HISTORY OF ALIASES</source>
<translation type="unfinished">HISTÓRICO DE ALIASES</translation>
</message>
<message>
<source>Automatically accept files from contact if set</source>
<translation>Se marcado, aceita automaticamente arquivos do contato</translation>
</message>
<message>
<source>Auto accept files</source>
<translation type="unfinished">Aceitar arquivos automaticamente</translation>
</message>
<message>
<source>Default directory to save files:</source>
<translation type="unfinished">Diretório de arquivos salvos padrão:</translation>
</message>
<message>
<source>Auto accept for this contact is disabled</source>
<translation type="unfinished">Aceitar automaticamente desabilitado para esse contato</translation>
</message>
<message>
<source>Auto accept call:</source>
<translation type="unfinished">Aceitar chamada automaticamente:</translation>
</message>
<message>
<source>Manual</source>
<translation type="unfinished">Manual</translation>
</message>
<message>
<source>Audio</source>
<translation type="unfinished">Áudio</translation>
</message>
<message>
<source>Audio + Video</source>
<translation type="unfinished">Áudio + Vídeo</translation>
</message>
<message>
<source>Automatically accept group chat invitations from this contact if set.</source>
<translation>Se marcado, aceita automaticamente os convites de chat em grupo desse contato.</translation>
</message>
<message>
<source>Auto accept group invites</source>
<translation>Aceitar automaticamente convites de grupos</translation>
</message>
<message>
<source>Remove history (operation can not be undone!)</source>
<translation type="unfinished">Apagar histórico (Operação irreversível!)</translation>
</message>
<message>
<source>Notes</source>
<translation type="unfinished">Notas</translation>
</message>
<message>
<source>Input field for notes about the contact</source>
<translation>Campo de entrada para notas sobre o contato</translation>
</message>
<message>
<source>You can save comment about this contact here.</source>
<translation type="unfinished">Você pode salvar comentários sobre esse contato aqui.</translation>
</message>
<message>
<source>Choose an auto accept directory</source>
<comment>popup title</comment>
<translation type="unfinished">Escolher um diretório para aceitar arquivos automaticamente</translation>
</message>
<message>
<source>History removed</source>
<translation type="unfinished">Histórico apagado</translation>
</message>
<message>
<source>Chat history with %1 removed!</source>
<translation type="unfinished">O histórico de conversas com %1 foi apagado!</translation>
</message>
</context>
<context>
<name>AboutSettings</name>
<message>
<source>Version</source>
<translation>Versão</translation>
</message>
<message>
<source>License</source>
<translation>Licença</translation>
</message>
<message>
<source>Authors</source>
<translation>Autores</translation>
</message>
<message>
<source>Known Issues</source>
<translation>Problemas Conhecidos</translation>
</message>
<message>
<source>Downloading update: %p%</source>
<translation>Baixando atualização: %p%</translation>
</message>
</context>
<context>
<name>AddFriendForm</name>
<message>
<source>Add Friends</source>
<translation>Adicionar aos Contatos</translation>
</message>
<message>
<source>Send friend request</source>
<translation>Enviar pedido de amizade</translation>
</message>
<message>
<source>Couldn't add friend</source>
<translation>Não foi possível adicionar amigo</translation>
</message>
<message>
<source>Invalid Tox ID format</source>
<translation>Formato inválido de ID Tox</translation>
</message>
<message>
<source>Add a friend</source>
<translation>Adicionar um contato</translation>
</message>
<message>
<source>Friend requests</source>
<translation>Solicitações de amizade</translation>
</message>
<message>
<source>Accept</source>
<translation>Aceitar</translation>
</message>
<message>
<source>Reject</source>
<translation>Rejeitar</translation>
</message>
<message>
<source>Tox ID, either 76 hexadecimal characters or [email protected]</source>
<translation>ID Tox, sejam os 76 caracteres hexadecimais ou [email protected]</translation>
</message>
<message>
<source>Type in Tox ID of your friend</source>
<translation>Digite o ID Tox do seu amigo</translation>
</message>
<message>
<source>Friend request message</source>
<translation>Mensagem de solicitação de amigo</translation>
</message>
<message>
<source>Type message to send with the friend request or leave empty to send a default message</source>
<translation>Digite a mensagem para enviar com a solicitação de amizade ou deixe vazio para enviar uma mensagem padrão</translation>
</message>
<message>
<source>%1 Tox ID is invalid or does not exist</source>
<comment>Toxme error</comment>
<translation>% 1 Tox ID é inválido ou não existe</translation>
</message>
<message>
<source>You can't add yourself as a friend!</source>
<extracomment>When trying to add your own Tox ID as friend</extracomment>
<translation type="unfinished">Você não pode adicionar a si mesmo como contato!</translation>
</message>
<message>
<source>Open contact list</source>
<translation>Abrir lista de contatos</translation>
</message>
<message>
<source>Couldn't open file</source>
<translation>Não foi possível abrir o arquivo</translation>
</message>
<message>
<source>Couldn't open the contact file</source>
<extracomment>Error message when trying to open a contact list file to import</extracomment>
<translation>Não foi possível abrir o arquivo de contatos</translation>
</message>
<message>
<source>Invalid file</source>
<translation>Arquivo inválido</translation>
</message>
<message>
<source>We couldn't find any contacts to import in this file!</source>
<translation>Não foi possível encontrar nenhum contato para importar nesse arquivo!</translation>
</message>
<message>
<source>Tox ID</source>
<extracomment>Tox ID of the person you're sending a friend request to</extracomment>
<translation type="unfinished">ID Tox</translation>
</message>
<message>
<source>either 76 hexadecimal characters or [email protected]</source>
<extracomment>Tox ID format description</extracomment>
<translation type="unfinished">Ou 76 caracteres hexadecimais ou [email protected]</translation>
</message>
<message>
<source>Message</source>
<extracomment>The message you send in friend requests</extracomment>
<translation type="unfinished">Mensagem</translation>
</message>
<message>
<source>Open</source>
<extracomment>Button to choose a file with a list of contacts to import</extracomment>
<translation type="unfinished"></translation>
</message>
<message>
<source>Send friend requests</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>%1 here! Tox me maybe?</source>
<extracomment>Default message in friend requests if the field is left blank. Write something appropriate!</extracomment>
<translation type="unfinished">Ola, %1 aqui! Gostaria de me adicionar no Tox?</translation>
</message>
<message>
<source>Import a list of contacts, one Tox ID per line</source>
<translation type="unfinished"></translation>
</message>
<message numerus="yes">
<source>Ready to import %n contact(s), click send to confirm</source>
<extracomment>Shows the number of contacts we're about to import from a file (at least one)</extracomment>
<translation type="unfinished">
<numerusform></numerusform>
<numerusform></numerusform>
</translation>
</message>
<message>
<source>Import contacts</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>AdvancedForm</name>
<message>
<source>Advanced</source>
<translation>Avançado</translation>
</message>
<message>
<source>Unless you %1 know what you are doing, please do %2 change anything here. Changes made here may lead to problems with qTox, and even to loss of your data, e.g. history.</source>
<translation>A menos que você %1 saiva o que está fazendo, por favor %2 faça alterações aqui. Mudanças podem levar a problemas com o qTox, e até perda de suas informações, como histórico.</translation>
</message>
<message>
<source>really</source>
<translation>realmente</translation>
</message>
<message>
<source>not</source>
<translation>não</translation>
</message>
<message>
<source>IMPORTANT NOTE</source>
<translation>NOTA IMPORTANTE</translation>
</message>
<message>
<source>Reset settings</source>
<translation>Redefinir configurações</translation>
</message>
<message>
<source>All settings will be reset to default. Are you sure?</source>
<translation>Todas configurações serão redefinidas para o padrão. Deseja prosseguir?</translation>
</message>
<message>
<source>Yes</source>
<translation>Sim</translation>
</message>
<message>
<source>No</source>
<translation>Não</translation>
</message>
<message>
<source>Call active</source>
<comment>popup title</comment>
<translation>Chamada ativa</translation>
</message>
<message>
<source>You can't disconnect while a call is active!</source>
<comment>popup text</comment>
<translation>Você não pode desconectar enquanto uma chamada estiver ativa!</translation>
</message>
<message>
<source>Save File</source>
<translation>Salvar Arquivo</translation>
</message>
<message>
<source>Logs (*.log)</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>AdvancedSettings</name>
<message>
<source>Save settings to the working directory instead of the usual conf dir</source>
<extracomment>describes makeToxPortable checkbox</extracomment>
<translation>Armazena as configurações no diretório atual ao invés do diretório de configurações prédefinido</translation>
</message>
<message>
<source>Make Tox portable</source>
<translation>Deixe o Tox portável</translation>
</message>
<message>
<source>Reset to default settings</source>
<translation>Restaurar às configurações padrões</translation>
</message>
<message>
<source>Portable</source>
<translation>Portátil</translation>
</message>
<message>
<source>Connection Settings</source>
<translation>Configuraçẽs de Conexão</translation>
</message>
<message>
<source>Enable IPv6 (recommended)</source>
<extracomment>Text on a checkbox to enable IPv6</extracomment>
<translation>Habilitar IPv6 (recomendado)</translation>
</message>
<message>
<source>Disabling this allows, e.g., toxing over Tor. It adds load to the Tox network however, so uncheck only when necessary.</source>
<extracomment>force tcp checkbox tooltip</extracomment>
<translation>Desabilitar esta opção permite, por exemplo, utilizar a rede Tor. Ela adiciona mais dados à rede Tor no entanto, portanto desmarque apenas se necessário.</translation>
</message>
<message>
<source>Enable UDP (recommended)</source>
<extracomment>Text on checkbox to disable UDP</extracomment>
<translation>Habilitar UDP (recomendado)</translation>
</message>
<message>
<source>Proxy type:</source>
<translation>Tipo de proxy:</translation>
</message>
<message>
<source>Address:</source>
<extracomment>Text on proxy addr label</extracomment>
<translation>Endereço:</translation>
</message>
<message>
<source>Port:</source>
<extracomment>Text on proxy port label</extracomment>
<translation>Porta:</translation>
</message>
<message>
<source>None</source>
<translation>Nenhum</translation>
</message>
<message>
<source>SOCKS5</source>
<translation>SOCKS5</translation>
</message>
<message>
<source>HTTP</source>
<translation>HTTP</translation>
</message>
<message>
<source>Reconnect</source>
<comment>reconnect button</comment>
<translation>Reconectar</translation>
</message>
<message>
<source>Debug</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Export Debug Log</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Copy Debug Log</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>ChatForm</name>
<message>
<source>Load chat history...</source>
<translation>Carregar histórico de conversas...</translation>
</message>
<message>
<source>Send a file</source>
<translation>Enviar um arquivo</translation>
</message>
<message>
<source>qTox wasn't able to open %1</source>
<translation>qTox não foi capaz de abrir %1</translation>
</message>
<message>
<source>%1 calling</source>
<translation>%1 chamando</translation>
</message>
<message>
<source>End video call</source>
<translation>Terminar chamada de vídeo</translation>
</message>
<message>
<source>End audio call</source>
<translation>Terminar chamada de áudio</translation>
</message>
<message>
<source>Mute microphone</source>
<translation>Silenciar microfone</translation>
</message>
<message>
<source>Mute call</source>
<translation>Silenciar chamada</translation>
</message>
<message>
<source>Cancel video call</source>
<translation>Cancelar chamada de vídeo</translation>
</message>
<message>
<source>Cancel audio call</source>
<translation>Cancelar chamada de áudio</translation>
</message>
<message>
<source>Start audio call</source>
<translation>Iniciar chamada de áudio</translation>
</message>
<message>
<source>Start video call</source>
<translation>Iniciar chamada de vídeo</translation>
</message>
<message>
<source>Unmute microphone</source>
<translation>Desmutar microfone</translation>
</message>
<message>
<source>Unmute call</source>
<translation>Desmutar chamada</translation>
</message>
<message>
<source>Failed to send file "%1"</source>
<translation>Falha ao enviar o arquivo "%1"</translation>
</message>
<message>
<source>Failed to open temporary file</source>
<comment>Temporary file for screenshot</comment>
<translation>Não foi possível abir o arquivo temporário</translation>
</message>
<message>
<source>qTox wasn't able to save the screenshot</source>
<translation>qTox não conseguiu salvar a imagem capturada</translation>
</message>
<message>
<source>Call with %1 ended. %2</source>
<translation>Chamada para %1 terminada. %2</translation>
</message>
<message>
<source>Call duration: </source>
<translation>Duração da chamada: </translation>
</message>
<message>
<source>Unable to open</source>
<translation>Impossível abrir</translation>
</message>
<message>
<source>Bad idea</source>
<translation>Má idéia</translation>
</message>
<message>
<source>Calling %1</source>
<translation>Chamando %1</translation>
</message>
<message>
<source>%1 is typing</source>
<translation>%1 está digitando</translation>
</message>
<message>
<source>Copy</source>
<translation>Copiar</translation>
</message>
<message>
<source>You're trying to send a sequential file, which is not going to work!</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>away</source>
<comment>contact status</comment>
<translation type="unfinished">ausente</translation>
</message>
<message>
<source>busy</source>
<comment>contact status</comment>
<translation type="unfinished">ocupado</translation>
</message>
<message>
<source>offline</source>
<comment>contact status</comment>
<translation type="unfinished">offline</translation>
</message>
<message>
<source>online</source>
<comment>contact status</comment>
<translation type="unfinished">online</translation>
</message>
<message>
<source>%1 is now %2</source>
<comment>e.g. "Dubslow is now online"</comment>
<translation type="unfinished">%1 agora é %2</translation>
</message>
<message>
<source>Can't start video call</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Can't start audio call</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Microphone can be muted only during a call</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Sound can be disabled only during a call</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Export to file</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Save chat log</source>
<translation type="unfinished">Armazenar histórico da conversa</translation>
</message>
<message>
<source>Call with %1 ended unexpectedly. %2</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>ChatLog</name>
<message>
<source>Copy</source>
<translation>Copiar</translation>
</message>
<message>
<source>Select all</source>
<translatorcomment>Tudo ou todos?</translatorcomment>
<translation>Selecionar tudo</translation>
</message>
<message>
<source>pending</source>
<translatorcomment>Plural? Singular?</translatorcomment>
<translation>pendente</translation>
</message>
</context>
<context>
<name>ChatTextEdit</name>
<message>
<source>Type your message here...</source>
<translation>Digite sua mensagem aqui...</translation>
</message>
</context>
<context>
<name>CircleWidget</name>
<message>
<source>Rename circle</source>
<comment>Menu for renaming a circle</comment>
<translation>Renomear círculo</translation>
</message>
<message>
<source>Remove circle</source>
<comment>Menu for removing a circle</comment>
<translation>Remover círculo</translation>
</message>
<message>
<source>Open all in new window</source>
<translation>Abrir tudo em uma nova janela</translation>
</message>
</context>
<context>
<name>Core</name>
<message>
<source>Toxing on qTox</source>
<translation>Toxing com qTox</translation>
</message>
<message>
<source>/me offers friendship, "%1"</source>
<translation>/me oferece contato, "%1"</translation>
</message>
<message>
<source>Invalid Tox ID</source>
<comment>Error while sending friendship request</comment>
<translation type="unfinished"></translation>
</message>
<message>
<source>You need to write a message with your request</source>
<comment>Error while sending friendship request</comment>
<translation type="unfinished">Você deve escrever uma mensagem junto do pedido</translation>
</message>
<message>
<source>Your message is too long!</source>
<comment>Error while sending friendship request</comment>
<translation type="unfinished">Sua mensagem é muito longa!</translation>
</message>
<message>
<source>Friend is already added</source>
<comment>Error while sending friendship request</comment>
<translation type="unfinished">Contato já adicionado</translation>
</message>
</context>
<context>
<name>FileTransferWidget</name>
<message>
<source>Form</source>
<translation type="unfinished">Formulário</translation>
</message>
<message>
<source>10Mb</source>
<translation>10Mb</translation>
</message>
<message>
<source>0kb/s</source>
<translation>0kb/s</translation>
</message>
<message>
<source>ETA:10:10</source>
<translation>T:10:10</translation>
</message>
<message>
<source>Filename</source>
<translation>Nome do arquivo</translation>
</message>
<message>
<source>Waiting to send...</source>
<comment>file transfer widget</comment>
<translation>Esperando para enviar...</translation>
</message>
<message>
<source>Accept to receive this file</source>
<comment>file transfer widget</comment>
<translation>Aceite recebimento deste arquivo</translation>
</message>
<message>
<source>Location not writable</source>
<comment>Title of permissions popup</comment>
<translation>Impossível gravar aqui</translation>
</message>
<message>
<source>You do not have permission to write that location. Choose another, or cancel the save dialog.</source>
<comment>text of permissions popup</comment>
<translation>Você não possui permissão de escrita aqui. Escolha outro local ou cancele a operação.</translation>
</message>
<message>
<source>Resuming...</source>
<comment>file transfer widget</comment>
<translation>Continuando...</translation>
</message>
<message>
<source>Cancel transfer</source>
<translation>Cancelar transferência</translation>
</message>
<message>
<source>Pause transfer</source>
<translation>Pausar transferência</translation>
</message>
<message>
<source>Resume transfer</source>
<translation>Continuar transferência</translation>
</message>
<message>
<source>Accept transfer</source>
<translation>Aceitar transferência</translation>
</message>
<message>
<source>Save a file</source>
<comment>Title of the file saving dialog</comment>
<translation>Salvar arquivo</translation>
</message>
<message>
<source>Paused</source>
<comment>file transfer widget</comment>
<translation>Pausado</translation>
</message>
<message>
<source>Open file</source>
<translation>Abrir arquivo</translation>
</message>
<message>
<source>Open file directory</source>
<translation>Abrir pasta do arquivo</translation>
</message>
</context>
<context>
<name>FilesForm</name>
<message>
<source>Downloads</source>
<translation>Recebidos</translation>
</message>
<message>
<source>Uploads</source>
<translation>Enviados</translation>
</message>
<message>
<source>Transferred Files</source>
<comment>"Headline" of the window</comment>
<translation>Transferências</translation>
</message>
</context>
<context>
<name>FriendListWidget</name>
<message>
<source>Today</source>
<translation type="unfinished">Hoje</translation>
</message>
<message>
<source>Yesterday</source>
<translation type="unfinished">Ontem</translation>
</message>
<message>
<source>Last 7 days</source>
<translation type="unfinished">Últimos 7 dias</translation>
</message>
<message>
<source>This month</source>
<translation type="unfinished">Este mês</translation>
</message>
<message>
<source>Older than 6 Months</source>
<translation type="unfinished">Mais de 6 Meses</translation>
</message>
<message>
<source>Never</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>FriendRequestDialog</name>
<message>
<source>Friend request</source>
<comment>Title of the window to aceept/deny a friend request</comment>
<translation>Solicitação de contato</translation>
</message>
<message>
<source>Someone wants to make friends with you</source>
<translation>Alguém quer adicionar você como contato</translation>
</message>
<message>
<source>User ID:</source>
<translation>ID do usuário:</translation>
</message>
<message>
<source>Friend request message:</source>
<translation>Mensagem de requisição contato:</translation>
</message>
<message>
<source>Accept</source>
<comment>Accept a friend request</comment>
<translation>Aceitar</translation>
</message>
<message>
<source>Reject</source>
<comment>Reject a friend request</comment>
<translation>Rejeitar</translation>
</message>
</context>
<context>
<name>FriendWidget</name>
<message>
<source>Invite to group</source>
<comment>Menu to invite a friend to a groupchat</comment>
<translation>Convidar para grupo</translation>
</message>
<message>
<source>Move to circle...</source>
<comment>Menu to move a friend into a different circle</comment>
<translation>Mover para círculo...</translation>
</message>
<message>
<source>To new circle</source>
<translation>Para um novo círculo</translation>
</message>
<message>
<source>Remove from circle '%1'</source>
<translation>Remover do círculo "%1"</translation>
</message>
<message>
<source>Move to circle "%1"</source>
<translation>Mover para o círculo "%1"</translation>
</message>
<message>
<source>Set alias...</source>
<translation>Apelido...</translation>
</message>
<message>
<source>Auto accept files from this friend</source>
<comment>context menu entry</comment>
<translation>Aceitar arquivos automaticamente deste contato</translation>
</message>
<message>
<source>Remove friend</source>
<comment>Menu to remove the friend from our friendlist</comment>
<translation>Remover contato</translation>
</message>
<message>
<source>Choose an auto accept directory</source>
<comment>popup title</comment>
<translation>Escolher um diretório para aceitar arquivos automaticamente</translation>
</message>
<message>
<source>New message</source>
<translation>Nova mensagem</translation>
</message>
<message>
<source>Online</source>
<translation>Conectado</translation>
</message>
<message>
<source>Away</source>
<translation>Ausente</translation>
</message>
<message>
<source>Busy</source>
<translation>Ocupado</translation>
</message>
<message>
<source>Offline</source>
<translation>Desconectado</translation>
</message>
<message>
<source>Open chat in new window</source>
<translation>Abrir conversa em uma nova janela</translation>
</message>
<message>
<source>Remove chat from this window</source>
<translation>Retirar conversa desta janela</translation>
</message>
<message>
<source>To new group</source>
<translation>Para um novo grupo</translation>
</message>
<message>
<source>Invite to group '%1'</source>
<translation>Convidar ao grupo '%1'</translation>
</message>
<message>
<source>Show details</source>
<translation>Mostrar detalhes</translation>
</message>
</context>
<context>
<name>GUI</name>
<message>
<source>Enter your password</source>
<translation>Informe sua senha</translation>
</message>
<message>
<source>Decrypt</source>
<translation>Descriptografar</translation>
</message>
<message>
<source>You must enter a non-empty password:</source>
<translation>Você deve informar uma senha:</translation>
</message>
</context>
<context>
<name>GeneralForm</name>
<message>
<source>General</source>
<translation>Geral</translation>
</message>
<message>
<source>Choose an auto accept directory</source>
<comment>popup title</comment>
<translation>Escolher um diretório para aceitar arquivos automaticamente</translation>
</message>
</context>
<context>
<name>GeneralSettings</name>
<message>
<source>General Settings</source>
<translation>Configurações Gerais</translation>
</message>
<message>
<source>The translation may not load until qTox restarts.</source>
<translation>A tradução pode não ser atualizada antes do qTox ser reinicializado.</translation>
</message>
<message>
<source>Show system tray icon</source>
<translation>Mostrar ícone na bandeja</translation>
</message>
<message>
<source>Enable light tray icon.</source>
<comment>toolTip for light icon setting</comment>
<translation>Habilitar ícone da bandeja claro.</translation>
</message>
<message>
<source>qTox will start minimized in tray.</source>
<comment>toolTip for Start in tray setting</comment>
<translation>O qTox vai iniciar minimizado na bandeja.</translation>
</message>
<message>
<source>Start in tray</source>
<translation>Inicializar na bandeja</translation>
</message>
<message>
<source>After pressing close (X) qTox will minimize to tray,
instead of closing itself.</source>
<comment>toolTip for close to tray setting</comment>
<translation>Após clicar em fechar (X), o qTox será minimizado para a bandeja ao em vez de fechar.</translation>
</message>
<message>
<source>Close to tray</source>
<translation>Fechar para a bandeja</translation>
</message>
<message>
<source>After pressing minimize (_) qTox will minimize itself to tray,
instead of system taskbar.</source>
<comment>toolTip for minimize to tray setting</comment>
<translation>Após clicar em minimizar (_) o qTox será minimizado para a bandeja, ao invés da barra de tarefas.</translation>
</message>
<message>
<source>Minimize to tray</source>
<translation>Minimizar para a bandeja</translation>
</message>
<message>
<source>Light icon</source>
<translation>Ícone claro</translation>
</message>
<message>
<source>Language:</source>
<translation>Idioma:</translation>
</message>
<message>
<source>Check for updates on startup</source>
<translation>Verificar por atualizações na inicialização</translation>
</message>
<message>
<source>Set where files will be saved.</source>
<translation>Defina onde os arquivos serão salvos.</translation>
</message>
<message>
<source>Your status is changed to Away after set period of inactivity.</source>
<translation>Seu status é alterado para Ausente após o período de inatividade.</translation>
</message>
<message>
<source>Auto away after (0 to disable):</source>
<translation>Ausente após (0 para desabilitar):</translation>
</message>
<message>
<source>Play sound</source>
<translation>Tocar som</translation>
</message>
<message>
<source>Show contacts' status changes</source>
<translation>Mostrar alterações no status de contatos</translation>
</message>
<message>
<source>Faux offline messaging</source>
<translation>Simular envio de mensagens "offline"</translation>
</message>
<message>
<source>Set to 0 to disable</source>
<translation>Defina 0 para desativar</translation>
</message>
<message>
<source>You can set this on a per-friend basis by right clicking them.</source>
<comment>autoaccept cb tooltip</comment>
<translation>Você pode definir esta configuração por contato clicando com o botão direito sobre eles.</translation>
</message>
<message>
<source>Autoaccept files</source>
<translation>Aceitar arquivos automaticamente</translation>
</message>
<message>
<source>Autostart</source>
<translation>Iniciar automaticamente</translation>
</message>
<message>
<source>On new message:</source>
<translation>Ao receber uma nova mensagem:</translation>
</message>
<message>
<source>Start qTox on operating system startup (current profile).</source>
<translation>Iniciar qTox com o sistema operacional (usando atual perfil).</translation>
</message>
<message>
<source>Default directory to save files:</source>
<translation>Diretório de arquivos salvos padrão:</translation>
</message>
<message>
<source>Play sound while Busy</source>
<translation>Reproduzir som enquanto Ocupado</translation>
</message>
</context>
<context>
<name>GenericChatForm</name>
<message>
<source>Send message</source>
<translation>Enviar mensagem</translation>
</message>
<message>
<source>Smileys</source>
<translation>Emoticons</translation>
</message>
<message>
<source>Send file(s)</source>
<translation>Enviar arquivo(s)</translation>
</message>
<message>
<source>Save chat log</source>
<translation>Armazenar histórico da conversa</translation>
</message>
<message>
<source>Send a screenshot</source>
<translation>Enviar captura de tela</translation>
</message>
<message>
<source>Clear displayed messages</source>
<translation>Remover mensagens</translation>
</message>
<message>
<source>Not sent</source>
<translation>Não enviado</translation>
</message>
<message>
<source>Cleared</source>
<translation>Removidas</translation>
</message>
<message>
<source>Start audio call</source>
<translation>Iniciar chamada de áudio</translation>
</message>
<message>
<source>Accept audio call</source>
<translation>Aceitar chamada de áudio</translation>
</message>
<message>
<source>End audio call</source>
<translation>Finalizar chamada de audio</translation>
</message>
<message>
<source>Start video call</source>
<translation>Iniciar chamada de vídeo</translation>
</message>
<message>
<source>Accept video call</source>
<translation>Aceitar chamada de vídeo</translation>
</message>
<message>
<source>End video call</source>
<translation>Finalizar chamada de vídeo</translation>
</message>
<message>
<source>Quote selected text</source>
<translation>Citar texto selecionado</translation>
</message>
<message>
<source>Copy link address</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>GenericNetCamView</name>
<message>
<source>Tox video</source>
<translation>Vídeo Tox</translation>
</message>
<message>
<source>Show Messages</source>
<translation>Mostrar mensagens</translation>
</message>
<message>
<source>Hide Messages</source>
<translation>Esconder mensagens</translation>
</message>
</context>
<context>
<name>Group</name>
<message>
<source><Empty></source>
<comment>Placeholder when someone's name in a group chat is empty</comment>
<translation><Vazio></translation>
</message>
</context>
<context>
<name>GroupChatForm</name>
<message>
<source>Start audio call</source>
<translation>Iniciar chamada de áudio</translation>
</message>
<message>
<source>Mute microphone</source>
<translation>Silenciar microfone</translation>
</message>
<message>
<source>Unmute microphone</source>
<translation>Reativar microfone</translation>
</message>
<message>
<source>Mute call</source>
<translation>Silenciar chamada</translation>
</message>
<message>
<source>Unmute call</source>
<translation>Desmutar chamada</translation>
</message>
<message>
<source>End audio call</source>
<translation>Terminar chamada de áudio</translation>
</message>
<message>
<source>%1 users in chat</source>
<comment>Number of users in chat</comment>
<translation>%1 usuários no grupo</translation>
</message>
<message>
<source>1 user in chat</source>
<comment>Number of users in chat</comment>
<translation>1 usuário em chat</translation>
</message>
</context>
<context>
<name>GroupInviteForm</name>
<message>
<source>Groups</source>
<translation>Grupos</translation>
</message>
<message>
<source>Create new group</source>
<translation>Criar um novo grupo</translation>
</message>
<message>
<source>Group invites</source>
<translation>Convites à grupos</translation>
</message>
</context>
<context>
<name>GroupInviteWidget</name>
<message>
<source>Invited by %1 on %2 at %3.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Join</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Decline</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>GroupWidget</name>
<message>
<source>%1 users in chat</source>
<translation>%1 usuários no grupo</translation>
</message>
<message>
<source>Set title...</source>
<translation>Defina o título...</translation>
</message>
<message>
<source>Quit group</source>
<comment>Menu to quit a groupchat</comment>
<translation>Sair do grupo</translation>
</message>
<message>
<source>Open chat in new window</source>
<translation>Abrir conversa em outra janela</translation>
</message>
<message>
<source>Remove chat from this window</source>
<translation type="unfinished">Retirar conversa desta janela</translation>
</message>
<message>
<source>1 user in chat</source>
<translation type="unfinished">1 usuário em chat</translation>
</message>
</context>
<context>
<name>IdentitySettings</name>
<message>
<source>Public Information</source>
<translation>Informações Públicas</translation>
</message>
<message>
<source>Tox ID</source>
<translation>ID Tox</translation>
</message>
<message>
<source>This bunch of characters tells other Tox clients how to contact you.
Share it with your friends to communicate.</source>
<comment>Tox ID tooltip</comment>
<translation>Este conjunto de caracteres informa a outros clientes Tox como contactar você. Compartilhe com seus contatos para se comunicar.</translation>
</message>
<message>
<source>Your Tox ID (click to copy)</source>
<translation>Seu ID Tox (clique para copiar)</translation>
</message>
<message>
<source>This QR code contains your Tox ID. You may share this with your friends as well.</source>
<translation>Este código QR contém seu ID Tox. Você pode compartilhá-lo com seus amigos.</translation>
</message>
<message>
<source>Save image</source>
<translation>Salvar imagem</translation>
</message>
<message>
<source>Copy image</source>
<translation>Copiar imagem</translation>
</message>
<message>
<source>Profile</source>
<translation>Perfil</translation>
</message>
<message>
<source>Rename profile.</source>
<comment>tooltip for renaming profile button</comment>
<translation>Renomear perfil.</translation>
</message>
<message>
<source>Delete profile.</source>
<comment>delete profile button tooltip</comment>
<translation>Remover perfil.</translation>
</message>
<message>
<source>Go back to the login screen</source>
<comment>tooltip for logout button</comment>
<translation>Voltar a tela inicial</translation>
</message>
<message>
<source>Logout</source>
<comment>import profile button</comment>
<translation>Encerrar sessão</translation>
</message>
<message>
<source>Remove password</source>
<translation>Remover senha</translation>
</message>
<message>
<source>Change password</source>
<translation>Mudar a senha</translation>
</message>
<message>
<source>Allows you to export your Tox profile to a file.
Profile does not contain your history.</source>
<comment>tooltip for profile exporting button</comment>
<translation>Permite exportar seu perfil Tox para um arquivo. O perfil não contem o seu histórico.</translation>
</message>
<message>
<source>Rename</source>
<comment>rename profile button</comment>
<translation>Renomear</translation>
</message>
<message>
<source>Export</source>
<comment>export profile button</comment>
<translation>Exportar</translation>
</message>
<message>
<source>Delete</source>
<comment>delete profile button</comment>
<translation>Excluir</translation>
</message>
<message>
<source>Server</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Hide my name from the public list</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Register</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Your password</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Update</source>
<translation type="unfinished">Atualizar</translation>
</message>
<message>
<source>Register on ToxMe</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Name for the ToxMe service.</source>
<comment>Tooltip for the `Username` ToxMe field.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<source>Optional. Something about you. Or your cat.</source>
<comment>Tooltip for the Biography text.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<source>Optional. Something about you. Or your cat.</source>
<comment>Tooltip for the Biography field.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<source>ToxMe service to register on.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>If not set, ToxMe entries are publicly visible.</source>
<comment>Tooltip for the `Hide my name from public list` ToxMe checkbox.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<source>Remove your password and encryption from your profile.</source>
<comment>Tooltip for the `Remove password` button.</comment>
<translation type="unfinished"></translation>
</message>
<message>
<source>Name input</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Name visible to contacts</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Status message input</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Status message visible to contacts</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Your Tox ID</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Save QR image as file</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Copy QR image to clipboard</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>ToxMe username to be shown on ToxMe</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Optional ToxMe biography to be shown on ToxMe</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>ToxMe service address</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Visibility on the ToxMe service</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Password</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Update ToxMe entry</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Rename profile.</source>
<translation type="unfinished">Renomear perfil.</translation>
</message>
<message>
<source>Delete profile.</source>
<translation type="unfinished">Remover perfil.</translation>
</message>
<message>
<source>Export profile</source>
<translation type="unfinished">Exportar perfil</translation>
</message>
<message>
<source>Remove password from profile</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Change profile password</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>My name:</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>My status:</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>My username</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>My biography</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>My profile</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>LoadHistoryDialog</name>
<message>
<source>Load History Dialog</source>
<translation>Carregar Histórico</translation>
</message>
<message>
<source>Load history from:</source>
<translation>Carregar histórico de:</translation>
</message>
<message>
<source>%1 messages</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>LoginScreen</name>
<message>
<source>Username:</source>
<translation>Usuário:</translation>
</message>
<message>
<source>Password:</source>
<translation>Senha:</translation>
</message>
<message>
<source>Confirm:</source>
<translation>Confirmar:</translation>
</message>
<message>
<source>Password strength: %p%</source>
<translation type="unfinished">Segurança da senha: %p%</translation>
</message>
<message>
<source>If the profile does not have a password, qTox can skip the login screen</source>
<translation>Se o perfil não tiver uma senha, qTox pode pular a tela de entrada</translation>
</message>
<message>
<source>New Profile</source>
<translation>Novo Perfil</translation>
</message>
<message>
<source>Couldn't create a new profile</source>
<translation>Não foi possível criar um novo perfil</translation>
</message>
<message>
<source>The username must not be empty.</source>
<translation>O nome de usuário não pode ser vazio.</translation>
</message>
<message>
<source>The password must be at least 6 characters long.</source>
<translation>A senha deve ter pelo menos 6 caracterers.</translation>
</message>
<message>
<source>The passwords you've entered are different.
Please make sure to enter same password twice.</source>
<translation>As senhas digitadas diferem.
Certifique-se de que você entrou a mesma senha duas vezes.</translation>
</message>
<message>
<source>A profile with this name already exists.</source>
<translation>Um perfil com este nome já existe.</translation>
</message>
<message>
<source>Unknown error: Couldn't create a new profile.
If you encountered this error, please report it.</source>
<translation>Erro desconhecido: não foi possível criar perfil.
Por favor, reporte este erro.</translation>
</message>
<message>
<source>Couldn't load this profile</source>
<translation>Não foi possível carregar o perfil</translation>
</message>
<message>
<source>This profile is already in use.</source>
<translation>Este perfil já está em uso.</translation>
</message>
<message>
<source>Profile already in use. Close other clients.</source>
<translation>Perfil em uso. Feche outros clientes.</translation>
</message>
<message>
<source>Wrong password.</source>
<translation>Senha incorreta.</translation>
</message>
<message>
<source>Create Profile</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Load automatically</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Import</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Load</source>
<translation type="unfinished">Carregar</translation>
</message>
<message>
<source>Load Profile</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Password protected profiles can't be automatically loaded.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Couldn't load profile</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>There is no selected profile.
You may want to create one.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Username input field</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Password input field, you can leave it empty (no password), or type at least 6 characters</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Password confirmation field</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Create a new profile button</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Profile list</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>List of profiles</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Password input</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Load automatically checkbox</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Import profile</source>
<translation type="unfinished">Importar perfil</translation>
</message>
<message>
<source>Load selected profile button</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>New profile creation page</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Loading existing profile page</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>MainWindow</name>
<message>
<source>Your name</source>
<translation>Seu nome</translation>
</message>
<message>
<source>Your status</source>
<translation>Seu status</translation>
</message>
<message>
<source>...</source>
<translation>...</translation>
</message>
<message>
<source>Add friends</source>
<translation>Adicionar contatos</translation>
</message>
<message>
<source>Create a group chat</source>
<translation>Criar um grupo</translation>
</message>
<message>
<source>View completed file transfers</source>
<translation>Ver transferências de arquivos completadas</translation>
</message>
<message>
<source>Change your settings</source>
<translation>Alterar suas configurações</translation>
</message>
<message>
<source>Close</source>
<translation>Fechar</translation>
</message>
<message>
<source>Open profile</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Open profile page when clicked</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Status message input</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Set your status message that will be shown to others</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Status</source>
<translation type="unfinished">Status</translation>
</message>
<message>
<source>Set availability status</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Contact search</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Contact search input for known friends</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Sorting and visibility</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Set friends sorting and visibility</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Open Add friends page</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Groupchat</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Open groupchat management page</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>File transfers history</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Open File transfers history</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Settings</source>
<translation type="unfinished">Configurações</translation>
</message>
<message>
<source>Open Settings</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>Nexus</name>
<message>
<source>Images (%1)</source>
<comment>filetype filter</comment>
<translation>Imagens (%1)</translation>
</message>
<message>
<source>View</source>
<comment>OS X Menu bar</comment>
<translation type="unfinished">Visualizar</translation>
</message>
<message>
<source>Window</source>
<comment>OS X Menu bar</comment>
<translation type="unfinished">Janela</translation>
</message>
<message>
<source>Minimize</source>
<comment>OS X Menu bar</comment>
<translation type="unfinished">Minimizar</translation>
</message>
<message>
<source>Bring All to Front</source>
<comment>OS X Menu bar</comment>
<translation type="unfinished">Trazer Todos para a Frente</translation>
</message>
<message>
<source>Exit Fullscreen</source>
<translation type="unfinished">Sair de Tela Cheia</translation>
</message>
<message>
<source>Enter Fullscreen</source>
<translation type="unfinished">Entrar em Tela Cheia</translation>
</message>
</context>
<context>
<name>NotificationEdgeWidget</name>
<message numerus="yes">
<source>Unread message(s)</source>
<translation>
<numerusform>Mensagem não lida</numerusform>
<numerusform>Mensagens não lidas</numerusform>
</translation>
</message>
</context>
<context>
<name>PasswordEdit</name>
<message>
<source>CAPS-LOCK ENABLED</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>PrivacyForm</name>
<message>
<source>Privacy</source>
<translation>Privacidade</translation>
</message>
<message>
<source>Confirmation</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Do you want to permanently delete all chat history?</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>PrivacySettings</name>
<message>
<source>Your friends will be able to see when you are typing.</source>
<comment>tooltip for typing notifications setting</comment>
<translation>Seus contatos poderão ver quando você estiver digitando.</translation>
</message>
<message>
<source>Send typing notifications</source>
<translation>Enviar notificação de digitação</translation>
</message>
<message>
<source>Keep chat history</source>
<translation>Guardar histórico de conversas</translation>
</message>
<message>
<source>NoSpam is part of your Tox ID.
If you are being spammed with friend requests, you should change your NoSpam.
People will be unable to add you with your old ID, but you will keep your current friends.</source>
<comment>toolTip for nospam</comment>
<translation>NoSpam faz parte de seu ID Tox.
Se você estiver recebendo muitas solicitações indesejadas, você deve mudar seu NoSpam.
Não será possível lhe adicionar com seu ID antigo, mas você manterá sua lista de amigos.</translation>
</message>
<message>
<source>NoSpam</source>
<translation>NoSpam</translation>
</message>
<message>
<source>NoSpam is a part of your ID that can be changed at will.
If you are getting spammed with friend requests, change the NoSpam.</source>
<translation>NoSpam faz parte de seu ID Tox e pode ser mudado a vontade.
Se você estiver recebendo muitas solicitações indesejadas, mude seu NoSpam.</translation>
</message>
<message>
<source>Generate random NoSpam</source>
<translation>Gerar NoSpam aleatório</translation>
</message>
<message>
<source>Chat history keeping is still in development.
Save format changes are possible, which may result in data loss.</source>
<comment>toolTip for Keep History setting</comment>
<translation>O histórico de conversas ainda está em desenvolvimento. Mudanças no arquivo salvo podem ocorrer, isso pode resultar em perda de dados.</translation>
</message>
<message>
<source>Privacy</source>
<translation type="unfinished">Privacidade</translation>
</message>
<message>
<source>BlackList</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Filter group message by group member's public key. Put public key here, one per line.</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>Profile</name>
<message>
<source>Failed to derive key from password, the profile won't use the new password.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Couldn't change password on the database, it might be corrupted or use the old password.</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>ProfileForm</name>
<message>
<source>Choose a profile picture</source>
<translation>Escolha uma imagem para o perfil</translation>
</message>
<message>
<source>Error</source>
<translation>Erro</translation>
</message>
<message>
<source>Unable to open this file.</source>
<translation type="unfinished">Não foi possível abrir este arquivo.</translation>
</message>
<message>
<source>Unable to read this image.</source>
<translation>Não foi possível ler esta imagem.</translation>
</message>
<message>
<source>The supplied image is too large.
Please use another image.</source>
<translation>A imagem é muito grande.
Por favor, escolha outra.</translation>
</message>
<message>
<source>Rename "%1"</source>
<comment>renaming a profile</comment>
<translation>Renomear "%1"</translation>
</message>
<message>
<source>Couldn't rename the profile to "%1"</source>
<translation>Não foi possível renomear o perfil para "%1"</translation>
</message>
<message>
<source>Location not writable</source>
<comment>Title of permissions popup</comment>
<translation>Impossível gravar aqui</translation>
</message>
<message>
<source>You do not have permission to write that location. Choose another, or cancel the save dialog.</source>
<comment>text of permissions popup</comment>
<translation>Você não possui permissão de escrita aqui. Escolha outro local ou cancele a operação.</translation>
</message>
<message>
<source>Failed to copy file</source>
<translation>Falha ao copiar o arquivo</translation>
</message>
<message>
<source>The file you chose could not be written to.</source>
<translation>O arquivo que você escolheu não pôde ser escrito.</translation>
</message>
<message>
<source>Really delete profile?</source>
<comment>deletion confirmation title</comment>
<translation type="unfinished">Realmente remover perfil?</translation>
</message>
<message>
<source>Are you sure you want to delete this profile?</source>
<comment>deletion confirmation text</comment>
<translation>Tem certeza de que deseja remover este perfil?</translation>
</message>
<message>
<source>Save</source>
<comment>save qr image</comment>
<translation>Salvar</translation>
</message>
<message>
<source>Save QrCode (*.png)</source>
<comment>save dialog filter</comment>
<translation>Salvar código QR (*.png)</translation>
</message>
<message>
<source>Nothing to remove</source>
<translation>Nada para remover</translation>
</message>
<message>
<source>Your profile does not have a password!</source>
<translation>Seu perfil não possui uma senha!</translation>
</message>
<message>
<source>Really delete password?</source>
<comment>deletion confirmation title</comment>
<translation>Realmente remover senha?</translation>
</message>
<message>
<source>Please enter a new password.</source>
<translation>Por favor, insira uma nova senha.</translation>
</message>
<message>
<source>Current profile: </source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Remove</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Files could not be deleted!</source>
<comment>deletion failed title</comment>
<translation type="unfinished"></translation>
</message>
<message>
<source>Register (processing)</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Update (processing)</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Done!</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Account %1@%2 updated successfully</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Successfully added %1@%2 to the database. Save your password</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Toxme error</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Register</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Update</source>
<translation type="unfinished">Atualizar</translation>
</message>
<message>
<source>Change password</source>
<comment>button text</comment>
<translation type="unfinished">Mudar a senha</translation>
</message>
<message>
<source>Set profile password</source>
<comment>button text</comment>
<translation type="unfinished"></translation>
</message>
<message>
<source>Current profile location: %1</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Couldn't change password</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>This bunch of characters tells other Tox clients how to contact you.
Share it with your friends to communicate.
This ID includes the NoSpam code (in blue), and the checksum (in gray).</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Empty path is unavaliable</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Failed to rename</source>
<translation type="unfinished">Não foi possível renomear</translation>
</message>
<message>
<source>Profile already exists</source>
<translation type="unfinished">O perfil já existe</translation>
</message>
<message>
<source>A profile named "%1" already exists.</source>
<translation type="unfinished">Um perfil chamada "%1" já existe.</translation>
</message>
<message>
<source>Empty name</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Empty name is unavaliable</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Empty path</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Couldn't change password on the database, it might be corrupted or use the old password.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Export profile</source>
<translation type="unfinished">Exportar perfil</translation>
</message>
<message>
<source>Tox save file (*.tox)</source>
<extracomment>save dialog filter</extracomment>
<translation type="unfinished">Arquivo Tox (*.tox)</translation>
</message>
<message>
<source>The following files could not be deleted:</source>
<extracomment>deletion failed text part 1</extracomment>
<translation type="unfinished"></translation>
</message>
<message>
<source>Please manually remove them.</source>
<extracomment>deletion failed text part 2</extracomment>
<translation type="unfinished"></translation>
</message>
<message>
<source>Are you sure you want to delete your password?</source>
<extracomment>deletion confirmation text</extracomment>
<translation type="unfinished">Tem certeza de que deseja remover sua senha?</translation>
</message>
</context>
<context>
<name>ProfileImporter</name>
<message>
<source>Import profile</source>
<comment>import dialog title</comment>
<translation type="unfinished">Importar perfil</translation>
</message>
<message>
<source>Tox save file (*.tox)</source>
<comment>import dialog filter</comment>
<translation type="unfinished">Arquivo Tox (*.tox)</translation>
</message>
<message>
<source>Ignoring non-Tox file</source>
<comment>popup title</comment>
<translation type="unfinished">Ignorando arquivo não Tox</translation>
</message>
<message>
<source>Warning: You have chosen a file that is not a Tox save file; ignoring.</source>
<comment>popup text</comment>
<translation type="unfinished"></translation>
</message>
<message>
<source>Profile already exists</source>
<comment>import confirm title</comment>
<translation type="unfinished">O perfil já existe</translation>
</message>
<message>
<source>A profile named "%1" already exists. Do you want to erase it?</source>
<comment>import confirm text</comment>
<translation type="unfinished">Um perfil chamado "%1" já existe. Deseja sobrescrevê-lo?</translation>
</message>
<message>
<source>File doesn't exist</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Profile doesn't exist</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Profile imported</source>
<translation type="unfinished">Perfil importado</translation>
</message>
<message>
<source>%1.tox was successfully imported</source>
<translation type="unfinished">%1.tox importado com sucesso</translation>
</message>
</context>
<context>
<name>QApplication</name>
<message>
<source>Ok</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Cancel</source>
<translation type="unfinished">Cancelar</translation>
</message>
<message>
<source>Yes</source>
<translation type="unfinished">Sim</translation>
</message>
<message>
<source>No</source>
<translation type="unfinished">Não</translation>
</message>
<message>
<source>LTR</source>
<comment>Translate this string to the string 'RTL' in right-to-left languages (for example Hebrew and Arabic) to get proper widget layout</comment>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>QMessageBox</name>
<message>
<source>Couldn't add friend</source>
<translation type="unfinished">Não foi possível adicionar amigo</translation>
</message>
<message>
<source>%1 is not a valid Toxme address.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>You can't add yourself as a friend!</source>
<comment>When trying to add your own Tox ID as friend</comment>
<translation type="unfinished">Você não pode adicionar a si mesmo como contato!</translation>
</message>
</context>
<context>
<name>QObject</name>
<message>
<source>Update</source>
<comment>The title of a message box</comment>
<translation>Atualizar</translation>
</message>
<message>
<source>An update is available, do you want to download it now?
It will be installed when qTox restarts.</source>
<translation>Uma atualização está disponível, você deseja baixá-la agora?
Ela será instalada quando o qTox for reiniciado.</translation>
</message>
<message>
<source>Tox URI to parse</source>
<translation>UTI Tox para interpretar</translation>
</message>
<message>
<source>Starts new instance and loads specified profile.</source>
<translation>Inicia uma nova instância e carrega o perfil especificado.</translation>
</message>
<message>
<source>profile</source>
<translation>perfil</translation>
</message>
<message>
<source>Default</source>
<translation>Padrão</translation>
</message>
<message>
<source>Blue</source>
<translation>Azul</translation>
</message>
<message>
<source>Olive</source>
<translation>Verde-oliva</translation>
</message>
<message>
<source>Red</source>
<translation>Vermelho</translation>
</message>
<message>
<source>Violet</source>
<translation>Violeta</translation>
</message>
<message>
<source>Incoming call...</source>
<translation>Recebendo chamada...</translation>
</message>
<message>
<source>%1 here! Tox me maybe?</source>
<comment>Default message in Tox URI friend requests. Write something appropriate!</comment>
<translation>Ola, %1 aqui! Gostaria de me adicionar no Tox?</translation>
</message>
<message>
<source>Version %1, %2</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Server doesn't support Toxme</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>You're making too many requests. Wait an hour and try again</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>This name is already in use</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>This Tox ID is already registered under another name</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Please don't use a space in your name</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Password incorrect</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>You can't use this name</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Name not found</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Tox ID not sent</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>That user does not exist</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Error</source>
<translation type="unfinished">Erro</translation>
</message>
<message>
<source>qTox couldn't open your chat logs, they will be disabled.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>None</source>
<comment>No camera device set</comment>
<translation type="unfinished">Nenhum</translation>
</message>
<message>
<source>Desktop</source>
<comment>Desktop as a camera input for screen sharing</comment>
<translation type="unfinished"></translation>
</message>
<message>
<source>Problem with HTTPS connection</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Internal ToxMe error</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Reformatting text in progress..</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Starts new instance and opens the login screen.</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>RemoveFriendDialog</name>
<message>
<source>Remove friend</source>
<translation type="unfinished">Remover contato</translation>
</message>
<message>
<source>Also remove chat history</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Remove</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Are you sure you want to remove %1 from your contacts list?</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Remove all chat history with the friend if set</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>ScreenshotGrabber</name>
<message>
<source>Click and drag to select a region. Press %1 to hide/show qTox window, or %2 to cancel.</source>
<comment>Help text shown when no region has been selected yet</comment>
<translation type="unfinished"></translation>
</message>
<message>
<source>Space</source>
<comment>[Space] key on the keyboard</comment>
<translation type="unfinished"></translation>
</message>
<message>
<source>Escape</source>
<comment>[Escape] key on the keyboard</comment>
<translation type="unfinished"></translation>
</message>
<message>
<source>Press %1 to send a screenshot of the selection, %2 to hide/show qTox window, or %3 to cancel.</source>
<comment>Help text shown when a region has been selected</comment>
<translation type="unfinished"></translation>
</message>
<message>
<source>Enter</source>
<comment>[Enter] key on the keyboard</comment>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>SetPasswordDialog</name>
<message>
<source>Set your password</source>
<translation>Informe sua senha</translation>
</message>
<message>
<source>The password is too short</source>
<translation>Senha muito curta</translation>
</message>
<message>
<source>The password doesn't match.</source>
<translation>Senha não coincide.</translation>
</message>
<message>
<source>Confirm:</source>
<translation type="unfinished">Confirmar:</translation>
</message>
<message>
<source>Password:</source>
<translation type="unfinished">Senha:</translation>
</message>
<message>
<source>Password strength: %p%</source>
<translation type="unfinished">Segurança da senha: %p%</translation>
</message>
<message>
<source>Confirm password</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Confirm password input</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Password input</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Password input field, minimum 6 characters long</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>Settings</name>
<message>
<source>Circle #%1</source>
<translation>Círculo #%1</translation>
</message>
</context>
<context>
<name>ToxURIDialog</name>
<message>
<source>Add a friend</source>
<comment>Title of the window to add a friend through Tox URI</comment>
<translation>Adicionar um contato</translation>
</message>
<message>
<source>Do you want to add %1 as a friend?</source>
<translation>Você deseja adicionar %1 como seu contato?</translation>
</message>
<message>
<source>User ID:</source>
<translation>ID do usuário:</translation>
</message>
<message>
<source>Friend request message:</source>
<translation>Mensagem de requisição contato:</translation>
</message>
<message>
<source>Send</source>
<comment>Send a friend request</comment>
<translation>Enviar</translation>
</message>
<message>
<source>Cancel</source>
<comment>Don't send a friend request</comment>
<translation>Cancelar</translation>
</message>
</context>
<context>
<name>UserInterfaceForm</name>
<message>
<source>None</source>
<translation type="unfinished">Nenhum</translation>
</message>
<message>
<source>User Interface</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>UserInterfaceSettings</name>
<message>
<source>Chat</source>
<translation type="unfinished">Conversas</translation>
</message>
<message>
<source>Base font:</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>px</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Size: </source>
<translation type="unfinished"></translation>
</message>
<message>
<source>New text styling preference may not load until qTox restarts.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Text Style format:</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Select text styling preference.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Plaintext</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Show formatting characters</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Don't show formatting characters</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>New message</source>
<translation type="unfinished">Nova mensagem</translation>
</message>
<message>
<source>Open qTox's window when you receive a new message and no window is open yet.</source>
<comment>tooltip for Show window setting</comment>
<translation type="unfinished"></translation>
</message>
<message>
<source>Open window</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Focus qTox when you receive message.</source>
<comment>toolTip for Focus window setting</comment>
<translation type="unfinished">Alterar o foco para o qTox ao receber mensagens.</translation>
</message>
<message>
<source>Focus window</source>
<translation type="unfinished">Colocar janela em foco</translation>
</message>
<message>
<source>Contact list</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Always notify about new messages in groupchats.</source>
<comment>toolTip for Group chat always notify</comment>
<translation type="unfinished">Sempre notificar sobre novas mensagens em grupos de conversa.</translation>
</message>
<message>
<source>Group chats always notify</source>
<translation type="unfinished">Notificação de conversas em grupo</translation>
</message>
<message>
<source>If checked, groupchats will be placed at the top of the friends list, otherwise, they'll be placed below online friends.</source>
<comment>toolTip for groupchat positioning</comment>
<translation type="unfinished">Se marcada, conversas em grupo serão colocadas no topo de sua lista de amigos. Caso contrário, estarão abaixo dos amigos conectados.</translation>
</message>
<message>
<source>Place groupchats at top of friend list</source>
<translation type="unfinished">Colocar conversas em grupo no topo da lista de amigos</translation>
</message>
<message>
<source>Your contact list will be shown in compact mode.</source>
<comment>toolTip for compact layout setting</comment>
<translation type="unfinished">Sua lista de contatos será exibida em modo compacto.</translation>
</message>
<message>
<source>Compact contact list</source>
<translation type="unfinished">Lista de contatos compacta</translation>
</message>
<message>
<source>Multiple windows mode</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Open each chat in an individual window</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Emoticons</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Use emoticons</source>
<translation type="unfinished">Usar emoticons</translation>
</message>
<message>
<source>Smiley Pack:</source>
<extracomment>Text on smiley pack label</extracomment>
<translation type="unfinished">Pacote de emoticons:</translation>
</message>
<message>
<source>Emoticon size:</source>
<translation type="unfinished">Tamanho dos emoticons:</translation>
</message>
<message>
<source> px</source>
<translation type="unfinished"> px</translation>
</message>
<message>
<source>Theme</source>
<translation type="unfinished">Tema</translation>
</message>
<message>
<source>Style:</source>
<translation type="unfinished">Estilo:</translation>
</message>
<message>
<source>Theme color:</source>
<translation type="unfinished">Cor do tema:</translation>
</message>
<message>
<source>Timestamp format:</source>
<translation type="unfinished">Formato de hora:</translation>
</message>
<message>
<source>Date format:</source>
<translation type="unfinished">Formato de datas:</translation>
</message>
</context>
<context>
<name>Widget</name>
<message>
<source>Online</source>
<translation>Conectados</translation>
</message>
<message>
<source>Add new circle...</source>
<translation>Adicionar novo círculo...</translation>
</message>
<message>
<source>By Name</source>
<translation>Por Nome</translation>
</message>
<message>
<source>By Activity</source>
<translation>Por Atividade</translation>
</message>
<message>
<source>All</source>
<translation>Todos</translation>
</message>
<message>
<source>Offline</source>
<translation>Desconectados</translation>
</message>
<message>
<source>Friends</source>
<translation>Amigos</translation>
</message>
<message>
<source>Groups</source>
<translation>Grupos</translation>
</message>
<message>
<source>Search Contacts</source>
<translation>Buscar Contatos</translation>
</message>
<message>
<source>Online</source>
<comment>Button to set your status to 'Online'</comment>
<translation>Online</translation>
</message>
<message>
<source>Away</source>
<comment>Button to set your status to 'Away'</comment>
<translation>Ausente</translation>
</message>
<message>
<source>Busy</source>
<comment>Button to set your status to 'Busy'</comment>
<translation>Ocupado</translation>
</message>
<message>
<source>toxcore failed to start with your proxy settings. qTox cannot run; please modify your settings and restart.</source>
<comment>popup text</comment>
<translation>O Toxcore falhou ao inicializar suas configurações de proxy. O qTox não pode ser executado, por favor modifique suas configurações e reinicialize o aplicativo.</translation>
</message>
<message>
<source>File</source>
<translation>Arquivo</translation>
</message>
<message>
<source>Edit Profile</source>
<translation>Editar Perfil</translation>
</message>
<message>
<source>Change Status</source>
<translation type="unfinished">Mudar Status</translation>
</message>
<message>
<source>Log out</source>
<translation>Sair</translation>
</message>
<message>
<source>Edit</source>
<translation>Editar</translation>
</message>
<message>
<source>Filter...</source>
<translation>Filtrar...</translation>
</message>
<message>
<source>Contacts</source>
<translation>Contatos</translation>
</message>
<message>
<source>Add Contact...</source>
<translation>Adicionar Contato...</translation>
</message>
<message>
<source>Next Conversation</source>
<translation>Próxima Conversa</translation>
</message>
<message>
<source>Previous Conversation</source>
<translation>Conversa Anterior</translation>
</message>
<message>
<source>Executable file</source>
<comment>popup title</comment>
<translation>Arquivo executável</translation>
</message>
<message>
<source>You have asked qTox to open an executable file. Executable files can potentially damage your computer. Are you sure want to open this file?</source>
<comment>popup text</comment>
<translation>Você pediu ao qTox para abrir um arquivo executável. Executáveis podem potencialmente danificar seu computador. Tem certeza de que deseja abrir este arquivo?</translation>
</message>
<message>
<source>Couldn't request friendship</source>
<translation>Não foi possível adicionar o contato</translation>
</message>
<message>
<source>%1 has set the title to %2</source>
<translation>%1 alterou o título para %2</translation>
</message>
<message>
<source>Status</source>
<translation type="unfinished">Status</translation>
</message>
<message>
<source>Message failed to send</source>
<translation>Falha no envio da mensagem</translation>
</message>
<message>
<source>toxcore failed to start, the application will terminate after you close this message.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Your name</source>
<translation type="unfinished">Seu nome</translation>
</message>
<message>
<source>Your status</source>
<translation type="unfinished">Seu status</translation>
</message>
<message>
<source><Empty></source>
<comment>Placeholder when someone's name in a group chat is empty</comment>
<translation type="unfinished"><Vazio></translation>
</message><|fim▁hole|> <message>
<source>Create new group...</source>
<translation type="unfinished"></translation>
</message>
<message numerus="yes">
<source>%n New Friend Request(s)</source>
<translation type="unfinished">
<numerusform></numerusform>
<numerusform></numerusform>
</translation>
</message>
<message numerus="yes">
<source>%n New Group Invite(s)</source>
<translation type="unfinished">
<numerusform></numerusform>
<numerusform></numerusform>
</translation>
</message>
<message>
<source>Logout</source>
<comment>Tray action menu to logout user</comment>
<translation type="unfinished">Encerrar sessão</translation>
</message>
<message>
<source>Exit</source>
<comment>Tray action menu to exit tox</comment>
<translation type="unfinished"></translation>
</message>
<message>
<source>Show</source>
<comment>Tray action menu to show qTox window</comment>
<translation type="unfinished"></translation>
</message>
<message>
<source>Add friend</source>
<comment>title of the window</comment>
<translation type="unfinished">Adicionar contato</translation>
</message>
<message>
<source>Group invites</source>
<comment>title of the window</comment>
<translation type="unfinished">Convites à grupos</translation>
</message>
<message>
<source>File transfers</source>
<comment>title of the window</comment>
<translation type="unfinished">Transferências de arquivo</translation>
</message>
<message>
<source>Settings</source>
<comment>title of the window</comment>
<translation type="unfinished">Configurações</translation>
</message>
<message>
<source>My profile</source>
<comment>title of the window</comment>
<translation type="unfinished"></translation>
</message>
</context>
</TS><|fim▁end|>
|
<message>
<source>Groupchat #%1</source>
<translation type="unfinished"></translation>
</message>
|
<|file_name|>nsis.js<|end_file_name|><|fim▁begin|>/* ***** BEGIN LICENSE BLOCK *****
* Distributed under the BSD license:
*<|fim▁hole|> * All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * 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.
* * Neither the name of Ajax.org B.V. 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 AJAX.ORG B.V. 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.
*
* ***** END LICENSE BLOCK ***** */
/*
THIS FILE WAS AUTOGENERATED BY mode.tmpl.js
*/
define(function(require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var NSISHighlightRules = require("./nsis_highlight_rules").NSISHighlightRules;
var FoldMode = require("./folding/cstyle").FoldMode;
var Mode = function() {
this.HighlightRules = NSISHighlightRules;
this.foldingRules = new FoldMode();
this.$behaviour = this.$defaultBehaviour;
};
oop.inherits(Mode, TextMode);
(function() {
this.lineCommentStart = [";", "#"];
this.blockComment = {start: "/*", end: "*/"};
this.$id = "ace/mode/nsis";
}).call(Mode.prototype);
exports.Mode = Mode;
});<|fim▁end|>
|
* Copyright (c) 2012, Ajax.org B.V.
|
<|file_name|>issue_12590_c.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<|fim▁hole|>
// pretty-compare-only
// pretty-mode:expanded
// pp-exact:issue_12590_c.pp
// The next line should be expanded
mod issue_12590_b;
fn main() { }<|fim▁end|>
|
// option. This file may not be copied, modified, or distributed
// except according to those terms.
|
<|file_name|>GridCachePreloaderAdapter.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.ignite.internal.processors.cache;
import java.util.Collection;
import java.util.UUID;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.IgniteLogger;
import org.apache.ignite.internal.IgniteInternalFuture;
import org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion;
import org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtFuture;
import org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtLocalPartition;
import org.apache.ignite.internal.processors.cache.distributed.dht.atomic.GridNearAtomicAbstractUpdateRequest;
import org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPartitionDemandMessage;
import org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPartitionSupplyMessage;
import org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPartitionsExchangeFuture;
import org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPreloaderAssignments;
import org.apache.ignite.internal.util.future.GridFinishedFuture;
import org.apache.ignite.internal.util.future.GridFutureAdapter;
import org.apache.ignite.lang.IgnitePredicate;
import org.jetbrains.annotations.Nullable;
/**
* Adapter for preloading which always assumes that preloading finished.
*/
public class GridCachePreloaderAdapter implements GridCachePreloader {
/** */
protected final CacheGroupContext grp;
/** */
protected final GridCacheSharedContext ctx;
/** Logger. */
protected final IgniteLogger log;
/** Start future (always completed by default). */
private final IgniteInternalFuture finFut;
/** Preload predicate. */
protected IgnitePredicate<GridCacheEntryInfo> preloadPred;
/**
* @param grp Cache group.
*/
public GridCachePreloaderAdapter(CacheGroupContext grp) {
assert grp != null;
this.grp = grp;
ctx = grp.shared();
log = ctx.logger(getClass());
finFut = new GridFinishedFuture();
}
/** {@inheritDoc} */
@Override public void start() throws IgniteCheckedException {
// No-op.
}
/** {@inheritDoc} */
@Override public void onKernalStop() {
// No-op.
}
/** {@inheritDoc} */
@Override public IgniteInternalFuture<Boolean> forceRebalance() {
return new GridFinishedFuture<>(true);
}
/** {@inheritDoc} */
@Override public boolean needForceKeys() {
return false;
}
/** {@inheritDoc} */
@Override public void onReconnected() {
// No-op.
}
/** {@inheritDoc} */
@Override public void preloadPredicate(IgnitePredicate<GridCacheEntryInfo> preloadPred) {
this.preloadPred = preloadPred;
}
/** {@inheritDoc} */
@Override public IgnitePredicate<GridCacheEntryInfo> preloadPredicate() {
return preloadPred;
}
/** {@inheritDoc} */
@Override public IgniteInternalFuture<Object> startFuture() {
return finFut;<|fim▁hole|> @Override public IgniteInternalFuture<?> syncFuture() {
return finFut;
}
/** {@inheritDoc} */
@Override public IgniteInternalFuture<Boolean> rebalanceFuture() {
return finFut;
}
/** {@inheritDoc} */
@Override public void unwindUndeploys() {
grp.unwindUndeploys();
}
/** {@inheritDoc} */
@Override public void handleSupplyMessage(int idx, UUID id, GridDhtPartitionSupplyMessage s) {
// No-op.
}
/** {@inheritDoc} */
@Override public void handleDemandMessage(int idx, UUID id, GridDhtPartitionDemandMessage d) {
// No-op.
}
/** {@inheritDoc} */
@Override public GridDhtFuture<Object> request(GridCacheContext ctx, Collection<KeyCacheObject> keys,
AffinityTopologyVersion topVer) {
return null;
}
/** {@inheritDoc} */
@Override public GridDhtFuture<Object> request(GridCacheContext ctx, GridNearAtomicAbstractUpdateRequest req,
AffinityTopologyVersion topVer) {
return null;
}
/** {@inheritDoc} */
@Override public void onInitialExchangeComplete(@Nullable Throwable err) {
// No-op.
}
/** {@inheritDoc} */
@Override public GridDhtPreloaderAssignments assign(GridDhtPartitionsExchangeFuture exchFut) {
return null;
}
/** {@inheritDoc} */
@Override public Runnable addAssignments(GridDhtPreloaderAssignments assignments,
boolean forcePreload,
int cnt,
Runnable next,
@Nullable GridFutureAdapter<Boolean> forcedRebFut) {
return null;
}
/** {@inheritDoc} */
@Override public void evictPartitionAsync(GridDhtLocalPartition part) {
// No-op.
}
/** {@inheritDoc} */
@Override public void onTopologyChanged(GridDhtPartitionsExchangeFuture lastFut) {
// No-op.
}
/** {@inheritDoc} */
@Override public void dumpDebugInfo() {
// No-op.
}
}<|fim▁end|>
|
}
/** {@inheritDoc} */
|
<|file_name|>cc_puppet.py<|end_file_name|><|fim▁begin|># vi: ts=4 expandtab
#
# Copyright (C) 2009-2010 Canonical Ltd.
# Copyright (C) 2012 Hewlett-Packard Development Company, L.P.
#
# Author: Scott Moser <[email protected]>
# Author: Juerg Haefliger <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3, as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from StringIO import StringIO
import os
import socket
from cloudinit import helpers
from cloudinit import util
PUPPET_CONF_PATH = '/etc/puppet/puppet.conf'
PUPPET_SSL_CERT_DIR = '/var/lib/puppet/ssl/certs/'
PUPPET_SSL_DIR = '/var/lib/puppet/ssl'
PUPPET_SSL_CERT_PATH = '/var/lib/puppet/ssl/certs/ca.pem'
def _autostart_puppet(log):
# Set puppet to automatically start
if os.path.exists('/etc/default/puppet'):
util.subp(['sed', '-i',
'-e', 's/^START=.*/START=yes/',
'/etc/default/puppet'], capture=False)
elif os.path.exists('/bin/systemctl'):
util.subp(['/bin/systemctl', 'enable', 'puppet.service'],
capture=False)
elif os.path.exists('/sbin/chkconfig'):
util.subp(['/sbin/chkconfig', 'puppet', 'on'], capture=False)
else:
log.warn(("Sorry we do not know how to enable"
" puppet services on this system"))
def handle(name, cfg, cloud, log, _args):
# If there isn't a puppet key in the configuration don't do anything
if 'puppet' not in cfg:
log.debug(("Skipping module named %s,"
" no 'puppet' configuration found"), name)
return
puppet_cfg = cfg['puppet']
# Start by installing the puppet package if necessary...
install = util.get_cfg_option_bool(puppet_cfg, 'install', True)
version = util.get_cfg_option_str(puppet_cfg, 'version', None)
if not install and version:
log.warn(("Puppet install set false but version supplied,"
" doing nothing."))
elif install:
log.debug(("Attempting to install puppet %s,"),
version if version else 'latest')
cloud.distro.install_packages(('puppet', version))
# ... and then update the puppet configuration
if 'conf' in puppet_cfg:
# Add all sections from the conf object to puppet.conf
contents = util.load_file(PUPPET_CONF_PATH)
# Create object for reading puppet.conf values
puppet_config = helpers.DefaultingConfigParser()
# Read puppet.conf values from original file in order to be able to
# mix the rest up. First clean them up<|fim▁hole|> # (TODO(harlowja) is this really needed??)
cleaned_lines = [i.lstrip() for i in contents.splitlines()]
cleaned_contents = '\n'.join(cleaned_lines)
puppet_config.readfp(StringIO(cleaned_contents),
filename=PUPPET_CONF_PATH)
for (cfg_name, cfg) in puppet_cfg['conf'].iteritems():
# Cert configuration is a special case
# Dump the puppet master ca certificate in the correct place
if cfg_name == 'ca_cert':
# Puppet ssl sub-directory isn't created yet
# Create it with the proper permissions and ownership
util.ensure_dir(PUPPET_SSL_DIR, 0771)
util.chownbyname(PUPPET_SSL_DIR, 'puppet', 'root')
util.ensure_dir(PUPPET_SSL_CERT_DIR)
util.chownbyname(PUPPET_SSL_CERT_DIR, 'puppet', 'root')
util.write_file(PUPPET_SSL_CERT_PATH, str(cfg))
util.chownbyname(PUPPET_SSL_CERT_PATH, 'puppet', 'root')
else:
# Iterate throug the config items, we'll use ConfigParser.set
# to overwrite or create new items as needed
for (o, v) in cfg.iteritems():
if o == 'certname':
# Expand %f as the fqdn
# TODO(harlowja) should this use the cloud fqdn??
v = v.replace("%f", socket.getfqdn())
# Expand %i as the instance id
v = v.replace("%i", cloud.get_instance_id())
# certname needs to be downcased
v = v.lower()
puppet_config.set(cfg_name, o, v)
# We got all our config as wanted we'll rename
# the previous puppet.conf and create our new one
util.rename(PUPPET_CONF_PATH, "%s.old" % (PUPPET_CONF_PATH))
util.write_file(PUPPET_CONF_PATH, puppet_config.stringify())
# Set it up so it autostarts
_autostart_puppet(log)
# Start puppetd
util.subp(['service', 'puppet', 'start'], capture=False)<|fim▁end|>
| |
<|file_name|>doc.go<|end_file_name|><|fim▁begin|>// softlayer_billing_item_cancellation_request - SoftLayer customers can use this API to submit a
// cancellation request. A single service cancellation can contain multiple cancellation items which
// contain a billing item.
package softlayer_billing_item_cancellation_request<|fim▁hole|><|fim▁end|>
|
// DO NOT EDIT. THIS FILE WAS AUTOMATICALLY GENERATED
|
<|file_name|>importHelpersWithLocalCollisions(module=amd).js<|end_file_name|><|fim▁begin|>//// [tests/cases/compiler/importHelpersWithLocalCollisions.ts] ////
//// [a.ts]
declare var dec: any, __decorate: any;
@dec export class A {
}
const o = { a: 1 };
const y = { ...o };
//// [tslib.d.ts]
export declare function __extends(d: Function, b: Function): void;
export declare function __decorate(decorators: Function[], target: any, key?: string | symbol, desc?: any): any;
export declare function __param(paramIndex: number, decorator: Function): Function;
export declare function __metadata(metadataKey: any, metadataValue: any): Function;
export declare function __awaiter(thisArg: any, _arguments: any, P: Function, generator: Function): any;
//// [a.js]
define(["require", "exports", "tslib"], function (require, exports, tslib_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.A = void 0;
let A = class A {
<|fim▁hole|> };
A = (0, tslib_1.__decorate)([
dec
], A);
exports.A = A;
const o = { a: 1 };
const y = Object.assign({}, o);
});<|fim▁end|>
| |
<|file_name|>0042_studytableevent_notes.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Generated by Django 1.10a1 on 2016-07-19 15:11
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('dashboard', '0041_auto_20160707_1856'),<|fim▁hole|>
operations = [
migrations.AddField(
model_name='studytableevent',
name='notes',
field=models.TextField(blank=True, null=True),
),
]<|fim▁end|>
|
]
|
<|file_name|>materialize.min.js<|end_file_name|><|fim▁begin|>version https://git-lfs.github.com/spec/v1<|fim▁hole|><|fim▁end|>
|
oid sha256:355954a2b585f8b34c53b8bea9346fabde06b161ec86b87e9b829bea4acb87e9
size 108190
|
<|file_name|>download.component.ts<|end_file_name|><|fim▁begin|>import { Component, OnInit } from '@angular/core';
import {BaServerService} from "../../theme/services/baServer/baServer.service";
@Component({
selector: 'download',
styles: [require('./download.scss')],
template: require('./download.component.html')
})
export class DownloadComponent implements OnInit {
public downloads;
constructor(private _serverService: BaServerService) {
}
ngOnInit() {
this.getDownloads();
}
<|fim▁hole|> // the first argument is a function which runs on success
data => {
this.downloads = data.obj;
},
// the second argument is a function which runs on error
err => console.error(err)
);
}
}<|fim▁end|>
|
getDownloads() {
this._serverService.get().subscribe(
|
<|file_name|>common.go<|end_file_name|><|fim▁begin|>package domain
import (
"flag"
)
type Config struct {
DockerAPIEndpoint string
VulcandAPIEndpoint string
HostIP string
}
<|fim▁hole|> flag.StringVar(&config.DockerAPIEndpoint, "d", "/var/run/docker.sock", "Docker API endpoint")
flag.StringVar(&config.VulcandAPIEndpoint, "v", "172.17.8.101:8182", "Vulcand API endpoint")
flag.StringVar(&config.HostIP, "h", "172.17.8.101", "Host's external facing ip")
}<|fim▁end|>
|
func (config *Config) InstallFlags() {
|
<|file_name|>StorageFileAccess.java<|end_file_name|><|fim▁begin|>/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* 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 .
*/
package com.sun.star.sdbcx.comp.hsqldb;
import org.hsqldb.lib.FileAccess;
import org.hsqldb.lib.FileSystemRuntimeException;
@SuppressWarnings("ucd")
public class StorageFileAccess implements org.hsqldb.lib.FileAccess{
static { NativeLibraries.load(); }
String ds_name;
String key;
/** Creates a new instance of StorageFileAccess */
public StorageFileAccess(Object key) throws java.lang.Exception{
this.key = (String)key;
}
public void createParentDirs(String filename) {
}
public boolean isStreamElement(String elementName) {
return isStreamElement(key,elementName);
}
public java.io.InputStream openInputStreamElement(String streamName) throws java.io.IOException {
return new NativeInputStreamHelper(key,streamName);
}
public java.io.OutputStream openOutputStreamElement(String streamName) throws java.io.IOException {<|fim▁hole|>
public void removeElement(String filename) throws java.util.NoSuchElementException {
try {
if ( isStreamElement(key,filename) )
removeElement(key,filename);
} catch (java.io.IOException e) {
throw new FileSystemRuntimeException( e );
}
}
public void renameElement(String oldName, String newName) throws java.util.NoSuchElementException {
try {
if ( isStreamElement(key,oldName) ){
removeElement(key,newName);
renameElement(key,oldName, newName);
}
} catch (java.io.IOException e) {
throw new FileSystemRuntimeException( e );
}
}
private class FileSync implements FileAccess.FileSync
{
private final NativeOutputStreamHelper os;
private FileSync(NativeOutputStreamHelper _os)
{
os = _os;
}
public void sync() throws java.io.IOException
{
os.sync();
}
}
public FileAccess.FileSync getFileSync(java.io.OutputStream os) throws java.io.IOException
{
return new FileSync((NativeOutputStreamHelper)os);
}
static native boolean isStreamElement(String key,String elementName);
static native void removeElement(String key,String filename) throws java.util.NoSuchElementException, java.io.IOException;
static native void renameElement(String key,String oldName, String newName) throws java.util.NoSuchElementException, java.io.IOException;
}<|fim▁end|>
|
return new NativeOutputStreamHelper(key,streamName);
}
|
<|file_name|>mul.rs<|end_file_name|><|fim▁begin|>use {Instruction,Value,Expression,Type};
#[derive(Clone,Debug,PartialEq,Eq)]
pub struct Mul
{
pub lhs: Box<Value>,
pub rhs: Box<Value>,<|fim▁hole|>}
impl Mul
{
pub fn new(lhs: Value, rhs: Value) -> Self {
Mul {
lhs: Box::new(lhs),
rhs: Box::new(rhs),
}
}
pub fn ty(&self) -> Type { self.lhs.node.ty() }
}
impl_instruction!(Mul: lhs, rhs);
impl_instruction_binary!(Mul: lhs, rhs);<|fim▁end|>
| |
<|file_name|>index.js<|end_file_name|><|fim▁begin|>'use strict';
var fs = require('fs'),
path = require('path');
// path.basename('/foo/bar/baz/asdf/quux.html', '.html') = quux
// path.dirname('/foo/bar/baz/asdf/quux.html') = /foo/bar/baz/asdf/
// path.parse('/home/user/dir/file.txt')
// returns
// {
// root : "/",
// dir : "/home/user/dir",
// base : "file.txt",
// ext : ".txt",
// name : "file"
// }
var walk = function(dir, done){
var results = {};
fs.readdir(dir, function(err, list){
if (err) {
return done(err);
}
var pending = list.length;
if (!pending) {
return done(null, results);
}
list.forEach(function(layer){
var target = path.resolve(dir, layer);
fs.stat(target, function(err, stat){
if (stat && stat.isDirectory()) {
console.log(layer);
results[layer] = [];
walk(target, function(err, file){
console.log(file);
if (!--pending) {
done(null, results);
}
});
} else {
var file = path.basename(target);
if (file[0] === '_') {
// results[layer][].push(file);
null;
}
if (!--pending) {
done(null, results);
}
}
});
});
});
};
var walking = function(config, done){
var results = {};
var pending = config.layers.length;
config.layers.forEach(function(layer){
results[layer] = [];
if (!pending) {
return done(null, results);
}
fs.readdir(config.src.scss + '/' + layer, function(err, files){
if (err) {
return 'error #1';
}
files.forEach(function(file){
if (file[0] !== '.') {
if (file[0] !== '_') {
results[layer].push(file);
} else {
results[layer].push(file.slice(1, -5));
}
}
});
});
if (pending === 1) {
done(null, results);
} else {
--pending;
}
});
};
<|fim▁hole|>var layers = function(dir){
var results = walk(dir, function(err, results){
if (err) {
throw err;
}
results = JSON.stringify(results, null, 4);
console.log(results);
fs.writeFile('guide/app.json', results);
return results;
});
}
module.exports = layers;<|fim▁end|>
| |
<|file_name|>combination_sum1.py<|end_file_name|><|fim▁begin|>Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
The same repeated number may be chosen from C unlimited number of times.
Note:
All numbers (including target) will be positive integers.
Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
The solution set must not contain duplicate combinations.
For example, given candidate set 2,3,6,7 and target 7,
A solution set is:
[7]
[2, 2, 3]
class Solution:
# @param candidates, a list of integers
# @param target, integer
# @return a list of lists of integers
# Recursion
# Sort the array at first, then use the recursion to find
# the result, Time O(n^2)
# 96ms
def combinationSum(self, candidates, target):
candidates.sort()
self.result = []
self.dfs(candidates,target,0,[])
return self.result
def dfs(self,candidates,target,start,reslist):
length = len(candidates)
if target == 0:
return self.result.append(reslist)
for i in xrange(start,length):
if target < candidates[i]:return
self.dfs(candidates,target-candidates[i],i,reslist+[candidates[i]])
# DFS, not sort array (220ms)
def combinationSum(self, candidates, target):
self.result = []
self.dfs(candidates,0,target,[])
return self.result
def dfs(self,can,cursum,target,res):
if cursum > target: return
if cursum == target:
self.result.append(res)
return
for i in xrange(len(can)):
if not res or res[len(res)-1] <= can[i]:
self.dfs(can,cursum+can[i],target,res+[can[i]])
For the combination_sum2, just change the start index from i to the i+1<|fim▁hole|>Time Complexity: T(n) = T(n-1) + 1 = O(n) ?<|fim▁end|>
| |
<|file_name|>test1.py<|end_file_name|><|fim▁begin|>from time import sleep<|fim▁hole|> def testOne(self):
sleep(1.5) # To check duration
assert 4 == 2*2
def testTwo(self):
assert True
def testThree():
assert 4 == 2*2<|fim▁end|>
|
class TestPyTest:
|
<|file_name|>extensions.py<|end_file_name|><|fim▁begin|># Copyright 2011 OpenStack Foundation
# Copyright 2011 Justin Santa Barbara
# 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.
import os
from oslo.config import cfg
import webob.dec
import webob.exc
import cinder.api.openstack
from cinder.api.openstack import wsgi
from cinder.api import xmlutil
from cinder import exception
from cinder.i18n import _
from cinder.openstack.common import importutils
from cinder.openstack.common import log as logging
import cinder.policy
CONF = cfg.CONF
LOG = logging.getLogger(__name__)
class ExtensionDescriptor(object):
"""Base class that defines the contract for extensions.
Note that you don't have to derive from this class to have a valid
extension; it is purely a convenience.
"""
# The name of the extension, e.g., 'Fox In Socks'
name = None
# The alias for the extension, e.g., 'FOXNSOX'
alias = None
# Description comes from the docstring for the class
# The XML namespace for the extension, e.g.,
# 'http://www.fox.in.socks/api/ext/pie/v1.0'
namespace = None
# The timestamp when the extension was last updated, e.g.,
# '2011-01-22T13:25:27-06:00'
updated = None
def __init__(self, ext_mgr):
"""Register extension with the extension manager."""
ext_mgr.register(self)
self.ext_mgr = ext_mgr
def get_resources(self):
"""List of extensions.ResourceExtension extension objects.
Resources define new nouns, and are accessible through URLs.
"""
resources = []
return resources
def get_controller_extensions(self):
"""List of extensions.ControllerExtension extension objects.
Controller extensions are used to extend existing controllers.
"""
controller_exts = []
return controller_exts
@classmethod
def nsmap(cls):
"""Synthesize a namespace map from extension."""
# Start with a base nsmap
nsmap = ext_nsmap.copy()
# Add the namespace for the extension
nsmap[cls.alias] = cls.namespace
return nsmap
@classmethod
def xmlname(cls, name):
"""Synthesize element and attribute names."""
return '{%s}%s' % (cls.namespace, name)
def make_ext(elem):
elem.set('name')
elem.set('namespace')
elem.set('alias')
elem.set('updated')
desc = xmlutil.SubTemplateElement(elem, 'description')
desc.text = 'description'
xmlutil.make_links(elem, 'links')
ext_nsmap = {None: xmlutil.XMLNS_COMMON_V10, 'atom': xmlutil.XMLNS_ATOM}
class ExtensionTemplate(xmlutil.TemplateBuilder):
def construct(self):
root = xmlutil.TemplateElement('extension', selector='extension')
make_ext(root)
return xmlutil.MasterTemplate(root, 1, nsmap=ext_nsmap)
class ExtensionsTemplate(xmlutil.TemplateBuilder):
def construct(self):
root = xmlutil.TemplateElement('extensions')
elem = xmlutil.SubTemplateElement(root, 'extension',
selector='extensions')
make_ext(elem)
return xmlutil.MasterTemplate(root, 1, nsmap=ext_nsmap)<|fim▁hole|>
class ExtensionsResource(wsgi.Resource):
def __init__(self, extension_manager):
self.extension_manager = extension_manager
super(ExtensionsResource, self).__init__(None)
def _translate(self, ext):
ext_data = {}
ext_data['name'] = ext.name
ext_data['alias'] = ext.alias
ext_data['description'] = ext.__doc__
ext_data['namespace'] = ext.namespace
ext_data['updated'] = ext.updated
ext_data['links'] = [] # TODO(dprince): implement extension links
return ext_data
@wsgi.serializers(xml=ExtensionsTemplate)
def index(self, req):
extensions = []
for _alias, ext in self.extension_manager.extensions.iteritems():
extensions.append(self._translate(ext))
return dict(extensions=extensions)
@wsgi.serializers(xml=ExtensionTemplate)
def show(self, req, id):
try:
# NOTE(dprince): the extensions alias is used as the 'id' for show
ext = self.extension_manager.extensions[id]
except KeyError:
raise webob.exc.HTTPNotFound()
return dict(extension=self._translate(ext))
def delete(self, req, id):
raise webob.exc.HTTPNotFound()
def create(self, req):
raise webob.exc.HTTPNotFound()
class ExtensionManager(object):
"""Load extensions from the configured extension path.
See cinder/tests/api/extensions/foxinsocks/extension.py for an
example extension implementation.
"""
def __init__(self):
LOG.info(_('Initializing extension manager.'))
self.cls_list = CONF.osapi_volume_extension
self.extensions = {}
self._load_extensions()
def is_loaded(self, alias):
return alias in self.extensions
def register(self, ext):
# Do nothing if the extension doesn't check out
if not self._check_extension(ext):
return
alias = ext.alias
LOG.info(_('Loaded extension: %s'), alias)
if alias in self.extensions:
raise exception.Error("Found duplicate extension: %s" % alias)
self.extensions[alias] = ext
def get_resources(self):
"""Returns a list of ResourceExtension objects."""
resources = []
resources.append(ResourceExtension('extensions',
ExtensionsResource(self)))
for ext in self.extensions.values():
try:
resources.extend(ext.get_resources())
except AttributeError:
# NOTE(dprince): Extension aren't required to have resource
# extensions
pass
return resources
def get_controller_extensions(self):
"""Returns a list of ControllerExtension objects."""
controller_exts = []
for ext in self.extensions.values():
try:
get_ext_method = ext.get_controller_extensions
except AttributeError:
# NOTE(Vek): Extensions aren't required to have
# controller extensions
continue
controller_exts.extend(get_ext_method())
return controller_exts
def _check_extension(self, extension):
"""Checks for required methods in extension objects."""
try:
LOG.debug('Ext name: %s', extension.name)
LOG.debug('Ext alias: %s', extension.alias)
LOG.debug('Ext description: %s',
' '.join(extension.__doc__.strip().split()))
LOG.debug('Ext namespace: %s', extension.namespace)
LOG.debug('Ext updated: %s', extension.updated)
except AttributeError as ex:
LOG.exception(_("Exception loading extension: %s"), unicode(ex))
return False
return True
def load_extension(self, ext_factory):
"""Execute an extension factory.
Loads an extension. The 'ext_factory' is the name of a
callable that will be imported and called with one
argument--the extension manager. The factory callable is
expected to call the register() method at least once.
"""
LOG.debug("Loading extension %s", ext_factory)
# Load the factory
factory = importutils.import_class(ext_factory)
# Call it
LOG.debug("Calling extension factory %s", ext_factory)
factory(self)
def _load_extensions(self):
"""Load extensions specified on the command line."""
extensions = list(self.cls_list)
# NOTE(thingee): Backwards compat for the old extension loader path.
# We can drop this post-grizzly in the H release.
old_contrib_path = ('cinder.api.openstack.volume.contrib.'
'standard_extensions')
new_contrib_path = 'cinder.api.contrib.standard_extensions'
if old_contrib_path in extensions:
LOG.warn(_('osapi_volume_extension is set to deprecated path: %s'),
old_contrib_path)
LOG.warn(_('Please set your flag or cinder.conf settings for '
'osapi_volume_extension to: %s'), new_contrib_path)
extensions = [e.replace(old_contrib_path, new_contrib_path)
for e in extensions]
for ext_factory in extensions:
try:
self.load_extension(ext_factory)
except Exception as exc:
LOG.warn(_('Failed to load extension %(ext_factory)s: '
'%(exc)s'),
{'ext_factory': ext_factory, 'exc': exc})
class ControllerExtension(object):
"""Extend core controllers of cinder OpenStack API.
Provide a way to extend existing cinder OpenStack API core
controllers.
"""
def __init__(self, extension, collection, controller):
self.extension = extension
self.collection = collection
self.controller = controller
class ResourceExtension(object):
"""Add top level resources to the OpenStack API in cinder."""
def __init__(self, collection, controller, parent=None,
collection_actions=None, member_actions=None,
custom_routes_fn=None):
if not collection_actions:
collection_actions = {}
if not member_actions:
member_actions = {}
self.collection = collection
self.controller = controller
self.parent = parent
self.collection_actions = collection_actions
self.member_actions = member_actions
self.custom_routes_fn = custom_routes_fn
def load_standard_extensions(ext_mgr, logger, path, package, ext_list=None):
"""Registers all standard API extensions."""
# Walk through all the modules in our directory...
our_dir = path[0]
for dirpath, dirnames, filenames in os.walk(our_dir):
# Compute the relative package name from the dirpath
relpath = os.path.relpath(dirpath, our_dir)
if relpath == '.':
relpkg = ''
else:
relpkg = '.%s' % '.'.join(relpath.split(os.sep))
# Now, consider each file in turn, only considering .py files
for fname in filenames:
root, ext = os.path.splitext(fname)
# Skip __init__ and anything that's not .py
if ext != '.py' or root == '__init__':
continue
# Try loading it
classname = "%s%s" % (root[0].upper(), root[1:])
classpath = ("%s%s.%s.%s" %
(package, relpkg, root, classname))
if ext_list is not None and classname not in ext_list:
logger.debug("Skipping extension: %s" % classpath)
continue
try:
ext_mgr.load_extension(classpath)
except Exception as exc:
logger.warn(_('Failed to load extension %(classpath)s: '
'%(exc)s'),
{'classpath': classpath, 'exc': exc})
# Now, let's consider any subdirectories we may have...
subdirs = []
for dname in dirnames:
# Skip it if it does not have __init__.py
if not os.path.exists(os.path.join(dirpath, dname,
'__init__.py')):
continue
# If it has extension(), delegate...
ext_name = ("%s%s.%s.extension" %
(package, relpkg, dname))
try:
ext = importutils.import_class(ext_name)
except ImportError:
# extension() doesn't exist on it, so we'll explore
# the directory for ourselves
subdirs.append(dname)
else:
try:
ext(ext_mgr)
except Exception as exc:
logger.warn(_('Failed to load extension %(ext_name)s: '
'%(exc)s'),
{'ext_name': ext_name, 'exc': exc})
# Update the list of directories we'll explore...
dirnames[:] = subdirs
def extension_authorizer(api_name, extension_name):
def authorize(context, target=None):
if target is None:
target = {'project_id': context.project_id,
'user_id': context.user_id}
action = '%s_extension:%s' % (api_name, extension_name)
cinder.policy.enforce(context, action, target)
return authorize
def soft_extension_authorizer(api_name, extension_name):
hard_authorize = extension_authorizer(api_name, extension_name)
def authorize(context):
try:
hard_authorize(context)
return True
except exception.NotAuthorized:
return False
return authorize<|fim▁end|>
| |
<|file_name|>filter.go<|end_file_name|><|fim▁begin|>package filter
import (
"fmt"
"strings"
"github.com/elastic/beats/libbeat/common"
"github.com/elastic/beats/libbeat/logp"
)
type FilterCondition struct {
}
type FilterRule interface {
Filter(event common.MapStr) (common.MapStr, error)
String() string
}
/* extends FilterRule */
type IncludeFields struct {
Fields []string
// condition
}
/* extend FilterRule */
type DropFields struct {
Fields []string
// condition
}
type FilterList struct {
filters []FilterRule
}
/* FilterList methods */
func New(config []FilterConfig) (*FilterList, error) {
Filters := &FilterList{}
Filters.filters = []FilterRule{}
logp.Debug("filter", "configuration %v", config)
for _, filterConfig := range config {
if filterConfig.DropFields != nil {
Filters.Register(NewDropFields(filterConfig.DropFields.Fields))
}
if filterConfig.IncludeFields != nil {
Filters.Register(NewIncludeFields(filterConfig.IncludeFields.Fields))
}
}
logp.Debug("filter", "filters: %v", Filters)
return Filters, nil
}
func (filters *FilterList) Register(filter FilterRule) {
filters.filters = append(filters.filters, filter)
logp.Debug("filter", "Register filter: %v", filter)
}
func (filters *FilterList) Get(index int) FilterRule {
return filters.filters[index]
}
// Applies a sequence of filtering rules and returns the filtered event
func (filters *FilterList) Filter(event common.MapStr) common.MapStr {
// Check if filters are set, just return event if not
if len(filters.filters) == 0 {
return event
}
// clone the event at first, before starting filtering
filtered := event.Clone()
var err error
for _, filter := range filters.filters {
filtered, err = filter.Filter(filtered)
if err != nil {
logp.Debug("filter", "fail to apply filtering rule %s: %s", filter, err)
}
}
return filtered
}
func (filters *FilterList) String() string {
s := []string{}
for _, filter := range filters.filters {
s = append(s, filter.String())
}
return strings.Join(s, ", ")
}
/* IncludeFields methods */
func NewIncludeFields(fields []string) *IncludeFields {
/* add read only fields if they are not yet */
for _, readOnly := range MandatoryExportedFields {
found := false
for _, field := range fields {
if readOnly == field {
found = true
}
}
if !found {
fields = append(fields, readOnly)
}
}
return &IncludeFields{Fields: fields}
}
func (f *IncludeFields) Filter(event common.MapStr) (common.MapStr, error) {
filtered := common.MapStr{}
for _, field := range f.Fields {
hasKey, err := event.HasKey(field)
if err != nil {
return filtered, fmt.Errorf("Fail to check the key %s: %s", field, err)
}
if hasKey {
errorOnCopy := event.CopyFieldsTo(filtered, field)
if errorOnCopy != nil {
return filtered, fmt.Errorf("Fail to copy key %s: %s", field, err)
}
}
}
return filtered, nil
}
func (f *IncludeFields) String() string {
return "include_fields=" + strings.Join(f.Fields, ", ")
}
/* DropFields methods */
func NewDropFields(fields []string) *DropFields {
/* remove read only fields */
for _, readOnly := range MandatoryExportedFields {
for i, field := range fields {
if readOnly == field {
fields = append(fields[:i], fields[i+1:]...)
}
}
}
return &DropFields{Fields: fields}
}
func (f *DropFields) Filter(event common.MapStr) (common.MapStr, error) {
for _, field := range f.Fields {
err := event.Delete(field)
if err != nil {
return event, fmt.Errorf("Fail to delete key %s: %s", field, err)
}
}
return event, nil<|fim▁hole|>}
func (f *DropFields) String() string {
return "drop_fields=" + strings.Join(f.Fields, ", ")
}<|fim▁end|>
| |
<|file_name|>certstore.py<|end_file_name|><|fim▁begin|># Authors:
# Jan Cholasta <[email protected]>
#
# Copyright (C) 2014 Red Hat
# see file 'COPYING' for use and warranty information
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
"""
LDAP shared certificate store.
"""
from pyasn1.error import PyAsn1Error
from ipapython.dn import DN
from ipapython.certdb import get_ca_nickname
from ipalib import errors, x509
def _parse_cert(dercert):
try:
cert = x509.load_certificate(dercert, x509.DER)
subject = DN(cert.subject)
issuer = DN(cert.issuer)
serial_number = cert.serial_number
public_key_info = x509.get_der_public_key_info(dercert, x509.DER)
except (ValueError, PyAsn1Error) as e:
raise ValueError("failed to decode certificate: %s" % e)
subject = str(subject).replace('\\;', '\\3b')
issuer = str(issuer).replace('\\;', '\\3b')
issuer_serial = '%s;%s' % (issuer, serial_number)
return subject, issuer_serial, public_key_info
def init_ca_entry(entry, dercert, nickname, trusted, ext_key_usage):
"""
Initialize certificate store entry for a CA certificate.
"""<|fim▁hole|> subject, issuer_serial, public_key = _parse_cert(dercert)
if ext_key_usage is not None:
try:
cert_eku = x509.get_ext_key_usage(dercert, x509.DER)
except ValueError as e:
raise ValueError("failed to decode certificate: %s" % e)
if cert_eku is not None:
cert_eku -= {x509.EKU_SERVER_AUTH, x509.EKU_CLIENT_AUTH,
x509.EKU_EMAIL_PROTECTION, x509.EKU_CODE_SIGNING,
x509.EKU_ANY, x509.EKU_PLACEHOLDER}
ext_key_usage = ext_key_usage | cert_eku
entry['objectClass'] = ['ipaCertificate', 'pkiCA', 'ipaKeyPolicy']
entry['cn'] = [nickname]
entry['ipaCertSubject'] = [subject]
entry['ipaCertIssuerSerial'] = [issuer_serial]
entry['ipaPublicKey'] = [public_key]
entry['cACertificate;binary'] = [dercert]
if trusted is not None:
entry['ipaKeyTrust'] = ['trusted' if trusted else 'distrusted']
if ext_key_usage is not None:
ext_key_usage = list(ext_key_usage)
if not ext_key_usage:
ext_key_usage.append(x509.EKU_PLACEHOLDER)
entry['ipaKeyExtUsage'] = ext_key_usage
def update_compat_ca(ldap, base_dn, dercert):
"""
Update the CA certificate in cn=CAcert,cn=ipa,cn=etc,SUFFIX.
"""
dn = DN(('cn', 'CAcert'), ('cn', 'ipa'), ('cn', 'etc'), base_dn)
try:
entry = ldap.get_entry(dn, attrs_list=['cACertificate;binary'])
entry.single_value['cACertificate;binary'] = dercert
ldap.update_entry(entry)
except errors.NotFound:
entry = ldap.make_entry(dn)
entry['objectClass'] = ['nsContainer', 'pkiCA']
entry.single_value['cn'] = 'CAcert'
entry.single_value['cACertificate;binary'] = dercert
ldap.add_entry(entry)
except errors.EmptyModlist:
pass
def clean_old_config(ldap, base_dn, dn, config_ipa, config_compat):
"""
Remove ipaCA and compatCA flags from their previous carriers.
"""
if not config_ipa and not config_compat:
return
try:
result, _truncated = ldap.find_entries(
base_dn=DN(('cn', 'certificates'), ('cn', 'ipa'), ('cn', 'etc'),
base_dn),
filter='(|(ipaConfigString=ipaCA)(ipaConfigString=compatCA))',
attrs_list=['ipaConfigString'])
except errors.NotFound:
return
for entry in result:
if entry.dn == dn:
continue
for config in list(entry['ipaConfigString']):
if config.lower() == 'ipaca' and config_ipa:
entry['ipaConfigString'].remove(config)
elif config.lower() == 'compatca' and config_compat:
entry['ipaConfigString'].remove(config)
try:
ldap.update_entry(entry)
except errors.EmptyModlist:
pass
def add_ca_cert(ldap, base_dn, dercert, nickname, trusted=None,
ext_key_usage=None, config_ipa=False, config_compat=False):
"""
Add new entry for a CA certificate to the certificate store.
"""
container_dn = DN(('cn', 'certificates'), ('cn', 'ipa'), ('cn', 'etc'),
base_dn)
dn = DN(('cn', nickname), container_dn)
entry = ldap.make_entry(dn)
init_ca_entry(entry, dercert, nickname, trusted, ext_key_usage)
if config_ipa:
entry.setdefault('ipaConfigString', []).append('ipaCA')
if config_compat:
entry.setdefault('ipaConfigString', []).append('compatCA')
if config_compat:
update_compat_ca(ldap, base_dn, dercert)
ldap.add_entry(entry)
clean_old_config(ldap, base_dn, dn, config_ipa, config_compat)
def update_ca_cert(ldap, base_dn, dercert, trusted=None, ext_key_usage=None,
config_ipa=False, config_compat=False):
"""
Update existing entry for a CA certificate in the certificate store.
"""
subject, issuer_serial, public_key = _parse_cert(dercert)
filter = ldap.make_filter({'ipaCertSubject': subject})
result, _truncated = ldap.find_entries(
base_dn=DN(('cn', 'certificates'), ('cn', 'ipa'), ('cn', 'etc'),
base_dn),
filter=filter,
attrs_list=['cn', 'ipaCertSubject', 'ipaCertIssuerSerial',
'ipaPublicKey', 'ipaKeyTrust', 'ipaKeyExtUsage',
'ipaConfigString', 'cACertificate;binary'])
entry = result[0]
dn = entry.dn
for old_cert in entry['cACertificate;binary']:
# Check if we are adding a new cert
if old_cert == dercert:
break
else:
# We are adding a new cert, validate it
if entry.single_value['ipaCertSubject'].lower() != subject.lower():
raise ValueError("subject name mismatch")
if entry.single_value['ipaPublicKey'] != public_key:
raise ValueError("subject public key info mismatch")
entry['ipaCertIssuerSerial'].append(issuer_serial)
entry['cACertificate;binary'].append(dercert)
# Update key trust
if trusted is not None:
old_trust = entry.single_value.get('ipaKeyTrust')
new_trust = 'trusted' if trusted else 'distrusted'
if old_trust is not None and old_trust.lower() != new_trust:
raise ValueError("inconsistent trust")
entry.single_value['ipaKeyTrust'] = new_trust
# Update extended key usage
if trusted is not False:
if ext_key_usage is not None:
old_eku = set(entry.get('ipaKeyExtUsage', []))
old_eku.discard(x509.EKU_PLACEHOLDER)
new_eku = old_eku | ext_key_usage
if not new_eku:
new_eku.add(x509.EKU_PLACEHOLDER)
entry['ipaKeyExtUsage'] = list(new_eku)
else:
entry.pop('ipaKeyExtUsage', None)
# Update configuration flags
is_ipa = False
is_compat = False
for config in entry.get('ipaConfigString', []):
if config.lower() == 'ipaca':
is_ipa = True
elif config.lower() == 'compatca':
is_compat = True
if config_ipa and not is_ipa:
entry.setdefault('ipaConfigString', []).append('ipaCA')
if config_compat and not is_compat:
entry.setdefault('ipaConfigString', []).append('compatCA')
if is_compat or config_compat:
update_compat_ca(ldap, base_dn, dercert)
ldap.update_entry(entry)
clean_old_config(ldap, base_dn, dn, config_ipa, config_compat)
def put_ca_cert(ldap, base_dn, dercert, nickname, trusted=None,
ext_key_usage=None, config_ipa=False, config_compat=False):
"""
Add or update entry for a CA certificate in the certificate store.
"""
try:
update_ca_cert(ldap, base_dn, dercert, trusted, ext_key_usage,
config_ipa=config_ipa, config_compat=config_compat)
except errors.NotFound:
add_ca_cert(ldap, base_dn, dercert, nickname, trusted, ext_key_usage,
config_ipa=config_ipa, config_compat=config_compat)
except errors.EmptyModlist:
pass
def make_compat_ca_certs(certs, realm, ipa_ca_subject):
"""
Make CA certificates and associated key policy from DER certificates.
"""
result = []
for cert in certs:
subject, _issuer_serial, _public_key_info = _parse_cert(cert)
subject = DN(subject)
if ipa_ca_subject is not None and subject == DN(ipa_ca_subject):
nickname = get_ca_nickname(realm)
ext_key_usage = {x509.EKU_SERVER_AUTH,
x509.EKU_CLIENT_AUTH,
x509.EKU_EMAIL_PROTECTION,
x509.EKU_CODE_SIGNING}
else:
nickname = str(subject)
ext_key_usage = {x509.EKU_SERVER_AUTH}
result.append((cert, nickname, True, ext_key_usage))
return result
def get_ca_certs(ldap, base_dn, compat_realm, compat_ipa_ca,
filter_subject=None):
"""
Get CA certificates and associated key policy from the certificate store.
"""
if filter_subject is not None:
if not isinstance(filter_subject, list):
filter_subject = [filter_subject]
filter_subject = [str(subj).replace('\\;', '\\3b')
for subj in filter_subject]
certs = []
config_dn = DN(('cn', 'ipa'), ('cn', 'etc'), base_dn)
container_dn = DN(('cn', 'certificates'), config_dn)
try:
# Search the certificate store for CA certificate entries
filters = ['(objectClass=ipaCertificate)', '(objectClass=pkiCA)']
if filter_subject:
filter = ldap.make_filter({'ipaCertSubject': filter_subject})
filters.append(filter)
result, _truncated = ldap.find_entries(
base_dn=container_dn,
filter=ldap.combine_filters(filters, ldap.MATCH_ALL),
attrs_list=['cn', 'ipaCertSubject', 'ipaCertIssuerSerial',
'ipaPublicKey', 'ipaKeyTrust', 'ipaKeyExtUsage',
'cACertificate;binary'])
for entry in result:
nickname = entry.single_value['cn']
trusted = entry.single_value.get('ipaKeyTrust', 'unknown').lower()
if trusted == 'trusted':
trusted = True
elif trusted == 'distrusted':
trusted = False
else:
trusted = None
ext_key_usage = entry.get('ipaKeyExtUsage')
if ext_key_usage is not None:
ext_key_usage = set(str(p) for p in ext_key_usage)
ext_key_usage.discard(x509.EKU_PLACEHOLDER)
for cert in entry.get('cACertificate;binary', []):
try:
_parse_cert(cert)
except ValueError:
certs = []
break
certs.append((cert, nickname, trusted, ext_key_usage))
except errors.NotFound:
try:
ldap.get_entry(container_dn, [''])
except errors.NotFound:
# Fallback to cn=CAcert,cn=ipa,cn=etc,SUFFIX
dn = DN(('cn', 'CAcert'), config_dn)
entry = ldap.get_entry(dn, ['cACertificate;binary'])
cert = entry.single_value['cACertificate;binary']
try:
subject, _issuer_serial, _public_key_info = _parse_cert(cert)
except ValueError:
pass
else:
if filter_subject is not None and subject not in filter_subject:
raise errors.NotFound(reason="no matching entry found")
if compat_ipa_ca:
ca_subject = subject
else:
ca_subject = None
certs = make_compat_ca_certs([cert], compat_realm, ca_subject)
if certs:
return certs
else:
raise errors.NotFound(reason="no such entry")
def trust_flags_to_key_policy(trust_flags):
"""
Convert certutil trust flags to certificate store key policy.
"""
if 'p' in trust_flags:
if 'C' in trust_flags or 'P' in trust_flags or 'T' in trust_flags:
raise ValueError("cannot be both trusted and not trusted")
return False, None, None
elif 'C' in trust_flags or 'T' in trust_flags:
if 'P' in trust_flags:
raise ValueError("cannot be both CA and not CA")
ca = True
elif 'P' in trust_flags:
ca = False
else:
return None, None, set()
trust_flags = trust_flags.split(',')
ext_key_usage = set()
for i, kp in enumerate((x509.EKU_SERVER_AUTH,
x509.EKU_EMAIL_PROTECTION,
x509.EKU_CODE_SIGNING)):
if 'C' in trust_flags[i] or 'P' in trust_flags[i]:
ext_key_usage.add(kp)
if 'T' in trust_flags[0]:
ext_key_usage.add(x509.EKU_CLIENT_AUTH)
return True, ca, ext_key_usage
def key_policy_to_trust_flags(trusted, ca, ext_key_usage):
"""
Convert certificate store key policy to certutil trust flags.
"""
if trusted is False:
return 'p,p,p'
elif trusted is None or ca is None:
return ',,'
elif ext_key_usage is None:
if ca:
return 'CT,C,C'
else:
return 'P,P,P'
trust_flags = ['', '', '']
for i, kp in enumerate((x509.EKU_SERVER_AUTH,
x509.EKU_EMAIL_PROTECTION,
x509.EKU_CODE_SIGNING)):
if kp in ext_key_usage:
trust_flags[i] += ('C' if ca else 'P')
if ca and x509.EKU_CLIENT_AUTH in ext_key_usage:
trust_flags[0] += 'T'
trust_flags = ','.join(trust_flags)
return trust_flags
def put_ca_cert_nss(ldap, base_dn, dercert, nickname, trust_flags,
config_ipa=False, config_compat=False):
"""
Add or update entry for a CA certificate in the certificate store.
"""
trusted, ca, ext_key_usage = trust_flags_to_key_policy(trust_flags)
if ca is False:
raise ValueError("must be CA certificate")
put_ca_cert(ldap, base_dn, dercert, nickname, trusted, ext_key_usage,
config_ipa, config_compat)
def get_ca_certs_nss(ldap, base_dn, compat_realm, compat_ipa_ca,
filter_subject=None):
"""
Get CA certificates and associated trust flags from the certificate store.
"""
nss_certs = []
certs = get_ca_certs(ldap, base_dn, compat_realm, compat_ipa_ca,
filter_subject=filter_subject)
for cert, nickname, trusted, ext_key_usage in certs:
trust_flags = key_policy_to_trust_flags(trusted, True, ext_key_usage)
nss_certs.append((cert, nickname, trust_flags))
return nss_certs<|fim▁end|>
| |
<|file_name|>start.py<|end_file_name|><|fim▁begin|>from bank_CI import BankCI
from bank_controller import BankController
from settings import DB_NAME, CREATE_TABLES, DROP_DATABASE
from sql_manager import BankDatabaseManager
def main():
manager = BankDatabaseManager.create_from_db_and_sql(DB_NAME, CREATE_TABLES, DROP_DATABASE, create_if_exists=False)
controller = BankController(manager)
command_interface = BankCI(controller)
command_interface.main_menu()
<|fim▁hole|><|fim▁end|>
|
if __name__ == '__main__':
main()
|
<|file_name|>main_test.go<|end_file_name|><|fim▁begin|>package main
import (
"bytes"
"fmt"
"os"
"os/exec"
"strings"
"testing"
<|fim▁hole|>func deleteTestFiles(t *testing.T) {
if err := os.RemoveAll(app.Path()); err != nil {
t.Error(err)
}
}
func TestMain(t *testing.M) {
os.Setenv("BANKSAURUS_ENV", "dev")
defer os.Setenv("BANKSAURUS_ENV", "")
os.Exit(t.Run())
}
func TestAcceptanceUsage(t *testing.T) {
defer deleteTestFiles(t)
testCases := []struct {
name string
command []string
expected string
errorExpected bool
}{
{
name: "Shows usage if no option is defined",
command: []string{""},
expected: usage + "\n",
errorExpected: true,
},
}
for _, tc := range testCases {
t.Log(tc.name)
t.Log(fmt.Sprintf("$ bscli %s", strings.Join(tc.command, " ")))
cmd := exec.Command("../../bscli", tc.command...)
var outBuffer, errBuffer bytes.Buffer
cmd.Stdout = &outBuffer
cmd.Stderr = &errBuffer
err := cmd.Run()
if !tc.errorExpected && err != nil {
t.Log(outBuffer.String())
t.Log(errBuffer.String())
t.Fatalf("Test failed due to command error: %s", err.Error())
}
testkit.AssertEqual(t, tc.expected, errBuffer.String())
testkit.AssertEqual(t, "", outBuffer.String())
}
}
func TestAcceptance(t *testing.T) {
defer deleteTestFiles(t)
fixture := "./data/fixtures/sample_records_load.csv"
testCases := []struct {
name string
command []string
expected string
errorExpected bool
}{
{
name: "Shows usage if option is '-h'",
command: []string{"-h"},
expected: intro + usage + options + "\n",
errorExpected: false,
},
{
name: "Shows version if option is '--version'",
command: []string{"--version"},
expected: app.Version + "\n",
errorExpected: false,
},
{
name: "No seller should be available here",
command: []string{"seller", "show"},
expected: "",
},
{
name: "Load records from file",
command: []string{"load", "--input", fixture},
expected: "",
},
{
name: "Shows seller loaded by the load records from file",
command: []string{"seller", "show"},
expected: "COMPRA CONTINENTE MAI\nTRF CREDIT\nCOMPRA FARMACIA SAO J\n",
},
{
name: "Shows report with all available transactions",
command: []string{"report"},
expected: "-0,52€ COMPRA CONTINENTE MAI\n593,48€ TRF CREDIT\n-95,09€ COMPRA FARMACIA SAO J\n-95,09€ COMPRA FARMACIA SAO J\n",
errorExpected: false,
},
{
name: "Shows report from bank records file",
command: []string{"report", "--input", fixture},
expected: "-0,52€ COMPRA CONTINENTE MAI\n593,48€ TRF CREDIT\n-95,09€ COMPRA FARMACIA SAO J\n-95,09€ COMPRA FARMACIA SAO J\n",
errorExpected: false,
},
{
name: "Shows report from bank records file, returns error if path does not exist",
command: []string{"report", "--input", "./thispathdoesnotexist/sample_records_load.csv"},
expected: errGeneric.Error() + "\n",
errorExpected: true,
},
{
name: "Shows report from bank records file, grouped by seller",
command: []string{
"report",
"--input", fixture,
"--grouped",
},
expected: "-0,52€ COMPRA CONTINENTE MAI\n593,48€ TRF CREDIT\n-190,18€ COMPRA FARMACIA SAO J\n",
errorExpected: false,
},
{
name: "Adds pretty name to seller",
command: []string{"seller", "change", "COMPRA CONTINENTE MAI", "--pretty", "Continente"},
expected: "",
},
{
name: "Show seller changed",
command: []string{"seller", "show"},
expected: "Continente\nTRF CREDIT\nCOMPRA FARMACIA SAO J\n",
},
{
name: "Shows report, with seller name instead of slug",
command: []string{"report"},
expected: "-0,52€ Continente\n593,48€ TRF CREDIT\n-95,09€ COMPRA FARMACIA SAO J\n-95,09€ COMPRA FARMACIA SAO J\n",
errorExpected: false,
},
}
for _, tc := range testCases {
t.Log(tc.name)
t.Log(fmt.Sprintf("$ bscli %s", strings.Join(tc.command, " ")))
cmd := exec.Command("../../bscli", tc.command...)
var outBuffer, errBuffer bytes.Buffer
cmd.Stdout = &outBuffer
cmd.Stderr = &errBuffer
err := cmd.Run()
if !tc.errorExpected && err != nil {
t.Log(outBuffer.String())
t.Log(errBuffer.String())
t.Fatalf("Test failed due to command error: %s", err.Error())
} else {
if tc.errorExpected {
testkit.AssertEqual(t, tc.expected, errBuffer.String())
testkit.AssertEqual(t, "", outBuffer.String())
} else {
testkit.AssertEqual(t, "", errBuffer.String())
testkit.AssertEqual(t, tc.expected, outBuffer.String())
}
}
}
}<|fim▁end|>
|
app "github.com/luistm/banksaurus/cmd/bscli/application"
"github.com/luistm/testkit"
)
|
<|file_name|>test_wheels_util.py<|end_file_name|><|fim▁begin|>from __future__ import absolute_import, unicode_literals
import pytest
from virtualenv.seed.wheels.embed import MAX, get_embed_wheel
from virtualenv.seed.wheels.util import Wheel
def test_wheel_support_no_python_requires(mocker):
wheel = get_embed_wheel("setuptools", for_py_version=None)
zip_mock = mocker.MagicMock()
mocker.patch("virtualenv.seed.wheels.util.ZipFile", new=zip_mock)
zip_mock.return_value.__enter__.return_value.read = lambda name: b""
supports = wheel.support_py("3.8")
assert supports is True
def test_bad_as_version_tuple():
with pytest.raises(ValueError, match="bad"):
Wheel.as_version_tuple("bad")
<|fim▁hole|> wheel = get_embed_wheel("setuptools", MAX)
assert wheel.support_py("3.3") is False
def test_wheel_repr():
wheel = get_embed_wheel("setuptools", MAX)
assert str(wheel.path) in repr(wheel)<|fim▁end|>
|
def test_wheel_not_support():
|
<|file_name|>DouDiZhuPokerAction.py<|end_file_name|><|fim▁begin|>#!/bin/python
import os
import roomai.common
import copy
#
#0, 1, 2, 3, ..., 7, 8, 9, 10, 11, 12, 13, 14
#^ ^ ^ ^ ^
#| | | | |
#3, 10, J, Q, K, A, 2, r, R
#
class DouDiZhuActionElement:
str_to_rank = {'3':0, '4':1, '5':2, '6':3, '7':4, '8':5, '9':6, 'T':7, 'J':8, 'Q':9, 'K':10, 'A':11, '2':12, 'r':13, 'R':14, 'x':15, 'b':16}
# x means check, b means bid
rank_to_str = {0: '3', 1: '4', 2: '5', 3: '6', 4: '7', 5: '8', 6: '9', 7: 'T', 8: 'J', 9: 'Q', 10: 'K', 11: 'A', 12: '2', 13: 'r', 14: 'R', 15: 'x', 16: 'b'}
total_normal_cards = 15
class DouDiZhuPokerAction(roomai.common.AbstractAction):
"""
"""
def __init__(self):
"""
"""
pass
def __init__(self, masterCards, slaveCards):
self.__masterCards__ = [c for c in masterCards]
self.__slaveCards__ = [c for c in slaveCards]
self.__masterPoints2Count__ = None
self.__slavePoints2Count__ = None
self.__isMasterStraight__ = None
self.__maxMasterPoint__ = None
self.__minMasterPoint__ = None<|fim▁hole|> self.__pattern__ = None
self.__action2pattern__()
self.__key__ = DouDiZhuPokerAction.__master_slave_cards_to_key__(masterCards, slaveCards)
def __get_key__(self): return self.__key__
key = property(__get_key__, doc="The key of DouDiZhu Action")
def __get_masterCards__(self): return self.__masterCards__
masterCards = property(__get_masterCards__, doc="The cards act as the master cards")
def __get_slaveCards__(self): return self.__slaveCards__
slaveCards = property(__get_slaveCards__, doc="The cards act as the slave cards")
def __get_masterPoints2Count__(self): return self.__masterPoints2Count__
masterPoints2Count = property(__get_masterPoints2Count__, doc="The count of different points in the masterCards")
def __get_slavePoints2Count__(self): return self.__slavePoints2Count__
slavePoints2Count = property(__get_slavePoints2Count__, doc="The count of different points in the slaveCards")
def __get_isMasterStraight__(self): return self.__isMasterStraight__
isMasterStraight = property(__get_isMasterStraight__, doc="The master cards are straight")
def __get_maxMasterPoint__(self): return self.__maxMasterPoint__
maxMasterPoint = property(__get_maxMasterPoint__, doc="The max point in the master cards")
def __get_minMasterPoint__(self): return self.__minMasterPoint__
minMasterPoint = property(__get_minMasterPoint__, doc="The min point in the master cards")
def __get_pattern__(self): return self.__pattern__
pattern = property(__get_pattern__, doc="The pattern of the action")
@classmethod
def lookup(cls, key):
return AllActions["".join(sorted(key))]
@classmethod
def __master_slave_cards_to_key__(cls, masterCards, slaveCards):
key_int = (masterCards + slaveCards)
key_str = []
for key in key_int:
key_str.append(DouDiZhuActionElement.rank_to_str[key])
key_str.sort()
return "".join(key_str)
def __action2pattern__(self):
self.__masterPoints2Count__ = dict()
for c in self.__masterCards__:
if c in self.__masterPoints2Count__:
self.__masterPoints2Count__[c] += 1
else:
self.__masterPoints2Count__[c] = 1
self.__slavePoints2Count__ = dict()
for c in self.__slaveCards__:
if c in self.__slavePoints2Count__:
self.__slavePoints2Count__[c] += 1
else:
self.__slavePoints2Count__[c] = 1
self.__isMasterStraight__ = 0
num = 0
for v in self.__masterPoints2Count__:
if (v + 1) in self.__masterPoints2Count__ and (v + 1) < DouDiZhuActionElement.str_to_rank["2"]:
num += 1
if num == len(self.__masterPoints2Count__) - 1 and len(self.__masterPoints2Count__) != 1:
self.__isMasterStraight__ = 1
self.__maxMasterPoint__ = -1
self.__minMasterPoint__ = 100
for c in self.__masterPoints2Count__:
if self.__maxMasterPoint__ < c:
self.__maxMasterPoint__ = c
if self.__minMasterPoint__ > c:
self.__minMasterPoint__ = c
########################
## action 2 pattern ####
########################
# is cheat?
if len(self.__masterCards__) == 1 \
and len(self.__slaveCards__) == 0 \
and self.__masterCards__[0] == DouDiZhuActionElement.str_to_rank["x"]:
self.__pattern__ = AllPatterns["i_cheat"]
# is roblord
elif len(self.__masterCards__) == 1 \
and len(self.__slaveCards__) == 0 \
and self.__masterCards__[0] == DouDiZhuActionElement.str_to_rank["b"]:
self.__pattern__ = AllPatterns["i_bid"]
# is twoKings
elif len(self.__masterCards__) == 2 \
and len(self.__masterPoints2Count__) == 2 \
and len(self.__slaveCards__) == 0 \
and self.__masterCards__[0] in [DouDiZhuActionElement.str_to_rank["r"], DouDiZhuActionElement.str_to_rank["R"]] \
and self.__masterCards__[1] in [DouDiZhuActionElement.str_to_rank["r"], DouDiZhuActionElement.str_to_rank["R"]]:
self.__pattern__ = AllPatterns["x_rocket"]
else:
## process masterCards
masterPoints = self.__masterPoints2Count__
if len(masterPoints) > 0:
count = masterPoints[self.__masterCards__[0]]
for c in masterPoints:
if masterPoints[c] != count:
self.__pattern__ = AllPatterns["i_invalid"]
if self.__pattern__ == None:
pattern = "p_%d_%d_%d_%d_%d" % (len(self.__masterCards__), len(masterPoints), \
self.__isMasterStraight__, \
len(self.__slaveCards__), 0)
if pattern in AllPatterns:
self.__pattern__= AllPatterns[pattern]
else:
self.__pattern__ = AllPatterns["i_invalid"]
def __deepcopy__(self, memodict={}, newinstance = None):
return self.lookup(self.key)
############## read data ################
AllPatterns = dict()
AllActions = dict()
from roomai.doudizhu import doudizhu_action_data
from roomai.doudizhu import doudizhu_pattern_data
for line in doudizhu_pattern_data:
line = line.replace(" ", "").strip()
line = line.split("#")[0]
if len(line) == 0 or len(line[0].strip()) == 0:
continue
lines = line.split(",")
for i in range(1, len(lines)):
lines[i] = int(lines[i])
AllPatterns[lines[0]] = lines
for line in doudizhu_action_data:
line = line.replace(" ", "").strip()
lines = line.split("\t")
if lines[3] not in AllPatterns:
continue
m = [int(str1) for str1 in lines[1].split(",")]
s = []
if len(lines[2]) > 0:
s = [int(str1) for str1 in lines[2].split(",")]
action = DouDiZhuPokerAction(m, s)
if "b" in line:
b = 0
if action.key != lines[0] or action.pattern[0] != lines[3]:
raise ValueError("%s is wrong. The generated action has key(%s) and pattern(%s)"%(line, action.key,action.pattern[0]))
AllActions[action.key] = action<|fim▁end|>
| |
<|file_name|>mysqloffset.go<|end_file_name|><|fim▁begin|>package mysql
import (
"reflect"
"github.com/qiniu/log"
. "github.com/qiniu/logkit/reader/sql"
)
func (r *MysqlReader) updateStartTime(offsetKeyIndex int, scanArgs []interface{}) bool {
if r.timestampKeyInt {
timeOffset, ok := GetTimeIntFromArgs(offsetKeyIndex, scanArgs)
if ok && timeOffset > r.startTimeInt {
r.startTimeInt = timeOffset
r.timestampMux.Lock()
r.timeCacheMap = nil
r.timestampMux.Unlock()
return true
}
return false
}
timeData, ok := GetTimeFromArgs(offsetKeyIndex, scanArgs)
if ok && timeData.After(r.startTime) {
r.startTime = timeData
r.timestampMux.Lock()<|fim▁hole|> }
return false
}
func GetTimeStrFromArgs(offsetKeyIndex int, scanArgs []interface{}) (string, bool) {
if offsetKeyIndex < 0 || offsetKeyIndex > len(scanArgs) {
return "", false
}
v := scanArgs[offsetKeyIndex]
dpv := reflect.ValueOf(v)
if dpv.Kind() != reflect.Ptr {
log.Error("scanArgs not a pointer")
return "", false
}
if dpv.IsNil() {
log.Error("scanArgs is a nil pointer")
return "", false
}
dv := reflect.Indirect(dpv)
switch dv.Kind() {
case reflect.Interface:
data := dv.Interface()
switch data.(type) {
case []byte:
ret, _ := data.([]byte)
return string(ret), true
default:
log.Errorf("updateStartTimeStr failed as %v(%T) is not []byte", data, data)
}
default:
log.Errorf("updateStartTimeStr is not Interface but %v", dv.Kind())
}
return "", false
}
//用于更新时间戳,已经同样时间戳上那个数据点
func (r *MysqlReader) updateTimeCntFromData(v ReadInfo) {
if r.timestampKeyInt {
timeData, ok := GetTimeIntFromData(v.Data, r.timestampKey)
if !ok {
return
}
if timeData > r.startTimeInt {
r.startTimeInt = timeData
r.timestampMux.Lock()
r.timeCacheMap = map[string]string{v.Json: "1"}
r.timestampMux.Unlock()
} else if timeData == r.startTimeInt {
r.timestampMux.Lock()
if r.timeCacheMap == nil {
r.timeCacheMap = make(map[string]string)
}
r.timeCacheMap[v.Json] = "1"
r.timestampMux.Unlock()
}
return
}
timeData, ok := GetTimeFromData(v.Data, r.timestampKey)
if !ok {
return
}
if timeData.After(r.startTime) {
r.startTime = timeData
r.timestampMux.Lock()
r.timeCacheMap = map[string]string{v.Json: "1"}
r.timestampMux.Unlock()
} else if timeData.Equal(r.startTime) {
r.timestampMux.Lock()
if r.timeCacheMap == nil {
r.timeCacheMap = make(map[string]string)
}
r.timeCacheMap[v.Json] = "1"
r.timestampMux.Unlock()
}
return
}
func (r *MysqlReader) trimExistData(datas []ReadInfo) []ReadInfo {
if len(r.timestampKey) <= 0 || len(datas) < 1 {
return datas
}
datas, success := GetJson(datas)
if !success {
return datas
}
newdatas := make([]ReadInfo, 0, len(datas))
for _, v := range datas {
var compare int
var exist bool
if r.timestampKeyInt {
compare, exist = CompareWithStartTimeInt(v.Data, r.timestampKey, r.startTimeInt)
} else {
compare, exist = CompareWithStartTime(v.Data, r.timestampKey, r.startTime)
}
if !exist {
//如果出现了数据中没有时间的,实际上已经不合法了,那就获取
newdatas = append(newdatas, v)
continue
}
if compare == 1 {
//找到的数据都是比当前时间还要新的,选取
newdatas = append(newdatas, v)
continue
}
if compare == 0 {
r.timestampMux.RLock()
//判断map去重
if _, ok := r.timeCacheMap[v.Json]; !ok {
newdatas = append(newdatas, v)
}
r.timestampMux.RUnlock()
}
}
return newdatas
}<|fim▁end|>
|
r.timeCacheMap = nil
r.timestampMux.Unlock()
return true
|
<|file_name|>video_bench_ovl.py<|end_file_name|><|fim▁begin|>#! /bin/env python
import sys, time, os
import pymedia.muxer as muxer
import pymedia.video.vcodec as vcodec
import pymedia.audio.acodec as acodec
import pymedia.audio.sound as sound
if os.environ.has_key( 'PYCAR_DISPLAY' ) and os.environ[ 'PYCAR_DISPLAY' ]== 'directfb':
import pydfb as pygame
YV12= pygame.PF_YV12
else:
import pygame<|fim▁hole|>def videoDecodeBenchmark( inFile, opt ):
pygame.init()
pygame.display.set_mode( (800,600), 0 )
ovl= None
dm= muxer.Demuxer( inFile.split( '.' )[ -1 ] )
f= open( inFile, 'rb' )
s= f.read( 400000 )
r= dm.parse( s )
v= filter( lambda x: x[ 'type' ]== muxer.CODEC_TYPE_VIDEO, dm.streams )
if len( v )== 0:
raise 'There is no video stream in a file %s' % inFile
v_id= v[ 0 ][ 'index' ]
print 'Assume video stream at %d index: ' % v_id
a= filter( lambda x: x[ 'type' ]== muxer.CODEC_TYPE_AUDIO, dm.streams )
if len( a )== 0:
print 'There is no audio stream in a file %s. Ignoring audio.' % inFile
opt= 'noaudio'
else:
a_id= a[ 0 ][ 'index' ]
t= time.time()
vc= vcodec.Decoder( dm.streams[ v_id ] )
print dm.streams[ v_id ]
if opt!= 'noaudio':
ac= acodec.Decoder( dm.streams[ a_id ] )
resampler= None
frames= 0
q= []
while len( s )> 0:
for fr in r:
if fr[ 0 ]== v_id:
d= vc.decode( fr[ 1 ] )
if d and d.data:
frames+= 1
#ff= open( 'c:\\test', 'wb' )
#ff.write( d.data[ 0 ] )
#ff.close()
if not ovl:
ovl= pygame.Overlay( YV12, d.size )
q.append( d )
if len( q )> 4:
try:
ovl.set_data( q[0].data )
ovl.display()
except:
ovl.display(q[0].data)
del( q[0] )
elif opt!= 'noaudio' and fr[ 0 ]== a_id:
d= ac.decode( fr[ 1 ] )
if resampler== None:
if d and d.channels> 2:
resampler= sound.Resampler( (d.sample_rate,d.channels), (d.sample_rate,2) )
else:
data= resampler.resample( d.data )
s= f.read( 400000 )
r= dm.parse( s )
tt= time.time()- t
print '%d frames in %d secs( %.02f fps )' % ( frames, tt, float(frames)/tt )
ev= pygame.event.get()
for e in ev:
if e.type== pygame.KEYDOWN and e.key== pygame.K_ESCAPE:
s= ''
break
if __name__== '__main__':
if len( sys.argv )< 2 or len( sys.argv )> 3:
print "Usage: video_bench <in_file> [ noaudio ]"
else:
s= ''
if len( sys.argv )> 2:
if sys.argv[ 2 ] not in ( 'noaudio' ):
print "Option %s not recognized. Should be 'noaudio'. Ignored..." % sys.argv[ 2 ]
else:
s= sys.argv[ 2 ]
videoDecodeBenchmark( sys.argv[ 1 ], s )<|fim▁end|>
|
YV12= pygame.YV12_OVERLAY
|
<|file_name|>0122_unusual_numbers.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
"""
NPR 2017-01-22
www.npr.org/2017/01/22/511046359/youve-got-to-comb-together-to-solve-this-one
The numbers 5,000, 8,000, and 9,000 share a property that only five integers altogether have.
Identify the property and the two other integers that have it.
"""
# The property is that they are supervocalic (one each of aeiou).
# This code will simply try to find the other such numbers.<|fim▁hole|> We also want it not to have a 'y'
'''
vowels = 'aeiou'
for vowel in vowels:
if w.lower().count(vowel) != 1:
return False
if 'y' in w.lower():
return False
return True
# Thanks to http://stackoverflow.com/a/19193721
def numToWords(num,join=True):
'''words = {} convert an integer number into words'''
units = ['','one','two','three','four','five','six','seven','eight','nine']
teens = ['','eleven','twelve','thirteen','fourteen','fifteen','sixteen', \
'seventeen','eighteen','nineteen']
tens = ['','ten','twenty','thirty','forty','fifty','sixty','seventy', \
'eighty','ninety']
thousands = ['','thousand','million','billion','trillion','quadrillion', \
'quintillion','sextillion','septillion','octillion', \
'nonillion','decillion','undecillion','duodecillion', \
'tredecillion','quattuordecillion','sexdecillion', \
'septendecillion','octodecillion','novemdecillion', \
'vigintillion']
words = []
if num==0: words.append('zero')
else:
numStr = '%d'%num
numStrLen = len(numStr)
groups = (numStrLen+2)/3
numStr = numStr.zfill(groups*3)
for i in range(0,groups*3,3):
h,t,u = int(numStr[i]),int(numStr[i+1]),int(numStr[i+2])
g = groups-(i/3+1)
if h>=1:
words.append(units[h])
words.append('hundred')
if t>1:
words.append(tens[t])
if u>=1: words.append(units[u])
elif t==1:
if u>=1: words.append(teens[u])
else: words.append(tens[t])
else:
if u>=1: words.append(units[u])
if (g>=1) and ((h+t+u)>0): words.append(thousands[g])
if join: return ' '.join(words)
return words
# Note that every integer greater than 100,000 has a repeated vowel
for i in range(100000):
word = numToWords(i)
if is_supervocalic(word):
print i, word<|fim▁end|>
|
def is_supervocalic(w):
'''
Determine if a word has one each of a, e, i, o, u
|
<|file_name|>DispersiveRamseyFringes.py<|end_file_name|><|fim▁begin|>from matplotlib import pyplot as plt, colorbar
from lib2.VNATimeResolvedDispersiveMeasurement2D import *
class DispersiveRamseyFringes(VNATimeResolvedDispersiveMeasurement2D):
def __init__(self, name, sample_name, **devs_aliases_map):
devs_aliases_map["q_z_awg"] = None
super().__init__(name, sample_name, devs_aliases_map)
self._measurement_result = \
DispersiveRamseyFringesResult(name, sample_name)
self._sequence_generator = IQPulseBuilder.build_dispersive_ramsey_sequences
def set_fixed_parameters(self, pulse_sequence_parameters, **dev_params):
super().set_fixed_parameters(pulse_sequence_parameters, **dev_params)
def set_swept_parameters(self, ramsey_delays, excitation_freqs):
q_if_frequency = self._q_awg.get_calibration() \
.get_radiation_parameters()["if_frequency"]
swept_pars = {"ramsey_delay": \
(self._output_pulse_sequence,
ramsey_delays),
"excitation_frequency":
(lambda x: self._exc_iqvg.set_frequency(x + q_if_frequency),<|fim▁hole|> self._pulse_sequence_parameters["ramsey_delay"] = ramsey_delay
super()._output_pulse_sequence()
class DispersiveRamseyFringesResult(VNATimeResolvedDispersiveMeasurement2DResult):
def _prepare_data_for_plot(self, data):
return data["excitation_frequency"] / 1e9, \
data["ramsey_delay"] / 1e3, \
data["data"]
def _annotate_axes(self, axes):
axes[0].set_ylabel("Ramsey delay [$\mu$s]")
axes[-2].set_ylabel("Ramsey delay [$\mu$s]")
axes[-1].set_xlabel("Excitation if_freq [GHz]")
axes[-2].set_xlabel("Excitation if_freq [GHz]")<|fim▁end|>
|
excitation_freqs)}
super().set_swept_parameters(**swept_pars)
def _output_pulse_sequence(self, ramsey_delay):
|
<|file_name|>pickCube3.js<|end_file_name|><|fim▁begin|>var elt;
var canvas;
var gl;
var program;
var NumVertices = 36;
var pointsArray = [];
var normalsArray = [];
var colorsArray = [];
var framebuffer;
var flag = true;
var color = new Uint8Array(4);
var vertices = [
vec4( -0.5, -0.5, 0.5, 1.0 ),
vec4( -0.5, 0.5, 0.5, 1.0 ),
vec4( 0.5, 0.5, 0.5, 1.0 ),
vec4( 0.5, -0.5, 0.5, 1.0 ),
vec4( -0.5, -0.5, -0.5, 1.0 ),
vec4( -0.5, 0.5, -0.5, 1.0 ),
vec4( 0.5, 0.5, -0.5, 1.0 ),
vec4( 0.5, -0.5, -0.5, 1.0 ),
];
var vertexColors = [
vec4( 0.0, 0.0, 0.0, 1.0 ), // black
vec4( 1.0, 0.0, 0.0, 1.0 ), // red
vec4( 1.0, 1.0, 0.0, 1.0 ), // yellow
vec4( 0.0, 1.0, 0.0, 1.0 ), // green
vec4( 0.0, 0.0, 1.0, 1.0 ), // blue
vec4( 1.0, 0.0, 1.0, 1.0 ), // magenta
vec4( 0.0, 1.0, 1.0, 1.0 ), // cyan
vec4( 1.0, 1.0, 1.0, 1.0 ), // white
];
var lightPosition = vec4(1.0, 1.0, 1.0, 0.0 );
var lightAmbient = vec4(0.2, 0.2, 0.2, 1.0 );
var lightDiffuse = vec4( 1.0, 1.0, 1.0, 1.0 );
var lightSpecular = vec4( 1.0, 1.0, 1.0, 1.0 );
//var materialAmbient = vec4( 1.0, 0.0, 1.0, 1.0 );
var materialAmbient = vec4( 1.0, 1.0, 1.0, 1.0 );
//var materialDiffuse = vec4( 1.0, 0.8, 0.0, 1.0);
var materialDiffuse = vec4( 0.5, 0.5, 0.5, 1.0);
var materialSpecular = vec4( 1.0, 0.8, 0.0, 1.0 );
var materialShininess = 10.0;
var ctm;
var ambientColor, diffuseColor, specularColor;
var modelView, projection;
var viewerPos;
var program;
var xAxis = 0;
var yAxis = 1;
var zAxis = 2;
var axis = xAxis;
var theta = [45.0, 45.0, 45.0];
var thetaLoc;
var Index = 0;
function quad(a, b, c, d) {
var t1 = subtract(vertices[b], vertices[a]);
var t2 = subtract(vertices[c], vertices[b]);
var normal = cross(t1, t2);
var normal = vec3(normal);
normal = normalize(normal);
pointsArray.push(vertices[a]);
normalsArray.push(normal);
colorsArray.push(vertexColors[a]);
pointsArray.push(vertices[b]);
normalsArray.push(normal);
colorsArray.push(vertexColors[a]);
pointsArray.push(vertices[c]);
normalsArray.push(normal);
colorsArray.push(vertexColors[a]);
pointsArray.push(vertices[a]);
normalsArray.push(normal);
colorsArray.push(vertexColors[a]);
pointsArray.push(vertices[c]);
normalsArray.push(normal);
colorsArray.push(vertexColors[a]);
pointsArray.push(vertices[d]);
normalsArray.push(normal);
colorsArray.push(vertexColors[a]);
}
function colorCube()
{
quad( 1, 0, 3, 2 );
quad( 2, 3, 7, 6 );
quad( 3, 0, 4, 7 );
quad( 6, 5, 1, 2 );
quad( 4, 5, 6, 7 );
quad( 5, 4, 0, 1 );
}
window.onload = function init() {
canvas = document.getElementById( "gl-canvas" );
var ctx = canvas.getContext("experimental-webgl", {preserveDrawingBuffer: true});
gl = WebGLUtils.setupWebGL( canvas );
if ( !gl ) { alert( "WebGL isn't available" ); }
elt = document.getElementById("test");
gl.viewport( 0, 0, canvas.width, canvas.height );
gl.clearColor( 0.5, 0.5, 0.5, 1.0 );
gl.enable(gl.CULL_FACE);
var texture = gl.createTexture();
gl.bindTexture( gl.TEXTURE_2D, texture );
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 512, 512, 0,
gl.RGBA, gl.UNSIGNED_BYTE, null);
gl.generateMipmap(gl.TEXTURE_2D);
// Allocate a frame buffer object
framebuffer = gl.createFramebuffer();
gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer);
// Attach color buffer
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
// check for completeness
//var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
//if(status != gl.FRAMEBUFFER_COMPLETE) alert('Frame Buffer Not Complete');
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
//
// Load shaders and initialize attribute buffers
//
program = initShaders( gl, "vertex-shader", "fragment-shader" );
gl.useProgram( program );
colorCube();
var cBuffer = gl.createBuffer();
gl.bindBuffer( gl.ARRAY_BUFFER, cBuffer );
gl.bufferData( gl.ARRAY_BUFFER, flatten(colorsArray), gl.STATIC_DRAW );
var vColor = gl.getAttribLocation( program, "vColor" );
gl.vertexAttribPointer( vColor, 4, gl.FLOAT, false, 0, 0 );<|fim▁hole|> gl.enableVertexAttribArray( vColor );
var nBuffer = gl.createBuffer();
gl.bindBuffer( gl.ARRAY_BUFFER, nBuffer );
gl.bufferData( gl.ARRAY_BUFFER, flatten(normalsArray), gl.STATIC_DRAW );
var vNormal = gl.getAttribLocation( program, "vNormal" );
gl.vertexAttribPointer( vNormal, 3, gl.FLOAT, false, 0, 0 );
gl.enableVertexAttribArray( vNormal );
var vBuffer = gl.createBuffer();
gl.bindBuffer( gl.ARRAY_BUFFER, vBuffer );
gl.bufferData( gl.ARRAY_BUFFER, flatten(pointsArray), gl.STATIC_DRAW );
var vPosition = gl.getAttribLocation(program, "vPosition");
gl.vertexAttribPointer(vPosition, 4, gl.FLOAT, false, 0, 0);
gl.enableVertexAttribArray(vPosition);
thetaLoc = gl.getUniformLocation(program, "theta");
viewerPos = vec3(0.0, 0.0, -20.0 );
projection = ortho(-1, 1, -1, 1, -100, 100);
ambientProduct = mult(lightAmbient, materialAmbient);
diffuseProduct = mult(lightDiffuse, materialDiffuse);
specularProduct = mult(lightSpecular, materialSpecular);
document.getElementById("ButtonX").onclick = function(){axis = xAxis;};
document.getElementById("ButtonY").onclick = function(){axis = yAxis;};
document.getElementById("ButtonZ").onclick = function(){axis = zAxis;};
document.getElementById("ButtonT").onclick = function(){flag = !flag};
gl.uniform4fv(gl.getUniformLocation(program, "ambientProduct"),
flatten(ambientProduct));
gl.uniform4fv(gl.getUniformLocation(program, "diffuseProduct"),
flatten(diffuseProduct) );
gl.uniform4fv(gl.getUniformLocation(program, "specularProduct"),
flatten(specularProduct) );
gl.uniform4fv(gl.getUniformLocation(program, "lightPosition"),
flatten(lightPosition) );
gl.uniform1f(gl.getUniformLocation(program,
"shininess"),materialShininess);
gl.uniformMatrix4fv( gl.getUniformLocation(program, "projectionMatrix"),
false, flatten(projection));
canvas.addEventListener("mousedown", function(event){
gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
gl.clear( gl.COLOR_BUFFER_BIT);
gl.uniform3fv(thetaLoc, theta);
for(var i=0; i<6; i++) {
gl.uniform1i(gl.getUniformLocation(program, "i"), i+1);
gl.drawArrays( gl.TRIANGLES, 6*i, 6 );
}
var x = event.clientX;
var y = canvas.height -event.clientY;
gl.readPixels(x, y, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, color);
if(color[0]==255)
if(color[1]==255) elt.innerHTML = "<div> cyan </div>";
else if(color[2]==255) elt.innerHTML = "<div> magenta </div>";
else elt.innerHTML = "<div> red </div>";
else if(color[1]==255)
if(color[2]==255) elt.innerHTML = "<div> blue </div>";
else elt.innerHTML = "<div> yellow </div>";
else if(color[2]==255) elt.innerHTML = "<div> green </div>";
else elt.innerHTML = "<div> background </div>";
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
gl.uniform1i(gl.getUniformLocation(program, "i"), 0);
gl.clear( gl.COLOR_BUFFER_BIT );
gl.uniform3fv(thetaLoc, theta);
gl.drawArrays(gl.TRIANGLES, 0, 36);
});
render();
}
var render = function(){
gl.clear( gl.COLOR_BUFFER_BIT );
if(flag) theta[axis] += 2.0;
modelView = mat4();
modelView = mult(modelView, rotate(theta[xAxis], [1, 0, 0] ));
modelView = mult(modelView, rotate(theta[yAxis], [0, 1, 0] ));
modelView = mult(modelView, rotate(theta[zAxis], [0, 0, 1] ));
gl.uniformMatrix4fv( gl.getUniformLocation(program,
"modelViewMatrix"), false, flatten(modelView) );
gl.uniform1i(gl.getUniformLocation(program, "i"),0);
gl.drawArrays( gl.TRIANGLES, 0, 36 );
requestAnimFrame(render);
}<|fim▁end|>
| |
<|file_name|>xmlrpc.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Implement PyPiXmlRpc Service.
See: http://wiki.python.org/moin/PyPiXmlRpc
"""
import logging
from pyramid_xmlrpc import XMLRPCView
from pyshop.models import DBSession, Package, Release, ReleaseFile
from pyshop.helpers import pypi
log = logging.getLogger(__name__)
# XXX not tested.
class PyPI(XMLRPCView):
def list_packages(self):
"""
Retrieve a list of the package names registered with the package index.
Returns a list of name strings.
"""
session = DBSession()
names = [p.name for p in Package.all(session, order_by=Package.name)]
return names
def package_releases(self, package_name, show_hidden=False):
"""
Retrieve a list of the releases registered for the given package_name.
Returns a list with all version strings if show_hidden is True or
only the non-hidden ones otherwise."""
session = DBSession()
package = Package.by_name(session, package_name)
return [rel.version for rel in package.sorted_releases]
def package_roles(self, package_name):
"""
Retrieve a list of users and their attributes roles for a given
package_name. Role is either 'Maintainer' or 'Owner'.
"""
session = DBSession()
package = Package.by_name(session, package_name)
owners = [('Owner', o.name) for o in package.owners]
maintainers = [('Maintainer', o.name) for o in package.maintainers]
return owners + maintainers
def user_packages(self, user):
"""
Retrieve a list of [role_name, package_name] for a given username.
Role is either 'Maintainer' or 'Owner'.
"""
session = DBSession()
owned = Package.by_owner(session, user)
maintained = Package.by_maintainer(session, user)
owned = [('Owner', p.name) for p in owned]
maintained = [('Maintainer', p.name) for p in maintained]
return owned + maintained
def release_downloads(self, package_name, version):
"""
Retrieve a list of files and download count for a given package and
release version.
"""
session = DBSession()
release_files = ReleaseFile.by_release(session, package_name, version)
if release_files:
release_files = [(f.release.package.name,
f.filename) for f in release_files]
return release_files
def release_urls(self, package_name, version):
"""
Retrieve a list of download URLs for the given package release.
Returns a list of dicts with the following keys:
url
packagetype ('sdist', 'bdist', etc)
filename
size
md5_digest<|fim▁hole|> downloads
has_sig
python_version (required version, or 'source', or 'any')
comment_text
"""
session = DBSession()
release_files = ReleaseFile.by_release(session, package_name, version)
return [{'url': f.url,
'packagetype': f.package_type,
'filename': f.filename,
'size': f.size,
'md5_digest': f.md5_digest,
'downloads': f.downloads,
'has_sig': f.has_sig,
'comment_text': f.comment_text,
'python_version': f.python_version
}
for f in release_files]
def release_data(self, package_name, version):
"""
Retrieve metadata describing a specific package release.
Returns a dict with keys for:
name
version
stable_version
author
author_email
maintainer
maintainer_email
home_page
license
summary
description
keywords
platform
download_url
classifiers (list of classifier strings)
requires
requires_dist
provides
provides_dist
requires_external
requires_python
obsoletes
obsoletes_dist
project_url
docs_url (URL of the packages.python.org docs
if they've been supplied)
If the release does not exist, an empty dictionary is returned.
"""
session = DBSession()
release = Release.by_version(session, package_name, version)
if release:
result = {'name': release.package.name,
'version': release.version,
'stable_version': '',
'author': release.author.name,
'author_email': release.author.email,
'home_page': release.home_page,
'license': release.license,
'summary': release.summary,
'description': release.description,
'keywords': release.keywords,
'platform': release.platform,
'download_url': release.download_url,
'classifiers': [c.name for c in release.classifiers],
#'requires': '',
#'requires_dist': '',
#'provides': '',
#'provides_dist': '',
#'requires_external': '',
#'requires_python': '',
#'obsoletes': '',
#'obsoletes_dist': '',
'bugtrack_url': release.bugtrack_url,
'docs_url': release.docs_url,
}
if release.maintainer:
result.update({'maintainer': release.maintainer.name,
'maintainer_email': release.maintainer.email,
})
return dict([(key, val or '') for key, val in result.items()])
def search(self, spec, operator='and'):
"""
Search the package database using the indicated search spec.
The spec may include any of the keywords described in the above list
(except 'stable_version' and 'classifiers'),
for example: {'description': 'spam'} will search description fields.
Within the spec, a field's value can be a string or a list of strings
(the values within the list are combined with an OR),
for example: {'name': ['foo', 'bar']}.
Valid keys for the spec dict are listed here. Invalid keys are ignored:
name
version
author
author_email
maintainer
maintainer_email
home_page
license
summary
description
keywords
platform
download_url
Arguments for different fields are combined using either "and"
(the default) or "or".
Example: search({'name': 'foo', 'description': 'bar'}, 'or').
The results are returned as a list of dicts
{'name': package name,
'version': package release version,
'summary': package release summary}
"""
api = pypi.proxy
rv = []
# search in proxy
for k, v in spec.items():
rv += api.search({k: v}, True)
# search in local
session = DBSession()
release = Release.search(session, spec, operator)
rv += [{'name': r.package.name,
'version': r.version,
'summary': r.summary,
# hack https://mail.python.org/pipermail/catalog-sig/2012-October/004633.html
'_pypi_ordering':'',
} for r in release]
return rv
def browse(self, classifiers):
"""
Retrieve a list of (name, version) pairs of all releases classified
with all of the given classifiers. 'classifiers' must be a list of
Trove classifier strings.
changelog(since)
Retrieve a list of four-tuples (name, version, timestamp, action)
since the given timestamp. All timestamps are UTC values.
The argument is a UTC integer seconds since the epoch.
"""
session = DBSession()
release = Release.by_classifiers(session, classifiers)
rv = [(r.package.name, r.version) for r in release]
return rv<|fim▁end|>
| |
<|file_name|>cron-send-cpu-mem-stats.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python2
'''
Simple monitoring script to collect per process cpu percentage
and mem usage in bytes (vms or virt and rss)
usage:
cron-send-cpu-mem-stats process_name openshift.whatever.zabbix.key
or
cron-send-cpu-mem-stats 'something parameter more params' openshift.something.parameter.more.params
The script will attach .cpu and .mem.{vms|rss} to the end of the zabbix key name for the values
Future enhancement can be to add multiple instances, that would add pid to the key, but those
would have to be dynamic items in zabbix
'''
# vim: expandtab:tabstop=4:shiftwidth=4
# Disabling invalid-name because pylint doesn't like the naming conention we have.
# pylint: disable=invalid-name
import argparse
import psutil
# Reason: disable pylint import-error because our libs aren't loaded on jenkins.
# Status: temporary until we start testing in a container where our stuff is installed.
# pylint: disable=import-error
from openshift_tools.monitoring.metric_sender import MetricSender
def parse_args():
""" parse the args from the cli """
parser = argparse.ArgumentParser(description='CPU and Memory per process stats collector')
parser.add_argument('--debug', action='store_true', default=None, help='Debug?')
parser.add_argument('process_str', help='The process command line string to match')
parser.add_argument('zabbix_key_prefix', help='Prefix for the key that will be sent \
to zabbix with this data, will get a .cpu and .mem suffix')
return parser.parse_args()
def main():
""" Main function to run the check """
argz = parse_args()
proc_parts = argz.process_str.split()
zagg_data = {}
for proc in psutil.process_iter():
try:
if proc_parts[0] == proc.name():
proc.dict = proc.as_dict(['cmdline', 'memory_info'])
cmdline = proc.dict['cmdline']
if len(proc_parts) > 1 and len(cmdline) > 1:
part_count = len(proc_parts[1:])
# This call might be confusing, (I know I will be in 2 weeks) so quick explanation:
# if the process name matches above, it will check the rest of the strings<|fim▁hole|> if argz.debug:
print cmdline
cpu_percent = '{0:.2f}'.format(proc.cpu_percent(interval=0.5))
mem_vms = '{0}'.format(getattr(proc.dict['memory_info'], 'vms'))
mem_rss = '{0}'.format(getattr(proc.dict['memory_info'], 'rss'))
zagg_data = {'{0}.cpu'.format(argz.zabbix_key_prefix) : cpu_percent,
'{0}.mem.vms'.format(argz.zabbix_key_prefix) : mem_vms,
'{0}.mem.rss'.format(argz.zabbix_key_prefix) : mem_rss}
except psutil.NoSuchProcess:
pass
if argz.debug:
try:
print 'Process ({0}) is using {1} CPU and {2} {3} memory'.format(argz.process_str,
cpu_percent,
mem_vms,
mem_rss)
print 'Zagg will receive: {0}'.format(zagg_data)
except NameError as ex:
print 'No values: {0}'.format(ex)
if zagg_data:
ms = MetricSender(debug=argz.debug)
ms.add_metric(zagg_data)
ms.send_metrics()
if __name__ == '__main__':
main()<|fim▁end|>
|
# against the /proc/<pid>/cmdline contents, order shouldn't matter since all have to match
if len(set(proc_parts[1:]).intersection(set(cmdline[1:1+part_count]))) != part_count:
continue
|
<|file_name|>1234_1243_2134_2431_4213.py<|end_file_name|><|fim▁begin|><|fim▁hole|>import permstruct.dag
from permstruct import *
from permstruct.dag import taylor_dag
import sys
# -- Example from Kuszmaul paper -- #
# STATUS ================================================ >
task = '1234_1243_2134_2431_4213'
patts = [ Permutation([ int(c) for c in p ]) for p in task.split('_') ]
# patts = [Permutation([5,2,3,4,1]), Permutation([5,3,2,4,1]), Permutation([5,2,4,3,1]), Permutation([3,5,1,4,2]), Permutation([4,2,5,1,3]), Permutation([3,5,1,6,2,4])]
struct(patts, size=6, perm_bound = 8, subpatts_len=4, subpatts_num=3)
# struct(patts, size = 4, verify_bound = 10, ask_verify_higher = True)<|fim▁end|>
|
from __future__ import print_function
from permuta import *
import permstruct
|
<|file_name|>environment.py<|end_file_name|><|fim▁begin|>import time
import uuid as uuid
from splinter.browser import Browser
from django.contrib.auth.models import User
from webparticipation.apps.ureporter.models import Ureporter
from webparticipation.apps.ureport_auth.models import PasswordReset
def before_all(context):
context.browser = Browser('chrome')
time.sleep(5)
def before_scenario(context, scenario):
email = '[email protected]'
username = 'user999999999'
password = 'password'
email1 = '[email protected]'
username1 = 'user999999991'
uid = uuid.uuid4()
uid1 = uuid.uuid4()
Ureporter.objects.create(uuid=uid,
user=User.objects.create_user(username=username, email=email, password=password))
Ureporter.objects.create(uuid=uid1,
user=User.objects.create_user(username=username1, email=email1, password=password))
def after_scenario(context, scenario):
User.objects.all().delete()
Ureporter.objects.all().delete()
PasswordReset.objects.all().delete()
def after_all(context):
context.browser.quit()
context.browser = None<|fim▁hole|><|fim▁end|>
|
context.server = None
|
<|file_name|>iconset-typicon-2.0.6.js<|end_file_name|><|fim▁begin|>/* ========================================================================
* Bootstrap: iconset-typicon-2.0.6.js by @recktoner
* https://victor-valencia.github.com/bootstrap-iconpicker
*
* Iconset: Typicons 2.0.6
* https://github.com/stephenhutchings/typicons.font
* ========================================================================
* Copyright 2013-2014 Victor Valencia Rico.
*
* 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.
* ======================================================================== */
;(function($){
$.iconset_typicon = {
iconClass: 'typcn',
iconClassFix: 'typcn-',
icons: [
'adjust-brightness',
'adjust-contrast',
'anchor-outline',
'anchor',
'archive',
'arrow-back-outline',
'arrow-back',
'arrow-down-outline',
'arrow-down-thick',
'arrow-down',
'arrow-forward-outline',
'arrow-forward',
'arrow-left-outline',
'arrow-left-thick',
'arrow-left',
'arrow-loop-outline',
'arrow-loop',
'arrow-maximise-outline',
'arrow-maximise',
'arrow-minimise-outline',
'arrow-minimise',
'arrow-move-outline',
'arrow-move',
'arrow-repeat-outline',
'arrow-repeat',
'arrow-right-outline',
'arrow-right-thick',
'arrow-right',
'arrow-shuffle',
'arrow-sorted-down',
'arrow-sorted-up',
'arrow-sync-outline',
'arrow-sync',
'arrow-unsorted',
'arrow-up-outline',
'arrow-up-thick',
'arrow-up',
'at',
'attachment-outline',
'attachment',
'backspace-outline',
'backspace',
'battery-charge',
'battery-full',
'battery-high',
'battery-low',
'battery-mid',
'beaker',
'beer',
'bell',
'book',
'bookmark',
'briefcase',
'brush',
'business-card',
'calculator',
'calendar-outline',
'calendar',
'camera-outline',
'camera',
'cancel-outline',
'cancel',
'chart-area-outline',
'chart-area',
'chart-bar-outline',
'chart-bar',
'chart-line-outline',
'chart-line',
'chart-pie-outline',
'chart-pie',
'chevron-left-outline',
'chevron-left',
'chevron-right-outline',
'chevron-right',
'clipboard',
'cloud-storage',
'cloud-storage-outline',
'code-outline',
'code',
'coffee',
'cog-outline',
'cog',
'compass',
'contacts',
'credit-card',
'css3',
'database',
'delete-outline',
'delete',
'device-desktop',
'device-laptop',
'device-phone',
'device-tablet',
'directions',
'divide-outline',
'divide',<|fim▁hole|> 'download-outline',
'download',
'dropbox',
'edit',
'eject-outline',
'eject',
'equals-outline',
'equals',
'export-outline',
'export',
'eye-outline',
'eye',
'feather',
'film',
'filter',
'flag-outline',
'flag',
'flash-outline',
'flash',
'flow-children',
'flow-merge',
'flow-parallel',
'flow-switch',
'folder-add',
'folder-delete',
'folder-open',
'folder',
'gift',
'globe-outline',
'globe',
'group-outline',
'group',
'headphones',
'heart-full-outline',
'heart-half-outline',
'heart-outline',
'heart',
'home-outline',
'home',
'html5',
'image-outline',
'image',
'infinity-outline',
'infinity',
'info-large-outline',
'info-large',
'info-outline',
'info',
'input-checked-outline',
'input-checked',
'key-outline',
'key',
'keyboard',
'leaf',
'lightbulb',
'link-outline',
'link',
'location-arrow-outline',
'location-arrow',
'location-outline',
'location',
'lock-closed-outline',
'lock-closed',
'lock-open-outline',
'lock-open',
'mail',
'map',
'media-eject-outline',
'media-eject',
'media-fast-forward-outline',
'media-fast-forward',
'media-pause-outline',
'media-pause',
'media-play-outline',
'media-play-reverse-outline',
'media-play-reverse',
'media-play',
'media-record-outline',
'media-record',
'media-rewind-outline',
'media-rewind',
'media-stop-outline',
'media-stop',
'message-typing',
'message',
'messages',
'microphone-outline',
'microphone',
'minus-outline',
'minus',
'mortar-board',
'news',
'notes-outline',
'notes',
'pen',
'pencil',
'phone-outline',
'phone',
'pi-outline',
'pi',
'pin-outline',
'pin',
'pipette',
'plane-outline',
'plane',
'plug',
'plus-outline',
'plus',
'point-of-interest-outline',
'point-of-interest',
'power-outline',
'power',
'printer',
'puzzle-outline',
'puzzle',
'radar-outline',
'radar',
'refresh-outline',
'refresh',
'rss-outline',
'rss',
'scissors-outline',
'scissors',
'shopping-bag',
'shopping-cart',
'social-at-circular',
'social-dribbble-circular',
'social-dribbble',
'social-facebook-circular',
'social-facebook',
'social-flickr-circular',
'social-flickr',
'social-github-circular',
'social-github',
'social-google-plus-circular',
'social-google-plus',
'social-instagram-circular',
'social-instagram',
'social-last-fm-circular',
'social-last-fm',
'social-linkedin-circular',
'social-linkedin',
'social-pinterest-circular',
'social-pinterest',
'social-skype-outline',
'social-skype',
'social-tumbler-circular',
'social-tumbler',
'social-twitter-circular',
'social-twitter',
'social-vimeo-circular',
'social-vimeo',
'social-youtube-circular',
'social-youtube',
'sort-alphabetically-outline',
'sort-alphabetically',
'sort-numerically-outline',
'sort-numerically',
'spanner-outline',
'spanner',
'spiral',
'star-full-outline',
'star-half-outline',
'star-half',
'star-outline',
'star',
'starburst-outline',
'starburst',
'stopwatch',
'support',
'tabs-outline',
'tag',
'tags',
'th-large-outline',
'th-large',
'th-list-outline',
'th-list',
'th-menu-outline',
'th-menu',
'th-small-outline',
'th-small',
'thermometer',
'thumbs-down',
'thumbs-ok',
'thumbs-up',
'tick-outline',
'tick',
'ticket',
'time',
'times-outline',
'times',
'trash',
'tree',
'upload-outline',
'upload',
'user-add-outline',
'user-add',
'user-delete-outline',
'user-delete',
'user-outline',
'user',
'vendor-android',
'vendor-apple',
'vendor-microsoft',
'video-outline',
'video',
'volume-down',
'volume-mute',
'volume-up',
'volume',
'warning-outline',
'warning',
'watch',
'waves-outline',
'waves',
'weather-cloudy',
'weather-downpour',
'weather-night',
'weather-partly-sunny',
'weather-shower',
'weather-snow',
'weather-stormy',
'weather-sunny',
'weather-windy-cloudy',
'weather-windy',
'wi-fi-outline',
'wi-fi',
'wine',
'world-outline',
'world',
'zoom-in-outline',
'zoom-in',
'zoom-out-outline',
'zoom-out',
'zoom-outline',
'zoom'
]};
})(jQuery);<|fim▁end|>
|
'document-add',
'document-delete',
'document-text',
'document',
|
<|file_name|>views.py<|end_file_name|><|fim▁begin|>"""Views fo the node settings page."""
# -*- coding: utf-8 -*-
from flask import request
import logging
from addons.dropbox.serializer import DropboxSerializer
from addons.base import generic_views
from website.project.decorators import must_have_addon, must_be_addon_authorizer
logger = logging.getLogger(__name__)
debug = logger.debug
SHORT_NAME = 'dropbox'
FULL_NAME = 'Dropbox'
<|fim▁hole|>)
dropbox_import_auth = generic_views.import_auth(
SHORT_NAME,
DropboxSerializer
)
@must_have_addon(SHORT_NAME, 'node')
@must_be_addon_authorizer(SHORT_NAME)
def dropbox_folder_list(node_addon, **kwargs):
""" Returns all the subsequent folders under the folder id passed.
"""
folder_id = request.args.get('folder_id')
return node_addon.get_folders(folder_id=folder_id)
dropbox_get_config = generic_views.get_config(
SHORT_NAME,
DropboxSerializer
)
def _set_folder(node_addon, folder, auth):
uid = folder['id']
node_addon.set_folder(uid, auth=auth)
node_addon.save()
dropbox_set_config = generic_views.set_config(
SHORT_NAME,
FULL_NAME,
DropboxSerializer,
_set_folder
)
dropbox_deauthorize_node = generic_views.deauthorize_node(
SHORT_NAME
)<|fim▁end|>
|
dropbox_account_list = generic_views.account_list(
SHORT_NAME,
DropboxSerializer
|
<|file_name|>index.ts<|end_file_name|><|fim▁begin|>// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import * as Terminal from './terminal';
import * as TerminalAPI from './restapi';<|fim▁hole|>
export * from './manager';
export { Terminal, TerminalAPI };<|fim▁end|>
| |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|>
|
from implementation import *
from implementations import *
|
<|file_name|>ExampleUnitTest.java<|end_file_name|><|fim▁begin|>package top.blue7.permission;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/<|fim▁hole|>public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
}<|fim▁end|>
| |
<|file_name|>color_test.go<|end_file_name|><|fim▁begin|>package color
import (
"bytes"
"fmt"
"os"
"testing"
"github.com/shiena/ansicolor"
)
// Testing colors is kinda different. First we test for given colors and their
// escaped formatted results. Next we create some visual tests to be tested.
// Each visual test includes the color name to be compared.
func TestColor(t *testing.T) {
rb := new(bytes.Buffer)
Output = rb
NoColor = false
testColors := []struct {
text string
code Attribute
}{
{text: "black", code: FgBlack},
{text: "red", code: FgRed},
{text: "green", code: FgGreen},
{text: "yellow", code: FgYellow},
{text: "blue", code: FgBlue},
{text: "magent", code: FgMagenta},
{text: "cyan", code: FgCyan},
{text: "white", code: FgWhite},
}
for _, c := range testColors {
New(c.code).Print(c.text)
line, _ := rb.ReadString('\n')
scannedLine := fmt.Sprintf("%q", line)
colored := fmt.Sprintf("\x1b[%dm%s\x1b[0m", c.code, c.text)
escapedForm := fmt.Sprintf("%q", colored)
fmt.Printf("%s\t: %s\n", c.text, line)
if scannedLine != escapedForm {
t.Errorf("Expecting %s, got '%s'\n", escapedForm, scannedLine)
}
}
}
func TestColorEquals(t *testing.T) {
fgblack1 := New(FgBlack)
fgblack2 := New(FgBlack)
bgblack := New(BgBlack)
fgbgblack := New(FgBlack, BgBlack)
fgblackbgred := New(FgBlack, BgRed)
fgred := New(FgRed)
bgred := New(BgRed)
if !fgblack1.Equals(fgblack2) {
t.Error("Two black colors are not equal")
}
if fgblack1.Equals(bgblack) {
t.Error("Fg and bg black colors are equal")
}
if fgblack1.Equals(fgbgblack) {
t.Error("Fg black equals fg/bg black color")
}
if fgblack1.Equals(fgred) {
t.Error("Fg black equals Fg red")
}
if fgblack1.Equals(bgred) {
t.Error("Fg black equals Bg red")
}
if fgblack1.Equals(fgblackbgred) {
t.Error("Fg black equals fg black bg red")
}
}
func TestNoColor(t *testing.T) {<|fim▁hole|> text string
code Attribute
}{
{text: "black", code: FgBlack},
{text: "red", code: FgRed},
{text: "green", code: FgGreen},
{text: "yellow", code: FgYellow},
{text: "blue", code: FgBlue},
{text: "magent", code: FgMagenta},
{text: "cyan", code: FgCyan},
{text: "white", code: FgWhite},
}
for _, c := range testColors {
p := New(c.code)
p.DisableColor()
p.Print(c.text)
line, _ := rb.ReadString('\n')
if line != c.text {
t.Errorf("Expecting %s, got '%s'\n", c.text, line)
}
}
// global check
NoColor = true
defer func() {
NoColor = false
}()
for _, c := range testColors {
p := New(c.code)
p.Print(c.text)
line, _ := rb.ReadString('\n')
if line != c.text {
t.Errorf("Expecting %s, got '%s'\n", c.text, line)
}
}
}
func TestColorVisual(t *testing.T) {
// First Visual Test
fmt.Println("")
Output = ansicolor.NewAnsiColorWriter(os.Stdout)
New(FgRed).Printf("red\t")
New(BgRed).Print(" ")
New(FgRed, Bold).Println(" red")
New(FgGreen).Printf("green\t")
New(BgGreen).Print(" ")
New(FgGreen, Bold).Println(" green")
New(FgYellow).Printf("yellow\t")
New(BgYellow).Print(" ")
New(FgYellow, Bold).Println(" yellow")
New(FgBlue).Printf("blue\t")
New(BgBlue).Print(" ")
New(FgBlue, Bold).Println(" blue")
New(FgMagenta).Printf("magenta\t")
New(BgMagenta).Print(" ")
New(FgMagenta, Bold).Println(" magenta")
New(FgCyan).Printf("cyan\t")
New(BgCyan).Print(" ")
New(FgCyan, Bold).Println(" cyan")
New(FgWhite).Printf("white\t")
New(BgWhite).Print(" ")
New(FgWhite, Bold).Println(" white")
fmt.Println("")
// Second Visual test
Black("black")
Red("red")
Green("green")
Yellow("yellow")
Blue("blue")
Magenta("magenta")
Cyan("cyan")
White("white")
// Third visual test
fmt.Println()
Set(FgBlue)
fmt.Println("is this blue?")
Unset()
Set(FgMagenta)
fmt.Println("and this magenta?")
Unset()
// Fourth Visual test
fmt.Println()
blue := New(FgBlue).PrintlnFunc()
blue("blue text with custom print func")
red := New(FgRed).PrintfFunc()
red("red text with a printf func: %d\n", 123)
put := New(FgYellow).SprintFunc()
warn := New(FgRed).SprintFunc()
fmt.Fprintf(Output, "this is a %s and this is %s.\n", put("warning"), warn("error"))
info := New(FgWhite, BgGreen).SprintFunc()
fmt.Fprintf(Output, "this %s rocks!\n", info("package"))
// Fifth Visual Test
fmt.Println()
fmt.Fprintln(Output, BlackString("black"))
fmt.Fprintln(Output, RedString("red"))
fmt.Fprintln(Output, GreenString("green"))
fmt.Fprintln(Output, YellowString("yellow"))
fmt.Fprintln(Output, BlueString("blue"))
fmt.Fprintln(Output, MagentaString("magenta"))
fmt.Fprintln(Output, CyanString("cyan"))
fmt.Fprintln(Output, WhiteString("white"))
}<|fim▁end|>
|
rb := new(bytes.Buffer)
Output = rb
testColors := []struct {
|
<|file_name|>sitemaps.js<|end_file_name|><|fim▁begin|>// 3rd
const Router = require('koa-router')
const compress = require('koa-compress')
const nunjucks = require('nunjucks')
// 1st
const cache = require('../cache')
const router = new Router()
////////////////////////////////////////////////////////////<|fim▁hole|>
router.get('/sitemap.txt', async ctx => {
ctx.redirect('/sitemap.xml')
})
router.get('/sitemaps/:idx.txt', compress(), async ctx => {
const idx = parseInt(ctx.params.idx) || 0
const chunk = cache.get('sitemaps')[idx]
ctx.assert(chunk, 404)
ctx.type = 'text/plain'
ctx.body = chunk.join('\n')
})
////////////////////////////////////////////////////////////
// { count: <sitemaps total> }
const indexTemplate = nunjucks.compile(
`
<?xml version="1.0" encoding="UTF-8"?>
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
{% for i in range(0, count) %}
<sitemap>
<loc>https://www.roleplayerguild.com/sitemaps/{{ i }}.txt</loc>
</sitemap>
{% endfor %}
</sitemapindex>
`.trim()
)
router.get('/sitemap.xml', async ctx => {
var chunks = cache.get('sitemaps')
ctx.type = 'text/xml'
ctx.body = indexTemplate.render({ count: chunks.length })
})
////////////////////////////////////////////////////////////
module.exports = router<|fim▁end|>
| |
<|file_name|>GLFWEngine.cpp<|end_file_name|><|fim▁begin|>// GLFW Engine.
// -----------------------------------------------------------------------------
// Copyright (C) 2011, ZEUS project (See authors)
//
// This program is open source and distributed under the New BSD License. See
// license for more detail.
// -----------------------------------------------------------------------------
#include <Core/GLFWEngine.h>
#include <Devices/GLFWKeyboard.h>
#include <Devices/GLFWMouse.h>
#include <Display/Camera.h>
#include <Display/GLFWWindow.h>
#include <Math/Vector.h>
#include <GL/glfw.h>
#include <stdlib.h>
using namespace ZEUS::Display;
using namespace ZEUS::Devices;
using namespace ZEUS::Math;
namespace ZEUS {
namespace Core {
GLFWEngine::GLFWEngine()
: IEngine() {
if (!glfwInit()) exit(EXIT_FAILURE);
Vector<2, unsigned int> res(800, 600);<|fim▁hole|>
IKeyboard::Add<GLFWKeyboard>();
IMouse::Add<GLFWMouse>();
}
GLFWEngine::~GLFWEngine(){
glfwTerminate();
}
GLFWEngine* GLFWEngine::CreateEngine(){
GLFWEngine* tmp = new GLFWEngine();
engine = tmp;
return tmp;
}
void GLFWEngine::Initialize(){
glfwSetTime(0.0);
}
double GLFWEngine::GetImplTime(){
return glfwGetTime();
}
}
}<|fim▁end|>
|
window = new Display::GLFWWindow(res);
|
<|file_name|>AwayActionTest.java<|end_file_name|><|fim▁begin|>/***************************************************************************
* (C) Copyright 2003-2015 - Stendhal *
***************************************************************************
***************************************************************************
* *
* 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. *
* *
***************************************************************************/
package games.stendhal.server.actions.chat;
import static org.junit.Assert.assertEquals;
import games.stendhal.server.entity.player.Player;
import marauroa.common.game.RPAction;
import org.junit.Test;
import utilities.PlayerTestHelper;
public class AwayActionTest {
/**
* Tests for playerIsNull.
*/
@Test(expected = NullPointerException.class)
public void testPlayerIsNull() {
final RPAction action = new RPAction();
action.put("type", "away");
final AwayAction aa = new AwayAction();
aa.onAction(null, action);
}
/**
* Tests for onAction.
*/
@Test
public void testOnAction() {
final Player bob = PlayerTestHelper.createPlayer("bob");
final RPAction action = new RPAction();
action.put("type", "away");
final AwayAction aa = new AwayAction();
aa.onAction(bob, action);
assertEquals(null, bob.getAwayMessage());
action.put("message", "bla");
aa.onAction(bob, action);
assertEquals("\"bla\"", bob.getAwayMessage());
}
/**
* Tests for onInvalidAction.
*/
@Test
public void testOnInvalidAction() {
final Player bob = PlayerTestHelper.createPlayer("bob");
bob.clearEvents();<|fim▁hole|> action.put("message", "bla");
final AwayAction aa = new AwayAction();
aa.onAction(bob, action);
assertEquals(null, bob.getAwayMessage());
}
}<|fim▁end|>
|
final RPAction action = new RPAction();
action.put("type", "bla");
|
<|file_name|>settings.py<|end_file_name|><|fim▁begin|>from django.conf import settings
<|fim▁hole|> return getattr(settings, 'SESSIONPROFILE_BACKEND', 'sessionprofile.backends.db')<|fim▁end|>
|
def _get_backend():
|
<|file_name|>comp-3174.component.spec.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 { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { Comp3174Component } from './comp-3174.component';
describe('Comp3174Component', () => {
let component: Comp3174Component;
let fixture: ComponentFixture<Comp3174Component>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ Comp3174Component ]
})
.compileComponents();
}));<|fim▁hole|> fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});<|fim▁end|>
|
beforeEach(() => {
fixture = TestBed.createComponent(Comp3174Component);
component = fixture.componentInstance;
|
<|file_name|>hash-table.cc<|end_file_name|><|fim▁begin|>// Copyright 2012 Cloudera Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "exec/hash-table.inline.h"
#include "codegen/codegen-anyval.h"
#include "codegen/llvm-codegen.h"
#include "exprs/expr.h"
#include "exprs/expr-context.h"
#include "exprs/slot-ref.h"
#include "runtime/buffered-block-mgr.h"
#include "runtime/mem-tracker.h"
#include "runtime/raw-value.h"
#include "runtime/runtime-state.h"
#include "runtime/string-value.inline.h"
#include "util/debug-util.h"
#include "util/impalad-metrics.h"
#include "common/names.h"
using namespace impala;
using namespace llvm;
DEFINE_bool(enable_quadratic_probing, true, "Enable quadratic probing hash table");
const char* HashTableCtx::LLVM_CLASS_NAME = "class.impala::HashTableCtx";
// Page sizes used only for BE test. For non-testing, we use the io buffer size.
static const int64_t TEST_PAGE_SIZE = 8 * 1024 * 1024;
// Random primes to multiply the seed with.
static uint32_t SEED_PRIMES[] = {
1, // First seed must be 1, level 0 is used by other operators in the fragment.
1431655781,
1183186591,
622729787,
472882027,
338294347,
275604541,
41161739,
29999999,
27475109,
611603,
16313357,
11380003,
21261403,
33393119,
101,
71043403
};
// Put a non-zero constant in the result location for NULL.
// We don't want(NULL, 1) to hash to the same as (0, 1).
// This needs to be as big as the biggest primitive type since the bytes
// get copied directly.
// TODO find a better approach, since primitives like CHAR(N) can be up to 128 bytes
static int64_t NULL_VALUE[] = { HashUtil::FNV_SEED, HashUtil::FNV_SEED,
HashUtil::FNV_SEED, HashUtil::FNV_SEED,
HashUtil::FNV_SEED, HashUtil::FNV_SEED,
HashUtil::FNV_SEED, HashUtil::FNV_SEED,
HashUtil::FNV_SEED, HashUtil::FNV_SEED,
HashUtil::FNV_SEED, HashUtil::FNV_SEED,
HashUtil::FNV_SEED, HashUtil::FNV_SEED,
HashUtil::FNV_SEED, HashUtil::FNV_SEED };
// The first NUM_SMALL_BLOCKS of nodes_ are made of blocks less than the IO size (of 8MB)
// to reduce the memory footprint of small queries. In particular, we always first use a
// 64KB and a 512KB block before starting using IO-sized blocks.
static const int64_t INITIAL_DATA_PAGE_SIZES[] = { 64 * 1024, 512 * 1024 };
static const int NUM_SMALL_DATA_PAGES = sizeof(INITIAL_DATA_PAGE_SIZES) / sizeof(int64_t);
HashTableCtx::HashTableCtx(const vector<ExprContext*>& build_expr_ctxs,
const vector<ExprContext*>& probe_expr_ctxs, bool stores_nulls, bool finds_nulls,
int32_t initial_seed, int max_levels, int num_build_tuples)
: build_expr_ctxs_(build_expr_ctxs),
probe_expr_ctxs_(probe_expr_ctxs),
stores_nulls_(stores_nulls),
finds_nulls_(finds_nulls),
level_(0),
row_(reinterpret_cast<TupleRow*>(malloc(sizeof(Tuple*) * num_build_tuples))) {
// Compute the layout and buffer size to store the evaluated expr results
DCHECK_EQ(build_expr_ctxs_.size(), probe_expr_ctxs_.size());
DCHECK(!build_expr_ctxs_.empty());
results_buffer_size_ = Expr::ComputeResultsLayout(build_expr_ctxs_,
&expr_values_buffer_offsets_, &var_result_begin_);
expr_values_buffer_ = new uint8_t[results_buffer_size_];
memset(expr_values_buffer_, 0, sizeof(uint8_t) * results_buffer_size_);
expr_value_null_bits_ = new uint8_t[build_expr_ctxs.size()];
// Populate the seeds to use for all the levels. TODO: revisit how we generate these.
DCHECK_GE(max_levels, 0);
DCHECK_LT(max_levels, sizeof(SEED_PRIMES) / sizeof(SEED_PRIMES[0]));
DCHECK_NE(initial_seed, 0);
seeds_.resize(max_levels + 1);
seeds_[0] = initial_seed;
for (int i = 1; i <= max_levels; ++i) {
seeds_[i] = seeds_[i - 1] * SEED_PRIMES[i];
}
}
void HashTableCtx::Close() {
// TODO: use tr1::array?
DCHECK(expr_values_buffer_ != NULL);
delete[] expr_values_buffer_;
expr_values_buffer_ = NULL;
DCHECK(expr_value_null_bits_ != NULL);
delete[] expr_value_null_bits_;
expr_value_null_bits_ = NULL;
free(row_);
row_ = NULL;
}
bool HashTableCtx::EvalRow(TupleRow* row, const vector<ExprContext*>& ctxs) {
bool has_null = false;
for (int i = 0; i < ctxs.size(); ++i) {
void* loc = expr_values_buffer_ + expr_values_buffer_offsets_[i];
void* val = ctxs[i]->GetValue(row);
if (val == NULL) {
// If the table doesn't store nulls, no reason to keep evaluating
if (!stores_nulls_) return true;
expr_value_null_bits_[i] = true;
val = reinterpret_cast<void*>(&NULL_VALUE);
has_null = true;
} else {
expr_value_null_bits_[i] = false;
}
DCHECK_LE(build_expr_ctxs_[i]->root()->type().GetSlotSize(),
sizeof(NULL_VALUE));
RawValue::Write(val, loc, build_expr_ctxs_[i]->root()->type(), NULL);
}
return has_null;
}
uint32_t HashTableCtx::HashVariableLenRow() {
uint32_t hash = seeds_[level_];
// Hash the non-var length portions (if there are any)
if (var_result_begin_ != 0) {
hash = Hash(expr_values_buffer_, var_result_begin_, hash);
}
for (int i = 0; i < build_expr_ctxs_.size(); ++i) {
// non-string and null slots are already part of expr_values_buffer
if (build_expr_ctxs_[i]->root()->type().type != TYPE_STRING &&
build_expr_ctxs_[i]->root()->type().type != TYPE_VARCHAR) continue;
void* loc = expr_values_buffer_ + expr_values_buffer_offsets_[i];
if (expr_value_null_bits_[i]) {
// Hash the null random seed values at 'loc'
hash = Hash(loc, sizeof(StringValue), hash);
} else {
// Hash the string
// TODO: when using CRC hash on empty string, this only swaps bytes.
StringValue* str = reinterpret_cast<StringValue*>(loc);
hash = Hash(str->ptr, str->len, hash);
}
}
return hash;
}
bool HashTableCtx::Equals(TupleRow* build_row) {
for (int i = 0; i < build_expr_ctxs_.size(); ++i) {
void* val = build_expr_ctxs_[i]->GetValue(build_row);
if (val == NULL) {
if (!stores_nulls_) return false;
if (!expr_value_null_bits_[i]) return false;
continue;
} else {
if (expr_value_null_bits_[i]) return false;
}
void* loc = expr_values_buffer_ + expr_values_buffer_offsets_[i];
if (!RawValue::Eq(loc, val, build_expr_ctxs_[i]->root()->type())) {
return false;
}
}
return true;
}
const double HashTable::MAX_FILL_FACTOR = 0.75f;
HashTable::HashTable(RuntimeState* state, BufferedBlockMgr::Client* client,
int num_build_tuples, BufferedTupleStream* stream, int64_t max_num_buckets,
int64_t num_buckets)
: state_(state),
block_mgr_client_(client),
tuple_stream_(stream),
data_page_pool_(NULL),
stores_tuples_(num_build_tuples == 1),
quadratic_probing_(FLAGS_enable_quadratic_probing),
total_data_page_size_(0),
next_node_(NULL),
node_remaining_current_page_(0),
num_duplicate_nodes_(0),
max_num_buckets_(max_num_buckets),
buckets_(NULL),
num_buckets_(num_buckets),
num_filled_buckets_(0),
num_buckets_with_duplicates_(0),
num_build_tuples_(num_build_tuples),
has_matches_(false),
num_probes_(0), num_failed_probes_(0), travel_length_(0), num_hash_collisions_(0),
num_resizes_(0) {
DCHECK_EQ((num_buckets & (num_buckets-1)), 0) << "num_buckets must be a power of 2";
DCHECK_GT(num_buckets, 0) << "num_buckets must be larger than 0";
DCHECK(stores_tuples_ || stream != NULL);
}
HashTable::HashTable(MemPool* pool, bool quadratic_probing, int num_buckets)
: state_(NULL),
block_mgr_client_(NULL),
tuple_stream_(NULL),
data_page_pool_(pool),
stores_tuples_(true),
quadratic_probing_(quadratic_probing),
total_data_page_size_(0),
next_node_(NULL),
node_remaining_current_page_(0),
num_duplicate_nodes_(0),
max_num_buckets_(-1),
buckets_(NULL),
num_buckets_(num_buckets),
num_filled_buckets_(0),
num_buckets_with_duplicates_(0),
num_build_tuples_(1),
has_matches_(false),
num_probes_(0), num_failed_probes_(0), travel_length_(0), num_hash_collisions_(0),
num_resizes_(0) {
DCHECK_EQ((num_buckets & (num_buckets-1)), 0) << "num_buckets must be a power of 2";
DCHECK_GT(num_buckets, 0) << "num_buckets must be larger than 0";
bool ret = Init();
DCHECK(ret);
}
bool HashTable::Init() {
int64_t buckets_byte_size = num_buckets_ * sizeof(Bucket);
if (block_mgr_client_ != NULL &&
!state_->block_mgr()->ConsumeMemory(block_mgr_client_, buckets_byte_size)) {
num_buckets_ = 0;
return false;
}
buckets_ = reinterpret_cast<Bucket*>(malloc(buckets_byte_size));
memset(buckets_, 0, buckets_byte_size);
return GrowNodeArray();
}
void HashTable::Close() {
// Print statistics only for the large or heavily used hash tables.
// TODO: Tweak these numbers/conditions, or print them always?
const int64_t LARGE_HT = 128 * 1024;
const int64_t HEAVILY_USED = 1024 * 1024;
// TODO: These statistics should go to the runtime profile as well.
if ((num_buckets_ > LARGE_HT) || (num_probes_ > HEAVILY_USED)) VLOG(2) << PrintStats();
for (int i = 0; i < data_pages_.size(); ++i) {
data_pages_[i]->Delete();
}
if (ImpaladMetrics::HASH_TABLE_TOTAL_BYTES != NULL) {
ImpaladMetrics::HASH_TABLE_TOTAL_BYTES->Increment(-total_data_page_size_);
}
data_pages_.clear();
if (buckets_ != NULL) free(buckets_);
if (block_mgr_client_ != NULL) {
state_->block_mgr()->ReleaseMemory(block_mgr_client_,
num_buckets_ * sizeof(Bucket));
}
}
int64_t HashTable::CurrentMemSize() const {
return num_buckets_ * sizeof(Bucket) + num_duplicate_nodes_ * sizeof(DuplicateNode);
}
bool HashTable::CheckAndResize(uint64_t buckets_to_fill, HashTableCtx* ht_ctx) {
uint64_t shift = 0;
while (num_filled_buckets_ + buckets_to_fill >
(num_buckets_ << shift) * MAX_FILL_FACTOR) {
// TODO: next prime instead of double?
++shift;
}
if (shift > 0) return ResizeBuckets(num_buckets_ << shift, ht_ctx);
return true;
}
bool HashTable::ResizeBuckets(int64_t num_buckets, HashTableCtx* ht_ctx) {
DCHECK_EQ((num_buckets & (num_buckets-1)), 0)
<< "num_buckets=" << num_buckets << " must be a power of 2";
DCHECK_GT(num_buckets, num_filled_buckets_) << "Cannot shrink the hash table to "
"smaller number of buckets than the number of filled buckets.";
VLOG(2) << "Resizing hash table from "
<< num_buckets_ << " to " << num_buckets << " buckets.";
if (max_num_buckets_ != -1 && num_buckets > max_num_buckets_) return false;
++num_resizes_;
// All memory that can grow proportional to the input should come from the block mgrs
// mem tracker.
// Note that while we copying over the contents of the old hash table, we need to have
// allocated both the old and the new hash table. Once we finish, we return the memory
// of the old hash table.
int64_t old_size = num_buckets_ * sizeof(Bucket);
int64_t new_size = num_buckets * sizeof(Bucket);
if (block_mgr_client_ != NULL &&
!state_->block_mgr()->ConsumeMemory(block_mgr_client_, new_size)) {
return false;
}
Bucket* new_buckets = reinterpret_cast<Bucket*>(malloc(new_size));
DCHECK(new_buckets != NULL);
memset(new_buckets, 0, new_size);
// Walk the old table and copy all the filled buckets to the new (resized) table.
// We do not have to do anything with the duplicate nodes. This operation is expected
// to succeed.
for (HashTable::Iterator iter = Begin(ht_ctx); !iter.AtEnd();
NextFilledBucket(&iter.bucket_idx_, &iter.node_)) {
Bucket* bucket_to_copy = &buckets_[iter.bucket_idx_];
bool found = false;
int64_t bucket_idx = Probe(new_buckets, num_buckets, NULL, bucket_to_copy->hash,
&found);
DCHECK(!found);
DCHECK_NE(bucket_idx, Iterator::BUCKET_NOT_FOUND) << " Probe failed even though "
" there are free buckets. " << num_buckets << " " << num_filled_buckets_;
Bucket* dst_bucket = &new_buckets[bucket_idx];
*dst_bucket = *bucket_to_copy;
}
num_buckets_ = num_buckets;
free(buckets_);
buckets_ = new_buckets;
// TODO: Remove this check, i.e. block_mgr_client_ should always be != NULL,
// see IMPALA-1656.
if (block_mgr_client_ != NULL) {
state_->block_mgr()->ReleaseMemory(block_mgr_client_, old_size);
}
return true;
}
bool HashTable::GrowNodeArray() {
int64_t page_size = 0;
if (block_mgr_client_ != NULL) {
page_size = state_->block_mgr()->max_block_size();;
if (data_pages_.size() < NUM_SMALL_DATA_PAGES) {
page_size = min(page_size, INITIAL_DATA_PAGE_SIZES[data_pages_.size()]);
}
BufferedBlockMgr::Block* block = NULL;
Status status = state_->block_mgr()->GetNewBlock(
block_mgr_client_, NULL, &block, page_size);
DCHECK(status.ok() || block == NULL);
if (block == NULL) return false;
data_pages_.push_back(block);
next_node_ = block->Allocate<DuplicateNode>(page_size);
ImpaladMetrics::HASH_TABLE_TOTAL_BYTES->Increment(page_size);
} else {
// Only used for testing.
DCHECK(data_page_pool_ != NULL);
page_size = TEST_PAGE_SIZE;
next_node_ = reinterpret_cast<DuplicateNode*>(data_page_pool_->Allocate(page_size));
if (data_page_pool_->mem_tracker()->LimitExceeded()) return false;
DCHECK(next_node_ != NULL);
}
node_remaining_current_page_ = page_size / sizeof(DuplicateNode);
total_data_page_size_ += page_size;
return true;
}
void HashTable::DebugStringTuple(stringstream& ss, HtData& htdata,
const RowDescriptor* desc) {
if (stores_tuples_) {
ss << "(" << htdata.tuple << ")";
} else {
ss << "(" << htdata.idx.block() << ", " << htdata.idx.idx()
<< ", " << htdata.idx.offset() << ")";
}
if (desc != NULL) {
Tuple* row[num_build_tuples_];
ss << " " << PrintRow(GetRow(htdata, reinterpret_cast<TupleRow*>(row)), *desc);
}
}
string HashTable::DebugString(bool skip_empty, bool show_match,
const RowDescriptor* desc) {
stringstream ss;
ss << endl;
for (int i = 0; i < num_buckets_; ++i) {
if (skip_empty && !buckets_[i].filled) continue;
ss << i << ": ";
if (show_match) {
if (buckets_[i].matched) {
ss << " [M]";
} else {
ss << " [U]";
}
}
if (buckets_[i].hasDuplicates) {
DuplicateNode* node = buckets_[i].bucketData.duplicates;
bool first = true;
ss << " [D] ";
while (node != NULL) {
if (!first) ss << ",";
DebugStringTuple(ss, node->htdata, desc);
node = node->next;
first = false;
}
} else {
ss << " [B] ";
if (buckets_[i].filled) {
DebugStringTuple(ss, buckets_[i].bucketData.htdata, desc);
} else {
ss << " - ";
}
}
ss << endl;
}
return ss.str();
}
string HashTable::PrintStats() const {
double curr_fill_factor = (double)num_filled_buckets_/(double)num_buckets_;
double avg_travel = (double)travel_length_/(double)num_probes_;
double avg_collisions = (double)num_hash_collisions_/(double)num_filled_buckets_;
stringstream ss;
ss << "Buckets: " << num_buckets_ << " " << num_filled_buckets_ << " "
<< curr_fill_factor << endl;
ss << "Duplicates: " << num_buckets_with_duplicates_ << " buckets "
<< num_duplicate_nodes_ << " nodes" << endl;
ss << "Probes: " << num_probes_ << endl;
ss << "FailedProbes: " << num_failed_probes_ << endl;
ss << "Travel: " << travel_length_ << " " << avg_travel << endl;
ss << "HashCollisions: " << num_hash_collisions_ << " " << avg_collisions << endl;
ss << "Resizes: " << num_resizes_ << endl;
return ss.str();
}
// Helper function to store a value into the results buffer if the expr
// evaluated to NULL. We don't want (NULL, 1) to hash to the same as (0,1) so
// we'll pick a more random value.
static void CodegenAssignNullValue(LlvmCodeGen* codegen,
LlvmCodeGen::LlvmBuilder* builder, Value* dst, const ColumnType& type) {
int64_t fvn_seed = HashUtil::FNV_SEED;
if (type.type == TYPE_STRING || type.type == TYPE_VARCHAR) {
Value* dst_ptr = builder->CreateStructGEP(dst, 0, "string_ptr");
Value* dst_len = builder->CreateStructGEP(dst, 1, "string_len");
Value* null_len = codegen->GetIntConstant(TYPE_INT, fvn_seed);
Value* null_ptr = builder->CreateIntToPtr(null_len, codegen->ptr_type());
builder->CreateStore(null_ptr, dst_ptr);
builder->CreateStore(null_len, dst_len);
} else {
Value* null_value = NULL;
// Get a type specific representation of fvn_seed
switch (type.type) {
case TYPE_BOOLEAN:
// In results, booleans are stored as 1 byte
dst = builder->CreateBitCast(dst, codegen->ptr_type());
null_value = codegen->GetIntConstant(TYPE_TINYINT, fvn_seed);
break;
case TYPE_TINYINT:
case TYPE_SMALLINT:
case TYPE_INT:
case TYPE_BIGINT:
null_value = codegen->GetIntConstant(type.type, fvn_seed);
break;
case TYPE_FLOAT: {
// Don't care about the value, just the bit pattern
float fvn_seed_float = *reinterpret_cast<float*>(&fvn_seed);
null_value = ConstantFP::get(codegen->context(), APFloat(fvn_seed_float));
break;
}
case TYPE_DOUBLE: {
// Don't care about the value, just the bit pattern
double fvn_seed_double = *reinterpret_cast<double*>(&fvn_seed);
null_value = ConstantFP::get(codegen->context(), APFloat(fvn_seed_double));
break;
}
default:
DCHECK(false);
}
builder->CreateStore(null_value, dst);
}
}
// Codegen for evaluating a tuple row over either build_expr_ctxs_ or probe_expr_ctxs_.
// For the case where we are joining on a single int, the IR looks like
// define i1 @EvalBuildRow(%"class.impala::HashTableCtx"* %this_ptr,
// %"class.impala::TupleRow"* %row) #20 {
// entry:
// %result = call i64 @GetSlotRef1(%"class.impala::ExprContext"* inttoptr
// (i64 67971664 to %"class.impala::ExprContext"*),
// %"class.impala::TupleRow"* %row)
// %is_null = trunc i64 %result to i1
// %0 = zext i1 %is_null to i8
// store i8 %0, i8* inttoptr (i64 95753144 to i8*)
// br i1 %is_null, label %null, label %not_null
//
// null: ; preds = %entry
// store i32 -2128831035, i32* inttoptr (i64 95753128 to i32*)
// br label %continue
//
// not_null: ; preds = %entry
// %1 = ashr i64 %result, 32
// %2 = trunc i64 %1 to i32
// store i32 %2, i32* inttoptr (i64 95753128 to i32*)
// br label %continue
//
// continue: ; preds = %not_null, %null
// ret i1 true
// }
// For each expr, we create 3 code blocks. The null, not null and continue blocks.
// Both the null and not null branch into the continue block. The continue block
// becomes the start of the next block for codegen (either the next expr or just the
// end of the function).
Function* HashTableCtx::CodegenEvalRow(RuntimeState* state, bool build) {
// TODO: CodegenAssignNullValue() can't handle TYPE_TIMESTAMP or TYPE_DECIMAL yet
const vector<ExprContext*>& ctxs = build ? build_expr_ctxs_ : probe_expr_ctxs_;
for (int i = 0; i < ctxs.size(); ++i) {
PrimitiveType type = ctxs[i]->root()->type().type;
if (type == TYPE_TIMESTAMP || type == TYPE_DECIMAL || type == TYPE_CHAR) return NULL;
}
LlvmCodeGen* codegen;
if (!state->GetCodegen(&codegen).ok()) return NULL;
// Get types to generate function prototype
Type* tuple_row_type = codegen->GetType(TupleRow::LLVM_CLASS_NAME);
DCHECK(tuple_row_type != NULL);
PointerType* tuple_row_ptr_type = PointerType::get(tuple_row_type, 0);
Type* this_type = codegen->GetType(HashTableCtx::LLVM_CLASS_NAME);
DCHECK(this_type != NULL);
PointerType* this_ptr_type = PointerType::get(this_type, 0);
LlvmCodeGen::FnPrototype prototype(codegen, build ? "EvalBuildRow" : "EvalProbeRow",
codegen->GetType(TYPE_BOOLEAN));
prototype.AddArgument(LlvmCodeGen::NamedVariable("this_ptr", this_ptr_type));
prototype.AddArgument(LlvmCodeGen::NamedVariable("row", tuple_row_ptr_type));
LLVMContext& context = codegen->context();
LlvmCodeGen::LlvmBuilder builder(context);
Value* args[2];
Function* fn = prototype.GeneratePrototype(&builder, args);
Value* row = args[1];
Value* has_null = codegen->false_value();
for (int i = 0; i < ctxs.size(); ++i) {
// TODO: refactor this to somewhere else? This is not hash table specific except for
// the null handling bit and would be used for anyone that needs to materialize a
// vector of exprs
// Convert result buffer to llvm ptr type
void* loc = expr_values_buffer_ + expr_values_buffer_offsets_[i];
Value* llvm_loc = codegen->CastPtrToLlvmPtr(
codegen->GetPtrType(ctxs[i]->root()->type()), loc);
BasicBlock* null_block = BasicBlock::Create(context, "null", fn);
BasicBlock* not_null_block = BasicBlock::Create(context, "not_null", fn);
BasicBlock* continue_block = BasicBlock::Create(context, "continue", fn);
// Call expr
Function* expr_fn;
Status status = ctxs[i]->root()->GetCodegendComputeFn(state, &expr_fn);
if (!status.ok()) {
VLOG_QUERY << "Problem with CodegenEvalRow: " << status.GetDetail();
fn->eraseFromParent(); // deletes function
return NULL;
}
Value* ctx_arg = codegen->CastPtrToLlvmPtr(
codegen->GetPtrType(ExprContext::LLVM_CLASS_NAME), ctxs[i]);
Value* expr_fn_args[] = { ctx_arg, row };
CodegenAnyVal result = CodegenAnyVal::CreateCallWrapped(
codegen, &builder, ctxs[i]->root()->type(), expr_fn, expr_fn_args, "result");
Value* is_null = result.GetIsNull();
// Set null-byte result
Value* null_byte = builder.CreateZExt(is_null, codegen->GetType(TYPE_TINYINT));
uint8_t* null_byte_loc = &expr_value_null_bits_[i];
Value* llvm_null_byte_loc =
codegen->CastPtrToLlvmPtr(codegen->ptr_type(), null_byte_loc);
builder.CreateStore(null_byte, llvm_null_byte_loc);
builder.CreateCondBr(is_null, null_block, not_null_block);
// Null block
builder.SetInsertPoint(null_block);
if (!stores_nulls_) {
// hash table doesn't store nulls, no reason to keep evaluating exprs
builder.CreateRet(codegen->true_value());
} else {
CodegenAssignNullValue(codegen, &builder, llvm_loc, ctxs[i]->root()->type());
builder.CreateBr(continue_block);
}
<|fim▁hole|> builder.CreateBr(continue_block);
// Continue block
builder.SetInsertPoint(continue_block);
if (stores_nulls_) {
// Update has_null
PHINode* is_null_phi = builder.CreatePHI(codegen->boolean_type(), 2, "is_null_phi");
is_null_phi->addIncoming(codegen->true_value(), null_block);
is_null_phi->addIncoming(codegen->false_value(), not_null_block);
has_null = builder.CreateOr(has_null, is_null_phi, "has_null");
}
}
builder.CreateRet(has_null);
return codegen->FinalizeFunction(fn);
}
// Codegen for hashing the current row. In the case with both string and non-string data
// (group by int_col, string_col), the IR looks like:
// define i32 @HashCurrentRow(%"class.impala::HashTableCtx"* %this_ptr) #20 {
// entry:
// %seed = call i32 @GetHashSeed(%"class.impala::HashTableCtx"* %this_ptr)
// %0 = call i32 @CrcHash16(i8* inttoptr (i64 119151296 to i8*), i32 16, i32 %seed)
// %1 = load i8* inttoptr (i64 119943721 to i8*)
// %2 = icmp ne i8 %1, 0
// br i1 %2, label %null, label %not_null
//
// null: ; preds = %entry
// %3 = call i32 @CrcHash161(i8* inttoptr (i64 119151312 to i8*), i32 16, i32 %0)
// br label %continue
//
// not_null: ; preds = %entry
// %4 = load i8** getelementptr inbounds (%"struct.impala::StringValue"* inttoptr
// (i64 119151312 to %"struct.impala::StringValue"*), i32 0, i32 0)
// %5 = load i32* getelementptr inbounds (%"struct.impala::StringValue"* inttoptr
// (i64 119151312 to %"struct.impala::StringValue"*), i32 0, i32 1)
// %6 = call i32 @IrCrcHash(i8* %4, i32 %5, i32 %0)
// br label %continue
//
// continue: ; preds = %not_null, %null
// %7 = phi i32 [ %6, %not_null ], [ %3, %null ]
// call void @set_hash(%"class.impala::HashTableCtx"* %this_ptr, i32 %7)
// ret i32 %7
// }
Function* HashTableCtx::CodegenHashCurrentRow(RuntimeState* state, bool use_murmur) {
for (int i = 0; i < build_expr_ctxs_.size(); ++i) {
// Disable codegen for CHAR
if (build_expr_ctxs_[i]->root()->type().type == TYPE_CHAR) return NULL;
}
LlvmCodeGen* codegen;
if (!state->GetCodegen(&codegen).ok()) return NULL;
// Get types to generate function prototype
Type* this_type = codegen->GetType(HashTableCtx::LLVM_CLASS_NAME);
DCHECK(this_type != NULL);
PointerType* this_ptr_type = PointerType::get(this_type, 0);
LlvmCodeGen::FnPrototype prototype(codegen,
(use_murmur ? "MurmurHashCurrentRow" : "HashCurrentRow"),
codegen->GetType(TYPE_INT));
prototype.AddArgument(LlvmCodeGen::NamedVariable("this_ptr", this_ptr_type));
LLVMContext& context = codegen->context();
LlvmCodeGen::LlvmBuilder builder(context);
Value* this_arg;
Function* fn = prototype.GeneratePrototype(&builder, &this_arg);
// Call GetHashSeed() to get seeds_[level_]
Function* get_hash_seed_fn = codegen->GetFunction(IRFunction::HASH_TABLE_GET_HASH_SEED);
Value* seed = builder.CreateCall(get_hash_seed_fn, this_arg, "seed");
Value* hash_result = seed;
Value* data = codegen->CastPtrToLlvmPtr(codegen->ptr_type(), expr_values_buffer_);
if (var_result_begin_ == -1) {
// No variable length slots, just hash what is in 'expr_values_buffer_'
if (results_buffer_size_ > 0) {
Function* hash_fn = use_murmur ?
codegen->GetMurmurHashFunction(results_buffer_size_) :
codegen->GetHashFunction(results_buffer_size_);
Value* len = codegen->GetIntConstant(TYPE_INT, results_buffer_size_);
hash_result = builder.CreateCall3(hash_fn, data, len, hash_result, "hash");
}
} else {
if (var_result_begin_ > 0) {
Function* hash_fn = use_murmur ?
codegen->GetMurmurHashFunction(var_result_begin_) :
codegen->GetHashFunction(var_result_begin_);
Value* len = codegen->GetIntConstant(TYPE_INT, var_result_begin_);
hash_result = builder.CreateCall3(hash_fn, data, len, hash_result, "hash");
}
// Hash string slots
for (int i = 0; i < build_expr_ctxs_.size(); ++i) {
if (build_expr_ctxs_[i]->root()->type().type != TYPE_STRING
&& build_expr_ctxs_[i]->root()->type().type != TYPE_VARCHAR) continue;
BasicBlock* null_block = NULL;
BasicBlock* not_null_block = NULL;
BasicBlock* continue_block = NULL;
Value* str_null_result = NULL;
void* loc = expr_values_buffer_ + expr_values_buffer_offsets_[i];
// If the hash table stores nulls, we need to check if the stringval
// evaluated to NULL
if (stores_nulls_) {
null_block = BasicBlock::Create(context, "null", fn);
not_null_block = BasicBlock::Create(context, "not_null", fn);
continue_block = BasicBlock::Create(context, "continue", fn);
uint8_t* null_byte_loc = &expr_value_null_bits_[i];
Value* llvm_null_byte_loc =
codegen->CastPtrToLlvmPtr(codegen->ptr_type(), null_byte_loc);
Value* null_byte = builder.CreateLoad(llvm_null_byte_loc, "null_byte");
Value* is_null = builder.CreateICmpNE(null_byte,
codegen->GetIntConstant(TYPE_TINYINT, 0), "is_null");
builder.CreateCondBr(is_null, null_block, not_null_block);
// For null, we just want to call the hash function on the portion of
// the data
builder.SetInsertPoint(null_block);
Function* null_hash_fn = use_murmur ?
codegen->GetMurmurHashFunction(sizeof(StringValue)) :
codegen->GetHashFunction(sizeof(StringValue));
Value* llvm_loc = codegen->CastPtrToLlvmPtr(codegen->ptr_type(), loc);
Value* len = codegen->GetIntConstant(TYPE_INT, sizeof(StringValue));
str_null_result =
builder.CreateCall3(null_hash_fn, llvm_loc, len, hash_result, "str_null");
builder.CreateBr(continue_block);
builder.SetInsertPoint(not_null_block);
}
// Convert expr_values_buffer_ loc to llvm value
Value* str_val = codegen->CastPtrToLlvmPtr(codegen->GetPtrType(TYPE_STRING), loc);
Value* ptr = builder.CreateStructGEP(str_val, 0);
Value* len = builder.CreateStructGEP(str_val, 1);
ptr = builder.CreateLoad(ptr, "ptr");
len = builder.CreateLoad(len, "len");
// Call hash(ptr, len, hash_result);
Function* general_hash_fn = use_murmur ? codegen->GetMurmurHashFunction() :
codegen->GetHashFunction();
Value* string_hash_result =
builder.CreateCall3(general_hash_fn, ptr, len, hash_result, "string_hash");
if (stores_nulls_) {
builder.CreateBr(continue_block);
builder.SetInsertPoint(continue_block);
// Use phi node to reconcile that we could have come from the string-null
// path and string not null paths.
PHINode* phi_node = builder.CreatePHI(codegen->GetType(TYPE_INT), 2, "hash_phi");
phi_node->addIncoming(string_hash_result, not_null_block);
phi_node->addIncoming(str_null_result, null_block);
hash_result = phi_node;
} else {
hash_result = string_hash_result;
}
}
}
builder.CreateRet(hash_result);
return codegen->FinalizeFunction(fn);
}
// Codegen for HashTableCtx::Equals. For a hash table with two exprs (string,int),
// the IR looks like:
//
// define i1 @Equals(%"class.impala::HashTableCtx"* %this_ptr,
// %"class.impala::TupleRow"* %row) {
// entry:
// %result = call i64 @GetSlotRef(%"class.impala::ExprContext"* inttoptr
// (i64 146381856 to %"class.impala::ExprContext"*),
// %"class.impala::TupleRow"* %row)
// %0 = trunc i64 %result to i1
// br i1 %0, label %null, label %not_null
//
// false_block: ; preds = %not_null2, %null1, %not_null, %null
// ret i1 false
//
// null: ; preds = %entry
// br i1 false, label %continue, label %false_block
//
// not_null: ; preds = %entry
// %1 = load i32* inttoptr (i64 104774368 to i32*)
// %2 = ashr i64 %result, 32
// %3 = trunc i64 %2 to i32
// %cmp_raw = icmp eq i32 %3, %1
// br i1 %cmp_raw, label %continue, label %false_block
//
// continue: ; preds = %not_null, %null
// %result4 = call { i64, i8* } @GetSlotRef1(
// %"class.impala::ExprContext"* inttoptr
// (i64 146381696 to %"class.impala::ExprContext"*),
// %"class.impala::TupleRow"* %row)
// %4 = extractvalue { i64, i8* } %result4, 0
// %5 = trunc i64 %4 to i1
// br i1 %5, label %null1, label %not_null2
//
// null1: ; preds = %continue
// br i1 false, label %continue3, label %false_block
//
// not_null2: ; preds = %continue
// %6 = extractvalue { i64, i8* } %result4, 0
// %7 = ashr i64 %6, 32
// %8 = trunc i64 %7 to i32
// %result5 = extractvalue { i64, i8* } %result4, 1
// %cmp_raw6 = call i1 @_Z11StringValEQPciPKN6impala11StringValueE(
// i8* %result5, i32 %8, %"struct.impala::StringValue"* inttoptr
// (i64 104774384 to %"struct.impala::StringValue"*))
// br i1 %cmp_raw6, label %continue3, label %false_block
//
// continue3: ; preds = %not_null2, %null1
// ret i1 true
// }
Function* HashTableCtx::CodegenEquals(RuntimeState* state) {
for (int i = 0; i < build_expr_ctxs_.size(); ++i) {
// Disable codegen for CHAR
if (build_expr_ctxs_[i]->root()->type().type == TYPE_CHAR) return NULL;
}
LlvmCodeGen* codegen;
if (!state->GetCodegen(&codegen).ok()) return NULL;
// Get types to generate function prototype
Type* tuple_row_type = codegen->GetType(TupleRow::LLVM_CLASS_NAME);
DCHECK(tuple_row_type != NULL);
PointerType* tuple_row_ptr_type = PointerType::get(tuple_row_type, 0);
Type* this_type = codegen->GetType(HashTableCtx::LLVM_CLASS_NAME);
DCHECK(this_type != NULL);
PointerType* this_ptr_type = PointerType::get(this_type, 0);
LlvmCodeGen::FnPrototype prototype(codegen, "Equals", codegen->GetType(TYPE_BOOLEAN));
prototype.AddArgument(LlvmCodeGen::NamedVariable("this_ptr", this_ptr_type));
prototype.AddArgument(LlvmCodeGen::NamedVariable("row", tuple_row_ptr_type));
LLVMContext& context = codegen->context();
LlvmCodeGen::LlvmBuilder builder(context);
Value* args[2];
Function* fn = prototype.GeneratePrototype(&builder, args);
Value* row = args[1];
BasicBlock* false_block = BasicBlock::Create(context, "false_block", fn);
for (int i = 0; i < build_expr_ctxs_.size(); ++i) {
BasicBlock* null_block = BasicBlock::Create(context, "null", fn);
BasicBlock* not_null_block = BasicBlock::Create(context, "not_null", fn);
BasicBlock* continue_block = BasicBlock::Create(context, "continue", fn);
// call GetValue on build_exprs[i]
Function* expr_fn;
Status status = build_expr_ctxs_[i]->root()->GetCodegendComputeFn(state, &expr_fn);
if (!status.ok()) {
VLOG_QUERY << "Problem with CodegenEquals: " << status.GetDetail();
fn->eraseFromParent(); // deletes function
return NULL;
}
Value* ctx_arg = codegen->CastPtrToLlvmPtr(
codegen->GetPtrType(ExprContext::LLVM_CLASS_NAME), build_expr_ctxs_[i]);
Value* expr_fn_args[] = { ctx_arg, row };
CodegenAnyVal result = CodegenAnyVal::CreateCallWrapped(codegen, &builder,
build_expr_ctxs_[i]->root()->type(), expr_fn, expr_fn_args, "result");
Value* is_null = result.GetIsNull();
// Determine if probe is null (i.e. expr_value_null_bits_[i] == true). In
// the case where the hash table does not store nulls, this is always false.
Value* probe_is_null = codegen->false_value();
uint8_t* null_byte_loc = &expr_value_null_bits_[i];
if (stores_nulls_) {
Value* llvm_null_byte_loc =
codegen->CastPtrToLlvmPtr(codegen->ptr_type(), null_byte_loc);
Value* null_byte = builder.CreateLoad(llvm_null_byte_loc);
probe_is_null = builder.CreateICmpNE(null_byte,
codegen->GetIntConstant(TYPE_TINYINT, 0));
}
// Get llvm value for probe_val from 'expr_values_buffer_'
void* loc = expr_values_buffer_ + expr_values_buffer_offsets_[i];
Value* probe_val = codegen->CastPtrToLlvmPtr(
codegen->GetPtrType(build_expr_ctxs_[i]->root()->type()), loc);
// Branch for GetValue() returning NULL
builder.CreateCondBr(is_null, null_block, not_null_block);
// Null block
builder.SetInsertPoint(null_block);
builder.CreateCondBr(probe_is_null, continue_block, false_block);
// Not-null block
builder.SetInsertPoint(not_null_block);
if (stores_nulls_) {
BasicBlock* cmp_block = BasicBlock::Create(context, "cmp", fn);
// First need to compare that probe expr[i] is not null
builder.CreateCondBr(probe_is_null, false_block, cmp_block);
builder.SetInsertPoint(cmp_block);
}
// Check result == probe_val
Value* is_equal = result.EqToNativePtr(probe_val);
builder.CreateCondBr(is_equal, continue_block, false_block);
builder.SetInsertPoint(continue_block);
}
builder.CreateRet(codegen->true_value());
builder.SetInsertPoint(false_block);
builder.CreateRet(codegen->false_value());
return codegen->FinalizeFunction(fn);
}<|fim▁end|>
|
// Not null block
builder.SetInsertPoint(not_null_block);
result.ToNativePtr(llvm_loc);
|
<|file_name|>chute_storage.py<|end_file_name|><|fim▁begin|>from __future__ import print_function
###################################################################
# Copyright 2013-2017 All Rights Reserved
# Authors: The Paradrop Team
###################################################################
import sys
from paradrop.base import settings
from paradrop.lib.utils.pd_storage import PDStorage
from .chute import Chute
class ChuteStorage(PDStorage):
"""
ChuteStorage class.
This class holds onto the list of Chutes on this AP.
It implements the PDStorage class which allows us to save the chuteList to disk transparently
"""
# Class variable of chute list so all instances see the same thing
chuteList = dict()
def __init__(self, filename=None, save_timer=settings.FC_CHUTESTORAGE_SAVE_TIMER):
if(not filename):
filename = settings.FC_CHUTESTORAGE_FILE
PDStorage.__init__(self, filename, save_timer)
# Has it been loaded?
if(len(ChuteStorage.chuteList) == 0):
self.loadFromDisk()
def setAttr(self, attr):
"""Save our attr however we want (as class variable for all to see)"""
ChuteStorage.chuteList = attr
def getAttr(self):
"""Get our attr (as class variable for all to see)"""
return ChuteStorage.chuteList
def getChuteList(self):
"""Return a list of the names of the chutes we know of."""
return ChuteStorage.chuteList.values()
def getChute(self, name):
"""Returns a reference to a chute we have in our cache, or None."""
return ChuteStorage.chuteList.get(name, None)
def deleteChute(self, ch):
"""Deletes a chute from the chute storage. Can be sent the chute object, or the chute name."""
if (isinstance(ch, Chute)):
del ChuteStorage.chuteList[ch.name]
else:
del ChuteStorage.chuteList[ch]
self.saveToDisk()
def saveChute(self, ch):
"""
Saves the chute provided in our internal chuteList.
Also since we just received a new chute to hold onto we should save our ChuteList to disk.
"""
# check if there is a version of the chute already
oldch = ChuteStorage.chuteList.get(ch.name, None)
if(oldch != None):
# we should merge these chutes so we don't lose any data
oldch.__dict__.update(ch.__dict__)
# TODO: do we need to deal with cache separate? Old code we did
else:
ChuteStorage.chuteList[ch.name] = ch
self.saveToDisk()
def clearChuteStorage(self):
ChuteStorage.chuteList.clear()
self.saveToDisk()
#
# Functions we override to implement PDStorage Properly
#
def attrSaveable(self):
"""Returns True if we should save the ChuteList, otherwise False."""
return (type(ChuteStorage.chuteList) == dict)
@classmethod
def get_chute(cls, name):
return cls.chuteList[name]
if(__name__ == '__main__'): # pragma: no cover<|fim▁hole|> try:
if(sys.argv[1] != '-ls'):
usage()
except Exception as e:
print(e)
usage()
cs = ChuteStorage()
chutes = cs.getChuteList()
for ch in chutes:
print(ch)<|fim▁end|>
|
def usage():
print('Usage: $0 -ls : print chute storage details')
exit(0)
|
<|file_name|>_ip_groups_operations.py<|end_file_name|><|fim▁begin|># coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from typing import TYPE_CHECKING
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpRequest, HttpResponse
from azure.core.polling import LROPoller, NoPolling, PollingMethod
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.arm_polling import ARMPolling
from .. import models as _models
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
class IpGroupsOperations(object):
"""IpGroupsOperations operations.<|fim▁hole|> You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.network.v2020_11_01.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
def get(
self,
resource_group_name, # type: str
ip_groups_name, # type: str
expand=None, # type: Optional[str]
**kwargs # type: Any
):
# type: (...) -> "_models.IpGroup"
"""Gets the specified ipGroups.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param ip_groups_name: The name of the ipGroups.
:type ip_groups_name: str
:param expand: Expands resourceIds (of Firewalls/Network Security Groups etc.) back referenced
by the IpGroups resource.
:type expand: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: IpGroup, or the result of cls(response)
:rtype: ~azure.mgmt.network.v2020_11_01.models.IpGroup
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.IpGroup"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-11-01"
accept = "application/json"
# Construct URL
url = self.get.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'ipGroupsName': self._serialize.url("ip_groups_name", ip_groups_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
if expand is not None:
query_parameters['$expand'] = self._serialize.query("expand", expand, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.get(url, query_parameters, header_parameters)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize('IpGroup', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ipGroups/{ipGroupsName}'} # type: ignore
def _create_or_update_initial(
self,
resource_group_name, # type: str
ip_groups_name, # type: str
parameters, # type: "_models.IpGroup"
**kwargs # type: Any
):
# type: (...) -> "_models.IpGroup"
cls = kwargs.pop('cls', None) # type: ClsType["_models.IpGroup"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-11-01"
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
# Construct URL
url = self._create_or_update_initial.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'ipGroupsName': self._serialize.url("ip_groups_name", ip_groups_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {} # type: Dict[str, Any]
body_content = self._serialize.body(parameters, 'IpGroup')
body_content_kwargs['content'] = body_content
request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize('IpGroup', pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize('IpGroup', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ipGroups/{ipGroupsName}'} # type: ignore
def begin_create_or_update(
self,
resource_group_name, # type: str
ip_groups_name, # type: str
parameters, # type: "_models.IpGroup"
**kwargs # type: Any
):
# type: (...) -> LROPoller["_models.IpGroup"]
"""Creates or updates an ipGroups in a specified resource group.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param ip_groups_name: The name of the ipGroups.
:type ip_groups_name: str
:param parameters: Parameters supplied to the create or update IpGroups operation.
:type parameters: ~azure.mgmt.network.v2020_11_01.models.IpGroup
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling.
Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
:return: An instance of LROPoller that returns either IpGroup or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.network.v2020_11_01.models.IpGroup]
:raises ~azure.core.exceptions.HttpResponseError:
"""
polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod]
cls = kwargs.pop('cls', None) # type: ClsType["_models.IpGroup"]
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]
if cont_token is None:
raw_result = self._create_or_update_initial(
resource_group_name=resource_group_name,
ip_groups_name=ip_groups_name,
parameters=parameters,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
kwargs.pop('content_type', None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize('IpGroup', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'ipGroupsName': self._serialize.url("ip_groups_name", ip_groups_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = NoPolling()
else: polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ipGroups/{ipGroupsName}'} # type: ignore
def update_groups(
self,
resource_group_name, # type: str
ip_groups_name, # type: str
parameters, # type: "_models.TagsObject"
**kwargs # type: Any
):
# type: (...) -> "_models.IpGroup"
"""Updates tags of an IpGroups resource.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param ip_groups_name: The name of the ipGroups.
:type ip_groups_name: str
:param parameters: Parameters supplied to the update ipGroups operation.
:type parameters: ~azure.mgmt.network.v2020_11_01.models.TagsObject
:keyword callable cls: A custom type or function that will be passed the direct response
:return: IpGroup, or the result of cls(response)
:rtype: ~azure.mgmt.network.v2020_11_01.models.IpGroup
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.IpGroup"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-11-01"
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
# Construct URL
url = self.update_groups.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'ipGroupsName': self._serialize.url("ip_groups_name", ip_groups_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {} # type: Dict[str, Any]
body_content = self._serialize.body(parameters, 'TagsObject')
body_content_kwargs['content'] = body_content
request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize('IpGroup', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
update_groups.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ipGroups/{ipGroupsName}'} # type: ignore
def _delete_initial(
self,
resource_group_name, # type: str
ip_groups_name, # type: str
**kwargs # type: Any
):
# type: (...) -> None
cls = kwargs.pop('cls', None) # type: ClsType[None]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-11-01"
accept = "application/json"
# Construct URL
url = self._delete_initial.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'ipGroupsName': self._serialize.url("ip_groups_name", ip_groups_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.delete(url, query_parameters, header_parameters)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ipGroups/{ipGroupsName}'} # type: ignore
def begin_delete(
self,
resource_group_name, # type: str
ip_groups_name, # type: str
**kwargs # type: Any
):
# type: (...) -> LROPoller[None]
"""Deletes the specified ipGroups.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param ip_groups_name: The name of the ipGroups.
:type ip_groups_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be ARMPolling.
Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
:return: An instance of LROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod]
cls = kwargs.pop('cls', None) # type: ClsType[None]
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]
if cont_token is None:
raw_result = self._delete_initial(
resource_group_name=resource_group_name,
ip_groups_name=ip_groups_name,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
kwargs.pop('content_type', None)
def get_long_running_output(pipeline_response):
if cls:
return cls(pipeline_response, None, {})
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'ipGroupsName': self._serialize.url("ip_groups_name", ip_groups_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = NoPolling()
else: polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ipGroups/{ipGroupsName}'} # type: ignore
def list_by_resource_group(
self,
resource_group_name, # type: str
**kwargs # type: Any
):
# type: (...) -> Iterable["_models.IpGroupListResult"]
"""Gets all IpGroups in a resource group.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either IpGroupListResult or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.network.v2020_11_01.models.IpGroupListResult]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.IpGroupListResult"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-11-01"
accept = "application/json"
def prepare_request(next_link=None):
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
if not next_link:
# Construct URL
url = self.list_by_resource_group.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
request = self._client.get(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {} # type: Dict[str, Any]
request = self._client.get(url, query_parameters, header_parameters)
return request
def extract_data(pipeline_response):
deserialized = self._deserialize('IpGroupListResult', pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
error = self._deserialize.failsafe_deserialize(_models.Error, response)
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(
get_next, extract_data
)
list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ipGroups'} # type: ignore
def list(
self,
**kwargs # type: Any
):
# type: (...) -> Iterable["_models.IpGroupListResult"]
"""Gets all IpGroups in a subscription.
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either IpGroupListResult or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.network.v2020_11_01.models.IpGroupListResult]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.IpGroupListResult"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-11-01"
accept = "application/json"
def prepare_request(next_link=None):
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
if not next_link:
# Construct URL
url = self.list.metadata['url'] # type: ignore
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
request = self._client.get(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {} # type: Dict[str, Any]
request = self._client.get(url, query_parameters, header_parameters)
return request
def extract_data(pipeline_response):
deserialized = self._deserialize('IpGroupListResult', pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
error = self._deserialize.failsafe_deserialize(_models.Error, response)
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(
get_next, extract_data
)
list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Network/ipGroups'} # type: ignore<|fim▁end|>
| |
<|file_name|>cd_hit.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
"""Application controller for CD-HIT v3.1.1"""
import shutil
from os import remove
from cogent.app.parameters import ValuedParameter
from cogent.app.util import CommandLineApplication, ResultPath,\
get_tmp_filename
from cogent.core.moltype import RNA, DNA, PROTEIN
from cogent.core.alignment import SequenceCollection
from cogent.parse.fasta import MinimalFastaParser
__author__ = "Daniel McDonald"
__copyright__ = "Copyright 2007-2012, The Cogent Project"
__credits__ = ["Daniel McDonald"]
__license__ = "GPL"
__version__ = "1.5.3"
__maintainer__ = "Daniel McDonald"
__email__ = "[email protected]"
__status__ = "Development"
class CD_HIT(CommandLineApplication):
"""cd-hit Application Controller
Use this version of CD-HIT if your MolType is PROTEIN
"""
_command = 'cd-hit'
_input_handler = '_input_as_multiline_string'
_parameters = {
# input input filename in fasta format, required
'-i':ValuedParameter('-',Name='i',Delimiter=' ',IsPath=True),
# output filename, required
'-o':ValuedParameter('-',Name='o',Delimiter=' ',IsPath=True),
# sequence identity threshold, default 0.9
# this is the default cd-hit's "global sequence identity" calc'd as :
# number of identical amino acids in alignment
# divided by the full length of the shorter sequence
'-c':ValuedParameter('-',Name='c',Delimiter=' '),
# use global sequence identity, default 1
# if set to 0, then use local sequence identity, calculated as :
# number of identical amino acids in alignment
# divided by the length of the alignment
# NOTE!!! don't use -G 0 unless you use alignment coverage controls
# see options -aL, -AL, -aS, -AS
'-g':ValuedParameter('-',Name='g',Delimiter=' '),
# band_width of alignment, default 20
'-b':ValuedParameter('-',Name='b',Delimiter=' '),
# max available memory (Mbyte), default 400
'-M':ValuedParameter('-',Name='M',Delimiter=' '),
# word_length, default 8, see user's guide for choosing it
'-n':ValuedParameter('-',Name='n',Delimiter=' '),
# length of throw_away_sequences, default 10
'-l':ValuedParameter('-',Name='l',Delimiter=' '),
# tolerance for redundance, default 2
'-t':ValuedParameter('-',Name='t',Delimiter=' '),
# length of description in .clstr file, default 20
# if set to 0, it takes the fasta defline and stops at first space
'-d':ValuedParameter('-',Name='d',Delimiter=' '),
# length difference cutoff, default 0.0
# if set to 0.9, the shorter sequences need to be
# at least 90% length of the representative of the cluster
'-s':ValuedParameter('-',Name='s',Delimiter=' '),
# length difference cutoff in amino acid, default 999999
# f set to 60, the length difference between the shorter sequences
# and the representative of the cluster can not be bigger than 60
'-S':ValuedParameter('-',Name='S',Delimiter=' '),
# alignment coverage for the longer sequence, default 0.0
# if set to 0.9, the alignment must covers 90% of the sequence
'-aL':ValuedParameter('-',Name='aL',Delimiter=' '),
# alignment coverage control for the longer sequence, default 99999999
# if set to 60, and the length of the sequence is 400,
# then the alignment must be >= 340 (400-60) residues
'-AL':ValuedParameter('-',Name='AL',Delimiter=' '),
# alignment coverage for the shorter sequence, default 0.0
# if set to 0.9, the alignment must covers 90% of the sequence
'-aS':ValuedParameter('-',Name='aS',Delimiter=' '),
# alignment coverage control for the shorter sequence, default 99999999
# if set to 60, and the length of the sequence is 400,
# then the alignment must be >= 340 (400-60) residues
'-AS':ValuedParameter('-',Name='AS',Delimiter=' '),
# 1 or 0, default 0, by default, sequences are stored in RAM
# if set to 1, sequence are stored on hard drive
# it is recommended to use -B 1 for huge databases
'-B':ValuedParameter('-',Name='B',Delimiter=' '),
# 1 or 0, default 0
# if set to 1, print alignment overlap in .clstr file
'-p':ValuedParameter('-',Name='p',Delimiter=' '),
# 1 or 0, default 0
# by cd-hit's default algorithm, a sequence is clustered to the first
# cluster that meet the threshold (fast cluster). If set to 1, the program
# will cluster it into the most similar cluster that meet the threshold
# (accurate but slow mode)
# but either 1 or 0 won't change the representatives of final clusters
'-g':ValuedParameter('-',Name='g',Delimiter=' '),
# print this help
'-h':ValuedParameter('-',Name='h',Delimiter=' ')
}
_synonyms = {'Similarity':'-c'}
def getHelp(self):
"""Method that points to documentation"""
help_str =\
"""
CD-HIT is hosted as an open source project at:
http://www.bioinformatics.org/cd-hit/
The following papers should be cited if this resource is used:
Clustering of highly homologous sequences to reduce thesize of large
protein database", Weizhong Li, Lukasz Jaroszewski & Adam Godzik
Bioinformatics, (2001) 17:282-283
Tolerating some redundancy significantly speeds up clustering of large
protein databases", Weizhong Li, Lukasz Jaroszewski & Adam Godzik
Bioinformatics, (2002) 18:77-82
"""
return help_str
def _input_as_multiline_string(self, data):
"""Writes data to tempfile and sets -i parameter
data -- list of lines
"""
if data:
self.Parameters['-i']\
.on(super(CD_HIT,self)._input_as_multiline_string(data))
return ''
def _input_as_lines(self, data):
"""Writes data to tempfile and sets -i parameter
data -- list of lines, ready to be written to file
"""
if data:
self.Parameters['-i']\
.on(super(CD_HIT,self)._input_as_lines(data))
return ''
def _input_as_seqs(self, data):
"""Creates a list of seqs to pass to _input_as_lines
data -- list like object of sequences
"""
lines = []
for i,s in enumerate(data):
# will number the sequences 1,2,3, etc...
lines.append(''.join(['>',str(i+1)]))
lines.append(s)
return self._input_as_lines(lines)
def _input_as_string(self, data):
"""Makes data the value of a specific parameter"""
if data:
self.Parameters['-i'].on(str(data))
return ''
def _get_seqs_outfile(self):
"""Returns the absolute path to the seqs outfile"""
if self.Parameters['-o'].isOn():
return self.Parameters['-o'].Value
else:
raise ValueError, "No output file specified"
def _get_clstr_outfile(self):
"""Returns the absolute path to the clstr outfile"""
if self.Parameters['-o'].isOn():
return ''.join([self.Parameters['-o'].Value, '.clstr'])
else:
raise ValueError, "No output file specified"
def _get_result_paths(self, data):
"""Return dict of {key: ResultPath}"""
result = {}
result['FASTA'] = ResultPath(Path=self._get_seqs_outfile())
result['CLSTR'] = ResultPath(Path=self._get_clstr_outfile())
return result
class CD_HIT_EST(CD_HIT):
"""cd-hit Application Controller
Use this version of CD-HIT if your MolType is PROTEIN
"""
_command = 'cd-hit-est'
_input_handler = '_input_as_multiline_string'
_parameters = CD_HIT._parameters
_parameters.update({\
# 1 or 0, default 0, by default only +/+ strand alignment
# if set to 1, do both +/+ & +/- alignments
'-r':ValuedParameter('-',Name='r',Delimiter=' ')
})
def cdhit_clusters_from_seqs(seqs, moltype, params=None):
"""Returns the CD-HIT clusters given seqs
seqs : dict like collection of sequences
moltype : cogent.core.moltype object
params : cd-hit parameters
NOTE: This method will call CD_HIT if moltype is PROTIEN,
CD_HIT_EST if moltype is RNA/DNA, and raise if any other
moltype is passed.
"""
# keys are not remapped. Tested against seq_ids of 100char length
seqs = SequenceCollection(seqs, MolType=moltype)
#Create mapping between abbreviated IDs and full IDs
int_map, int_keys = seqs.getIntMap()
#Create SequenceCollection from int_map.
int_map = SequenceCollection(int_map,MolType=moltype)
# setup params and make sure the output argument is set
if params is None:
params = {}
if '-o' not in params:
params['-o'] = get_tmp_filename()
# call the correct version of cd-hit base on moltype
working_dir = get_tmp_filename()
if moltype is PROTEIN:
app = CD_HIT(WorkingDir=working_dir, params=params)
elif moltype is RNA:
app = CD_HIT_EST(WorkingDir=working_dir, params=params)
elif moltype is DNA:
app = CD_HIT_EST(WorkingDir=working_dir, params=params)
else:
raise ValueError, "Moltype must be either PROTEIN, RNA, or DNA"
# grab result
res = app(int_map.toFasta())
clusters = parse_cdhit_clstr_file(res['CLSTR'].readlines())
remapped_clusters = []
for c in clusters:
curr = [int_keys[i] for i in c]<|fim▁hole|> remapped_clusters.append(curr)
# perform cleanup
res.cleanUp()
shutil.rmtree(working_dir)
remove(params['-o'] + '.bak.clstr')
return remapped_clusters
def cdhit_from_seqs(seqs, moltype, params=None):
"""Returns the CD-HIT results given seqs
seqs : dict like collection of sequences
moltype : cogent.core.moltype object
params : cd-hit parameters
NOTE: This method will call CD_HIT if moltype is PROTIEN,
CD_HIT_EST if moltype is RNA/DNA, and raise if any other
moltype is passed.
"""
# keys are not remapped. Tested against seq_ids of 100char length
seqs = SequenceCollection(seqs, MolType=moltype)
# setup params and make sure the output argument is set
if params is None:
params = {}
if '-o' not in params:
params['-o'] = get_tmp_filename()
# call the correct version of cd-hit base on moltype
working_dir = get_tmp_filename()
if moltype is PROTEIN:
app = CD_HIT(WorkingDir=working_dir, params=params)
elif moltype is RNA:
app = CD_HIT_EST(WorkingDir=working_dir, params=params)
elif moltype is DNA:
app = CD_HIT_EST(WorkingDir=working_dir, params=params)
else:
raise ValueError, "Moltype must be either PROTEIN, RNA, or DNA"
# grab result
res = app(seqs.toFasta())
new_seqs = dict(MinimalFastaParser(res['FASTA'].readlines()))
# perform cleanup
res.cleanUp()
shutil.rmtree(working_dir)
remove(params['-o'] + '.bak.clstr')
return SequenceCollection(new_seqs, MolType=moltype)
def clean_cluster_seq_id(id):
"""Returns a cleaned cd-hit sequence id
The cluster file has sequence ids in the form of:
>some_id...
"""
return id[1:-3]
def parse_cdhit_clstr_file(lines):
"""Returns a list of list of sequence ids representing clusters"""
clusters = []
curr_cluster = []
for l in lines:
if l.startswith('>Cluster'):
if not curr_cluster:
continue
clusters.append(curr_cluster)
curr_cluster = []
else:
curr_cluster.append(clean_cluster_seq_id(l.split()[2]))
if curr_cluster:
clusters.append(curr_cluster)
return clusters<|fim▁end|>
| |
<|file_name|>login.component.ts<|end_file_name|><|fim▁begin|>import {Component} from 'angular2/core';
import {DataService} from './services/data.service';
import {UserService} from './services/user.service';
import {ToolService} from './services/tools.service';
import {Router, ROUTER_DIRECTIVES} from 'angular2/router';
@Component({
selector: 'my-login',
templateUrl: './templates/login.tpl.html',
styleUrls: ['../src/css/login.css'],
directives: [ROUTER_DIRECTIVES]
})
export class LoginComponent {
show_error: Object;
constructor(
private _dataService: DataService,
private _router: Router,
private _userService: UserService,
private _tools: ToolService) {}
onSubmit(form) {
this._dataService.postData(form.value, 'login')
.subscribe(
data => this.loginUser(data),
error => this.handleError(error)
);
}
loginUser(data) {
this._tools.setCookie('user_session', data.response.user.session_id);
this._tools.setCookie('username', data.response.user.username);<|fim▁hole|>
this._userService.setUserData()
.subscribe(
success => {
this._router.navigate(['MyClients', {group: 'all'}]);
},
error => console.log(error)
);
}
handleError(error) {
this.show_error = error;
console.log(error);
}
}<|fim▁end|>
| |
<|file_name|>price_breakdown.py<|end_file_name|><|fim▁begin|>from sevenbridges.meta.resource import Resource
from sevenbridges.meta.fields import StringField
class Breakdown(Resource):
"""
Breakdown resource contains price breakdown by storage and computation.<|fim▁hole|> storage = StringField(read_only=True)
computation = StringField(read_only=True)
data_transfer = StringField(read_only=True)
def __str__(self):
if self.data_transfer:
return (
f'<Breakdown: storage={self.storage}, '
f'computation={self.computation}, '
f'data_transfer={self.data_transfer}>'
)
return (
f'<Breakdown: storage={self.storage}, '
f'computation={self.computation}>'
)<|fim▁end|>
|
"""
|
<|file_name|>es.js<|end_file_name|><|fim▁begin|>/*
Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.<|fim▁hole|>CKEDITOR.plugins.setLang("language","es",{button:"Fijar lenguaje",remove:"Quitar lenguaje"});<|fim▁end|>
|
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
|
<|file_name|>test_signature.py<|end_file_name|><|fim▁begin|>import py
from rpython.rlib.signature import signature, finishsigs, FieldSpec, ClassSpec
from rpython.rlib import types
from rpython.annotator import model
from rpython.rtyper.llannotation import SomePtr
from rpython.annotator.signature import SignatureError
from rpython.translator.translator import TranslationContext, graphof
from rpython.rtyper.lltypesystem import rstr
from rpython.rtyper.annlowlevel import LowLevelAnnotatorPolicy
def annotate_at(f, policy=None):
t = TranslationContext()
t.config.translation.check_str_without_nul = True
a = t.buildannotator(policy=policy)
a.annotate_helper(f, [model.s_ImpossibleValue]*f.func_code.co_argcount, policy=policy)
return a
def sigof(a, f):
# returns [param1, param2, ..., ret]
g = graphof(a.translator, f)
return [a.binding(v) for v in g.startblock.inputargs] + [a.binding(g.getreturnvar())]
def getsig(f, policy=None):
a = annotate_at(f, policy=policy)
return sigof(a, f)
def check_annotator_fails(caller):
exc = py.test.raises(model.AnnotatorError, annotate_at, caller).value
assert caller.func_name in str(exc)
def test_bookkeeping():
@signature('x', 'y', returns='z')
def f(a, b):
return a + len(b)
f.foo = 'foo'
assert f._signature_ == (('x', 'y'), 'z')
assert f.func_name == 'f'
assert f.foo == 'foo'
assert f(1, 'hello') == 6
def test_basic():
@signature(types.int(), types.str(), returns=types.char())
def f(a, b):
return b[a]
assert getsig(f) == [model.SomeInteger(), model.SomeString(), model.SomeChar()]
def test_arg_errors():
@signature(types.int(), types.str(), returns=types.int())
def f(a, b):
return a + len(b)
@check_annotator_fails
def ok_for_body(): # would give no error without signature
f(2.0, 'b')
@check_annotator_fails
def bad_for_body(): # would give error inside 'f' body, instead errors at call
f('a', 'b')
def test_return():
@signature(returns=types.str())
def f():
return 'a'
assert getsig(f) == [model.SomeString()]
@signature(types.str(), returns=types.str())
def f(x):
return x
def g():
return f('a')
a = annotate_at(g)
assert sigof(a, f) == [model.SomeString(), model.SomeString()]
def test_return_errors():
@check_annotator_fails
@signature(returns=types.int())
def int_not_char():
return 'a'
@check_annotator_fails
@signature(types.str(), returns=types.int())
def str_to_int(s):
return s
@signature(returns=types.str())
def str_not_None():
return None
@check_annotator_fails
def caller_of_str_not_None():
return str_not_None()
@py.test.mark.xfail
def test_return_errors_xfail():
@check_annotator_fails
@signature(returns=types.str())
def str_not_None():
return None
def test_none():
@signature(returns=types.none())
def f():
pass
assert getsig(f) == [model.s_None]
def test_float():
@signature(types.longfloat(), types.singlefloat(), returns=types.float())
def f(a, b):
return 3.0
assert getsig(f) == [model.SomeLongFloat(), model.SomeSingleFloat(), model.SomeFloat()]
def test_unicode():
@signature(types.unicode(), returns=types.int())
def f(u):
return len(u)
assert getsig(f) == [model.SomeUnicodeString(), model.SomeInteger()]
def test_str0():
@signature(types.unicode0(), returns=types.str0())
def f(u):
return 'str'
assert getsig(f) == [model.SomeUnicodeString(no_nul=True),
model.SomeString(no_nul=True)]
def test_ptr():
policy = LowLevelAnnotatorPolicy()
@signature(types.ptr(rstr.STR), returns=types.none())
def f(buf):
pass
argtype = getsig(f, policy=policy)[0]
assert isinstance(argtype, SomePtr)
assert argtype.ll_ptrtype.TO == rstr.STR
def g():
f(rstr.mallocstr(10))
getsig(g, policy=policy)
def test_list():
@signature(types.list(types.int()), returns=types.int())
def f(a):
return len(a)
argtype = getsig(f)[0]
assert isinstance(argtype, model.SomeList)
item = argtype.listdef.listitem
assert item.s_value == model.SomeInteger()
assert item.resized == True
@check_annotator_fails
def ok_for_body():
f(['a'])
@check_annotator_fails
def bad_for_body():
f('a')
@signature(returns=types.list(types.char()))
def ff():
return ['a']
@check_annotator_fails
def mutate_broader():
ff()[0] = 'abc'
@check_annotator_fails
def mutate_unrelated():
ff()[0] = 1
@check_annotator_fails
@signature(types.list(types.char()), returns=types.int())
def mutate_in_body(l):
l[0] = 'abc'
return len(l)
def can_append():
l = ff()
l.append('b')
getsig(can_append)
def test_array():
@signature(returns=types.array(types.int()))
def f():
return [1]
rettype = getsig(f)[0]
assert isinstance(rettype, model.SomeList)
item = rettype.listdef.listitem
assert item.s_value == model.SomeInteger()
assert item.resized == False
def try_append():
l = f()
l.append(2)
check_annotator_fails(try_append)
def test_dict():
@signature(returns=types.dict(types.str(), types.int()))
def f():
return {'a': 1, 'b': 2}
rettype = getsig(f)[0]
assert isinstance(rettype, model.SomeDict)
assert rettype.dictdef.dictkey.s_value == model.SomeString()
assert rettype.dictdef.dictvalue.s_value == model.SomeInteger()
def test_instance():
class C1(object):
pass
class C2(C1):
pass
class C3(C2):
pass
@signature(types.instance(C3), returns=types.instance(C2))
def f(x):
assert isinstance(x, C2)
return x
argtype, rettype = getsig(f)
assert isinstance(argtype, model.SomeInstance)
assert argtype.classdef.classdesc.pyobj == C3
assert isinstance(rettype, model.SomeInstance)
assert rettype.classdef.classdesc.pyobj == C2
@check_annotator_fails
def ok_for_body():
f(C2())
@check_annotator_fails
def bad_for_body():
f(C1())
@check_annotator_fails
def ok_for_body():
f(None)
def test_instance_or_none():
class C1(object):
pass
class C2(C1):
pass
class C3(C2):
pass
@signature(types.instance(C3, can_be_None=True), returns=types.instance(C2, can_be_None=True))
def f(x):
assert isinstance(x, C2) or x is None
return x
argtype, rettype = getsig(f)
assert isinstance(argtype, model.SomeInstance)
assert argtype.classdef.classdesc.pyobj == C3
assert argtype.can_be_None
assert isinstance(rettype, model.SomeInstance)
assert rettype.classdef.classdesc.pyobj == C2
assert rettype.can_be_None
@check_annotator_fails<|fim▁hole|> def bad_for_body():
f(C1())
def test_self():
@finishsigs
class C(object):
@signature(types.self(), types.self(), returns=types.none())
def f(self, other):
pass
class D1(C):
pass
class D2(C):
pass
def g():
D1().f(D2())
a = annotate_at(g)
argtype = sigof(a, C.__dict__['f'])[0]
assert isinstance(argtype, model.SomeInstance)
assert argtype.classdef.classdesc.pyobj == C
def test_self_error():
class C(object):
@signature(types.self(), returns=types.none())
def incomplete_sig_meth(self):
pass
exc = py.test.raises(SignatureError, annotate_at, C.incomplete_sig_meth).value
assert 'incomplete_sig_meth' in str(exc)
assert 'finishsigs' in str(exc)
def test_any_as_argument():
@signature(types.any(), types.int(), returns=types.float())
def f(x, y):
return x + y
@signature(types.int(), returns=types.float())
def g(x):
return f(x, x)
sig = getsig(g)
assert sig == [model.SomeInteger(), model.SomeFloat()]
@signature(types.float(), returns=types.float())
def g(x):
return f(x, 4)
sig = getsig(g)
assert sig == [model.SomeFloat(), model.SomeFloat()]
@signature(types.str(), returns=types.int())
def cannot_add_string(x):
return f(x, 2)
exc = py.test.raises(model.AnnotatorError, annotate_at, cannot_add_string).value
assert 'Blocked block' in str(exc)
def test_return_any():
@signature(types.int(), returns=types.any())
def f(x):
return x
sig = getsig(f)
assert sig == [model.SomeInteger(), model.SomeInteger()]
@signature(types.str(), returns=types.any())
def cannot_add_string(x):
return f(3) + x
exc = py.test.raises(model.AnnotatorError, annotate_at, cannot_add_string).value
assert 'Blocked block' in str(exc)
assert 'cannot_add_string' in str(exc)
@py.test.mark.xfail
def test_class_basic():
class C(object):
_fields_ = ClassSpec({'x': FieldSpec(types.int)})
def wrong_type():
c = C()
c.x = 'a'
check_annotator_fails(wrong_type)
def bad_field():
c = C()
c.y = 3
check_annotator_fails(bad_field)
@py.test.mark.xfail
def test_class_shorthand():
class C1(object):
_fields_ = {'x': FieldSpec(types.int)}
def wrong_type_1():
c = C1()
c.x = 'a'
check_annotator_fails(wrong_type_1)
class C2(object):
_fields_ = ClassSpec({'x': types.int})
def wrong_type_2():
c = C2()
c.x = 'a'
check_annotator_fails(wrong_type_1)
@py.test.mark.xfail
def test_class_inherit():
class C(object):
_fields_ = ClassSpec({'x': FieldSpec(types.int)})
class C1(object):
_fields_ = ClassSpec({'y': FieldSpec(types.int)})
class C2(object):
_fields_ = ClassSpec({'y': FieldSpec(types.int)}, inherit=True)
def no_inherit():
c = C1()
c.x = 3
check_annotator_fails(no_inherit)
def good():
c = C2()
c.x = 3
annotate_at(good)
def wrong_type():
c = C2()
c.x = 'a'
check_annotator_fails(wrong_type)<|fim▁end|>
|
def ok_for_body():
f(C2())
@check_annotator_fails
|
<|file_name|>tasks.py<|end_file_name|><|fim▁begin|>import hashlib
import logging
import os
from django.conf import settings
from django.core.files.storage import default_storage as storage
from django.db import transaction
from PIL import Image
from olympia import amo
from olympia.addons.models import (
Addon, attach_tags, attach_translations, AppSupport, CompatOverride,
IncompatibleVersions, Persona, Preview)
from olympia.addons.indexers import AddonIndexer
from olympia.amo.celery import task
from olympia.amo.decorators import set_modified_on, write
from olympia.amo.helpers import user_media_path
from olympia.amo.storage_utils import rm_stored_dir
from olympia.amo.utils import cache_ns_key, ImageCheck, LocalFileStorage
from olympia.editors.models import RereviewQueueTheme
from olympia.lib.es.utils import index_objects
from olympia.versions.models import Version
# pulling tasks from cron
from . import cron # noqa
log = logging.getLogger('z.task')
@task
@write
def version_changed(addon_id, **kw):
update_last_updated(addon_id)
update_appsupport([addon_id])
def update_last_updated(addon_id):
queries = Addon._last_updated_queries()
try:
addon = Addon.objects.get(pk=addon_id)
except Addon.DoesNotExist:
log.info('[1@None] Updating last updated for %s failed, no addon found'
% addon_id)
return
log.info('[1@None] Updating last updated for %s.' % addon_id)
if addon.is_persona():
q = 'personas'
elif addon.status == amo.STATUS_PUBLIC:
q = 'public'
else:
q = 'exp'
qs = queries[q].filter(pk=addon_id).using('default')
res = qs.values_list('id', 'last_updated')
if res:
pk, t = res[0]
Addon.objects.filter(pk=pk).update(last_updated=t)
@write
def update_appsupport(ids):
log.info("[%s@None] Updating appsupport for %s." % (len(ids), ids))
<|fim▁hole|> addons = Addon.objects.no_cache().filter(id__in=ids).no_transforms()
support = []
for addon in addons:
for app, appver in addon.compatible_apps.items():
if appver is None:
# Fake support for all version ranges.
min_, max_ = 0, 999999999999999999
else:
min_, max_ = appver.min.version_int, appver.max.version_int
support.append(AppSupport(addon=addon, app=app.id,
min=min_, max=max_))
if not support:
return
with transaction.atomic():
AppSupport.objects.filter(addon__id__in=ids).delete()
AppSupport.objects.bulk_create(support)
# All our updates were sql, so invalidate manually.
Addon.objects.invalidate(*addons)
@task
def delete_preview_files(id, **kw):
log.info('[1@None] Removing preview with id of %s.' % id)
p = Preview(id=id)
for f in (p.thumbnail_path, p.image_path):
try:
storage.delete(f)
except Exception, e:
log.error('Error deleting preview file (%s): %s' % (f, e))
@task(acks_late=True)
def index_addons(ids, **kw):
log.info('Indexing addons %s-%s. [%s]' % (ids[0], ids[-1], len(ids)))
transforms = (attach_tags, attach_translations)
index_objects(ids, Addon, AddonIndexer.extract_document,
kw.pop('index', None), transforms, Addon.unfiltered)
@task
def unindex_addons(ids, **kw):
for addon in ids:
log.info('Removing addon [%s] from search index.' % addon)
Addon.unindex(addon)
@task
def delete_persona_image(dst, **kw):
log.info('[1@None] Deleting persona image: %s.' % dst)
if not dst.startswith(user_media_path('addons')):
log.error("Someone tried deleting something they shouldn't: %s" % dst)
return
try:
storage.delete(dst)
except Exception, e:
log.error('Error deleting persona image: %s' % e)
@set_modified_on
def create_persona_preview_images(src, full_dst, **kw):
"""
Creates a 680x100 thumbnail used for the Persona preview and
a 32x32 thumbnail used for search suggestions/detail pages.
"""
log.info('[1@None] Resizing persona images: %s' % full_dst)
preview, full = amo.PERSONA_IMAGE_SIZES['header']
preview_w, preview_h = preview
orig_w, orig_h = full
with storage.open(src) as fp:
i_orig = i = Image.open(fp)
# Crop image from the right.
i = i.crop((orig_w - (preview_w * 2), 0, orig_w, orig_h))
# Resize preview.
i = i.resize(preview, Image.ANTIALIAS)
i.load()
with storage.open(full_dst[0], 'wb') as fp:
i.save(fp, 'png')
_, icon_size = amo.PERSONA_IMAGE_SIZES['icon']
icon_w, icon_h = icon_size
# Resize icon.
i = i_orig
i.load()
i = i.crop((orig_w - (preview_h * 2), 0, orig_w, orig_h))
i = i.resize(icon_size, Image.ANTIALIAS)
i.load()
with storage.open(full_dst[1], 'wb') as fp:
i.save(fp, 'png')
return True
@set_modified_on
def save_persona_image(src, full_dst, **kw):
"""Creates a PNG of a Persona header/footer image."""
log.info('[1@None] Saving persona image: %s' % full_dst)
img = ImageCheck(storage.open(src))
if not img.is_image():
log.error('Not an image: %s' % src, exc_info=True)
return
with storage.open(src, 'rb') as fp:
i = Image.open(fp)
with storage.open(full_dst, 'wb') as fp:
i.save(fp, 'png')
return True
@task
def update_incompatible_appversions(data, **kw):
"""Updates the incompatible_versions table for this version."""
log.info('Updating incompatible_versions for %s versions.' % len(data))
addon_ids = set()
for version_id in data:
# This is here to handle both post_save and post_delete hooks.
IncompatibleVersions.objects.filter(version=version_id).delete()
try:
version = Version.objects.get(pk=version_id)
except Version.DoesNotExist:
log.info('Version ID [%d] not found. Incompatible versions were '
'cleared.' % version_id)
return
addon_ids.add(version.addon_id)
try:
compat = CompatOverride.objects.get(addon=version.addon)
except CompatOverride.DoesNotExist:
log.info('Compat override for addon with version ID [%d] not '
'found. Incompatible versions were cleared.' % version_id)
return
app_ranges = []
ranges = compat.collapsed_ranges()
for range in ranges:
if range.min == '0' and range.max == '*':
# Wildcard range, add all app ranges
app_ranges.extend(range.apps)
else:
# Since we can't rely on add-on version numbers, get the min
# and max ID values and find versions whose ID is within those
# ranges, being careful with wildcards.
min_id = max_id = None
if range.min == '0':
versions = (Version.objects.filter(addon=version.addon_id)
.order_by('id')
.values_list('id', flat=True)[:1])
if versions:
min_id = versions[0]
else:
try:
min_id = Version.objects.get(addon=version.addon_id,
version=range.min).id
except Version.DoesNotExist:
pass
if range.max == '*':
versions = (Version.objects.filter(addon=version.addon_id)
.order_by('-id')
.values_list('id', flat=True)[:1])
if versions:
max_id = versions[0]
else:
try:
max_id = Version.objects.get(addon=version.addon_id,
version=range.max).id
except Version.DoesNotExist:
pass
if min_id and max_id:
if min_id <= version.id <= max_id:
app_ranges.extend(range.apps)
for app_range in app_ranges:
IncompatibleVersions.objects.create(version=version,
app=app_range.app.id,
min_app_version=app_range.min,
max_app_version=app_range.max)
log.info('Added incompatible version for version ID [%d]: '
'app:%d, %s -> %s' % (version_id, app_range.app.id,
app_range.min, app_range.max))
# Increment namespace cache of compat versions.
for addon_id in addon_ids:
cache_ns_key('d2c-versions:%s' % addon_id, increment=True)
def make_checksum(header_path, footer_path):
ls = LocalFileStorage()
footer = footer_path and ls._open(footer_path).read() or ''
raw_checksum = ls._open(header_path).read() + footer
return hashlib.sha224(raw_checksum).hexdigest()
def theme_checksum(theme, **kw):
theme.checksum = make_checksum(theme.header_path, theme.footer_path)
dupe_personas = Persona.objects.filter(checksum=theme.checksum)
if dupe_personas.exists():
theme.dupe_persona = dupe_personas[0]
theme.save()
def rereviewqueuetheme_checksum(rqt, **kw):
"""Check for possible duplicate theme images."""
dupe_personas = Persona.objects.filter(
checksum=make_checksum(rqt.header_path or rqt.theme.header_path,
rqt.footer_path or rqt.theme.footer_path))
if dupe_personas.exists():
rqt.dupe_persona = dupe_personas[0]
rqt.save()
@task
@write
def save_theme(header, footer, addon, **kw):
"""Save theme image and calculates checksum after theme save."""
dst_root = os.path.join(user_media_path('addons'), str(addon.id))
header = os.path.join(settings.TMP_PATH, 'persona_header', header)
header_dst = os.path.join(dst_root, 'header.png')
if footer:
footer = os.path.join(settings.TMP_PATH, 'persona_footer', footer)
footer_dst = os.path.join(dst_root, 'footer.png')
try:
save_persona_image(src=header, full_dst=header_dst)
if footer:
save_persona_image(src=footer, full_dst=footer_dst)
create_persona_preview_images(
src=header, full_dst=[os.path.join(dst_root, 'preview.png'),
os.path.join(dst_root, 'icon.png')],
set_modified_on=[addon])
theme_checksum(addon.persona)
except IOError:
addon.delete()
raise
@task
@write
def save_theme_reupload(header, footer, addon, **kw):
header_dst = None
footer_dst = None
dst_root = os.path.join(user_media_path('addons'), str(addon.id))
try:
if header:
header = os.path.join(settings.TMP_PATH, 'persona_header', header)
header_dst = os.path.join(dst_root, 'pending_header.png')
save_persona_image(src=header, full_dst=header_dst)
if footer:
footer = os.path.join(settings.TMP_PATH, 'persona_footer', footer)
footer_dst = os.path.join(dst_root, 'pending_footer.png')
save_persona_image(src=footer, full_dst=footer_dst)
except IOError as e:
log.error(str(e))
raise
if header_dst or footer_dst:
theme = addon.persona
header = 'pending_header.png' if header_dst else theme.header
# Theme footer is optional, but can't be None.
footer = theme.footer or ''
if footer_dst:
footer = 'pending_footer.png'
# Store pending header and/or footer file paths for review.
RereviewQueueTheme.objects.filter(theme=theme).delete()
rqt = RereviewQueueTheme(theme=theme, header=header, footer=footer)
rereviewqueuetheme_checksum(rqt=rqt)
rqt.save()
@task
@write
def calc_checksum(theme_id, **kw):
"""For migration 596."""
lfs = LocalFileStorage()
theme = Persona.objects.get(id=theme_id)
header = theme.header_path
footer = theme.footer_path
# Delete invalid themes that are not images (e.g. PDF, EXE).
try:
Image.open(header)
Image.open(footer)
except IOError:
log.info('Deleting invalid theme [%s] (header: %s) (footer: %s)' %
(theme.addon.id, header, footer))
theme.addon.delete()
theme.delete()
rm_stored_dir(header.replace('header.png', ''), storage=lfs)
return
# Calculate checksum and save.
try:
theme.checksum = make_checksum(header, footer)
theme.save()
except IOError as e:
log.error(str(e))<|fim▁end|>
| |
<|file_name|>errors_view.js<|end_file_name|><|fim▁begin|>IWitness.ErrorsView = Ember.View.extend({<|fim▁hole|> classNames: ["error-bubble"],
classNameBindings: ["isError"],
isError: function() {
return !!this.get("error");
}.property("error")
});<|fim▁end|>
| |
<|file_name|>main.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
import datetime
from openerp import http
from openerp.http import request
from openerp.addons.website_portal.controllers.main import website_account
<|fim▁hole|> """ Add sales documents to main account page """
response = super(website_account, self).account()
partner = request.env.user.partner_id
res_sale_order = request.env['sale.order']
res_invoices = request.env['account.invoice']
quotations = res_sale_order.search([
('state', 'in', ['sent', 'cancel'])
])
orders = res_sale_order.search([
('state', 'in', ['sale', 'done'])
])
invoices = res_invoices.search([
('state', 'in', ['open', 'paid', 'cancelled'])
])
response.qcontext.update({
'date': datetime.date.today().strftime('%Y-%m-%d'),
'quotations': quotations,
'orders': orders,
'invoices': invoices,
})
return response
@http.route(['/my/orders/<int:order>'], type='http', auth="user", website=True)
def orders_followup(self, order=None):
partner = request.env['res.users'].browse(request.uid).partner_id
domain = [
('partner_id.id', '=', partner.id),
('state', 'not in', ['draft', 'cancel']),
('id', '=', order)
]
order = request.env['sale.order'].search(domain)
invoiced_lines = request.env['account.invoice.line'].search([('invoice_id', 'in', order.invoice_ids.ids)])
order_invoice_lines = {il.product_id.id: il.invoice_id for il in invoiced_lines}
return request.website.render("website_portal_sale.orders_followup", {
'order': order.sudo(),
'order_invoice_lines': order_invoice_lines,
})<|fim▁end|>
|
class website_account(website_account):
@http.route(['/my/home'], type='http', auth="user", website=True)
def account(self, **kw):
|
<|file_name|>gauge.rs<|end_file_name|><|fim▁begin|>use super::*;
/// A gauge metric for floating point values with helper methods
/// for incrementing and decrementing it's value
///
/// Internally uses a `Metric<f64>` with `Semantics::Instant`,
/// `Count::One` scale, and `1` count dimension
pub struct Gauge {
metric: Metric<f64>,
init_val: f64
}
impl Gauge {
/// Creates a new gauge metric with given initial value
pub fn new(name: &str, init_val: f64, shorthelp_text: &str, longhelp_text: &str) -> Result<Self, String> {
let metric = Metric::new(
name,
init_val,
Semantics::Instant,
Unit::new().count(Count::One, 1)?,
shorthelp_text,
longhelp_text
)?;
Ok(Gauge {
metric: metric,
init_val: init_val
})
}
/// Returns the current value of the gauge
pub fn val(&self) -> f64 {
self.metric.val()
}
/// Sets the value of the gauge
pub fn set(&mut self, val: f64) -> io::Result<()> {
self.metric.set_val(val)
}
/// Increments the gauge by the given value
pub fn inc(&mut self, increment: f64) -> io::Result<()> {
let val = self.metric.val();
self.metric.set_val(val + increment)
}
/// Decrements the gauge by the given value
pub fn dec(&mut self, decrement: f64) -> io::Result<()> {
let val = self.metric.val();
self.metric.set_val(val - decrement)
}
/// Resets the gauge to the initial value that was passed when
/// creating it
pub fn reset(&mut self) -> io::Result<()> {
self.metric.set_val(self.init_val)
}
}
impl MMVWriter for Gauge {
private_impl!{}
fn write(&mut self, ws: &mut MMVWriterState, c: &mut Cursor<&mut [u8]>, mmv_ver: Version) -> io::Result<()> {
self.metric.write(ws, c, mmv_ver)
}
fn register(&self, ws: &mut MMVWriterState, mmv_ver: Version) {
self.metric.register(ws, mmv_ver)<|fim▁hole|> }
}
#[test]
pub fn test() {
use super::super::Client;
let mut gauge = Gauge::new("gauge", 1.5, "", "").unwrap();
assert_eq!(gauge.val(), 1.5);
Client::new("gauge_test").unwrap()
.export(&mut [&mut gauge]).unwrap();
gauge.set(3.0).unwrap();
assert_eq!(gauge.val(), 3.0);
gauge.inc(3.0).unwrap();
assert_eq!(gauge.val(), 6.0);
gauge.dec(1.5).unwrap();
assert_eq!(gauge.val(), 4.5);
gauge.reset().unwrap();
assert_eq!(gauge.val(), 1.5);
}<|fim▁end|>
|
}
fn has_mmv2_string(&self) -> bool {
self.metric.has_mmv2_string()
|
<|file_name|>gzip.go<|end_file_name|><|fim▁begin|>package gzip
import (
"compress/gzip"
"fmt"
"io/ioutil"
"net/http"
"path/filepath"
"strings"
"sync"
"github.com/gin-gonic/gin"
)
const (
BestCompression = gzip.BestCompression
BestSpeed = gzip.BestSpeed
DefaultCompression = gzip.DefaultCompression
NoCompression = gzip.NoCompression
)
func Gzip(level int) gin.HandlerFunc {
var gzPool sync.Pool
gzPool.New = func() interface{} {
gz, err := gzip.NewWriterLevel(ioutil.Discard, level)
if err != nil {
panic(err)
}
return gz
}
return func(c *gin.Context) {
if !shouldCompress(c.Request) {
return
}
gz := gzPool.Get().(*gzip.Writer)
defer gzPool.Put(gz)
gz.Reset(c.Writer)
c.Header("Content-Encoding", "gzip")
c.Header("Vary", "Accept-Encoding")
c.Writer = &gzipWriter{c.Writer, gz}
defer func() {
gz.Close()
c.Header("Content-Length", fmt.Sprint(c.Writer.Size()))
}()
c.Next()
}
}
type gzipWriter struct {
gin.ResponseWriter
writer *gzip.Writer
}
func (g *gzipWriter) WriteString(s string) (int, error) {
return g.writer.Write([]byte(s))
}
func (g *gzipWriter) Write(data []byte) (int, error) {<|fim▁hole|>}
func shouldCompress(req *http.Request) bool {
if !strings.Contains(req.Header.Get("Accept-Encoding"), "gzip") {
return false
}
extension := filepath.Ext(req.URL.Path)
if len(extension) < 4 { // fast path
return true
}
switch extension {
case ".png", ".gif", ".jpeg", ".jpg":
return false
default:
return true
}
}<|fim▁end|>
|
return g.writer.Write(data)
|
<|file_name|>utils.py<|end_file_name|><|fim▁begin|># (c) Copyright 2013 Hewlett-Packard Development Company, L.P.
# 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.
#
# @author: Swaminathan Vasudevan, Hewlett-Packard.
#
"""VPN Utilities and helper functions."""
from neutronclient.common import exceptions
from neutronclient.i18n import _
dpd_supported_actions = ['hold', 'clear', 'restart',
'restart-by-peer', 'disabled']
dpd_supported_keys = ['action', 'interval', 'timeout']
lifetime_keys = ['units', 'value']
lifetime_units = ['seconds']
def validate_dpd_dict(dpd_dict):
for key, value in dpd_dict.items():
if key not in dpd_supported_keys:
message = _(
"DPD Dictionary KeyError: "
"Reason-Invalid DPD key : "
"'%(key)s' not in %(supported_key)s ") % {
'key': key, 'supported_key': dpd_supported_keys}
raise exceptions.CommandError(message)
if key == 'action' and value not in dpd_supported_actions:
message = _(
"DPD Dictionary ValueError: "
"Reason-Invalid DPD action : "
"'%(key_value)s' not in %(supported_action)s ") % {
'key_value': value,
'supported_action': dpd_supported_actions}
raise exceptions.CommandError(message)
if key in ('interval', 'timeout'):
try:
if int(value) <= 0:
raise ValueError()
except ValueError:
message = _(
"DPD Dictionary ValueError: "
"Reason-Invalid positive integer value: "
"'%(key)s' = %(value)s ") % {
'key': key, 'value': value}
raise exceptions.CommandError(message)
else:
dpd_dict[key] = int(value)
return
def validate_lifetime_dict(lifetime_dict):
for key, value in lifetime_dict.items():
if key not in lifetime_keys:
message = _(
"Lifetime Dictionary KeyError: "
"Reason-Invalid unit key : "
"'%(key)s' not in %(supported_key)s ") % {
'key': key, 'supported_key': lifetime_keys}
raise exceptions.CommandError(message)
if key == 'units' and value not in lifetime_units:
message = _(
"Lifetime Dictionary ValueError: "
"Reason-Invalid units : "
"'%(key_value)s' not in %(supported_units)s ") % {
'key_value': key, 'supported_units': lifetime_units}<|fim▁hole|> raise exceptions.CommandError(message)
if key == 'value':
try:
if int(value) < 60:
raise ValueError()
except ValueError:
message = _(
"Lifetime Dictionary ValueError: "
"Reason-Invalid value should be at least 60:"
"'%(key_value)s' = %(value)s ") % {
'key_value': key, 'value': value}
raise exceptions.CommandError(message)
else:
lifetime_dict['value'] = int(value)
return
def lifetime_help(policy):
lifetime = _("%s lifetime attributes. "
"'units'-seconds, default:seconds. "
"'value'-non negative integer, default:3600.") % policy
return lifetime
def dpd_help(policy):
dpd = _(" %s Dead Peer Detection attributes."
" 'action'-hold,clear,disabled,restart,restart-by-peer."
" 'interval' and 'timeout' are non negative integers. "
" 'interval' should be less than 'timeout' value. "
" 'action', default:hold 'interval', default:30, "
" 'timeout', default:120.") % policy.capitalize()
return dpd<|fim▁end|>
| |
<|file_name|>pointbreak.js<|end_file_name|><|fim▁begin|>/* pointbreak.js - PointBreak provides a friendly interface to matchMedia with named media queries and easy to create callbacks. Authors & copyright (c) 2013: WebLinc, David Knight. */
(function(win) {
'use strict';
var EVENT_TYPE_MATCH = 'match',
EVENT_TYPE_UNMATCH = 'unmatch';
// Create a point object which contains the functionality to trigger events and name alias for the media query
function createPoint() {
return {
name : null,
media : '',
mql : null,
listeners : {
once : {
match : null,
unmatch : null
},
match : [],
unmatch : []
},
trigger : function(type) {
var listenerType = this.listeners[type];
for (var i = 0, len = listenerType.length; i < len; i++) {
var listener = listenerType[i];
if (typeof(listener.callback) === 'function') {
listener.callback.call(win, this, listener.data);
}
}
},
handleListener: null,
// Fires 'callback' that matches the 'type' immediately
now : function(type, callback, data) {
var matches = this.mql && this.mql.matches;
if ((type === EVENT_TYPE_MATCH && matches) || (type === EVENT_TYPE_UNMATCH && !matches)) {
callback.call(win, this, data || {});
}
return this;
},
// Fired the first time the conditions are matched or unmatched
once : function(type, callback, data) {
var matches = this.mql && this.mql.matches;
if ((type === EVENT_TYPE_MATCH && matches) || (type === EVENT_TYPE_UNMATCH && !matches)) {
this.once[type] = null;
callback.call(win, this, data || {});
} else {
this.once[type] = {
callback : callback,
data : data
};
}
return this;
},
// Fired each time the conditions are matched or unmatched which could be multiple times during a session
on : function(type, callback, data) {
this.listeners[type].push({
callback : callback,
data : data || {}
});
return this;
},
// Removes a specific callback or all callbacks if 'callback' is undefined for 'match' or 'unmatch'
off : function(type, callback) {
if (callback) {
var listenerType = this.listeners[type];
for (var i = 0; i < listenerType.length; i++) {
if (listenerType[i].callback === callback) {
listenerType.splice(i, 1);
i--;
}
}
} else {
this.listeners[type] = [];
this.once[type] = null;
}
return this;
}
};
}
// Interface for points that provides easy get/set methods and storage in the 'points' object
win.PointBreak = {
// Contains alias for media queries
points: {},
// PointBreak.set('xsmall', '(min-width: 320px) and (max-width: 480px)')
set: function (name, value) {
var point = this.points[name];
// Reset 'listeners' and removeListener from 'mql' (MediaQueryList)
// else create point object and add 'name' property
if (point) {
point.mql.removeListener(point.handleListener);
point
.off(EVENT_TYPE_MATCH)
.off(EVENT_TYPE_UNMATCH);
} else {
point = this.points[name] = createPoint();
point.name = name;
}
// Set up listener function for 'mql'
point.handleListener = function(mql) {
var type = (mql.matches && EVENT_TYPE_MATCH) || EVENT_TYPE_UNMATCH,
once = point.once[type];
// 'point' comes from the 'set' scope
if (typeof(once) === 'function') {
point.once[type] = null;
once.call(win, point);
}
point.trigger(type);
};
// Set up matchMedia and listener, requires matchMedia support or equivalent polyfill to evaluate media query
// See https://github.com/weblinc/media-match or https://github.com/paulirish/matchMedia.js for matchMedia polyfill
point.media = value || 'all';
point.mql = (win.matchMedia && win.matchMedia(point.media)) || {
matches : false,
media : point.media,
addListener : function() {},
removeListener : function() {}
};
point.mql.addListener(point.handleListener);
return point;
},
// PointBreak.get('xsmall')
get: function(name) {
return this.points[name] || null;
},
// PointBreak.matches('xsmall')
matches: function(name) {
return (this.points[name] && this.points[name].mql.matches) || false;
},
// PointBreak.lastMatch('xsmall small medium')
lastMatch: function(nameList) {
var list = nameList.indexOf(' ') ? nameList.split(' ') : [nameList],
<|fim▁hole|> result = '';
for (var i = 0, len = list.length; i < len; i++) {
name = list[i];
if (this.points[name] && this.points[name].mql.matches) {
result = name;
}
}
return result;
}
};
})(window);<|fim▁end|>
|
name = '',
|
<|file_name|>metadata.py<|end_file_name|><|fim▁begin|>import Fast5File
def run(parser, args):
if args.read:
for i, fast5 in enumerate(Fast5File.Fast5FileSet(args.files)):
for metadata_dict in fast5.read_metadata:
if i == 0:
header = metadata_dict.keys()
print "\t".join(["filename"] + header)
print "\t".join([fast5.filename] + [str( metadata_dict[k] ) for k in header])<|fim▁hole|> print "asic_id\tasic_temp\theatsink_temp"
for fast5 in Fast5File.Fast5FileSet(args.files):
asic_temp = fast5.get_asic_temp()
asic_id = fast5.get_asic_id()
heatsink_temp = fast5.get_heatsink_temp()
print "%s\t%s\t%s" % (asic_id, asic_temp, heatsink_temp)
fast5.close()<|fim▁end|>
|
else:
|
<|file_name|>errors.py<|end_file_name|><|fim▁begin|>"""
This file is part of py-sonic.
py-sonic 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.
py-sonic 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 py-sonic. If not, see <http://www.gnu.org/licenses/>
"""
class SonicError(Exception):
pass
class ParameterError(SonicError):
pass
class VersionError(SonicError):
pass
class CredentialError(SonicError):
pass
class AuthError(SonicError):
pass
class LicenseError(SonicError):
pass
class DataNotFoundError(SonicError):
pass
class ArgumentError(SonicError):
pass
# This maps the error code numbers from the Subsonic server to their
# appropriate Exceptions
ERR_CODE_MAP = {
0: SonicError ,
10: ParameterError ,
20: VersionError ,
30: VersionError ,
40: CredentialError ,
50: AuthError ,<|fim▁hole|> 70: DataNotFoundError ,
}
def getExcByCode(code):
code = int(code)
if code in ERR_CODE_MAP:
return ERR_CODE_MAP[code]
return SonicError<|fim▁end|>
|
60: LicenseError ,
|
<|file_name|>MacroScreenView.js<|end_file_name|><|fim▁begin|>// Copyright 2013-2021, University of Colorado Boulder
/**
* View for the 'Macro' screen.
*
* @author Chris Malley (PixelZoom, Inc.)
*/
import Property from '../../../../axon/js/Property.js';
import ScreenView from '../../../../joist/js/ScreenView.js';
import merge from '../../../../phet-core/js/merge.js';
import ModelViewTransform2 from '../../../../phetcommon/js/view/ModelViewTransform2.js';
import ResetAllButton from '../../../../scenery-phet/js/buttons/ResetAllButton.js';
import EyeDropperNode from '../../../../scenery-phet/js/EyeDropperNode.js';
import { Node } from '../../../../scenery/js/imports.js';
import Tandem from '../../../../tandem/js/Tandem.js';
import Water from '../../common/model/Water.js';
import PHScaleConstants from '../../common/PHScaleConstants.js';
import BeakerNode from '../../common/view/BeakerNode.js';
import DrainFaucetNode from '../../common/view/DrainFaucetNode.js';
import DropperFluidNode from '../../common/view/DropperFluidNode.js';
import FaucetFluidNode from '../../common/view/FaucetFluidNode.js';
import PHDropperNode from '../../common/view/PHDropperNode.js';
import SoluteComboBox from '../../common/view/SoluteComboBox.js';
import SolutionNode from '../../common/view/SolutionNode.js';
import VolumeIndicatorNode from '../../common/view/VolumeIndicatorNode.js';
import WaterFaucetNode from '../../common/view/WaterFaucetNode.js';
import phScale from '../../phScale.js';
import MacroPHMeterNode from './MacroPHMeterNode.js';
import NeutralIndicatorNode from './NeutralIndicatorNode.js';
class MacroScreenView extends ScreenView {
/**
* @param {MacroModel} model
* @param {ModelViewTransform2} modelViewTransform
* @param {Tandem} tandem
*/
constructor( model, modelViewTransform, tandem ) {
assert && assert( tandem instanceof Tandem, 'invalid tandem' );
assert && assert( modelViewTransform instanceof ModelViewTransform2, 'invalid modelViewTransform' );
super( merge( {}, PHScaleConstants.SCREEN_VIEW_OPTIONS, {
tandem: tandem
} ) );
// beaker
const beakerNode = new BeakerNode( model.beaker, modelViewTransform, {
tandem: tandem.createTandem( 'beakerNode' )
} );
// solution in the beaker
const solutionNode = new SolutionNode( model.solution, model.beaker, modelViewTransform );
// volume indicator on the right edge of beaker
const volumeIndicatorNode = new VolumeIndicatorNode( model.solution.totalVolumeProperty, model.beaker, modelViewTransform, {
tandem: tandem.createTandem( 'volumeIndicatorNode' )
} );
// Neutral indicator that appears in the bottom of the beaker.
const neutralIndicatorNode = new NeutralIndicatorNode( model.solution, {
tandem: tandem.createTandem( 'neutralIndicatorNode' )
} );
// dropper
const DROPPER_SCALE = 0.85;
const dropperNode = new PHDropperNode( model.dropper, modelViewTransform, {
visibleProperty: model.dropper.visibleProperty,
tandem: tandem.createTandem( 'dropperNode' )
} );
dropperNode.setScaleMagnitude( DROPPER_SCALE );
const dropperFluidNode = new DropperFluidNode( model.dropper, model.beaker, DROPPER_SCALE * EyeDropperNode.TIP_WIDTH,
modelViewTransform, {
visibleProperty: model.dropper.visibleProperty
} );
// faucets
const waterFaucetNode = new WaterFaucetNode( model.waterFaucet, modelViewTransform, {
tandem: tandem.createTandem( 'waterFaucetNode' )
} );
const drainFaucetNode = new DrainFaucetNode( model.drainFaucet, modelViewTransform, {
tandem: tandem.createTandem( 'drainFaucetNode' )
} );
// fluids coming out of faucets
const WATER_FLUID_HEIGHT = model.beaker.position.y - model.waterFaucet.position.y;
const DRAIN_FLUID_HEIGHT = 1000; // tall enough that resizing the play area is unlikely to show bottom of fluid
const waterFluidNode = new FaucetFluidNode( model.waterFaucet, new Property( Water.color ), WATER_FLUID_HEIGHT, modelViewTransform );
const drainFluidNode = new FaucetFluidNode( model.drainFaucet, model.solution.colorProperty, DRAIN_FLUID_HEIGHT, modelViewTransform );
// Hide fluids when their faucets are hidden. See https://github.com/phetsims/ph-scale/issues/107
waterFaucetNode.visibleProperty.lazyLink( () => {
waterFaucetNode.visibile = waterFaucetNode.visible;
} );
drainFluidNode.visibleProperty.lazyLink( () => {
waterFaucetNode.visibile = drainFluidNode.visible;
} );
// pH meter
const pHMeterNode = new MacroPHMeterNode( model.pHMeter, model.solution, model.dropper,
solutionNode, dropperFluidNode, waterFluidNode, drainFluidNode, modelViewTransform, {
tandem: tandem.createTandem( 'pHMeterNode' )
} );
// solutes combo box
const soluteListParent = new Node();
const soluteComboBox = new SoluteComboBox( model.solutes, model.dropper.soluteProperty, soluteListParent, {
maxWidth: 400,
tandem: tandem.createTandem( 'soluteComboBox' )
} );
const resetAllButton = new ResetAllButton( {
scale: 1.32,
listener: () => {
this.interruptSubtreeInput();
model.reset();
},
tandem: tandem.createTandem( 'resetAllButton' )
} );
// Parent for all nodes added to this screen
const rootNode = new Node( {
children: [
// nodes are rendered in this order
waterFluidNode,
waterFaucetNode,
drainFluidNode,
drainFaucetNode,
dropperFluidNode,
dropperNode,
solutionNode,
beakerNode,
neutralIndicatorNode,
volumeIndicatorNode,
soluteComboBox,
resetAllButton,
pHMeterNode, // next to last so that probe doesn't get lost behind anything
soluteListParent // last, so that combo box list is on top
]<|fim▁hole|>
// Layout of nodes that don't have a position specified in the model
soluteComboBox.left = modelViewTransform.modelToViewX( model.beaker.left ) - 20; // anchor on left so it grows to the right during i18n
soluteComboBox.top = this.layoutBounds.top + 15;
neutralIndicatorNode.centerX = beakerNode.centerX;
neutralIndicatorNode.bottom = beakerNode.bottom - 30;
resetAllButton.right = this.layoutBounds.right - 40;
resetAllButton.bottom = this.layoutBounds.bottom - 20;
model.isAutofillingProperty.link( () => dropperNode.interruptSubtreeInput() );
}
}
phScale.register( 'MacroScreenView', MacroScreenView );
export default MacroScreenView;<|fim▁end|>
|
} );
this.addChild( rootNode );
|
<|file_name|>PolygonSetInterface.hpp<|end_file_name|><|fim▁begin|>#pragma once
/* Copyright STIFTELSEN SINTEF 2014
*
* This file is part of FRView.
* FRView 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.
*
* FRView is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with the FRView. If not, see <http://www.gnu.org/licenses/>.
*/
#include <GL/glew.h>
#include <string>
#include <vector>
#include <boost/utility.hpp>
namespace render {
namespace mesh {
class PolygonSetInterface
{
public:
virtual
~PolygonSetInterface();
/** Number of cells that use a polygon.
*
* \return 1 for polygon meshes (where a polygon touches exactly one
* cells, and 2 for polyhedral meshes (where a polygon touches one or two
* cells).
*/
virtual
GLuint
polygonCellCount() const = 0;
/** Returns a per-polygon vertex array object. */<|fim▁hole|> polygonVertexArray() const = 0;
virtual
GLuint
polygonVertexIndexTexture() const = 0;
virtual
GLuint
polygonVertexIndexBuffer() const = 0;
virtual
GLuint
polygonNormalIndexTexture() const = 0;
/** Returns the number of polygon faces. */
virtual
GLsizei
polygonCount() const = 0;
/** Returns the max number of vertices in a polygon face. */
virtual
GLsizei
polygonMaxPolygonSize() const = 0;
/** Returns the number of triangles needed to triangulate all polygons in grid. */
virtual
GLsizei
polygonTriangulatedCount() const = 0;
};
} // of namespace mesh
} // of namespace render<|fim▁end|>
|
virtual
GLuint
|
<|file_name|>enc-latin1-tests.ts<|end_file_name|><|fim▁begin|>/// <reference path="../../yui/yui.d.ts" />
/// <reference path="../cryptojs.d.ts" />
YUI.add('enc-latin1-test', function (Y) {
var C = CryptoJS;
Y.Test.Runner.add(new Y.Test.Case({
name: 'Latin1',
testStringify: function () {
Y.Assert.areEqual('\x12\x34\x56\x78', C.enc.Latin1.stringify(C.lib.WordArray.create([0x12345678])));
},
testParse: function () {
Y.Assert.areEqual(C.lib.WordArray.create([0x12345678]).toString(), C.enc.Latin1.parse('\x12\x34\x56\x78').toString());
}
}));<|fim▁hole|><|fim▁end|>
|
}, '$Rev$');
|
<|file_name|>17-xml_namespace.js<|end_file_name|><|fim▁begin|>(function () {
function RunningInNode () {
return(
(typeof require) == "function"
&&
<|fim▁hole|> (typeof exports) == "object"
&&
(typeof module) == "object"
&&
(typeof __filename) == "string"
&&
(typeof __dirname) == "string"
);
}
if (!RunningInNode()) {
if (!this.Tautologistics)
this.Tautologistics = {};
if (!this.Tautologistics.NodeHtmlParser)
this.Tautologistics.NodeHtmlParser = {};
if (!this.Tautologistics.NodeHtmlParser.Tests)
this.Tautologistics.NodeHtmlParser.Tests = [];
exports = {};
this.Tautologistics.NodeHtmlParser.Tests.push(exports);
}
exports.name = "XML Namespace";
exports.options = {
handler: {}
, parser: {}
};
exports.html = "<ns:tag>text</ns:tag>";
exports.expected =
[ { raw: 'ns:tag', data: 'ns:tag', type: 'tag', name: 'ns:tag', children: [ { raw: 'text', data: 'text', type: 'text' } ] }
];
})();<|fim▁end|>
| |
<|file_name|>issue-2723-b.rs<|end_file_name|><|fim▁begin|>// Copyright 2012-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
// aux-build:issue_2723_a.rs
extern crate issue_2723_a;
use issue_2723_a::f;
<|fim▁hole|> f(vec![2]);
}
}<|fim▁end|>
|
pub fn main() {
unsafe {
|
<|file_name|>test_saving_energy.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
# Copyright (c) 2017 ZTE
#
# 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 unittest import mock
from watcher.common import clients
from watcher.common import utils
from watcher.decision_engine.strategy import strategies
from watcher.tests.decision_engine.strategy.strategies.test_base \
import TestBaseStrategy
class TestSavingEnergy(TestBaseStrategy):
def setUp(self):
super(TestSavingEnergy, self).setUp()
mock_node1_dict = {
'uuid': '922d4762-0bc5-4b30-9cb9-48ab644dd861'}
mock_node2_dict = {
'uuid': '922d4762-0bc5-4b30-9cb9-48ab644dd862'}
mock_node1 = mock.Mock(**mock_node1_dict)
mock_node2 = mock.Mock(**mock_node2_dict)
self.fake_nodes = [mock_node1, mock_node2]
p_ironic = mock.patch.object(
clients.OpenStackClients, 'ironic')
self.m_ironic = p_ironic.start()
self.addCleanup(p_ironic.stop)
p_nova = mock.patch.object(
clients.OpenStackClients, 'nova')
self.m_nova = p_nova.start()
self.addCleanup(p_nova.stop)
self.m_ironic.node.list.return_value = self.fake_nodes
self.m_c_model.return_value = self.fake_c_cluster.generate_scenario_1()
self.strategy = strategies.SavingEnergy(
config=mock.Mock())
self.strategy.input_parameters = utils.Struct()
self.strategy.input_parameters.update(
{'free_used_percent': 10.0,
'min_free_hosts_num': 1})
self.strategy.free_used_percent = 10.0
self.strategy.min_free_hosts_num = 1
self.strategy._ironic_client = self.m_ironic
self.strategy._nova_client = self.m_nova
def test_get_hosts_pool_with_vms_node_pool(self):
mock_node1_dict = {
'extra': {'compute_node_id': 1},
'power_state': 'power on'}
mock_node2_dict = {
'extra': {'compute_node_id': 2},
'power_state': 'power off'}
mock_node1 = mock.Mock(**mock_node1_dict)
mock_node2 = mock.Mock(**mock_node2_dict)
self.m_ironic.node.get.side_effect = [mock_node1, mock_node2]
mock_hyper1 = mock.Mock()
mock_hyper2 = mock.Mock()
mock_hyper1.to_dict.return_value = {
'running_vms': 2, 'service': {'host': 'hostname_0'}, 'state': 'up'}
mock_hyper2.to_dict.return_value = {
'running_vms': 2, 'service': {'host': 'hostname_1'}, 'state': 'up'}
self.m_nova.hypervisors.get.side_effect = [mock_hyper1, mock_hyper2]
self.strategy.get_hosts_pool()
self.assertEqual(len(self.strategy.with_vms_node_pool), 2)
self.assertEqual(len(self.strategy.free_poweron_node_pool), 0)
self.assertEqual(len(self.strategy.free_poweroff_node_pool), 0)
def test_get_hosts_pool_free_poweron_node_pool(self):
mock_node1_dict = {
'extra': {'compute_node_id': 1},
'power_state': 'power on'}
mock_node2_dict = {
'extra': {'compute_node_id': 2},
'power_state': 'power on'}
mock_node1 = mock.Mock(**mock_node1_dict)
mock_node2 = mock.Mock(**mock_node2_dict)
self.m_ironic.node.get.side_effect = [mock_node1, mock_node2]
mock_hyper1 = mock.Mock()
mock_hyper2 = mock.Mock()
mock_hyper1.to_dict.return_value = {
'running_vms': 0, 'service': {'host': 'hostname_0'}, 'state': 'up'}
mock_hyper2.to_dict.return_value = {
'running_vms': 0, 'service': {'host': 'hostname_1'}, 'state': 'up'}
self.m_nova.hypervisors.get.side_effect = [mock_hyper1, mock_hyper2]
self.strategy.get_hosts_pool()
self.assertEqual(len(self.strategy.with_vms_node_pool), 0)
self.assertEqual(len(self.strategy.free_poweron_node_pool), 2)
self.assertEqual(len(self.strategy.free_poweroff_node_pool), 0)
def test_get_hosts_pool_free_poweroff_node_pool(self):
mock_node1_dict = {
'extra': {'compute_node_id': 1},
'power_state': 'power off'}
mock_node2_dict = {
'extra': {'compute_node_id': 2},
'power_state': 'power off'}
mock_node1 = mock.Mock(**mock_node1_dict)
mock_node2 = mock.Mock(**mock_node2_dict)
self.m_ironic.node.get.side_effect = [mock_node1, mock_node2]
mock_hyper1 = mock.Mock()
mock_hyper2 = mock.Mock()
mock_hyper1.to_dict.return_value = {
'running_vms': 0, 'service': {'host': 'hostname_0'}, 'state': 'up'}
mock_hyper2.to_dict.return_value = {
'running_vms': 0, 'service': {'host': 'hostname_1'}, 'state': 'up'}
self.m_nova.hypervisors.get.side_effect = [mock_hyper1, mock_hyper2]
self.strategy.get_hosts_pool()
self.assertEqual(len(self.strategy.with_vms_node_pool), 0)
self.assertEqual(len(self.strategy.free_poweron_node_pool), 0)
self.assertEqual(len(self.strategy.free_poweroff_node_pool), 2)
def test_get_hosts_pool_with_node_out_model(self):
mock_node1_dict = {
'extra': {'compute_node_id': 1},<|fim▁hole|> 'power_state': 'power off'}
mock_node1 = mock.Mock(**mock_node1_dict)
mock_node2 = mock.Mock(**mock_node2_dict)
self.m_ironic.node.get.side_effect = [mock_node1, mock_node2]
mock_hyper1 = mock.Mock()
mock_hyper2 = mock.Mock()
mock_hyper1.to_dict.return_value = {
'running_vms': 0, 'service': {'host': 'hostname_0'},
'state': 'up'}
mock_hyper2.to_dict.return_value = {
'running_vms': 0, 'service': {'host': 'hostname_10'},
'state': 'up'}
self.m_nova.hypervisors.get.side_effect = [mock_hyper1, mock_hyper2]
self.strategy.get_hosts_pool()
self.assertEqual(len(self.strategy.with_vms_node_pool), 0)
self.assertEqual(len(self.strategy.free_poweron_node_pool), 0)
self.assertEqual(len(self.strategy.free_poweroff_node_pool), 1)
def test_save_energy_poweron(self):
self.strategy.free_poweroff_node_pool = [
mock.Mock(uuid='922d4762-0bc5-4b30-9cb9-48ab644dd861'),
mock.Mock(uuid='922d4762-0bc5-4b30-9cb9-48ab644dd862')
]
self.strategy.save_energy()
self.assertEqual(len(self.strategy.solution.actions), 1)
action = self.strategy.solution.actions[0]
self.assertEqual(action.get('input_parameters').get('state'), 'on')
def test_save_energy_poweroff(self):
self.strategy.free_poweron_node_pool = [
mock.Mock(uuid='922d4762-0bc5-4b30-9cb9-48ab644dd861'),
mock.Mock(uuid='922d4762-0bc5-4b30-9cb9-48ab644dd862')
]
self.strategy.save_energy()
self.assertEqual(len(self.strategy.solution.actions), 1)
action = self.strategy.solution.actions[0]
self.assertEqual(action.get('input_parameters').get('state'), 'off')
def test_execute(self):
mock_node1_dict = {
'extra': {'compute_node_id': 1},
'power_state': 'power on'}
mock_node2_dict = {
'extra': {'compute_node_id': 2},
'power_state': 'power on'}
mock_node1 = mock.Mock(**mock_node1_dict)
mock_node2 = mock.Mock(**mock_node2_dict)
self.m_ironic.node.get.side_effect = [mock_node1, mock_node2]
mock_hyper1 = mock.Mock()
mock_hyper2 = mock.Mock()
mock_hyper1.to_dict.return_value = {
'running_vms': 0, 'service': {'host': 'hostname_0'}, 'state': 'up'}
mock_hyper2.to_dict.return_value = {
'running_vms': 0, 'service': {'host': 'hostname_1'}, 'state': 'up'}
self.m_nova.hypervisors.get.side_effect = [mock_hyper1, mock_hyper2]
model = self.fake_c_cluster.generate_scenario_1()
self.m_c_model.return_value = model
solution = self.strategy.execute()
self.assertEqual(len(solution.actions), 1)<|fim▁end|>
|
'power_state': 'power off'}
mock_node2_dict = {
'extra': {'compute_node_id': 2},
|
<|file_name|>vrpose.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use core::nonzero::NonZero;
use dom::bindings::codegen::Bindings::VRPoseBinding;
use dom::bindings::codegen::Bindings::VRPoseBinding::VRPoseMethods;
use dom::bindings::js::Root;
use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object};
use dom::globalscope::GlobalScope;
use dom_struct::dom_struct;
use js::jsapi::{Heap, JSContext, JSObject};
use js::typedarray::{Float32Array, CreateWith};
use std::ptr;
use webvr_traits::webvr;
#[dom_struct]
pub struct VRPose {
reflector_: Reflector,
position: Heap<*mut JSObject>,
orientation: Heap<*mut JSObject>,
linear_vel: Heap<*mut JSObject>,
angular_vel: Heap<*mut JSObject>,
linear_acc: Heap<*mut JSObject>,
angular_acc: Heap<*mut JSObject>,
}
#[allow(unsafe_code)]
unsafe fn update_or_create_typed_array(cx: *mut JSContext,
src: Option<&[f32]>,
dst: &Heap<*mut JSObject>) {
match src {
Some(data) => {
if dst.get().is_null() {
rooted!(in (cx) let mut array = ptr::null_mut());
let _ = Float32Array::create(cx, CreateWith::Slice(data), array.handle_mut());
(*dst).set(array.get());
} else {
typedarray!(in(cx) let array: Float32Array = dst.get());
if let Ok(mut array) = array {
array.update(data);
}
}
},
None => {
if !dst.get().is_null() {
dst.set(ptr::null_mut());
}
}
}
}
<|fim▁hole|>#[allow(unsafe_code)]
fn heap_to_option(heap: &Heap<*mut JSObject>) -> Option<NonZero<*mut JSObject>> {
let js_object = heap.get();
if js_object.is_null() {
None
} else {
unsafe {
Some(NonZero::new_unchecked(js_object))
}
}
}
impl VRPose {
fn new_inherited() -> VRPose {
VRPose {
reflector_: Reflector::new(),
position: Heap::default(),
orientation: Heap::default(),
linear_vel: Heap::default(),
angular_vel: Heap::default(),
linear_acc: Heap::default(),
angular_acc: Heap::default(),
}
}
pub fn new(global: &GlobalScope, pose: &webvr::VRPose) -> Root<VRPose> {
let root = reflect_dom_object(box VRPose::new_inherited(),
global,
VRPoseBinding::Wrap);
root.update(&pose);
root
}
#[allow(unsafe_code)]
pub fn update(&self, pose: &webvr::VRPose) {
let cx = self.global().get_cx();
unsafe {
update_or_create_typed_array(cx, pose.position.as_ref().map(|v| &v[..]), &self.position);
update_or_create_typed_array(cx, pose.orientation.as_ref().map(|v| &v[..]), &self.orientation);
update_or_create_typed_array(cx, pose.linear_velocity.as_ref().map(|v| &v[..]), &self.linear_vel);
update_or_create_typed_array(cx, pose.angular_velocity.as_ref().map(|v| &v[..]), &self.angular_vel);
update_or_create_typed_array(cx, pose.linear_acceleration.as_ref().map(|v| &v[..]), &self.linear_acc);
update_or_create_typed_array(cx, pose.angular_acceleration.as_ref().map(|v| &v[..]), &self.angular_acc);
}
}
}
impl VRPoseMethods for VRPose {
#[allow(unsafe_code)]
// https://w3c.github.io/webvr/#dom-vrpose-position
unsafe fn GetPosition(&self, _cx: *mut JSContext) -> Option<NonZero<*mut JSObject>> {
heap_to_option(&self.position)
}
#[allow(unsafe_code)]
// https://w3c.github.io/webvr/#dom-vrpose-linearvelocity
unsafe fn GetLinearVelocity(&self, _cx: *mut JSContext) -> Option<NonZero<*mut JSObject>> {
heap_to_option(&self.linear_vel)
}
#[allow(unsafe_code)]
// https://w3c.github.io/webvr/#dom-vrpose-linearacceleration
unsafe fn GetLinearAcceleration(&self, _cx: *mut JSContext) -> Option<NonZero<*mut JSObject>> {
heap_to_option(&self.linear_acc)
}
#[allow(unsafe_code)]
// https://w3c.github.io/webvr/#dom-vrpose-orientation
unsafe fn GetOrientation(&self, _cx: *mut JSContext) -> Option<NonZero<*mut JSObject>> {
heap_to_option(&self.orientation)
}
#[allow(unsafe_code)]
// https://w3c.github.io/webvr/#dom-vrpose-angularvelocity
unsafe fn GetAngularVelocity(&self, _cx: *mut JSContext) -> Option<NonZero<*mut JSObject>> {
heap_to_option(&self.angular_vel)
}
#[allow(unsafe_code)]
// https://w3c.github.io/webvr/#dom-vrpose-angularacceleration
unsafe fn GetAngularAcceleration(&self, _cx: *mut JSContext) -> Option<NonZero<*mut JSObject>> {
heap_to_option(&self.angular_acc)
}
}<|fim▁end|>
|
#[inline]
|
<|file_name|>08b6358a04bf_txnreconcile_allow_txn_id_to_be_null.py<|end_file_name|><|fim▁begin|>"""TxnReconcile allow txn_id to be null
Revision ID: 08b6358a04bf
Revises: 04e61490804b
Create Date: 2018-03-07 19:48:06.050926
"""
from alembic import op
from sqlalchemy.dialects import mysql
# revision identifiers, used by Alembic.
revision = '08b6358a04bf'
down_revision = '04e61490804b'
branch_labels = None
depends_on = None
def upgrade():
op.alter_column(
'txn_reconciles', 'txn_id',
existing_type=mysql.INTEGER(display_width=11),
nullable=True<|fim▁hole|>
def downgrade():
conn = op.get_bind()
conn.execute("SET FOREIGN_KEY_CHECKS=0")
op.alter_column(
'txn_reconciles', 'txn_id',
existing_type=mysql.INTEGER(display_width=11),
nullable=False
)
conn.execute("SET FOREIGN_KEY_CHECKS=1")<|fim▁end|>
|
)
|
<|file_name|>AppConstants.java<|end_file_name|><|fim▁begin|>package mahout;
/**
* Date: 12/11/14
* Time: 8:33 PM<|fim▁hole|> */
public class AppConstants {
public static final String TEST_FILE = "dataset.csv";
}<|fim▁end|>
|
* To change this template use File | Settings | File Templates.
|
<|file_name|>Encoder.java<|end_file_name|><|fim▁begin|>/*
* Licensed to the Apache Software Foundation (ASF) under one<|fim▁hole|> * 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.accumulo.core.client.lexicoder;
/**
* An encoder represents a typed object that can be encoded/decoded to/from a byte array.
*
* @since 1.6.0
*/
public interface Encoder<T> {
byte[] encode(T object);
T decode(byte[] bytes) throws IllegalArgumentException;
}<|fim▁end|>
| |
<|file_name|>unwind-fail.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.
// error-pattern:fail
fn main() {
@0;<|fim▁hole|><|fim▁end|>
|
fail!();
}
|
<|file_name|>puback.rs<|end_file_name|><|fim▁begin|>//! PUBACK
use std::io::Read;
use crate::control::variable_header::PacketIdentifier;
use crate::control::{ControlType, FixedHeader, PacketType};
use crate::packet::{DecodablePacket, PacketError};
use crate::Decodable;
<|fim▁hole|>/// `PUBACK` packet
#[derive(Debug, Eq, PartialEq, Clone)]
pub struct PubackPacket {
fixed_header: FixedHeader,
packet_identifier: PacketIdentifier,
}
encodable_packet!(PubackPacket(packet_identifier));
impl PubackPacket {
pub fn new(pkid: u16) -> PubackPacket {
PubackPacket {
fixed_header: FixedHeader::new(PacketType::with_default(ControlType::PublishAcknowledgement), 2),
packet_identifier: PacketIdentifier(pkid),
}
}
pub fn packet_identifier(&self) -> u16 {
self.packet_identifier.0
}
pub fn set_packet_identifier(&mut self, pkid: u16) {
self.packet_identifier.0 = pkid;
}
}
impl DecodablePacket for PubackPacket {
type DecodePacketError = std::convert::Infallible;
fn decode_packet<R: Read>(reader: &mut R, fixed_header: FixedHeader) -> Result<Self, PacketError<Self>> {
let packet_identifier: PacketIdentifier = PacketIdentifier::decode(reader)?;
Ok(PubackPacket {
fixed_header,
packet_identifier,
})
}
}<|fim▁end|>
| |
<|file_name|>parsedir.py<|end_file_name|><|fim▁begin|># This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Written by John Hoffman and Uoti Urpala
import os
import hashlib
from Anomos.bencode import bencode, bdecode
from Anomos.btformats import check_message
NOISY = False
def parsedir(directory, parsed, files, blocked, errfunc,
include_metainfo=True):
if NOISY:
errfunc('checking dir')
dirs_to_check = [directory]
new_files = {}
new_blocked = {}
while dirs_to_check: # first, recurse directories and gather torrents
directory = dirs_to_check.pop()
newtorrents = False
try:
dir_contents = os.listdir(directory)
except (IOError, OSError), e:
errfunc("Could not read directory " + directory)
continue
for f in dir_contents:
if f.endswith('.atorrent'):
newtorrents = True
p = os.path.join(directory, f)
try:
new_files[p] = [(int(os.path.getmtime(p)),os.path.getsize(p)),0]
except (IOError, OSError), e:
errfunc("Could not stat " + p + " : " + str(e))
if not newtorrents:
for f in dir_contents:
p = os.path.join(directory, f)
if os.path.isdir(p):
dirs_to_check.append(p)
new_parsed = {}
to_add = []
added = {}
removed = {}
# files[path] = [(modification_time, size), hash], hash is 0 if the file
# has not been successfully parsed
for p,v in new_files.items(): # re-add old items and check for changes
oldval = files.get(p)
if oldval is None: # new file
to_add.append(p)
continue
h = oldval[1]
if oldval[0] == v[0]: # file is unchanged from last parse
if h:
if p in blocked: # parseable + blocked means duplicate
to_add.append(p) # other duplicate may have gone away
else:
new_parsed[h] = parsed[h]
new_files[p] = oldval
else:
new_blocked[p] = None # same broken unparseable file
continue
if p not in blocked and h in parsed: # modified; remove+add
if NOISY:
errfunc('removing '+p+' (will re-add)')
removed[h] = parsed[h]
to_add.append(p)
to_add.sort()
for p in to_add: # then, parse new and changed torrents
new_file = new_files[p]
v = new_file[0]
if new_file[1] in new_parsed: # duplicate
if p not in blocked or files[p][0] != v:
errfunc('**warning** '+ p + ' is a duplicate torrent for ' +
new_parsed[new_file[1]]['path'])
new_blocked[p] = None
continue
if NOISY:
errfunc('adding '+p)
try:
ff = open(p, 'rb')
d = bdecode(ff.read())
check_message(d)
h = hashlib.sha1(bencode(d['info'])).digest()
new_file[1] = h
if new_parsed.has_key(h):
errfunc('**warning** '+ p +
' is a duplicate torrent for '+new_parsed[h]['path'])
new_blocked[p] = None
continue
a = {}
a['path'] = p
f = os.path.basename(p)
a['file'] = f
i = d['info']
l = 0
nf = 0
if i.has_key('length'):
l = i.get('length',0)
nf = 1
elif i.has_key('files'):
for li in i['files']:
nf += 1
if li.has_key('length'):
l += li['length']
a['numfiles'] = nf
a['length'] = l
a['name'] = i.get('name', f)
def setkey(k, d = d, a = a):
if d.has_key(k):
a[k] = d[k]
setkey('failure reason')
setkey('warning message')
setkey('announce-list')
if include_metainfo:
a['metainfo'] = d<|fim▁hole|> try:
ff.close()
except:
pass
if NOISY:
errfunc('... successful')
new_parsed[h] = a
added[h] = a
for p,v in files.iteritems(): # and finally, mark removed torrents
if p not in new_files and p not in blocked:
if NOISY:
errfunc('removing '+p)
removed[v[1]] = parsed[v[1]]
if NOISY:
errfunc('done checking')
return (new_parsed, new_files, new_blocked, added, removed)<|fim▁end|>
|
except:
errfunc('**warning** '+p+' has errors')
new_blocked[p] = None
continue
|
<|file_name|>main.cpp<|end_file_name|><|fim▁begin|>/*******************************************************************************
Copyright (C) 2016 OLogN Technologies AG
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation.
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.
*******************************************************************************/
#include "idlc_include.h"
#include "front-back/idl_tree.h"
#include "back/idlc_back.h"
#include "front/idl/parser.h"<|fim▁hole|> unique_ptr<Root> root(new Root());
uint8_t baseBuff[0x10000];
FILE* in = fopen(fileName, "rb");
if (!in) {
fmt::print("Failed to open input file '{}'\n", fileName);
return nullptr;
}
size_t sz = fread(baseBuff, 1, 0x10000, in);
fclose(in);
IStream i(baseBuff, sz);
bool ok = deserializeRoot(*root, i);
return ok ? root.release() : nullptr;
}
struct CmdOptions {
vector<string> templs;
string templPath;
string inputIdl;
string inputBinary;
};
CmdOptions getCmdOptionFake()
{
CmdOptions result;
result.templPath = "../../Hare-IDL/src/targets/cpp/codegen/protobuf/";
result.templs = { "main.txt", "mapping.txt", "encoding.txt", "proto.txt",
"dbg_helpers.txt" };
// result.inputBinary = "../../Hare-IDL/test/targets/protobuf/poly-ptr/test.h.idlbin";
result.inputIdl = "../../Hare-IDL/test/targets/protobuf/idl-primitive/test.idl";
return result;
}
CmdOptions getCmdOption(char** begin, char** end)
{
if (begin != end) {
string current(*begin);
if (current == "--debug") {
return getCmdOptionFake();
}
}
CmdOptions result;
for (char** it = begin; it != end; ++it) {
string current(*it);
if (current.substr(0, 11) == "--template=")
result.templs.push_back(current.substr(11));
else if (current.substr(0, 15) == "--templatePath=")
result.templPath = current.substr(15);
else if (current.substr(0, 14) == "--inputBinary=")
result.inputBinary = current.substr(14);
else if (current.substr(0, 11) == "--inputIdl=")
result.inputIdl = current.substr(11);
else
fmt::print("Unrecognized command line option: {}\n", current);
}
return result;
}
int main(int argc, char* argv[])
{
try
{
HAREASSERT(argc >= 1);
CmdOptions opts = getCmdOption(argv + 1, argv + argc);
Root* root = 0;
if(!opts.inputIdl.empty()) {
root = parseSourceFile(opts.inputIdl, false);
}
else if (!opts.inputBinary.empty()) {
root = deserializeFile(opts.inputBinary.c_str());
}
else {
fmt::print("Missing input file name\n");
return 1;
}
HAREASSERT(root);
idlcBackEnd(*root, opts.templPath, opts.templs, false);
}
catch ( std::exception& x )
{
fmt::print( "Exception happened:\n{}\n", x.what() );
return 1;
}
return 0;
}<|fim▁end|>
|
#include "front-back/idl_tree_serializer.h"
Root* deserializeFile(const char* fileName) {
|
<|file_name|>quarantine_windows.go<|end_file_name|><|fim▁begin|>//go:build windows
// +build windows
package attachments
import (
"io/ioutil"<|fim▁hole|>
"golang.org/x/net/context"
)
func Quarantine(ctx context.Context, path string) error {
// Zones 0-4 correspond to Local Machine, Local intranet, Trusted sites, Internet, Restricted sites.
// https://docs.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/platform-apis/ms537183(v=vs.85)
return ioutil.WriteFile(path+":Zone.Identifier", []byte("[ZoneTransfer]\r\nZoneId=3"), 0644)
}<|fim▁end|>
| |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># Copyright 2013 Hewlett-Packard Development Company, L.P.
#
# Author: Kiall Mac Innes <[email protected]>
#
# 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
#<|fim▁hole|># 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 designate.api.v2 import patches # flake8: noqa
import pecan.deploy
from oslo.config import cfg
from designate.openstack.common import log as logging
LOG = logging.getLogger(__name__)
def factory(global_config, **local_conf):
if not cfg.CONF['service:api'].enable_api_v2:
def disabled_app(environ, start_response):
status = '404 Not Found'
start_response(status, [])
return []
return disabled_app
conf = {
'app': {
'root': 'designate.api.v2.controllers.root.RootController',
'modules': ['designate.api.v2']
}
}
app = pecan.deploy.deploy(conf)
return app<|fim▁end|>
| |
<|file_name|>bitcoin_fa_IR.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" ?><!DOCTYPE TS><TS language="fa_IR" version="2.0">
<defaultcodec>UTF-8</defaultcodec>
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About callcoin</source>
<translation>در مورد بیتکویین</translation>
</message>
<message>
<location line="+39"/>
<source><b>callcoin</b> version</source>
<translation><b>callcoin</b> version</translation>
</message>
<message>
<location line="+57"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young ([email protected]) and UPnP software written by Thomas Bernard.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../aboutdialog.cpp" line="+14"/>
<source>Copyright</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The callcoin developers</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>دفترچه آدرس</translation>
</message>
<message>
<location line="+19"/>
<source>Double-click to edit address or label</source>
<translation>برای ویرایش آدرس/برچسب دوبار کلیک نمایید</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>یک آدرس جدید بسازید</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>آدرس انتخاب شده را در کلیپ بوردِ سیستم کپی کنید</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation>و آدرس جدید</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+63"/>
<source>These are your callcoin 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 filename="../forms/addressbookpage.ui" line="+14"/>
<source>&Copy Address</source>
<translation>و کپی آدرس</translation>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation>نشان و کد QR</translation>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a callcoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Export the data in the current tab to a file</source>
<translation>صدور داده نوار جاری به یک فایل</translation>
</message>
<message>
<location line="+3"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-44"/>
<source>Verify a message to ensure it was signed with a specified callcoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>و حذف</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="-5"/>
<source>These are your callcoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Copy &Label</source>
<translation>کپی و برچسب</translation>
</message>
<message>
<location line="+1"/>
<source>&Edit</source>
<translation>و ویرایش</translation>
</message>
<message>
<location line="+1"/>
<source>Send &Coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+260"/>
<source>Export Address Book Data</source>
<translation>انتقال اطلاعات دفترچه آدرس</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>سی.اس.وی. (فایل جداگانه دستوری)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>صدور پیام خطا</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>قابل کپی در فایل نیست %1</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>برچسب</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>آدرس</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(برچسب ندارد)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>رمز/پَس فرِیز را وارد کنید</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>رمز/پَس فرِیز جدید را وارد کنید</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>رمز/پَس فرِیز را دوباره وارد کنید</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+33"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation>رمز/پَس فرِیز جدید را در wallet وارد کنید. برای انتخاب رمز/پَس فرِیز از 10 کاراکتر تصادفی یا بیشتر و یا هشت کلمه یا بیشتر استفاده کنید. </translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>wallet را رمزگذاری کنید</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>برای انجام این عملکرد به رمز/پَس فرِیزِwallet نیاز است تا آن را از حالت قفل درآورد.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>باز کردن قفل wallet </translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>برای کشف رمز wallet، به رمز/پَس فرِیزِwallet نیاز است.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>کشف رمز wallet</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>تغییر رمز/پَس فرِیز</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>رمز/پَس فرِیزِ قدیم و جدید را در wallet وارد کنید</translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>رمزگذاری wallet را تایید کنید</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR SKEINCOINS</b>!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation type="unfinished"/>
</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="+100"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-130"/>
<location line="+58"/>
<source>Wallet encrypted</source>
<translation>تایید رمزگذاری</translation>
</message>
<message>
<location line="-56"/>
<source>callcoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your callcoins from being stolen by malware infecting your computer.</source>
<translation>callcoin برای اتمام فرایند رمزگذاری بسته خواهد شد. به خاطر داشته باشید که رمزگذاری WALLET شما، کامپیوتر شما را از آلودگی به بدافزارها مصون نمی دارد.</translation>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+42"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>رمزگذاری تایید نشد</translation>
</message>
<message>
<location line="-54"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>رمزگذاری به علت خطای داخلی تایید نشد. wallet شما رمزگذاری نشد</translation>
</message>
<message>
<location line="+7"/>
<location line="+48"/>
<source>The supplied passphrases do not match.</source>
<translation>رمزهای/پَس فرِیزهایِ وارد شده با هم تطابق ندارند</translation>
</message>
<message>
<location line="-37"/>
<source>Wallet unlock failed</source>
<translation>قفل wallet باز نشد</translation>
</message>
<message>
<location line="+1"/>
<location line="+11"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>رمزهای/پَس فرِیزهایِ وارد شده wallet برای کشف رمز اشتباه است.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>کشف رمز wallet انجام نشد</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+233"/>
<source>Sign &message...</source>
<translation>امضا و پیام</translation>
</message>
<message>
<location line="+280"/>
<source>Synchronizing with network...</source>
<translation>به روز رسانی با شبکه...</translation>
</message>
<message>
<location line="-349"/>
<source>&Overview</source>
<translation>و بازبینی</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation>نمای کلی از wallet را نشان بده</translation>
</message>
<message>
<location line="+20"/>
<source>&Transactions</source>
<translation>و تراکنش</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>تاریخچه تراکنش را باز کن</translation>
</message>
<message>
<location line="+7"/>
<source>Edit the list of stored addresses and labels</source>
<translation>فهرست آدرسها و برچسبهای ذخیره شده را ویرایش کن</translation>
</message>
<message>
<location line="-14"/>
<source>Show the list of addresses for receiving payments</source>
<translation>فهرست آدرسها را برای دریافت وجه نشان بده</translation>
</message>
<message>
<location line="+31"/>
<source>E&xit</source>
<translation>خروج</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>از "درخواست نامه"/ application خارج شو</translation>
</message>
<message>
<location line="+4"/>
<source>Show information about callcoin</source>
<translation>اطلاعات در مورد callcoin را نشان بده</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>درباره و QT</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>نمایش اطلاعات درباره QT</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>و انتخابها</translation>
</message>
<message>
<location line="+6"/>
<source>&Encrypt Wallet...</source>
<translation>و رمزگذاری wallet</translation>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation>و گرفتن نسخه پیشتیبان از wallet</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>تغییر رمز/پَس فرِیز</translation>
</message>
<message>
<location line="+285"/>
<source>Importing blocks from disk...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Reindexing blocks on disk...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-347"/>
<source>Send coins to a callcoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>Modify configuration options for callcoin</source>
<translation>اصلاح انتخابها برای پیکربندی callcoin</translation>
</message>
<message>
<location line="+9"/>
<source>Backup wallet to another location</source>
<translation>گرفتن نسخه پیشتیبان در آدرسی دیگر</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>رمز مربوط به رمزگذاریِ wallet را تغییر دهید</translation>
</message>
<message>
<location line="+6"/>
<source>&Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-4"/>
<source>&Verify message...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-165"/>
<location line="+530"/>
<source>callcoin</source>
<translation>callcoin</translation>
</message>
<message>
<location line="-530"/>
<source>Wallet</source>
<translation>کیف پول</translation>
</message>
<message>
<location line="+101"/>
<source>&Send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Receive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>&Addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>&About callcoin</source>
<translation>&در مورد بیتکویین</translation>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation>&نمایش/ عدم نمایش و</translation>
</message>
<message>
<location line="+1"/>
<source>Show or hide the main Window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Encrypt the private keys that belong to your wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Sign messages with your callcoin addresses to prove you own them</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Verify messages to ensure they were signed with specified callcoin addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>&File</source>
<translation>و فایل</translation>
</message>
<message>
<location line="+7"/>
<source>&Settings</source>
<translation>و تنظیمات</translation>
</message>
<message>
<location line="+6"/>
<source>&Help</source>
<translation>و راهنما</translation>
</message>
<message>
<location line="+9"/>
<source>Tabs toolbar</source>
<translation>نوار ابزار</translation>
</message>
<message>
<location line="+17"/>
<location line="+10"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
<message>
<location line="+47"/>
<source>callcoin client</source>
<translation>مشتری callcoin</translation>
</message>
<message numerus="yes">
<location line="+141"/>
<source>%n active connection(s) to callcoin network</source>
<translation><numerusform>%n ارتباط فعال به شبکه callcoin
%n ارتباط فعال به شبکه callcoin</numerusform></translation>
</message>
<message>
<location line="+22"/>
<source>No block source available...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Processed %1 of %2 (estimated) blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Processed %1 blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+20"/>
<source>%n hour(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n week(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>%1 behind</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Last received block was generated %1 ago.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Transactions after this will not yet be visible.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>Error</source>
<translation 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="+70"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-140"/>
<source>Up to date</source>
<translation>روزآمد</translation>
</message>
<message>
<location line="+31"/>
<source>Catching up...</source>
<translation>در حال روزآمد سازی..</translation>
</message>
<message>
<location line="+113"/>
<source>Confirm transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Sent transaction</source>
<translation>ارسال تراکنش</translation>
</message>
<message>
<location line="+0"/>
<source>Incoming transaction</source>
<translation>تراکنش دریافتی</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>تاریخ: %1⏎ میزان وجه : %2⏎ نوع: %3⏎ آدرس: %4⏎
</translation>
</message>
<message>
<location line="+33"/>
<location line="+23"/>
<source>URI handling</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-23"/>
<location line="+23"/>
<source>URI can not be parsed! This can be caused by an invalid callcoin address or malformed URI parameters.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>wallet رمزگذاری شد و در حال حاضر از حالت قفل در آمده است</translation>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>wallet رمزگذاری شد و در حال حاضر قفل است</translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="+111"/>
<source>A fatal error occurred. callcoin can no longer continue safely and will quit.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+104"/>
<source>Network Alert</source>
<translation>هشدار شبکه</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>ویرایش آدرسها</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>و برچسب</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation>برچسب مربوط به این دفترچه آدرس</translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>و آدرس</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>برچسب مربوط به این دفترچه آدرس و تنها ب</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+21"/>
<source>New receiving address</source>
<translation>آدرسِ دریافت کننده جدید</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>آدرس ارسال کننده جدید</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>ویرایش آدرسِ دریافت کننده</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>ویرایش آدرسِ ارسال کننده</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>آدرس وارد شده %1 قبلا به فهرست آدرسها اضافه شده بوده است.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid callcoin address.</source>
<translation>آدرس وارد شده "%1" یک آدرس صحیح برای callcoin نسشت</translation>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>عدم توانیی برای قفل گشایی wallet</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>عدم توانیی در ایجاد کلید جدید</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+424"/>
<location line="+12"/>
<source>callcoin-Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation>نسخه</translation>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation>میزان استفاده:</translation>
</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 "de_DE" (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>انتخاب/آپشن</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Automatically start callcoin after logging in to the system.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Start callcoin on system login</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Reset all client options to default.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Reset Options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>&Network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Automatically open the callcoin 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 &UPnP</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Connect to the callcoin network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation type="unfinished"/>
</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>&Port:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting callcoin.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Whether to show callcoin addresses in the transaction list or not.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation>و نمایش آدرسها در فهرست تراکنش</translation>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>و تایید</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>و رد</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation>و به کار گرفتن</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+53"/>
<source>default</source>
<translation>پیش فرض</translation>
</message>
<message>
<location line="+130"/>
<source>Confirm options reset</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Some settings may require a client restart to take effect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Do you want to proceed?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+42"/>
<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 callcoin.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>فرم</translation>
</message>
<message>
<location line="+50"/>
<location line="+166"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the callcoin network after a connection is established, but this process has not completed yet.</source>
<translation>اطلاعات نمایش داده شده ممکن است روزآمد نباشد. wallet شما به صورت خودکار بعد از برقراری اتصال با شبکه callcoin به روز می شود اما این فرایند هنوز تکمیل نشده است.</translation>
</message>
<message>
<location line="-124"/>
<source>Balance:</source>
<translation>مانده حساب:</translation>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation>تایید نشده</translation>
</message>
<message>
<location line="-78"/>
<source>Wallet</source>
<translation>کیف پول</translation>
</message>
<message>
<location line="+107"/>
<source>Immature:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation>تراکنشهای اخیر</translation>
</message>
<message>
<location line="-101"/>
<source>Your current balance</source>
<translation>مانده حساب جاری</translation>
</message>
<message>
<location line="+29"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation>تعداد تراکنشهایی که نیاز به تایید دارند و هنوز در مانده حساب جاری شما به حساب نیامده اند</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="+116"/>
<location line="+1"/>
<source>out of sync</source>
<translation>خارج از روزآمد سازی</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+107"/>
<source>Cannot start callcoin: 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>درخواست وجه</translation>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation>میزان وجه:</translation>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation>برچسب:</translation>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation>پیام:</translation>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation>و ذخیره با عنوانِ...</translation>
</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>متن وارد شده طولانی است، متنِ برچسب/پیام را کوتاه کنید</translation>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation>تصاویر با فرمت PNG
(*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<location line="+23"/>
<location filename="../rpcconsole.cpp" line="+339"/>
<source>N/A</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Show the callcoin-Qt help message to get a list with possible callcoin command-line options.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-104"/>
<source>callcoin - Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>callcoin Core</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Open the callcoin 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 type="unfinished"/>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-30"/>
<source>Welcome to the callcoin RPC console.</source>
<translation>به کنسول آر.پی.سی. SKEINCOIN خوش آمدید</translation>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+124"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>سکه های ارسالی</translation>
</message>
<message>
<location line="+50"/>
<source>Send to multiple recipients at once</source>
<translation>ارسال همزمان به گیرنده های متعدد</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation>تمامی فیلدهای تراکنش حذف شوند</translation>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>Balance:</source>
<translation>مانده حساب:</translation>
</message>
<message>
<location line="+10"/>
<source>123.456 BTC</source>
<translation>123.456 BTC</translation>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation>تایید عملیات ارسال </translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation>و ارسال</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-59"/>
<source><b>%1</b> to %2 (%3)</source>
<translation>%1 به %2 (%3)</translation>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>تایید ارسال سکه ها</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation>شما مطمئن هستید که می خواهید %1 را ارسال کنید؟</translation>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation>و</translation>
</message>
<message>
<location line="+23"/>
<source>The recipient address is not valid, please recheck.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>میزان پرداخت باید بیشتر از 0 باشد</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation type="unfinished"/>
</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>خطا: تراکنش تایید نشد. این خطا ممکن است به این دلیل اتفاق بیافتد که سکه های wallet شما خرج شده باشند مثلا اگر wallet.dat را مپی کرده باشید و سکه های شما در آن کپی استفاده شده باشند اما در اینجا نمایش داده نشده اند.</translation><|fim▁hole|> <name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation>فرم</translation>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation>و میزان وجه</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>پرداخت و به چه کسی</translation>
</message>
<message>
<location line="+34"/>
<source>The address to send the payment to (e.g. X6ENACNZSWAvxM96TiGp3Du9YhVmbhweMa)</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>یک برچسب برای این آدرس بنویسید تا به دفترچه آدرسهای شما اضافه شود</translation>
</message>
<message>
<location line="-78"/>
<source>&Label:</source>
<translation>و برچسب</translation>
</message>
<message>
<location line="+28"/>
<source>Choose address from address book</source>
<translation>آدرس از فهرست آدرس انتخاب کنید</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation>Alt و A</translation>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation>آدرس را بر کلیپ بورد کپی کنید</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>این گیرنده را حذف کن</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a callcoin address (e.g. X6ENACNZSWAvxM96TiGp3Du9YhVmbhweMa)</source>
<translation>یک آدرس callcoin وارد کنید (مثال X6ENACNZSWAvxM96TiGp3Du9YhVmbhweMa)</translation>
</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"/>
<source>&Sign Message</source>
<translation>و امضای پیام </translation>
</message>
<message>
<location line="+6"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. X6ENACNZSWAvxM96TiGp3Du9YhVmbhweMa)</source>
<translation>یک آدرس callcoin وارد کنید (مثال X6ENACNZSWAvxM96TiGp3Du9YhVmbhweMa)</translation>
</message>
<message>
<location line="+10"/>
<location line="+213"/>
<source>Choose an address from the address book</source>
<translation>آدرس از فهرست آدرس انتخاب کنید</translation>
</message>
<message>
<location line="-203"/>
<location line="+213"/>
<source>Alt+A</source>
<translation>Alt و A</translation>
</message>
<message>
<location line="-203"/>
<source>Paste address from clipboard</source>
<translation>آدرس را بر کلیپ بورد کپی کنید</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 type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<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 callcoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Reset all sign message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-87"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. X6ENACNZSWAvxM96TiGp3Du9YhVmbhweMa)</source>
<translation>یک آدرس callcoin وارد کنید (مثال X6ENACNZSWAvxM96TiGp3Du9YhVmbhweMa)</translation>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified callcoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Verify &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Reset all verify message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a callcoin address (e.g. X6ENACNZSWAvxM96TiGp3Du9YhVmbhweMa)</source>
<translation>یک آدرس callcoin وارد کنید (مثال X6ENACNZSWAvxM96TiGp3Du9YhVmbhweMa)</translation>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Enter callcoin signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<location filename="../splashscreen.cpp" line="+25"/>
<source>The callcoin developers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+20"/>
<source>Open until %1</source>
<translation>باز کن تا %1</translation>
</message>
<message>
<location line="+6"/>
<source>%1/offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1 غیرقابل تایید</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 تاییدها</translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>تاریخ</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation>برچسب</translation>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>پیام</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won'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 type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Inputs</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation>میزان</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-209"/>
<source>, has not been successfully broadcast yet</source>
<translation>تا به حال با موفقیت انتشار نیافته است</translation>
</message>
<message numerus="yes">
<location line="-35"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+70"/>
<source>unknown</source>
<translation>ناشناس</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>جزئیات تراکنش</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>این بخش جزئیات تراکنش را نشان می دهد</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+225"/>
<source>Date</source>
<translation>تاریخ</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>نوع</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>آدرس</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>میزان وجه</translation>
</message>
<message numerus="yes">
<location line="+57"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+3"/>
<source>Open until %1</source>
<translation>باز کن تا %1</translation>
</message>
<message>
<location line="+3"/>
<source>Offline (%1 confirmations)</source>
<translation>برون خطی (%1 تاییدها)</translation>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation>تایید نشده (%1 از %2 تاییدها)</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed (%1 confirmations)</source>
<translation>تایید شده (%1 تاییدها)</translation>
</message>
<message numerus="yes">
<location line="+8"/>
<source>Mined balance will be available when it matures in %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+5"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>این block توسط گره های دیگری دریافت نشده است و ممکن است قبول نشود</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>تولید شده اما قبول نشده است</translation>
</message>
<message>
<location line="+43"/>
<source>Received with</source>
<translation>قبول با </translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>دریافت شده از</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>ارسال به</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>وجه برای شما </translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>استخراج شده</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>خالی</translation>
</message>
<message>
<location line="+199"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>وضعیت تراکنش. با اشاره به این بخش تعداد تاییدها نمایش داده می شود</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>زمان و تاریخی که تراکنش دریافت شده است</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>نوع تراکنش</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>آدرس مقصد در تراکنش</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>میزان وجه کم شده یا اضافه شده به حساب</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+52"/>
<location line="+16"/>
<source>All</source>
<translation>همه</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>امروز</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>این هفته</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>این ماه</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>ماه گذشته</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>این سال</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>حدود..</translation>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation>دریافت با</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>ارسال به</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>به شما</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>استخراج شده</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>دیگر</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>آدرس یا برچسب را برای جستجو وارد کنید</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>حداقل میزان وجه</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>آدرس را کپی کنید</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>برچسب را کپی کنید</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>میزان وجه کپی شود</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>برچسب را ویرایش کنید</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+139"/>
<source>Export Transaction Data</source>
<translation>داده های تراکنش را صادر کنید</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Comma separated file (*.csv) فایل جداگانه دستوری</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>تایید شده</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>تاریخ</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>نوع</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>برچسب</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>آدرس</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>میزان</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>شناسه کاربری</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>خطا در ارسال</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>قابل کپی به فایل نیست %1.</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>دامنه:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>به</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+193"/>
<source>Send Coins</source>
<translation>سکه های ارسالی</translation>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<location filename="../walletview.cpp" line="+42"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Export the data in the current tab to a file</source>
<translation>صدور داده نوار جاری به یک فایل</translation>
</message>
<message>
<location line="+193"/>
<source>Backup Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation 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>
<location line="+4"/>
<source>Backup Successful</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The wallet data was successfully saved to the new location.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+94"/>
<source>callcoin version</source>
<translation>نسخه callcoin</translation>
</message>
<message>
<location line="+102"/>
<source>Usage:</source>
<translation>میزان استفاده:</translation>
</message>
<message>
<location line="-29"/>
<source>Send command to -server or callcoind</source>
<translation>ارسال دستور به سرور یا callcoined</translation>
</message>
<message>
<location line="-23"/>
<source>List commands</source>
<translation>فهرست دستورها</translation>
</message>
<message>
<location line="-12"/>
<source>Get help for a command</source>
<translation>درخواست کمک برای یک دستور</translation>
</message>
<message>
<location line="+24"/>
<source>Options:</source>
<translation>انتخابها:</translation>
</message>
<message>
<location line="+24"/>
<source>Specify configuration file (default: callcoin.conf)</source>
<translation>فایل پیکربندیِ را مشخص کنید (پیش فرض: callcoin.conf)</translation>
</message>
<message>
<location line="+3"/>
<source>Specify pid file (default: callcoind.pid)</source>
<translation>فایل pid را مشخص کنید (پیش فرض: callcoind.pid)</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>دایرکتوری داده را مشخص کن</translation>
</message>
<message>
<location line="-9"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>حافظه بانک داده را به مگابایت تنظیم کنید (پیش فرض: 25)</translation>
</message>
<message>
<location line="-28"/>
<source>Listen for connections on <port> (default: 8333 or testnet: 18333)</source>
<translation>ارتباطات را در <PORT> بشنوید (پیش فرض: 8333 or testnet: 18333)</translation>
</message>
<message>
<location line="+5"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>نگهداری <N> ارتباطات برای قرینه سازی (پیش فرض:125)</translation>
</message>
<message>
<location line="-48"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<source>Specify your own public address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>آستانه قطع برای قرینه سازی اشتباه (پیش فرض:100)</translation>
</message>
<message>
<location line="-134"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>تعداد ثانیه ها برای اتصال دوباره قرینه های اشتباه (پیش فرض:86400)</translation>
</message>
<message>
<location line="-29"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Listen for JSON-RPC connections on <port> (default: 8332 or testnet: 18332)</source>
<translation>ارتباطاتِ JSON-RPC را در <port> گوش کنید (پیش فرض:8332)</translation>
</message>
<message>
<location line="+37"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>command line و JSON-RPC commands را قبول کنید</translation>
</message>
<message>
<location line="+76"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>به عنوان daemon بک گراند را اجرا کنید و دستورات را قبول نمایید</translation>
</message>
<message>
<location line="+37"/>
<source>Use the test network</source>
<translation>از تستِ شبکه استفاده نمایید</translation>
</message>
<message>
<location line="-112"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-80"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=callcoinrpc
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 "callcoin Alert" [email protected]
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. callcoin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong callcoin will not work properly.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Block creation options:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Connect only to the specified node(s)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Corrupted block database detected</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Do you want to rebuild the block database now?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error initializing block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error initializing wallet database environment %s!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error loading block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error opening block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error: Disk space is low!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: Wallet locked, unable to create transaction!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: system error: </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to read block info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to read block</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to sync block index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write file info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write to coin database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write transaction index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write undo data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Find peers using DNS lookup (default: 1 unless -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Generate coins (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 288, 0 = all)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-4, default: 3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Not enough file descriptors available.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Rebuild block chain index from current blk000??.dat files</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+26"/>
<source>Verifying blocks...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Verifying wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-69"/>
<source>Imports blocks from external blk000??.dat file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-76"/>
<source>Set the number of script verification threads (up to 16, 0 = auto, <0 = leave that many cores free, default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+77"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Invalid -tor address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -minrelaytxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -mintxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Maintain a full transaction index (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Only accept block chain matching built-in checkpoints (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Prepend debug output with timestamp</source>
<translation>برونداد اشکال زدایی با timestamp</translation>
</message>
<message>
<location line="+5"/>
<source>SSL options: (see the callcoin Wiki for SSL setup instructions)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>ارسال اطلاعات پیگیری/خطایابی به کنسول به جای ارسال به فایل debug.log</translation>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation>ارسال اطاعات خطایابی/پیگیری به سیستم خطایاب</translation>
</message>
<message>
<location line="+5"/>
<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="+2"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Signing transaction failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation>تعیین مدت زمان وقفه (time out) به هزارم ثانیه</translation>
</message>
<message>
<location line="+4"/>
<source>System error: </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Transaction amount too small</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction amounts must be positive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction too large</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Username for JSON-RPC connections</source>
<translation>شناسه کاربری برای ارتباطاتِ JSON-RPC</translation>
</message>
<message>
<location line="+4"/>
<source>Warning</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="+1"/>
<source>You need to rebuild the databases using -reindex to change -txindex</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-50"/>
<source>Password for JSON-RPC connections</source>
<translation>رمز برای ارتباطاتِ JSON-RPC</translation>
</message>
<message>
<location line="-67"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>ارتباطاتِ JSON-RPC را از آدرس آی.پی. مشخصی برقرار کنید.</translation>
</message>
<message>
<location line="+76"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>دستورات را به گره اجرا شده در<ip> ارسال کنید (پیش فرض:127.0.0.1)</translation>
</message>
<message>
<location line="-120"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>دستور را وقتی بهترین بلاک تغییر کرد اجرا کن (%s در دستور توسط block hash جایگزین شده است)</translation>
</message>
<message>
<location line="+147"/>
<source>Upgrade wallet to latest format</source>
<translation>wallet را به جدیدترین نسخه روزآمد کنید</translation>
</message>
<message>
<location line="-21"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>حجم key pool را به اندازه <n> تنظیم کنید (پیش فرض:100)</translation>
</message>
<message>
<location line="-12"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>زنجیره بلاک را برای تراکنش جا افتاده در WALLET دوباره اسکن کنید</translation>
</message>
<message>
<location line="+35"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>برای ارتباطاتِ JSON-RPC از OpenSSL (https) استفاده کنید</translation>
</message>
<message>
<location line="-26"/>
<source>Server certificate file (default: server.cert)</source>
<translation>فایل certificate سرور (پیش فرض server.cert)</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>رمز اختصاصی سرور (پیش فرض: server.pem)</translation>
</message>
<message>
<location line="-151"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation>ciphers قابل قبول (پیش فرض: default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation>
</message>
<message>
<location line="+165"/>
<source>This help message</source>
<translation>این پیام راهنما</translation>
</message>
<message>
<location line="+6"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-91"/>
<source>Connect through socks proxy</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-10"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+55"/>
<source>Loading addresses...</source>
<translation>لود شدن آدرسها..</translation>
</message>
<message>
<location line="-35"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>خطا در هنگام لود شدن wallet.dat: Wallet corrupted</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat: Wallet requires newer version of callcoin</source>
<translation>خطا در هنگام لود شدن wallet.dat. به نسخه جدید callcoin برای wallet نیاز است.</translation>
</message>
<message>
<location line="+93"/>
<source>Wallet needed to be rewritten: restart callcoin to complete</source>
<translation>wallet نیاز به بازنویسی دارد. callcoin را برای تکمیل عملیات دوباره اجرا کنید.</translation>
</message>
<message>
<location line="-95"/>
<source>Error loading wallet.dat</source>
<translation>خطا در هنگام لود شدن wallet.dat</translation>
</message>
<message>
<location line="+28"/>
<source>Invalid -proxy address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+56"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-96"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+44"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>میزان اشتباه است for -paytxfee=<amount>: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount</source>
<translation>میزان اشتباه است</translation>
</message>
<message>
<location line="-6"/>
<source>Insufficient funds</source>
<translation>وجوه ناکافی</translation>
</message>
<message>
<location line="+10"/>
<source>Loading block index...</source>
<translation>لود شدن نمایه بلاکها..</translation>
</message>
<message>
<location line="-57"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>یک گره برای اتصال اضافه کنید و تلاش کنید تا اتصال را باز نگاه دارید</translation>
</message>
<message>
<location line="-25"/>
<source>Unable to bind to %s on this computer. callcoin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+64"/>
<source>Fee per KB to add to transactions you send</source>
<translation>هزینه بر اساس کیلو بایت برای اضافه شدن به تراکنشی که ارسال کرده اید</translation>
</message>
<message>
<location line="+19"/>
<source>Loading wallet...</source>
<translation>wallet در حال لود شدن است...</translation>
</message>
<message>
<location line="-52"/>
<source>Cannot downgrade wallet</source>
<translation>قابلیت برگشت به نسخه قبلی برای wallet امکان پذیر نیست</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot write default address</source>
<translation>آدرس پیش فرض قابل ذخیره نیست</translation>
</message>
<message>
<location line="+64"/>
<source>Rescanning...</source>
<translation>اسکنِ دوباره...</translation>
</message>
<message>
<location line="-57"/>
<source>Done loading</source>
<translation>اتمام لود شدن</translation>
</message>
<message>
<location line="+82"/>
<source>To use the %s option</source>
<translation>برای استفاده از %s از اختیارات</translation>
</message>
<message>
<location line="-74"/>
<source>Error</source>
<translation>خطا</translation>
</message>
<message>
<location line="-31"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation>شما باید یک رمز rpcpassword=<password> را در فایل تنظیمات ایجاد کنید⏎ %s ⏎ اگر فایل ایجاد نشده است، آن را با یک فایل "فقط متنی" ایجاد کنید.
</translation>
</message>
</context>
</TS><|fim▁end|>
|
</message>
</context>
<context>
|
<|file_name|>group_specs.py<|end_file_name|><|fim▁begin|># Copyright (c) 2016 EMC Corporation
#
# 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.
"""The group types specs controller"""
import webob
from cinder.api import common
from cinder.api.openstack import wsgi
from cinder import db
from cinder import exception
from cinder.i18n import _
from cinder import policy
from cinder import rpc
from cinder import utils
from cinder.volume import group_types
class GroupTypeSpecsController(wsgi.Controller):
"""The group type specs API controller for the OpenStack API."""
def _check_policy(self, context):
target = {
'project_id': context.project_id,
'user_id': context.user_id,
}
policy.enforce(context, 'group:group_types_specs', target)
def _get_group_specs(self, context, group_type_id):
group_specs = db.group_type_specs_get(context, group_type_id)
specs_dict = {}
for key, value in group_specs.items():
specs_dict[key] = value
return dict(group_specs=specs_dict)
def _check_type(self, context, group_type_id):
try:
group_types.get_group_type(context, group_type_id)
except exception.GroupTypeNotFound as ex:
raise webob.exc.HTTPNotFound(explanation=ex.msg)
@wsgi.Controller.api_version('3.11')
def index(self, req, group_type_id):
"""Returns the list of group specs for a given group type."""
context = req.environ['cinder.context']
self._check_policy(context)
self._check_type(context, group_type_id)
return self._get_group_specs(context, group_type_id)
@wsgi.Controller.api_version('3.11')
@wsgi.response(202)
def create(self, req, group_type_id, body=None):
context = req.environ['cinder.context']
self._check_policy(context)
self.assert_valid_body(body, 'group_specs')
self._check_type(context, group_type_id)
specs = body['group_specs']
self._check_key_names(specs.keys())
utils.validate_dictionary_string_length(specs)
db.group_type_specs_update_or_create(context,
group_type_id,
specs)
notifier_info = dict(type_id=group_type_id, specs=specs)
notifier = rpc.get_notifier('groupTypeSpecs')
notifier.info(context, 'group_type_specs.create',
notifier_info)
return body
@wsgi.Controller.api_version('3.11')
def update(self, req, group_type_id, id, body=None):
context = req.environ['cinder.context']
self._check_policy(context)
if not body:
expl = _('Request body empty')
raise webob.exc.HTTPBadRequest(explanation=expl)
self._check_type(context, group_type_id)
if id not in body:
expl = _('Request body and URI mismatch')
raise webob.exc.HTTPBadRequest(explanation=expl)
if len(body) > 1:
expl = _('Request body contains too many items')
raise webob.exc.HTTPBadRequest(explanation=expl)
self._check_key_names(body.keys())
utils.validate_dictionary_string_length(body)
db.group_type_specs_update_or_create(context,
group_type_id,
body)
notifier_info = dict(type_id=group_type_id, id=id)
notifier = rpc.get_notifier('groupTypeSpecs')
notifier.info(context,
'group_type_specs.update',
notifier_info)
return body
@wsgi.Controller.api_version('3.11')
def show(self, req, group_type_id, id):
"""Return a single extra spec item."""
context = req.environ['cinder.context']
self._check_policy(context)
self._check_type(context, group_type_id)
specs = self._get_group_specs(context, group_type_id)
if id in specs['group_specs']:
return {id: specs['group_specs'][id]}
else:
msg = _("Group Type %(type_id)s has no extra spec with key "
"%(id)s.") % ({'type_id': group_type_id, 'id': id})
raise webob.exc.HTTPNotFound(explanation=msg)
@wsgi.Controller.api_version('3.11')
def delete(self, req, group_type_id, id):
"""Deletes an existing group spec."""
context = req.environ['cinder.context']
self._check_policy(context)
self._check_type(context, group_type_id)
try:
db.group_type_specs_delete(context, group_type_id, id)
except exception.GroupTypeSpecsNotFound as error:
raise webob.exc.HTTPNotFound(explanation=error.msg)
notifier_info = dict(type_id=group_type_id, id=id)
notifier = rpc.get_notifier('groupTypeSpecs')
notifier.info(context,
'group_type_specs.delete',
notifier_info)
return webob.Response(status_int=202)
def _check_key_names(self, keys):
if not common.validate_key_names(keys):
expl = _('Key names can only contain alphanumeric characters, '
'underscores, periods, colons and hyphens.')<|fim▁hole|> raise webob.exc.HTTPBadRequest(explanation=expl)
def create_resource():
return wsgi.Resource(GroupTypeSpecsController())<|fim▁end|>
| |
<|file_name|>app.module.ts<|end_file_name|><|fim▁begin|>import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpModule, JsonpModule } from '@angular/http';
import { routing } from './app.routing';
import { AppComponent } from './components/app.component';
import { LoginModalComponent } from "./components/login-modal.component";
import { HomeComponent } from "./components/home.component";
import { MainNavComponent } from "./components/main-nav.component";
import { SecondPotComponent } from "./components/second-pot.component";
import { AuthService } from "./services/auth.service";
import { SettingsService } from "./services/settings.service";
import { PlayersService } from "./services/players.service";
import { Ng2Bs3ModalModule } from 'ng2-bs3-modal/ng2-bs3-modal';
import {CommonModule} from "@angular/common";
@NgModule({
imports: [
CommonModule,
BrowserModule,
FormsModule,
routing,
Ng2Bs3ModalModule,
HttpModule,
JsonpModule
],
declarations: [
AppComponent,
LoginModalComponent,
HomeComponent,
MainNavComponent,
SecondPotComponent
],
providers: [
AuthService,<|fim▁hole|>})
export class AppModule { }<|fim▁end|>
|
SettingsService,
PlayersService
],
bootstrap: [ AppComponent ]
|
<|file_name|>project.py<|end_file_name|><|fim▁begin|># project.py
import signac
def classify(job):
yield 'init'
if 'V' in job.document:
yield 'volume-computed'
def next_operation(job):
if 'volume-computed' not in classify(job):
return 'compute_volume'
if __name__ == '__main__':
project = signac.get_project()
print(project)<|fim▁hole|>
for job in project.find_jobs():
labels = ','.join(classify(job))
p = '{:04.1f}'.format(job.statepoint()['p'])
print(job, p, labels)<|fim▁end|>
| |
<|file_name|>RDFGraphListURIPrefixKernel.java<|end_file_name|><|fim▁begin|>package org.data2semantics.mustard.rdfvault;
import java.util.List;
import java.util.Set;
import org.data2semantics.mustard.kernels.ComputationTimeTracker;
import org.data2semantics.mustard.kernels.FeatureInspector;
import org.data2semantics.mustard.kernels.KernelUtils;
import org.data2semantics.mustard.kernels.data.RDFData;
import org.data2semantics.mustard.kernels.data.SingleDTGraph;
import org.data2semantics.mustard.kernels.graphkernels.FeatureVectorKernel;
import org.data2semantics.mustard.kernels.graphkernels.GraphKernel;
import org.data2semantics.mustard.kernels.graphkernels.singledtgraph.DTGraphGraphListWLSubTreeKernel;
import org.data2semantics.mustard.kernels.SparseVector;
import org.data2semantics.mustard.rdf.RDFDataSet;
import org.data2semantics.mustard.rdf.RDFUtils;
import org.openrdf.model.Resource;
import org.openrdf.model.Statement;
public class RDFGraphListURIPrefixKernel implements GraphKernel<RDFData>, FeatureVectorKernel<RDFData>, ComputationTimeTracker {
private int depth;
private boolean inference;
private DTGraphGraphListURIPrefixKernel kernel;
private SingleDTGraph graph;
public RDFGraphListURIPrefixKernel(double lambda, int depth, boolean inference, boolean normalize) {
super();
this.depth = depth;
this.inference = inference;
kernel = new DTGraphGraphListURIPrefixKernel(lambda, depth, normalize);
}
public String getLabel() {
return KernelUtils.createLabel(this) + "_" + kernel.getLabel();
}
public void setNormalize(boolean normalize) {
kernel.setNormalize(normalize);
}
public SparseVector[] computeFeatureVectors(RDFData data) {
init(data.getDataset(), data.getInstances(), data.getBlackList());
return kernel.computeFeatureVectors(graph);
}
public double[][] compute(RDFData data) {
init(data.getDataset(), data.getInstances(), data.getBlackList());
return kernel.compute(graph);
}
private void init(RDFDataSet dataset, List<Resource> instances, List<Statement> blackList) {
Set<Statement> stmts = RDFUtils.getStatements4Depth(dataset, instances, depth, inference);
<|fim▁hole|>
public long getComputationTime() {
return kernel.getComputationTime();
}
}<|fim▁end|>
|
stmts.removeAll(blackList);
graph = RDFUtils.statements2Graph(stmts, RDFUtils.REGULAR_LITERALS, instances, true);
}
|
<|file_name|>questao01.py<|end_file_name|><|fim▁begin|># coding=utf-8
import random
lista = []
for x in range(10):
numero = random.randint(1, 100)
if x == 0:
maior, menor = numero, numero
elif numero > maior:
maior = numero
elif numero < menor:
menor = numero
lista.append(numero)
lista.sort()
print(lista)
print("Maior: %d" % maior)<|fim▁hole|><|fim▁end|>
|
print("Menor: %d" % menor)
|
<|file_name|>RemoteGameDoubleMap.java<|end_file_name|><|fim▁begin|>/*
* The MIT License (MIT)
*
* Copyright (c) 2016 MrInformatic.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package game.saver.remote.gamemaps;
import game.saver.GameData;
import game.saver.Quarry;
import game.saver.gamemaps.GameDoubleMap;
import game.saver.gamemaps.GameFloatMap;
import game.saver.remote.RemoteClassMap;
import game.saver.remote.Remoteable;
import java.util.LinkedList;
import java.util.Map;
/**
*
* @author MrInformatic
*/
public class RemoteGameDoubleMap<T extends GameData> extends GameDoubleMap<T> implements Remoteable{
private int id;
private Quarry quarry;
private RemoteClassMap remoteClassMap;
public RemoteGameDoubleMap(Quarry quarry,RemoteClassMap remoteClassMap){
this.quarry = quarry;
this.remoteClassMap = remoteClassMap;
}
@Override
public T put(Double key, T value) {
LinkedList<GameData> gameDatas = getUnaddedGameData(value);
T type = super.put(key,value);
sendPut(key, value, gameDatas);
return type;
}
@Override
public T remove(Object key) {
quarry.writeByte((byte)1);
quarry.writeDouble((Double)key);
return super.remove(key);
}
@Override
public void putAll(Map<? extends Double, ? extends T> m) {
LinkedList<GameData>[] gameDatases = new LinkedList[m.size()];
int i=0;
for(T ms : m.values()){
gameDatases[i] = getUnaddedGameData(ms);
i++;
}
super.putAll(m);
i=0;
for(Map.Entry<? extends Double, ? extends T> ms : m.entrySet()){
sendPut(ms.getKey(),ms.getValue(),gameDatases[i]);
i++;
}
}
@Override
public void clear() {
quarry.writeByte((byte)2);
super.clear();
}
private void sendPut(Double key,T value,LinkedList<GameData> unaddedGameData){
for(GameData gameData : unaddedGameData){
remoteClassMap.addClass(gameData.getClass());
}
quarry.writeInt(id);
quarry.writeByte((byte)0);
quarry.writeDouble(key);
quarry.writeInt(unaddedGameData.size());
for(GameData gameData : unaddedGameData){
quarry.writeInt(gameData.getId());
quarry.writeInt(remoteClassMap.getClassId(gameData.getClass()));
quarry.write(gameData);
}<|fim▁hole|> }
private LinkedList<GameData> getUnaddedGameData(GameData gameData){
LinkedList<GameData> result = new LinkedList<>();
getUnaddedGameData(result,gameData);
return result;
}
private LinkedList<GameData> getUnaddedGameData(LinkedList<GameData> list,GameData gameData){
if(gameData.getId()==-1){
list.add(gameData);
}
for(GameData gameData1 : gameData.getChilds()){
getUnaddedGameData(list,gameData1);
}
return list;
}
@Override
public void update() {
try {
switch(quarry.readByte()){
case 0:
double key = quarry.readDouble();
LinkedList<GameData> gameDatas = new LinkedList<>();
int length = quarry.readInt();
for(int i=0;i<length;i++){
int id = quarry.readInt();
T value = (T)quarry.read(remoteClassMap.getClassbyId(quarry.readInt()));
gameDatas.add(value);
graph.set(id,value);
}
for(GameData gameData : gameDatas){
gameData.readChilds(quarry,graph);
}
break;
case 1:
remove(quarry.readDouble());
break;
case 2:
clear();
break;
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void setId(int id){
this.id = id;
}
}<|fim▁end|>
|
for(GameData gameData : unaddedGameData){
gameData.writeChilds(quarry);
}
quarry.writeInt(-1);
|
<|file_name|>ad_parameter_error.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright 2020 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.
#
import proto # type: ignore
__protobuf__ = proto.module(
package="google.ads.googleads.v9.errors",
marshal="google.ads.googleads.v9",
manifest={"AdParameterErrorEnum",},
)<|fim▁hole|> r"""Container for enum describing possible ad parameter errors.
"""
class AdParameterError(proto.Enum):
r"""Enum describing possible ad parameter errors."""
UNSPECIFIED = 0
UNKNOWN = 1
AD_GROUP_CRITERION_MUST_BE_KEYWORD = 2
INVALID_INSERTION_TEXT_FORMAT = 3
__all__ = tuple(sorted(__protobuf__.manifest))<|fim▁end|>
|
class AdParameterErrorEnum(proto.Message):
|
<|file_name|>logging_binary_test.go<|end_file_name|><|fim▁begin|>// +build functional
package cri_containerd
import (
"context"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"testing"
"time"
runtime "k8s.io/cri-api/pkg/apis/runtime/v1alpha2"
)
// This test requires compiling a helper logging binary which can be found
// at test/cri-containerd/helpers/log.go. Copy log.exe as "sample-logging-driver.exe"
// to ContainerPlat install directory or set "TEST_BINARY_ROOT" environment variable,
// which this test will use to construct logPath for CreateContainerRequest and as
// the location of stdout artifacts created by the binary
func Test_Run_Container_With_Binary_Logger(t *testing.T) {
client := newTestRuntimeClient(t)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
binaryPath := requireBinary(t, "sample-logging-driver.exe")
logPath := "binary:///" + binaryPath
type config struct {
name string
containerName string
requiredFeatures []string
runtimeHandler string
sandboxImage string
containerImage string
cmd []string
expectedContent string
}
tests := []config{
{
name: "WCOW_Process",
containerName: t.Name() + "-Container-WCOW_Process",
requiredFeatures: []string{featureWCOWProcess},
runtimeHandler: wcowProcessRuntimeHandler,
sandboxImage: imageWindowsNanoserver,
containerImage: imageWindowsNanoserver,
cmd: []string{"ping", "-t", "127.0.0.1"},
expectedContent: "Pinging 127.0.0.1 with 32 bytes of data",
},
{
name: "WCOW_Hypervisor",
containerName: t.Name() + "-Container-WCOW_Hypervisor",
requiredFeatures: []string{featureWCOWHypervisor},
runtimeHandler: wcowHypervisorRuntimeHandler,
sandboxImage: imageWindowsNanoserver,
containerImage: imageWindowsNanoserver,
cmd: []string{"ping", "-t", "127.0.0.1"},
expectedContent: "Pinging 127.0.0.1 with 32 bytes of data",
},
{
name: "LCOW",
containerName: t.Name() + "-Container-LCOW",
requiredFeatures: []string{featureLCOW},
runtimeHandler: lcowRuntimeHandler,
sandboxImage: imageLcowK8sPause,
containerImage: imageLcowAlpine,
cmd: []string{"ash", "-c", "while true; do echo 'Hello, World!'; sleep 1; done"},
expectedContent: "Hello, World!",
},
}
// Positive tests
for _, test := range tests {
t.Run(test.name+"_Positive", func(t *testing.T) {
requireFeatures(t, test.requiredFeatures...)
requiredImages := []string{test.sandboxImage, test.containerImage}
if test.runtimeHandler == lcowRuntimeHandler {
pullRequiredLcowImages(t, requiredImages)
} else {
pullRequiredImages(t, requiredImages)
}
podReq := getRunPodSandboxRequest(t, test.runtimeHandler)
podID := runPodSandbox(t, client, ctx, podReq)
defer removePodSandbox(t, client, ctx, podID)
logFileName := fmt.Sprintf(`%s\stdout-%s.txt`, filepath.Dir(binaryPath), test.name)
conReq := getCreateContainerRequest(podID, test.containerName, test.containerImage, test.cmd, podReq.Config)
conReq.Config.LogPath = logPath + fmt.Sprintf("?%s", logFileName)
createAndRunContainer(t, client, ctx, conReq)<|fim▁hole|> t.Fatalf("log file was not created: %s", logFileName)
}
defer os.Remove(logFileName)
ok, err := assertFileContent(logFileName, test.expectedContent)
if err != nil {
t.Fatalf("failed to read log file: %s", err)
}
if !ok {
t.Fatalf("file content validation failed: %s", test.expectedContent)
}
})
}
// Negative tests
for _, test := range tests {
t.Run(test.name+"_Negative", func(t *testing.T) {
requireFeatures(t, test.requiredFeatures...)
requiredImages := []string{test.sandboxImage, test.containerImage}
if test.runtimeHandler == lcowRuntimeHandler {
pullRequiredLcowImages(t, requiredImages)
} else {
pullRequiredImages(t, requiredImages)
}
podReq := getRunPodSandboxRequest(t, test.runtimeHandler)
podID := runPodSandbox(t, client, ctx, podReq)
defer removePodSandbox(t, client, ctx, podID)
nonExistentPath := "/does/not/exist/log.txt"
conReq := getCreateContainerRequest(podID, test.containerName, test.containerImage, test.cmd, podReq.Config)
conReq.Config.LogPath = logPath + fmt.Sprintf("?%s", nonExistentPath)
containerID := createContainer(t, client, ctx, conReq)
defer removeContainer(t, client, ctx, containerID)
// This should fail, since the filepath doesn't exist
_, err := client.StartContainer(ctx, &runtime.StartContainerRequest{
ContainerId: containerID,
})
if err == nil {
t.Fatal("container start should fail")
}
if !strings.Contains(err.Error(), "failed to start binary logger") {
t.Fatalf("expected 'failed to start binary logger' error, got: %s", err)
}
})
}
}
func createAndRunContainer(t *testing.T, client runtime.RuntimeServiceClient, ctx context.Context, conReq *runtime.CreateContainerRequest) {
containerID := createContainer(t, client, ctx, conReq)
defer removeContainer(t, client, ctx, containerID)
startContainer(t, client, ctx, containerID)
defer stopContainer(t, client, ctx, containerID)
// Let stdio kick in
time.Sleep(time.Second * 1)
}
func assertFileContent(path string, content string) (bool, error) {
fileContent, err := ioutil.ReadFile(path)
if err != nil {
return false, err
}
return strings.Contains(string(fileContent), content), nil
}<|fim▁end|>
|
if _, err := os.Stat(logFileName); os.IsNotExist(err) {
|
<|file_name|>convolution_border_modes.py<|end_file_name|><|fim▁begin|>import string
__version__ = string.split('$Revision: 1.6 $')[1]
__date__ = string.join(string.split('$Date: 2001/11/17 14:12:34 $')[1:3], ' ')
__author__ = 'Tarn Weisner Burton <[email protected]>'
__doc__ = 'http://oss.sgi.com/projects/ogl-sample/registry/SUN/convolution_border_modes.txt'
__api_version__ = 0x103
GL_WRAP_BORDER_SUN = 0x81D4
def glInitConvolutionBorderModesSUN():
from OpenGL.GL import __has_extension
<|fim▁hole|> return __has_extension("GL_SUN_convolution_border_modes")
def __info():
if glInitConvolutionBorderModesSUN():
return []<|fim▁end|>
| |
<|file_name|>general.py<|end_file_name|><|fim▁begin|>"""
General Character commands usually availabe to all characters
"""
from django.conf import settings
from evennia.utils import utils, prettytable
from evennia.commands.default.muxcommand import MuxCommand
# limit symbol import for API
__all__ = ("CmdHome", "CmdLook", "CmdNick",
"CmdInventory", "CmdGet", "CmdDrop", "CmdGive",
"CmdSay", "CmdPose", "CmdAccess")
class CmdHome(MuxCommand):
"""
move to your character's home location
Usage:
home
Teleports you to your home location.
"""
key = "home"
locks = "cmd:perm(home) or perm(Builders)"
arg_regex = r"$"
def func(self):
"Implement the command"
caller = self.caller
home = caller.home
if not home:
caller.msg("You have no home!")
elif home == caller.location:
caller.msg("You are already home!")
else:
caller.move_to(home)
caller.msg("There's no place like home ...")
class CmdLook(MuxCommand):
"""
look at location or object
Usage:
look
look <obj>
look *<player>
Observes your location or objects in your vicinity.
"""
key = "look"
aliases = ["l", "ls"]
locks = "cmd:all()"
arg_regex = r"\s|$"
def func(self):
"""
Handle the looking.
"""
caller = self.caller
args = self.args
if args:
# Use search to handle duplicate/nonexistant results.
looking_at_obj = caller.search(args, use_nicks=True)
if not looking_at_obj:
return
else:
looking_at_obj = caller.location
if not looking_at_obj:
caller.msg("You have no location to look at!")
return
if not hasattr(looking_at_obj, 'return_appearance'):
# this is likely due to us having a player instead
looking_at_obj = looking_at_obj.character
if not looking_at_obj.access(caller, "view"):
caller.msg("Could not find '%s'." % args)
return
# get object's appearance
caller.msg(looking_at_obj.return_appearance(caller))
# the object's at_desc() method.
looking_at_obj.at_desc(looker=caller)
class CmdNick(MuxCommand):
"""
define a personal alias/nick
Usage:
nick[/switches] <nickname> = [<string>]
alias ''
Switches:
object - alias an object
player - alias a player
clearall - clear all your aliases
list - show all defined aliases (also "nicks" works)
Examples:
nick hi = say Hello, I'm Sarah!
nick/object tom = the tall man
<|fim▁hole|> A 'nick' is a personal shortcut you create for your own use. When
you enter the nick, the alternative string will be sent instead.
The switches control in which situations the substitution will
happen. The default is that it will happen when you enter a
command. The 'object' and 'player' nick-types kick in only when
you use commands that requires an object or player as a target -
you can then use the nick to refer to them.
Note that no objects are actually renamed or changed by this
command - the nick is only available to you. If you want to
permanently add keywords to an object for everyone to use, you
need build privileges and to use the @alias command.
"""
key = "nick"
aliases = ["nickname", "nicks", "@nick", "alias"]
locks = "cmd:all()"
def func(self):
"Create the nickname"
caller = self.caller
switches = self.switches
nicks = caller.nicks.get(return_obj=True)
if 'list' in switches:
table = prettytable.PrettyTable(["{wNickType",
"{wNickname",
"{wTranslates-to"])
for nick in utils.make_iter(nicks):
table.add_row([nick.db_category, nick.db_key, nick.db_strvalue])
string = "{wDefined Nicks:{n\n%s" % table
caller.msg(string)
return
if 'clearall' in switches:
caller.nicks.clear()
caller.msg("Cleared all aliases.")
return
if not self.args or not self.lhs:
caller.msg("Usage: nick[/switches] nickname = [realname]")
return
nick = self.lhs
real = self.rhs
if real == nick:
caller.msg("No point in setting nick same as the string to replace...")
return
# check so we have a suitable nick type
if not any(True for switch in switches if switch in ("object", "player", "inputline")):
switches = ["inputline"]
string = ""
for switch in switches:
oldnick = caller.nicks.get(key=nick, category=switch)
if not real:
# removal of nick
if oldnick:
# clear the alias
string += "\nNick '%s' (= '%s') was cleared." % (nick, oldnick)
caller.nicks.delete(nick, category=switch)
else:
string += "\nNo nick '%s' found, so it could not be removed." % nick
else:
# creating new nick
if oldnick:
string += "\nNick %s changed from '%s' to '%s'." % (nick, oldnick, real)
else:
string += "\nNick set: '%s' = '%s'." % (nick, real)
caller.nicks.add(nick, real, category=switch)
caller.msg(string)
class CmdInventory(MuxCommand):
"""
view inventory
Usage:
inventory
inv
Shows your inventory.
"""
key = "inventory"
aliases = ["inv", "i"]
locks = "cmd:all()"
arg_regex = r"$"
def func(self):
"check inventory"
items = self.caller.contents
if not items:
string = "You are not carrying anything."
else:
table = prettytable.PrettyTable(["name", "desc"])
table.header = False
table.border = False
for item in items:
table.add_row(["{C%s{n" % item.name, item.db.desc and item.db.desc or ""])
string = "{wYou are carrying:\n%s" % table
self.caller.msg(string)
class CmdGet(MuxCommand):
"""
pick up something
Usage:
get <obj>
Picks up an object from your location and puts it in
your inventory.
"""
key = "get"
aliases = "grab"
locks = "cmd:all()"
arg_regex = r"\s|$"
def func(self):
"implements the command."
caller = self.caller
if not self.args:
caller.msg("Get what?")
return
#print "general/get:", caller, caller.location, self.args, caller.location.contents
obj = caller.search(self.args, location=caller.location)
if not obj:
return
if caller == obj:
caller.msg("You can't get yourself.")
return
if not obj.access(caller, 'get'):
if obj.db.get_err_msg:
caller.msg(obj.db.get_err_msg)
else:
caller.msg("You can't get that.")
return
obj.move_to(caller, quiet=True)
caller.msg("You pick up %s." % obj.name)
caller.location.msg_contents("%s picks up %s." %
(caller.name,
obj.name),
exclude=caller)
# calling hook method
obj.at_get(caller)
class CmdDrop(MuxCommand):
"""
drop something
Usage:
drop <obj>
Lets you drop an object from your inventory into the
location you are currently in.
"""
key = "drop"
locks = "cmd:all()"
arg_regex = r"\s|$"
def func(self):
"Implement command"
caller = self.caller
if not self.args:
caller.msg("Drop what?")
return
# Because the DROP command by definition looks for items
# in inventory, call the search function using location = caller
obj = caller.search(self.args, location=caller,
nofound_string="You aren't carrying %s." % self.args,
multimatch_string="You carry more than one %s:" % self.args)
if not obj:
return
obj.move_to(caller.location, quiet=True)
caller.msg("You drop %s." % (obj.name,))
caller.location.msg_contents("%s drops %s." %
(caller.name, obj.name),
exclude=caller)
# Call the object script's at_drop() method.
obj.at_drop(caller)
class CmdGive(MuxCommand):
"""
give away something to someone
Usage:
give <inventory obj> = <target>
Gives an items from your inventory to another character,
placing it in their inventory.
"""
key = "give"
locks = "cmd:all()"
arg_regex = r"\s|$"
def func(self):
"Implement give"
caller = self.caller
if not self.args or not self.rhs:
caller.msg("Usage: give <inventory object> = <target>")
return
to_give = caller.search(self.lhs, location=caller,
nofound_string="You aren't carrying %s." % self.lhs,
multimatch_string="You carry more than one %s:" % self.lhs)
target = caller.search(self.rhs)
if not (to_give and target):
return
if target == caller:
caller.msg("You keep %s to yourself." % to_give.key)
return
if not to_give.location == caller:
caller.msg("You are not holding %s." % to_give.key)
return
# give object
caller.msg("You give %s to %s." % (to_give.key, target.key))
to_give.move_to(target, quiet=True)
target.msg("%s gives you %s." % (caller.key, to_give.key))
class CmdDesc(MuxCommand):
"""
describe yourself
Usage:
desc <description>
Add a description to yourself. This
will be visible to people when they
look at you.
"""
key = "desc"
locks = "cmd:all()"
arg_regex = r"\s|$"
def func(self):
"add the description"
if not self.args:
self.caller.msg("You must add a description.")
return
self.caller.db.desc = self.args.strip()
self.caller.msg("You set your description.")
class CmdSay(MuxCommand):
"""
speak as your character
Usage:
say <message>
Talk to those in your current location.
"""
key = "say"
aliases = ['"', "'"]
locks = "cmd:all()"
def func(self):
"Run the say command"
caller = self.caller
if not self.args:
caller.msg("Say what?")
return
speech = self.args
# calling the speech hook on the location
speech = caller.location.at_say(caller, speech)
# Feedback for the object doing the talking.
caller.msg('You say, "%s{n"' % speech)
# Build the string to emit to neighbors.
emit_string = '%s says, "%s{n"' % (caller.name,
speech)
caller.location.msg_contents(emit_string,
exclude=caller)
class CmdPose(MuxCommand):
"""
strike a pose
Usage:
pose <pose text>
pose's <pose text>
Example:
pose is standing by the wall, smiling.
-> others will see:
Tom is standing by the wall, smiling.
Describe an action being taken. The pose text will
automatically begin with your name.
"""
key = "pose"
aliases = [":", "emote"]
locks = "cmd:all()"
def parse(self):
"""
Custom parse the cases where the emote
starts with some special letter, such
as 's, at which we don't want to separate
the caller's name and the emote with a
space.
"""
args = self.args
if args and not args[0] in ["'", ",", ":"]:
args = " %s" % args.strip()
self.args = args
def func(self):
"Hook function"
if not self.args:
msg = "What do you want to do?"
self.caller.msg(msg)
else:
msg = "%s%s" % (self.caller.name, self.args)
self.caller.location.msg_contents(msg)
class CmdAccess(MuxCommand):
"""
show your current game access
Usage:
access
This command shows you the permission hierarchy and
which permission groups you are a member of.
"""
key = "access"
aliases = ["groups", "hierarchy"]
locks = "cmd:all()"
arg_regex = r"$"
def func(self):
"Load the permission groups"
caller = self.caller
hierarchy_full = settings.PERMISSION_HIERARCHY
string = "\n{wPermission Hierarchy{n (climbing):\n %s" % ", ".join(hierarchy_full)
#hierarchy = [p.lower() for p in hierarchy_full]
if self.caller.player.is_superuser:
cperms = "<Superuser>"
pperms = "<Superuser>"
else:
cperms = ", ".join(caller.permissions.all())
pperms = ", ".join(caller.player.permissions.all())
string += "\n{wYour access{n:"
string += "\nCharacter {c%s{n: %s" % (caller.key, cperms)
if hasattr(caller, 'player'):
string += "\nPlayer {c%s{n: %s" % (caller.player.key, pperms)
caller.msg(string)<|fim▁end|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.