prompt
large_stringlengths 70
991k
| completion
large_stringlengths 0
1.02k
|
---|---|
<|file_name|>load_archive.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# SIM-CITY client
#
# Copyright 2015 Netherlands eScience Center <[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
#
# 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 tarfile
class load_data:
'''
class to load txt data
'''
<|fim▁hole|> tfile, members = self.get_archive_object_tar()
self.read_files(tfile, members)
def get_archive_object_tar(self):
'''
return tarfile object and its members
'''
tfile = tarfile.open(name=self.filename)
members = tfile.getnames()
return tfile, members
def read_files(self, tfile, members):
'''
array with txt data from tarfile object
'''
self.data = [tfile.extractfile(member).read() for member in members if
tfile.extractfile(member) is not None]
def main():
load_data('enron_mail_clean.tar.gz')
import pdb
pdb.set_trace()
if __name__ == "__main__":
main()<|fim▁end|>
|
def __init__(self, filename):
self.filename = filename
|
<|file_name|>request.js<|end_file_name|><|fim▁begin|>'use strict';
var _ = require('lodash');
var Request = function(opts) {
opts = opts || {};
this.method = opts.method || this.ANY;
this.url = opts.url || this.ANY;
this.auth = opts.auth || this.ANY;
this.params = opts.params || this.ANY;
this.data = opts.data || this.ANY;
this.headers = opts.headers || this.ANY;
};
Request.prototype.ANY = '*';
Request.prototype.attributeEqual = function(lhs, rhs) {
if (lhs === this.ANY || rhs === this.ANY) {
return true;
}
lhs = lhs || undefined;
rhs = rhs || undefined;
return _.isEqual(lhs, rhs);<|fim▁hole|> this.attributeEqual(this.url, other.url) &&
this.attributeEqual(this.auth, other.auth) &&
this.attributeEqual(this.params, other.params) &&
this.attributeEqual(this.data, other.data) &&
this.attributeEqual(this.headers, other.headers));
};
Request.prototype.toString = function() {
var auth = '';
if (this.auth && this.auth !== this.ANY) {
auth = this.auth + ' ';
}
var params = '';
if (this.params && this.params !== this.ANY) {
params = '?' + _.join(_.chain(_.keys(this.params))
.map(function(key) { return key + '=' + this.params[key]; }.bind(this))
.value(), '&');
}
var data = '';
if (this.data && this.data !== this.ANY) {
if (this.method === 'GET') {
data = '\n -G';
}
data = data + '\n' + _.join(
_.map(this.data, function(value, key) {
return ' -d ' + key + '=' + value;
}), '\n');
}
var headers = '';
if (this.headers && this.headers !== this.ANY) {
headers = '\n' + _.join(
_.map(this.headers, function(value, key) {
return ' -H ' + key + '=' + value;
}), '\n');
}
return auth + this.method + ' ' + this.url + params + data + headers;
};
module.exports = Request;<|fim▁end|>
|
};
Request.prototype.isEqual = function(other) {
return (this.attributeEqual(this.method, other.method) &&
|
<|file_name|>helpers.py<|end_file_name|><|fim▁begin|>"""
*2014.09.10 16:10:05
DEPRECATED!!!!
please use building.models.search_building and building.models.make_building
instead of the make_unit and make_building functions found here...
out of date.
"""
import sys, os, json, codecs, re
sys.path.append(os.path.dirname(os.getcwd()))
from geopy import geocoders, distance
# MapQuest no longer available in present api. Work around
# detailed here: http://stackoverflow.com/questions/30132636/geocoding-error-with-geopandas-and-geopy
geocoders.MapQuest = geocoders.OpenMapQuest
#http://stackoverflow.com/questions/8047204/django-script-to-access-model-objects-without-using-manage-py-shell
#from rentrocket import settings
#from django.core.management import setup_environ
#setup_environ(settings)
#pre django 1.4 approach:
#from rentrocket import settings as rrsettings
#from django.core.management import setup_environ
#setup_environ(settings)
#from django.conf import settings
#settings.configure(rrsettings)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "rentrocket.settings")
from building.models import Building, Parcel, BuildingPerson, Unit
from person.models import Person
def parse_person(text):
"""
take a string representing all details of a person
and try to parse out the different details for that person...
usually it's a comma separated string,
but sometimes names have commas in them
instead, look for the start of the address,
either a number or a PO variation
"""
name = ''
address = ''
phone = ''
remainder = ''
print "Parsing: %s" % text
phone = re.compile("(\d{3})\W*(\d{3})\W*(\d{4})\W*(\w*)")
m = phone.search(text)
if m:
#print dir(m)
#print len(m.groups())
phone1 = m.group(1)
parts = text.split(phone1)
#update text so it only contains part without phone number:
text = parts[0]
full_phone = phone1+parts[1]
print "Phone found: %s" % full_phone
filler='.*?' # Non-greedy match on filler
po_box='( P\\.O\\. | P O | PO )'
rg = re.compile(po_box,re.IGNORECASE|re.DOTALL)
m = rg.search(text)
if m:
csv1=m.group(1)
print "PO BOX MATCH: ("+csv1+")"+"\n"
print text
parts = text.split(csv1)
#name = m.group(0)
name = parts[0]
#IndexError: no such group
#address = m.group(1) + m.group(2)
address = m.group(1) + parts[1]
else:
re2='(\\d+)' # Integer Number 1
rg = re.compile(re2,re.IGNORECASE|re.DOTALL)
m = rg.search(text)
if m:
int1 = m.group(1)
print "NUMBER MATCH: (" + int1 + ")"
parts = text.split(int1)
#name = m.group(0)
name = parts[0]
#IndexError: no such group
#address = m.group(1) + m.group(2)
address = m.group(1) + parts[1]
address = address.strip()
name = name.strip()
print "name: %s" % name
print "address: %s" % address
print ""
if name[-1] == ',':
name = name[:-1]
if address[-1] == ',':
address = address[:-1]
return (name, address, phone, remainder)
def make_building(location, bldg_id, city, feed_source, parcel_id=None, bldg_type=None, no_units=None, sqft=None):
"""
add the building to the database
#*2015.03.07 14:04:37
#see search_building(bldgform.cleaned_data.get("address"), unit=unit, make=True)
"""
full_city = '%s, IN, USA' % city.name
match = False
#find an address to use
for geo_source in location.sources:
if not match:
source_list = location.get_source(geo_source)
if len(source_list) and source_list[0]['place'] and source_list[0]['place'] != full_city:
print "using: %s to check: %s" % (geo_source, source_list[0]['place'])
match = True
#TODO: process this a bit more...
#probably don't want city and zip here:
#keeping city and zip minimizes chance for overlap
#especially since this is used as a key
#can always take it out on display, if necessary
#*2014.09.10 14:51:28
#this has changed... should only use street now...
#see building/models.py -> make_building
#cur_address = source_list[0]['place']
#cur_address = source_list[0]['place']
if parcel_id == None:
cid = "%s-%s" % (city.tag, bldg_id)
else:
cid = parcel_id
print "Checking parcel id: %s" % (cid)
parcels = Parcel.objects.filter(custom_id=cid)
if parcels.exists():
parcel = parcels[0]
print "Already had parcel: %s" % parcel.custom_id
else:
parcel = Parcel()
parcel.custom_id = cid
parcel.save()
print "Created new parcel: %s" % parcel.custom_id
buildings = Building.objects.filter(city=city).filter(address=cur_address)
bldg = None
#check if a previous building object in the db exists
if buildings.exists():
bldg = buildings[0]
print "Already had: %s" % bldg.address
else:
#if not,
#CREATE A NEW BUILDING OBJECT HERE
#cur_building = Building()
bldg = Building()
#bldg.address = source_list[0]['place']
bldg.address = source_list[0]['street']
bldg.latitude = float(source_list[0]['lat'])
bldg.longitude = float(source_list[0]['lng'])
bldg.parcel = parcel
bldg.geocoder = geo_source
bldg.source = feed_source
bldg.city = city
bldg.state = city.state
if bldg_type:
bldg.type = bldg_type
if no_units:
bldg.number_of_units = no_units
if sqft:
bldg.sqft = sqft
bldg.save()
print "Created new building: %s" % bldg.address
return bldg
else:
print "Skipping: %s with value: %s" % (geo_source, source_list[0]['place'])
def make_unit(apt_num, building):
#check for existing:
units = Unit.objects.filter(building=building).filter(number=apt_num)
unit = None
#check if a previous building object in the db exists
if units.exists():
unit = units[0]
print "Already had Unit: %s" % unit.address
else:
#if not,
#CREATE A NEW UNIT OBJECT HERE
unit = Unit()
unit.building = building
unit.number = apt_num
# don't want to set this unless it's different:
#unit.address = building.address + ", " + apt_num
## bedrooms
## bathrooms
## sqft
## max_occupants
unit.save()
print "Created new unit: %s" % unit.number
return unit
def make_person(name, building, relation, address=None, city=None, website=None, phone=None):
#now associate applicant with building:
#first find/make person
people = Person.objects.filter(city=city).filter(name=name)
person = None
#check if a previous building object in the db exists
if people.exists():
person = people[0]
print "Already had Person: %s" % person.name
else:
#if not,
#CREATE A NEW PERSON OBJECT HERE
person = Person()
person.name = name
if city:
person.city = city
if address:
person.address = address
if website:
person.website = website
if phone:
person.phone = phone
person.save()
#then find/make association:
bpeople = BuildingPerson.objects.filter(building=building).filter(person=person)
bperson = None
#check if a previous building_person object in the db exists
if bpeople.exists():
bperson = bpeople[0]
print "Already had BuildingPerson: %s with: %s" % (bperson.person.name, bperson.building.address)
else:
#if not,
#CREATE A NEW BUILDING PERSON OBJECT HERE
bperson = BuildingPerson()
bperson.person = person
bperson.building = building
bperson.relation = relation
bperson.save()
return (person, bperson)
def save_results(locations, destination="test.tsv"):
#destination = "test.tsv"
match_tallies = {}
closest_tallies = {}
furthest_tallies = {}
print "Saving: %s results to %s" % (len(locations), destination)
with codecs.open(destination, 'w', encoding='utf-8') as out:
#print locations.values()[0].make_header()
out.write(locations.values()[0].make_header())
for key, location in locations.items():
for source in location.sources:
#if hasattr(location, source) and getattr(location, source)[0]['place']:
source_list = location.get_source(source)
if len(source_list) and source_list[0]['place']:
if match_tallies.has_key(source):
match_tallies[source] += 1
else:
match_tallies[source] = 1
location.compare_points()
#print location.make_row()
# this was used to filter units with 1, 1 out separately
#if location.bldg_units == '1, 1':
# out.write(location.make_row())
print match_tallies
exit()
class Location(object):
"""
hold geolocation data associated with a specific address
making an object to help with processing results consistently
"""
def __init__(self, dictionary={}, sources=None):
"""
http://stackoverflow.com/questions/1305532/convert-python-dict-to-object
"""
self.__dict__.update(dictionary)
if sources:
self.sources = sources
else:
self.sources = ["google", "bing", "usgeo", "geonames", "openmq", "mq"]
#*2014.01.08 09:01:16
#this was only needed for csv exporting
#but these valued should be passed in to make_building
#this is not provided by any geolocation service,
#so it doesn't make sense to track here:
#self.units_bdrms = ''
#self.bldg_units = ''
def get_source(self, source):
"""
wrap hasattr/getattr combination
if we have something, return it,
otherwise return empty list
"""
if hasattr(self, source):
return getattr(self, source)
else:
return []
def to_dict(self):
"""
http://stackoverflow.com/questions/61517/python-dictionary-from-an-objects-fields
"""
result = self.__dict__.copy()
#can't remove('sources') on a dict
result.pop('sources', None)
return result
def compare_points(self):
#find only points with something in them
options = {}
for source in self.sources:
#this does the same thing as the next 2 lines,
#but is not as easy to read
#if hasattr(self, source) and getattr(self, source)[0]['place']:
source_list = self.get_source(source)
if len(source_list) and source_list[0]['place']:
#options[source] = getattr(self, source)[0]
options[source] = source_list[0]
d = distance.distance
available = options.keys()
self.distances = {}
self.totals = {}
index = 1
for item in available:
total = 0
others = available[:]
if item in others:
others.remove(item)
for other in others:
pt1 = ( options[item]['lat'], options[item]['lng'] )
pt2 = ( options[other]['lat'], options[other]['lng'] )
key = "%s-%s" % (item, other)
#https://github.com/geopy/geopy/blob/master/geopy/distance.py
#miles are also an option
#cur_d = d(pt1, pt2).miles
cur_d = d(pt1, pt2).feet
if not self.distances.has_key(key):
self.distances[key] = cur_d
total += cur_d
#this will be the same for all items if adding everything
self.totals[item] = total
def min_max_distances(self):
if not self.distances:
self.compare_points()
sortable = []
for key, value in self.distances.items():
sortable.append( (value, key) )
sortable.sort()
if len(sortable) >= 2:
return ( sortable[0], sortable[-1] )
else:
return ( ('', ''), ('', '') )
def min_max_totals(self):
if not self.distances:
self.compare_points()
sortable = []
for key, value in self.totals.items():
sortable.append( (value, key) )
sortable.sort()
if len(sortable) >= 2:
return ( sortable[0], sortable[-1] )
else:
return ( ('', ''), ('', '') )
def make_header(self):
"""
return a row representation of the header (for CSV output)
"""
#header = [ 'search', 'address', 'bldg_units', 'units_bdrms', '' ]
header = [ 'search', 'address', '' ]
header.extend( self.sources )
header.extend( [ '', 'closest', 'closest_amt', 'furthest', 'furthest_amt', '' ] )
header.extend( [ '', 'tclosest', 'tclosest_amt', 'tfurthest', 'tfurthest_amt', '' ] )
index = 1
for item1 in self.sources:
for item2 in self.sources[index:]:
title = "%s-%s" % (item1, item2)
header.append(title)
return "\t".join(header) + '\n'
def make_row(self):
"""
return a row representation of our data (for CSV output)
"""
## for source in self.sources:
## if self.get
## if source == 'google':
## #set this as the default
## if location.google['place']:
## location.address = location.google['place']
## else:
## #TODO
## #maybe check other places?
## location.address = ''
#row = [ self.address ]
row = []
found_address = False
for source in self.sources:
source_list = self.get_source(source)
if len(source_list) and source_list[0]['place']:
#if hasattr(self, source) and getattr(self, source)[0]['place']:
# cur = getattr(self, source)[0]
cur = source_list[0]
ll = "%s, %s" % (cur['lat'], cur['lng'])
#pick out the first address that has a value
if not found_address:
#insert these in reverse order:
self.address = cur['place']
row.insert(0, '')
#row.insert(0, self.units_bdrms)<|fim▁hole|> #row.insert(0, self.bldg_units)
row.insert(0, self.address)
#this should always be set... if not, investigate why:
if not hasattr(self, 'address_alt'):
print self.to_dict()
exit()
row.insert(0, self.address_alt)
found_address = True
else:
ll = ''
row.append( ll )
#couldn't find an address anywhere:
if not found_address:
row.insert(0, '')
#row.insert(0, self.units_bdrms)
#row.insert(0, self.bldg_units)
row.insert(0, '')
row.insert(0, self.address_alt)
print "ERROR LOCATING: %s" % self.address_alt
(mi, ma) = self.min_max_distances()
# 'closest', 'closest_amt', 'furthest', 'furthest_amt',
row.extend( [ '', mi[1], str(mi[0]), ma[1], str(ma[0]), '' ] )
(mi, ma) = self.min_max_totals()
# 'closest', 'closest_amt', 'furthest', 'furthest_amt',
row.extend( [ '', mi[1], str(mi[0]), ma[1], str(ma[0]), '' ] )
index = 1
for item1 in self.sources:
for item2 in self.sources[index:]:
title = "%s-%s" % (item1, item2)
if self.distances.has_key(title):
row.append(str(self.distances[title]))
else:
row.append('')
return "\t".join(row) + '\n'
class Geo(object):
"""
object to assist with geocoding tasks...
wraps geopy
and initializes coders in one spot
"""
def __init__(self):
#initialize geocoders once:
self.google = geocoders.GoogleV3()
#doesn't look like yahoo supports free api any longer:
#http://developer.yahoo.com/forum/General-Discussion-at-YDN/Yahoo-GeoCode-404-Not-Found/1362061375511-7faa66ba-191d-4593-ba63-0bb8f5d43c06
#yahoo = geocoders.Yahoo('PCqXY9bV34G8P7jzm_9JeuOfIviv37mvfyTvA62Ro_pBrwDtoIaiNLT_bqRVtETpb79.avb0LFV4U1fvgyz0bQlX_GoBA0s-')
self.usgeo = geocoders.GeocoderDotUS()
#self.geonames = geocoders.GeoNames()
self.bing = geocoders.Bing('AnFGlcOgRppf5ZSLF8wxXXN2_E29P-W9CMssWafE1RC9K9eXhcAL7nqzTmjwzMQD')
self.openmq = geocoders.OpenMapQuest()
#self.mq = geocoders.MapQuest('Fmjtd%7Cluub2hu7nl%2C20%3Do5-9uzg14')
#skipping mediawiki, seems less complete?
#mediawiki = geocoders.MediaWiki("http://wiki.case.edu/%s")
def lookup(self, address, source="google", location=None, force=False):
"""
look up the specified address using the designated source
if location dictionary is specified (for local caching)
store results there
return results either way
"""
updated = False
if not location is None:
self.location = location
else:
self.location = Location()
#if we already have any value for source (even None)
#won't look again unless force is set True
if (not hasattr(location, source)) or force:
do_query = False
if hasattr(location, source):
previous_result = getattr(location, source)
if previous_result[0]['place'] is None:
do_query = True
else:
do_query = True
if do_query:
print "Looking for: %s in %s" % (address, source)
coder = getattr(self, source)
if hasattr(location, source):
result = getattr(location, source)
else:
result = []
#Be very careful when enabling try/except here:
#can hide limit errors with a geocoder.
#good to do at the last phase
#try:
options = coder.geocode(address, exactly_one=False)
if options:
if isinstance(options[0], unicode):
(place, (lat, lng)) = options
result.append({'place': place, 'lat': lat, 'lng': lng})
setattr(location, source, result)
print location.to_dict()
updated = True
else:
print options
for place, (lat, lng) in options:
#clear out any old "None" entries:
for item in result[:]:
if item['place'] is None:
result.remove(item)
result.append({'place': place, 'lat': lat, 'lng': lng})
setattr(location, source, result)
print location.to_dict()
updated = True
#print "Result was: %s" % place
#print "lat: %s, long: %s" % (lat, lng)
#setattr(location, source, {'place': place, 'lat': lat, 'lng': lng})
## except:
## print "Error with lookup!"
## result.append({'place': None, 'lat': None, 'lng': None})
## setattr(location, source, result)
else:
print "Already have %s results for: %s" % (source, address)
return updated
def save_json(destination, json_objects):
json_file = codecs.open(destination, 'w', encoding='utf-8', errors='ignore')
json_file.write(json.dumps(json_objects))
json_file.close()
def load_json(source_file, create=False):
if not os.path.exists(source_file):
json_objects = {}
if create:
print "CREATING NEW JSON FILE: %s" % source_file
json_file = codecs.open(source_file, 'w', encoding='utf-8', errors='ignore')
#make sure there is something there for subsequent loads
json_file.write(json.dumps(json_objects))
json_file.close()
else:
raise ValueError, "JSON file does not exist: %s" % source_file
else:
json_file = codecs.open(source_file, 'r', encoding='utf-8', errors='ignore')
try:
json_objects = json.loads(json_file.read())
except:
raise ValueError, "No JSON object could be decoded from: %s" % source_file
json_file.close()
return json_objects<|fim▁end|>
| |
<|file_name|>app.js<|end_file_name|><|fim▁begin|><|fim▁hole|>import '../styles/appStyles.scss';<|fim▁end|>
|
import Aquaman from './components/Aquaman.jsx'; // eslint-disable-line no-unused-vars
|
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (c) 2009 Zikzakmedia S.L. (http://zikzakmedia.com) All Rights Reserved.
# Jordi Esteve <[email protected]>
# $Id$
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License<|fim▁hole|># along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
"""
Spanish Fiscal Year Closing Wizards
"""
import wizard_run<|fim▁end|>
| |
<|file_name|>EnumTypeAdapterTest.java<|end_file_name|><|fim▁begin|>/*
* Copyright (c) 2017 pCloud AG
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pcloud.networking.serialization;
import com.pcloud.networking.protocol.*;
import okio.Buffer;
import okio.ByteString;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
public class EnumTypeAdapterTest {
private enum StringEnumType {
@ParameterValue("something1")
FIRST_VALUE,
@ParameterValue("something2")
SECOND_VALUE,
@ParameterValue("something3")
THIRD_VALUE,
}
private enum NumberEnumType {
@ParameterValue("5000")
FIRST_VALUE,
@ParameterValue("2")
SECOND_VALUE,
@ParameterValue("10")
THIRD_VALUE,
}
private enum DuplicateNamesEnumType1 {
@ParameterValue("something")
FIRST_VALUE,
@ParameterValue("something")
SECOND_VALUE,
@ParameterValue("something")
THIRD_VALUE,<|fim▁hole|> @ParameterValue("something")
something1,
something,
}
private enum DuplicateNamesEnumType3 {
@ParameterValue("1")
FIRST_VALUE,
@ParameterValue("1")
SECOND_VALUE,
}
@Rule
public ExpectedException expectedException = ExpectedException.none();
@Test
public void returns_Correct_Constant_When_Deserializing_Strings() throws Exception {
ProtocolReader reader = readerWithValues("something1", "something2", "something3");
TypeAdapter<StringEnumType> adapter = new EnumTypeAdapter<>(StringEnumType.class);
assertEquals(StringEnumType.FIRST_VALUE, adapter.deserialize(reader));
assertEquals(StringEnumType.SECOND_VALUE, adapter.deserialize(reader));
assertEquals(StringEnumType.THIRD_VALUE, adapter.deserialize(reader));
}
@Test
public void returns_Correct_Constant_When_Deserializing_Numbers() throws Exception {
ProtocolReader reader = readerWithValues(5000, 2, 10);
TypeAdapter<NumberEnumType> adapter = new EnumTypeAdapter<>(NumberEnumType.class);
assertEquals(NumberEnumType.FIRST_VALUE, adapter.deserialize(reader));
assertEquals(NumberEnumType.SECOND_VALUE, adapter.deserialize(reader));
assertEquals(NumberEnumType.THIRD_VALUE, adapter.deserialize(reader));
}
@Test
public void throws_On_Duplicate_Type_Annotations_When_Initialized1() throws Exception {
expectedException.expect(IllegalStateException.class);
TypeAdapter<DuplicateNamesEnumType1> adapter = new EnumTypeAdapter<>(DuplicateNamesEnumType1.class);
}
@Test
public void throws_On_Duplicate_Type_Annotations_When_Initialized2() throws Exception {
expectedException.expect(IllegalStateException.class);
TypeAdapter<DuplicateNamesEnumType2> adapter = new EnumTypeAdapter<>(DuplicateNamesEnumType2.class);
}
@Test
public void throws_On_Duplicate_Type_Annotations_When_Initialized3() throws Exception {
expectedException.expect(IllegalStateException.class);
TypeAdapter<DuplicateNamesEnumType2> adapter = new EnumTypeAdapter<>(DuplicateNamesEnumType2.class);
}
@Test
public void throws_On_Invalid_Protocol_Type1() throws Exception {
ProtocolReader reader = readerWithValues(false, true, false);
TypeAdapter<NumberEnumType> adapter = new EnumTypeAdapter<>(NumberEnumType.class);
expectedException.expect(SerializationException.class);
adapter.deserialize(reader);
}
@Test
public void throws_On_Invalid_Protocol_Type2() throws Exception {
ProtocolReader reader = readerWithValues();
TypeAdapter<NumberEnumType> adapter = new EnumTypeAdapter<>(NumberEnumType.class);
expectedException.expect(SerializationException.class);
adapter.deserialize(reader);
}
private static ProtocolReader readerWithValues(Object... values) throws IOException {
ByteString response = ResponseBytesWriter.empty()
.beginObject()
.writeValue("values", values)
.endObject()
.bytes();
ProtocolResponseReader reader = new BytesReader(new Buffer().write(response));
reader.beginResponse();
reader.beginObject();
reader.readString();
reader.beginArray();
return reader;
}
}<|fim▁end|>
|
}
private enum DuplicateNamesEnumType2 {
|
<|file_name|>ApiDispatcherServletConfiguration.java<|end_file_name|><|fim▁begin|>/* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flowable.app.servlet;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import java.util.List;
@Configuration
@ComponentScan(value = {"org.flowable.app.rest.api", "org.flowable.app.rest.exception"})
@EnableAsync
public class ApiDispatcherServletConfiguration extends WebMvcConfigurationSupport {
@Autowired
protected ObjectMapper objectMapper;
@Autowired
protected Environment environment;
@Bean
public SessionLocaleResolver localeResolver() {
return new SessionLocaleResolver();
}
@Bean
public RequestMappingHandlerMapping requestMappingHandlerMapping() {
RequestMappingHandlerMapping requestMappingHandlerMapping = new RequestMappingHandlerMapping();
requestMappingHandlerMapping.setUseSuffixPatternMatch(false);<|fim▁hole|>
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
addDefaultHttpMessageConverters(converters);
for (HttpMessageConverter<?> converter: converters) {
if (converter instanceof MappingJackson2HttpMessageConverter) {
MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = (MappingJackson2HttpMessageConverter) converter;
jackson2HttpMessageConverter.setObjectMapper(objectMapper);
break;
}
}
}
}<|fim▁end|>
|
requestMappingHandlerMapping.setRemoveSemicolonContent(false);
requestMappingHandlerMapping.setInterceptors(getInterceptors());
return requestMappingHandlerMapping;
}
|
<|file_name|>renew.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# Welcome to CLRenew, a simple python script that automates mouse clicks to
# renew craigslist postings credit to https://github.com/yuqianli for base code
import pyautogui
import os
# Set a counter to count the # of exceptions occur
counter = 0
# Start the while loop<|fim▁hole|>while True:
try:
print ("Be sure your active listings page is up and active")
pyautogui.time.sleep(2)
renewButtonLocationX, renewButtonLocationY = pyautogui.locateCenterOnScreen('renew.png')
pyautogui.moveTo(renewButtonLocationX, renewButtonLocationY)
pyautogui.click()
pyautogui.time.sleep(2)
# This part of the loop will depend on your browser binding to go back a page:
pyautogui.keyDown('alt')
pyautogui.press('left')
pyautogui.keyUp('alt')
pyautogui.time.sleep(2)
# Exception handle when pyautogui can't locate the renew button on the screen
# or if it clicks away by mistake
# this section needs work and sometimes fails to function properly
except Exception:
print ("Exception thrown, calculating course of action")
pyautogui.press('pgdn')
counter += 1
print ("counter =" + str(counter))
if counter >= 3: counter = 0
pyautogui.time.sleep(2)
renewButtonLocationX,renewButtonLocationY = pyautogui.locateCenterOnScreen('page2.png')
pyautogui.moveTo(renewButtonLocationX, renewButtonLocationY)
pyautogui.click()
pyautogui.time.sleep(2)<|fim▁end|>
| |
<|file_name|>test_cover.py<|end_file_name|><|fim▁begin|>"""The tests for the MQTT cover platform."""
from unittest.mock import patch
import pytest
from homeassistant.components import cover
from homeassistant.components.cover import (
ATTR_CURRENT_POSITION,
ATTR_CURRENT_TILT_POSITION,
ATTR_POSITION,
ATTR_TILT_POSITION,
)
from homeassistant.components.mqtt import CONF_STATE_TOPIC
from homeassistant.components.mqtt.cover import (
CONF_GET_POSITION_TEMPLATE,
CONF_GET_POSITION_TOPIC,
CONF_SET_POSITION_TEMPLATE,
CONF_SET_POSITION_TOPIC,
CONF_TILT_COMMAND_TEMPLATE,
CONF_TILT_COMMAND_TOPIC,
CONF_TILT_STATUS_TEMPLATE,
CONF_TILT_STATUS_TOPIC,
MQTT_COVER_ATTRIBUTES_BLOCKED,
MqttCover,
)
from homeassistant.const import (
ATTR_ASSUMED_STATE,
ATTR_ENTITY_ID,
CONF_VALUE_TEMPLATE,
SERVICE_CLOSE_COVER,
SERVICE_CLOSE_COVER_TILT,
SERVICE_OPEN_COVER,
SERVICE_OPEN_COVER_TILT,
SERVICE_SET_COVER_POSITION,
SERVICE_SET_COVER_TILT_POSITION,
SERVICE_STOP_COVER,
SERVICE_TOGGLE,
SERVICE_TOGGLE_COVER_TILT,
STATE_CLOSED,
STATE_CLOSING,
STATE_OPEN,
STATE_OPENING,
STATE_UNKNOWN,
)
from homeassistant.setup import async_setup_component
from .test_common import (
help_test_availability_when_connection_lost,
help_test_availability_without_topic,
help_test_custom_availability_payload,
help_test_default_availability_payload,
help_test_discovery_broken,
help_test_discovery_removal,
help_test_discovery_update,
help_test_discovery_update_attr,
help_test_discovery_update_unchanged,
help_test_encoding_subscribable_topics,
help_test_entity_debug_info_message,
help_test_entity_device_info_remove,
help_test_entity_device_info_update,
help_test_entity_device_info_with_connection,
help_test_entity_device_info_with_identifier,
help_test_entity_id_update_discovery_update,
help_test_entity_id_update_subscriptions,
help_test_publishing_with_custom_encoding,
help_test_reloadable,
help_test_reloadable_late,
help_test_setting_attribute_via_mqtt_json_message,
help_test_setting_attribute_with_template,
help_test_setting_blocked_attribute_via_mqtt_json_message,
help_test_unique_id,
help_test_update_with_json_attrs_bad_JSON,
help_test_update_with_json_attrs_not_dict,
)
from tests.common import async_fire_mqtt_message
DEFAULT_CONFIG = {
cover.DOMAIN: {"platform": "mqtt", "name": "test", "state_topic": "test-topic"}
}
async def test_state_via_state_topic(hass, mqtt_mock):
"""Test the controlling state via topic."""
assert await async_setup_component(
hass,
cover.DOMAIN,
{
cover.DOMAIN: {
"platform": "mqtt",
"name": "test",
"state_topic": "state-topic",
"command_topic": "command-topic",
"qos": 0,
"payload_open": "OPEN",
"payload_close": "CLOSE",
"payload_stop": "STOP",
}
},
)
await hass.async_block_till_done()
state = hass.states.get("cover.test")
assert state.state == STATE_UNKNOWN
assert not state.attributes.get(ATTR_ASSUMED_STATE)
async_fire_mqtt_message(hass, "state-topic", STATE_CLOSED)
state = hass.states.get("cover.test")
assert state.state == STATE_CLOSED
async_fire_mqtt_message(hass, "state-topic", STATE_OPEN)
state = hass.states.get("cover.test")
assert state.state == STATE_OPEN
async def test_opening_and_closing_state_via_custom_state_payload(hass, mqtt_mock):
"""Test the controlling opening and closing state via a custom payload."""
assert await async_setup_component(
hass,
cover.DOMAIN,
{
cover.DOMAIN: {
"platform": "mqtt",
"name": "test",
"state_topic": "state-topic",
"command_topic": "command-topic",
"qos": 0,
"payload_open": "OPEN",
"payload_close": "CLOSE",
"payload_stop": "STOP",
"state_opening": "34",
"state_closing": "--43",
}
},
)
await hass.async_block_till_done()
state = hass.states.get("cover.test")
assert state.state == STATE_UNKNOWN
assert not state.attributes.get(ATTR_ASSUMED_STATE)
async_fire_mqtt_message(hass, "state-topic", "34")
state = hass.states.get("cover.test")
assert state.state == STATE_OPENING
async_fire_mqtt_message(hass, "state-topic", "--43")
state = hass.states.get("cover.test")
assert state.state == STATE_CLOSING
async_fire_mqtt_message(hass, "state-topic", STATE_CLOSED)
state = hass.states.get("cover.test")
assert state.state == STATE_CLOSED
async def test_open_closed_state_from_position_optimistic(hass, mqtt_mock):
"""Test the state after setting the position using optimistic mode."""
assert await async_setup_component(
hass,
cover.DOMAIN,
{
cover.DOMAIN: {
"platform": "mqtt",
"name": "test",
"position_topic": "position-topic",
"set_position_topic": "set-position-topic",
"qos": 0,
"payload_open": "OPEN",
"payload_close": "CLOSE",
"payload_stop": "STOP",
"optimistic": True,
}
},
)
await hass.async_block_till_done()
state = hass.states.get("cover.test")
assert state.state == STATE_UNKNOWN
await hass.services.async_call(
cover.DOMAIN,
SERVICE_SET_COVER_POSITION,
{ATTR_ENTITY_ID: "cover.test", ATTR_POSITION: 0},
blocking=True,
)
state = hass.states.get("cover.test")
assert state.state == STATE_CLOSED
assert state.attributes.get(ATTR_ASSUMED_STATE)
await hass.services.async_call(
cover.DOMAIN,
SERVICE_SET_COVER_POSITION,
{ATTR_ENTITY_ID: "cover.test", ATTR_POSITION: 100},
blocking=True,
)
state = hass.states.get("cover.test")
assert state.state == STATE_OPEN
assert state.attributes.get(ATTR_ASSUMED_STATE)
async def test_position_via_position_topic(hass, mqtt_mock):
"""Test the controlling state via topic."""
assert await async_setup_component(
hass,
cover.DOMAIN,
{
cover.DOMAIN: {
"platform": "mqtt",
"name": "test",
"position_topic": "get-position-topic",
"position_open": 100,
"position_closed": 0,
"command_topic": "command-topic",
"qos": 0,
"payload_open": "OPEN",
"payload_close": "CLOSE",
"payload_stop": "STOP",
}
},
)
await hass.async_block_till_done()
state = hass.states.get("cover.test")
assert state.state == STATE_UNKNOWN
assert not state.attributes.get(ATTR_ASSUMED_STATE)
async_fire_mqtt_message(hass, "get-position-topic", "0")
state = hass.states.get("cover.test")
assert state.state == STATE_CLOSED
async_fire_mqtt_message(hass, "get-position-topic", "100")
state = hass.states.get("cover.test")
assert state.state == STATE_OPEN
async def test_state_via_template(hass, mqtt_mock):
"""Test the controlling state via topic."""
assert await async_setup_component(
hass,
cover.DOMAIN,
{
cover.DOMAIN: {
"platform": "mqtt",
"name": "test",
"state_topic": "state-topic",
"command_topic": "command-topic",
"qos": 0,
"value_template": "\
{% if (value | multiply(0.01) | int) == 0 %}\
closed\
{% else %}\
open\
{% endif %}",
}
},
)
await hass.async_block_till_done()
state = hass.states.get("cover.test")
assert state.state == STATE_UNKNOWN
async_fire_mqtt_message(hass, "state-topic", "10000")
state = hass.states.get("cover.test")
assert state.state == STATE_OPEN
async_fire_mqtt_message(hass, "state-topic", "99")
state = hass.states.get("cover.test")
assert state.state == STATE_CLOSED
async def test_state_via_template_and_entity_id(hass, mqtt_mock):
"""Test the controlling state via topic."""
assert await async_setup_component(
hass,
cover.DOMAIN,
{
cover.DOMAIN: {
"platform": "mqtt",
"name": "test",
"state_topic": "state-topic",
"command_topic": "command-topic",
"qos": 0,
"value_template": '\
{% if value == "open" or value == "closed" %}\
{{ value }}\
{% else %}\
{{ states(entity_id) }}\
{% endif %}',
}
},
)
await hass.async_block_till_done()
state = hass.states.get("cover.test")
assert state.state == STATE_UNKNOWN
async_fire_mqtt_message(hass, "state-topic", "open")
async_fire_mqtt_message(hass, "state-topic", "invalid")
state = hass.states.get("cover.test")
assert state.state == STATE_OPEN
async_fire_mqtt_message(hass, "state-topic", "closed")
async_fire_mqtt_message(hass, "state-topic", "invalid")
state = hass.states.get("cover.test")
assert state.state == STATE_CLOSED
async def test_state_via_template_with_json_value(hass, mqtt_mock, caplog):
"""Test the controlling state via topic with JSON value."""
assert await async_setup_component(
hass,
cover.DOMAIN,
{
cover.DOMAIN: {
"platform": "mqtt",
"name": "test",
"state_topic": "state-topic",
"command_topic": "command-topic",
"qos": 0,
"value_template": "{{ value_json.Var1 }}",
}
},
)
await hass.async_block_till_done()
state = hass.states.get("cover.test")
assert state.state == STATE_UNKNOWN
async_fire_mqtt_message(hass, "state-topic", '{ "Var1": "open", "Var2": "other" }')
state = hass.states.get("cover.test")
assert state.state == STATE_OPEN
async_fire_mqtt_message(
hass, "state-topic", '{ "Var1": "closed", "Var2": "other" }'
)
state = hass.states.get("cover.test")
assert state.state == STATE_CLOSED
async_fire_mqtt_message(hass, "state-topic", '{ "Var2": "other" }')
assert (
"Template variable warning: 'dict object' has no attribute 'Var1' when rendering"
) in caplog.text
async def test_position_via_template_and_entity_id(hass, mqtt_mock):
"""Test the controlling state via topic."""
assert await async_setup_component(
hass,
cover.DOMAIN,
{
cover.DOMAIN: {
"platform": "mqtt",
"name": "test",
"position_topic": "get-position-topic",
"command_topic": "command-topic",
"qos": 0,
"position_template": '\
{% if state_attr(entity_id, "current_position") == None %}\
{{ value }}\
{% else %}\
{{ state_attr(entity_id, "current_position") + value | int }}\
{% endif %}',
}
},
)
await hass.async_block_till_done()
state = hass.states.get("cover.test")
assert state.state == STATE_UNKNOWN
async_fire_mqtt_message(hass, "get-position-topic", "10")
current_cover_position = hass.states.get("cover.test").attributes[
ATTR_CURRENT_POSITION
]
assert current_cover_position == 10
async_fire_mqtt_message(hass, "get-position-topic", "10")
current_cover_position = hass.states.get("cover.test").attributes[
ATTR_CURRENT_POSITION
]
assert current_cover_position == 20
@pytest.mark.parametrize(
"config, assumed_state",
[
({"command_topic": "abc"}, True),
({"command_topic": "abc", "state_topic": "abc"}, False),
# ({"set_position_topic": "abc"}, True), - not a valid configuration
({"set_position_topic": "abc", "position_topic": "abc"}, False),
({"tilt_command_topic": "abc"}, True),
({"tilt_command_topic": "abc", "tilt_status_topic": "abc"}, False),
],
)
async def test_optimistic_flag(hass, mqtt_mock, config, assumed_state):
"""Test assumed_state is set correctly."""
assert await async_setup_component(
hass,
cover.DOMAIN,
{cover.DOMAIN: {**config, "platform": "mqtt", "name": "test", "qos": 0}},
)
await hass.async_block_till_done()
state = hass.states.get("cover.test")
assert state.state == STATE_UNKNOWN
if assumed_state:
assert ATTR_ASSUMED_STATE in state.attributes
else:
assert ATTR_ASSUMED_STATE not in state.attributes
async def test_optimistic_state_change(hass, mqtt_mock):
"""Test changing state optimistically."""
assert await async_setup_component(
hass,
cover.DOMAIN,
{
cover.DOMAIN: {
"platform": "mqtt",
"name": "test",
"command_topic": "command-topic",
"qos": 0,
}
},
)
await hass.async_block_till_done()
state = hass.states.get("cover.test")
assert state.state == STATE_UNKNOWN
assert state.attributes.get(ATTR_ASSUMED_STATE)
await hass.services.async_call(
cover.DOMAIN, SERVICE_OPEN_COVER, {ATTR_ENTITY_ID: "cover.test"}, blocking=True
)
mqtt_mock.async_publish.assert_called_once_with("command-topic", "OPEN", 0, False)
mqtt_mock.async_publish.reset_mock()
state = hass.states.get("cover.test")
assert state.state == STATE_OPEN
await hass.services.async_call(
cover.DOMAIN, SERVICE_CLOSE_COVER, {ATTR_ENTITY_ID: "cover.test"}, blocking=True
)
mqtt_mock.async_publish.assert_called_once_with("command-topic", "CLOSE", 0, False)
mqtt_mock.async_publish.reset_mock()
state = hass.states.get("cover.test")
assert state.state == STATE_CLOSED
await hass.services.async_call(
cover.DOMAIN, SERVICE_TOGGLE, {ATTR_ENTITY_ID: "cover.test"}, blocking=True
)
mqtt_mock.async_publish.assert_called_once_with("command-topic", "OPEN", 0, False)
mqtt_mock.async_publish.reset_mock()
state = hass.states.get("cover.test")
assert state.state == STATE_OPEN
await hass.services.async_call(
cover.DOMAIN, SERVICE_TOGGLE, {ATTR_ENTITY_ID: "cover.test"}, blocking=True
)
mqtt_mock.async_publish.assert_called_once_with("command-topic", "CLOSE", 0, False)
state = hass.states.get("cover.test")
assert state.state == STATE_CLOSED
async def test_optimistic_state_change_with_position(hass, mqtt_mock):
"""Test changing state optimistically."""
assert await async_setup_component(
hass,
cover.DOMAIN,
{
cover.DOMAIN: {
"platform": "mqtt",
"name": "test",
"optimistic": True,
"command_topic": "command-topic",
"position_topic": "position-topic",
"qos": 0,
}
},
)
await hass.async_block_till_done()
state = hass.states.get("cover.test")
assert state.state == STATE_UNKNOWN
assert state.attributes.get(ATTR_ASSUMED_STATE)
assert state.attributes.get(ATTR_CURRENT_POSITION) is None
await hass.services.async_call(
cover.DOMAIN, SERVICE_OPEN_COVER, {ATTR_ENTITY_ID: "cover.test"}, blocking=True
)
mqtt_mock.async_publish.assert_called_once_with("command-topic", "OPEN", 0, False)
mqtt_mock.async_publish.reset_mock()
state = hass.states.get("cover.test")
assert state.state == STATE_OPEN
assert state.attributes.get(ATTR_CURRENT_POSITION) == 100
await hass.services.async_call(
cover.DOMAIN, SERVICE_CLOSE_COVER, {ATTR_ENTITY_ID: "cover.test"}, blocking=True
)
mqtt_mock.async_publish.assert_called_once_with("command-topic", "CLOSE", 0, False)
mqtt_mock.async_publish.reset_mock()
state = hass.states.get("cover.test")
assert state.state == STATE_CLOSED
assert state.attributes.get(ATTR_CURRENT_POSITION) == 0
await hass.services.async_call(
cover.DOMAIN, SERVICE_TOGGLE, {ATTR_ENTITY_ID: "cover.test"}, blocking=True
)
mqtt_mock.async_publish.assert_called_once_with("command-topic", "OPEN", 0, False)
mqtt_mock.async_publish.reset_mock()
state = hass.states.get("cover.test")
assert state.state == STATE_OPEN
assert state.attributes.get(ATTR_CURRENT_POSITION) == 100
await hass.services.async_call(
cover.DOMAIN, SERVICE_TOGGLE, {ATTR_ENTITY_ID: "cover.test"}, blocking=True
)
mqtt_mock.async_publish.assert_called_once_with("command-topic", "CLOSE", 0, False)
state = hass.states.get("cover.test")
assert state.state == STATE_CLOSED
assert state.attributes.get(ATTR_CURRENT_POSITION) == 0
async def test_send_open_cover_command(hass, mqtt_mock):
"""Test the sending of open_cover."""
assert await async_setup_component(
hass,
cover.DOMAIN,
{
cover.DOMAIN: {
"platform": "mqtt",
"name": "test",
"state_topic": "state-topic",
"command_topic": "command-topic",
"qos": 2,
}
},
)
await hass.async_block_till_done()
state = hass.states.get("cover.test")
assert state.state == STATE_UNKNOWN
await hass.services.async_call(
cover.DOMAIN, SERVICE_OPEN_COVER, {ATTR_ENTITY_ID: "cover.test"}, blocking=True
)
mqtt_mock.async_publish.assert_called_once_with("command-topic", "OPEN", 2, False)
state = hass.states.get("cover.test")
assert state.state == STATE_UNKNOWN
async def test_send_close_cover_command(hass, mqtt_mock):
"""Test the sending of close_cover."""
assert await async_setup_component(
hass,
cover.DOMAIN,
{
cover.DOMAIN: {
"platform": "mqtt",
"name": "test",
"state_topic": "state-topic",
"command_topic": "command-topic",
"qos": 2,
}
},
)
await hass.async_block_till_done()
state = hass.states.get("cover.test")
assert state.state == STATE_UNKNOWN
await hass.services.async_call(
cover.DOMAIN, SERVICE_CLOSE_COVER, {ATTR_ENTITY_ID: "cover.test"}, blocking=True
)
mqtt_mock.async_publish.assert_called_once_with("command-topic", "CLOSE", 2, False)
state = hass.states.get("cover.test")
assert state.state == STATE_UNKNOWN
async def test_send_stop__cover_command(hass, mqtt_mock):
"""Test the sending of stop_cover."""
assert await async_setup_component(
hass,
cover.DOMAIN,
{
cover.DOMAIN: {
"platform": "mqtt",
"name": "test",
"state_topic": "state-topic",
"command_topic": "command-topic",
"qos": 2,
}
},
)
await hass.async_block_till_done()
state = hass.states.get("cover.test")
assert state.state == STATE_UNKNOWN
await hass.services.async_call(
cover.DOMAIN, SERVICE_STOP_COVER, {ATTR_ENTITY_ID: "cover.test"}, blocking=True
)
mqtt_mock.async_publish.assert_called_once_with("command-topic", "STOP", 2, False)
state = hass.states.get("cover.test")
assert state.state == STATE_UNKNOWN
async def test_current_cover_position(hass, mqtt_mock):
"""Test the current cover position."""
assert await async_setup_component(
hass,
cover.DOMAIN,
{
cover.DOMAIN: {
"platform": "mqtt",
"name": "test",
"position_topic": "get-position-topic",
"command_topic": "command-topic",
"position_open": 100,
"position_closed": 0,
"payload_open": "OPEN",
"payload_close": "CLOSE",
"payload_stop": "STOP",
}
},
)
await hass.async_block_till_done()
state_attributes_dict = hass.states.get("cover.test").attributes
assert ATTR_CURRENT_POSITION not in state_attributes_dict
assert ATTR_CURRENT_TILT_POSITION not in state_attributes_dict
assert 4 & hass.states.get("cover.test").attributes["supported_features"] != 4
async_fire_mqtt_message(hass, "get-position-topic", "0")
current_cover_position = hass.states.get("cover.test").attributes[
ATTR_CURRENT_POSITION
]
assert current_cover_position == 0
async_fire_mqtt_message(hass, "get-position-topic", "50")
current_cover_position = hass.states.get("cover.test").attributes[
ATTR_CURRENT_POSITION
]
assert current_cover_position == 50
async_fire_mqtt_message(hass, "get-position-topic", "non-numeric")
current_cover_position = hass.states.get("cover.test").attributes[
ATTR_CURRENT_POSITION
]
assert current_cover_position == 50
async_fire_mqtt_message(hass, "get-position-topic", "101")
current_cover_position = hass.states.get("cover.test").attributes[
ATTR_CURRENT_POSITION
]
assert current_cover_position == 100
async def test_current_cover_position_inverted(hass, mqtt_mock):
"""Test the current cover position."""
assert await async_setup_component(
hass,
cover.DOMAIN,
{
cover.DOMAIN: {
"platform": "mqtt",
"name": "test",
"position_topic": "get-position-topic",
"command_topic": "command-topic",
"position_open": 0,
"position_closed": 100,
"payload_open": "OPEN",
"payload_close": "CLOSE",
"payload_stop": "STOP",
}
},
)
await hass.async_block_till_done()
state_attributes_dict = hass.states.get("cover.test").attributes
assert ATTR_CURRENT_POSITION not in state_attributes_dict
assert ATTR_CURRENT_TILT_POSITION not in state_attributes_dict
assert 4 & hass.states.get("cover.test").attributes["supported_features"] != 4
async_fire_mqtt_message(hass, "get-position-topic", "100")
current_percentage_cover_position = hass.states.get("cover.test").attributes[
ATTR_CURRENT_POSITION
]
assert current_percentage_cover_position == 0
assert hass.states.get("cover.test").state == STATE_CLOSED
async_fire_mqtt_message(hass, "get-position-topic", "0")
current_percentage_cover_position = hass.states.get("cover.test").attributes[
ATTR_CURRENT_POSITION
]
assert current_percentage_cover_position == 100
assert hass.states.get("cover.test").state == STATE_OPEN
async_fire_mqtt_message(hass, "get-position-topic", "50")
current_percentage_cover_position = hass.states.get("cover.test").attributes[
ATTR_CURRENT_POSITION
]
assert current_percentage_cover_position == 50
assert hass.states.get("cover.test").state == STATE_OPEN
async_fire_mqtt_message(hass, "get-position-topic", "non-numeric")
current_percentage_cover_position = hass.states.get("cover.test").attributes[
ATTR_CURRENT_POSITION
]
assert current_percentage_cover_position == 50
assert hass.states.get("cover.test").state == STATE_OPEN
async_fire_mqtt_message(hass, "get-position-topic", "101")
current_percentage_cover_position = hass.states.get("cover.test").attributes[
ATTR_CURRENT_POSITION
]
assert current_percentage_cover_position == 0
assert hass.states.get("cover.test").state == STATE_CLOSED
async def test_optimistic_position(hass, mqtt_mock):
"""Test optimistic position is not supported."""
assert await async_setup_component(
hass,
cover.DOMAIN,
{
cover.DOMAIN: {
"platform": "mqtt",
"name": "test",
"command_topic": "command-topic",
"set_position_topic": "set-position-topic",
}
},
)
await hass.async_block_till_done()
state = hass.states.get("cover.test")
assert state is None
async def test_position_update(hass, mqtt_mock):
"""Test cover position update from received MQTT message."""
assert await async_setup_component(
hass,
cover.DOMAIN,
{
cover.DOMAIN: {
"platform": "mqtt",
"name": "test",
"position_topic": "get-position-topic",
"command_topic": "command-topic",
"set_position_topic": "set-position-topic",
"position_open": 100,
"position_closed": 0,
"payload_open": "OPEN",
"payload_close": "CLOSE",
"payload_stop": "STOP",
}
},
)
await hass.async_block_till_done()
state_attributes_dict = hass.states.get("cover.test").attributes
assert ATTR_CURRENT_POSITION not in state_attributes_dict
assert ATTR_CURRENT_TILT_POSITION not in state_attributes_dict
assert 4 & hass.states.get("cover.test").attributes["supported_features"] == 4
async_fire_mqtt_message(hass, "get-position-topic", "22")
state_attributes_dict = hass.states.get("cover.test").attributes
assert ATTR_CURRENT_POSITION in state_attributes_dict
assert ATTR_CURRENT_TILT_POSITION not in state_attributes_dict
current_cover_position = hass.states.get("cover.test").attributes[
ATTR_CURRENT_POSITION
]
assert current_cover_position == 22
@pytest.mark.parametrize(
"pos_template,pos_call,pos_message",
[("{{position-1}}", 43, "42"), ("{{100-62}}", 100, "38")],
)
async def test_set_position_templated(
hass, mqtt_mock, pos_template, pos_call, pos_message
):
"""Test setting cover position via template."""
assert await async_setup_component(
hass,
cover.DOMAIN,
{
cover.DOMAIN: {
"platform": "mqtt",
"name": "test",
"position_topic": "get-position-topic",
"command_topic": "command-topic",
"position_open": 100,
"position_closed": 0,
"set_position_topic": "set-position-topic",
"set_position_template": pos_template,
"payload_open": "OPEN",
"payload_close": "CLOSE",
"payload_stop": "STOP",
}
},
)
await hass.async_block_till_done()
await hass.services.async_call(
cover.DOMAIN,
SERVICE_SET_COVER_POSITION,
{ATTR_ENTITY_ID: "cover.test", ATTR_POSITION: pos_call},
blocking=True,
)
mqtt_mock.async_publish.assert_called_once_with(
"set-position-topic", pos_message, 0, False
)
async def test_set_position_templated_and_attributes(hass, mqtt_mock):
"""Test setting cover position via template and using entities attributes."""
assert await async_setup_component(
hass,
cover.DOMAIN,
{
cover.DOMAIN: {
"platform": "mqtt",
"name": "test",
"position_topic": "get-position-topic",
"command_topic": "command-topic",
"position_open": 100,
"position_closed": 0,
"set_position_topic": "set-position-topic",
"set_position_template": '\
{% if position > 99 %}\
{% if state_attr(entity_id, "current_position") == None %}\
{{ 5 }}\
{% else %}\
{{ 23 }}\
{% endif %}\
{% else %}\
{{ 42 }}\
{% endif %}',
"payload_open": "OPEN",
"payload_close": "CLOSE",
"payload_stop": "STOP",
}
},
)
await hass.async_block_till_done()
await hass.services.async_call(
cover.DOMAIN,
SERVICE_SET_COVER_POSITION,
{ATTR_ENTITY_ID: "cover.test", ATTR_POSITION: 100},
blocking=True,
)
mqtt_mock.async_publish.assert_called_once_with("set-position-topic", "5", 0, False)
async def test_set_tilt_templated(hass, mqtt_mock):
"""Test setting cover tilt position via template."""
assert await async_setup_component(
hass,
cover.DOMAIN,
{
cover.DOMAIN: {
"platform": "mqtt",
"name": "test",
"position_topic": "get-position-topic",
"command_topic": "command-topic",
"tilt_command_topic": "tilt-command-topic",
"position_open": 100,
"position_closed": 0,
"set_position_topic": "set-position-topic",
"set_position_template": "{{position-1}}",
"tilt_command_template": "{{tilt_position+1}}",
"payload_open": "OPEN",
"payload_close": "CLOSE",
"payload_stop": "STOP",
}
},
)
await hass.async_block_till_done()
await hass.services.async_call(
cover.DOMAIN,
SERVICE_SET_COVER_TILT_POSITION,
{ATTR_ENTITY_ID: "cover.test", ATTR_TILT_POSITION: 41},
blocking=True,
)
mqtt_mock.async_publish.assert_called_once_with(
"tilt-command-topic", "42", 0, False
)
async def test_set_tilt_templated_and_attributes(hass, mqtt_mock):
"""Test setting cover tilt position via template and using entities attributes."""
assert await async_setup_component(
hass,
cover.DOMAIN,
{
cover.DOMAIN: {
"platform": "mqtt",
"name": "test",
"position_topic": "get-position-topic",
"command_topic": "command-topic",
"tilt_command_topic": "tilt-command-topic",
"position_open": 100,
"position_closed": 0,
"set_position_topic": "set-position-topic",
"set_position_template": "{{position-1}}",
"tilt_command_template": "{"
'"enitity_id": "{{ entity_id }}",'
'"value": {{ value }},'
'"tilt_position": {{ tilt_position }}'
"}",
"payload_open": "OPEN",
"payload_close": "CLOSE",
"payload_stop": "STOP",
}
},
)
await hass.async_block_till_done()
await hass.services.async_call(
cover.DOMAIN,
SERVICE_SET_COVER_TILT_POSITION,
{ATTR_ENTITY_ID: "cover.test", ATTR_TILT_POSITION: 45},
blocking=True,
)
mqtt_mock.async_publish.assert_called_once_with(
"tilt-command-topic",
'{"enitity_id": "cover.test","value": 45,"tilt_position": 45}',
0,
False,
)
mqtt_mock.async_publish.reset_mock()
await hass.services.async_call(
cover.DOMAIN,
SERVICE_OPEN_COVER_TILT,
{ATTR_ENTITY_ID: "cover.test"},
blocking=True,
)
mqtt_mock.async_publish.assert_called_once_with(
"tilt-command-topic",
'{"enitity_id": "cover.test","value": 100,"tilt_position": 100}',
0,
False,
)
mqtt_mock.async_publish.reset_mock()
await hass.services.async_call(
cover.DOMAIN,
SERVICE_CLOSE_COVER_TILT,
{ATTR_ENTITY_ID: "cover.test"},
blocking=True,
)
mqtt_mock.async_publish.assert_called_once_with(
"tilt-command-topic",
'{"enitity_id": "cover.test","value": 0,"tilt_position": 0}',
0,
False,
)
mqtt_mock.async_publish.reset_mock()
await hass.services.async_call(
cover.DOMAIN,
SERVICE_TOGGLE_COVER_TILT,
{ATTR_ENTITY_ID: "cover.test"},
blocking=True,
)
mqtt_mock.async_publish.assert_called_once_with(
"tilt-command-topic",
'{"enitity_id": "cover.test","value": 100,"tilt_position": 100}',
0,
False,
)
async def test_set_position_untemplated(hass, mqtt_mock):
"""Test setting cover position via template."""
assert await async_setup_component(
hass,
cover.DOMAIN,
{
cover.DOMAIN: {
"platform": "mqtt",
"name": "test",
"position_topic": "state-topic",
"command_topic": "command-topic",
"set_position_topic": "position-topic",
"payload_open": "OPEN",
"payload_close": "CLOSE",
"payload_stop": "STOP",
}
},
)
await hass.async_block_till_done()
await hass.services.async_call(
cover.DOMAIN,
SERVICE_SET_COVER_POSITION,
{ATTR_ENTITY_ID: "cover.test", ATTR_POSITION: 62},
blocking=True,
)
mqtt_mock.async_publish.assert_called_once_with("position-topic", "62", 0, False)
async def test_set_position_untemplated_custom_percentage_range(hass, mqtt_mock):
"""Test setting cover position via template."""
assert await async_setup_component(
hass,
cover.DOMAIN,
{
cover.DOMAIN: {
"platform": "mqtt",
"name": "test",
"position_topic": "state-topic",
"command_topic": "command-topic",
"set_position_topic": "position-topic",
"position_open": 0,
"position_closed": 100,
"payload_open": "OPEN",
"payload_close": "CLOSE",
"payload_stop": "STOP",
}
},
)
await hass.async_block_till_done()
await hass.services.async_call(
cover.DOMAIN,
SERVICE_SET_COVER_POSITION,
{ATTR_ENTITY_ID: "cover.test", ATTR_POSITION: 38},
blocking=True,
)
mqtt_mock.async_publish.assert_called_once_with("position-topic", "62", 0, False)
async def test_no_command_topic(hass, mqtt_mock):
"""Test with no command topic."""
assert await async_setup_component(
hass,
cover.DOMAIN,
{
cover.DOMAIN: {
"platform": "mqtt",
"name": "test",
"qos": 0,
"payload_open": "OPEN",
"payload_close": "CLOSE",
"payload_stop": "STOP",
"tilt_command_topic": "tilt-command",
"tilt_status_topic": "tilt-status",
}
},
)
await hass.async_block_till_done()
assert hass.states.get("cover.test").attributes["supported_features"] == 240
async def test_no_payload_close(hass, mqtt_mock):
"""Test with no close payload."""
assert await async_setup_component(
hass,
cover.DOMAIN,
{
cover.DOMAIN: {
"platform": "mqtt",
"name": "test",
"command_topic": "command-topic",
"qos": 0,
"payload_open": "OPEN",
"payload_close": None,
"payload_stop": "STOP",
}
},
)
await hass.async_block_till_done()
assert hass.states.get("cover.test").attributes["supported_features"] == 9
async def test_no_payload_open(hass, mqtt_mock):
"""Test with no open payload."""
assert await async_setup_component(
hass,
cover.DOMAIN,
{
cover.DOMAIN: {
"platform": "mqtt",
"name": "test",
"command_topic": "command-topic",
"qos": 0,
"payload_open": None,
"payload_close": "CLOSE",
"payload_stop": "STOP",
}
},
)
await hass.async_block_till_done()
assert hass.states.get("cover.test").attributes["supported_features"] == 10
async def test_no_payload_stop(hass, mqtt_mock):
"""Test with no stop payload."""
assert await async_setup_component(
hass,
cover.DOMAIN,
{
cover.DOMAIN: {
"platform": "mqtt",
"name": "test",
"command_topic": "command-topic",
"qos": 0,
"payload_open": "OPEN",
"payload_close": "CLOSE",
"payload_stop": None,
}
},
)
await hass.async_block_till_done()
assert hass.states.get("cover.test").attributes["supported_features"] == 3
async def test_with_command_topic_and_tilt(hass, mqtt_mock):
"""Test with command topic and tilt config."""
assert await async_setup_component(
hass,
cover.DOMAIN,
{
cover.DOMAIN: {
"command_topic": "test",
"platform": "mqtt",
"name": "test",
"qos": 0,
"payload_open": "OPEN",
"payload_close": "CLOSE",
"payload_stop": "STOP",
"tilt_command_topic": "tilt-command",
"tilt_status_topic": "tilt-status",
}
},
)
await hass.async_block_till_done()
assert hass.states.get("cover.test").attributes["supported_features"] == 251
async def test_tilt_defaults(hass, mqtt_mock):
"""Test the defaults."""
assert await async_setup_component(
hass,
cover.DOMAIN,
{
cover.DOMAIN: {
"platform": "mqtt",
"name": "test",
"state_topic": "state-topic",
"command_topic": "command-topic",
"qos": 0,
"payload_open": "OPEN",
"payload_close": "CLOSE",
"payload_stop": "STOP",
"tilt_command_topic": "tilt-command",
"tilt_status_topic": "tilt-status",
}
},
)
await hass.async_block_till_done()
state_attributes_dict = hass.states.get("cover.test").attributes
assert ATTR_CURRENT_TILT_POSITION in state_attributes_dict
current_cover_position = hass.states.get("cover.test").attributes[
ATTR_CURRENT_TILT_POSITION
]
assert current_cover_position == STATE_UNKNOWN
async def test_tilt_via_invocation_defaults(hass, mqtt_mock):
"""Test tilt defaults on close/open."""
assert await async_setup_component(
hass,
cover.DOMAIN,
{
cover.DOMAIN: {
"platform": "mqtt",
"name": "test",
"state_topic": "state-topic",
"command_topic": "command-topic",
"qos": 0,
"payload_open": "OPEN",
"payload_close": "CLOSE",
"payload_stop": "STOP",
"tilt_command_topic": "tilt-command-topic",
"tilt_status_topic": "tilt-status-topic",
}
},
)
await hass.async_block_till_done()
await hass.services.async_call(
cover.DOMAIN,
SERVICE_OPEN_COVER_TILT,
{ATTR_ENTITY_ID: "cover.test"},
blocking=True,
)
mqtt_mock.async_publish.assert_called_once_with(
"tilt-command-topic", "100", 0, False
)
mqtt_mock.async_publish.reset_mock()
await hass.services.async_call(
cover.DOMAIN,
SERVICE_CLOSE_COVER_TILT,
{ATTR_ENTITY_ID: "cover.test"},
blocking=True,
)
mqtt_mock.async_publish.assert_called_once_with("tilt-command-topic", "0", 0, False)
mqtt_mock.async_publish.reset_mock()
# Close tilt status would be received from device when non-optimistic
async_fire_mqtt_message(hass, "tilt-status-topic", "0")
current_cover_tilt_position = hass.states.get("cover.test").attributes[
ATTR_CURRENT_TILT_POSITION
]
assert current_cover_tilt_position == 0
await hass.services.async_call(
cover.DOMAIN,
SERVICE_TOGGLE_COVER_TILT,
{ATTR_ENTITY_ID: "cover.test"},
blocking=True,
)
mqtt_mock.async_publish.assert_called_once_with(
"tilt-command-topic", "100", 0, False
)
mqtt_mock.async_publish.reset_mock()
# Open tilt status would be received from device when non-optimistic
async_fire_mqtt_message(hass, "tilt-status-topic", "100")
current_cover_tilt_position = hass.states.get("cover.test").attributes[
ATTR_CURRENT_TILT_POSITION
]
assert current_cover_tilt_position == 100
await hass.services.async_call(
cover.DOMAIN,
SERVICE_TOGGLE_COVER_TILT,
{ATTR_ENTITY_ID: "cover.test"},
blocking=True,
)
mqtt_mock.async_publish.assert_called_once_with("tilt-command-topic", "0", 0, False)
async def test_tilt_given_value(hass, mqtt_mock):
"""Test tilting to a given value."""
assert await async_setup_component(
hass,
cover.DOMAIN,
{
cover.DOMAIN: {
"platform": "mqtt",
"name": "test",
"state_topic": "state-topic",
"command_topic": "command-topic",
"qos": 0,
"payload_open": "OPEN",
"payload_close": "CLOSE",
"payload_stop": "STOP",
"tilt_command_topic": "tilt-command-topic",
"tilt_status_topic": "tilt-status-topic",
"tilt_opened_value": 80,
"tilt_closed_value": 25,
}
},
)
await hass.async_block_till_done()
await hass.services.async_call(
cover.DOMAIN,
SERVICE_OPEN_COVER_TILT,
{ATTR_ENTITY_ID: "cover.test"},
blocking=True,
)
mqtt_mock.async_publish.assert_called_once_with(
"tilt-command-topic", "80", 0, False
)
mqtt_mock.async_publish.reset_mock()
await hass.services.async_call(
cover.DOMAIN,
SERVICE_CLOSE_COVER_TILT,
{ATTR_ENTITY_ID: "cover.test"},
blocking=True,
)
mqtt_mock.async_publish.assert_called_once_with(
"tilt-command-topic", "25", 0, False
)
mqtt_mock.async_publish.reset_mock()
# Close tilt status would be received from device when non-optimistic
async_fire_mqtt_message(hass, "tilt-status-topic", "25")
current_cover_tilt_position = hass.states.get("cover.test").attributes[
ATTR_CURRENT_TILT_POSITION
]
assert current_cover_tilt_position == 25
await hass.services.async_call(
cover.DOMAIN,
SERVICE_TOGGLE_COVER_TILT,
{ATTR_ENTITY_ID: "cover.test"},
blocking=True,
)
mqtt_mock.async_publish.assert_called_once_with(
"tilt-command-topic", "80", 0, False
)
mqtt_mock.async_publish.reset_mock()
# Open tilt status would be received from device when non-optimistic
async_fire_mqtt_message(hass, "tilt-status-topic", "80")
current_cover_tilt_position = hass.states.get("cover.test").attributes[
ATTR_CURRENT_TILT_POSITION
]
assert current_cover_tilt_position == 80
await hass.services.async_call(
cover.DOMAIN,
SERVICE_TOGGLE_COVER_TILT,
{ATTR_ENTITY_ID: "cover.test"},
blocking=True,
)
mqtt_mock.async_publish.assert_called_once_with(
"tilt-command-topic", "25", 0, False
)
async def test_tilt_given_value_optimistic(hass, mqtt_mock):
"""Test tilting to a given value."""
assert await async_setup_component(
hass,
cover.DOMAIN,
{
cover.DOMAIN: {
"platform": "mqtt",
"name": "test",
"state_topic": "state-topic",
"command_topic": "command-topic",
"qos": 0,
"payload_open": "OPEN",
"payload_close": "CLOSE",
"payload_stop": "STOP",
"tilt_command_topic": "tilt-command-topic",
"tilt_status_topic": "tilt-status-topic",
"tilt_opened_value": 80,
"tilt_closed_value": 25,
"tilt_optimistic": True,
}
},
)
await hass.async_block_till_done()
await hass.services.async_call(
cover.DOMAIN,
SERVICE_OPEN_COVER_TILT,
{ATTR_ENTITY_ID: "cover.test"},
blocking=True,
)
current_cover_tilt_position = hass.states.get("cover.test").attributes[
ATTR_CURRENT_TILT_POSITION
]
assert current_cover_tilt_position == 80
mqtt_mock.async_publish.assert_called_once_with(
"tilt-command-topic", "80", 0, False
)
mqtt_mock.async_publish.reset_mock()
await hass.services.async_call(
cover.DOMAIN,
SERVICE_SET_COVER_TILT_POSITION,
{ATTR_ENTITY_ID: "cover.test", ATTR_TILT_POSITION: 50},
blocking=True,
)
current_cover_tilt_position = hass.states.get("cover.test").attributes[
ATTR_CURRENT_TILT_POSITION
]
assert current_cover_tilt_position == 50
mqtt_mock.async_publish.assert_called_once_with(
"tilt-command-topic", "50", 0, False
)
mqtt_mock.async_publish.reset_mock()
await hass.services.async_call(
cover.DOMAIN,
SERVICE_CLOSE_COVER_TILT,
{ATTR_ENTITY_ID: "cover.test"},
blocking=True,
)
current_cover_tilt_position = hass.states.get("cover.test").attributes[
ATTR_CURRENT_TILT_POSITION
]
assert current_cover_tilt_position == 25
mqtt_mock.async_publish.assert_called_once_with(
"tilt-command-topic", "25", 0, False
)
async def test_tilt_given_value_altered_range(hass, mqtt_mock):
"""Test tilting to a given value."""
assert await async_setup_component(
hass,
cover.DOMAIN,
{
cover.DOMAIN: {
"platform": "mqtt",
"name": "test",
"state_topic": "state-topic",
"command_topic": "command-topic",
"qos": 0,
"payload_open": "OPEN",
"payload_close": "CLOSE",
"payload_stop": "STOP",
"tilt_command_topic": "tilt-command-topic",
"tilt_status_topic": "tilt-status-topic",
"tilt_opened_value": 25,
"tilt_closed_value": 0,
"tilt_min": 0,
"tilt_max": 50,
"tilt_optimistic": True,
}
},
)
await hass.async_block_till_done()
await hass.services.async_call(
cover.DOMAIN,
SERVICE_OPEN_COVER_TILT,
{ATTR_ENTITY_ID: "cover.test"},
blocking=True,
)
current_cover_tilt_position = hass.states.get("cover.test").attributes[
ATTR_CURRENT_TILT_POSITION
]
assert current_cover_tilt_position == 50
mqtt_mock.async_publish.assert_called_once_with(
"tilt-command-topic", "25", 0, False
)
mqtt_mock.async_publish.reset_mock()
await hass.services.async_call(
cover.DOMAIN,
SERVICE_CLOSE_COVER_TILT,
{ATTR_ENTITY_ID: "cover.test"},
blocking=True,
)
current_cover_tilt_position = hass.states.get("cover.test").attributes[
ATTR_CURRENT_TILT_POSITION
]
assert current_cover_tilt_position == 0
mqtt_mock.async_publish.assert_called_once_with("tilt-command-topic", "0", 0, False)
mqtt_mock.async_publish.reset_mock()
await hass.services.async_call(
cover.DOMAIN,
SERVICE_TOGGLE_COVER_TILT,
{ATTR_ENTITY_ID: "cover.test"},
blocking=True,
)
current_cover_tilt_position = hass.states.get("cover.test").attributes[
ATTR_CURRENT_TILT_POSITION
]
assert current_cover_tilt_position == 50
mqtt_mock.async_publish.assert_called_once_with(
"tilt-command-topic", "25", 0, False
)
async def test_tilt_via_topic(hass, mqtt_mock):
"""Test tilt by updating status via MQTT."""
assert await async_setup_component(
hass,
cover.DOMAIN,
{
cover.DOMAIN: {
"platform": "mqtt",
"name": "test",
"state_topic": "state-topic",
"command_topic": "command-topic",
"qos": 0,
"payload_open": "OPEN",
"payload_close": "CLOSE",
"payload_stop": "STOP",
"tilt_command_topic": "tilt-command-topic",
"tilt_status_topic": "tilt-status-topic",
}
},
)
await hass.async_block_till_done()
async_fire_mqtt_message(hass, "tilt-status-topic", "0")
current_cover_tilt_position = hass.states.get("cover.test").attributes[
ATTR_CURRENT_TILT_POSITION
]
assert current_cover_tilt_position == 0
async_fire_mqtt_message(hass, "tilt-status-topic", "50")
current_cover_tilt_position = hass.states.get("cover.test").attributes[
ATTR_CURRENT_TILT_POSITION
]
assert current_cover_tilt_position == 50
async def test_tilt_via_topic_template(hass, mqtt_mock):
"""Test tilt by updating status via MQTT and template."""
assert await async_setup_component(
hass,
cover.DOMAIN,
{
cover.DOMAIN: {
"platform": "mqtt",
"name": "test",
"state_topic": "state-topic",
"command_topic": "command-topic",
"qos": 0,
"payload_open": "OPEN",
"payload_close": "CLOSE",
"payload_stop": "STOP",
"tilt_command_topic": "tilt-command-topic",
"tilt_status_topic": "tilt-status-topic",
"tilt_status_template": "{{ (value | multiply(0.01)) | int }}",
"tilt_opened_value": 400,
"tilt_closed_value": 125,
}
},
)
await hass.async_block_till_done()
async_fire_mqtt_message(hass, "tilt-status-topic", "99")
current_cover_tilt_position = hass.states.get("cover.test").attributes[
ATTR_CURRENT_TILT_POSITION
]
assert current_cover_tilt_position == 0
async_fire_mqtt_message(hass, "tilt-status-topic", "5000")
current_cover_tilt_position = hass.states.get("cover.test").attributes[
ATTR_CURRENT_TILT_POSITION
]
assert current_cover_tilt_position == 50
async def test_tilt_via_topic_template_json_value(hass, mqtt_mock, caplog):
"""Test tilt by updating status via MQTT and template with JSON value."""
assert await async_setup_component(
hass,
cover.DOMAIN,
{
cover.DOMAIN: {
"platform": "mqtt",
"name": "test",
"state_topic": "state-topic",
"command_topic": "command-topic",
"qos": 0,
"payload_open": "OPEN",
"payload_close": "CLOSE",
"payload_stop": "STOP",
"tilt_command_topic": "tilt-command-topic",
"tilt_status_topic": "tilt-status-topic",
"tilt_status_template": "{{ value_json.Var1 }}",
"tilt_opened_value": 400,
"tilt_closed_value": 125,
}
},
)
await hass.async_block_till_done()
async_fire_mqtt_message(hass, "tilt-status-topic", '{"Var1": 9, "Var2": 30}')
current_cover_tilt_position = hass.states.get("cover.test").attributes[
ATTR_CURRENT_TILT_POSITION
]
assert current_cover_tilt_position == 9
async_fire_mqtt_message(hass, "tilt-status-topic", '{"Var1": 50, "Var2": 10}')
current_cover_tilt_position = hass.states.get("cover.test").attributes[
ATTR_CURRENT_TILT_POSITION
]
assert current_cover_tilt_position == 50
async_fire_mqtt_message(hass, "tilt-status-topic", '{"Var2": 10}')
assert (
"Template variable warning: 'dict object' has no attribute 'Var1' when rendering"
) in caplog.text
async def test_tilt_via_topic_altered_range(hass, mqtt_mock):
"""Test tilt status via MQTT with altered tilt range."""
assert await async_setup_component(
hass,
cover.DOMAIN,
{
cover.DOMAIN: {
"platform": "mqtt",
"name": "test",
"state_topic": "state-topic",
"command_topic": "command-topic",
"qos": 0,
"payload_open": "OPEN",
"payload_close": "CLOSE",
"payload_stop": "STOP",
"tilt_command_topic": "tilt-command-topic",
"tilt_status_topic": "tilt-status-topic",
"tilt_min": 0,
"tilt_max": 50,
}
},
)
await hass.async_block_till_done()
async_fire_mqtt_message(hass, "tilt-status-topic", "0")
current_cover_tilt_position = hass.states.get("cover.test").attributes[
ATTR_CURRENT_TILT_POSITION
]
assert current_cover_tilt_position == 0
async_fire_mqtt_message(hass, "tilt-status-topic", "50")
current_cover_tilt_position = hass.states.get("cover.test").attributes[
ATTR_CURRENT_TILT_POSITION
]
assert current_cover_tilt_position == 100
async_fire_mqtt_message(hass, "tilt-status-topic", "25")
current_cover_tilt_position = hass.states.get("cover.test").attributes[
ATTR_CURRENT_TILT_POSITION
]
assert current_cover_tilt_position == 50
async def test_tilt_status_out_of_range_warning(hass, caplog, mqtt_mock):
"""Test tilt status via MQTT tilt out of range warning message."""
assert await async_setup_component(
hass,
cover.DOMAIN,
{
cover.DOMAIN: {
"platform": "mqtt",
"name": "test",
"state_topic": "state-topic",
"command_topic": "command-topic",
"qos": 0,
"payload_open": "OPEN",
"payload_close": "CLOSE",
"payload_stop": "STOP",
"tilt_command_topic": "tilt-command-topic",
"tilt_status_topic": "tilt-status-topic",
"tilt_min": 0,
"tilt_max": 50,
}
},
)
await hass.async_block_till_done()
async_fire_mqtt_message(hass, "tilt-status-topic", "60")
assert (
"Payload '60' is out of range, must be between '0' and '50' inclusive"
) in caplog.text
async def test_tilt_status_not_numeric_warning(hass, caplog, mqtt_mock):
"""Test tilt status via MQTT tilt not numeric warning message."""
assert await async_setup_component(
hass,
cover.DOMAIN,
{
cover.DOMAIN: {
"platform": "mqtt",
"name": "test",
"state_topic": "state-topic",
"command_topic": "command-topic",
"qos": 0,
"payload_open": "OPEN",
"payload_close": "CLOSE",
"payload_stop": "STOP",
"tilt_command_topic": "tilt-command-topic",
"tilt_status_topic": "tilt-status-topic",
"tilt_min": 0,
"tilt_max": 50,
}
},
)
await hass.async_block_till_done()
async_fire_mqtt_message(hass, "tilt-status-topic", "abc")
assert ("Payload 'abc' is not numeric") in caplog.text
async def test_tilt_via_topic_altered_range_inverted(hass, mqtt_mock):
"""Test tilt status via MQTT with altered tilt range and inverted tilt position."""
assert await async_setup_component(
hass,
cover.DOMAIN,
{
cover.DOMAIN: {
"platform": "mqtt",
"name": "test",
"state_topic": "state-topic",
"command_topic": "command-topic",
"qos": 0,
"payload_open": "OPEN",
"payload_close": "CLOSE",
"payload_stop": "STOP",
"tilt_command_topic": "tilt-command-topic",
"tilt_status_topic": "tilt-status-topic",
"tilt_min": 50,
"tilt_max": 0,
}
},
)
await hass.async_block_till_done()
async_fire_mqtt_message(hass, "tilt-status-topic", "0")
current_cover_tilt_position = hass.states.get("cover.test").attributes[
ATTR_CURRENT_TILT_POSITION
]
assert current_cover_tilt_position == 100
async_fire_mqtt_message(hass, "tilt-status-topic", "50")
current_cover_tilt_position = hass.states.get("cover.test").attributes[
ATTR_CURRENT_TILT_POSITION
]
assert current_cover_tilt_position == 0
async_fire_mqtt_message(hass, "tilt-status-topic", "25")
current_cover_tilt_position = hass.states.get("cover.test").attributes[
ATTR_CURRENT_TILT_POSITION
]
assert current_cover_tilt_position == 50
async def test_tilt_via_topic_template_altered_range(hass, mqtt_mock):
"""Test tilt status via MQTT and template with altered tilt range."""
assert await async_setup_component(
hass,
cover.DOMAIN,
{
cover.DOMAIN: {
"platform": "mqtt",
"name": "test",
"state_topic": "state-topic",
"command_topic": "command-topic",
"qos": 0,
"payload_open": "OPEN",
"payload_close": "CLOSE",
"payload_stop": "STOP",
"tilt_command_topic": "tilt-command-topic",
"tilt_status_topic": "tilt-status-topic",
"tilt_status_template": "{{ (value | multiply(0.01)) | int }}",
"tilt_opened_value": 400,
"tilt_closed_value": 125,
"tilt_min": 0,
"tilt_max": 50,
}
},
)
await hass.async_block_till_done()
async_fire_mqtt_message(hass, "tilt-status-topic", "99")
current_cover_tilt_position = hass.states.get("cover.test").attributes[
ATTR_CURRENT_TILT_POSITION
]
assert current_cover_tilt_position == 0
async_fire_mqtt_message(hass, "tilt-status-topic", "5000")
current_cover_tilt_position = hass.states.get("cover.test").attributes[
ATTR_CURRENT_TILT_POSITION
]
assert current_cover_tilt_position == 100
async_fire_mqtt_message(hass, "tilt-status-topic", "2500")
current_cover_tilt_position = hass.states.get("cover.test").attributes[
ATTR_CURRENT_TILT_POSITION
]
assert current_cover_tilt_position == 50
async def test_tilt_position(hass, mqtt_mock):
"""Test tilt via method invocation."""
assert await async_setup_component(
hass,
cover.DOMAIN,
{
cover.DOMAIN: {
"platform": "mqtt",
"name": "test",
"state_topic": "state-topic",
"command_topic": "command-topic",
"qos": 0,
"payload_open": "OPEN",
"payload_close": "CLOSE",
"payload_stop": "STOP",
"tilt_command_topic": "tilt-command-topic",
"tilt_status_topic": "tilt-status-topic",
}
},
)
await hass.async_block_till_done()
await hass.services.async_call(
cover.DOMAIN,
SERVICE_SET_COVER_TILT_POSITION,
{ATTR_ENTITY_ID: "cover.test", ATTR_TILT_POSITION: 50},
blocking=True,
)
mqtt_mock.async_publish.assert_called_once_with(
"tilt-command-topic", "50", 0, False
)
async def test_tilt_position_templated(hass, mqtt_mock):
"""Test tilt position via template."""
assert await async_setup_component(
hass,
cover.DOMAIN,
{
cover.DOMAIN: {
"platform": "mqtt",
"name": "test",
"state_topic": "state-topic",
"command_topic": "command-topic",
"qos": 0,
"payload_open": "OPEN",
"payload_close": "CLOSE",
"payload_stop": "STOP",
"tilt_command_topic": "tilt-command-topic",
"tilt_status_topic": "tilt-status-topic",
"tilt_command_template": "{{100-32}}",
}
},
)
await hass.async_block_till_done()
await hass.services.async_call(
cover.DOMAIN,
SERVICE_SET_COVER_TILT_POSITION,
{ATTR_ENTITY_ID: "cover.test", ATTR_TILT_POSITION: 100},
blocking=True,
)
mqtt_mock.async_publish.assert_called_once_with(
"tilt-command-topic", "68", 0, False
)
async def test_tilt_position_altered_range(hass, mqtt_mock):
"""Test tilt via method invocation with altered range."""
assert await async_setup_component(
hass,
cover.DOMAIN,
{
cover.DOMAIN: {
"platform": "mqtt",
"name": "test",
"state_topic": "state-topic",
"command_topic": "command-topic",
"qos": 0,
"payload_open": "OPEN",
"payload_close": "CLOSE",
"payload_stop": "STOP",
"tilt_command_topic": "tilt-command-topic",
"tilt_status_topic": "tilt-status-topic",
"tilt_opened_value": 400,
"tilt_closed_value": 125,
"tilt_min": 0,
"tilt_max": 50,
}
},
)
await hass.async_block_till_done()
await hass.services.async_call(
cover.DOMAIN,
SERVICE_SET_COVER_TILT_POSITION,
{ATTR_ENTITY_ID: "cover.test", ATTR_TILT_POSITION: 50},
blocking=True,
)
mqtt_mock.async_publish.assert_called_once_with(
"tilt-command-topic", "25", 0, False
)
async def test_find_percentage_in_range_defaults(hass, mqtt_mock):
"""Test find percentage in range with default range."""
mqtt_cover = MqttCover(
hass,
{
"name": "cover.test",
"state_topic": "state-topic",
"get_position_topic": None,
"command_topic": "command-topic",
"availability_topic": None,
"tilt_command_topic": "tilt-command-topic",
"tilt_status_topic": "tilt-status-topic",
"qos": 0,
"retain": False,
"state_open": "OPEN",
"state_closed": "CLOSE",
"position_open": 100,
"position_closed": 0,
"payload_open": "OPEN",
"payload_close": "CLOSE",
"payload_stop": "STOP",
"payload_available": None,
"payload_not_available": None,
"optimistic": False,
"value_template": None,
"tilt_open_position": 100,
"tilt_closed_position": 0,
"tilt_min": 0,
"tilt_max": 100,
"tilt_optimistic": False,
"set_position_topic": None,
"set_position_template": None,
"unique_id": None,
"device_config": None,
},
None,
None,
)
assert mqtt_cover.find_percentage_in_range(44) == 44
assert mqtt_cover.find_percentage_in_range(44, "cover") == 44
async def test_find_percentage_in_range_altered(hass, mqtt_mock):
"""Test find percentage in range with altered range."""
mqtt_cover = MqttCover(
hass,
{
"name": "cover.test",
"state_topic": "state-topic",
"get_position_topic": None,
"command_topic": "command-topic",
"availability_topic": None,
"tilt_command_topic": "tilt-command-topic",
"tilt_status_topic": "tilt-status-topic",
"qos": 0,
"retain": False,
"state_open": "OPEN",
"state_closed": "CLOSE",
"position_open": 180,
"position_closed": 80,
"payload_open": "OPEN",
"payload_close": "CLOSE",
"payload_stop": "STOP",
"payload_available": None,
"payload_not_available": None,
"optimistic": False,
"value_template": None,
"tilt_open_position": 180,
"tilt_closed_position": 80,
"tilt_min": 80,
"tilt_max": 180,
"tilt_optimistic": False,
"set_position_topic": None,
"set_position_template": None,
"unique_id": None,
"device_config": None,
},
None,
None,
)
assert mqtt_cover.find_percentage_in_range(120) == 40
assert mqtt_cover.find_percentage_in_range(120, "cover") == 40
async def test_find_percentage_in_range_defaults_inverted(hass, mqtt_mock):
"""Test find percentage in range with default range but inverted."""
mqtt_cover = MqttCover(
hass,
{
"name": "cover.test",
"state_topic": "state-topic",
"get_position_topic": None,
"command_topic": "command-topic",
"availability_topic": None,
"tilt_command_topic": "tilt-command-topic",
"tilt_status_topic": "tilt-status-topic",
"qos": 0,
"retain": False,
"state_open": "OPEN",
"state_closed": "CLOSE",
"position_open": 0,
"position_closed": 100,
"payload_open": "OPEN",
"payload_close": "CLOSE",
"payload_stop": "STOP",
"payload_available": None,
"payload_not_available": None,
"optimistic": False,
"value_template": None,
"tilt_open_position": 100,
"tilt_closed_position": 0,
"tilt_min": 100,
"tilt_max": 0,
"tilt_optimistic": False,
"set_position_topic": None,
"set_position_template": None,
"unique_id": None,
"device_config": None,
},
None,
None,
)
assert mqtt_cover.find_percentage_in_range(44) == 56
assert mqtt_cover.find_percentage_in_range(44, "cover") == 56
async def test_find_percentage_in_range_altered_inverted(hass, mqtt_mock):
"""Test find percentage in range with altered range and inverted."""
mqtt_cover = MqttCover(
hass,
{
"name": "cover.test",
"state_topic": "state-topic",
"get_position_topic": None,
"command_topic": "command-topic",
"availability_topic": None,
"tilt_command_topic": "tilt-command-topic",
"tilt_status_topic": "tilt-status-topic",
"qos": 0,
"retain": False,
"state_open": "OPEN",
"state_closed": "CLOSE",
"position_open": 80,
"position_closed": 180,
"payload_open": "OPEN",
"payload_close": "CLOSE",
"payload_stop": "STOP",
"payload_available": None,
"payload_not_available": None,
"optimistic": False,
"value_template": None,
"tilt_open_position": 180,
"tilt_closed_position": 80,
"tilt_min": 180,
"tilt_max": 80,
"tilt_optimistic": False,
"set_position_topic": None,
"set_position_template": None,
"unique_id": None,
"device_config": None,
},
None,
None,
)
assert mqtt_cover.find_percentage_in_range(120) == 60
assert mqtt_cover.find_percentage_in_range(120, "cover") == 60
async def test_find_in_range_defaults(hass, mqtt_mock):
"""Test find in range with default range."""
mqtt_cover = MqttCover(
hass,
{
"name": "cover.test",
"state_topic": "state-topic",
"get_position_topic": None,
"command_topic": "command-topic",
"availability_topic": None,
"tilt_command_topic": "tilt-command-topic",
"tilt_status_topic": "tilt-status-topic",
"qos": 0,
"retain": False,
"state_open": "OPEN",
"state_closed": "CLOSE",
"position_open": 100,
"position_closed": 0,
"payload_open": "OPEN",
"payload_close": "CLOSE",
"payload_stop": "STOP",
"payload_available": None,
"payload_not_available": None,
"optimistic": False,
"value_template": None,
"tilt_open_position": 100,
"tilt_closed_position": 0,
"tilt_min": 0,
"tilt_max": 100,
"tilt_optimistic": False,
"set_position_topic": None,
"set_position_template": None,
"unique_id": None,
"device_config": None,
},
None,
None,
)
<|fim▁hole|> assert mqtt_cover.find_in_range_from_percent(44) == 44
assert mqtt_cover.find_in_range_from_percent(44, "cover") == 44
async def test_find_in_range_altered(hass, mqtt_mock):
"""Test find in range with altered range."""
mqtt_cover = MqttCover(
hass,
{
"name": "cover.test",
"state_topic": "state-topic",
"get_position_topic": None,
"command_topic": "command-topic",
"availability_topic": None,
"tilt_command_topic": "tilt-command-topic",
"tilt_status_topic": "tilt-status-topic",
"qos": 0,
"retain": False,
"state_open": "OPEN",
"state_closed": "CLOSE",
"position_open": 180,
"position_closed": 80,
"payload_open": "OPEN",
"payload_close": "CLOSE",
"payload_stop": "STOP",
"payload_available": None,
"payload_not_available": None,
"optimistic": False,
"value_template": None,
"tilt_open_position": 180,
"tilt_closed_position": 80,
"tilt_min": 80,
"tilt_max": 180,
"tilt_optimistic": False,
"set_position_topic": None,
"set_position_template": None,
"unique_id": None,
"device_config": None,
},
None,
None,
)
assert mqtt_cover.find_in_range_from_percent(40) == 120
assert mqtt_cover.find_in_range_from_percent(40, "cover") == 120
async def test_find_in_range_defaults_inverted(hass, mqtt_mock):
"""Test find in range with default range but inverted."""
mqtt_cover = MqttCover(
hass,
{
"name": "cover.test",
"state_topic": "state-topic",
"get_position_topic": None,
"command_topic": "command-topic",
"availability_topic": None,
"tilt_command_topic": "tilt-command-topic",
"tilt_status_topic": "tilt-status-topic",
"qos": 0,
"retain": False,
"state_open": "OPEN",
"state_closed": "CLOSE",
"position_open": 0,
"position_closed": 100,
"payload_open": "OPEN",
"payload_close": "CLOSE",
"payload_stop": "STOP",
"payload_available": None,
"payload_not_available": None,
"optimistic": False,
"value_template": None,
"tilt_open_position": 100,
"tilt_closed_position": 0,
"tilt_min": 100,
"tilt_max": 0,
"tilt_optimistic": False,
"set_position_topic": None,
"set_position_template": None,
"unique_id": None,
"device_config": None,
},
None,
None,
)
assert mqtt_cover.find_in_range_from_percent(56) == 44
assert mqtt_cover.find_in_range_from_percent(56, "cover") == 44
async def test_find_in_range_altered_inverted(hass, mqtt_mock):
"""Test find in range with altered range and inverted."""
mqtt_cover = MqttCover(
hass,
{
"name": "cover.test",
"state_topic": "state-topic",
"get_position_topic": None,
"command_topic": "command-topic",
"availability_topic": None,
"tilt_command_topic": "tilt-command-topic",
"tilt_status_topic": "tilt-status-topic",
"qos": 0,
"retain": False,
"state_open": "OPEN",
"state_closed": "CLOSE",
"position_open": 80,
"position_closed": 180,
"payload_open": "OPEN",
"payload_close": "CLOSE",
"payload_stop": "STOP",
"payload_available": None,
"payload_not_available": None,
"optimistic": False,
"value_template": None,
"tilt_open_position": 180,
"tilt_closed_position": 80,
"tilt_min": 180,
"tilt_max": 80,
"tilt_optimistic": False,
"set_position_topic": None,
"set_position_template": None,
"unique_id": None,
"device_config": None,
},
None,
None,
)
assert mqtt_cover.find_in_range_from_percent(60) == 120
assert mqtt_cover.find_in_range_from_percent(60, "cover") == 120
async def test_availability_when_connection_lost(hass, mqtt_mock):
"""Test availability after MQTT disconnection."""
await help_test_availability_when_connection_lost(
hass, mqtt_mock, cover.DOMAIN, DEFAULT_CONFIG
)
async def test_availability_without_topic(hass, mqtt_mock):
"""Test availability without defined availability topic."""
await help_test_availability_without_topic(
hass, mqtt_mock, cover.DOMAIN, DEFAULT_CONFIG
)
async def test_default_availability_payload(hass, mqtt_mock):
"""Test availability by default payload with defined topic."""
await help_test_default_availability_payload(
hass, mqtt_mock, cover.DOMAIN, DEFAULT_CONFIG
)
async def test_custom_availability_payload(hass, mqtt_mock):
"""Test availability by custom payload with defined topic."""
await help_test_custom_availability_payload(
hass, mqtt_mock, cover.DOMAIN, DEFAULT_CONFIG
)
async def test_valid_device_class(hass, mqtt_mock):
"""Test the setting of a valid device class."""
assert await async_setup_component(
hass,
cover.DOMAIN,
{
cover.DOMAIN: {
"platform": "mqtt",
"name": "test",
"device_class": "garage",
"state_topic": "test-topic",
}
},
)
await hass.async_block_till_done()
state = hass.states.get("cover.test")
assert state.attributes.get("device_class") == "garage"
async def test_invalid_device_class(hass, mqtt_mock):
"""Test the setting of an invalid device class."""
assert await async_setup_component(
hass,
cover.DOMAIN,
{
cover.DOMAIN: {
"platform": "mqtt",
"name": "test",
"device_class": "abc123",
"state_topic": "test-topic",
}
},
)
await hass.async_block_till_done()
state = hass.states.get("cover.test")
assert state is None
async def test_setting_attribute_via_mqtt_json_message(hass, mqtt_mock):
"""Test the setting of attribute via MQTT with JSON payload."""
await help_test_setting_attribute_via_mqtt_json_message(
hass, mqtt_mock, cover.DOMAIN, DEFAULT_CONFIG
)
async def test_setting_blocked_attribute_via_mqtt_json_message(hass, mqtt_mock):
"""Test the setting of attribute via MQTT with JSON payload."""
await help_test_setting_blocked_attribute_via_mqtt_json_message(
hass, mqtt_mock, cover.DOMAIN, DEFAULT_CONFIG, MQTT_COVER_ATTRIBUTES_BLOCKED
)
async def test_setting_attribute_with_template(hass, mqtt_mock):
"""Test the setting of attribute via MQTT with JSON payload."""
await help_test_setting_attribute_with_template(
hass, mqtt_mock, cover.DOMAIN, DEFAULT_CONFIG
)
async def test_update_with_json_attrs_not_dict(hass, mqtt_mock, caplog):
"""Test attributes get extracted from a JSON result."""
await help_test_update_with_json_attrs_not_dict(
hass, mqtt_mock, caplog, cover.DOMAIN, DEFAULT_CONFIG
)
async def test_update_with_json_attrs_bad_json(hass, mqtt_mock, caplog):
"""Test attributes get extracted from a JSON result."""
await help_test_update_with_json_attrs_bad_JSON(
hass, mqtt_mock, caplog, cover.DOMAIN, DEFAULT_CONFIG
)
async def test_discovery_update_attr(hass, mqtt_mock, caplog):
"""Test update of discovered MQTTAttributes."""
await help_test_discovery_update_attr(
hass, mqtt_mock, caplog, cover.DOMAIN, DEFAULT_CONFIG
)
async def test_unique_id(hass, mqtt_mock):
"""Test unique_id option only creates one cover per id."""
config = {
cover.DOMAIN: [
{
"platform": "mqtt",
"name": "Test 1",
"state_topic": "test-topic",
"unique_id": "TOTALLY_UNIQUE",
},
{
"platform": "mqtt",
"name": "Test 2",
"state_topic": "test-topic",
"unique_id": "TOTALLY_UNIQUE",
},
]
}
await help_test_unique_id(hass, mqtt_mock, cover.DOMAIN, config)
async def test_discovery_removal_cover(hass, mqtt_mock, caplog):
"""Test removal of discovered cover."""
data = '{ "name": "test", "command_topic": "test_topic" }'
await help_test_discovery_removal(hass, mqtt_mock, caplog, cover.DOMAIN, data)
async def test_discovery_update_cover(hass, mqtt_mock, caplog):
"""Test update of discovered cover."""
config1 = {"name": "Beer", "command_topic": "test_topic"}
config2 = {"name": "Milk", "command_topic": "test_topic"}
await help_test_discovery_update(
hass, mqtt_mock, caplog, cover.DOMAIN, config1, config2
)
async def test_discovery_update_unchanged_cover(hass, mqtt_mock, caplog):
"""Test update of discovered cover."""
data1 = '{ "name": "Beer", "command_topic": "test_topic" }'
with patch(
"homeassistant.components.mqtt.cover.MqttCover.discovery_update"
) as discovery_update:
await help_test_discovery_update_unchanged(
hass, mqtt_mock, caplog, cover.DOMAIN, data1, discovery_update
)
@pytest.mark.no_fail_on_log_exception
async def test_discovery_broken(hass, mqtt_mock, caplog):
"""Test handling of bad discovery message."""
data1 = '{ "name": "Beer", "command_topic": "test_topic#" }'
data2 = '{ "name": "Milk", "command_topic": "test_topic" }'
await help_test_discovery_broken(
hass, mqtt_mock, caplog, cover.DOMAIN, data1, data2
)
async def test_entity_device_info_with_connection(hass, mqtt_mock):
"""Test MQTT cover device registry integration."""
await help_test_entity_device_info_with_connection(
hass, mqtt_mock, cover.DOMAIN, DEFAULT_CONFIG
)
async def test_entity_device_info_with_identifier(hass, mqtt_mock):
"""Test MQTT cover device registry integration."""
await help_test_entity_device_info_with_identifier(
hass, mqtt_mock, cover.DOMAIN, DEFAULT_CONFIG
)
async def test_entity_device_info_update(hass, mqtt_mock):
"""Test device registry update."""
await help_test_entity_device_info_update(
hass, mqtt_mock, cover.DOMAIN, DEFAULT_CONFIG
)
async def test_entity_device_info_remove(hass, mqtt_mock):
"""Test device registry remove."""
await help_test_entity_device_info_remove(
hass, mqtt_mock, cover.DOMAIN, DEFAULT_CONFIG
)
async def test_entity_id_update_subscriptions(hass, mqtt_mock):
"""Test MQTT subscriptions are managed when entity_id is updated."""
await help_test_entity_id_update_subscriptions(
hass, mqtt_mock, cover.DOMAIN, DEFAULT_CONFIG
)
async def test_entity_id_update_discovery_update(hass, mqtt_mock):
"""Test MQTT discovery update when entity_id is updated."""
await help_test_entity_id_update_discovery_update(
hass, mqtt_mock, cover.DOMAIN, DEFAULT_CONFIG
)
async def test_entity_debug_info_message(hass, mqtt_mock):
"""Test MQTT debug info."""
await help_test_entity_debug_info_message(
hass,
mqtt_mock,
cover.DOMAIN,
DEFAULT_CONFIG,
SERVICE_OPEN_COVER,
command_payload="OPEN",
)
async def test_state_and_position_topics_state_not_set_via_position_topic(
hass, mqtt_mock
):
"""Test state is not set via position topic when both state and position topics are set."""
assert await async_setup_component(
hass,
cover.DOMAIN,
{
cover.DOMAIN: {
"platform": "mqtt",
"name": "test",
"state_topic": "state-topic",
"position_topic": "get-position-topic",
"position_open": 100,
"position_closed": 0,
"state_open": "OPEN",
"state_closed": "CLOSE",
"command_topic": "command-topic",
"qos": 0,
}
},
)
await hass.async_block_till_done()
state = hass.states.get("cover.test")
assert state.state == STATE_UNKNOWN
assert not state.attributes.get(ATTR_ASSUMED_STATE)
async_fire_mqtt_message(hass, "state-topic", "OPEN")
state = hass.states.get("cover.test")
assert state.state == STATE_OPEN
async_fire_mqtt_message(hass, "get-position-topic", "0")
state = hass.states.get("cover.test")
assert state.state == STATE_OPEN
async_fire_mqtt_message(hass, "get-position-topic", "100")
state = hass.states.get("cover.test")
assert state.state == STATE_OPEN
async_fire_mqtt_message(hass, "state-topic", "CLOSE")
state = hass.states.get("cover.test")
assert state.state == STATE_CLOSED
async_fire_mqtt_message(hass, "get-position-topic", "0")
state = hass.states.get("cover.test")
assert state.state == STATE_CLOSED
async_fire_mqtt_message(hass, "get-position-topic", "100")
state = hass.states.get("cover.test")
assert state.state == STATE_CLOSED
async def test_set_state_via_position_using_stopped_state(hass, mqtt_mock):
"""Test the controlling state via position topic using stopped state."""
assert await async_setup_component(
hass,
cover.DOMAIN,
{
cover.DOMAIN: {
"platform": "mqtt",
"name": "test",
"state_topic": "state-topic",
"position_topic": "get-position-topic",
"position_open": 100,
"position_closed": 0,
"state_open": "OPEN",
"state_closed": "CLOSE",
"state_stopped": "STOPPED",
"command_topic": "command-topic",
"qos": 0,
}
},
)
await hass.async_block_till_done()
state = hass.states.get("cover.test")
assert state.state == STATE_UNKNOWN
assert not state.attributes.get(ATTR_ASSUMED_STATE)
async_fire_mqtt_message(hass, "state-topic", "OPEN")
state = hass.states.get("cover.test")
assert state.state == STATE_OPEN
async_fire_mqtt_message(hass, "get-position-topic", "0")
state = hass.states.get("cover.test")
assert state.state == STATE_OPEN
async_fire_mqtt_message(hass, "state-topic", "STOPPED")
state = hass.states.get("cover.test")
assert state.state == STATE_CLOSED
async_fire_mqtt_message(hass, "get-position-topic", "100")
state = hass.states.get("cover.test")
assert state.state == STATE_CLOSED
async_fire_mqtt_message(hass, "state-topic", "STOPPED")
state = hass.states.get("cover.test")
assert state.state == STATE_OPEN
async def test_position_via_position_topic_template(hass, mqtt_mock):
"""Test position by updating status via position template."""
assert await async_setup_component(
hass,
cover.DOMAIN,
{
cover.DOMAIN: {
"platform": "mqtt",
"name": "test",
"state_topic": "state-topic",
"command_topic": "command-topic",
"set_position_topic": "set-position-topic",
"position_topic": "get-position-topic",
"position_template": "{{ (value | multiply(0.01)) | int }}",
}
},
)
await hass.async_block_till_done()
async_fire_mqtt_message(hass, "get-position-topic", "99")
current_cover_position_position = hass.states.get("cover.test").attributes[
ATTR_CURRENT_POSITION
]
assert current_cover_position_position == 0
async_fire_mqtt_message(hass, "get-position-topic", "5000")
current_cover_position_position = hass.states.get("cover.test").attributes[
ATTR_CURRENT_POSITION
]
assert current_cover_position_position == 50
async def test_position_via_position_topic_template_json_value(hass, mqtt_mock, caplog):
"""Test position by updating status via position template with a JSON value."""
assert await async_setup_component(
hass,
cover.DOMAIN,
{
cover.DOMAIN: {
"platform": "mqtt",
"name": "test",
"state_topic": "state-topic",
"command_topic": "command-topic",
"set_position_topic": "set-position-topic",
"position_topic": "get-position-topic",
"position_template": "{{ value_json.Var1 }}",
}
},
)
await hass.async_block_till_done()
async_fire_mqtt_message(hass, "get-position-topic", '{"Var1": 9, "Var2": 60}')
current_cover_position_position = hass.states.get("cover.test").attributes[
ATTR_CURRENT_POSITION
]
assert current_cover_position_position == 9
async_fire_mqtt_message(hass, "get-position-topic", '{"Var1": 50, "Var2": 10}')
current_cover_position_position = hass.states.get("cover.test").attributes[
ATTR_CURRENT_POSITION
]
assert current_cover_position_position == 50
async_fire_mqtt_message(hass, "get-position-topic", '{"Var2": 60}')
assert (
"Template variable warning: 'dict object' has no attribute 'Var1' when rendering"
) in caplog.text
async def test_position_template_with_entity_id(hass, mqtt_mock):
"""Test position by updating status via position template."""
assert await async_setup_component(
hass,
cover.DOMAIN,
{
cover.DOMAIN: {
"platform": "mqtt",
"name": "test",
"state_topic": "state-topic",
"command_topic": "command-topic",
"set_position_topic": "set-position-topic",
"position_topic": "get-position-topic",
"position_template": '\
{% if state_attr(entity_id, "current_position") != None %}\
{{ value | int + state_attr(entity_id, "current_position") }} \
{% else %} \
{{ value }} \
{% endif %}',
}
},
)
await hass.async_block_till_done()
async_fire_mqtt_message(hass, "get-position-topic", "10")
current_cover_position_position = hass.states.get("cover.test").attributes[
ATTR_CURRENT_POSITION
]
assert current_cover_position_position == 10
async_fire_mqtt_message(hass, "get-position-topic", "10")
current_cover_position_position = hass.states.get("cover.test").attributes[
ATTR_CURRENT_POSITION
]
assert current_cover_position_position == 20
async def test_position_via_position_topic_template_return_json(hass, mqtt_mock):
"""Test position by updating status via position template and returning json."""
assert await async_setup_component(
hass,
cover.DOMAIN,
{
cover.DOMAIN: {
"platform": "mqtt",
"name": "test",
"state_topic": "state-topic",
"command_topic": "command-topic",
"set_position_topic": "set-position-topic",
"position_topic": "get-position-topic",
"position_template": '{{ {"position" : value} | tojson }}',
}
},
)
await hass.async_block_till_done()
async_fire_mqtt_message(hass, "get-position-topic", "55")
current_cover_position_position = hass.states.get("cover.test").attributes[
ATTR_CURRENT_POSITION
]
assert current_cover_position_position == 55
async def test_position_via_position_topic_template_return_json_warning(
hass, caplog, mqtt_mock
):
"""Test position by updating status via position template returning json without position attribute."""
assert await async_setup_component(
hass,
cover.DOMAIN,
{
cover.DOMAIN: {
"platform": "mqtt",
"name": "test",
"state_topic": "state-topic",
"command_topic": "command-topic",
"set_position_topic": "set-position-topic",
"position_topic": "get-position-topic",
"position_template": '{{ {"pos" : value} | tojson }}',
}
},
)
await hass.async_block_till_done()
async_fire_mqtt_message(hass, "get-position-topic", "55")
assert (
"Template (position_template) returned JSON without position attribute"
in caplog.text
)
async def test_position_and_tilt_via_position_topic_template_return_json(
hass, mqtt_mock
):
"""Test position and tilt by updating the position via position template."""
assert await async_setup_component(
hass,
cover.DOMAIN,
{
cover.DOMAIN: {
"platform": "mqtt",
"name": "test",
"state_topic": "state-topic",
"command_topic": "command-topic",
"set_position_topic": "set-position-topic",
"position_topic": "get-position-topic",
"position_template": '\
{{ {"position" : value, "tilt_position" : (value | int / 2)| int } | tojson }}',
}
},
)
await hass.async_block_till_done()
async_fire_mqtt_message(hass, "get-position-topic", "0")
current_cover_position = hass.states.get("cover.test").attributes[
ATTR_CURRENT_POSITION
]
current_tilt_position = hass.states.get("cover.test").attributes[
ATTR_CURRENT_TILT_POSITION
]
assert current_cover_position == 0 and current_tilt_position == 0
async_fire_mqtt_message(hass, "get-position-topic", "99")
current_cover_position = hass.states.get("cover.test").attributes[
ATTR_CURRENT_POSITION
]
current_tilt_position = hass.states.get("cover.test").attributes[
ATTR_CURRENT_TILT_POSITION
]
assert current_cover_position == 99 and current_tilt_position == 49
async def test_position_via_position_topic_template_all_variables(hass, mqtt_mock):
"""Test position by updating status via position template."""
assert await async_setup_component(
hass,
cover.DOMAIN,
{
cover.DOMAIN: {
"platform": "mqtt",
"name": "test",
"state_topic": "state-topic",
"command_topic": "command-topic",
"set_position_topic": "set-position-topic",
"position_topic": "get-position-topic",
"tilt_command_topic": "tilt-command-topic",
"position_open": 99,
"position_closed": 1,
"tilt_min": 11,
"tilt_max": 22,
"position_template": "\
{% if value | int < tilt_max %}\
{{ tilt_min }}\
{% endif %}\
{% if value | int > position_closed %}\
{{ position_open }}\
{% endif %}",
}
},
)
await hass.async_block_till_done()
async_fire_mqtt_message(hass, "get-position-topic", "0")
current_cover_position = hass.states.get("cover.test").attributes[
ATTR_CURRENT_POSITION
]
assert current_cover_position == 10
async_fire_mqtt_message(hass, "get-position-topic", "55")
current_cover_position = hass.states.get("cover.test").attributes[
ATTR_CURRENT_POSITION
]
assert current_cover_position == 100
async def test_set_state_via_stopped_state_no_position_topic(hass, mqtt_mock):
"""Test the controlling state via stopped state when no position topic."""
assert await async_setup_component(
hass,
cover.DOMAIN,
{
cover.DOMAIN: {
"platform": "mqtt",
"name": "test",
"state_topic": "state-topic",
"state_open": "OPEN",
"state_closed": "CLOSE",
"state_stopped": "STOPPED",
"state_opening": "OPENING",
"state_closing": "CLOSING",
"command_topic": "command-topic",
"qos": 0,
"optimistic": False,
}
},
)
await hass.async_block_till_done()
async_fire_mqtt_message(hass, "state-topic", "OPEN")
state = hass.states.get("cover.test")
assert state.state == STATE_OPEN
async_fire_mqtt_message(hass, "state-topic", "OPENING")
state = hass.states.get("cover.test")
assert state.state == STATE_OPENING
async_fire_mqtt_message(hass, "state-topic", "STOPPED")
state = hass.states.get("cover.test")
assert state.state == STATE_OPEN
async_fire_mqtt_message(hass, "state-topic", "CLOSING")
state = hass.states.get("cover.test")
assert state.state == STATE_CLOSING
async_fire_mqtt_message(hass, "state-topic", "STOPPED")
state = hass.states.get("cover.test")
assert state.state == STATE_CLOSED
async def test_position_via_position_topic_template_return_invalid_json(
hass, caplog, mqtt_mock
):
"""Test position by updating status via position template and returning invalid json."""
assert await async_setup_component(
hass,
cover.DOMAIN,
{
cover.DOMAIN: {
"platform": "mqtt",
"name": "test",
"state_topic": "state-topic",
"command_topic": "command-topic",
"set_position_topic": "set-position-topic",
"position_topic": "get-position-topic",
"position_template": '{{ {"position" : invalid_json} }}',
}
},
)
await hass.async_block_till_done()
async_fire_mqtt_message(hass, "get-position-topic", "55")
assert ("Payload '{'position': Undefined}' is not numeric") in caplog.text
async def test_set_position_topic_without_get_position_topic_error(
hass, caplog, mqtt_mock
):
"""Test error when set_position_topic is used without position_topic."""
assert await async_setup_component(
hass,
cover.DOMAIN,
{
cover.DOMAIN: {
"platform": "mqtt",
"name": "test",
"command_topic": "command-topic",
"set_position_topic": "set-position-topic",
"value_template": "{{100-62}}",
}
},
)
await hass.async_block_till_done()
assert (
f"'{CONF_SET_POSITION_TOPIC}' must be set together with '{CONF_GET_POSITION_TOPIC}'."
) in caplog.text
async def test_value_template_without_state_topic_error(hass, caplog, mqtt_mock):
"""Test error when value_template is used and state_topic is missing."""
assert await async_setup_component(
hass,
cover.DOMAIN,
{
cover.DOMAIN: {
"platform": "mqtt",
"name": "test",
"command_topic": "command-topic",
"value_template": "{{100-62}}",
}
},
)
await hass.async_block_till_done()
assert (
f"'{CONF_VALUE_TEMPLATE}' must be set together with '{CONF_STATE_TOPIC}'."
) in caplog.text
async def test_position_template_without_position_topic_error(hass, caplog, mqtt_mock):
"""Test error when position_template is used and position_topic is missing."""
assert await async_setup_component(
hass,
cover.DOMAIN,
{
cover.DOMAIN: {
"platform": "mqtt",
"name": "test",
"command_topic": "command-topic",
"position_template": "{{100-52}}",
}
},
)
await hass.async_block_till_done()
assert (
f"'{CONF_GET_POSITION_TEMPLATE}' must be set together with '{CONF_GET_POSITION_TOPIC}'."
in caplog.text
)
async def test_set_position_template_without_set_position_topic(
hass, caplog, mqtt_mock
):
"""Test error when set_position_template is used and set_position_topic is missing."""
assert await async_setup_component(
hass,
cover.DOMAIN,
{
cover.DOMAIN: {
"platform": "mqtt",
"name": "test",
"command_topic": "command-topic",
"set_position_template": "{{100-42}}",
}
},
)
await hass.async_block_till_done()
assert (
f"'{CONF_SET_POSITION_TEMPLATE}' must be set together with '{CONF_SET_POSITION_TOPIC}'."
in caplog.text
)
async def test_tilt_command_template_without_tilt_command_topic(
hass, caplog, mqtt_mock
):
"""Test error when tilt_command_template is used and tilt_command_topic is missing."""
assert await async_setup_component(
hass,
cover.DOMAIN,
{
cover.DOMAIN: {
"platform": "mqtt",
"name": "test",
"command_topic": "command-topic",
"tilt_command_template": "{{100-32}}",
}
},
)
await hass.async_block_till_done()
assert (
f"'{CONF_TILT_COMMAND_TEMPLATE}' must be set together with '{CONF_TILT_COMMAND_TOPIC}'."
in caplog.text
)
async def test_tilt_status_template_without_tilt_status_topic_topic(
hass, caplog, mqtt_mock
):
"""Test error when tilt_status_template is used and tilt_status_topic is missing."""
assert await async_setup_component(
hass,
cover.DOMAIN,
{
cover.DOMAIN: {
"platform": "mqtt",
"name": "test",
"command_topic": "command-topic",
"tilt_status_template": "{{100-22}}",
}
},
)
await hass.async_block_till_done()
assert (
f"'{CONF_TILT_STATUS_TEMPLATE}' must be set together with '{CONF_TILT_STATUS_TOPIC}'."
in caplog.text
)
@pytest.mark.parametrize(
"service,topic,parameters,payload,template",
[
(
SERVICE_OPEN_COVER,
"command_topic",
None,
"OPEN",
None,
),
(
SERVICE_SET_COVER_POSITION,
"set_position_topic",
{ATTR_POSITION: "50"},
50,
"set_position_template",
),
(
SERVICE_SET_COVER_TILT_POSITION,
"tilt_command_topic",
{ATTR_TILT_POSITION: "45"},
45,
"tilt_command_template",
),
],
)
async def test_publishing_with_custom_encoding(
hass,
mqtt_mock,
caplog,
service,
topic,
parameters,
payload,
template,
):
"""Test publishing MQTT payload with different encoding."""
domain = cover.DOMAIN
config = DEFAULT_CONFIG[domain]
config["position_topic"] = "some-position-topic"
await help_test_publishing_with_custom_encoding(
hass,
mqtt_mock,
caplog,
domain,
config,
service,
topic,
parameters,
payload,
template,
)
async def test_reloadable(hass, mqtt_mock, caplog, tmp_path):
"""Test reloading the MQTT platform."""
domain = cover.DOMAIN
config = DEFAULT_CONFIG[domain]
await help_test_reloadable(hass, mqtt_mock, caplog, tmp_path, domain, config)
async def test_reloadable_late(hass, mqtt_client_mock, caplog, tmp_path):
"""Test reloading the MQTT platform with late entry setup."""
domain = cover.DOMAIN
config = DEFAULT_CONFIG[domain]
await help_test_reloadable_late(hass, caplog, tmp_path, domain, config)
@pytest.mark.parametrize(
"topic,value,attribute,attribute_value",
[
("state_topic", "open", None, None),
("state_topic", "closing", None, None),
("position_topic", "40", "current_position", 40),
("tilt_status_topic", "60", "current_tilt_position", 60),
],
)
async def test_encoding_subscribable_topics(
hass, mqtt_mock, caplog, topic, value, attribute, attribute_value
):
"""Test handling of incoming encoded payload."""
await help_test_encoding_subscribable_topics(
hass,
mqtt_mock,
caplog,
cover.DOMAIN,
DEFAULT_CONFIG[cover.DOMAIN],
topic,
value,
attribute,
attribute_value,
skip_raw_test=True,
)<|fim▁end|>
| |
<|file_name|>main.rs<|end_file_name|><|fim▁begin|>#[macro_use]
extern crate clap;
use clap::Arg;
use failure::Fail;
use lucet_validate::{self, Validator};
use std::fs::File;
use std::io::{self, Read};
use std::path::{Path, PathBuf};
use std::process;
use witx;
pub fn main() {
// rebuild if env vars used by app_from_crate! change:
let _ = include_str!("../Cargo.toml");
let matches = app_from_crate!()
.arg(
Arg::with_name("module")
.takes_value(true)
.required(true)
.help("WebAssembly module"),
)
.arg(
Arg::with_name("witx")
.takes_value(true)
.required(true)
.help("validate against interface in this witx file"),
)
.arg(
Arg::with_name("wasi-exe")
.takes_value(false)
.required(false)
.short("w")
.long("wasi-exe")
.help("validate exports of WASI executable"),
)
.arg(
Arg::with_name("verbose")
.short("v")
.takes_value(false)
.required(false),
)
.get_matches();
let module_path = matches
.value_of("module")
.map(Path::new)
.expect("module arg required");
match run(
&module_path,
Path::new(matches.value_of("witx").expect("witx path required")),
matches.is_present("wasi-exe"),
) {
Ok(()) => {
if matches.is_present("verbose") {
println!("validated successfully")
}
}
Err(e) => {
if matches.is_present("verbose") {
match e {
Error::Witx(e) => {
println!("{}", e.report());
}
_ => {
println!("{:?}", e);
}
}
} else {
println!("{}", e);
}
process::exit(-1);
}
}
}
fn run(module_path: &Path, witx_path: &Path, wasi_exe: bool) -> Result<(), Error> {
let mut module_contents = Vec::new();
let mut file = File::open(module_path).map_err(|e| Error::Io(module_path.into(), e))?;
file.read_to_end(&mut module_contents)
.map_err(|e| Error::Io(module_path.into(), e))?;
let validator = Validator::load(witx_path)?.with_wasi_exe(wasi_exe);
validator.validate(&module_contents)?;
Ok(())
}
#[derive(Debug, Fail)]
enum Error {<|fim▁hole|> #[fail(display = "{}", _0)]
Validate(#[cause] lucet_validate::Error),
}
impl From<witx::WitxError> for Error {
fn from(e: witx::WitxError) -> Error {
Error::Witx(e)
}
}
impl From<lucet_validate::Error> for Error {
fn from(e: lucet_validate::Error) -> Error {
Error::Validate(e)
}
}<|fim▁end|>
|
#[fail(display = "{}", _0)]
Witx(#[cause] witx::WitxError),
#[fail(display = "With file {:?}: {}", _0, _1)]
Io(PathBuf, #[cause] io::Error),
|
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>#![allow(non_upper_case_globals)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
include!(concat!(env!("OUT_DIR"), "/bindings.rs"));
#[cfg(test)]
mod tests {
use super::*;
use std::mem;
use std::ptr;
use std::ffi::CString;
use std::ffi::CStr;
#[test]
fn constants() {
assert_eq!(
CUPS_FORMAT_TEXT,
CString::new("text/plain").unwrap().as_bytes_with_nul()
);
assert_eq!(CUPS_JOBID_CURRENT, 0);
}
#[test]
fn list_printers() {
unsafe {
let mut dests: *mut cups_dest_t = mem::zeroed();
let num_dests = cupsGetDests(&mut dests as *mut _);
std::slice::from_raw_parts(dests, num_dests as usize);
cupsFreeDests(num_dests, dests);
}
}
#[test]
fn default_printer() {
unsafe {
let mut dests: *mut cups_dest_t = mem::zeroed();
let num_dests = cupsGetDests(&mut dests as *mut _);
cupsGetDest(ptr::null(), ptr::null(), num_dests, dests);
cupsFreeDests(num_dests, dests);
}
}
#[test]
fn printer_info() {
unsafe {
let mut dests: *mut cups_dest_t = mem::zeroed();
let num_dests = cupsGetDests(&mut dests as *mut _);
let destinations = std::slice::from_raw_parts(dests, num_dests as usize);
for destination in destinations {
let c_printer_name = CStr::from_ptr((*destination).name);
let printer_name = c_printer_name.to_string_lossy();
let c_make_and_model = cupsGetOption(
CString::new("printer-make-and-model").unwrap().as_ptr(),
destination.num_options,
destination.options,
);
let make_and_model = CStr::from_ptr(c_make_and_model).to_string_lossy();
println!("{} ({})", printer_name, make_and_model);<|fim▁hole|> }
}
}
#[test]
#[ignore]
fn test_print_page() {
unsafe {
let mut dests: *mut cups_dest_t = mem::zeroed();
let num_dests = cupsGetDests(&mut dests as *mut _);
let destinations = std::slice::from_raw_parts(dests, num_dests as usize);
for dest in destinations {
let printer_name = CStr::from_ptr((*dest).name).to_string_lossy();
let make_and_model = CStr::from_ptr(cupsGetOption(
CString::new("printer-make-and-model").unwrap().as_ptr(),
dest.num_options,
dest.options,
)).to_string_lossy();
println!("{} ({})", printer_name, make_and_model);
let job_id: i32 = cupsPrintFile(
dest.name,
CString::new("./test-resources/testPrintFile.txt")
.unwrap()
.as_ptr(),
CString::new("Test Print").unwrap().as_ptr(),
dest.num_options,
dest.options,
);
println!("{}", job_id);
cupsFreeDests(num_dests, dests);
}
}
}
}<|fim▁end|>
|
cupsFreeDests(num_dests, dests);
|
<|file_name|>test_LD_X_decr.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python
###############################################################################
#
# simulavr - A simulator for the Atmel AVR family of microcontrollers.
# Copyright (C) 2001, 2002 Theodore A. Roth
#
# This program is free software; you can redistribute it and/or modify<|fim▁hole|># it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
###############################################################################
#
# $Id: test_LD_X_decr.py,v 1.1 2004/07/31 00:59:11 rivetwa Exp $
#
"""Test the LD_X_decr opcode.
"""
import base_test
from registers import Reg, SREG
class LD_X_decr_TestFail(base_test.TestFail): pass
class base_LD_X_decr(base_test.opcode_test):
"""Generic test case for testing LD_X_decr opcode.
LD_X_decr - Load Indirect from data space to Register using index X and
pre decrement X.
Operation: X <- X - 1 then Rd <- (X)
opcode is '1001 000d dddd 1110' where 0 <= d <= 31 and d != {26,27}
Only registers PC, R26, R27 and Rd should be changed.
"""
def setup(self):
# Set the register values
self.setup_regs[self.Rd] = 0
self.setup_regs[Reg.R26] = (self.X & 0xff)
self.setup_regs[Reg.R27] = ((self.X >> 8) & 0xff)
# set up the val in memory (memory is read after X is decremented,
# thus we need to write to memory _at_ X - 1)
self.mem_byte_write( self.X - 1, self.Vd )
# Return the raw opcode
return 0x900E | (self.Rd << 4)
def analyze_results(self):
self.reg_changed.extend( [self.Rd, Reg.R26, Reg.R27] )
# check that result is correct
expect = self.Vd
got = self.anal_regs[self.Rd]
if expect != got:
self.fail('LD_X_decr: expect=%02x, got=%02x' % (expect, got))
# check that X was decremented
expect = self.X - 1
got = (self.anal_regs[Reg.R26] & 0xff) | ((self.anal_regs[Reg.R27] << 8) & 0xff00)
if expect != got:
self.fail('LD_X_decr X not decr: expect=%04x, got=%04x' % (expect, got))
#
# Template code for test case.
# The fail method will raise a test specific exception.
#
template = """
class LD_X_decr_r%02d_X%04x_v%02x_TestFail(LD_X_decr_TestFail): pass
class test_LD_X_decr_r%02d_X%04x_v%02x(base_LD_X_decr):
Rd = %d
X = 0x%x
Vd = 0x%x
def fail(self,s):
raise LD_X_decr_r%02d_X%04x_v%02x_TestFail, s
"""
#
# automagically generate the test_LD_X_decr_rNN_vXX class definitions.
#
# Operation is undefined for d = 26 and d = 27.
#
code = ''
for d in range(0,26)+range(28,32):
for x in (0x10f, 0x1ff):
for v in (0xaa, 0x55):
args = (d,x,v)*4
code += template % args
exec code<|fim▁end|>
| |
<|file_name|>html2rawtest.go<|end_file_name|><|fim▁begin|>package main
import (
"fmt"
"golang.org/x/net/html"
"io"
"strings"
)
//const url = `https://www.ziprecruiter.com/jobs/cybercoders-befe3473/senior-software-engineer-golang-0dbe59d6?source=ziprecruiter-jobs-site`
const htmldata = `<!DOCTYPE html1234>
<html567>
<head>
<title>Page Title</title>
</head>
<body>
<h1 a123=123456>This is a Heading1</h1>
<p>This is a paragraph.</p>
<h1 b123=qwerty>This is a Heading2</h1>
</body>
</html567>`
<|fim▁hole|> htmlReader := strings.NewReader(htmldata)
allText := html2rawtext(htmlReader)
fmt.Println(allText)
}
func html2rawtext(htmlReader io.Reader) string {
z := html.NewTokenizer(htmlReader)
alltext := func(z *html.Tokenizer) []string {
var alltext []string
for {
tt := z.Next()
if tt == html.ErrorToken {
// End of the document, we're done
return alltext
}
if tt == html.TextToken {
t := z.Token()
//default:
alltext = append(alltext, t.Data)
//fmt.Println(cleanNonPrintChar(t.Data))
//isAnchor := t.Data == "a"
//if isAnchor {
// fmt.Println("We found a link!")
//}
}
}
}(z)
return cleanNonPrintChar(strings.Join(alltext, " "))
}
func cleanNonPrintChar(text string) string {
clean := make([]rune, 0, len(text))
var prev rune
for _, t := range text {
// replace all non printable char with white space
if t < 32 { // all non printable characters ascii is < 32
t = 32
}
// reduce all repeating white spaces to single white space
if !(t == 32 && prev == 32) {
clean = append(clean, t)
prev = t
}
}
return string(clean)
}<|fim▁end|>
|
func main() {
|
<|file_name|>FinishListener.java<|end_file_name|><|fim▁begin|>/*
* Copyright (C) 2010 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zzn.aeassistant.zxing.decoding;
import android.app.Activity;
import android.content.DialogInterface;
/**
* Simple listener used to exit the app in a few cases.
*
* @author Sean Owen
*/
public final class FinishListener
implements DialogInterface.OnClickListener, DialogInterface.OnCancelListener, Runnable {
private final Activity activityToFinish;
<|fim▁hole|> public FinishListener(Activity activityToFinish) {
this.activityToFinish = activityToFinish;
}
@Override
public void onCancel(DialogInterface dialogInterface) {
run();
}
@Override
public void onClick(DialogInterface dialogInterface, int i) {
run();
}
@Override
public void run() {
activityToFinish.finish();
}
}<|fim▁end|>
| |
<|file_name|>serializers.py<|end_file_name|><|fim▁begin|># Copyright (C) 2014-2016 Andrey Antukh <[email protected]>
# Copyright (C) 2014-2016 Jesús Espino <[email protected]>
# Copyright (C) 2014-2016 David Barragán <[email protected]>
# Copyright (C) 2014-2016 Alejandro Alonso <[email protected]>
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from taiga.projects.issues.serializers import IssueSerializer
from taiga.projects.userstories.serializers import UserStorySerializer
from taiga.projects.tasks.serializers import TaskSerializer
from taiga.projects.wiki.serializers import WikiPageSerializer
<|fim▁hole|>from taiga.projects.issues.models import Issue
from taiga.projects.userstories.models import UserStory
from taiga.projects.tasks.models import Task
from taiga.projects.wiki.models import WikiPage
class IssueSearchResultsSerializer(IssueSerializer):
class Meta:
model = Issue
fields = ('id', 'ref', 'subject', 'status', 'assigned_to')
class TaskSearchResultsSerializer(TaskSerializer):
class Meta:
model = Task
fields = ('id', 'ref', 'subject', 'status', 'assigned_to')
class UserStorySearchResultsSerializer(UserStorySerializer):
class Meta:
model = UserStory
fields = ('id', 'ref', 'subject', 'status', 'total_points',
'milestone_name', 'milestone_slug')
class WikiPageSearchResultsSerializer(WikiPageSerializer):
class Meta:
model = WikiPage
fields = ('id', 'slug')<|fim▁end|>
| |
<|file_name|>bitcoin_ru.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" ?><!DOCTYPE TS><TS language="ru" version="2.0">
<defaultcodec>UTF-8</defaultcodec>
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="14"/>
<source>About CosbyCoin</source>
<translation>О CosbyCoin</translation>
</message>
<message>
<location filename="../forms/aboutdialog.ui" line="53"/>
<source><b>CosbyCoin</b> version</source>
<translation><b>CosbyCoin</b> версия</translation>
</message>
<message>
<location filename="../forms/aboutdialog.ui" line="85"/>
<source>Copyright © 2011-2013 CosbyCoin Developers
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file license.txt 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>Все права защищены © 2011-2013 Разработчики CosbyCoin
Это экспериментальная программа.
Распространяется на правах лицензии MIT/X11, см. файл license.txt или http://www.opensource.org/licenses/mit-license.php.
Этот продукт включате ПО, разработанное OpenSSL Project для использования в OpenSSL Toolkit (http://www.openssl.org/) и криптографическое ПО, написанное Eric Young ([email protected]) и ПО для работы с UPnP, написанное Thomas Bernard.</translation>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="14"/>
<source>Address Book</source>
<translation>Адресная книга</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="20"/>
<source>These are your CosbyCoin 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>Здесь перечислены Ваши адреса для получения платежей. Вы можете использовать их для того, чтобы давать разным людям разные адреса и таким образом иметь возможность отслеживать кто и сколько Вам платил, а так же поддерживать бо́льшую анонимность..</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="33"/>
<source>Double-click to edit address or label</source>
<translation>Для того, чтобы изменить адрес или метку давжды кликните по изменяемому объекту</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="57"/>
<source>Create a new address</source>
<translation>Создать новый адрес</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="60"/>
<source>&New Address...</source>
<translation>&Создать адрес...</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="71"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Копировать текущий выделенный адрес в буфер обмена</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="74"/>
<source>&Copy to Clipboard</source>
<translation>&Kопировать</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="85"/>
<source>Show &QR Code</source>
<translation>Показать &QR код</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="96"/>
<source>Sign a message to prove you own this address</source>
<translation>Подпишите сообщение для доказательства </translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="99"/>
<source>&Sign Message</source>
<translation>&Подписать сообщение</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="110"/>
<source>Delete the currently selected address from the list. Only sending addresses can be deleted.</source>
<translation>Удалить выделенный адрес из списка (могут быть удалены только записи из адресной книги).</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="113"/>
<source>&Delete</source>
<translation>&Удалить</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="61"/>
<source>Copy address</source>
<translation>Копировать адрес</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="62"/>
<source>Copy label</source>
<translation>Копировать метку</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="63"/>
<source>Edit</source>
<translation>Правка</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="64"/>
<source>Delete</source>
<translation>Удалить</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="281"/>
<source>Export Address Book Data</source>
<translation>Экспортировать адресную книгу</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="282"/>
<source>Comma separated file (*.csv)</source>
<translation>Текст, разделённый запятыми (*.csv)</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="295"/>
<source>Error exporting</source>
<translation>Ошибка экспорта</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="295"/>
<source>Could not write to file %1.</source>
<translation>Невозможно записать в файл %1.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="77"/>
<source>Label</source>
<translation>Метка</translation>
</message>
<message>
<location filename="../addresstablemodel.cpp" line="77"/>
<source>Address</source>
<translation>Адрес</translation>
</message>
<message>
<location filename="../addresstablemodel.cpp" line="113"/>
<source>(no label)</source>
<translation>[нет метки]</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="26"/>
<source>Dialog</source>
<translation>Dialog</translation>
</message>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="32"/>
<location filename="../forms/askpassphrasedialog.ui" line="97"/>
<source>TextLabel</source>
<translation>TextLabel</translation>
</message>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="50"/>
<source>Enter passphrase</source>
<translation>Введите пароль</translation>
</message>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="64"/>
<source>New passphrase</source>
<translation>Новый пароль</translation>
</message>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="78"/>
<source>Repeat new passphrase</source>
<translation>Повторите новый пароль</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="34"/>
<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>Введите новый пароль для бумажника. <br/> Пожалуйста, используйте фразы из <b>10 или более случайных символов,</b> или <b>восьми и более слов.</b></translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="35"/>
<source>Encrypt wallet</source>
<translation>Зашифровать бумажник</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="38"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Для выполнения операции требуется пароль вашего бумажника.</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="43"/>
<source>Unlock wallet</source>
<translation>Разблокировать бумажник</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="46"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Для выполнения операции требуется пароль вашего бумажника.</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="51"/>
<source>Decrypt wallet</source>
<translation>Расшифровать бумажник</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="54"/>
<source>Change passphrase</source>
<translation>Сменить пароль</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="55"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Введите старый и новый пароль для бумажника.</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="101"/>
<source>Confirm wallet encryption</source>
<translation>Подтвердите шифрование бумажника</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="102"/>
<source>WARNING: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR CBCoinS</b>!
Are you sure you wish to encrypt your wallet?</source>
<translation>ВНИМАНИЕ: Если вы зашифруете бумажник и потеряете свой пароль, вы <b>ПОТЕРЯЕТЕ ВСЕ ВАШИ БИТКОИНЫ!</b>
Вы действительно хотите зашифровать ваш бумажник?</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="111"/>
<location filename="../askpassphrasedialog.cpp" line="160"/>
<source>Wallet encrypted</source>
<translation>Бумажник зашифрован</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="112"/>
<source>CosbyCoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your CBCoins from being stolen by malware infecting your computer.</source>
<translation>Сейчас программа закроется для завершения процесса шифрования. Помните, что шифрование вашего бумажника не может полностью защитить ваши биткоины от кражи с помощью инфицирования вашего компьютера вредоносным ПО.</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="208"/>
<location filename="../askpassphrasedialog.cpp" line="232"/>
<source>Warning: The Caps Lock key is on.</source>
<translation>Внимание: Caps Lock включен.</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="117"/>
<location filename="../askpassphrasedialog.cpp" line="124"/>
<location filename="../askpassphrasedialog.cpp" line="166"/>
<location filename="../askpassphrasedialog.cpp" line="172"/>
<source>Wallet encryption failed</source>
<translation>Не удалось зашифровать бумажник</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="118"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Шифрование бумажника не удалось из-за внутренней ошибки. Ваш бумажник не был зашифрован.</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="125"/>
<location filename="../askpassphrasedialog.cpp" line="173"/>
<source>The supplied passphrases do not match.</source>
<translation>Введённые пароли не совпадают.</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="136"/>
<source>Wallet unlock failed</source>
<translation>Разблокировка бумажника не удалась</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="137"/>
<location filename="../askpassphrasedialog.cpp" line="148"/>
<location filename="../askpassphrasedialog.cpp" line="167"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>Указанный пароль не подходит.</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="147"/>
<source>Wallet decryption failed</source>
<translation>Расшифрование бумажника не удалось</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="161"/>
<source>Wallet passphrase was succesfully changed.</source>
<translation>Пароль бумажника успешно изменён.</translation>
</message>
</context>
<context>
<name>CBCoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="69"/>
<source>CosbyCoin Wallet</source>
<translation>CosbyCoin-бумажник</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="142"/>
<location filename="../bitcoingui.cpp" line="464"/>
<source>Synchronizing with network...</source>
<translation>Синхронизация с сетью...</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="145"/>
<source>Block chain synchronization in progress</source>
<translation>Идёт синхронизация цепочки блоков</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="176"/>
<source>&Overview</source>
<translation>О&бзор</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="177"/>
<source>Show general overview of wallet</source>
<translation>Показать общий обзор действий с бумажником</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="182"/>
<source>&Transactions</source>
<translation>&Транзакции</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="183"/>
<source>Browse transaction history</source>
<translation>Показать историю транзакций</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="188"/>
<source>&Address Book</source>
<translation>&Адресная книга</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="189"/>
<source>Edit the list of stored addresses and labels</source>
<translation>Изменить список сохранённых адресов и меток к ним</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="194"/>
<source>&Receive coins</source>
<translation>&Получение монет</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="195"/>
<source>Show the list of addresses for receiving payments</source>
<translation>Показать список адресов для получения платежей</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="200"/>
<source>&Send coins</source>
<translation>Отп&равка монет</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="201"/>
<source>Send coins to a CosbyCoin address</source>
<translation>Отправить монеты на указанный адрес</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="206"/>
<source>Sign &message</source>
<translation>Подписать &сообщение</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="207"/>
<source>Prove you control an address</source>
<translation>Доказать, что вы владеете адресом</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="226"/>
<source>E&xit</source>
<translation>В&ыход</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="227"/>
<source>Quit application</source>
<translation>Закрыть приложение</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="230"/>
<source>&About %1</source>
<translation>&О %1</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="231"/>
<source>Show information about CosbyCoin</source>
<translation>Показать информацию о CosbyCoin'е</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="233"/>
<source>About &Qt</source>
<translation>О &Qt</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="234"/>
<source>Show information about Qt</source>
<translation>Показать информацию о Qt</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="236"/>
<source>&Options...</source>
<translation>Оп&ции...</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="237"/>
<source>Modify configuration options for CosbyCoin</source>
<translation>Изменить настройки</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="239"/>
<source>Open &CosbyCoin</source>
<translation>&Показать бумажник</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="240"/>
<source>Show the CosbyCoin window</source>
<translation>Показать окно бумажника</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="241"/>
<source>&Export...</source>
<translation>&Экспорт...</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="242"/>
<source>Export the data in the current tab to a file</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoingui.cpp" line="243"/>
<source>&Encrypt Wallet</source>
<translation>&Зашифровать бумажник</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="244"/>
<source>Encrypt or decrypt wallet</source>
<translation>Зашифровать или расшифровать бумажник</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="246"/>
<source>&Backup Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoingui.cpp" line="247"/>
<source>Backup wallet to another location</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoingui.cpp" line="248"/>
<source>&Change Passphrase</source>
<translation>&Изменить пароль</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="249"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Изменить пароль шифрования бумажника</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="272"/>
<source>&File</source>
<translation>&Файл</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="281"/>
<source>&Settings</source>
<translation>&Настройки</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="287"/>
<source>&Help</source><|fim▁hole|> <message>
<location filename="../bitcoingui.cpp" line="294"/>
<source>Tabs toolbar</source>
<translation>Панель вкладок</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="305"/>
<source>Actions toolbar</source>
<translation>Панель действий</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="317"/>
<source>[testnet]</source>
<translation>[тестовая сеть]</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="407"/>
<source>CosbyCoin-qt</source>
<translation>CosbyCoin-qt</translation>
</message>
<message numerus="yes">
<location filename="../bitcoingui.cpp" line="449"/>
<source>%n active connection(s) to CosbyCoin network</source>
<translation><numerusform>%n активное соединение с сетью</numerusform><numerusform>%n активных соединений с сетью</numerusform><numerusform>%n активных соединений с сетью</numerusform></translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="475"/>
<source>Downloaded %1 of %2 blocks of transaction history.</source>
<translation>Загружено %1 из %2 блоков истории транзакций.</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="487"/>
<source>Downloaded %1 blocks of transaction history.</source>
<translation>Загружено %1 блоков истории транзакций.</translation>
</message>
<message numerus="yes">
<location filename="../bitcoingui.cpp" line="502"/>
<source>%n second(s) ago</source>
<translation><numerusform>%n секунду назад</numerusform><numerusform>%n секунды назад</numerusform><numerusform>%n секунд назад</numerusform></translation>
</message>
<message numerus="yes">
<location filename="../bitcoingui.cpp" line="506"/>
<source>%n minute(s) ago</source>
<translation><numerusform>%n минуту назад</numerusform><numerusform>%n минуты назад</numerusform><numerusform>%n минут назад</numerusform></translation>
</message>
<message numerus="yes">
<location filename="../bitcoingui.cpp" line="510"/>
<source>%n hour(s) ago</source>
<translation><numerusform>%n час назад</numerusform><numerusform>%n часа назад</numerusform><numerusform>%n часов назад</numerusform></translation>
</message>
<message numerus="yes">
<location filename="../bitcoingui.cpp" line="514"/>
<source>%n day(s) ago</source>
<translation><numerusform>%n день назад</numerusform><numerusform>%n дня назад</numerusform><numerusform>%n дней назад</numerusform></translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="520"/>
<source>Up to date</source>
<translation>Синхронизированно</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="525"/>
<source>Catching up...</source>
<translation>Синхронизируется...</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="533"/>
<source>Last received block was generated %1.</source>
<translation>Последний полученный блок был сгенерирован %1.</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="597"/>
<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>Данная транзакция превышает предельно допустимый размер. Но Вы можете всё равно совершить ей, добавив комиссию в %1, которая отправится тем узлам, которые обработают Вашу транзакцию и поможет поддержать сеть. Вы хотите добавить комиссию?</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="602"/>
<source>Sending...</source>
<translation>Отправка...</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="629"/>
<source>Sent transaction</source>
<translation>Исходящая транзакция</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="630"/>
<source>Incoming transaction</source>
<translation>Входящая транзакция</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="631"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Дата: %1
Количество: %2
Тип: %3
Адрес: %4
</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="751"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Бумажник <b>зашифрован</b> и в настоящее время <b>разблокирован</b></translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="759"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Бумажник <b>зашифрован</b> и в настоящее время <b>заблокирован</b></translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="782"/>
<source>Backup Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoingui.cpp" line="782"/>
<source>Wallet Data (*.dat)</source>
<translation>Данные Кошелька (*.dat)</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="785"/>
<source>Backup Failed</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoingui.cpp" line="785"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>DisplayOptionsPage</name>
<message>
<location filename="../optionsdialog.cpp" line="270"/>
<source>&Unit to show amounts in: </source>
<translation>&Измерять монеты в: </translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="274"/>
<source>Choose the default subdivision unit to show in the interface, and when sending coins</source>
<translation>Единица измерения количества монет при отображении и при отправке</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="281"/>
<source>Display addresses in transaction list</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 filename="../forms/editaddressdialog.ui" line="25"/>
<source>&Label</source>
<translation>&Метка</translation>
</message>
<message>
<location filename="../forms/editaddressdialog.ui" line="35"/>
<source>The label associated with this address book entry</source>
<translation>Метка, связанная с данной записью</translation>
</message>
<message>
<location filename="../forms/editaddressdialog.ui" line="42"/>
<source>&Address</source>
<translation>&Адрес</translation>
</message>
<message>
<location filename="../forms/editaddressdialog.ui" line="52"/>
<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="20"/>
<source>New receiving address</source>
<translation>Новый адрес для получения</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="24"/>
<source>New sending address</source>
<translation>Новый адрес для отправки</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="27"/>
<source>Edit receiving address</source>
<translation>Изменение адреса для получения</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="31"/>
<source>Edit sending address</source>
<translation>Изменение адреса для отправки</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="91"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>Введённый адрес «%1» уже находится в адресной книге.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="96"/>
<source>The entered address "%1" is not a valid CosbyCoin address.</source>
<translation>Введённый адрес «%1» не является правильным CosbyCoin-адресом.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="101"/>
<source>Could not unlock wallet.</source>
<translation>Не удается разблокировать бумажник.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="106"/>
<source>New key generation failed.</source>
<translation>Генерация нового ключа не удалась.</translation>
</message>
</context>
<context>
<name>MainOptionsPage</name>
<message>
<location filename="../optionsdialog.cpp" line="170"/>
<source>&Start CosbyCoin on window system startup</source>
<translation>&Запускать бумажник при входе в систему</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="171"/>
<source>Automatically start CosbyCoin after the computer is turned on</source>
<translation>Автоматически запускать бумажник, когда включается компьютер</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="175"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&Cворачивать в системный лоток вместо панели задач</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="176"/>
<source>Show only a tray icon after minimizing the window</source>
<translation>Показывать только иконку в системном лотке при сворачивании окна</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="180"/>
<source>Map port using &UPnP</source>
<translation>Пробросить порт через &UPnP</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="181"/>
<source>Automatically open the CosbyCoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>Автоматически открыть порт для CosbyCoin-клиента на роутере. Работает ТОЛЬКО если Ваш роутер поддерживает UPnP и данная функция включена.</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="185"/>
<source>M&inimize on close</source>
<translation>С&ворачивать вместо закрытия</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="186"/>
<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>Сворачивать вместо закрытия. Если данная опция будет выбрана — приложение закроется только после выбора соответствующего пункта в меню.</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="190"/>
<source>&Connect through SOCKS4 proxy:</source>
<translation>&Подключаться через SOCKS4 прокси:</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="191"/>
<source>Connect to the Bitcon network through a SOCKS4 proxy (e.g. when connecting through Tor)</source>
<translation>Подключаться к сети CosbyCoin через SOCKS4 прокси (например, при использовании Tor)</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="196"/>
<source>Proxy &IP: </source>
<translation>&IP Прокси: </translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="202"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation>IP-адрес прокси (например 127.0.0.1)</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="205"/>
<source>&Port: </source>
<translation>По&рт: </translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="211"/>
<source>Port of the proxy (e.g. 1234)</source>
<translation>Порт прокси-сервера (например 1234)</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="217"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source>
<translation>Опциональная комиссия за каждый КБ транзакции, которая позволяет быть уверенным, что Ваша транзакция будет обработано быстро. Большинство транзакций занимают 1КБ. Рекомендуется комиссия 0.01.</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="223"/>
<source>Pay transaction &fee</source>
<translation>Добавлять ко&миссию</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="226"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source>
<translation>Опциональная комиссия за каждый КБ транзакции, которая позволяет быть уверенным, что Ваша транзакция будет обработано быстро. Большинство транзакций занимают 1КБ. Рекомендуется комиссия 0.01.</translation>
</message>
</context>
<context>
<name>MessagePage</name>
<message>
<location filename="../forms/messagepage.ui" line="14"/>
<source>Message</source>
<translation>Сообщение</translation>
</message>
<message>
<location filename="../forms/messagepage.ui" line="20"/>
<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 filename="../forms/messagepage.ui" line="38"/>
<source>The address to send the payment to (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation>Адрес получателя платежа (например 1LA5FtQhnnWnkK6zjFfutR7Stiit4wKd63)</translation>
</message>
<message>
<location filename="../forms/messagepage.ui" line="48"/>
<source>Choose adress from address book</source>
<translation>Выбрать адрес из адресной книги</translation>
</message>
<message>
<location filename="../forms/messagepage.ui" line="58"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location filename="../forms/messagepage.ui" line="71"/>
<source>Paste address from clipboard</source>
<translation>Вставить адрес из буфера обмена</translation>
</message>
<message>
<location filename="../forms/messagepage.ui" line="81"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location filename="../forms/messagepage.ui" line="93"/>
<source>Enter the message you want to sign here</source>
<translation>Введите сообщение для подписи</translation>
</message>
<message>
<location filename="../forms/messagepage.ui" line="105"/>
<source>Click "Sign Message" to get signature</source>
<translation>Для создания подписи нажмите на "Подписать сообщение"</translation>
</message>
<message>
<location filename="../forms/messagepage.ui" line="117"/>
<source>Sign a message to prove you own this address</source>
<translation>Подпишите сообщение для доказательства </translation>
</message>
<message>
<location filename="../forms/messagepage.ui" line="120"/>
<source>&Sign Message</source>
<translation>&Подписать сообщение</translation>
</message>
<message>
<location filename="../forms/messagepage.ui" line="131"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Копировать текущий выделенный адрес в буфер обмена</translation>
</message>
<message>
<location filename="../forms/messagepage.ui" line="134"/>
<source>&Copy to Clipboard</source>
<translation>&Kопировать</translation>
</message>
<message>
<location filename="../messagepage.cpp" line="74"/>
<location filename="../messagepage.cpp" line="89"/>
<location filename="../messagepage.cpp" line="101"/>
<source>Error signing</source>
<translation>Ошибка создания подписи</translation>
</message>
<message>
<location filename="../messagepage.cpp" line="74"/>
<source>%1 is not a valid address.</source>
<translation>%1 не является правильным адресом.</translation>
</message>
<message>
<location filename="../messagepage.cpp" line="89"/>
<source>Private key for %1 is not available.</source>
<translation>Секретный ключ для %1 не доступен</translation>
</message>
<message>
<location filename="../messagepage.cpp" line="101"/>
<source>Sign failed</source>
<translation>Подписание не удалось.</translation>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../optionsdialog.cpp" line="79"/>
<source>Main</source>
<translation>Основное</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="84"/>
<source>Display</source>
<translation>Отображение</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="104"/>
<source>Options</source>
<translation>Опции</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="14"/>
<source>Form</source>
<translation>Форма</translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="40"/>
<source>Balance:</source>
<translation>Баланс:</translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="47"/>
<source>123.456 BTC</source>
<translation>123.456 BTC</translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="54"/>
<source>Number of transactions:</source>
<translation>Количество транзакций:</translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="61"/>
<source>0</source>
<translation>0</translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="68"/>
<source>Unconfirmed:</source>
<translation>Не подтверждено:</translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="75"/>
<source>0 BTC</source>
<translation>0 BTC</translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="82"/>
<source><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
<html><head><meta name="qrichtext" content="1" /><style type="text/css">
p, li { white-space: pre-wrap; }
</style></head><body style=" font-family:'Ubuntu'; font-size:11pt; font-weight:400; font-style:normal;">
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">Wallet</span></p></body></html></source>
<translation><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
<html><head><meta name="qrichtext" content="1" /><style type="text/css">
p, li { white-space: pre-wrap; }
</style></head><body style=" font-family:'Ubuntu'; font-size:11pt; font-weight:400; font-style:normal;">
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">Бумажник</span></p></body></html></translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="122"/>
<source><b>Recent transactions</b></source>
<translation><b>Последние транзакции</b></translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="103"/>
<source>Your current balance</source>
<translation>Ваш текущий баланс</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="108"/>
<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="111"/>
<source>Total number of transactions in wallet</source>
<translation>Общее количество транзакций в Вашем бумажнике</translation>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="14"/>
<source>Dialog</source>
<translation>Dialog</translation>
</message>
<message>
<location filename="../forms/qrcodedialog.ui" line="32"/>
<source>QR Code</source>
<translation>QR код</translation>
</message>
<message>
<location filename="../forms/qrcodedialog.ui" line="52"/>
<source>Request Payment</source>
<translation>Запросить платёж</translation>
</message>
<message>
<location filename="../forms/qrcodedialog.ui" line="67"/>
<source>Amount:</source>
<translation>Количество:</translation>
</message>
<message>
<location filename="../forms/qrcodedialog.ui" line="102"/>
<source>BTC</source>
<translation>BTC</translation>
</message>
<message>
<location filename="../forms/qrcodedialog.ui" line="118"/>
<source>Label:</source>
<translation>Метка:</translation>
</message>
<message>
<location filename="../forms/qrcodedialog.ui" line="141"/>
<source>Message:</source>
<translation>Сообщение:</translation>
</message>
<message>
<location filename="../forms/qrcodedialog.ui" line="183"/>
<source>&Save As...</source>
<translation>&Сохранить как...</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="101"/>
<source>Save Image...</source>
<translation>Сохранить изображение...</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="101"/>
<source>PNG Images (*.png)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="14"/>
<location filename="../sendcoinsdialog.cpp" line="122"/>
<location filename="../sendcoinsdialog.cpp" line="127"/>
<location filename="../sendcoinsdialog.cpp" line="132"/>
<location filename="../sendcoinsdialog.cpp" line="137"/>
<location filename="../sendcoinsdialog.cpp" line="143"/>
<location filename="../sendcoinsdialog.cpp" line="148"/>
<location filename="../sendcoinsdialog.cpp" line="153"/>
<source>Send Coins</source>
<translation>Отправка</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="64"/>
<source>Send to multiple recipients at once</source>
<translation>Отправить нескольким получателям одновременно</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="67"/>
<source>&Add recipient...</source>
<translation>&Добавить получателя...</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="84"/>
<source>Remove all transaction fields</source>
<translation>Удалить все поля транзакции</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="87"/>
<source>Clear all</source>
<translation>Очистить всё</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="106"/>
<source>Balance:</source>
<translation>Баланс:</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="113"/>
<source>123.456 BTC</source>
<translation>123.456 BTC</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="144"/>
<source>Confirm the send action</source>
<translation>Подтвердить отправку</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="147"/>
<source>&Send</source>
<translation>&Отправить</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="94"/>
<source><b>%1</b> to %2 (%3)</source>
<translation><b>%1</b> адресату %2 (%3)</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="99"/>
<source>Confirm send coins</source>
<translation>Подтвердите отправку монет</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="100"/>
<source>Are you sure you want to send %1?</source>
<translation>Вы уверены, что хотите отправить %1?</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="100"/>
<source> and </source>
<translation> и </translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="123"/>
<source>The recepient address is not valid, please recheck.</source>
<translation>Адрес получателя неверный, пожалуйста, перепроверьте.</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="128"/>
<source>The amount to pay must be larger than 0.</source>
<translation>Количество монет для отправки должно быть больше 0.</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="133"/>
<source>Amount exceeds your balance</source>
<translation>Количество отправляемых монет превышает Ваш баланс</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="138"/>
<source>Total exceeds your balance when the %1 transaction fee is included</source>
<translation>Сумма превысит Ваш баланс, если комиссия в %1 будет добавлена к транзакции</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="144"/>
<source>Duplicate address found, can only send to each address once in one send operation</source>
<translation>Обнаружен дублирующийся адрес. Отправка на один и тот же адрес возможна только один раз за одну операцию отправки</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="149"/>
<source>Error: Transaction creation failed </source>
<translation>Ошибка: Создание транзакции не удалось </translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="154"/>
<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.dat), а монеты были потрачены из другой копии, но не были отмечены как потраченные в этой. Или в случае кражи (компрометации) Вашего бумажника.</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="14"/>
<source>Form</source>
<translation>Форма</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="29"/>
<source>A&mount:</source>
<translation>Ко&личество:</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="42"/>
<source>Pay &To:</source>
<translation>Полу&чатель:</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="66"/>
<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 filename="../forms/sendcoinsentry.ui" line="75"/>
<source>&Label:</source>
<translation>&Метка:</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="93"/>
<source>The address to send the payment to (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation>Адрес получателя платежа (например 1LA5FtQhnnWnkK6zjFfutR7Stiit4wKd63)</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="103"/>
<source>Choose address from address book</source>
<translation>Выберите адрес из адресной книги</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="113"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="120"/>
<source>Paste address from clipboard</source>
<translation>Вставить адрес из буфера обмена</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="130"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="137"/>
<source>Remove this recipient</source>
<translation>Удалить этого получателя</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="25"/>
<source>Enter a CosbyCoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation>Введите CosbyCoin-адрес (например 1LA5FtQhnnWnkK6zjFfutR7Stiit4wKd63)</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="18"/>
<source>Open for %1 blocks</source>
<translation>Открыто до получения %1 блоков</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="20"/>
<source>Open until %1</source>
<translation>Открыто до %1</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="26"/>
<source>%1/offline?</source>
<translation>%1/оффлайн?</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="28"/>
<source>%1/unconfirmed</source>
<translation>%1/не подтверждено</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="30"/>
<source>%1 confirmations</source>
<translation>%1 подтверждений</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="47"/>
<source><b>Status:</b> </source>
<translation><b>Статус:</b> </translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="52"/>
<source>, has not been successfully broadcast yet</source>
<translation>, ещё не было успешно разослано</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="54"/>
<source>, broadcast through %1 node</source>
<translation>, разослано через %1 узел</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="56"/>
<source>, broadcast through %1 nodes</source>
<translation>, разослано через %1 узлов</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="60"/>
<source><b>Date:</b> </source>
<translation><b>Дата:</b> </translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="67"/>
<source><b>Source:</b> Generated<br></source>
<translation><b>Источник:</b> [сгенерированно]<br></translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="73"/>
<location filename="../transactiondesc.cpp" line="90"/>
<source><b>From:</b> </source>
<translation><b>Отправитель:</b> </translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="90"/>
<source>unknown</source>
<translation>неизвестно</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="91"/>
<location filename="../transactiondesc.cpp" line="114"/>
<location filename="../transactiondesc.cpp" line="173"/>
<source><b>To:</b> </source>
<translation><b>Получатель:</b> </translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="94"/>
<source> (yours, label: </source>
<translation> (Ваш, метка:</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="96"/>
<source> (yours)</source>
<translation> (ваш)</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="131"/>
<location filename="../transactiondesc.cpp" line="145"/>
<location filename="../transactiondesc.cpp" line="190"/>
<location filename="../transactiondesc.cpp" line="207"/>
<source><b>Credit:</b> </source>
<translation><b>Кредит:</b> </translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="133"/>
<source>(%1 matures in %2 more blocks)</source>
<translation>(%1 станет доступно через %2 блоков)</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="137"/>
<source>(not accepted)</source>
<translation>(не принято)</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="181"/>
<location filename="../transactiondesc.cpp" line="189"/>
<location filename="../transactiondesc.cpp" line="204"/>
<source><b>Debit:</b> </source>
<translation><b>Дебет:</b> </translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="195"/>
<source><b>Transaction fee:</b> </source>
<translation><b>Комиссия:</b> </translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="211"/>
<source><b>Net amount:</b> </source>
<translation><b>Общая сумма:</b> </translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="217"/>
<source>Message:</source>
<translation>Сообщение:</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="219"/>
<source>Comment:</source>
<translation>Комментарий:</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="221"/>
<source>Transaction ID:</source>
<translation>Идентификатор транзакции:</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="224"/>
<source>Generated coins must wait 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, it will change to "not accepted" and not be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation>Сгенерированные монеты должны подождать 120 блоков прежде, чем они смогут быть отправлены. Когда Вы сгенерировали этот блок он был отправлен в сеть, чтобы он был добавлен к цепочке блоков. Если данная процедура не удастся, статус изменится на «не подтверждено» и монеты будут непередаваемыми. Такое может случайно происходить в случае, если другой узел сгенерирует блок на несколько секунд раньше.</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="14"/>
<source>Transaction details</source>
<translation>Детали транзакции</translation>
</message>
<message>
<location filename="../forms/transactiondescdialog.ui" line="20"/>
<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="213"/>
<source>Date</source>
<translation>Дата</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="213"/>
<source>Type</source>
<translation>Тип</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="213"/>
<source>Address</source>
<translation>Адрес</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="213"/>
<source>Amount</source>
<translation>Количество</translation>
</message>
<message numerus="yes">
<location filename="../transactiontablemodel.cpp" line="274"/>
<source>Open for %n block(s)</source>
<translation><numerusform>Открыто для %n блока</numerusform><numerusform>Открыто для %n блоков</numerusform><numerusform>Открыто для %n блоков</numerusform></translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="277"/>
<source>Open until %1</source>
<translation>Открыто до %1</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="280"/>
<source>Offline (%1 confirmations)</source>
<translation>Оффлайн (%1 подтверждений)</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="283"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation>Не подтверждено (%1 из %2 подтверждений)</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="286"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Подтверждено (%1 подтверждений)</translation>
</message>
<message numerus="yes">
<location filename="../transactiontablemodel.cpp" line="295"/>
<source>Mined balance will be available in %n more blocks</source>
<translation><numerusform>Добытыми монетами можно будет воспользоваться через %n блок</numerusform><numerusform>Добытыми монетами можно будет воспользоваться через %n блока</numerusform><numerusform>Добытыми монетами можно будет воспользоваться через %n блоков</numerusform></translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="301"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>Этот блок не был получен другими узлами и, возможно, не будет принят!</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="304"/>
<source>Generated but not accepted</source>
<translation>Сгенерированно, но не подтверждено</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="347"/>
<source>Received with</source>
<translation>Получено</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="349"/>
<source>Received from</source>
<translation>Получено от</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="352"/>
<source>Sent to</source>
<translation>Отправлено</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="354"/>
<source>Payment to yourself</source>
<translation>Отправлено себе</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="356"/>
<source>Mined</source>
<translation>Добыто</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="394"/>
<source>(n/a)</source>
<translation>[не доступно]</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="593"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Статус транзакции. Подведите курсор к нужному полю для того, чтобы увидеть количество подтверждений.</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="595"/>
<source>Date and time that the transaction was received.</source>
<translation>Дата и время, когда транзакция была получена.</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="597"/>
<source>Type of transaction.</source>
<translation>Тип транзакции.</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="599"/>
<source>Destination address of transaction.</source>
<translation>Адрес назначения транзакции.</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="601"/>
<source>Amount removed from or added to balance.</source>
<translation>Сумма, добавленная, или снятая с баланса.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="55"/>
<location filename="../transactionview.cpp" line="71"/>
<source>All</source>
<translation>Все</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="56"/>
<source>Today</source>
<translation>Сегодня</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="57"/>
<source>This week</source>
<translation>На этой неделе</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="58"/>
<source>This month</source>
<translation>В этом месяце</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="59"/>
<source>Last month</source>
<translation>За последний месяц</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="60"/>
<source>This year</source>
<translation>В этом году</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="61"/>
<source>Range...</source>
<translation>Промежуток...</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="72"/>
<source>Received with</source>
<translation>Получено на</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="74"/>
<source>Sent to</source>
<translation>Отправлено на</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="76"/>
<source>To yourself</source>
<translation>Отправленные себе</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="77"/>
<source>Mined</source>
<translation>Добытые</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="78"/>
<source>Other</source>
<translation>Другое</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="84"/>
<source>Enter address or label to search</source>
<translation>Введите адрес или метку для поиска</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="90"/>
<source>Min amount</source>
<translation>Мин. сумма</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="124"/>
<source>Copy address</source>
<translation>Копировать адрес</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="125"/>
<source>Copy label</source>
<translation>Копировать метку</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="126"/>
<source>Copy amount</source>
<translation>Скопировать сумму</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="127"/>
<source>Edit label</source>
<translation>Изменить метку</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="128"/>
<source>Show details...</source>
<translation>Показать детали...</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="268"/>
<source>Export Transaction Data</source>
<translation>Экспортировать данные транзакций</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="269"/>
<source>Comma separated file (*.csv)</source>
<translation>Текс, разделённый запятыми (*.csv)</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="277"/>
<source>Confirmed</source>
<translation>Подтверждено</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="278"/>
<source>Date</source>
<translation>Дата</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="279"/>
<source>Type</source>
<translation>Тип</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="280"/>
<source>Label</source>
<translation>Метка</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="281"/>
<source>Address</source>
<translation>Адрес</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="282"/>
<source>Amount</source>
<translation>Количество</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="283"/>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="287"/>
<source>Error exporting</source>
<translation>Ошибка экспорта</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="287"/>
<source>Could not write to file %1.</source>
<translation>Невозможно записать в файл %1.</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="382"/>
<source>Range:</source>
<translation>Промежуток от:</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="390"/>
<source>to</source>
<translation>до</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="145"/>
<source>Sending...</source>
<translation>Отправка....</translation>
</message>
</context>
<context>
<name>CosbyCoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="3"/>
<source>CosbyCoin version</source>
<translation>Версия</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="4"/>
<source>Usage:</source>
<translation>Использование:</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="5"/>
<source>Send command to -server or cosbycoind</source>
<translation>Отправить команду на -server или cosbycoind</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="6"/>
<source>List commands</source>
<translation>Список команд
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="7"/>
<source>Get help for a command</source>
<translation>Получить помощь по команде</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="8"/>
<source>Options:</source>
<translation>Опции:</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="9"/>
<source>Specify configuration file (default: CosbyCoin.conf)</source>
<translation>Указать конфигурационный файл (по умолчанию: CosbyCoin.conf)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="10"/>
<source>Specify pid file (default: cosbycoind.pid)</source>
<translation>Указать pid-файл (по умолчанию: CosbyCoin.pid)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="11"/>
<source>Generate coins</source>
<translation>Генерировать монеты</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="12"/>
<source>Don't generate coins</source>
<translation>Не генерировать монеты</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="13"/>
<source>Start minimized</source>
<translation>Запускать свёрнутым</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="14"/>
<source>Specify data directory</source>
<translation>Укажите каталог данных</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="15"/>
<source>Specify connection timeout (in milliseconds)</source>
<translation>Укажите таймаут соединения (в миллисекундах)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="16"/>
<source>Connect through socks4 proxy</source>
<translation>Подключаться через socks4 прокси</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="17"/>
<source>Allow DNS lookups for addnode and connect</source>
<translation>Разрешить обращения к DNS для addnode и подключения</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="18"/>
<source>Listen for connections on <port> (default: 8333 or testnet: 18333)</source>
<translation>Принимать входящие подключения на <port> (по умолчанию: 8333 или 18333 в тестовой сети)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="19"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Поддерживать не более <n> подключений к узлам (по умолчанию: 125)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="20"/>
<source>Add a node to connect to</source>
<translation>Добавить узел для подключения</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="21"/>
<source>Connect only to the specified node</source>
<translation>Подключаться только к указанному узлу</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="22"/>
<source>Don't accept connections from outside</source>
<translation>Не принимать входящие подключения</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="23"/>
<source>Don't bootstrap list of peers using DNS</source>
<translation>Не получать начальный список узлов через DNS</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="24"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>Порог для отключения неправильно ведущих себя узлов (по умолчанию: 100)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="25"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>Число секунд блокирования неправильно ведущих себя узлов (по умолчанию: 86400)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="28"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 10000)</source>
<translation>Максимальный размер буфера приёма на соединение, <n>*1000 байт (по умолчанию: 10000)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="29"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 10000)</source>
<translation>Максимальный размер буфера отправки на соединение, <n>*1000 байт (по умолчанию: 10000)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="30"/>
<source>Don't attempt to use UPnP to map the listening port</source>
<translation>Не пытаться использовать UPnP для назначения входящего порта</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="31"/>
<source>Attempt to use UPnP to map the listening port</source>
<translation>Пытаться использовать UPnP для назначения входящего порта</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="32"/>
<source>Fee per kB to add to transactions you send</source>
<translation>Комиссия на Кб, добавляемая к вашим переводам</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="33"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Принимать командную строку и команды JSON-RPC</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="34"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Запускаться в фоне как демон и принимать команды</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="35"/>
<source>Use the test network</source>
<translation>Использовать тестовую сеть</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="36"/>
<source>Output extra debugging information</source>
<translation>Выводить дополнительную отладочную информацию</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="37"/>
<source>Prepend debug output with timestamp</source>
<translation>Дописывать отметки времени к отладочному выводу</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="38"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Выводить информацию трассировки/отладки на консоль вместо файла debug.log</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="39"/>
<source>Send trace/debug info to debugger</source>
<translation>Отправлять информацию трассировки/отладки в отладчик</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="40"/>
<source>Username for JSON-RPC connections</source>
<translation>Имя для подключений JSON-RPC</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="41"/>
<source>Password for JSON-RPC connections</source>
<translation>Пароль для подключений JSON-RPC</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="42"/>
<source>Listen for JSON-RPC connections on <port> (default: 8332)</source>
<translation>Ожидать подключения JSON-RPC на <порт> (по умолчанию: 8332)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="43"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Разрешить подключения JSON-RPC с указанного IP</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="44"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Посылать команды узлу, запущенному на <ip> (по умолчанию: 127.0.0.1)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="45"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Установить размер запаса ключей в <n> (по умолчанию: 100)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="46"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Перепроверить цепь блоков на предмет отсутствующих в кошельке транзакций</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="47"/>
<source>
SSL options: (see the CosbyCoin Wiki for SSL setup instructions)</source>
<translation>
Параметры SSL: (см. CosbyCoin Wiki для инструкций по настройке SSL)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="50"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>Использовать OpenSSL (https) для подключений JSON-RPC</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="51"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Файл серверного сертификата (по умолчанию: server.cert)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="52"/>
<source>Server private key (default: server.pem)</source>
<translation>Приватный ключ сервера (по умолчанию: server.pem)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="53"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation>Разрешённые алгоритмы (по умолчанию: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="56"/>
<source>This help message</source>
<translation>Эта справка</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="57"/>
<source>Cannot obtain a lock on data directory %s. CosbyCoin is probably already running.</source>
<translation>Невозможно установить блокировку на рабочую директорию %s. Возможно, бумажник уже запущен.</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="60"/>
<source>Loading addresses...</source>
<translation>Загрузка адресов...</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="61"/>
<source>Error loading addr.dat</source>
<translation>Ошибка загрузки addr.dat</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="63"/>
<source>Error loading blkindex.dat</source>
<translation>Ошибка чтения blkindex.dat</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="65"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>Ошибка загрузки wallet.dat: Бумажник поврежден</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="66"/>
<source>Error loading wallet.dat: Wallet requires newer version of CosbyCoin</source>
<translation>Ошибка загрузки wallet.dat: бумажник требует более новую версию CosbyCoin</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="67"/>
<source>Wallet needed to be rewritten: restart CosbyCoin to complete</source>
<translation>Необходимо перезаписать бумажник, перезапустите CosbyCoin для завершения операции.</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="68"/>
<source>Error loading wallet.dat</source>
<translation>Ошибка при загрузке wallet.dat</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="62"/>
<source>Loading block index...</source>
<translation>Загрузка индекса блоков...</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="64"/>
<source>Loading wallet...</source>
<translation>Загрузка бумажника...</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="69"/>
<source>Rescanning...</source>
<translation>Сканирование...</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="70"/>
<source>Done loading</source>
<translation>Загрузка завершена</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="71"/>
<source>Invalid -proxy address</source>
<translation>Ошибка в адресе прокси</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="72"/>
<source>Invalid amount for -paytxfee=<amount></source>
<translation>Ошибка в сумме комиссии</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="73"/>
<source>Warning: -paytxfee is set very high. This is the transaction fee you will pay if you send a transaction.</source>
<translation>ВНИМАНИЕ: Установлена слишком большая комиссия (-paytxfee=). Данный параметр отвечает за комиссию, которую Вы будете добавлять к сумме при осуществлении транзакций.</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="76"/>
<source>Error: CreateThread(StartNode) failed</source>
<translation>Ошибка: Созданиние потока (запуск узла) не удался</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="77"/>
<source>Warning: Disk space is low </source>
<translation>ВНИМАНИЕ: На диске заканчивается свободное пространство </translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="78"/>
<source>Unable to bind to port %d on this computer. CosbyCoin is probably already running.</source>
<translation>Невозможно забиндить порт %d на данном компьютере. Возможно, бумажник ужк запущен.</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="81"/>
<source>Warning: Please check that your computer's date and time are correct. If your clock is wrong CosbyCoin will not work properly.</source>
<translation>ВНИМАНИЕ: Проверьте дату и время, установленные на Вашем компьютере. Если Ваши часы идут не правильно CosbyCoin может наботать не корректно.</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="84"/>
<source>beta</source>
<translation>бета</translation>
</message>
</context>
</TS><|fim▁end|>
|
<translation>&Помощь</translation>
</message>
|
<|file_name|>clusterrole.go<|end_file_name|><|fim▁begin|>/*
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package v1alpha1
import (
api "k8s.io/kubernetes/pkg/api"
v1 "k8s.io/kubernetes/pkg/api/v1"
meta_v1 "k8s.io/kubernetes/pkg/apis/meta/v1"<|fim▁hole|> v1alpha1 "k8s.io/kubernetes/pkg/apis/rbac/v1alpha1"
restclient "k8s.io/kubernetes/pkg/client/restclient"
watch "k8s.io/kubernetes/pkg/watch"
)
// ClusterRolesGetter has a method to return a ClusterRoleInterface.
// A group's client should implement this interface.
type ClusterRolesGetter interface {
ClusterRoles() ClusterRoleInterface
}
// ClusterRoleInterface has methods to work with ClusterRole resources.
type ClusterRoleInterface interface {
Create(*v1alpha1.ClusterRole) (*v1alpha1.ClusterRole, error)
Update(*v1alpha1.ClusterRole) (*v1alpha1.ClusterRole, error)
Delete(name string, options *v1.DeleteOptions) error
DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error
Get(name string, options meta_v1.GetOptions) (*v1alpha1.ClusterRole, error)
List(opts v1.ListOptions) (*v1alpha1.ClusterRoleList, error)
Watch(opts v1.ListOptions) (watch.Interface, error)
Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *v1alpha1.ClusterRole, err error)
ClusterRoleExpansion
}
// clusterRoles implements ClusterRoleInterface
type clusterRoles struct {
client restclient.Interface
}
// newClusterRoles returns a ClusterRoles
func newClusterRoles(c *RbacV1alpha1Client) *clusterRoles {
return &clusterRoles{
client: c.RESTClient(),
}
}
// Create takes the representation of a clusterRole and creates it. Returns the server's representation of the clusterRole, and an error, if there is any.
func (c *clusterRoles) Create(clusterRole *v1alpha1.ClusterRole) (result *v1alpha1.ClusterRole, err error) {
result = &v1alpha1.ClusterRole{}
err = c.client.Post().
Resource("clusterroles").
Body(clusterRole).
Do().
Into(result)
return
}
// Update takes the representation of a clusterRole and updates it. Returns the server's representation of the clusterRole, and an error, if there is any.
func (c *clusterRoles) Update(clusterRole *v1alpha1.ClusterRole) (result *v1alpha1.ClusterRole, err error) {
result = &v1alpha1.ClusterRole{}
err = c.client.Put().
Resource("clusterroles").
Name(clusterRole.Name).
Body(clusterRole).
Do().
Into(result)
return
}
// Delete takes name of the clusterRole and deletes it. Returns an error if one occurs.
func (c *clusterRoles) Delete(name string, options *v1.DeleteOptions) error {
return c.client.Delete().
Resource("clusterroles").
Name(name).
Body(options).
Do().
Error()
}
// DeleteCollection deletes a collection of objects.
func (c *clusterRoles) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error {
return c.client.Delete().
Resource("clusterroles").
VersionedParams(&listOptions, api.ParameterCodec).
Body(options).
Do().
Error()
}
// Get takes name of the clusterRole, and returns the corresponding clusterRole object, and an error if there is any.
func (c *clusterRoles) Get(name string, options meta_v1.GetOptions) (result *v1alpha1.ClusterRole, err error) {
result = &v1alpha1.ClusterRole{}
err = c.client.Get().
Resource("clusterroles").
Name(name).
VersionedParams(&options, api.ParameterCodec).
Do().
Into(result)
return
}
// List takes label and field selectors, and returns the list of ClusterRoles that match those selectors.
func (c *clusterRoles) List(opts v1.ListOptions) (result *v1alpha1.ClusterRoleList, err error) {
result = &v1alpha1.ClusterRoleList{}
err = c.client.Get().
Resource("clusterroles").
VersionedParams(&opts, api.ParameterCodec).
Do().
Into(result)
return
}
// Watch returns a watch.Interface that watches the requested clusterRoles.
func (c *clusterRoles) Watch(opts v1.ListOptions) (watch.Interface, error) {
return c.client.Get().
Prefix("watch").
Resource("clusterroles").
VersionedParams(&opts, api.ParameterCodec).
Watch()
}
// Patch applies the patch and returns the patched clusterRole.
func (c *clusterRoles) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *v1alpha1.ClusterRole, err error) {
result = &v1alpha1.ClusterRole{}
err = c.client.Patch(pt).
Resource("clusterroles").
SubResource(subresources...).
Name(name).
Body(data).
Do().
Into(result)
return
}<|fim▁end|>
| |
<|file_name|>15.2.3.5-4-258.js<|end_file_name|><|fim▁begin|>/// Copyright (c) 2012 Ecma International. All rights reserved.
/**
* @path ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-258.js
* @description Object.create - 'get' property of one property in 'Properties' is the primitive value null (8.10.5 step 7.b)
*/
<|fim▁hole|> prop: {
get: null
}
});
return false;
} catch (e) {
return (e instanceof TypeError);
}
}
runTestCase(testcase);<|fim▁end|>
|
function testcase() {
try {
Object.create({}, {
|
<|file_name|>perm_test.py<|end_file_name|><|fim▁begin|>import numpy as np
import itertools
from scipy.misc import comb as bincoef
import random
#########################################################################
# GENERATORS
#########################################################################
def sign_permutations(length):
""" Memory efficient generator: generate all n^2 sign permutations. """
# return a generator which generates the product of "length" smaller
# generators of (-1 or +1) (i.e. the unrolled signs, evaulated as needed)
return itertools.product([-1, 1], repeat=length)
def random_product(*args, **kwds):
""" Random selection from itertools.product(*args, **kwds). """
pools = map(tuple, args) * kwds.get('repeat', 1)
limiter = 0
generate_limit = kwds.get('generate_limit', None)
while True if generate_limit == None else limiter < generate_limit:
limiter = limiter + 1
yield tuple(random.choice(pool) for pool in pools)
def random_sign_permutations(length, limit):
""" Random sign permutation generator. """
return random_product([-1, 1], repeat=length, generate_limit=limit)
def binary_combinations(length, sublength, comb_function=itertools.combinations, limit=None):
""" Memory efficient generator: generate all length choose sublength combinations. """
# get the combination indices, support both infinite and finite length generators
combination_indices = comb_function(range(length), sublength, limit) if limit else comb_function(range(length), sublength)
def indices_to_sign_vectors():
""" Generates sign vectors from indices. """
for index_tuple in combination_indices:
for i in xrange(length):
yield 1 if index_tuple.count(i) > 0 else 0
def grouper(n, iterable, fillvalue=None):
" For grouping a generated stream into tuples. "
args = [iter(iterable)] * n
return itertools.izip_longest(fillvalue=fillvalue, *args)
# generate all combinations, grouped into tuples
return grouper(length, indices_to_sign_vectors())
def random_combination(iterable, r, limit=None):
""" Random selection from itertools.combinations(iterable, r). """
pool = tuple(iterable)
n = len(pool)
limiter = 0
comb = bincoef(len(iterable), r)
print comb
comb_indices = random.sample(xrange(comb), limit)
while True if limit == None else limiter < limit:
print comb_indices[limiter]
perm = get_nth_perm(pool, comb_indices[limiter])
subpool = sorted(perm[:r])
indices = sorted(random.sample(xrange(n), r))
print tuple(pool[i] for i in indices), subpool, perm
limiter = limiter + 1
yield tuple(pool[i] for i in indices)
def _progress_bar(self, max=100, label=""):
class Progress:
def __init__(self, max=100, label=""):
self.value = 1
self.label = label
self.max = max
def set(self, value):
self.value = value
p50 = int(50.0 * value / self.max)
if value >= self.max:
self.clear()
else:
sys.stdout.write("\r" + "|"*p50 + "\033[30m" + "·"*(50-p50) + "\033[0m %02d%% %s" % (p50*2, self.label))
sys.stdout.flush()
def advance(self):
self.set(self.value + 1)
def clear(self):
sys.stdout.write("\r"+" "*(80 + len(self.label))+"\r")
sys.stdout.flush()
return Progress(max, label)
def permutation_test(self, other, variables=None, ranked=False, two_samples=False, limit=1000):
"""Performs a permutation test on the given or the default dependent variables.
If two_samples is True, will conduct a two-sample test. Otherwise a one-sample test will be conducted.
If ranked is True, a Wilcoxon / Wilcoxon-Mann-Whitney test will be used for the one-sample /
two-sample case, respectively. Otherwise a Fisher / Pitman test will be conducted."""
variables = self._np1d(variables, fallback = self.dependent)
for var in variables:
A = self.get(var)
B = other.get(var)
if not two_samples:
D = [a - b for a, b in zip(A, B)]
if ranked:
D = self._signed_rank(D)
result = perm_test.one_sample(D, progress_bar = self._progress_bar(), limit=limit)
else:
if ranked:
D = self._rank(np.concatenate((A, B)))
A, B = D[:len(A)], D[len(A):]
result = perm_test.two_sample(A, B, progress_bar = self._progress_bar(), limit=limit)
return result
def _signed_rank(self, values):
"""Returns the signed rank of a list of values"""
lambda_signs = np.vectorize(lambda num: 1 if num >= 0 else -1)
signs = lambda_signs(values)
ranks = np.round(stats.rankdata(np.abs(values))).astype(int)
return signs*ranks
def signed_rank(self, attribute):
"""Returns the signed ranks of the data of the given attribute"""
values = self.get(attribute)
return self._signed_rank(values)
def _rank(self, values):
"""Returns the ranks of the data of a list of values"""
ranks = np.round(stats.rankdata(values)).astype(int)
return ranks
def rank(self, attribute):
"""Returns the ranks of the data of the given attribute"""
values = self.get(attribute)
return self._rank(values)
# def random_combination(iterable, r, limit=1000):
# """ Random selection from itertools.combinations(iterable, r). """
# pool = tuple(iterable)
# # number of
# comb = bincoef(len(iterable), r)
# comb_indices = random.sample(xrange(comb), limit)
# n = len(pool)
# limiter = 0
# for i in comb_indices:
# perm = get_nth_perm(pool, i)
# subpool = sorted(perm[:r])
# yield tuple(subpool)
def get_nth_perm(seq, index):
"Returns the <index>th permutation of <seq>"
seqc= list(seq[:])
seqn= [seqc.pop()]
divider= 2 # divider is meant to be len(seqn)+1, just a bit faster
while seqc:
index, new_index= index//divider, index%divider
seqn.insert(new_index, seqc.pop())
divider+= 1
return seqn
#########################################################################
# ACTUAL TESTS
#########################################################################
def one_sample(A, limit = 10000, progress_bar = None):
""" Conducts a permutation test on the input data"""
stat_ref = np.sum(A)
# count permutation test statistics <=, >=, or ||>=|| than reference stat
counts = np.array([0,0,0]) # (lesser, greater, more extreme)
total_perms = 2**len(A)
if total_perms < limit:
limit = total_perms
if progress_bar:
progress_bar.max = limit
progress_bar.label = "of %d permutations" % progress_bar.max
for sign_row in sign_permutations(len(A)):
stat_this = np.sum(np.array(A)*sign_row)
counts = counts + stat_compare(stat_ref,stat_this)
if progress_bar:
progress_bar.advance()
# return p-values for lower, upper, and two-tail tests (FP number)
return counts / 2.0**len(A)
def two_sample(A, B, limit = 10000, progress_bar = None):
""" Conducts a permutation test on the input data, transformed by fun. """
# apply transformation to input data (e.g. signed-rank for WMW)<|fim▁hole|> counts = np.array([0,0,0]) # (lesser, greater)
total_perms = bincoef(len(data), len(A))
if not limit or total_perms < limit :
limit = None
comb_function = itertools.combinations
else:
comb_function = random_combination
if progress_bar:
progress_bar.max = limit or total_perms
progress_bar.label = "of %d permutations" % progress_bar.max
for binary_row in binary_combinations(len(data), len(A), comb_function=comb_function, limit=limit):
#print binary_row
stat_this = np.sum(np.array(data)*binary_row)
counts = counts + stat_compare(stat_ref,stat_this)
# if progress_bar:
# progress_bar.advance()
# return p-values for lower, upper, and two-tail tests (FP number)
n_comb = np.multiply.reduce(np.array(range(len(data)-len(A)+1,len(data)+1)))\
/ np.multiply.reduce(np.array(range(1,len(A)+1)))
n_comb = limit or total_perms
counts[2] = min(2*counts[0:2].min(),n_comb) # hack to define p.twotail as 2*smaller of 1 tail p's
return counts / float(n_comb)
def stat_compare(ref,test):
""" Tests for comparing permutation and observed test statistics"""
lesser = 1 * (test <= ref)
greater = 1 * (test >= ref)
more_extreme = 1 * (np.abs(test) >= np.abs(ref))
return np.array([lesser,greater,more_extreme])<|fim▁end|>
|
data = np.concatenate((A, B))
stat_ref = np.sum(A)
# count permutation test statistics <=, >=, or ||>=|| than reference stat
|
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
__version__ = '0.5.0'<|fim▁hole|><|fim▁end|>
|
request_post_identifier = 'current_aldryn_blog_entry'
|
<|file_name|>text.js<|end_file_name|><|fim▁begin|>import test from 'ava';
import React from 'react';
import { shallow } from 'enzyme';
import Text from '../../../src/components/form-inputs/text';
test('Text | default props', (t) => {
const textWrapper = shallow(<Text />);
t.deepEqual(textWrapper.props(), {
type: 'text',
'data-form-id': '',
className: '',
id: '',
placeholder: '',
required: false,
value: '',
min: -1,<|fim▁hole|> });
});
test('Text | all props filled', (t) => {
const textWrapper = shallow(
<Text
className="test-class"
data-form-id="test-form-id"
id="test-id"
placeholder="test-placeholder"
required
value="test-value"
min={8}
max={30}
/>,
);
t.deepEqual(textWrapper.props(), {
type: 'text',
'data-form-id': 'test-form-id',
className: 'test-class',
id: 'test-id',
placeholder: 'test-placeholder',
required: true,
value: 'test-value',
min: 8,
max: 30,
});
});<|fim▁end|>
|
max: -1,
|
<|file_name|>logistic.rs<|end_file_name|><|fim▁begin|>use la::Matrix;
use opt::GradientDescent;
pub struct LogisticRegression {
theta : Matrix<f64>,
threshold : f64
}
impl LogisticRegression {
pub fn train<F : FnMut(f64) -> ()>(x : &Matrix<f64>, y : &Matrix<bool>, learning_rate : f64, max_iterations : usize, mut iter_notify_f_opt : Option<F>) -> LogisticRegression {
let extx = Matrix::one_vector(x.rows()).cr(x);
let numy = y.map(&|b : &bool| -> f64 { if *b { 1.0 } else { 0.0 } });
let mut theta = Matrix::new(extx.cols(), 1, vec![0.0f64; extx.cols()]);
let error_f = |theta : &Matrix<f64>| {
(&extx * theta).map(&|t : &f64| -> f64 { 1.0f64 / (1.0f64 + (- *t).exp()) }) - &numy
};
let grad_f = |error : &Matrix<f64>| {
// error = 1 / (1 + e^(- theta^T * x)) - y
// grad = 1 / m * x' * error
(extx.t() * error).scale(1.0f64 / extx.rows() as f64)
};
let cost_f = |error : &Matrix<f64>| {
// J(theta) = 1 / m * SUM{i = 1 to m}: Cost(h_theta(x), y)
// Cost(h_theta(x), y) = { - log(h_theta(x)) , if y = true (1)
// , - log(1 - h_theta(x)) } , if y = false (0)
// = - y * log(h_theta(x)) - (1 - y) * log(1 - h_theta(x))
error.dot(&error) / extx.rows() as f64
};
{
let mut grad_desc = GradientDescent::new(learning_rate, &mut theta, &error_f, &grad_f);
for _ in 0..max_iterations {
let res = grad_desc.iterate();
match &mut iter_notify_f_opt {
&mut Some(ref mut f) => {
f(cost_f(&res.error));
}
_ => { }
}
}
}
LogisticRegression {
theta : theta,
threshold : 0.5
}
}
pub fn get_theta<'a>(&'a self) -> &'a Matrix<f64> {
&self.theta
}
pub fn get_threshold(&self) -> f64 {
self.threshold
}
#[inline]
pub fn set_threshold(&mut self, threshold : f64) {
self.threshold = threshold;
}
<|fim▁hole|>
// sum = theta^T * x
let mut sum = self.theta.get_data()[0];
for i in 1..self.theta.get_data().len() {
sum += self.theta.get_data()[i] * x.get_data()[i - 1];
}
1.0 / (1.0 + (- sum).exp())
}
// h(x) >= threshold
pub fn predict(&self, x : &Matrix<f64>) -> bool {
(self.p(x) >= self.threshold)
}
#[inline]
pub fn hypothesis(&self, x : &Matrix<f64>) -> bool {
self.predict(x)
}
}<|fim▁end|>
|
// h(x) = 1 / (1 + e^(- theta^T * [1; x]))
pub fn p(&self, x : &Matrix<f64>) -> f64 {
assert!(x.cols() == 1);
assert!((x.rows() + 1) == self.theta.get_data().len());
|
<|file_name|>gulpfile.js<|end_file_name|><|fim▁begin|>// ## Globals
/*global $:true*/
var $ = require('gulp-load-plugins')({rename: {'gulp-jade-php': 'jade' }});
var argv = require('yargs').argv;
var browserSync = require('browser-sync');
var gulp = require('gulp');
var lazypipe = require('lazypipe');
var merge = require('merge-stream');
var runSequence = require('run-sequence');
// See https://github.com/austinpray/asset-builder
var manifest = require('asset-builder')('./assets/manifest.json');
// `path` - Paths to base asset directories. With trailing slashes.
// - `path.source` - Path to the source files. Default: `assets/`
// - `path.dist` - Path to the build directory. Default: `dist/`
var path = manifest.paths;
// `config` - Store arbitrary configuration values here.
var config = manifest.config || {};
// `globs` - These ultimately end up in their respective `gulp.src`.
// - `globs.js` - Array of asset-builder JS dependency objects. Example:
// ```
// {type: 'js', name: 'main.js', globs: []}
// ```
// - `globs.css` - Array of asset-builder CSS dependency objects. Example:
// ```
// {type: 'css', name: 'main.css', globs: []}
// ```
// - `globs.fonts` - Array of font path globs.
// - `globs.images` - Array of image path globs.
// - `globs.bower` - Array of all the main Bower files.
var globs = manifest.globs;
// `project` - paths to first-party assets.
// - `project.js` - Array of first-party JS assets.
// - `project.css` - Array of first-party CSS assets.
var project = manifest.getProjectGlobs();
// CLI options
var enabled = {
// Enable static asset revisioning when `--production`
rev: argv.production,
// Disable source maps when `--production`
maps: !argv.production,
// Fail styles task on error when `--production`
failStyleTask: argv.production
};
// Path to the compiled assets manifest in the dist directory
var revManifest = path.dist + 'assets.json';
// ## Reusable Pipelines
// See https://github.com/OverZealous/lazypipe
// ### CSS processing pipeline
// Example
// ```
// gulp.src(cssFiles)
// .pipe(cssTasks('main.css')
// .pipe(gulp.dest(path.dist + 'styles'))
// ```
var cssTasks = function(filename) {
return lazypipe()
.pipe(function() {
return $.if(!enabled.failStyleTask, $.plumber());
})
.pipe(function() {
return $.if(enabled.maps, $.sourcemaps.init());
})
.pipe(function() {
return $.if('*.less', $.less());
})
.pipe(function() {
return $.if('*.scss', $.sass({
outputStyle: 'nested', // libsass doesn't support expanded yet
precision: 10,
includePaths: ['.'],
errLogToConsole: !enabled.failStyleTask
}));
})
.pipe($.concat, filename)
.pipe($.autoprefixer, {
browsers: [
'last 2 versions', 'ie 8', 'ie 9', 'android 2.3', 'android 4',
'opera 12'
]
})
.pipe($.minifyCss)
.pipe(function() {
return $.if(enabled.rev, $.rev());
})
.pipe(function() {
return $.if(enabled.maps, $.sourcemaps.write('.'));
})();
};
// ### JS processing pipeline
// Example
// ```
// gulp.src(jsFiles)
// .pipe(jsTasks('main.js')
// .pipe(gulp.dest(path.dist + 'scripts'))
// ```
var jsTasks = function(filename) {
return lazypipe()
.pipe(function() {
return $.if(enabled.maps, $.sourcemaps.init());
})
.pipe($.concat, filename)
.pipe($.uglify)
.pipe(function() {
return $.if(enabled.rev, $.rev());
})
.pipe(function() {
return $.if(enabled.maps, $.sourcemaps.write('.'));
})();
};
// ### Write to rev manifest
// If there are any revved files then write them to the rev manifest.
// See https://github.com/sindresorhus/gulp-rev
var writeToManifest = function(directory) {
return lazypipe()
.pipe(gulp.dest, path.dist + directory)
.pipe(function() {
return $.if('**/*.{js,css}', browserSync.reload({stream:true}));
})
.pipe($.rev.manifest, revManifest, {
base: path.dist,
merge: true
})
.pipe(gulp.dest, path.dist)();
};
// ## Gulp tasks
// Run `gulp -T` for a task summary
// ### Styles
// `gulp styles` - Compiles, combines, and optimizes Bower CSS and project CSS.
// By default this task will only log a warning if a precompiler error is
// raised. If the `--production` flag is set: this task will fail outright.
gulp.task('styles', ['wiredep'], function() {
var merged = merge();
manifest.forEachDependency('css', function(dep) {
var cssTasksInstance = cssTasks(dep.name);
if (!enabled.failStyleTask) {
cssTasksInstance.on('error', function(err) {
console.error(err.message);
this.emit('end');
});
}
merged.add(gulp.src(dep.globs, {base: 'styles'})
.pipe(cssTasksInstance));
});
return merged
.pipe(writeToManifest('styles'));
});
// ### Scripts
// `gulp scripts` - Runs JSHint then compiles, combines, and optimizes Bower JS
// and project JS.
gulp.task('scripts', ['jshint'], function() {
var merged = merge();
manifest.forEachDependency('js', function(dep) {
merged.add(
gulp.src(dep.globs, {base: 'scripts'})
.pipe(jsTasks(dep.name))
);
});
return merged
.pipe(writeToManifest('scripts'));
});
// ### Fonts
// `gulp fonts` - Grabs all the fonts and outputs them in a flattened directory
// structure. See: https://github.com/armed/gulp-flatten
gulp.task('fonts', function() {
return gulp.src(globs.fonts)
.pipe($.flatten())
.pipe(gulp.dest(path.dist + 'fonts'));
});
// ### Images
// `gulp images` - Run lossless compression on all the images.
gulp.task('images', function() {
return gulp.src(globs.images)
.pipe($.imagemin({
progressive: true,
interlaced: true,
svgoPlugins: [{removeUnknownsAndDefaults: false}]
}))
.pipe(gulp.dest(path.dist + 'images'));
});
// ### JSHint
// `gulp jshint` - Lints configuration JSON and project JS.
gulp.task('jshint', function() {
return gulp.src([
'bower.json', 'gulpfile.js'
].concat(project.js))
.pipe($.jshint())
.pipe($.jshint.reporter('jshint-stylish'))
.pipe($.jshint.reporter('fail'));
});
// ### Jade Templates
// be careful - these views will overwrite the defaults in the root
// gulp.task('jade', function() {
// gulp.src('./assets/views/**/*.jade')
// .pipe($.jade({ pretty : true }))
// .on('error', function(err) {
// console.error(err.message);
// this.emit('end');
// })
// .pipe(gulp.dest('.'))
// ;
// });
// ### Clean
// `gulp clean` - Deletes the build folder entirely.
gulp.task('clean', require('del').bind(null, [path.dist]));
// ### Watch
// `gulp watch` - Use BrowserSync to proxy your dev server and synchronize code
// changes across devices. Specify the hostname of your dev server at
// `manifest.config.devUrl`. When a modification is made to an asset, run the
// build step for that asset and inject the changes into the page.
// See: http://www.browsersync.io
gulp.task('watch', function() {
browserSync({
proxy: config.devUrl,
snippetOptions: {
whitelist: ['/wp-admin/admin-ajax.php'],
blacklist: ['/wp-admin/**']
}
});
// gulp.watch([path.source + 'views/**/*'], ['jade']);
gulp.watch([path.source + 'styles/**/*'], ['styles']);
gulp.watch([path.source + 'scripts/**/*'], ['jshint', 'scripts']);
gulp.watch([path.source + 'fonts/**/*'], ['fonts']);
gulp.watch([path.source + 'images/**/*'], ['images']);
gulp.watch(['bower.json', 'assets/manifest.json'], ['build']);
gulp.watch('**/*.php', function() {
browserSync.reload();
});
});
// ### Build
// `gulp build` - Run all the build tasks but don't clean up beforehand.
// Generally you should be running `gulp` instead of `gulp build`.
gulp.task('build', function(callback) {
runSequence('styles',
'scripts',
['fonts', 'images'],
callback);
});<|fim▁hole|>// ### Wiredep
// `gulp wiredep` - Automatically inject Less and Sass Bower dependencies. See
// https://github.com/taptapship/wiredep
gulp.task('wiredep', function() {
var wiredep = require('wiredep').stream;
return gulp.src(project.css)
.pipe(wiredep())
.pipe($.changed(path.source + 'styles', {
hasChanged: $.changed.compareSha1Digest
}))
.pipe(gulp.dest(path.source + 'styles'));
});
// ### Gulp
// `gulp` - Run a complete build. To compile for production run `gulp --production`.
gulp.task('default', ['clean'], function() {
gulp.start('build');
});<|fim▁end|>
| |
<|file_name|>syslog.py<|end_file_name|><|fim▁begin|>import SocketServer
from abc import ABCMeta, abstractmethod
import json
import requests
import six
from .. import LOG as _LOG
from ..signal.signal import DEFAULT_ORCHESTRATOR_URL
from ..signal.event import LogEvent
LOG = _LOG.getChild(__name__)
@six.add_metaclass(ABCMeta)
class SyslogInspectorBase(object):
def __init__(
self, udp_port=10514, orchestrator_rest_url=DEFAULT_ORCHESTRATOR_URL,
entity_id='_earthquake_syslog_inspector'):
LOG.info('Syslog UDP port: %d', udp_port)
LOG.info('Orchestrator REST URL: %s', orchestrator_rest_url)
self.orchestrator_rest_url = orchestrator_rest_url
LOG.info('Inspector System Entity ID: %s', entity_id)
self.entity_id = entity_id
that = self
class SyslogUDPHandler(SocketServer.BaseRequestHandler):
def handle(self):
data = bytes.decode(self.request[0].strip(), 'utf-8')
that.on_syslog_recv(
self.client_address[0], self.client_address[1], data)
self.syslog_server = SocketServer.UDPServer(<|fim▁hole|> ('0.0.0.0', udp_port), SyslogUDPHandler)
def start(self):
self.syslog_server.serve_forever()
def on_syslog_recv(self, ip, port, data):
LOG.info('SYSLOG from %s:%d: "%s"', ip, port, data)
event = self.map_syslog_to_event(ip, port, data)
assert event is None or isinstance(event, LogEvent)
if event:
try:
self.send_event_to_orchestrator(event)
except Exception as e:
LOG.error('cannot send event: %s', event, exc_info=True)
def send_event_to_orchestrator(self, event):
event_jsdict = event.to_jsondict()
headers = {'content-type': 'application/json'}
post_url = self.orchestrator_rest_url + \
'/events/' + self.entity_id + '/' + event.uuid
# LOG.debug('POST %s', post_url)
r = requests.post(
post_url, data=json.dumps(event_jsdict), headers=headers)
@abstractmethod
def map_syslog_to_event(self, ip, port, data):
"""
:param ip:
:param port:
:param data:
:return: None or LogEvent
"""
pass
class BasicSyslogInspector(SyslogInspectorBase):
# @Override
def map_syslog_to_event(self, ip, port, data):
entity = 'entity-%s:%d' % (ip, port)
event = LogEvent.from_message(entity, data)
return event
if __name__ == "__main__":
insp = BasicSyslogInspector()
insp.start()<|fim▁end|>
| |
<|file_name|>server.go<|end_file_name|><|fim▁begin|>/*
*
* Copyright 2014, Google Inc.
* 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 Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE<|fim▁hole|> *
*/
package main
import (
"flag"
"fmt"
"io"
"net"
"strconv"
"time"
"github.com/coreos/etcd/Godeps/_workspace/src/github.com/golang/protobuf/proto"
"github.com/coreos/etcd/Godeps/_workspace/src/golang.org/x/net/context"
"github.com/coreos/etcd/Godeps/_workspace/src/google.golang.org/grpc"
"github.com/coreos/etcd/Godeps/_workspace/src/google.golang.org/grpc/credentials"
"github.com/coreos/etcd/Godeps/_workspace/src/google.golang.org/grpc/grpclog"
testpb "github.com/coreos/etcd/Godeps/_workspace/src/google.golang.org/grpc/interop/grpc_testing"
)
var (
useTLS = flag.Bool("use_tls", false, "Connection uses TLS if true, else plain TCP")
certFile = flag.String("tls_cert_file", "testdata/server1.pem", "The TLS cert file")
keyFile = flag.String("tls_key_file", "testdata/server1.key", "The TLS key file")
port = flag.Int("port", 10000, "The server port")
)
type testServer struct {
}
func (s *testServer) EmptyCall(ctx context.Context, in *testpb.Empty) (*testpb.Empty, error) {
return new(testpb.Empty), nil
}
func newPayload(t testpb.PayloadType, size int32) (*testpb.Payload, error) {
if size < 0 {
return nil, fmt.Errorf("requested a response with invalid length %d", size)
}
body := make([]byte, size)
switch t {
case testpb.PayloadType_COMPRESSABLE:
case testpb.PayloadType_UNCOMPRESSABLE:
return nil, fmt.Errorf("payloadType UNCOMPRESSABLE is not supported")
default:
return nil, fmt.Errorf("unsupported payload type: %d", t)
}
return &testpb.Payload{
Type: t.Enum(),
Body: body,
}, nil
}
func (s *testServer) UnaryCall(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) {
pl, err := newPayload(in.GetResponseType(), in.GetResponseSize())
if err != nil {
return nil, err
}
return &testpb.SimpleResponse{
Payload: pl,
}, nil
}
func (s *testServer) StreamingOutputCall(args *testpb.StreamingOutputCallRequest, stream testpb.TestService_StreamingOutputCallServer) error {
cs := args.GetResponseParameters()
for _, c := range cs {
if us := c.GetIntervalUs(); us > 0 {
time.Sleep(time.Duration(us) * time.Microsecond)
}
pl, err := newPayload(args.GetResponseType(), c.GetSize())
if err != nil {
return err
}
if err := stream.Send(&testpb.StreamingOutputCallResponse{
Payload: pl,
}); err != nil {
return err
}
}
return nil
}
func (s *testServer) StreamingInputCall(stream testpb.TestService_StreamingInputCallServer) error {
var sum int
for {
in, err := stream.Recv()
if err == io.EOF {
return stream.SendAndClose(&testpb.StreamingInputCallResponse{
AggregatedPayloadSize: proto.Int32(int32(sum)),
})
}
if err != nil {
return err
}
p := in.GetPayload().GetBody()
sum += len(p)
}
}
func (s *testServer) FullDuplexCall(stream testpb.TestService_FullDuplexCallServer) error {
for {
in, err := stream.Recv()
if err == io.EOF {
// read done.
return nil
}
if err != nil {
return err
}
cs := in.GetResponseParameters()
for _, c := range cs {
if us := c.GetIntervalUs(); us > 0 {
time.Sleep(time.Duration(us) * time.Microsecond)
}
pl, err := newPayload(in.GetResponseType(), c.GetSize())
if err != nil {
return err
}
if err := stream.Send(&testpb.StreamingOutputCallResponse{
Payload: pl,
}); err != nil {
return err
}
}
}
}
func (s *testServer) HalfDuplexCall(stream testpb.TestService_HalfDuplexCallServer) error {
var msgBuf []*testpb.StreamingOutputCallRequest
for {
in, err := stream.Recv()
if err == io.EOF {
// read done.
break
}
if err != nil {
return err
}
msgBuf = append(msgBuf, in)
}
for _, m := range msgBuf {
cs := m.GetResponseParameters()
for _, c := range cs {
if us := c.GetIntervalUs(); us > 0 {
time.Sleep(time.Duration(us) * time.Microsecond)
}
pl, err := newPayload(m.GetResponseType(), c.GetSize())
if err != nil {
return err
}
if err := stream.Send(&testpb.StreamingOutputCallResponse{
Payload: pl,
}); err != nil {
return err
}
}
}
return nil
}
func main() {
flag.Parse()
p := strconv.Itoa(*port)
lis, err := net.Listen("tcp", ":"+p)
if err != nil {
grpclog.Fatalf("failed to listen: %v", err)
}
var opts []grpc.ServerOption
if *useTLS {
creds, err := credentials.NewServerTLSFromFile(*certFile, *keyFile)
if err != nil {
grpclog.Fatalf("Failed to generate credentials %v", err)
}
opts = []grpc.ServerOption{grpc.Creds(creds)}
}
server := grpc.NewServer(opts...)
testpb.RegisterTestServiceServer(server, &testServer{})
server.Serve(lis)
}<|fim▁end|>
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
<|file_name|>gulpfile.js<|end_file_name|><|fim▁begin|>// Include gulp
import gulp from 'gulp';
import fs from 'fs';
// Include Our Plugins<|fim▁hole|>import sassCompiler from 'sass';
import rename from "gulp-rename";
import uglify from 'gulp-uglify';
import postcss from 'gulp-postcss';
import replace from 'gulp-replace';
import autoprefixer from 'autoprefixer';
import gulpStylelint from '@ronilaukkarinen/gulp-stylelint';
const browserSync = browserSyncJs.create();
const pkg = JSON.parse(fs.readFileSync('./package.json'));
const sass = sassJs(sassCompiler);
const doEslint = function() {
return gulp.src(
[
'*.js',
pkg.directories.bin + '/**/*',
pkg.directories.lib + '/**/*.js',
pkg.directories.test + '/**/*.js'
])
.pipe(eslint())
.pipe(eslint.format())
// .pipe(eslint.failAfterError())
;
};
const doMocha = function() {
return gulp.src(pkg.directories.test + '/**/*.js', {read: false})
.pipe(mocha({
reporter: 'dot'
}))
;
};
const buildJs = function() {
return gulp.src(pkg.directories.theme + '/**/js-src/*.js')
.pipe(eslint())
.pipe(eslint.format())
//.pipe(eslint.failAfterError())
.pipe(rename(function(path){
path.dirname = path.dirname.replace(/js-src/, 'js');
}))
.pipe(uglify({output: {
max_line_len: 9000
}}))
.pipe(gulp.dest(pkg.directories.theme))
;
};
const buildCss = function() {
return gulp.src(pkg.directories.theme + '/**/*.scss')
.pipe(gulpStylelint({
reporters: [
{formatter: 'string', console: true}
]
}))
.pipe(sass().on('error', sass.logError))
.pipe(postcss([
autoprefixer()
]))
.pipe(rename(function(path){
path.dirname = path.dirname.replace(/sass/, 'css');
}))
.pipe(replace(/(\n)\s*\n/g, '$1'))
.pipe(gulp.dest(pkg.directories.theme))
;
};
const serve = function() {
browserSync.init({
server: pkg.directories.htdocs,
port: 8080
});
gulp.watch(pkg.directories.htdocs + '/**/*').on('change', browserSync.reload);
};
// Watch Files For Changes
const watch = function() {
gulp.watch(['gulpfile.js', 'package.json'], process.exit);
gulp.watch(
[
'*.js', pkg.directories.bin + '/**/*',
pkg.directories.lib + '/**/*.js',
pkg.directories.test + '/**/*.js'
],
test
);
gulp.watch(pkg.directories.theme + '/**/*.js', buildJs);
gulp.watch(pkg.directories.theme + '/**/*.scss', buildCss);
};
// Bundle tasks
const test = gulp.parallel(doEslint, doMocha);
const build = gulp.parallel(buildJs, buildCss);
const defaultTask = gulp.parallel(serve, watch);
// Expose tasks
export {doEslint, doMocha, buildJs, buildCss, serve, watch, test, build};
export default defaultTask;<|fim▁end|>
|
import eslint from 'gulp-eslint';
import mocha from 'gulp-mocha';
import browserSyncJs from 'browser-sync';
import sassJs from 'gulp-sass';
|
<|file_name|>scrape.py<|end_file_name|><|fim▁begin|># Copyright (C) 2013-2014 Igor Tkach
#
# 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/.
import argparse
import fcntl
import hashlib
import os
import random
import socket
import tempfile
import time
import traceback
import urllib.parse
from urllib.parse import urlparse
from urllib.parse import urlunparse
from collections import namedtuple
from datetime import datetime, timedelta
from multiprocessing import RLock
from multiprocessing.pool import ThreadPool
from contextlib import contextmanager
import couchdb
import mwclient
import mwclient.page
import pylru
import _thread
def fix_server_url(general_siteinfo):
"""
Get server url from siteinfo's 'general' dict,
add http if scheme is missing. This will also modify
given dictionary.
>>> general_siteinfo = {'server': '//simple.wikipedia.org'}
>>> fix_server_url(general_siteinfo)
'http://simple.wikipedia.org'
>>> general_siteinfo
{'server': 'http://simple.wikipedia.org'}
>>> fix_server_url({'server': 'https://en.wikipedia.org'})
'https://en.wikipedia.org'
>>> fix_server_url({})
''
"""
server = general_siteinfo.get("server", "")
if server:
p = urlparse(server)
if not p.scheme:
server = urlunparse(
urllib.parse.ParseResult(
"http", p.netloc, p.path, p.params, p.query, p.fragment
)
)
general_siteinfo["server"] = server
return server
def update_siteinfo(site, couch_server, db_name):
try:
siteinfo_db = couch_server.create("siteinfo")
except couchdb.PreconditionFailed:
siteinfo_db = couch_server["siteinfo"]
siteinfo = site.api(
"query",
meta="siteinfo",
siprop="general|interwikimap|rightsinfo|statistics|namespaces",
)["query"]
fix_server_url(siteinfo["general"])
siteinfo.pop("userinfo", None)
siteinfo_doc = siteinfo_db.get(db_name)
if siteinfo_doc:
siteinfo_doc.update(siteinfo)
else:
siteinfo_doc = siteinfo
siteinfo_db[db_name] = siteinfo_doc
def parse_args():
argparser = argparse.ArgumentParser()
argparser.add_argument(
"site",
nargs="?",
help=("MediaWiki site to scrape (host name), " "e.g. en.wikipedia.org"),
)
argparser.add_argument(
"--site-path",
default="/w/",
help=("MediaWiki site API path" "Default: %(default)s"),
)
argparser.add_argument(
"--site-ext",
default=".php",
help=("MediaWiki site API script extension" "Default: %(default)s"),
)
argparser.add_argument(
"-c",
"--couch",
help=("CouchDB server URL. " "Default: %(default)s"),
default="http://localhost:5984",
)
argparser.add_argument(
"--db",
help=(
"CouchDB database name. "
"If not specified, the name will be "
"derived from Mediawiki host name."
),
default=None,
)
argparser.add_argument(
"--titles",
nargs="+",
help=(
"Download article pages with "
"these names (titles). "
"It name starts with @ it is "
"interpreted as name of file containing titles, "
"one per line, utf8 encoded."
),
)
argparser.add_argument(
"--start", help=("Download all article pages " "beginning with this name")
)
argparser.add_argument(
"--changes-since",
help=(
"Download all article pages "
"that change since specified time. "
"Timestamp format is yyyymmddhhmmss. "
"See https://www.mediawiki.org/wiki/Timestamp. "
"Hours, minutes and seconds can be omited"
),
)
argparser.add_argument(
"--recent-days",
type=int,
default=1,
help=("Number of days to look back for recent changes"),
)
argparser.add_argument(
"--recent",
action="store_true",
help=("Download recently changed articles only"),
)
argparser.add_argument(
"--timeout",
default=30.0,
type=float,
help=("Network communications timeout. " "Default: %(default)ss"),
)
argparser.add_argument(
"-S",
"--siteinfo-only",
action="store_true",
help=("Fetch or update siteinfo, then exit"),
)
argparser.add_argument(
"-r",
"--resume",
nargs="?",
default="",
metavar="SESSION ID",
help=(
"Resume previous scrape session. "
"This relies on stats saved in "
"mwscrape database."
),
)
argparser.add_argument(
"--sessions-db-name",
default="mwscrape",
help=(
"Name of database where " "session info is stored. " "Default: %(default)s"
),
)
argparser.add_argument(
"--desc", action="store_true", help=("Request all pages in descending order")
)
argparser.add_argument(
"--delete-not-found",
action="store_true",
help=("Remove non-existing pages from the database"),
)
argparser.add_argument(
"--speed", type=int, choices=range(0, 6), default=0, help=("Scrape speed")
)
argparser.add_argument(
"--delay",
type=float,
default=0,
help=(
"Pause before requesting rendered article "
"for this many seconds. Default: %(default)s."
"Some sites limit request rate so that even "
"single-threaded, request-at-a-time scrapes are too fast"
"and additional delay needs to be introduced"
),
)
argparser.add_argument(
"--namespace",
type=int,
default=0,
help=("ID of MediaWiki namespace to " "scrape. Default: %(default)s"),
)
return argparser.parse_args()
SHOW_FUNC = r"""
function(doc, req)
{
var r = /href="\/wiki\/(.*?)"/gi;
var replace = function(match, p1, offset, string) {
return 'href="' + p1.replace(/_/g, ' ') + '"';
};
return doc.parse.text['*'].replace(r, replace);
}
"""
def set_show_func(db, show_func=SHOW_FUNC, force=False):
design_doc = db.get("_design/w", {})
shows = design_doc.get("shows", {})
if force or not shows.get("html"):
shows["html"] = show_func
design_doc["shows"] = shows
db["_design/w"] = design_doc
Redirect = namedtuple("Redirect", "page fragment")
def redirects_to(site, from_title):
""" Same as mwclient.page.Page.redirects_to except it returns page and fragment
in a named tuple instead of just target page
"""
info = site.api("query", prop="pageprops", titles=from_title, redirects="")["query"]
if "redirects" in info:
for page in info["redirects"]:
if page["from"] == from_title:
return Redirect(
page=mwclient.page.Page(site, page["to"]),
fragment=page.get("tofragment", u""),
)
return None
return None
def scheme_and_host(site_host):
p = urlparse(site_host)
scheme = p.scheme if p.scheme else "https"
host = p.netloc if p.scheme else site_host
return scheme, host
def mkcouch(url):
parsed = urlparse(url)
server_url = parsed.scheme + "://" + parsed.netloc
server = couchdb.Server(server_url)
user = parsed.username
password = parsed.password
if password:
print("Connecting %s as user %s" % (server.resource.url, user))
server.resource.credentials = (user, password)
return server
@contextmanager
def flock(path):
with open(path, "w") as lock_fd:
try:
fcntl.flock(lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
yield
except IOError as ex:
if ex.errno == 11:
print(
"Scrape for this host is already in progress. "
"Use --speed option instead of starting multiple processes."
)
raise SystemExit(1)
finally:
lock_fd.close()
def fmt_mw_tms(dt):
return datetime.strftime(dt, "%Y%m%d%H%M%S")
def main():
args = parse_args()
socket.setdefaulttimeout(args.timeout)<|fim▁hole|> sessions_db_name = args.sessions_db_name
try:
sessions_db = couch_server.create(sessions_db_name)
except couchdb.PreconditionFailed:
sessions_db = couch_server[sessions_db_name]
if args.resume or args.resume is None:
session_id = args.resume
if session_id is None:
current_doc = sessions_db["$current"]
session_id = current_doc["session_id"]
print("Resuming session %s" % session_id)
session_doc = sessions_db[session_id]
site_host = session_doc["site"]
scheme, host = scheme_and_host(site_host)
db_name = session_doc["db_name"]
session_doc["resumed_at"] = datetime.utcnow().isoformat()
if args.start:
start_page_name = args.start
else:
start_page_name = session_doc.get("last_page_name", args.start)
if args.desc:
descending = True
else:
descending = session_doc.get("descending", False)
sessions_db[session_id] = session_doc
else:
site_host = args.site
db_name = args.db
start_page_name = args.start
descending = args.desc
if not site_host:
print("Site to scrape is not specified")
raise SystemExit(1)
scheme, host = scheme_and_host(site_host)
if not db_name:
db_name = host.replace(".", "-")
session_id = "-".join(
(db_name, str(int(time.time())), str(int(1000 * random.random())))
)
print("Starting session %s" % session_id)
sessions_db[session_id] = {
"created_at": datetime.utcnow().isoformat(),
"site": site_host,
"db_name": db_name,
"descending": descending,
}
current_doc = sessions_db.get("$current", {})
current_doc["session_id"] = session_id
sessions_db["$current"] = current_doc
site = mwclient.Site(host, path=args.site_path, ext=args.site_ext, scheme=scheme)
update_siteinfo(site, couch_server, db_name)
if args.siteinfo_only:
return
try:
db = couch_server.create(db_name)
except couchdb.PreconditionFailed:
db = couch_server[db_name]
set_show_func(db)
def titles_from_args(titles):
for title in titles:
if title.startswith("@"):
with open(os.path.expanduser(title[1:])) as f:
for line in f:
yield line.strip()
else:
yield title
def recently_changed_pages(timestamp):
changes = site.recentchanges(
start=timestamp,
namespace=0,
toponly=1,
type="edit|new",
dir="newer",
show="!minor|!redirect|!anon|!bot",
)
for page in changes:
title = page.get("title")
if title:
doc = db.get(title)
doc_revid = doc.get("parse", {}).get("revid") if doc else None
revid = page.get("revid")
if doc_revid == revid:
continue
yield title
page_list = mwclient.listing.PageList(site, namespace=args.namespace)
if args.titles:
pages = (page_list[title] for title in titles_from_args(args.titles))
elif args.changes_since or args.recent:
if args.recent:
recent_days = args.recent_days
changes_since = fmt_mw_tms(datetime.utcnow() + timedelta(days=-recent_days))
else:
changes_since = args.changes_since.ljust(14, "0")
print("Getting recent changes (since %s)" % changes_since)
pages = (page_list[title] for title in recently_changed_pages(changes_since))
else:
print("Starting at %s" % start_page_name)
pages = site.allpages(
start=start_page_name,
namespace=args.namespace,
dir="descending" if descending else "ascending",
)
# threads are updating the same session document,
# we don't want to have conflicts
lock = RLock()
def inc_count(count_name):
with lock:
session_doc = sessions_db[session_id]
count = session_doc.get(count_name, 0)
session_doc[count_name] = count + 1
sessions_db[session_id] = session_doc
def update_session(title):
with lock:
session_doc = sessions_db[session_id]
session_doc["last_page_name"] = title
session_doc["updated_at"] = datetime.utcnow().isoformat()
sessions_db[session_id] = session_doc
def process(page):
title = page.name
if not page.exists:
print("Not found: %s" % title)
inc_count("not_found")
if args.delete_not_found:
try:
del db[title]
except couchdb.ResourceNotFound:
print("%s was not in the database" % title)
except couchdb.ResourceConflict:
print("Conflict while deleting %s" % title)
except Exception:
traceback.print_exc()
else:
print("%s removed from the database" % title)
return
try:
aliases = set()
redirect_count = 0
while page.redirect:
redirect_count += 1
redirect_target = redirects_to(site, page.name)
frag = redirect_target.fragment
if frag:
alias = (title, frag)
else:
alias = title
aliases.add(alias)
page = redirect_target.page
print("%s ==> %s" % (title, page.name + (("#" + frag) if frag else "")))
if redirect_count >= 10:
print("Too many redirect levels: %r" % aliases)
break
title = page.name
if page.redirect:
print("Failed to resolve redirect %s", title)
inc_count("failed_redirect")
return
doc = db.get(title)
if doc:
current_aliases = set()
for alias in doc.get("aliases", ()):
if isinstance(alias, list):
alias = tuple(alias)
current_aliases.add(alias)
if not aliases.issubset(current_aliases):
merged_aliases = aliases | current_aliases
# remove aliases without fragment if one with fragment is present
# this is mostly to cleanup aliases in old scrapes
to_remove = set()
for alias in merged_aliases:
if isinstance(alias, tuple):
to_remove.add(alias[0])
merged_aliases = merged_aliases - to_remove
doc["aliases"] = list(merged_aliases)
db[title] = doc
revid = doc.get("parse", {}).get("revid")
if page.revision == revid:
print("%s is up to date (rev. %s), skipping" % (title, revid))
inc_count("up_to_date")
return
inc_count("updated")
print(
"[%s] rev. %s => %s %s"
% (
time.strftime("%x %X", (page.touched)) if page.touched else "?",
revid,
page.revision,
title,
)
)
if args.delay:
time.sleep(args.delay)
parse = site.api("parse", page=title)
except KeyboardInterrupt as kbd:
print("Caught KeyboardInterrupt", kbd)
_thread.interrupt_main()
except couchdb.ResourceConflict:
print("Update conflict, skipping: %s" % title)
return
except Exception:
print("Failed to process %s:" % title)
traceback.print_exc()
inc_count("error")
return
if doc:
doc.update(parse)
else:
inc_count("new")
doc = parse
if aliases:
doc["aliases"] = list(aliases)
try:
db[title] = doc
except couchdb.ResourceConflict:
print("Update conflict, skipping: %s" % title)
return
except Exception:
print("Error handling title %r" % title)
traceback.print_exc()
seen = pylru.lrucache(10000)
def ipages(pages):
for index, page in enumerate(pages):
title = page.name
print("%7s %s" % (index, title))
if title in seen:
print("Already saw %s, skipping" % (title,))
continue
seen[title] = True
update_session(title)
yield page
with flock(
os.path.join(
tempfile.gettempdir(), hashlib.sha1(host.encode("utf-8")).hexdigest()
)
):
if args.speed and not args.delay:
pool = ThreadPool(processes=args.speed * 2)
for _result in pool.imap(process, ipages(pages)):
pass
else:
for page in ipages(pages):
process(page)
if __name__ == "__main__":
main()<|fim▁end|>
|
couch_server = mkcouch(args.couch)
|
<|file_name|>Internationalizable.java<|end_file_name|><|fim▁begin|>/*
* Copyright 2005-2006 UniVis Explorer development team.
*
* This file is part of UniVis Explorer
* (http://phobos22.inf.uni-konstanz.de/univis).<|fim▁hole|> * of the License, or (at your option) any later version.
*
* Please see COPYING for the complete licence.
*/
package unikn.dbis.univis.message;
/**
* TODO: document me!!!
* <p/>
* <code>Internationalizable+</code>.
* <p/>
* User: raedler, weiler
* Date: 18.05.2006
* Time: 01:39:22
*
* @author Roman Rädle
* @author Andreas Weiler
* @version $Id: Internationalizable.java 338 2006-10-08 23:11:30Z raedler $
* @since UniVis Explorer 0.1
*/
public interface Internationalizable {
public void internationalize();
}<|fim▁end|>
|
*
* UniVis Explorer is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2.1
|
<|file_name|>domtokenlist.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 dom::attr::{Attr, AttrHelpers};
use dom::bindings::codegen::Bindings::DOMTokenListBinding;
use dom::bindings::codegen::Bindings::DOMTokenListBinding::DOMTokenListMethods;
use dom::bindings::error::{Fallible, InvalidCharacter, Syntax};
use dom::bindings::global::Window;
use dom::bindings::js::{JS, JSRef, Temporary, OptionalRootable};
use dom::bindings::utils::{Reflector, Reflectable, reflect_dom_object};
use dom::element::{Element, AttributeHandlers};
use dom::node::window_from_node;
use servo_util::atom::Atom;
use servo_util::namespace::Null;
use servo_util::str::{DOMString, HTML_SPACE_CHARACTERS};
#[deriving(Encodable)]
#[must_root]
pub struct DOMTokenList {
reflector_: Reflector,
element: JS<Element>,
local_name: &'static str,
}
impl DOMTokenList {
pub fn new_inherited(element: JSRef<Element>,
local_name: &'static str) -> DOMTokenList {
DOMTokenList {
reflector_: Reflector::new(),
element: JS::from_rooted(element),
local_name: local_name,
}
}
pub fn new(element: JSRef<Element>,
local_name: &'static str) -> Temporary<DOMTokenList> {
let window = window_from_node(element).root();
reflect_dom_object(box DOMTokenList::new_inherited(element, local_name),
&Window(*window), DOMTokenListBinding::Wrap)
}
}
impl Reflectable for DOMTokenList {
fn reflector<'a>(&'a self) -> &'a Reflector {
&self.reflector_
}
}
trait PrivateDOMTokenListHelpers {
fn attribute(self) -> Option<Temporary<Attr>>;
fn check_token_exceptions<'a>(self, token: &'a str) -> Fallible<&'a str>;
}
impl<'a> PrivateDOMTokenListHelpers for JSRef<'a, DOMTokenList> {
fn attribute(self) -> Option<Temporary<Attr>> {
let element = self.element.root();
element.deref().get_attribute(Null, self.local_name)
}
fn check_token_exceptions<'a>(self, token: &'a str) -> Fallible<&'a str> {
match token {
"" => Err(Syntax),
token if token.find(HTML_SPACE_CHARACTERS).is_some() => Err(InvalidCharacter),
token => Ok(token)
}
}
}
// http://dom.spec.whatwg.org/#domtokenlist
impl<'a> DOMTokenListMethods for JSRef<'a, DOMTokenList> {
// http://dom.spec.whatwg.org/#dom-domtokenlist-length
fn Length(self) -> u32 {
self.attribute().root().map(|attr| {
attr.value().tokens().map(|tokens| tokens.len()).unwrap_or(0)
}).unwrap_or(0) as u32
}<|fim▁hole|> self.attribute().root().and_then(|attr| attr.value().tokens().and_then(|mut tokens| {
tokens.idx(index as uint).map(|token| token.as_slice().to_string())
}))
}
fn IndexedGetter(self, index: u32, found: &mut bool) -> Option<DOMString> {
let item = self.Item(index);
*found = item.is_some();
item
}
// http://dom.spec.whatwg.org/#dom-domtokenlist-contains
fn Contains(self, token: DOMString) -> Fallible<bool> {
self.check_token_exceptions(token.as_slice()).map(|slice| {
self.attribute().root().and_then(|attr| attr.value().tokens().map(|mut tokens| {
let atom = Atom::from_slice(slice);
tokens.any(|token| *token == atom)
})).unwrap_or(false)
})
}
}<|fim▁end|>
|
// http://dom.spec.whatwg.org/#dom-domtokenlist-item
fn Item(self, index: u32) -> Option<DOMString> {
|
<|file_name|>daysLeftThisWeek.js<|end_file_name|><|fim▁begin|>function daysLeftThisWeek (date) {<|fim▁hole|>}
module.exports = daysLeftThisWeek<|fim▁end|>
|
return 6 - date.getDay()
|
<|file_name|>adaline.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python2
import math, sys, time
def drange(start, stop, step): #Generator for step <1, from http://stackoverflow.com/questions/477486/python-decimal-range-step-value
r = start
while r < stop:
yield r
r += step
class adaline:
def __init__(self, w_vec):#, bias): #absorbed
self.w_vec = w_vec
#self.bias = bias #absorbed
def transfer(self, yin, isTraining = False):
if isTraining: #training, f(yin) = yin
return yin
else: #not training, f(yin) = bipolar Heaviside step function
if yin >= 0:
return 1
else:
return -1
def calc_yin(self, x_vec): #Calculates yin = x.w + b
if len(x_vec) != len(self.w_vec):
raise Exception('Supplied input length does not match weight length.')
yin = 0
#yin = self.bias #absorbed
for xx,ww in zip(x_vec, self.w_vec):
yin += xx*ww
return yin
def train(self, s_vec_list, t_vec, rate):
if rate <= 0:
raise Exception('Rate not positive: ' + str(rate))
if len(s_vec_list) != len(t_vec):
raise Exception('Training set problem: input count does not match result count.')
insigFlag = False
loopCount = 0
while insigFlag == False and loopCount < numEpochs: #Loop till changes in the weights and bias are insignificant.
for s_vec, tt in zip(s_vec_list, t_vec):
yin = self.calc_yin(s_vec)
yy = self.transfer(yin, isTraining = True) # yy = yin
w_change = list()
bias_change = -2*rate*(yin - tt)
for i in range(len(self.w_vec)):
w_change.append(bias_change*s_vec[i])
if verbose_flag:
print "yy: ", yy
#print "bias_change: ", bias_change #absorbed
print "w_change: ", w_change
#self.bias = self.bias + bias_change #absorbed
for ii,wc in enumerate(self.w_vec):
self.w_vec[ii] = wc + w_change[ii]
#if math.fabs(bias_change) < 0.1: #absorbed
insigFlag = True #time to check if we need to exit
for wc in w_change:<|fim▁hole|> insigFlag = False
break
#time.sleep(1)
loopCount += 1
###
verbose_flag = False
if len(sys.argv) > 2:
raise Exception('Too many arguments. Usage: adaline.py [-v|--verbose]')
elif len(sys.argv) == 1:
pass
elif sys.argv[1] == '-v' or sys.argv[1] == '--verbose':
verbose_flag = True
else:
raise Exception('Bad argument. Usage: adaline.py [-v|--verbose]')
numEpochs = 100
#ACTUAL
test_s_vec_list = [[1, 1, 1, 1], [-1, 1, -1, -1], [1, 1, 1, -1], [1, -1, -1, 1]]
test_t_vec = [1, 1, -1, -1]
#AND for 2
#test_s_vec_list = [[1, 1], [1, -1], [-1, 1], [-1, -1]]
#test_t_vec = [1, -1, -1, -1]
#AND for 4
#test_s_vec_list = [[1, 1, 1, 1], [1, -1, 1, -1], [-1, 1, -1, 1], [-1, -1, -1, -1]]
#test_t_vec = [1, -1, -1, -1]
for test_s_vec in test_s_vec_list:
test_s_vec.insert(0,1) #absorbing the bias by placing an input shorted to 1 at the head of each training vector
for alpha in [0.1,0.5]:#drange(0.01,1,0.01):
p = adaline([0 for x in test_s_vec_list[0]])#, 0) #absorbed
#alpha = 0.1 #ACTUAL: 0.5
p.train(test_s_vec_list, test_t_vec, rate=alpha)
if verbose_flag:
print "bias+weights: ", p.w_vec
sol_vec = list()
for test_s_vec in test_s_vec_list:
sol_vec.append(p.transfer(p.calc_yin(test_s_vec), isTraining = False))
if verbose_flag:
print 'Solution: ', sol_vec, '\nExpected (t_vec): ', test_t_vec
match_flag = True
for i,j in zip(sol_vec, test_t_vec):
if i != j:
match_flag = False
break
if match_flag:
print 't_vec matched with rate', alpha<|fim▁end|>
|
if math.fabs(wc) < 0.1:
insigFlag = True
else:
|
<|file_name|>Battle.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python2
import time
import random
<|fim▁hole|>class Battle:
def __init__(self, user1, user2):
self.user1 = user1
self.user2 = user2
self.turn = user1
self.notTurn = user2
self.accepted = False
self.finished = False
self.auto = False
self.turnCount = 1
def fight(self, spell):
attacker = self.turn.getActivePokemon()
defender = self.notTurn.getActivePokemon()
message = attacker.fight(spell, defender)
if defender.life <= 0:
message += defender.name + " n'a plus de points de vie. "
if self.notTurn.hasAlivePokemon():
message += self.notTurn.username + " doit invoquer un nouveau pokemon. "
else:
message += self.notTurn.username + " a perdu. " + self.turn.username + " a gagne. "
message += attacker.name + " gagne " + str(attacker.calcGainedExp(defender)) + " points d'experience. "
old = attacker.level
attacker.gainExp(defender)
if attacker.level != old:
message += attacker.name + " passe niveau " + str(attacker.level) + "!"
self.finished = True
self.turn, self.notTurn = self.notTurn, self.turn
self.turnCount += 1
return message
def itemUsed(self):
self.turn, self.notTurn = self.notTurn, self.turn
def nextStep(self):
if self.finished:
self.user1.battle = None
self.user2.battle = None
return False
elif self.auto and self.turnCount % 2 == 0:
time.sleep(2)
return self.fight(self.turn.getActivePokemon().spells[random.randint(0, len(self.turn.getActivePokemon().spells) - 1)].name)<|fim▁end|>
| |
<|file_name|>variables_test.py<|end_file_name|><|fim▁begin|>from sys import platform
import unittest
import checksieve
class TestVariables(unittest.TestCase):
def test_set(self):
sieve = '''
require "variables";
set "honorific" "Mr";
'''
self.assertFalse(checksieve.parse_string(sieve, False))<|fim▁hole|> sieve = '''
require "variables";
set :length "b" "${a}";
'''
self.assertFalse(checksieve.parse_string(sieve, False))
def test_wrong_tag(self):
sieve = '''
require "variables";
set :mime "b" "c";
'''
self.assertTrue(checksieve.parse_string(sieve, True))
def test_set_wrong_arg(self):
sieve = '''
require "variables";
set "a" "b" "c";
'''
self.assertTrue(checksieve.parse_string(sieve, True))
def test_too_many_args(self):
sieve = '''
require "variables";
set "a" "b" "c" "d";
'''
self.assertTrue(checksieve.parse_string(sieve, True))
def test_test_string(self):
sieve = '''
require "variables";
set "state" "${state} pending";
if string :matches " ${state} " "* pending *" {
# the above test always succeeds
stop;
}
'''
self.assertFalse(checksieve.parse_string(sieve, False))
def test_numeral_varname(self):
sieve = '''
require "variables";
set "1" "${state} pending";
'''
self.assertFalse(checksieve.parse_string(sieve, False))
def test_bad_varname(self):
sieve = '''
require "variables";
set "bad-variable" "no dashes allowed!";
'''
self.assertTrue(checksieve.parse_string(sieve, True))
if __name__ == '__main__':
unittest.main()<|fim▁end|>
|
def test_mod_length(self):
|
<|file_name|>persistent_list.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/. */
//! A persistent, thread-safe singly-linked list.
use std::sync::Arc;
pub struct PersistentList<T> {
head: PersistentListLink<T>,
length: usize,
}
struct PersistentListEntry<T> {
value: T,
next: PersistentListLink<T>,
}
type PersistentListLink<T> = Option<Arc<PersistentListEntry<T>>>;
impl<T> PersistentList<T> where T: Send + Sync {
#[inline]
pub fn new() -> PersistentList<T> {
PersistentList {
head: None,
length: 0,
}
}
#[inline]
pub fn len(&self) -> usize {
self.length
}
#[inline]
pub fn front(&self) -> Option<&T> {
self.head.as_ref().map(|head| &head.value)
}
#[inline]
pub fn prepend_elem(&self, value: T) -> PersistentList<T> {
PersistentList {
head: Some(Arc::new(PersistentListEntry {
value: value,
next: self.head.clone(),
})),
length: self.length + 1,
}
}
#[inline]
pub fn iter(&self) -> PersistentListIterator<T> {
// This could clone (and would not need the lifetime if it did), but then it would incur
// atomic operations on every call to `.next()`. Bad.
PersistentListIterator {
entry: self.head.as_ref().map(|head| &**head),
}
}
}
impl<T> Clone for PersistentList<T> where T: Send + Sync {
fn clone(&self) -> PersistentList<T> {
// This establishes the persistent nature of this list: we can clone a list by just cloning
// its head.
PersistentList {
head: self.head.clone(),
length: self.length,
}
}
}<|fim▁hole|>}
impl<'a, T> Iterator for PersistentListIterator<'a, T> where T: Send + Sync + 'static {
type Item = &'a T;
#[inline]
fn next(&mut self) -> Option<&'a T> {
let entry = self.entry?;
let value = &entry.value;
self.entry = match entry.next {
None => None,
Some(ref entry) => Some(&**entry),
};
Some(value)
}
}<|fim▁end|>
|
pub struct PersistentListIterator<'a, T> where T: 'a + Send + Sync {
entry: Option<&'a PersistentListEntry<T>>,
|
<|file_name|>ifletsource1.rs<|end_file_name|><|fim▁begin|>fn main() {
// Toutes les variables sont de type `Option<i32>`.
let number = Some(7);
let letter: Option<i32> = None;
let emoticon: Option<i32> = None;
// L'ensemble `if let` se déroule de cette manière:
// `if let` déstructure `number` et assigne sa valeur à `i` et exécute
// le bloc (`{}`).
if let Some(i) = number {
println!("{:?} a été trouvé!", i);
}
// Si vous devez spécifier un cas d'erreur, utilisez un `else`:
if let Some(i) = letter {
println!("{:?} a été trouvé!", i);
} else {
// Déstructuration ratée. On exécute le `else`.
println!("Aucun nombre n'a été trouvé.
Cherchons une lettre!");
};<|fim▁hole|> if let Some(i) = emoticon {
println!("{:?} a été trouvé!", i);
// Déstructuration ratée. Passe à une condition `else if` pour tester si
// la condition alternative est vraie.
} else if i_like_letters {
println!("Aucun nombre n'a été trouvé.
Cherchons une lettre!");
} else {
// La condition évaluée est fausse. Branche par défaut:
println!("Je n'aime pas les lettres. Cherchons une emoticône :)!");
};
}<|fim▁end|>
|
// Fournit une condition alternative.
let i_like_letters = false;
|
<|file_name|>helpers.py<|end_file_name|><|fim▁begin|># coding=utf-8
# Author: Nic Wolfe <[email protected]>
# URL: https://sickrage.github.io
# Git: https://github.com/SickRage/SickRage.git
#
# This file is part of SickRage.
#
# SickRage 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.
#
# SickRage 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 SickRage. If not, see <http://www.gnu.org/licenses/>.
import os
import io
import ctypes
import random
import re
import socket
import stat
import tempfile
import time
import traceback
import urllib
import urllib2
import hashlib
import httplib
import urlparse
import uuid
import base64
import zipfile
import datetime
import errno
import ast
import operator
import platform
import sickbeard
import adba
import requests
import certifi
from contextlib import closing
from socket import timeout as SocketTimeout
from sickbeard import logger, classes
from sickbeard.common import USER_AGENT
from sickbeard import db
from sickbeard.notifiers import synoindex_notifier
from sickrage.helper.common import http_code_description, media_extensions, pretty_file_size, subtitle_extensions, episode_num
from sickrage.helper.encoding import ek
from sickrage.helper.exceptions import ex
from sickrage.show.Show import Show
from itertools import izip, cycle
import shutil
import shutil_custom
import xml.etree.ElementTree as ET
import json
shutil.copyfile = shutil_custom.copyfile_custom
# pylint: disable=protected-access
# Access to a protected member of a client class
urllib._urlopener = classes.SickBeardURLopener()
def fixGlob(path):
path = re.sub(r'\[', '[[]', path)
return re.sub(r'(?<!\[)\]', '[]]', path)
def indentXML(elem, level=0):
"""
Does our pretty printing, makes Matt very happy
"""
i = "\n" + level * " "
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + " "
if not elem.tail or not elem.tail.strip():
elem.tail = i
for elem in elem:
indentXML(elem, level + 1)
if not elem.tail or not elem.tail.strip():
elem.tail = i
else:
if level and (not elem.tail or not elem.tail.strip()):
elem.tail = i
def remove_non_release_groups(name):
"""
Remove non release groups from name
"""
if not name:
return name
# Do not remove all [....] suffixes, or it will break anime releases ## Need to verify this is true now
# Check your database for funky release_names and add them here, to improve failed handling, archiving, and history.
# select release_name from tv_episodes WHERE LENGTH(release_name);
# [eSc], [SSG], [GWC] are valid release groups for non-anime
removeWordsList = {
r'\[rartv\]$': 'searchre',
r'\[rarbg\]$': 'searchre',
r'\[eztv\]$': 'searchre',
r'\[ettv\]$': 'searchre',
r'\[cttv\]$': 'searchre',
r'\[vtv\]$': 'searchre',
r'\[EtHD\]$': 'searchre',
r'\[GloDLS\]$': 'searchre',
r'\[silv4\]$': 'searchre',
r'\[Seedbox\]$': 'searchre',
r'\[PublicHD\]$': 'searchre',
r'\[AndroidTwoU\]$': 'searchre',
r'\[brassetv]\]$': 'searchre',
r'\.\[BT\]$': 'searchre',
r' \[1044\]$': 'searchre',
r'\.RiPSaLoT$': 'searchre',
r'\.GiuseppeTnT$': 'searchre',
r'\.Renc$': 'searchre',
r'\.gz$': 'searchre',
r'(?<![57])\.1$': 'searchre',
r'-NZBGEEK$': 'searchre',
r'-Siklopentan$': 'searchre',
r'-Chamele0n$': 'searchre',
r'-Obfuscated$': 'searchre',
r'-\[SpastikusTV\]$': 'searchre',
r'-RP$': 'searchre',
r'-20-40$': 'searchre',
r'\.\[www\.usabit\.com\]$': 'searchre',
r'^\[www\.Cpasbien\.pe\] ': 'searchre',
r'^\[www\.Cpasbien\.com\] ': 'searchre',
r'^\[ www\.Cpasbien\.pw \] ': 'searchre',
r'^\.www\.Cpasbien\.pw': 'searchre',
r'^\[www\.newpct1\.com\]': 'searchre',
r'^\[ www\.Cpasbien\.com \] ': 'searchre',
r'- \{ www\.SceneTime\.com \}$': 'searchre',
r'^\{ www\.SceneTime\.com \} - ': 'searchre',
r'^\]\.\[www\.tensiontorrent.com\] - ': 'searchre',
r'^\]\.\[ www\.tensiontorrent.com \] - ': 'searchre',
r'- \[ www\.torrentday\.com \]$': 'searchre',
r'^\[ www\.TorrentDay\.com \] - ': 'searchre',
r'\[NO-RAR\] - \[ www\.torrentday\.com \]$': 'searchre',
}
_name = name
for remove_string, remove_type in removeWordsList.iteritems():
if remove_type == 'search':
_name = _name.replace(remove_string, '')
elif remove_type == 'searchre':
_name = re.sub(r'(?i)' + remove_string, '', _name)
return _name
def isMediaFile(filename):
"""
Check if named file may contain media
:param filename: Filename to check
:return: True if this is a known media file, False if not
"""
# ignore samples
try:
if re.search(r'(^|[\W_])(?<!shomin.)(sample\d*)[\W_]', filename, re.I):
return False
# ignore RARBG release intro
if re.search(r'^RARBG\.\w+\.(mp4|avi|txt)$', filename, re.I):
return False
# ignore MAC OS's retarded "resource fork" files
if filename.startswith('._'):
return False
sepFile = filename.rpartition(".")
if re.search('extras?$', sepFile[0], re.I):
return False
if sepFile[2].lower() in media_extensions:
return True
else:
return False
except TypeError as error: # Not a string
logger.log('Invalid filename. Filename must be a string. %s' % error, logger.DEBUG) # pylint: disable=no-member
return False
def isRarFile(filename):
"""
Check if file is a RAR file, or part of a RAR set
:param filename: Filename to check
:return: True if this is RAR/Part file, False if not
"""
archive_regex = r'(?P<file>^(?P<base>(?:(?!\.part\d+\.rar$).)*)\.(?:(?:part0*1\.)?rar)$)'
if re.search(archive_regex, filename):
return True
return False
def isBeingWritten(filepath):
"""
Check if file has been written in last 60 seconds
:param filepath: Filename to check
:return: True if file has been written recently, False if none
"""
# Return True if file was modified within 60 seconds. it might still be being written to.
ctime = max(ek(os.path.getctime, filepath), ek(os.path.getmtime, filepath))
if ctime > time.time() - 60:
return True
return False
def remove_file_failed(failed_file):
"""
Remove file from filesystem
:param file: File to remove
"""
try:
ek(os.remove, failed_file)
except Exception:
pass
def makeDir(path):
"""
Make a directory on the filesystem
:param path: directory to make
:return: True if success, False if failure
"""
if not ek(os.path.isdir, path):
try:
ek(os.makedirs, path)
# do the library update for synoindex
synoindex_notifier.addFolder(path)
except OSError:
return False
return True
def searchIndexerForShowID(regShowName, indexer=None, indexer_id=None, ui=None):
"""
Contacts indexer to check for information on shows by showid
:param regShowName: Name of show
:param indexer: Which indexer to use
:param indexer_id: Which indexer ID to look for
:param ui: Custom UI for indexer use
:return:
"""
showNames = [re.sub('[. -]', ' ', regShowName)]
# Query Indexers for each search term and build the list of results
for i in sickbeard.indexerApi().indexers if not indexer else int(indexer or []):
# Query Indexers for each search term and build the list of results
lINDEXER_API_PARMS = sickbeard.indexerApi(i).api_params.copy()
if ui is not None:
lINDEXER_API_PARMS['custom_ui'] = ui
t = sickbeard.indexerApi(i).indexer(**lINDEXER_API_PARMS)
for name in showNames:
logger.log(u"Trying to find " + name + " on " + sickbeard.indexerApi(i).name, logger.DEBUG)
try:
search = t[indexer_id] if indexer_id else t[name]
except Exception:
continue
try:
seriesname = search[0]['seriesname']
except Exception:
seriesname = None
try:
series_id = search[0]['id']
except Exception:
series_id = None
if not (seriesname and series_id):
continue
ShowObj = Show.find(sickbeard.showList, int(series_id))
# Check if we can find the show in our list (if not, it's not the right show)
if (indexer_id is None) and (ShowObj is not None) and (ShowObj.indexerid == int(series_id)):
return seriesname, i, int(series_id)
elif (indexer_id is not None) and (int(indexer_id) == int(series_id)):
return seriesname, i, int(indexer_id)
if indexer:
break
return None, None, None
def listMediaFiles(path):
"""
Get a list of files possibly containing media in a path
:param path: Path to check for files
:return: list of files
"""
if not dir or not ek(os.path.isdir, path):
return []
files = []
for curFile in ek(os.listdir, path):
fullCurFile = ek(os.path.join, path, curFile)
# if it's a folder do it recursively
if ek(os.path.isdir, fullCurFile) and not curFile.startswith('.') and not curFile == 'Extras':
files += listMediaFiles(fullCurFile)
elif isMediaFile(curFile):
files.append(fullCurFile)
return files
def copyFile(srcFile, destFile):
"""
Copy a file from source to destination
:param srcFile: Path of source file
:param destFile: Path of destination file
"""
ek(shutil.copyfile, srcFile, destFile)
try:
ek(shutil.copymode, srcFile, destFile)
except OSError:
pass
def moveFile(srcFile, destFile):
"""
Move a file from source to destination
:param srcFile: Path of source file
:param destFile: Path of destination file
"""
try:
ek(shutil.move, srcFile, destFile)
fixSetGroupID(destFile)
except OSError:
copyFile(srcFile, destFile)
ek(os.unlink, srcFile)
def link(src, dst):
"""
Create a file link from source to destination.
TODO: Make this unicode proof
:param src: Source file
:param dst: Destination file
"""
if os.name == 'nt':
if ctypes.windll.kernel32.CreateHardLinkW(unicode(dst), unicode(src), 0) == 0:
raise ctypes.WinError()
else:
ek(os.link, src, dst)
def hardlinkFile(srcFile, destFile):
"""
Create a hard-link (inside filesystem link) between source and destination
:param srcFile: Source file
:param destFile: Destination file
"""
try:
ek(link, srcFile, destFile)
fixSetGroupID(destFile)
except Exception as e:
logger.log(u"Failed to create hardlink of %s at %s. Error: %r. Copying instead"
% (srcFile, destFile, ex(e)), logger.WARNING)
copyFile(srcFile, destFile)
def symlink(src, dst):
"""
Create a soft/symlink between source and destination
:param src: Source file
:param dst: Destination file
"""
if os.name == 'nt':
if ctypes.windll.kernel32.CreateSymbolicLinkW(unicode(dst), unicode(src), 1 if ek(os.path.isdir, src) else 0) in [0, 1280]:
raise ctypes.WinError()
else:
ek(os.symlink, src, dst)
def moveAndSymlinkFile(srcFile, destFile):
"""
Move a file from source to destination, then create a symlink back from destination from source. If this fails, copy
the file from source to destination
:param srcFile: Source file
:param destFile: Destination file
"""
try:
ek(shutil.move, srcFile, destFile)
fixSetGroupID(destFile)
ek(symlink, destFile, srcFile)
except Exception as e:
logger.log(u"Failed to create symlink of %s at %s. Error: %r. Copying instead"
% (srcFile, destFile, ex(e)), logger.WARNING)
copyFile(srcFile, destFile)
def make_dirs(path):
"""
Creates any folders that are missing and assigns them the permissions of their
parents
"""
logger.log(u"Checking if the path %s already exists" % path, logger.DEBUG)
if not ek(os.path.isdir, path):
# Windows, create all missing folders
if os.name == 'nt' or os.name == 'ce':
try:
logger.log(u"Folder %s didn't exist, creating it" % path, logger.DEBUG)
ek(os.makedirs, path)
except (OSError, IOError) as e:
logger.log(u"Failed creating %s : %r" % (path, ex(e)), logger.ERROR)
return False
# not Windows, create all missing folders and set permissions
else:
sofar = ''
folder_list = path.split(os.path.sep)
# look through each subfolder and make sure they all exist
for cur_folder in folder_list:
sofar += cur_folder + os.path.sep
# if it exists then just keep walking down the line
if ek(os.path.isdir, sofar):
continue
try:
logger.log(u"Folder %s didn't exist, creating it" % sofar, logger.DEBUG)
ek(os.mkdir, sofar)
# use normpath to remove end separator, otherwise checks permissions against itself
chmodAsParent(ek(os.path.normpath, sofar))
# do the library update for synoindex
synoindex_notifier.addFolder(sofar)
except (OSError, IOError) as e:
logger.log(u"Failed creating %s : %r" % (sofar, ex(e)), logger.ERROR)
return False
return True
def rename_ep_file(cur_path, new_path, old_path_length=0):
"""
Creates all folders needed to move a file to its new location, renames it, then cleans up any folders
left that are now empty.
:param cur_path: The absolute path to the file you want to move/rename
:param new_path: The absolute path to the destination for the file WITHOUT THE EXTENSION
:param old_path_length: The length of media file path (old name) WITHOUT THE EXTENSION
"""
# new_dest_dir, new_dest_name = ek(os.path.split, new_path) # @UnusedVariable
if old_path_length == 0 or old_path_length > len(cur_path):
# approach from the right
cur_file_name, cur_file_ext = ek(os.path.splitext, cur_path) # @UnusedVariable
else:
# approach from the left
cur_file_ext = cur_path[old_path_length:]
cur_file_name = cur_path[:old_path_length]
if cur_file_ext[1:] in subtitle_extensions:
# Extract subtitle language from filename
sublang = ek(os.path.splitext, cur_file_name)[1][1:]
# Check if the language extracted from filename is a valid language
if sublang in sickbeard.subtitles.subtitle_code_filter():
cur_file_ext = '.' + sublang + cur_file_ext
# put the extension on the incoming file
new_path += cur_file_ext
make_dirs(ek(os.path.dirname, new_path))
# move the file
try:
logger.log(u"Renaming file from %s to %s" % (cur_path, new_path))
ek(shutil.move, cur_path, new_path)
except (OSError, IOError) as e:
logger.log(u"Failed renaming %s to %s : %r" % (cur_path, new_path, ex(e)), logger.ERROR)
return False
# clean up any old folders that are empty
delete_empty_folders(ek(os.path.dirname, cur_path))
return True
def delete_empty_folders(check_empty_dir, keep_dir=None):
"""
Walks backwards up the path and deletes any empty folders found.
:param check_empty_dir: The path to clean (absolute path to a folder)
:param keep_dir: Clean until this path is reached
"""
# treat check_empty_dir as empty when it only contains these items
ignore_items = []
logger.log(u"Trying to clean any empty folders under " + check_empty_dir)
# as long as the folder exists and doesn't contain any files, delete it
while ek(os.path.isdir, check_empty_dir) and check_empty_dir != keep_dir:
check_files = ek(os.listdir, check_empty_dir)
if not check_files or (len(check_files) <= len(ignore_items) and all(
[check_file in ignore_items for check_file in check_files])):
# directory is empty or contains only ignore_items
try:
logger.log(u"Deleting empty folder: " + check_empty_dir)
# need shutil.rmtree when ignore_items is really implemented
ek(os.rmdir, check_empty_dir)
# do the library update for synoindex
synoindex_notifier.deleteFolder(check_empty_dir)
except OSError as e:
logger.log(u"Unable to delete %s. Error: %r" % (check_empty_dir, repr(e)), logger.WARNING)
break
check_empty_dir = ek(os.path.dirname, check_empty_dir)
else:
break
def fileBitFilter(mode):
"""
Strip special filesystem bits from file
:param mode: mode to check and strip
:return: required mode for media file
"""
for bit in [stat.S_IXUSR, stat.S_IXGRP, stat.S_IXOTH, stat.S_ISUID, stat.S_ISGID]:
if mode & bit:
mode -= bit
return mode
def chmodAsParent(childPath):
"""
Retain permissions of parent for childs
(Does not work for Windows hosts)
:param childPath: Child Path to change permissions to sync from parent
"""
if os.name == 'nt' or os.name == 'ce':
return
parentPath = ek(os.path.dirname, childPath)
if not parentPath:
logger.log(u"No parent path provided in " + childPath + ", unable to get permissions from it", logger.DEBUG)
return
childPath = ek(os.path.join, parentPath, ek(os.path.basename, childPath))
parentPathStat = ek(os.stat, parentPath)
parentMode = stat.S_IMODE(parentPathStat[stat.ST_MODE])
childPathStat = ek(os.stat, childPath.encode(sickbeard.SYS_ENCODING))
childPath_mode = stat.S_IMODE(childPathStat[stat.ST_MODE])
if ek(os.path.isfile, childPath):
childMode = fileBitFilter(parentMode)
else:
childMode = parentMode
if childPath_mode == childMode:
return
childPath_owner = childPathStat.st_uid
user_id = os.geteuid() # @UndefinedVariable - only available on UNIX
if user_id != 0 and user_id != childPath_owner:
logger.log(u"Not running as root or owner of " + childPath + ", not trying to set permissions", logger.DEBUG)
return
try:
ek(os.chmod, childPath, childMode)
logger.log(u"Setting permissions for %s to %o as parent directory has %o" % (childPath, childMode, parentMode),
logger.DEBUG)
except OSError:
logger.log(u"Failed to set permission for %s to %o" % (childPath, childMode), logger.DEBUG)
def fixSetGroupID(childPath):
"""
Inherid SGID from parent
(does not work on Windows hosts)
:param childPath: Path to inherit SGID permissions from parent
"""
if os.name == 'nt' or os.name == 'ce':
return
parentPath = ek(os.path.dirname, childPath)
parentStat = ek(os.stat, parentPath)
parentMode = stat.S_IMODE(parentStat[stat.ST_MODE])
childPath = ek(os.path.join, parentPath, ek(os.path.basename, childPath))
if parentMode & stat.S_ISGID:
parentGID = parentStat[stat.ST_GID]
childStat = ek(os.stat, childPath.encode(sickbeard.SYS_ENCODING))
childGID = childStat[stat.ST_GID]
if childGID == parentGID:
return
childPath_owner = childStat.st_uid
user_id = os.geteuid() # @UndefinedVariable - only available on UNIX
if user_id != 0 and user_id != childPath_owner:
logger.log(u"Not running as root or owner of " + childPath + ", not trying to set the set-group-ID",
logger.DEBUG)
return
try:
ek(os.chown, childPath, -1, parentGID) # @UndefinedVariable - only available on UNIX
logger.log(u"Respecting the set-group-ID bit on the parent directory for %s" % childPath, logger.DEBUG)
except OSError:
logger.log(
u"Failed to respect the set-group-ID bit on the parent directory for %s (setting group ID %i)" % (
childPath, parentGID), logger.ERROR)
<|fim▁hole|> """
Check if any shows in list contain anime
:return: True if global showlist contains Anime, False if not
"""
for show in sickbeard.showList:
if show.is_anime:
return True
return False
def update_anime_support():
"""Check if we need to support anime, and if we do, enable the feature"""
sickbeard.ANIMESUPPORT = is_anime_in_show_list()
def get_absolute_number_from_season_and_episode(show, season, episode):
"""
Find the absolute number for a show episode
:param show: Show object
:param season: Season number
:param episode: Episode number
:return: The absolute number
"""
absolute_number = None
if season and episode:
main_db_con = db.DBConnection()
sql = "SELECT * FROM tv_episodes WHERE showid = ? and season = ? and episode = ?"
sql_results = main_db_con.select(sql, [show.indexerid, season, episode])
if len(sql_results) == 1:
absolute_number = int(sql_results[0]["absolute_number"])
logger.log(u"Found absolute number {absolute} for show {show} {ep}".format
(absolute=absolute_number, show=show.name,
ep=episode_num(season, episode)), logger.DEBUG)
else:
logger.log(u"No entries for absolute number for show {show} {ep}".format
(show=show.name, ep=episode_num(season, episode)), logger.DEBUG)
return absolute_number
def get_all_episodes_from_absolute_number(show, absolute_numbers, indexer_id=None):
episodes = []
season = None
if len(absolute_numbers):
if not show and indexer_id:
show = Show.find(sickbeard.showList, indexer_id)
for absolute_number in absolute_numbers if show else []:
ep = show.getEpisode(None, None, absolute_number=absolute_number)
if ep:
episodes.append(ep.episode)
season = ep.season # this will always take the last found season so eps that cross the season border are not handeled well
return season, episodes
def sanitizeSceneName(name, anime=False):
"""
Takes a show name and returns the "scenified" version of it.
:param anime: Some show have a ' in their name(Kuroko's Basketball) and is needed for search.
:return: A string containing the scene version of the show name given.
"""
if not name:
return ''
bad_chars = u',:()!?\u2019'
if not anime:
bad_chars += u"'"
# strip out any bad chars
for x in bad_chars:
name = name.replace(x, "")
# tidy up stuff that doesn't belong in scene names
name = name.replace("- ", ".").replace(" ", ".").replace("&", "and").replace('/', '.')
name = re.sub(r"\.\.*", ".", name)
if name.endswith('.'):
name = name[:-1]
return name
_binOps = {
ast.Add: operator.add,
ast.Sub: operator.sub,
ast.Mult: operator.mul,
ast.Div: operator.div,
ast.Mod: operator.mod
}
def arithmeticEval(s):
"""
A safe eval supporting basic arithmetic operations.
:param s: expression to evaluate
:return: value
"""
node = ast.parse(s, mode='eval')
def _eval(node):
if isinstance(node, ast.Expression):
return _eval(node.body)
elif isinstance(node, ast.Str):
return node.s
elif isinstance(node, ast.Num):
return node.n
elif isinstance(node, ast.BinOp):
return _binOps[type(node.op)](_eval(node.left), _eval(node.right))
else:
raise Exception('Unsupported type {}'.format(node))
return _eval(node.body)
def create_https_certificates(ssl_cert, ssl_key):
"""
Create self-signed HTTPS certificares and store in paths 'ssl_cert' and 'ssl_key'
:param ssl_cert: Path of SSL certificate file to write
:param ssl_key: Path of SSL keyfile to write
:return: True on success, False on failure
"""
# assert isinstance(ssl_key, unicode)
# assert isinstance(ssl_cert, unicode)
try:
from OpenSSL import crypto # @UnresolvedImport
from certgen import createKeyPair, createCertRequest, createCertificate, TYPE_RSA, \
serial # @UnresolvedImport
except Exception:
logger.log(u"pyopenssl module missing, please install for https access", logger.WARNING)
return False
# Create the CA Certificate
cakey = createKeyPair(TYPE_RSA, 1024)
careq = createCertRequest(cakey, CN='Certificate Authority')
cacert = createCertificate(careq, (careq, cakey), serial, (0, 60 * 60 * 24 * 365 * 10)) # ten years
cname = 'SickRage'
pkey = createKeyPair(TYPE_RSA, 1024)
req = createCertRequest(pkey, CN=cname)
cert = createCertificate(req, (cacert, cakey), serial, (0, 60 * 60 * 24 * 365 * 10)) # ten years
# Save the key and certificate to disk
try:
# pylint: disable=no-member
# Module has no member
io.open(ssl_key, 'wb').write(crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey))
io.open(ssl_cert, 'wb').write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
except Exception:
logger.log(u"Error creating SSL key and certificate", logger.ERROR)
return False
return True
def backupVersionedFile(old_file, version):
"""
Back up an old version of a file
:param old_file: Original file, to take a backup from
:param version: Version of file to store in backup
:return: True if success, False if failure
"""
numTries = 0
new_file = old_file + '.' + 'v' + str(version)
while not ek(os.path.isfile, new_file):
if not ek(os.path.isfile, old_file):
logger.log(u"Not creating backup, %s doesn't exist" % old_file, logger.DEBUG)
break
try:
logger.log(u"Trying to back up %s to %s" % (old_file, new_file), logger.DEBUG)
shutil.copy(old_file, new_file)
logger.log(u"Backup done", logger.DEBUG)
break
except Exception as e:
logger.log(u"Error while trying to back up %s to %s : %r" % (old_file, new_file, ex(e)), logger.WARNING)
numTries += 1
time.sleep(1)
logger.log(u"Trying again.", logger.DEBUG)
if numTries >= 10:
logger.log(u"Unable to back up %s to %s please do it manually." % (old_file, new_file), logger.ERROR)
return False
return True
def restoreVersionedFile(backup_file, version):
"""
Restore a file version to original state
:param backup_file: File to restore
:param version: Version of file to restore
:return: True on success, False on failure
"""
numTries = 0
new_file, _ = ek(os.path.splitext, backup_file)
restore_file = new_file + '.' + 'v' + str(version)
if not ek(os.path.isfile, new_file):
logger.log(u"Not restoring, %s doesn't exist" % new_file, logger.DEBUG)
return False
try:
logger.log(u"Trying to backup %s to %s.r%s before restoring backup"
% (new_file, new_file, version), logger.DEBUG)
shutil.move(new_file, new_file + '.' + 'r' + str(version))
except Exception as e:
logger.log(u"Error while trying to backup DB file %s before proceeding with restore: %r"
% (restore_file, ex(e)), logger.WARNING)
return False
while not ek(os.path.isfile, new_file):
if not ek(os.path.isfile, restore_file):
logger.log(u"Not restoring, %s doesn't exist" % restore_file, logger.DEBUG)
break
try:
logger.log(u"Trying to restore file %s to %s" % (restore_file, new_file), logger.DEBUG)
shutil.copy(restore_file, new_file)
logger.log(u"Restore done", logger.DEBUG)
break
except Exception as e:
logger.log(u"Error while trying to restore file %s. Error: %r" % (restore_file, ex(e)), logger.WARNING)
numTries += 1
time.sleep(1)
logger.log(u"Trying again. Attempt #: %s" % numTries, logger.DEBUG)
if numTries >= 10:
logger.log(u"Unable to restore file %s to %s" % (restore_file, new_file), logger.WARNING)
return False
return True
# generates a md5 hash of a file
def md5_for_file(filename, block_size=2 ** 16):
"""
Generate an md5 hash for a file
:param filename: File to generate md5 hash for
:param block_size: Block size to use (defaults to 2^16)
:return MD5 hexdigest on success, or None on failure
"""
# assert isinstance(filename, unicode)
try:
with io.open(filename, 'rb') as f:
md5 = hashlib.md5()
while True:
data = f.read(block_size)
if not data:
break
md5.update(data)
f.close()
return md5.hexdigest()
except Exception:
return None
def get_lan_ip():
"""Returns IP of system"""
try:
return [ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")][0]
except Exception:
return socket.gethostname()
def check_url(url):
"""
Check if a URL exists without downloading the whole file.
We only check the URL header.
"""
# see also http://stackoverflow.com/questions/2924422
# http://stackoverflow.com/questions/1140661
good_codes = [httplib.OK, httplib.FOUND, httplib.MOVED_PERMANENTLY]
host, path = urlparse.urlparse(url)[1:3] # elems [1] and [2]
try:
conn = httplib.HTTPConnection(host)
conn.request('HEAD', path)
return conn.getresponse().status in good_codes
except StandardError:
return None
def anon_url(*url):
"""
Return a URL string consisting of the Anonymous redirect URL and an arbitrary number of values appended.
"""
return '' if None in url else '%s%s' % (sickbeard.ANON_REDIRECT, ''.join(str(s) for s in url))
"""
Encryption
==========
By Pedro Jose Pereira Vieito <[email protected]> (@pvieito)
* If encryption_version==0 then return data without encryption
* The keys should be unique for each device
To add a new encryption_version:
1) Code your new encryption_version
2) Update the last encryption_version available in webserve.py
3) Remember to maintain old encryption versions and key generators for retrocompatibility
"""
# Key Generators
unique_key1 = hex(uuid.getnode() ** 2) # Used in encryption v1
# Encryption Functions
def encrypt(data, encryption_version=0, _decrypt=False):
# Version 1: Simple XOR encryption (this is not very secure, but works)
if encryption_version == 1:
if _decrypt:
return ''.join(chr(ord(x) ^ ord(y)) for (x, y) in izip(base64.decodestring(data), cycle(unique_key1)))
else:
return base64.encodestring(
''.join(chr(ord(x) ^ ord(y)) for (x, y) in izip(data, cycle(unique_key1)))).strip()
# Version 2: Simple XOR encryption (this is not very secure, but works)
elif encryption_version == 2:
if _decrypt:
return ''.join(chr(ord(x) ^ ord(y)) for (x, y) in izip(base64.decodestring(data), cycle(sickbeard.ENCRYPTION_SECRET)))
else:
return base64.encodestring(
''.join(chr(ord(x) ^ ord(y)) for (x, y) in izip(data, cycle(sickbeard.ENCRYPTION_SECRET)))).strip()
# Version 0: Plain text
else:
return data
def decrypt(data, encryption_version=0):
return encrypt(data, encryption_version, _decrypt=True)
def full_sanitizeSceneName(name):
return re.sub('[. -]', ' ', sanitizeSceneName(name)).lower().lstrip()
def _check_against_names(nameInQuestion, show, season=-1):
showNames = []
if season in [-1, 1]:
showNames = [show.name]
showNames.extend(sickbeard.scene_exceptions.get_scene_exceptions(show.indexerid, season=season))
for showName in showNames:
nameFromList = full_sanitizeSceneName(showName)
if nameFromList == nameInQuestion:
return True
return False
def get_show(name, tryIndexers=False):
if not sickbeard.showList:
return
showObj = None
fromCache = False
if not name:
return showObj
try:
# check cache for show
cache = sickbeard.name_cache.retrieveNameFromCache(name)
if cache:
fromCache = True
showObj = Show.find(sickbeard.showList, int(cache))
# try indexers
if not showObj and tryIndexers:
showObj = Show.find(
sickbeard.showList, searchIndexerForShowID(full_sanitizeSceneName(name), ui=classes.ShowListUI)[2])
# try scene exceptions
if not showObj:
ShowID = sickbeard.scene_exceptions.get_scene_exception_by_name(name)[0]
if ShowID:
showObj = Show.find(sickbeard.showList, int(ShowID))
# add show to cache
if showObj and not fromCache:
sickbeard.name_cache.addNameToCache(name, showObj.indexerid)
except Exception as e:
logger.log(u"Error when attempting to find show: %s in SickRage. Error: %r " % (name, repr(e)), logger.DEBUG)
return showObj
def is_hidden_folder(folder):
"""
Returns True if folder is hidden.
On Linux based systems hidden folders start with . (dot)
:param folder: Full path of folder to check
"""
def is_hidden(filepath):
name = ek(os.path.basename, ek(os.path.abspath, filepath))
return name.startswith('.') or has_hidden_attribute(filepath)
def has_hidden_attribute(filepath):
try:
attrs = ctypes.windll.kernel32.GetFileAttributesW(unicode(filepath))
assert attrs != -1
result = bool(attrs & 2)
except (AttributeError, AssertionError):
result = False
return result
if ek(os.path.isdir, folder):
if is_hidden(folder):
return True
return False
def real_path(path):
"""
Returns: the canonicalized absolute pathname. The resulting path will have no symbolic link, '/./' or '/../' components.
"""
return ek(os.path.normpath, ek(os.path.normcase, ek(os.path.realpath, path)))
def validateShow(show, season=None, episode=None):
indexer_lang = show.lang
try:
lINDEXER_API_PARMS = sickbeard.indexerApi(show.indexer).api_params.copy()
if indexer_lang and not indexer_lang == sickbeard.INDEXER_DEFAULT_LANGUAGE:
lINDEXER_API_PARMS['language'] = indexer_lang
if show.dvdorder != 0:
lINDEXER_API_PARMS['dvdorder'] = True
t = sickbeard.indexerApi(show.indexer).indexer(**lINDEXER_API_PARMS)
if season is None and episode is None:
return t
return t[show.indexerid][season][episode]
except (sickbeard.indexer_episodenotfound, sickbeard.indexer_seasonnotfound):
pass
def set_up_anidb_connection():
"""Connect to anidb"""
if not sickbeard.USE_ANIDB:
logger.log(u"Usage of anidb disabled. Skiping", logger.DEBUG)
return False
if not sickbeard.ANIDB_USERNAME and not sickbeard.ANIDB_PASSWORD:
logger.log(u"anidb username and/or password are not set. Aborting anidb lookup.", logger.DEBUG)
return False
if not sickbeard.ADBA_CONNECTION:
def anidb_logger(msg):
return logger.log(u"anidb: %s " % msg, logger.DEBUG)
try:
sickbeard.ADBA_CONNECTION = adba.Connection(keepAlive=True, log=anidb_logger)
except Exception as e:
logger.log(u"anidb exception msg: %r " % repr(e), logger.WARNING)
return False
try:
if not sickbeard.ADBA_CONNECTION.authed():
sickbeard.ADBA_CONNECTION.auth(sickbeard.ANIDB_USERNAME, sickbeard.ANIDB_PASSWORD)
else:
return True
except Exception as e:
logger.log(u"anidb exception msg: %r " % repr(e), logger.WARNING)
return False
return sickbeard.ADBA_CONNECTION.authed()
def makeZip(fileList, archive):
"""
Create a ZIP of files
:param fileList: A list of file names - full path each name
:param archive: File name for the archive with a full path
"""
try:
a = zipfile.ZipFile(archive, 'w', zipfile.ZIP_DEFLATED, allowZip64=True)
for f in fileList:
a.write(f)
a.close()
return True
except Exception as e:
logger.log(u"Zip creation error: %r " % repr(e), logger.ERROR)
return False
def extractZip(archive, targetDir):
"""
Unzip a file to a directory
:param fileList: A list of file names - full path each name
:param archive: The file name for the archive with a full path
"""
try:
if not ek(os.path.exists, targetDir):
ek(os.mkdir, targetDir)
zip_file = zipfile.ZipFile(archive, 'r', allowZip64=True)
for member in zip_file.namelist():
filename = ek(os.path.basename, member)
# skip directories
if not filename:
continue
# copy file (taken from zipfile's extract)
source = zip_file.open(member)
target = file(ek(os.path.join, targetDir, filename), "wb")
shutil.copyfileobj(source, target)
source.close()
target.close()
zip_file.close()
return True
except Exception as e:
logger.log(u"Zip extraction error: %r " % repr(e), logger.ERROR)
return False
def backupConfigZip(fileList, archive, arcname=None):
"""
Store the config file as a ZIP
:param fileList: List of files to store
:param archive: ZIP file name
:param arcname: Archive path
:return: True on success, False on failure
"""
try:
a = zipfile.ZipFile(archive, 'w', zipfile.ZIP_DEFLATED, allowZip64=True)
for f in fileList:
a.write(f, ek(os.path.relpath, f, arcname))
a.close()
return True
except Exception as e:
logger.log(u"Zip creation error: %r " % repr(e), logger.ERROR)
return False
def restoreConfigZip(archive, targetDir):
"""
Restores a Config ZIP file back in place
:param archive: ZIP filename
:param targetDir: Directory to restore to
:return: True on success, False on failure
"""
try:
if not ek(os.path.exists, targetDir):
ek(os.mkdir, targetDir)
else:
def path_leaf(path):
head, tail = ek(os.path.split, path)
return tail or ek(os.path.basename, head)
bakFilename = '{0}-{1}'.format(path_leaf(targetDir), datetime.datetime.now().strftime('%Y%m%d_%H%M%S'))
shutil.move(targetDir, ek(os.path.join, ek(os.path.dirname, targetDir), bakFilename))
zip_file = zipfile.ZipFile(archive, 'r', allowZip64=True)
for member in zip_file.namelist():
zip_file.extract(member, targetDir)
zip_file.close()
return True
except Exception as e:
logger.log(u"Zip extraction error: %r" % ex(e), logger.ERROR)
shutil.rmtree(targetDir)
return False
def mapIndexersToShow(showObj):
mapped = {}
# init mapped indexers object
for indexer in sickbeard.indexerApi().indexers:
mapped[indexer] = showObj.indexerid if int(indexer) == int(showObj.indexer) else 0
main_db_con = db.DBConnection()
sql_results = main_db_con.select(
"SELECT * FROM indexer_mapping WHERE indexer_id = ? AND indexer = ?",
[showObj.indexerid, showObj.indexer])
# for each mapped entry
for curResult in sql_results:
nlist = [i for i in curResult if i is not None]
# Check if its mapped with both tvdb and tvrage.
if len(nlist) >= 4:
logger.log(u"Found indexer mapping in cache for show: " + showObj.name, logger.DEBUG)
mapped[int(curResult['mindexer'])] = int(curResult['mindexer_id'])
break
else:
sql_l = []
for indexer in sickbeard.indexerApi().indexers:
if indexer == showObj.indexer:
mapped[indexer] = showObj.indexerid
continue
lINDEXER_API_PARMS = sickbeard.indexerApi(indexer).api_params.copy()
lINDEXER_API_PARMS['custom_ui'] = classes.ShowListUI
t = sickbeard.indexerApi(indexer).indexer(**lINDEXER_API_PARMS)
try:
mapped_show = t[showObj.name]
except Exception:
logger.log(u"Unable to map " + sickbeard.indexerApi(showObj.indexer).name + "->" + sickbeard.indexerApi(
indexer).name + " for show: " + showObj.name + ", skipping it", logger.DEBUG)
continue
if mapped_show and len(mapped_show) == 1:
logger.log(u"Mapping " + sickbeard.indexerApi(showObj.indexer).name + "->" + sickbeard.indexerApi(
indexer).name + " for show: " + showObj.name, logger.DEBUG)
mapped[indexer] = int(mapped_show[0]['id'])
logger.log(u"Adding indexer mapping to DB for show: " + showObj.name, logger.DEBUG)
sql_l.append([
"INSERT OR IGNORE INTO indexer_mapping (indexer_id, indexer, mindexer_id, mindexer) VALUES (?,?,?,?)",
[showObj.indexerid, showObj.indexer, int(mapped_show[0]['id']), indexer]])
if len(sql_l) > 0:
main_db_con = db.DBConnection()
main_db_con.mass_action(sql_l)
return mapped
def touchFile(fname, atime=None):
"""
Touch a file (change modification date)
:param fname: Filename to touch
:param atime: Specific access time (defaults to None)
:return: True on success, False on failure
"""
if atime is not None:
try:
with file(fname, 'a'):
os.utime(fname, (atime, atime))
return True
except Exception as e:
if e.errno == errno.ENOSYS:
logger.log(u"File air date stamping not available on your OS. Please disable setting", logger.DEBUG)
elif e.errno == errno.EACCES:
logger.log(u"File air date stamping failed(Permission denied). Check permissions for file: %s" % fname, logger.ERROR)
else:
logger.log(u"File air date stamping failed. The error is: %r" % ex(e), logger.ERROR)
return False
def _getTempDir():
"""
Returns the [system temp dir]/tvdb_api-u501 (or
tvdb_api-myuser)
"""
import getpass
if hasattr(os, 'getuid'):
uid = "u%d" % (os.getuid())
else:
# For Windows
try:
uid = getpass.getuser()
except ImportError:
return ek(os.path.join, tempfile.gettempdir(), "sickrage")
return ek(os.path.join, tempfile.gettempdir(), "sickrage-%s" % uid)
def _setUpSession(session, headers):
"""
Returns a session initialized with default cache and parameter settings
:param session: session object to (re)use
:param headers: Headers to pass to session
:return: session object
"""
# request session
# Lets try without caching sessions to disk for awhile
# cache_dir = sickbeard.CACHE_DIR or _getTempDir()
# session = CacheControl(sess=session, cache=caches.FileCache(ek(os.path.join, cache_dir, 'sessions'), use_dir_lock=True), cache_etags=False)
# request session clear residual referer
# pylint: disable=superfluous-parens
# These extra parens are necessary!
if 'Referer' in session.headers and 'Referer' not in (headers or {}):
session.headers.pop('Referer')
# request session headers
session.headers.update({'User-Agent': USER_AGENT, 'Accept-Encoding': 'gzip,deflate'})
if headers:
session.headers.update(headers)
# request session ssl verify
session.verify = certifi.old_where() if sickbeard.SSL_VERIFY else False
# request session proxies
if 'Referer' not in session.headers and sickbeard.PROXY_SETTING:
logger.log(u"Using global proxy: " + sickbeard.PROXY_SETTING, logger.DEBUG)
scheme, address = urllib2.splittype(sickbeard.PROXY_SETTING)
address = sickbeard.PROXY_SETTING if scheme else 'http://' + sickbeard.PROXY_SETTING
session.proxies = {
"http": address,
"https": address,
}
session.headers.update({'Referer': address})
if 'Content-Type' in session.headers:
session.headers.pop('Content-Type')
return session
def getURL(url, post_data=None, params=None, headers=None, timeout=30, session=None, json=False, need_bytes=False):
"""
Returns a byte-string retrieved from the url provider.
"""
session = _setUpSession(session, headers)
if params and isinstance(params, (list, dict)):
for param in params:
if isinstance(params[param], unicode):
params[param] = params[param].encode('utf-8')
session.params = params
try:
# decide if we get or post data to server
if post_data:
if isinstance(post_data, (list, dict)):
for param in post_data:
if isinstance(post_data[param], unicode):
post_data[param] = post_data[param].encode('utf-8')
session.headers.update({'Content-Type': 'application/x-www-form-urlencoded'})
resp = session.post(url, data=post_data, timeout=timeout, allow_redirects=True, verify=session.verify)
else:
resp = session.get(url, timeout=timeout, allow_redirects=True, verify=session.verify)
if not resp.ok:
logger.log(u"Requested getURL %s returned status code is %s: %s"
% (url, resp.status_code, http_code_description(resp.status_code)), logger.DEBUG)
return None
except (SocketTimeout, TypeError) as e:
logger.log(u"Connection timed out (sockets) accessing getURL %s Error: %r" % (url, ex(e)), logger.WARNING)
return None
except (requests.exceptions.HTTPError, requests.exceptions.TooManyRedirects) as e:
logger.log(u"HTTP error in getURL %s Error: %r" % (url, ex(e)), logger.WARNING)
return None
except requests.exceptions.ConnectionError as e:
logger.log(u"Connection error to getURL %s Error: %r" % (url, ex(e)), logger.WARNING)
return None
except requests.exceptions.Timeout as e:
logger.log(u"Connection timed out accessing getURL %s Error: %r" % (url, ex(e)), logger.WARNING)
return None
except requests.exceptions.ContentDecodingError:
logger.log(u"Content-Encoding was gzip, but content was not compressed. getURL: %s" % url, logger.DEBUG)
logger.log(traceback.format_exc(), logger.DEBUG)
return None
except Exception as e:
logger.log(u"Unknown exception in getURL %s Error: %r" % (url, ex(e)), logger.WARNING)
logger.log(traceback.format_exc(), logger.WARNING)
return None
return (resp.text, resp.content)[need_bytes] if not json else resp.json()
def download_file(url, filename, session=None, headers=None):
"""
Downloads a file specified
:param url: Source URL
:param filename: Target file on filesystem
:param session: request session to use
:param headers: override existing headers in request session
:return: True on success, False on failure
"""
session = _setUpSession(session, headers)
session.stream = True
try:
with closing(session.get(url, allow_redirects=True, verify=session.verify)) as resp:
if not resp.ok:
logger.log(u"Requested download url %s returned status code is %s: %s"
% (url, resp.status_code, http_code_description(resp.status_code)), logger.DEBUG)
return False
try:
with io.open(filename, 'wb') as fp:
for chunk in resp.iter_content(chunk_size=1024):
if chunk:
fp.write(chunk)
fp.flush()
chmodAsParent(filename)
except Exception:
logger.log(u"Problem setting permissions or writing file to: %s" % filename, logger.WARNING)
except (SocketTimeout, TypeError) as e:
remove_file_failed(filename)
logger.log(u"Connection timed out (sockets) while loading download URL %s Error: %r" % (url, ex(e)), logger.WARNING)
return None
except (requests.exceptions.HTTPError, requests.exceptions.TooManyRedirects) as e:
remove_file_failed(filename)
logger.log(u"HTTP error %r while loading download URL %s " % (ex(e), url), logger.WARNING)
return False
except requests.exceptions.ConnectionError as e:
remove_file_failed(filename)
logger.log(u"Connection error %r while loading download URL %s " % (ex(e), url), logger.WARNING)
return False
except requests.exceptions.Timeout as e:
remove_file_failed(filename)
logger.log(u"Connection timed out %r while loading download URL %s " % (ex(e), url), logger.WARNING)
return False
except EnvironmentError as e:
remove_file_failed(filename)
logger.log(u"Unable to save the file: %r " % ex(e), logger.WARNING)
return False
except Exception:
remove_file_failed(filename)
logger.log(u"Unknown exception while loading download URL %s : %r" % (url, traceback.format_exc()), logger.WARNING)
return False
return True
def get_size(start_path='.'):
"""
Find the total dir and filesize of a path
:param start_path: Path to recursively count size
:return: total filesize
"""
if not ek(os.path.isdir, start_path):
return -1
total_size = 0
for dirpath, _, filenames in ek(os.walk, start_path):
for f in filenames:
fp = ek(os.path.join, dirpath, f)
try:
total_size += ek(os.path.getsize, fp)
except OSError as e:
logger.log(u"Unable to get size for file %s Error: %r" % (fp, ex(e)), logger.ERROR)
logger.log(traceback.format_exc(), logger.DEBUG)
return total_size
def generateApiKey():
""" Return a new randomized API_KEY"""
try:
from hashlib import md5
except ImportError:
from md5 import md5
# Create some values to seed md5
t = str(time.time())
r = str(random.random())
# Create the md5 instance and give it the current time
m = md5(t)
# Update the md5 instance with the random variable
m.update(r)
# Return a hex digest of the md5, eg 49f68a5c8493ec2c0bf489821c21fc3b
logger.log(u"New API generated")
return m.hexdigest()
def remove_article(text=''):
"""Remove the english articles from a text string"""
return re.sub(r'(?i)^(?:(?:A(?!\s+to)n?)|The)\s(\w)', r'\1', text)
def generateCookieSecret():
"""Generate a new cookie secret"""
return base64.b64encode(uuid.uuid4().bytes + uuid.uuid4().bytes)
def verify_freespace(src, dest, oldfile=None):
"""
Checks if the target system has enough free space to copy or move a file.
:param src: Source filename
:param dest: Destination path
:param oldfile: File to be replaced (defaults to None)
:return: True if there is enough space for the file, False if there isn't. Also returns True if the OS doesn't support this option
"""
if not isinstance(oldfile, list):
oldfile = [oldfile]
logger.log(u"Trying to determine free space on destination drive", logger.DEBUG)
if hasattr(os, 'statvfs'): # POSIX
def disk_usage(path):
st = ek(os.statvfs, path)
free = st.f_bavail * st.f_frsize
return free
elif os.name == 'nt': # Windows
import sys
def disk_usage(path):
_, total, free = ctypes.c_ulonglong(), ctypes.c_ulonglong(), ctypes.c_ulonglong()
if sys.version_info >= (3,) or isinstance(path, unicode):
fun = ctypes.windll.kernel32.GetDiskFreeSpaceExW
else:
fun = ctypes.windll.kernel32.GetDiskFreeSpaceExA
ret = fun(path, ctypes.byref(_), ctypes.byref(total), ctypes.byref(free))
if ret == 0:
logger.log(u"Unable to determine free space, something went wrong", logger.WARNING)
raise ctypes.WinError()
return free.value
else:
logger.log(u"Unable to determine free space on your OS")
return True
if not ek(os.path.isfile, src):
logger.log(u"A path to a file is required for the source. " + src + " is not a file.", logger.WARNING)
return True
try:
diskfree = disk_usage(dest)
except Exception:
logger.log(u"Unable to determine free space, so I will assume there is enough.", logger.WARNING)
return True
neededspace = ek(os.path.getsize, src)
if oldfile:
for f in oldfile:
if ek(os.path.isfile, f.location):
diskfree += ek(os.path.getsize, f.location)
if diskfree > neededspace:
return True
else:
logger.log(u"Not enough free space: Needed: %s bytes ( %s ), found: %s bytes ( %s )"
% (neededspace, pretty_file_size(neededspace), diskfree, pretty_file_size(diskfree)), logger.WARNING)
return False
# https://gist.github.com/thatalextaylor/7408395
def pretty_time_delta(seconds):
sign_string = '-' if seconds < 0 else ''
seconds = abs(int(seconds))
days, seconds = divmod(seconds, 86400)
hours, seconds = divmod(seconds, 3600)
minutes, seconds = divmod(seconds, 60)
time_delta = sign_string
if days > 0:
time_delta += ' %dd' % days
if hours > 0:
time_delta += ' %dh' % hours
if minutes > 0:
time_delta += ' %dm' % minutes
if seconds > 0:
time_delta += ' %ds' % seconds
return time_delta
def isFileLocked(checkfile, writeLockCheck=False):
"""
Checks to see if a file is locked. Performs three checks
1. Checks if the file even exists
2. Attempts to open the file for reading. This will determine if the file has a write lock.
Write locks occur when the file is being edited or copied to, e.g. a file copy destination
3. If the readLockCheck parameter is True, attempts to rename the file. If this fails the
file is open by some other process for reading. The file can be read, but not written to
or deleted.
:param file: the file being checked
:param writeLockCheck: when true will check if the file is locked for writing (prevents move operations)
"""
checkfile = ek(os.path.abspath, checkfile)
if not ek(os.path.exists, checkfile):
return True
try:
f = io.open(checkfile, 'rb')
f.close()
except IOError:
return True
if writeLockCheck:
lockFile = checkfile + ".lckchk"
if ek(os.path.exists, lockFile):
ek(os.remove, lockFile)
try:
ek(os.rename, checkfile, lockFile)
time.sleep(1)
ek(os.rename, lockFile, checkfile)
except (OSError, IOError):
return True
return False
def getDiskSpaceUsage(diskPath=None):
"""
returns the free space in human readable bytes for a given path or False if no path given
:param diskPath: the filesystem path being checked
"""
if diskPath and ek(os.path.exists, diskPath):
if platform.system() == 'Windows':
free_bytes = ctypes.c_ulonglong(0)
ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(diskPath), None, None, ctypes.pointer(free_bytes))
return pretty_file_size(free_bytes.value)
else:
st = ek(os.statvfs, diskPath)
return pretty_file_size(st.f_bavail * st.f_frsize)
else:
return False
def getTVDBFromID(indexer_id, indexer):
session = requests.Session()
tvdb_id = ''
if indexer == 'IMDB':
url = "http://www.thetvdb.com/api/GetSeriesByRemoteID.php?imdbid=%s" % indexer_id
data = getURL(url, session=session, need_bytes=True)
if data is None:
return tvdb_id
try:
tree = ET.fromstring(data)
for show in tree.getiterator("Series"):
tvdb_id = show.findtext("seriesid")
except SyntaxError:
pass
return tvdb_id
elif indexer == 'ZAP2IT':
url = "http://www.thetvdb.com/api/GetSeriesByRemoteID.php?zap2it=%s" % indexer_id
data = getURL(url, session=session, need_bytes=True)
if data is None:
return tvdb_id
try:
tree = ET.fromstring(data)
for show in tree.getiterator("Series"):
tvdb_id = show.findtext("seriesid")
except SyntaxError:
pass
return tvdb_id
elif indexer == 'TVMAZE':
url = "http://api.tvmaze.com/shows/%s" % indexer_id
data = getURL(url, session=session, json=True)
if data is None:
return tvdb_id
tvdb_id = data['externals']['thetvdb']
return tvdb_id
else:
return tvdb_id
def get_showname_from_indexer(indexer, indexer_id, lang='en'):
lINDEXER_API_PARMS = sickbeard.indexerApi(indexer).api_params.copy()
if lang:
lINDEXER_API_PARMS['language'] = lang
logger.log(u"" + str(sickbeard.indexerApi(indexer).name) + ": " + repr(lINDEXER_API_PARMS))
t = sickbeard.indexerApi(indexer).indexer(**lINDEXER_API_PARMS)
s = t[int(indexer_id)]
if hasattr(s,'data'):
return s.data.get('seriesname')
return None
def is_ip_private(ip):
priv_lo = re.compile(r"^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$")
priv_24 = re.compile(r"^10\.\d{1,3}\.\d{1,3}\.\d{1,3}$")
priv_20 = re.compile(r"^192\.168\.\d{1,3}.\d{1,3}$")
priv_16 = re.compile(r"^172.(1[6-9]|2[0-9]|3[0-1]).[0-9]{1,3}.[0-9]{1,3}$")
return priv_lo.match(ip) or priv_24.match(ip) or priv_20.match(ip) or priv_16.match(ip)<|fim▁end|>
|
def is_anime_in_show_list():
|
<|file_name|>hue_gui.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'hue-gui.ui'<|fim▁hole|>
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(1161, 620)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.channel1Check = QtWidgets.QCheckBox(self.centralwidget)
self.channel1Check.setGeometry(QtCore.QRect(10, 10, 161, 17))
self.channel1Check.setChecked(True)
self.channel1Check.setObjectName("channel1Check")
self.channel2Check = QtWidgets.QCheckBox(self.centralwidget)
self.channel2Check.setGeometry(QtCore.QRect(10, 30, 151, 17))
self.channel2Check.setChecked(True)
self.channel2Check.setObjectName("channel2Check")
self.modeWidget = QtWidgets.QTabWidget(self.centralwidget)
self.modeWidget.setGeometry(QtCore.QRect(10, 60, 1131, 451))
self.modeWidget.setObjectName("modeWidget")
self.presetTab = QtWidgets.QWidget()
self.presetTab.setObjectName("presetTab")
self.presetModeWidget = QtWidgets.QTabWidget(self.presetTab)
self.presetModeWidget.setGeometry(QtCore.QRect(6, 10, 1101, 411))
self.presetModeWidget.setLayoutDirection(QtCore.Qt.LeftToRight)
self.presetModeWidget.setObjectName("presetModeWidget")
self.fixedTab = QtWidgets.QWidget()
self.fixedTab.setObjectName("fixedTab")
self.groupBox = QtWidgets.QGroupBox(self.fixedTab)
self.groupBox.setGeometry(QtCore.QRect(0, 0, 231, 361))
self.groupBox.setObjectName("groupBox")
self.fixedList = QtWidgets.QListWidget(self.groupBox)
self.fixedList.setGeometry(QtCore.QRect(10, 50, 111, 291))
self.fixedList.setObjectName("fixedList")
self.fixedAdd = QtWidgets.QPushButton(self.groupBox)
self.fixedAdd.setGeometry(QtCore.QRect(130, 50, 83, 28))
self.fixedAdd.setObjectName("fixedAdd")
self.fixedDelete = QtWidgets.QPushButton(self.groupBox)
self.fixedDelete.setGeometry(QtCore.QRect(130, 90, 83, 28))
self.fixedDelete.setObjectName("fixedDelete")
self.presetModeWidget.addTab(self.fixedTab, "")
self.breathingTab = QtWidgets.QWidget()
self.breathingTab.setObjectName("breathingTab")
self.groupBox_2 = QtWidgets.QGroupBox(self.breathingTab)
self.groupBox_2.setGeometry(QtCore.QRect(0, 0, 231, 361))
self.groupBox_2.setObjectName("groupBox_2")
self.breathingList = QtWidgets.QListWidget(self.groupBox_2)
self.breathingList.setGeometry(QtCore.QRect(10, 50, 111, 291))
self.breathingList.setObjectName("breathingList")
self.breathingAdd = QtWidgets.QPushButton(self.groupBox_2)
self.breathingAdd.setGeometry(QtCore.QRect(130, 50, 83, 28))
self.breathingAdd.setObjectName("breathingAdd")
self.breathingDelete = QtWidgets.QPushButton(self.groupBox_2)
self.breathingDelete.setGeometry(QtCore.QRect(130, 90, 83, 28))
self.breathingDelete.setObjectName("breathingDelete")
self.groupBox_11 = QtWidgets.QGroupBox(self.breathingTab)
self.groupBox_11.setGeometry(QtCore.QRect(240, 0, 321, 361))
self.groupBox_11.setObjectName("groupBox_11")
self.breathingSpeed = QtWidgets.QSlider(self.groupBox_11)
self.breathingSpeed.setGeometry(QtCore.QRect(15, 70, 31, 160))
self.breathingSpeed.setMaximum(4)
self.breathingSpeed.setProperty("value", 2)
self.breathingSpeed.setOrientation(QtCore.Qt.Vertical)
self.breathingSpeed.setTickPosition(QtWidgets.QSlider.TicksBothSides)
self.breathingSpeed.setObjectName("breathingSpeed")
self.label_2 = QtWidgets.QLabel(self.groupBox_11)
self.label_2.setGeometry(QtCore.QRect(10, 40, 62, 20))
self.label_2.setObjectName("label_2")
self.label_4 = QtWidgets.QLabel(self.groupBox_11)
self.label_4.setGeometry(QtCore.QRect(70, 60, 62, 20))
self.label_4.setObjectName("label_4")
self.label_5 = QtWidgets.QLabel(self.groupBox_11)
self.label_5.setGeometry(QtCore.QRect(70, 210, 62, 20))
self.label_5.setObjectName("label_5")
self.presetModeWidget.addTab(self.breathingTab, "")
self.fadingTab = QtWidgets.QWidget()
self.fadingTab.setObjectName("fadingTab")
self.groupBox_3 = QtWidgets.QGroupBox(self.fadingTab)
self.groupBox_3.setGeometry(QtCore.QRect(0, 0, 231, 361))
self.groupBox_3.setObjectName("groupBox_3")
self.fadingList = QtWidgets.QListWidget(self.groupBox_3)
self.fadingList.setGeometry(QtCore.QRect(10, 50, 111, 291))
self.fadingList.setObjectName("fadingList")
self.fadingAdd = QtWidgets.QPushButton(self.groupBox_3)
self.fadingAdd.setGeometry(QtCore.QRect(130, 50, 83, 28))
self.fadingAdd.setObjectName("fadingAdd")
self.fadingDelete = QtWidgets.QPushButton(self.groupBox_3)
self.fadingDelete.setGeometry(QtCore.QRect(130, 90, 83, 28))
self.fadingDelete.setObjectName("fadingDelete")
self.groupBox_12 = QtWidgets.QGroupBox(self.fadingTab)
self.groupBox_12.setGeometry(QtCore.QRect(240, 0, 321, 361))
self.groupBox_12.setObjectName("groupBox_12")
self.fadingSpeed = QtWidgets.QSlider(self.groupBox_12)
self.fadingSpeed.setGeometry(QtCore.QRect(15, 70, 31, 160))
self.fadingSpeed.setMaximum(4)
self.fadingSpeed.setProperty("value", 2)
self.fadingSpeed.setOrientation(QtCore.Qt.Vertical)
self.fadingSpeed.setTickPosition(QtWidgets.QSlider.TicksBothSides)
self.fadingSpeed.setObjectName("fadingSpeed")
self.label_9 = QtWidgets.QLabel(self.groupBox_12)
self.label_9.setGeometry(QtCore.QRect(10, 40, 62, 20))
self.label_9.setObjectName("label_9")
self.label_10 = QtWidgets.QLabel(self.groupBox_12)
self.label_10.setGeometry(QtCore.QRect(70, 60, 62, 20))
self.label_10.setObjectName("label_10")
self.label_11 = QtWidgets.QLabel(self.groupBox_12)
self.label_11.setGeometry(QtCore.QRect(70, 210, 62, 20))
self.label_11.setObjectName("label_11")
self.presetModeWidget.addTab(self.fadingTab, "")
self.marqueeTab = QtWidgets.QWidget()
self.marqueeTab.setObjectName("marqueeTab")
self.groupBox_4 = QtWidgets.QGroupBox(self.marqueeTab)
self.groupBox_4.setGeometry(QtCore.QRect(0, 0, 231, 361))
self.groupBox_4.setObjectName("groupBox_4")
self.marqueeList = QtWidgets.QListWidget(self.groupBox_4)
self.marqueeList.setGeometry(QtCore.QRect(10, 50, 111, 291))
self.marqueeList.setObjectName("marqueeList")
self.marqueeAdd = QtWidgets.QPushButton(self.groupBox_4)
self.marqueeAdd.setGeometry(QtCore.QRect(130, 50, 83, 28))
self.marqueeAdd.setObjectName("marqueeAdd")
self.marqueeDelete = QtWidgets.QPushButton(self.groupBox_4)
self.marqueeDelete.setGeometry(QtCore.QRect(130, 90, 83, 28))
self.marqueeDelete.setObjectName("marqueeDelete")
self.groupBox_13 = QtWidgets.QGroupBox(self.marqueeTab)
self.groupBox_13.setGeometry(QtCore.QRect(240, 0, 321, 361))
self.groupBox_13.setObjectName("groupBox_13")
self.marqueeSpeed = QtWidgets.QSlider(self.groupBox_13)
self.marqueeSpeed.setGeometry(QtCore.QRect(15, 70, 31, 160))
self.marqueeSpeed.setMaximum(4)
self.marqueeSpeed.setProperty("value", 2)
self.marqueeSpeed.setOrientation(QtCore.Qt.Vertical)
self.marqueeSpeed.setTickPosition(QtWidgets.QSlider.TicksBothSides)
self.marqueeSpeed.setObjectName("marqueeSpeed")
self.label_15 = QtWidgets.QLabel(self.groupBox_13)
self.label_15.setGeometry(QtCore.QRect(10, 40, 62, 20))
self.label_15.setObjectName("label_15")
self.label_16 = QtWidgets.QLabel(self.groupBox_13)
self.label_16.setGeometry(QtCore.QRect(70, 60, 62, 20))
self.label_16.setObjectName("label_16")
self.label_17 = QtWidgets.QLabel(self.groupBox_13)
self.label_17.setGeometry(QtCore.QRect(70, 210, 62, 20))
self.label_17.setObjectName("label_17")
self.marqueeSize = QtWidgets.QSlider(self.groupBox_13)
self.marqueeSize.setGeometry(QtCore.QRect(185, 70, 31, 160))
self.marqueeSize.setMaximum(3)
self.marqueeSize.setProperty("value", 2)
self.marqueeSize.setOrientation(QtCore.Qt.Vertical)
self.marqueeSize.setTickPosition(QtWidgets.QSlider.TicksBothSides)
self.marqueeSize.setObjectName("marqueeSize")
self.label_18 = QtWidgets.QLabel(self.groupBox_13)
self.label_18.setGeometry(QtCore.QRect(240, 210, 62, 20))
self.label_18.setObjectName("label_18")
self.label_19 = QtWidgets.QLabel(self.groupBox_13)
self.label_19.setGeometry(QtCore.QRect(180, 40, 62, 20))
self.label_19.setObjectName("label_19")
self.label_20 = QtWidgets.QLabel(self.groupBox_13)
self.label_20.setGeometry(QtCore.QRect(240, 60, 62, 20))
self.label_20.setObjectName("label_20")
self.marqueeBackwards = QtWidgets.QCheckBox(self.groupBox_13)
self.marqueeBackwards.setGeometry(QtCore.QRect(20, 260, 89, 26))
self.marqueeBackwards.setObjectName("marqueeBackwards")
self.presetModeWidget.addTab(self.marqueeTab, "")
self.coverMarqueeTab = QtWidgets.QWidget()
self.coverMarqueeTab.setObjectName("coverMarqueeTab")
self.groupBox_5 = QtWidgets.QGroupBox(self.coverMarqueeTab)
self.groupBox_5.setGeometry(QtCore.QRect(0, 0, 231, 361))
self.groupBox_5.setObjectName("groupBox_5")
self.coverMarqueeList = QtWidgets.QListWidget(self.groupBox_5)
self.coverMarqueeList.setGeometry(QtCore.QRect(10, 50, 111, 291))
self.coverMarqueeList.setObjectName("coverMarqueeList")
self.coverMarqueeAdd = QtWidgets.QPushButton(self.groupBox_5)
self.coverMarqueeAdd.setGeometry(QtCore.QRect(130, 50, 83, 28))
self.coverMarqueeAdd.setObjectName("coverMarqueeAdd")
self.coverMarqueeDelete = QtWidgets.QPushButton(self.groupBox_5)
self.coverMarqueeDelete.setGeometry(QtCore.QRect(130, 90, 83, 28))
self.coverMarqueeDelete.setObjectName("coverMarqueeDelete")
self.groupBox_15 = QtWidgets.QGroupBox(self.coverMarqueeTab)
self.groupBox_15.setGeometry(QtCore.QRect(240, 0, 321, 361))
self.groupBox_15.setObjectName("groupBox_15")
self.coverMarqueeSpeed = QtWidgets.QSlider(self.groupBox_15)
self.coverMarqueeSpeed.setGeometry(QtCore.QRect(15, 70, 31, 160))
self.coverMarqueeSpeed.setMaximum(4)
self.coverMarqueeSpeed.setProperty("value", 2)
self.coverMarqueeSpeed.setOrientation(QtCore.Qt.Vertical)
self.coverMarqueeSpeed.setTickPosition(QtWidgets.QSlider.TicksBothSides)
self.coverMarqueeSpeed.setObjectName("coverMarqueeSpeed")
self.label_27 = QtWidgets.QLabel(self.groupBox_15)
self.label_27.setGeometry(QtCore.QRect(10, 40, 62, 20))
self.label_27.setObjectName("label_27")
self.label_28 = QtWidgets.QLabel(self.groupBox_15)
self.label_28.setGeometry(QtCore.QRect(70, 60, 62, 20))
self.label_28.setObjectName("label_28")
self.label_29 = QtWidgets.QLabel(self.groupBox_15)
self.label_29.setGeometry(QtCore.QRect(70, 210, 62, 20))
self.label_29.setObjectName("label_29")
self.coverMarqueeBackwards = QtWidgets.QCheckBox(self.groupBox_15)
self.coverMarqueeBackwards.setGeometry(QtCore.QRect(20, 260, 89, 26))
self.coverMarqueeBackwards.setObjectName("coverMarqueeBackwards")
self.presetModeWidget.addTab(self.coverMarqueeTab, "")
self.pulseTab = QtWidgets.QWidget()
self.pulseTab.setObjectName("pulseTab")
self.groupBox_6 = QtWidgets.QGroupBox(self.pulseTab)
self.groupBox_6.setGeometry(QtCore.QRect(0, 0, 231, 361))
self.groupBox_6.setObjectName("groupBox_6")
self.pulseList = QtWidgets.QListWidget(self.groupBox_6)
self.pulseList.setGeometry(QtCore.QRect(10, 50, 111, 291))
self.pulseList.setObjectName("pulseList")
self.pulseAdd = QtWidgets.QPushButton(self.groupBox_6)
self.pulseAdd.setGeometry(QtCore.QRect(130, 50, 83, 28))
self.pulseAdd.setObjectName("pulseAdd")
self.pulseDelete = QtWidgets.QPushButton(self.groupBox_6)
self.pulseDelete.setGeometry(QtCore.QRect(130, 90, 83, 28))
self.pulseDelete.setObjectName("pulseDelete")
self.groupBox_16 = QtWidgets.QGroupBox(self.pulseTab)
self.groupBox_16.setGeometry(QtCore.QRect(240, 0, 321, 361))
self.groupBox_16.setObjectName("groupBox_16")
self.pulseSpeed = QtWidgets.QSlider(self.groupBox_16)
self.pulseSpeed.setGeometry(QtCore.QRect(15, 70, 31, 160))
self.pulseSpeed.setMaximum(4)
self.pulseSpeed.setProperty("value", 2)
self.pulseSpeed.setOrientation(QtCore.Qt.Vertical)
self.pulseSpeed.setTickPosition(QtWidgets.QSlider.TicksBothSides)
self.pulseSpeed.setObjectName("pulseSpeed")
self.label_33 = QtWidgets.QLabel(self.groupBox_16)
self.label_33.setGeometry(QtCore.QRect(10, 40, 62, 20))
self.label_33.setObjectName("label_33")
self.label_34 = QtWidgets.QLabel(self.groupBox_16)
self.label_34.setGeometry(QtCore.QRect(70, 60, 62, 20))
self.label_34.setObjectName("label_34")
self.label_35 = QtWidgets.QLabel(self.groupBox_16)
self.label_35.setGeometry(QtCore.QRect(70, 210, 62, 20))
self.label_35.setObjectName("label_35")
self.presetModeWidget.addTab(self.pulseTab, "")
self.spectrumTab = QtWidgets.QWidget()
self.spectrumTab.setObjectName("spectrumTab")
self.groupBox_17 = QtWidgets.QGroupBox(self.spectrumTab)
self.groupBox_17.setGeometry(QtCore.QRect(0, 0, 321, 361))
self.groupBox_17.setObjectName("groupBox_17")
self.spectrumSpeed = QtWidgets.QSlider(self.groupBox_17)
self.spectrumSpeed.setGeometry(QtCore.QRect(15, 70, 31, 160))
self.spectrumSpeed.setMaximum(4)
self.spectrumSpeed.setProperty("value", 2)
self.spectrumSpeed.setOrientation(QtCore.Qt.Vertical)
self.spectrumSpeed.setTickPosition(QtWidgets.QSlider.TicksBothSides)
self.spectrumSpeed.setObjectName("spectrumSpeed")
self.label_39 = QtWidgets.QLabel(self.groupBox_17)
self.label_39.setGeometry(QtCore.QRect(10, 40, 62, 20))
self.label_39.setObjectName("label_39")
self.label_40 = QtWidgets.QLabel(self.groupBox_17)
self.label_40.setGeometry(QtCore.QRect(70, 60, 62, 20))
self.label_40.setObjectName("label_40")
self.label_41 = QtWidgets.QLabel(self.groupBox_17)
self.label_41.setGeometry(QtCore.QRect(70, 210, 62, 20))
self.label_41.setObjectName("label_41")
self.spectrumBackwards = QtWidgets.QCheckBox(self.groupBox_17)
self.spectrumBackwards.setGeometry(QtCore.QRect(20, 260, 89, 26))
self.spectrumBackwards.setObjectName("spectrumBackwards")
self.presetModeWidget.addTab(self.spectrumTab, "")
self.alternatingTab = QtWidgets.QWidget()
self.alternatingTab.setObjectName("alternatingTab")
self.groupBox_7 = QtWidgets.QGroupBox(self.alternatingTab)
self.groupBox_7.setGeometry(QtCore.QRect(0, 0, 231, 361))
self.groupBox_7.setObjectName("groupBox_7")
self.alternatingList = QtWidgets.QListWidget(self.groupBox_7)
self.alternatingList.setGeometry(QtCore.QRect(10, 50, 111, 291))
self.alternatingList.setObjectName("alternatingList")
self.alternatingAdd = QtWidgets.QPushButton(self.groupBox_7)
self.alternatingAdd.setGeometry(QtCore.QRect(130, 50, 83, 28))
self.alternatingAdd.setObjectName("alternatingAdd")
self.alternatingDelete = QtWidgets.QPushButton(self.groupBox_7)
self.alternatingDelete.setGeometry(QtCore.QRect(130, 90, 83, 28))
self.alternatingDelete.setObjectName("alternatingDelete")
self.groupBox_18 = QtWidgets.QGroupBox(self.alternatingTab)
self.groupBox_18.setGeometry(QtCore.QRect(240, 0, 321, 361))
self.groupBox_18.setObjectName("groupBox_18")
self.alternatingSpeed = QtWidgets.QSlider(self.groupBox_18)
self.alternatingSpeed.setGeometry(QtCore.QRect(15, 70, 31, 160))
self.alternatingSpeed.setMaximum(4)
self.alternatingSpeed.setProperty("value", 2)
self.alternatingSpeed.setOrientation(QtCore.Qt.Vertical)
self.alternatingSpeed.setTickPosition(QtWidgets.QSlider.TicksBothSides)
self.alternatingSpeed.setObjectName("alternatingSpeed")
self.label_45 = QtWidgets.QLabel(self.groupBox_18)
self.label_45.setGeometry(QtCore.QRect(10, 40, 62, 20))
self.label_45.setObjectName("label_45")
self.label_46 = QtWidgets.QLabel(self.groupBox_18)
self.label_46.setGeometry(QtCore.QRect(70, 60, 62, 20))
self.label_46.setObjectName("label_46")
self.label_47 = QtWidgets.QLabel(self.groupBox_18)
self.label_47.setGeometry(QtCore.QRect(70, 210, 62, 20))
self.label_47.setObjectName("label_47")
self.alternatingSize = QtWidgets.QSlider(self.groupBox_18)
self.alternatingSize.setGeometry(QtCore.QRect(185, 70, 31, 160))
self.alternatingSize.setMaximum(3)
self.alternatingSize.setProperty("value", 2)
self.alternatingSize.setOrientation(QtCore.Qt.Vertical)
self.alternatingSize.setTickPosition(QtWidgets.QSlider.TicksBothSides)
self.alternatingSize.setObjectName("alternatingSize")
self.label_48 = QtWidgets.QLabel(self.groupBox_18)
self.label_48.setGeometry(QtCore.QRect(240, 210, 62, 20))
self.label_48.setObjectName("label_48")
self.label_49 = QtWidgets.QLabel(self.groupBox_18)
self.label_49.setGeometry(QtCore.QRect(180, 40, 62, 20))
self.label_49.setObjectName("label_49")
self.label_50 = QtWidgets.QLabel(self.groupBox_18)
self.label_50.setGeometry(QtCore.QRect(240, 60, 62, 20))
self.label_50.setObjectName("label_50")
self.alternatingBackwards = QtWidgets.QCheckBox(self.groupBox_18)
self.alternatingBackwards.setGeometry(QtCore.QRect(20, 260, 89, 26))
self.alternatingBackwards.setObjectName("alternatingBackwards")
self.alternatingMoving = QtWidgets.QCheckBox(self.groupBox_18)
self.alternatingMoving.setGeometry(QtCore.QRect(20, 290, 89, 26))
self.alternatingMoving.setObjectName("alternatingMoving")
self.presetModeWidget.addTab(self.alternatingTab, "")
self.candleTab = QtWidgets.QWidget()
self.candleTab.setObjectName("candleTab")
self.groupBox_8 = QtWidgets.QGroupBox(self.candleTab)
self.groupBox_8.setGeometry(QtCore.QRect(0, 0, 231, 361))
self.groupBox_8.setObjectName("groupBox_8")
self.candleList = QtWidgets.QListWidget(self.groupBox_8)
self.candleList.setGeometry(QtCore.QRect(10, 50, 111, 291))
self.candleList.setObjectName("candleList")
self.candleAdd = QtWidgets.QPushButton(self.groupBox_8)
self.candleAdd.setGeometry(QtCore.QRect(130, 50, 83, 28))
self.candleAdd.setObjectName("candleAdd")
self.candleDelete = QtWidgets.QPushButton(self.groupBox_8)
self.candleDelete.setGeometry(QtCore.QRect(130, 90, 83, 28))
self.candleDelete.setObjectName("candleDelete")
self.presetModeWidget.addTab(self.candleTab, "")
self.wingsTab = QtWidgets.QWidget()
self.wingsTab.setObjectName("wingsTab")
self.groupBox_9 = QtWidgets.QGroupBox(self.wingsTab)
self.groupBox_9.setGeometry(QtCore.QRect(0, 0, 231, 361))
self.groupBox_9.setObjectName("groupBox_9")
self.wingsList = QtWidgets.QListWidget(self.groupBox_9)
self.wingsList.setGeometry(QtCore.QRect(10, 50, 111, 291))
self.wingsList.setObjectName("wingsList")
self.wingsAdd = QtWidgets.QPushButton(self.groupBox_9)
self.wingsAdd.setGeometry(QtCore.QRect(130, 50, 83, 28))
self.wingsAdd.setObjectName("wingsAdd")
self.wingsDelete = QtWidgets.QPushButton(self.groupBox_9)
self.wingsDelete.setGeometry(QtCore.QRect(130, 90, 83, 28))
self.wingsDelete.setObjectName("wingsDelete")
self.groupBox_20 = QtWidgets.QGroupBox(self.wingsTab)
self.groupBox_20.setGeometry(QtCore.QRect(240, 0, 321, 361))
self.groupBox_20.setObjectName("groupBox_20")
self.wingsSpeed = QtWidgets.QSlider(self.groupBox_20)
self.wingsSpeed.setGeometry(QtCore.QRect(15, 70, 31, 160))
self.wingsSpeed.setMaximum(4)
self.wingsSpeed.setProperty("value", 2)
self.wingsSpeed.setOrientation(QtCore.Qt.Vertical)
self.wingsSpeed.setTickPosition(QtWidgets.QSlider.TicksBothSides)
self.wingsSpeed.setObjectName("wingsSpeed")
self.label_57 = QtWidgets.QLabel(self.groupBox_20)
self.label_57.setGeometry(QtCore.QRect(10, 40, 62, 20))
self.label_57.setObjectName("label_57")
self.label_58 = QtWidgets.QLabel(self.groupBox_20)
self.label_58.setGeometry(QtCore.QRect(70, 60, 62, 20))
self.label_58.setObjectName("label_58")
self.label_59 = QtWidgets.QLabel(self.groupBox_20)
self.label_59.setGeometry(QtCore.QRect(70, 210, 62, 20))
self.label_59.setObjectName("label_59")
self.presetModeWidget.addTab(self.wingsTab, "")
self.audioLevelTab = QtWidgets.QWidget()
self.audioLevelTab.setObjectName("audioLevelTab")
self.groupBox_21 = QtWidgets.QGroupBox(self.audioLevelTab)
self.groupBox_21.setGeometry(QtCore.QRect(240, 0, 321, 361))
self.groupBox_21.setObjectName("groupBox_21")
self.label_60 = QtWidgets.QLabel(self.groupBox_21)
self.label_60.setGeometry(QtCore.QRect(10, 30, 62, 20))
self.label_60.setObjectName("label_60")
self.label_61 = QtWidgets.QLabel(self.groupBox_21)
self.label_61.setGeometry(QtCore.QRect(10, 80, 81, 20))
self.label_61.setObjectName("label_61")
self.audioLevelTolerance = QtWidgets.QDoubleSpinBox(self.groupBox_21)
self.audioLevelTolerance.setGeometry(QtCore.QRect(10, 50, 68, 23))
self.audioLevelTolerance.setDecimals(1)
self.audioLevelTolerance.setProperty("value", 1.0)
self.audioLevelTolerance.setObjectName("audioLevelTolerance")
self.audioLevelSmooth = QtWidgets.QDoubleSpinBox(self.groupBox_21)
self.audioLevelSmooth.setGeometry(QtCore.QRect(10, 100, 68, 23))
self.audioLevelSmooth.setDecimals(0)
self.audioLevelSmooth.setProperty("value", 3.0)
self.audioLevelSmooth.setObjectName("audioLevelSmooth")
self.groupBox_10 = QtWidgets.QGroupBox(self.audioLevelTab)
self.groupBox_10.setGeometry(QtCore.QRect(0, 0, 231, 361))
self.groupBox_10.setObjectName("groupBox_10")
self.audioLevelList = QtWidgets.QListWidget(self.groupBox_10)
self.audioLevelList.setGeometry(QtCore.QRect(10, 50, 111, 291))
self.audioLevelList.setObjectName("audioLevelList")
self.audioLevelAdd = QtWidgets.QPushButton(self.groupBox_10)
self.audioLevelAdd.setGeometry(QtCore.QRect(130, 50, 83, 28))
self.audioLevelAdd.setObjectName("audioLevelAdd")
self.audioLevelDelete = QtWidgets.QPushButton(self.groupBox_10)
self.audioLevelDelete.setGeometry(QtCore.QRect(130, 90, 83, 28))
self.audioLevelDelete.setObjectName("audioLevelDelete")
self.presetModeWidget.addTab(self.audioLevelTab, "")
self.customTab = QtWidgets.QWidget()
self.customTab.setObjectName("customTab")
self.groupBox_22 = QtWidgets.QGroupBox(self.customTab)
self.groupBox_22.setGeometry(QtCore.QRect(630, 0, 321, 371))
self.groupBox_22.setObjectName("groupBox_22")
self.customSpeed = QtWidgets.QSlider(self.groupBox_22)
self.customSpeed.setGeometry(QtCore.QRect(15, 70, 31, 160))
self.customSpeed.setMaximum(4)
self.customSpeed.setProperty("value", 2)
self.customSpeed.setOrientation(QtCore.Qt.Vertical)
self.customSpeed.setTickPosition(QtWidgets.QSlider.TicksBothSides)
self.customSpeed.setObjectName("customSpeed")
self.label_62 = QtWidgets.QLabel(self.groupBox_22)
self.label_62.setGeometry(QtCore.QRect(10, 40, 62, 20))
self.label_62.setObjectName("label_62")
self.label_63 = QtWidgets.QLabel(self.groupBox_22)
self.label_63.setGeometry(QtCore.QRect(70, 60, 62, 20))
self.label_63.setObjectName("label_63")
self.label_64 = QtWidgets.QLabel(self.groupBox_22)
self.label_64.setGeometry(QtCore.QRect(70, 210, 62, 20))
self.label_64.setObjectName("label_64")
self.customMode = QtWidgets.QComboBox(self.groupBox_22)
self.customMode.setGeometry(QtCore.QRect(190, 70, 86, 25))
self.customMode.setObjectName("customMode")
self.customMode.addItem("")
self.customMode.addItem("")
self.customMode.addItem("")
self.label_65 = QtWidgets.QLabel(self.groupBox_22)
self.label_65.setGeometry(QtCore.QRect(190, 40, 62, 20))
self.label_65.setObjectName("label_65")
self.groupBox_19 = QtWidgets.QGroupBox(self.customTab)
self.groupBox_19.setGeometry(QtCore.QRect(0, 0, 611, 371))
self.groupBox_19.setObjectName("groupBox_19")
self.customTable = QtWidgets.QTableWidget(self.groupBox_19)
self.customTable.setGeometry(QtCore.QRect(10, 30, 471, 331))
self.customTable.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)
self.customTable.setDragDropOverwriteMode(False)
self.customTable.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
self.customTable.setRowCount(40)
self.customTable.setColumnCount(2)
self.customTable.setObjectName("customTable")
item = QtWidgets.QTableWidgetItem()
self.customTable.setHorizontalHeaderItem(0, item)
item = QtWidgets.QTableWidgetItem()
self.customTable.setHorizontalHeaderItem(1, item)
self.customTable.verticalHeader().setVisible(False)
self.customEdit = QtWidgets.QPushButton(self.groupBox_19)
self.customEdit.setGeometry(QtCore.QRect(500, 40, 83, 28))
self.customEdit.setObjectName("customEdit")
self.presetModeWidget.addTab(self.customTab, "")
self.profileTab = QtWidgets.QWidget()
self.profileTab.setObjectName("profileTab")
self.groupBox_14 = QtWidgets.QGroupBox(self.profileTab)
self.groupBox_14.setGeometry(QtCore.QRect(0, 0, 421, 361))
self.groupBox_14.setObjectName("groupBox_14")
self.profileList = QtWidgets.QListWidget(self.groupBox_14)
self.profileList.setGeometry(QtCore.QRect(10, 50, 111, 291))
self.profileList.setObjectName("profileList")
self.profileAdd = QtWidgets.QPushButton(self.groupBox_14)
self.profileAdd.setGeometry(QtCore.QRect(130, 50, 83, 28))
self.profileAdd.setObjectName("profileAdd")
self.profileDelete = QtWidgets.QPushButton(self.groupBox_14)
self.profileDelete.setGeometry(QtCore.QRect(130, 90, 83, 28))
self.profileDelete.setObjectName("profileDelete")
self.profileRefresh = QtWidgets.QPushButton(self.groupBox_14)
self.profileRefresh.setGeometry(QtCore.QRect(130, 130, 83, 28))
self.profileRefresh.setObjectName("profileRefresh")
self.profileName = QtWidgets.QLineEdit(self.groupBox_14)
self.profileName.setGeometry(QtCore.QRect(300, 50, 113, 28))
self.profileName.setObjectName("profileName")
self.label_3 = QtWidgets.QLabel(self.groupBox_14)
self.label_3.setGeometry(QtCore.QRect(220, 50, 62, 20))
self.label_3.setObjectName("label_3")
self.presetModeWidget.addTab(self.profileTab, "")
self.animatedTab = QtWidgets.QWidget()
self.animatedTab.setObjectName("animatedTab")
self.groupBox_23 = QtWidgets.QGroupBox(self.animatedTab)
self.groupBox_23.setGeometry(QtCore.QRect(0, 0, 721, 371))
self.groupBox_23.setObjectName("groupBox_23")
self.animatedTable = QtWidgets.QTableWidget(self.groupBox_23)
self.animatedTable.setGeometry(QtCore.QRect(230, 30, 361, 331))
self.animatedTable.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)
self.animatedTable.setDragDropOverwriteMode(False)
self.animatedTable.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
self.animatedTable.setRowCount(40)
self.animatedTable.setColumnCount(2)
self.animatedTable.setObjectName("animatedTable")
item = QtWidgets.QTableWidgetItem()
self.animatedTable.setHorizontalHeaderItem(0, item)
item = QtWidgets.QTableWidgetItem()
self.animatedTable.setHorizontalHeaderItem(1, item)
self.animatedTable.verticalHeader().setVisible(False)
self.animatedEdit = QtWidgets.QPushButton(self.groupBox_23)
self.animatedEdit.setGeometry(QtCore.QRect(610, 40, 83, 28))
self.animatedEdit.setObjectName("animatedEdit")
self.animatedList = QtWidgets.QListWidget(self.groupBox_23)
self.animatedList.setGeometry(QtCore.QRect(10, 40, 111, 291))
self.animatedList.setObjectName("animatedList")
self.animatedDelete = QtWidgets.QPushButton(self.groupBox_23)
self.animatedDelete.setGeometry(QtCore.QRect(130, 80, 83, 28))
self.animatedDelete.setObjectName("animatedDelete")
self.animatedAdd = QtWidgets.QPushButton(self.groupBox_23)
self.animatedAdd.setGeometry(QtCore.QRect(130, 40, 83, 28))
self.animatedAdd.setObjectName("animatedAdd")
self.animatedRoundName = QtWidgets.QLineEdit(self.groupBox_23)
self.animatedRoundName.setGeometry(QtCore.QRect(130, 120, 81, 25))
self.animatedRoundName.setObjectName("animatedRoundName")
self.groupBox_24 = QtWidgets.QGroupBox(self.animatedTab)
self.groupBox_24.setGeometry(QtCore.QRect(740, 0, 331, 371))
self.groupBox_24.setObjectName("groupBox_24")
self.label_66 = QtWidgets.QLabel(self.groupBox_24)
self.label_66.setGeometry(QtCore.QRect(10, 40, 201, 20))
self.label_66.setObjectName("label_66")
self.animatedSpeed = QtWidgets.QDoubleSpinBox(self.groupBox_24)
self.animatedSpeed.setGeometry(QtCore.QRect(10, 70, 68, 26))
self.animatedSpeed.setDecimals(0)
self.animatedSpeed.setMinimum(15.0)
self.animatedSpeed.setMaximum(5000.0)
self.animatedSpeed.setSingleStep(10.0)
self.animatedSpeed.setProperty("value", 50.0)
self.animatedSpeed.setObjectName("animatedSpeed")
self.label_21 = QtWidgets.QLabel(self.groupBox_24)
self.label_21.setGeometry(QtCore.QRect(40, 130, 261, 71))
self.label_21.setWordWrap(True)
self.label_21.setObjectName("label_21")
self.presetModeWidget.addTab(self.animatedTab, "")
self.modeWidget.addTab(self.presetTab, "")
self.timesTab = QtWidgets.QWidget()
self.timesTab.setObjectName("timesTab")
self.label_7 = QtWidgets.QLabel(self.timesTab)
self.label_7.setGeometry(QtCore.QRect(30, 20, 461, 17))
self.label_7.setObjectName("label_7")
self.offTime = QtWidgets.QLineEdit(self.timesTab)
self.offTime.setGeometry(QtCore.QRect(30, 40, 113, 25))
self.offTime.setObjectName("offTime")
self.onTime = QtWidgets.QLineEdit(self.timesTab)
self.onTime.setGeometry(QtCore.QRect(30, 100, 113, 25))
self.onTime.setObjectName("onTime")
self.label_8 = QtWidgets.QLabel(self.timesTab)
self.label_8.setGeometry(QtCore.QRect(30, 80, 461, 17))
self.label_8.setObjectName("label_8")
self.label_12 = QtWidgets.QLabel(self.timesTab)
self.label_12.setGeometry(QtCore.QRect(160, 50, 131, 17))
self.label_12.setObjectName("label_12")
self.label_13 = QtWidgets.QLabel(self.timesTab)
self.label_13.setGeometry(QtCore.QRect(160, 110, 131, 17))
self.label_13.setObjectName("label_13")
self.label_14 = QtWidgets.QLabel(self.timesTab)
self.label_14.setGeometry(QtCore.QRect(30, 140, 341, 111))
font = QtGui.QFont()
font.setPointSize(11)
self.label_14.setFont(font)
self.label_14.setWordWrap(True)
self.label_14.setObjectName("label_14")
self.timeSave = QtWidgets.QPushButton(self.timesTab)
self.timeSave.setGeometry(QtCore.QRect(40, 290, 82, 25))
self.timeSave.setObjectName("timeSave")
self.modeWidget.addTab(self.timesTab, "")
self.applyBtn = QtWidgets.QPushButton(self.centralwidget)
self.applyBtn.setGeometry(QtCore.QRect(490, 530, 101, 41))
self.applyBtn.setObjectName("applyBtn")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(940, 20, 62, 20))
self.label.setObjectName("label")
self.portTxt = QtWidgets.QLineEdit(self.centralwidget)
self.portTxt.setGeometry(QtCore.QRect(1000, 20, 113, 28))
self.portTxt.setObjectName("portTxt")
self.label_6 = QtWidgets.QLabel(self.centralwidget)
self.label_6.setGeometry(QtCore.QRect(180, -10, 741, 91))
font = QtGui.QFont()
font.setPointSize(13)
self.label_6.setFont(font)
self.label_6.setWordWrap(True)
self.label_6.setObjectName("label_6")
self.unitLEDBtn = QtWidgets.QPushButton(self.centralwidget)
self.unitLEDBtn.setGeometry(QtCore.QRect(840, 50, 121, 21))
self.unitLEDBtn.setObjectName("unitLEDBtn")
MainWindow.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
self.modeWidget.setCurrentIndex(0)
self.presetModeWidget.setCurrentIndex(0)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
MainWindow.setTabOrder(self.channel1Check, self.channel2Check)
MainWindow.setTabOrder(self.channel2Check, self.modeWidget)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "hue_plus"))
self.channel1Check.setText(_translate("MainWindow", "Channel 1"))
self.channel2Check.setText(_translate("MainWindow", "Channel 2"))
self.groupBox.setTitle(_translate("MainWindow", "Colors"))
self.fixedAdd.setText(_translate("MainWindow", "Add color"))
self.fixedDelete.setText(_translate("MainWindow", "Delete color"))
self.presetModeWidget.setTabText(self.presetModeWidget.indexOf(self.fixedTab), _translate("MainWindow", "Fixed"))
self.groupBox_2.setTitle(_translate("MainWindow", "Colors"))
self.breathingAdd.setText(_translate("MainWindow", "Add color"))
self.breathingDelete.setText(_translate("MainWindow", "Delete color"))
self.groupBox_11.setTitle(_translate("MainWindow", "Other"))
self.label_2.setText(_translate("MainWindow", "Speed"))
self.label_4.setText(_translate("MainWindow", "Fastest"))
self.label_5.setText(_translate("MainWindow", "Slowest"))
self.presetModeWidget.setTabText(self.presetModeWidget.indexOf(self.breathingTab), _translate("MainWindow", "Breathing"))
self.groupBox_3.setTitle(_translate("MainWindow", "Colors"))
self.fadingAdd.setText(_translate("MainWindow", "Add color"))
self.fadingDelete.setText(_translate("MainWindow", "Delete color"))
self.groupBox_12.setTitle(_translate("MainWindow", "Other"))
self.label_9.setText(_translate("MainWindow", "Speed"))
self.label_10.setText(_translate("MainWindow", "Fastest"))
self.label_11.setText(_translate("MainWindow", "Slowest"))
self.presetModeWidget.setTabText(self.presetModeWidget.indexOf(self.fadingTab), _translate("MainWindow", "Fading"))
self.groupBox_4.setTitle(_translate("MainWindow", "Colors"))
self.marqueeAdd.setText(_translate("MainWindow", "Add color"))
self.marqueeDelete.setText(_translate("MainWindow", "Delete color"))
self.groupBox_13.setTitle(_translate("MainWindow", "Other"))
self.label_15.setText(_translate("MainWindow", "Speed"))
self.label_16.setText(_translate("MainWindow", "Fastest"))
self.label_17.setText(_translate("MainWindow", "Slowest"))
self.label_18.setText(_translate("MainWindow", "Smaller"))
self.label_19.setText(_translate("MainWindow", "Size"))
self.label_20.setText(_translate("MainWindow", "Larger"))
self.marqueeBackwards.setText(_translate("MainWindow", "Backwards"))
self.presetModeWidget.setTabText(self.presetModeWidget.indexOf(self.marqueeTab), _translate("MainWindow", "Marquee"))
self.groupBox_5.setTitle(_translate("MainWindow", "Colors"))
self.coverMarqueeAdd.setText(_translate("MainWindow", "Add color"))
self.coverMarqueeDelete.setText(_translate("MainWindow", "Delete color"))
self.groupBox_15.setTitle(_translate("MainWindow", "Other"))
self.label_27.setText(_translate("MainWindow", "Speed"))
self.label_28.setText(_translate("MainWindow", "Fastest"))
self.label_29.setText(_translate("MainWindow", "Slowest"))
self.coverMarqueeBackwards.setText(_translate("MainWindow", "Backwards"))
self.presetModeWidget.setTabText(self.presetModeWidget.indexOf(self.coverMarqueeTab), _translate("MainWindow", "Covering Marquee"))
self.groupBox_6.setTitle(_translate("MainWindow", "Colors"))
self.pulseAdd.setText(_translate("MainWindow", "Add color"))
self.pulseDelete.setText(_translate("MainWindow", "Delete color"))
self.groupBox_16.setTitle(_translate("MainWindow", "Other"))
self.label_33.setText(_translate("MainWindow", "Speed"))
self.label_34.setText(_translate("MainWindow", "Fastest"))
self.label_35.setText(_translate("MainWindow", "Slowest"))
self.presetModeWidget.setTabText(self.presetModeWidget.indexOf(self.pulseTab), _translate("MainWindow", "Pulse"))
self.groupBox_17.setTitle(_translate("MainWindow", "Other"))
self.label_39.setText(_translate("MainWindow", "Speed"))
self.label_40.setText(_translate("MainWindow", "Fastest"))
self.label_41.setText(_translate("MainWindow", "Slowest"))
self.spectrumBackwards.setText(_translate("MainWindow", "Backwards"))
self.presetModeWidget.setTabText(self.presetModeWidget.indexOf(self.spectrumTab), _translate("MainWindow", "Spectrum"))
self.groupBox_7.setTitle(_translate("MainWindow", "Colors"))
self.alternatingAdd.setText(_translate("MainWindow", "Add color"))
self.alternatingDelete.setText(_translate("MainWindow", "Delete color"))
self.groupBox_18.setTitle(_translate("MainWindow", "Other"))
self.label_45.setText(_translate("MainWindow", "Speed"))
self.label_46.setText(_translate("MainWindow", "Fastest"))
self.label_47.setText(_translate("MainWindow", "Slowest"))
self.label_48.setText(_translate("MainWindow", "Smaller"))
self.label_49.setText(_translate("MainWindow", "Size"))
self.label_50.setText(_translate("MainWindow", "Larger"))
self.alternatingBackwards.setText(_translate("MainWindow", "Backwards"))
self.alternatingMoving.setText(_translate("MainWindow", "Moving"))
self.presetModeWidget.setTabText(self.presetModeWidget.indexOf(self.alternatingTab), _translate("MainWindow", "Alternating"))
self.groupBox_8.setTitle(_translate("MainWindow", "Colors"))
self.candleAdd.setText(_translate("MainWindow", "Add color"))
self.candleDelete.setText(_translate("MainWindow", "Delete color"))
self.presetModeWidget.setTabText(self.presetModeWidget.indexOf(self.candleTab), _translate("MainWindow", "Candle"))
self.groupBox_9.setTitle(_translate("MainWindow", "Colors"))
self.wingsAdd.setText(_translate("MainWindow", "Add color"))
self.wingsDelete.setText(_translate("MainWindow", "Delete color"))
self.groupBox_20.setTitle(_translate("MainWindow", "Other"))
self.label_57.setText(_translate("MainWindow", "Speed"))
self.label_58.setText(_translate("MainWindow", "Fastest"))
self.label_59.setText(_translate("MainWindow", "Slowest"))
self.presetModeWidget.setTabText(self.presetModeWidget.indexOf(self.wingsTab), _translate("MainWindow", "Wings"))
self.groupBox_21.setTitle(_translate("MainWindow", "Other"))
self.label_60.setText(_translate("MainWindow", "Tolerance"))
self.label_61.setText(_translate("MainWindow", "Smoothness"))
self.groupBox_10.setTitle(_translate("MainWindow", "Colors"))
self.audioLevelAdd.setText(_translate("MainWindow", "Add color"))
self.audioLevelDelete.setText(_translate("MainWindow", "Delete color"))
self.presetModeWidget.setTabText(self.presetModeWidget.indexOf(self.audioLevelTab), _translate("MainWindow", "Audio Level"))
self.groupBox_22.setTitle(_translate("MainWindow", "Other"))
self.label_62.setText(_translate("MainWindow", "Speed"))
self.label_63.setText(_translate("MainWindow", "Fastest"))
self.label_64.setText(_translate("MainWindow", "Slowest"))
self.customMode.setItemText(0, _translate("MainWindow", "Fixed"))
self.customMode.setItemText(1, _translate("MainWindow", "Breathing"))
self.customMode.setItemText(2, _translate("MainWindow", "Wave"))
self.label_65.setText(_translate("MainWindow", "Mode"))
self.groupBox_19.setTitle(_translate("MainWindow", "Colors"))
item = self.customTable.horizontalHeaderItem(0)
item.setText(_translate("MainWindow", "LED #"))
item = self.customTable.horizontalHeaderItem(1)
item.setText(_translate("MainWindow", "Colors"))
self.customEdit.setText(_translate("MainWindow", "Edit Color"))
self.presetModeWidget.setTabText(self.presetModeWidget.indexOf(self.customTab), _translate("MainWindow", "Custom"))
self.groupBox_14.setTitle(_translate("MainWindow", "Profiles"))
self.profileAdd.setText(_translate("MainWindow", "Add profile"))
self.profileDelete.setText(_translate("MainWindow", "Delete profile"))
self.profileRefresh.setText(_translate("MainWindow", "Refresh"))
self.profileName.setText(_translate("MainWindow", "profile1"))
self.label_3.setText(_translate("MainWindow", "Name:"))
self.presetModeWidget.setTabText(self.presetModeWidget.indexOf(self.profileTab), _translate("MainWindow", "Profiles"))
self.groupBox_23.setTitle(_translate("MainWindow", "Colors"))
item = self.animatedTable.horizontalHeaderItem(0)
item.setText(_translate("MainWindow", "LED #"))
item = self.animatedTable.horizontalHeaderItem(1)
item.setText(_translate("MainWindow", "Colors"))
self.animatedEdit.setText(_translate("MainWindow", "Edit Color"))
self.animatedDelete.setText(_translate("MainWindow", "Delete round"))
self.animatedAdd.setText(_translate("MainWindow", "Add round"))
self.animatedRoundName.setText(_translate("MainWindow", "round1"))
self.groupBox_24.setTitle(_translate("MainWindow", "Other"))
self.label_66.setText(_translate("MainWindow", "Speed between refresh, in ms"))
self.label_21.setText(_translate("MainWindow", "To use, simply set a custom pattern for each round."))
self.presetModeWidget.setTabText(self.presetModeWidget.indexOf(self.animatedTab), _translate("MainWindow", "Custom Animated"))
self.modeWidget.setTabText(self.modeWidget.indexOf(self.presetTab), _translate("MainWindow", "Preset"))
self.label_7.setText(_translate("MainWindow", "The time to turn off the lights (in 24 hour time, separated by a colon)"))
self.offTime.setText(_translate("MainWindow", "00:00"))
self.onTime.setText(_translate("MainWindow", "00:00"))
self.label_8.setText(_translate("MainWindow", "The time to turn on the lights (in 24 hour time, separated by a colon)"))
self.label_12.setText(_translate("MainWindow", "00:00 means none"))
self.label_13.setText(_translate("MainWindow", "00:00 means none"))
self.label_14.setText(_translate("MainWindow", "This looks for a profile called previous and uses that. If that profile does not exist, the time will not work."))
self.timeSave.setText(_translate("MainWindow", "Save"))
self.modeWidget.setTabText(self.modeWidget.indexOf(self.timesTab), _translate("MainWindow", "Times"))
self.applyBtn.setText(_translate("MainWindow", "Apply"))
self.label.setText(_translate("MainWindow", "Port:"))
self.portTxt.setText(_translate("MainWindow", "/dev/ttyACM0"))
self.label_6.setText(_translate("MainWindow", "Now with support for turning on and off at specific times, audio on Windows, a way to make your own modes, and more!"))
self.unitLEDBtn.setText(_translate("MainWindow", "Toggle Unit LED"))<|fim▁end|>
|
#
# Created by: PyQt5 UI code generator 5.8.2
#
# WARNING! All changes made in this file will be lost!
|
<|file_name|>types.rs<|end_file_name|><|fim▁begin|>//! NTRU type definitions
//!
//! This module includes all the needed structs and enums for NTRU encryption library. All of them
//! with their needed methods.
use std::ops::{Add, Sub};
use std::default::Default;
use std::{fmt, mem, error};
use libc::{int16_t, uint8_t, uint16_t};
use ffi;
use encparams::EncParams;
use rand::RandContext;
/// Max `N` value for all param sets; +1 for `ntru_invert_...()`
pub const MAX_DEGREE: usize = (1499 + 1);
/// (Max `coefficients` + 16) rounded to a multiple of 8
const INT_POLY_SIZE: usize = ((MAX_DEGREE + 16 + 7) & 0xFFF8);
/// `max(df1, df2, df3, dg)`
pub const MAX_ONES: usize = 499;
#[repr(C)]
/// A polynomial with integer coefficients.
pub struct IntPoly {
/// The number of coefficients
n: uint16_t,
/// The coefficients
coeffs: [int16_t; INT_POLY_SIZE],
}
impl Default for IntPoly {
fn default() -> IntPoly {
IntPoly {
n: 0,
coeffs: [0; INT_POLY_SIZE],
}
}
}
impl Clone for IntPoly {
fn clone(&self) -> IntPoly {
let mut new_coeffs = [0i16; INT_POLY_SIZE];
new_coeffs.clone_from_slice(&self.coeffs);
IntPoly {
n: self.n,
coeffs: new_coeffs,
}
}
}
impl Add for IntPoly {
type Output = IntPoly;
fn add(self, rhs: IntPoly) -> Self::Output {
let mut out = self.clone();
unsafe { ffi::ntru_add(&mut out, &rhs) };
out
}
}
impl Sub for IntPoly {
type Output = IntPoly;
fn sub(self, rhs: IntPoly) -> Self::Output {
let mut out = self.clone();
unsafe { ffi::ntru_sub(&mut out, &rhs) };
out
}
}
impl fmt::Debug for IntPoly {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f,
"{{ n: {}, coeffs: [{}...{}] }}",
self.n,
self.coeffs[0],
self.coeffs[INT_POLY_SIZE - 1])
}
}<|fim▁hole|> {
for i in 0..self.n as usize {
if self.coeffs[i] != other.coeffs[i] {
return false;
}
}
true
}
}
}
impl IntPoly {
/// Create a new IntPoly
pub fn new(coeffs: &[i16]) -> IntPoly {
let mut new_coeffs = [0; INT_POLY_SIZE];
for (i, coeff) in coeffs.iter().enumerate() {
new_coeffs[i] = *coeff;
}
IntPoly {
n: coeffs.len() as u16,
coeffs: new_coeffs,
}
}
/// Create a new random IntPoly
pub fn rand(n: u16, pow2q: u16, rand_ctx: &RandContext) -> IntPoly {
let rand_data = rand_ctx.get_rng().generate(n * 2, rand_ctx).unwrap();
let mut coeffs = [0i16; INT_POLY_SIZE];
let shift = 16 - pow2q;
for i in (n as usize)..0usize {
coeffs[i] = rand_data[i] as i16 >> shift;
}
IntPoly {
n: n,
coeffs: coeffs,
}
}
/// Convert array to IntPoly
pub fn from_arr(arr: &[u8], n: u16, q: u16) -> IntPoly {
let mut p: IntPoly = Default::default();
unsafe { ffi::ntru_from_arr(&arr[0], n, q, &mut p) };
p
}
/// Get the coefficients
pub fn get_coeffs(&self) -> &[i16] {
&self.coeffs[0..self.n as usize]
}
/// Set the coefficients
pub fn set_coeffs(&mut self, coeffs: &[i16]) {
self.coeffs = [0; INT_POLY_SIZE];
for (i, coeff) in coeffs.iter().enumerate() {
self.coeffs[i] = *coeff;
}
}
/// Set a coefficient
pub fn set_coeff(&mut self, index: usize, value: i16) {
self.coeffs[index] = value
}
/// Modifies the IntPoly with the given mask
pub fn mod_mask(&mut self, mod_mask: u16) {
unsafe { ffi::ntru_mod_mask(self, mod_mask) };
}
/// Converts the IntPoly to a byte array using 32 bit arithmetic
pub fn to_arr(&self, params: &EncParams) -> Box<[u8]> {
let mut a = vec![0u8; params.enc_len() as usize];
unsafe { ffi::ntru_to_arr(self, params.get_q(), &mut a[0]) };
a.into_boxed_slice()
}
/// General polynomial by ternary polynomial multiplication
///
/// Multiplies a IntPoly by a TernPoly. The number of coefficients must be the same for both
/// polynomials. It also returns if the number of coefficients differ or not.
pub fn mult_tern(&self, b: &TernPoly, mod_mask: u16) -> (IntPoly, bool) {
if self.n != b.n {
panic!("To multiply a IntPoly by a TernPoly the number of coefficients must \
be the same for both polynomials")
}
let mut c: IntPoly = Default::default();
let result = unsafe { ffi::ntru_mult_tern(self, b, &mut c, mod_mask) };
(c, result == 1)
}
/// Add a ternary polynomial
///
/// Adds a ternary polynomial to the general polynomial. Returns a new general polynomial.
pub fn add_tern(&self, b: &TernPoly) -> IntPoly {
IntPoly {
n: self.n,
coeffs: {
let mut coeffs = [0; INT_POLY_SIZE];
let tern_ones = b.get_ones();
let tern_neg_ones = b.get_neg_ones();
for one in tern_ones.iter() {
coeffs[*one as usize] = self.coeffs[*one as usize] + 1;
}
for neg_one in tern_neg_ones.iter() {
coeffs[*neg_one as usize] = self.coeffs[*neg_one as usize] + 1;
}
coeffs
},
}
}
/// General polynomial by product-form polynomial multiplication
///
/// Multiplies a IntPoly by a ProdPoly. The number of coefficients must be the same for both
/// polynomials. It also returns if the number of coefficients differ or not.
pub fn mult_prod(&self, b: &ProdPoly, mod_mask: u16) -> (IntPoly, bool) {
if self.n != b.n {
panic!("To multiply a IntPoly by a ProdPoly the number of coefficients must \
be the same for both polynomials")
}
let mut c: IntPoly = Default::default();
let result = unsafe { ffi::ntru_mult_prod(self, b, &mut c, mod_mask) };
(c, result == 1)
}
/// General polynomial by private polynomial multiplication
///
/// Multiplies a IntPoly by a PrivPoly, i.e. a TernPoly or a ProdPoly. The number of
/// coefficients must be the same for both polynomials. It also returns if the number of
/// coefficients differ or not.
pub fn mult_priv(&self, b: &PrivPoly, mod_mask: u16) -> (IntPoly, bool) {
if (b.is_product() && self.n != b.get_poly_prod().n) ||
(!b.is_product() && self.n != b.get_poly_tern().n) {
panic!("To multiply a IntPoly by a ProdPoly the number of coefficients must \
be the same for both polynomials")
}
let mut c: IntPoly = Default::default();
let result = unsafe { ffi::ntru_mult_priv(b, self, &mut c, mod_mask) };
(c, result == 1)
}
/// General polynomial by general polynomial multiplication
///
/// Multiplies a IntPoly by another IntPoly, i.e. a TernPoly or a ProdPoly. The number of
/// coefficients must be the same for both polynomials. It also returns if the number of
/// coefficients differ or not.
pub fn mult_int(&self, b: &IntPoly, mod_mask: u16) -> (IntPoly, bool) {
let mut c: IntPoly = Default::default();
let result = unsafe { ffi::ntru_mult_int(self, b, &mut c, mod_mask) };
(c, result == 1)
}
/// Multiply by factor
pub fn mult_fac(&mut self, factor: i16) {
unsafe { ffi::ntru_mult_fac(self, factor) };
}
/// Calls `ntru_mod_center()` in this polinomial.
pub fn mod_center(&mut self, modulus: u16) {
unsafe { ffi::ntru_mod_center(self, modulus) };
}
/// Calls `ntru_mod3()` in this polinomial.
pub fn mod3(&mut self) {
unsafe { ffi::ntru_mod3(self) };
}
/// Check if both polynomials are equals given a modulus
pub fn equals_mod(&self, other: &IntPoly, modulus: u16) -> bool {
self.n == other.n &&
{
for i in 0..self.n as usize {
if (self.coeffs[i] - other.coeffs[i]) as i32 % modulus as i32 != 0 {
return false;
}
}
true
}
}
/// Check if the IntPoly equals 1
pub fn equals1(&self) -> bool {
for i in 1..self.n {
if self.coeffs[i as usize] != 0 {
return false;
}
}
self.coeffs[0] == 1
}
}
#[repr(C)]
/// A ternary polynomial, i.e. all coefficients are equal to -1, 0, or 1.
pub struct TernPoly {
n: uint16_t,
num_ones: uint16_t,
num_neg_ones: uint16_t,
ones: [uint16_t; MAX_ONES],
neg_ones: [uint16_t; MAX_ONES],
}
impl Default for TernPoly {
fn default() -> TernPoly {
TernPoly {
n: 0,
num_ones: 0,
num_neg_ones: 0,
ones: [0; MAX_ONES],
neg_ones: [0; MAX_ONES],
}
}
}
impl Clone for TernPoly {
fn clone(&self) -> TernPoly {
let mut new_ones = [0u16; MAX_ONES];
new_ones.clone_from_slice(&self.ones);
let mut new_neg_ones = [0u16; MAX_ONES];
new_neg_ones.clone_from_slice(&self.neg_ones);
TernPoly {
n: self.n,
num_ones: self.num_ones,
num_neg_ones: self.num_neg_ones,
ones: new_ones,
neg_ones: new_neg_ones,
}
}
}
impl fmt::Debug for TernPoly {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f,
"{{ n: {}, num_ones: {}, num_neg_ones: {}, ones: [{}...{}], neg_ones: [{}...{}] }}",
self.n,
self.num_ones,
self.num_neg_ones,
self.ones[0],
self.ones[MAX_ONES - 1],
self.neg_ones[0],
self.neg_ones[MAX_ONES - 1])
}
}
impl PartialEq for TernPoly {
fn eq(&self, other: &TernPoly) -> bool {
self.n == other.n && self.num_ones == other.num_ones &&
self.num_neg_ones == other.num_neg_ones &&
{
for i in 0..MAX_ONES {
if self.ones[i] != other.ones[i] {
return false;
}
if self.neg_ones[i] != other.neg_ones[i] {
return false;
}
}
true
}
}
}
impl TernPoly {
/// Creates a new TernPoly
pub fn new(n: u16, ones: &[u16], neg_ones: &[u16]) -> TernPoly {
let mut new_ones = [0; MAX_ONES];
let mut new_neg_ones = [0; MAX_ONES];
for (i, one) in ones.iter().enumerate() {
new_ones[i] = *one;
}
for (i, neg_one) in neg_ones.iter().enumerate() {
new_neg_ones[i] = *neg_one;
}
TernPoly {
n: n,
num_ones: ones.len() as u16,
num_neg_ones: neg_ones.len() as u16,
ones: new_ones,
neg_ones: new_neg_ones,
}
}
/// Get the
pub fn get_n(&self) -> u16 {
self.n
}
/// Get +1 coefficients
pub fn get_ones(&self) -> &[u16] {
&self.ones[0..self.num_ones as usize]
}
/// Get -1 coefficients
pub fn get_neg_ones(&self) -> &[u16] {
&self.neg_ones[0..self.num_neg_ones as usize]
}
/// Ternary to general integer polynomial
///
/// Converts a TernPoly to an equivalent IntPoly.
pub fn to_int_poly(&self) -> IntPoly {
IntPoly {
n: self.n,
coeffs: {
let mut coeffs = [0; INT_POLY_SIZE];
for i in 0..self.num_ones {
coeffs[self.ones[i as usize] as usize] = 1;
}
for i in 0..self.num_neg_ones {
coeffs[self.neg_ones[i as usize] as usize] = -1;
}
coeffs
},
}
}
}
#[repr(C)]
#[derive(Debug, PartialEq, Clone)]
/// A product-form polynomial, i.e. a polynomial of the form f1*f2+f3 where f1,f2,f3 are very
/// sparsely populated ternary polynomials.
pub struct ProdPoly {
n: uint16_t,
f1: TernPoly,
f2: TernPoly,
f3: TernPoly,
}
impl Default for ProdPoly {
fn default() -> ProdPoly {
ProdPoly {
n: 0,
f1: Default::default(),
f2: Default::default(),
f3: Default::default(),
}
}
}
impl ProdPoly {
/// Creates a new `ProdPoly` from three `TernPoly`s
pub fn new(n: u16, f1: TernPoly, f2: TernPoly, f3: TernPoly) -> ProdPoly {
ProdPoly {
n: n,
f1: f1,
f2: f2,
f3: f3,
}
}
/// Random product-form polynomial
///
/// Generates a random product-form polynomial consisting of 3 random ternary polynomials.
/// Parameters:
///
/// * *N*: the number of coefficients, must be MAX_DEGREE or less
/// * *df1*: number of ones and negative ones in the first ternary polynomial
/// * *df2*: number of ones and negative ones in the second ternary polynomial
/// * *df3_ones*: number of ones ones in the third ternary polynomial
/// * *df3_neg_ones*: number of negative ones in the third ternary polynomial
/// * *rand_ctx*: a random number generator
pub fn rand(n: u16,
df1: u16,
df2: u16,
df3_ones: u16,
df3_neg_ones: u16,
rand_ctx: &RandContext)
-> Option<ProdPoly> {
let f1 = TernPoly::rand(n, df1, df1, rand_ctx);
if f1.is_none() {
return None;
}
let f1 = f1.unwrap();
let f2 = TernPoly::rand(n, df2, df2, rand_ctx);
if f2.is_none() {
return None;
}
let f2 = f2.unwrap();
let f3 = TernPoly::rand(n, df3_ones, df3_neg_ones, rand_ctx);
if f3.is_none() {
return None;
}
let f3 = f3.unwrap();
Some(ProdPoly::new(n, f1, f2, f3))
}
/// Returns an IntPoly equivalent to the ProdPoly
pub fn to_int_poly(&self, modulus: u16) -> IntPoly {
let c = IntPoly {
n: self.n,
coeffs: [0; INT_POLY_SIZE],
};
let mod_mask = modulus - 1;
let (c, _) = c.mult_tern(&self.f2, mod_mask);
c.add_tern(&self.f3)
}
}
/// The size of the union in 16 bit words
const PRIVUNION_SIZE: usize = 3004;
#[repr(C)]
/// Union for the private key polynomial
struct PrivUnion {
/// The union data as a 2-byte array
data: [uint16_t; PRIVUNION_SIZE],
}
impl Default for PrivUnion {
fn default() -> PrivUnion {
PrivUnion { data: [0; PRIVUNION_SIZE] }
}
}
impl Clone for PrivUnion {
fn clone(&self) -> PrivUnion {
let mut new_data = [0u16; PRIVUNION_SIZE];
for (i, data) in self.data.iter().enumerate() {
new_data[i] = *data
}
PrivUnion { data: new_data }
}
}
impl PrivUnion {
/// Create a new union from a ProdPoly
unsafe fn new_from_prod(poly: ProdPoly) -> PrivUnion {
let arr: &[uint16_t; 3004] = mem::transmute(&poly);
let mut data = [0; PRIVUNION_SIZE];
for (i, b) in arr.iter().enumerate() {
data[i] = *b;
}
PrivUnion { data: data }
}
/// Create a new union from a TernPoly
unsafe fn new_from_tern(poly: TernPoly) -> PrivUnion {
let arr: &[uint16_t; 1001] = mem::transmute(&poly);
let mut data = [0; PRIVUNION_SIZE];
for (i, b) in arr.iter().enumerate() {
data[i] = *b;
}
PrivUnion { data: data }
}
/// Get the union as a ProdPoly
unsafe fn prod(&self) -> &ProdPoly {
mem::transmute(&self.data)
}
/// Get the union as a TernPoly
unsafe fn tern(&self) -> &TernPoly {
mem::transmute(&self.data)
}
}
#[repr(C)]
#[derive(Clone)]
/// Private polynomial, can be ternary or product-form
pub struct PrivPoly {
// maybe we could do conditional compilation?
/// Whether the polynomial is in product form
prod_flag: uint8_t,
poly: PrivUnion,
}
impl Default for PrivPoly {
fn default() -> PrivPoly {
PrivPoly {
prod_flag: 0,
poly: Default::default(),
}
}
}
impl fmt::Debug for PrivPoly {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.is_product() {
write!(f, "PrivPoly {{ prod_poly: {:?} }}", self.get_poly_prod())
} else {
write!(f, "PrivPoly {{ tern_poly: {:?} }}", self.get_poly_tern())
}
}
}
impl PartialEq for PrivPoly {
fn eq(&self, other: &PrivPoly) -> bool {
self.prod_flag == other.prod_flag &&
{
if self.prod_flag > 0 {
self.get_poly_prod() == other.get_poly_prod()
} else {
self.get_poly_tern() == other.get_poly_tern()
}
}
}
}
impl PrivPoly {
/// Create a new PrivPoly with a ProdPoly
pub fn new_with_prod_poly(poly: ProdPoly) -> PrivPoly {
PrivPoly {
prod_flag: 1,
poly: unsafe { PrivUnion::new_from_prod(poly) },
}
}
/// Create a new PrivPoly with a TernPoly
pub fn new_with_tern_poly(poly: TernPoly) -> PrivPoly {
PrivPoly {
prod_flag: 0,
poly: unsafe { PrivUnion::new_from_tern(poly) },
}
}
/// If the PrivPoly contains a ProdPoly
pub fn is_product(&self) -> bool {
self.prod_flag == 1
}
/// Get the ProdPoly of the union
///
/// Panics if the union is actually a TernPoly
pub fn get_poly_prod(&self) -> &ProdPoly {
if self.prod_flag != 1 {
panic!("Trying to get PrivPoly from an union that is TernPoly.");
}
unsafe { &*self.poly.prod() }
}
/// Get the TernPoly of the union
///
/// Panics if the union is actually a ProdPoly
pub fn get_poly_tern(&self) -> &TernPoly {
if self.prod_flag != 0 {
panic!("Trying to get TernPoly from an union that is ProdPoly.");
}
unsafe { &*self.poly.tern() }
}
/// Inverse modulo q
///
/// Computes the inverse of 1+3a mod q; q must be a power of 2. It also returns if the
/// polynomial is invertible.
///
/// The algorithm is described in "Almost Inverses and Fast NTRU Key Generation" at
/// http://www.securityinnovation.com/uploads/Crypto/NTRUTech014.pdf
pub fn invert(&self, mod_mask: u16) -> (IntPoly, bool) {
let mut fq: IntPoly = Default::default();
let result = unsafe { ffi::ntru_invert(self, mod_mask, &mut fq) };
(fq, result == 1)
}
}
#[repr(C)]
#[derive(Debug, PartialEq, Clone)]
/// NTRU encryption private key
pub struct PrivateKey {
q: uint16_t,
t: PrivPoly,
}
impl Default for PrivateKey {
fn default() -> PrivateKey {
PrivateKey {
q: 0,
t: Default::default(),
}
}
}
impl PrivateKey {
/// Gets the q parameter of the PrivateKey
pub fn get_q(&self) -> u16 {
self.q
}
/// Gets the tparameter of the PrivateKey
pub fn get_t(&self) -> &PrivPoly {
&self.t
}
/// Get params from the private key
pub fn get_params(&self) -> Result<EncParams, Error> {
let mut params: EncParams = Default::default();
let result = unsafe { ffi::ntru_params_from_priv_key(self, &mut params) };
if result == 0 {
Ok(params)
} else {
Err(Error::from(result))
}
}
/// Import private key
pub fn import(arr: &[u8]) -> PrivateKey {
let mut key: PrivateKey = Default::default();
unsafe { ffi::ntru_import_priv(&arr[0], &mut key) };
key
}
/// Export private key
pub fn export(&self, params: &EncParams) -> Box<[u8]> {
let mut arr = vec![0u8; params.private_len() as usize];
let _ = unsafe { ffi::ntru_export_priv(self, &mut arr[..][0]) };
arr.into_boxed_slice()
}
}
#[repr(C)]
#[derive(Debug, PartialEq, Clone)]
/// NTRU encryption public key
pub struct PublicKey {
q: uint16_t,
h: IntPoly,
}
impl Default for PublicKey {
fn default() -> PublicKey {
PublicKey {
q: 0,
h: Default::default(),
}
}
}
impl PublicKey {
/// Get the q parameter of the PublicKey
pub fn get_q(&self) -> u16 {
self.q
}
/// Get the h parameter of the PublicKey
pub fn get_h(&self) -> &IntPoly {
&self.h
}
/// Import a public key
pub fn import(arr: &[u8]) -> PublicKey {
let mut key: PublicKey = Default::default();
let _ = unsafe { ffi::ntru_import_pub(&arr[0], &mut key) };
key
}
/// Export public key
pub fn export(&self, params: &EncParams) -> Box<[u8]> {
let mut arr = vec![0u8; params.public_len() as usize];
unsafe { ffi::ntru_export_pub(self, &mut arr[..][0]) };
arr.into_boxed_slice()
}
}
#[repr(C)]
#[derive(Debug, PartialEq, Clone)]
/// NTRU encryption key pair
pub struct KeyPair {
/// Private key
private: PrivateKey,
/// Public key
public: PublicKey,
}
impl Default for KeyPair {
fn default() -> KeyPair {
KeyPair {
private: Default::default(),
public: Default::default(),
}
}
}
impl KeyPair {
/// Generate a new key pair
pub fn new(private: PrivateKey, public: PublicKey) -> KeyPair {
KeyPair {
private: private,
public: public,
}
}
/// Get params from the key pair
pub fn get_params(&self) -> Result<EncParams, Error> {
self.private.get_params()
}
/// The private key
pub fn get_private(&self) -> &PrivateKey {
&self.private
}
/// The public key
pub fn get_public(&self) -> &PublicKey {
&self.public
}
}
/// The error enum
#[derive(Debug, PartialEq, Clone, Copy)]
pub enum Error {
/// Out of memory error.
OutOfMemory,
/// Error in the random number generator.
Prng,
/// Message is too long.
MessageTooLong,
/// Invalid maximum length.
InvalidMaxLength,
/// MD0 violation.
Md0Violation,
/// No zero pad.
NoZeroPad,
/// Invalid encoding of the message.
InvalidEncoding,
/// Null argument.
NullArgument,
/// Unknown parameter set.
UnknownParamSet,
/// Invalid parameter.
InvalidParam,
/// Invalid key.
InvalidKey,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", self)
}
}
impl From<uint8_t> for Error {
fn from(error: uint8_t) -> Error {
match error {
1 => Error::OutOfMemory,
2 => Error::Prng,
3 => Error::MessageTooLong,
4 => Error::InvalidMaxLength,
5 => Error::Md0Violation,
6 => Error::NoZeroPad,
7 => Error::InvalidEncoding,
8 => Error::NullArgument,
9 => Error::UnknownParamSet,
10 => Error::InvalidParam,
11 => Error::InvalidKey,
_ => unreachable!(),
}
}
}
impl error::Error for Error {
fn description(&self) -> &str {
match *self {
Error::OutOfMemory => "Out of memory error.",
Error::Prng => "Error in the random number generator.",
Error::MessageTooLong => "Message is too long.",
Error::InvalidMaxLength => "Invalid maximum length.",
Error::Md0Violation => "MD0 violation.",
Error::NoZeroPad => "No zero pad.",
Error::InvalidEncoding => "Invalid encoding of the message.",
Error::NullArgument => "Null argument.",
Error::UnknownParamSet => "Unknown parameter set.",
Error::InvalidParam => "Invalid parameter.",
Error::InvalidKey => "Invalid key.",
}
}
}<|fim▁end|>
|
impl PartialEq for IntPoly {
fn eq(&self, other: &IntPoly) -> bool {
self.n == other.n &&
|
<|file_name|>sample_oscillator.js<|end_file_name|><|fim▁begin|>import {Sample} from './sample'
import {context} from './init_audio'
let instanceIndex = 0
export class SampleOscillator extends Sample{
constructor(sampleData, event){
super(sampleData, event)
this.id = `${this.constructor.name}_${instanceIndex++}_${new Date().getTime()}`
if(this.sampleData === -1){
// create dummy source
this.source = {
start(){},
stop(){},
connect(){},
}
}else{
<|fim▁hole|>
switch(type){
case 'sine':
case 'square':
case 'sawtooth':
case 'triangle':
this.source.type = type
break
default:
this.source.type = 'square'
}
this.source.frequency.value = event.frequency
}
this.output = context.createGain()
this.volume = event.data2 / 127
this.output.gain.value = this.volume
this.source.connect(this.output)
//this.output.connect(context.destination)
}
}<|fim▁end|>
|
// @TODO add type 'custom' => PeriodicWave
let type = this.sampleData.type
this.source = context.createOscillator()
|
<|file_name|>test_subclass.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
# TEST_UNICODE_LITERALS
from ... import table
from .. import pprint
class MyRow(table.Row):
def __str__(self):<|fim▁hole|> pass
class MyMaskedColumn(table.MaskedColumn):
pass
class MyTableColumns(table.TableColumns):
pass
class MyTableFormatter(pprint.TableFormatter):
pass
class MyTable(table.Table):
Row = MyRow
Column = MyColumn
MaskedColumn = MyMaskedColumn
TableColumns = MyTableColumns
TableFormatter = MyTableFormatter
def test_simple_subclass():
t = MyTable([[1, 2], [3, 4]])
row = t[0]
assert isinstance(row, MyRow)
assert isinstance(t['col0'], MyColumn)
assert isinstance(t.columns, MyTableColumns)
assert isinstance(t.formatter, MyTableFormatter)
t2 = MyTable(t)
row = t2[0]
assert isinstance(row, MyRow)
assert str(row) == '(1, 3)'
t3 = table.Table(t)
row = t3[0]
assert not isinstance(row, MyRow)
assert str(row) != '(1, 3)'
t = MyTable([[1, 2], [3, 4]], masked=True)
row = t[0]
assert isinstance(row, MyRow)
assert str(row) == '(1, 3)'
assert isinstance(t['col0'], MyMaskedColumn)
assert isinstance(t.formatter, MyTableFormatter)
class ParamsRow(table.Row):
"""
Row class that allows access to an arbitrary dict of parameters
stored as a dict object in the ``params`` column.
"""
def __getitem__(self, item):
if item not in self.colnames:
return super(ParamsRow, self).__getitem__('params')[item]
else:
return super(ParamsRow, self).__getitem__(item)
def keys(self):
out = [name for name in self.colnames if name != 'params']
params = [key.lower() for key in sorted(self['params'])]
return out + params
def values(self):
return [self[key] for key in self.keys()]
class ParamsTable(table.Table):
Row = ParamsRow
def test_params_table():
t = ParamsTable(names=['a', 'b', 'params'], dtype=['i', 'f', 'O'])
t.add_row((1, 2.0, {'x': 1.5, 'y': 2.5}))
t.add_row((2, 3.0, {'z': 'hello', 'id': 123123}))
assert t['params'][0] == {'x': 1.5, 'y': 2.5}
assert t[0]['params'] == {'x': 1.5, 'y': 2.5}
assert t[0]['y'] == 2.5
assert t[1]['id'] == 123123
assert list(t[1].keys()) == ['a', 'b', 'id', 'z']
assert list(t[1].values()) == [2, 3.0, 123123, 'hello']<|fim▁end|>
|
return str(self.as_void())
class MyColumn(table.Column):
|
<|file_name|>EventDecorator.java<|end_file_name|><|fim▁begin|>package cn.libery.calendar.MaterialCalendar;
import android.content.Context;
import java.util.Collection;
import java.util.HashSet;
import cn.libery.calendar.MaterialCalendar.spans.DotSpan;
/**
* Decorate several days with a dot
*/
public class EventDecorator implements DayViewDecorator {
private int color;<|fim▁hole|> this.dates = new HashSet<>(dates);
}
@Override
public boolean shouldDecorate(CalendarDay day) {
return dates.contains(day);
}
@Override
public void decorate(DayViewFacade view, Context context) {
view.addSpan(new DotSpan(4, color));
}
}<|fim▁end|>
|
private HashSet<CalendarDay> dates;
public EventDecorator(int color, Collection<CalendarDay> dates) {
this.color = color;
|
<|file_name|>posv.hpp<|end_file_name|><|fim▁begin|>/*
*
* Copyright (c) Toon Knapen & Kresimir Fresl 2003
*
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*
* KF acknowledges the support of the Faculty of Civil Engineering,
* University of Zagreb, Croatia.
*
*/
#ifndef BOOST_NUMERIC_BINDINGS_LAPACK_POSV_HPP<|fim▁hole|>#include <boost/numeric/bindings/traits/traits.hpp>
#include <boost/numeric/bindings/lapack/lapack.h>
#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK
# include <boost/numeric/bindings/traits/detail/symm_herm_traits.hpp>
# include <boost/static_assert.hpp>
# include <boost/type_traits/is_same.hpp>
#endif
#include <cassert>
namespace boost { namespace numeric { namespace bindings {
namespace lapack {
/////////////////////////////////////////////////////////////////////
//
// system of linear equations A * X = B
// with A symmetric or Hermitian positive definite matrix
//
/////////////////////////////////////////////////////////////////////
/*
* posv() computes the solution to a system of linear equations
* A * X = B, where A is an N-by-N symmetric or Hermitian positive
* definite matrix and X and B are N-by-NRHS matrices.
*
* The Cholesky decomposition is used to factor A as
* A = U^T * U or A = U^H * U, if UPLO = 'U',
* A = L * L^T or A = L * L^H, if UPLO = 'L',
* where U is an upper triangular matrix and L is a lower triangular
* matrix. The factored form of A is then used to solve the system of
* equations A * X = B.
*
* If UPLO = 'U', the leading N-by-N upper triangular part of A
* contains the upper triangular part of the matrix A, and the
* strictly lower triangular part of A is not referenced.
* If UPLO = 'L', the leading N-by-N lower triangular part of A
* contains the lower triangular part of the matrix A, and the
* strictly upper triangular part of A is not referenced.
*/
namespace detail {
inline
void posv (char const uplo, int const n, int const nrhs,
float* a, int const lda,
float* b, int const ldb, int* info)
{
LAPACK_SPOSV (&uplo, &n, &nrhs, a, &lda, b, &ldb, info);
}
inline
void posv (char const uplo, int const n, int const nrhs,
double* a, int const lda,
double* b, int const ldb, int* info)
{
LAPACK_DPOSV (&uplo, &n, &nrhs, a, &lda, b, &ldb, info);
}
inline
void posv (char const uplo, int const n, int const nrhs,
traits::complex_f* a, int const lda,
traits::complex_f* b, int const ldb, int* info)
{
LAPACK_CPOSV (&uplo, &n, &nrhs,
traits::complex_ptr (a), &lda,
traits::complex_ptr (b), &ldb, info);
}
inline
void posv (char const uplo, int const n, int const nrhs,
traits::complex_d* a, int const lda,
traits::complex_d* b, int const ldb, int* info)
{
LAPACK_ZPOSV (&uplo, &n, &nrhs,
traits::complex_ptr (a), &lda,
traits::complex_ptr (b), &ldb, info);
}
template <typename SymmMatrA, typename MatrB>
inline
int posv (char const uplo, SymmMatrA& a, MatrB& b) {
int const n = traits::matrix_size1 (a);
assert (n == traits::matrix_size2 (a));
assert (n == traits::matrix_size1 (b));
int info;
posv (uplo, n, traits::matrix_size2 (b),
traits::matrix_storage (a),
traits::leading_dimension (a),
traits::matrix_storage (b),
traits::leading_dimension (b),
&info);
return info;
}
}
template <typename SymmMatrA, typename MatrB>
inline
int posv (char const uplo, SymmMatrA& a, MatrB& b) {
assert (uplo == 'U' || uplo == 'L');
#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK
BOOST_STATIC_ASSERT((boost::is_same<
typename traits::matrix_traits<SymmMatrA>::matrix_structure,
traits::general_t
>::value));
BOOST_STATIC_ASSERT((boost::is_same<
typename traits::matrix_traits<MatrB>::matrix_structure,
traits::general_t
>::value));
#endif
return detail::posv (uplo, a, b);
}
template <typename SymmMatrA, typename MatrB>
inline
int posv (SymmMatrA& a, MatrB& b) {
#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK
typedef traits::matrix_traits<SymmMatrA> matraits;
typedef typename matraits::value_type val_t;
BOOST_STATIC_ASSERT( (traits::detail::symm_herm_compatible< val_t, typename matraits::matrix_structure >::value ) ) ;
BOOST_STATIC_ASSERT((boost::is_same<
typename traits::matrix_traits<MatrB>::matrix_structure,
traits::general_t
>::value));
#endif
char uplo = traits::matrix_uplo_tag (a);
return detail::posv (uplo, a, b);
}
/*
* potrf() computes the Cholesky factorization of a symmetric
* or Hermitian positive definite matrix A. The factorization has
* the form
* A = U^T * U or A = U^H * U, if UPLO = 'U',
* A = L * L^T or A = L * L^H, if UPLO = 'L',
* where U is an upper triangular matrix and L is lower triangular.
*/
namespace detail {
inline
void potrf (char const uplo, int const n,
float* a, int const lda, int* info)
{
LAPACK_SPOTRF (&uplo, &n, a, &lda, info);
}
inline
void potrf (char const uplo, int const n,
double* a, int const lda, int* info)
{
LAPACK_DPOTRF (&uplo, &n, a, &lda, info);
}
inline
void potrf (char const uplo, int const n,
traits::complex_f* a, int const lda, int* info)
{
LAPACK_CPOTRF (&uplo, &n, traits::complex_ptr (a), &lda, info);
}
inline
void potrf (char const uplo, int const n,
traits::complex_d* a, int const lda, int* info)
{
LAPACK_ZPOTRF (&uplo, &n, traits::complex_ptr (a), &lda, info);
}
template <typename SymmMatrA>
inline
int potrf (char const uplo, SymmMatrA& a) {
int const n = traits::matrix_size1 (a);
assert (n == traits::matrix_size2 (a));
int info;
potrf (uplo, n, traits::matrix_storage (a),
traits::leading_dimension (a), &info);
return info;
}
}
template <typename SymmMatrA>
inline
int potrf (char const uplo, SymmMatrA& a) {
assert (uplo == 'U' || uplo == 'L');
#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK
BOOST_STATIC_ASSERT((boost::is_same<
typename traits::matrix_traits<SymmMatrA>::matrix_structure,
traits::general_t
>::value));
#endif
return detail::potrf (uplo, a);
}
template <typename SymmMatrA>
inline
int potrf (SymmMatrA& a) {
#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK
typedef traits::matrix_traits<SymmMatrA> matraits;
typedef typename matraits::value_type val_t;
BOOST_STATIC_ASSERT((boost::is_same<
typename matraits::matrix_structure,
typename traits::detail::symm_herm_t<val_t>::type
>::value));
#endif
char uplo = traits::matrix_uplo_tag (a);
return detail::potrf (uplo, a);
}
/*
* potrs() solves a system of linear equations A*X = B with
* a symmetric or Hermitian positive definite matrix A using
* the Cholesky factorization computed by potrf().
*/
namespace detail {
inline
void potrs (char const uplo, int const n, int const nrhs,
float const* a, int const lda,
float* b, int const ldb, int* info)
{
LAPACK_SPOTRS (&uplo, &n, &nrhs, a, &lda, b, &ldb, info);
}
inline
void potrs (char const uplo, int const n, int const nrhs,
double const* a, int const lda,
double* b, int const ldb, int* info)
{
LAPACK_DPOTRS (&uplo, &n, &nrhs, a, &lda, b, &ldb, info);
}
inline
void potrs (char const uplo, int const n, int const nrhs,
traits::complex_f const* a, int const lda,
traits::complex_f* b, int const ldb, int* info)
{
LAPACK_CPOTRS (&uplo, &n, &nrhs,
traits::complex_ptr (a), &lda,
traits::complex_ptr (b), &ldb, info);
}
inline
void potrs (char const uplo, int const n, int const nrhs,
traits::complex_d const* a, int const lda,
traits::complex_d* b, int const ldb, int* info)
{
LAPACK_ZPOTRS (&uplo, &n, &nrhs,
traits::complex_ptr (a), &lda,
traits::complex_ptr (b), &ldb, info);
}
template <typename SymmMatrA, typename MatrB>
inline
int potrs (char const uplo, SymmMatrA const& a, MatrB& b) {
int const n = traits::matrix_size1 (a);
assert (n == traits::matrix_size2 (a));
assert (n == traits::matrix_size1 (b));
int info;
potrs (uplo, n, traits::matrix_size2 (b),
#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING
traits::matrix_storage (a),
#else
traits::matrix_storage_const (a),
#endif
traits::leading_dimension (a),
traits::matrix_storage (b),
traits::leading_dimension (b),
&info);
return info;
}
}
template <typename SymmMatrA, typename MatrB>
inline
int potrs (char const uplo, SymmMatrA const& a, MatrB& b) {
assert (uplo == 'U' || uplo == 'L');
#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK
BOOST_STATIC_ASSERT((boost::is_same<
typename traits::matrix_traits<SymmMatrA>::matrix_structure,
traits::general_t
>::value));
BOOST_STATIC_ASSERT((boost::is_same<
typename traits::matrix_traits<MatrB>::matrix_structure,
traits::general_t
>::value));
#endif
return detail::potrs (uplo, a, b);
}
template <typename SymmMatrA, typename MatrB>
inline
int potrs (SymmMatrA const& a, MatrB& b) {
#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK
typedef traits::matrix_traits<SymmMatrA> matraits;
typedef traits::matrix_traits<MatrB> mbtraits;
typedef typename matraits::value_type val_t;
BOOST_STATIC_ASSERT((boost::is_same<
typename matraits::matrix_structure,
typename traits::detail::symm_herm_t<val_t>::type
>::value));
BOOST_STATIC_ASSERT((boost::is_same<
typename mbtraits::matrix_structure, traits::general_t
>::value));
#endif
char uplo = traits::matrix_uplo_tag (a);
return detail::potrs (uplo, a, b);
}
// TO DO: potri()
}
}}}
#endif<|fim▁end|>
|
#define BOOST_NUMERIC_BINDINGS_LAPACK_POSV_HPP
#include <boost/numeric/bindings/traits/type_traits.hpp>
|
<|file_name|>af.js<|end_file_name|><|fim▁begin|>/*
Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'save', 'af', {
toolbar: 'Bewaar'<|fim▁hole|><|fim▁end|>
|
} );
|
<|file_name|>Benchmark.cpp<|end_file_name|><|fim▁begin|>#include <vector>
#include <iostream>
struct point
{
double x;
double y;
};
int main()
{
// Generate a lot of uniformly distributed 2d points in the range -1,-1 to +1,+1.
enum { numXSamples = 10000 };
enum { numYSamples = 10000 };
std::vector<point> points;
points.reserve(numXSamples * numYSamples);
for(int x = 0;x < numXSamples;++x)
{
for(int y = 0;y < numXSamples;++y)
{
point p = {-1.0 + 2.0 * x / (numXSamples-1),-1.0 + 2.0 * y / (numYSamples-1)};<|fim▁hole|>
// Count the ratio of points inside the unit circle.
int numerator = 0;
int denominator = 0;
for(auto pointIt = points.begin();pointIt != points.end();++pointIt)
{
if(pointIt->x * pointIt->x + pointIt->y * pointIt->y < 1.0)
{
++numerator;
}
++denominator;
}
// Derive the area of the unit circle.
auto circleArea = 4.0 * (double)numerator / denominator;
std::cout << "result: " << circleArea << std::endl;
return 0;
}<|fim▁end|>
|
points.push_back(p);
}
}
|
<|file_name|>commit.py<|end_file_name|><|fim▁begin|>import os
# This function only READS the Commit info.
# There is no point in loading any commit in memory.
# What purpose can that serve? Nothing. (Prove this)
def load(cls, name, path):
try:
with open(path, 'rb') as commit_info_file:
commit_info_dict = pickle.load(commit_info_file.read())
return commit_info_dict
except FileNotFoundError:
print("Could not find commit-info here:\n`%s`" % path)
sys.exit(1)
# This object hold only some info about a SINGLE Commit
class Commit:
def __init__(self, parent, branch, message, repo):
self.message = message
self.hash = self.make_hash()
# self.repo.dstore.get_commits_by_branch(branch)
# make changes to tree<|fim▁hole|>
def make_hash(self):
return "yash uuid"<|fim▁end|>
|
# save
# make chages to main tree?
# exit
|
<|file_name|>_arrowcolor.py<|end_file_name|><|fim▁begin|>import _plotly_utils.basevalidators
class ArrowcolorValidator(_plotly_utils.basevalidators.ColorValidator):
def __init__(
self, plotly_name="arrowcolor", parent_name="layout.annotation", **kwargs
):<|fim▁hole|> plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "arraydraw"),
role=kwargs.pop("role", "style"),
**kwargs
)<|fim▁end|>
|
super(ArrowcolorValidator, self).__init__(
|
<|file_name|>Texts.java<|end_file_name|><|fim▁begin|>/*
* This file is part of SpongeAPI, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.api.text;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.collect.ImmutableList;
import org.spongepowered.api.scoreboard.Score;
import org.spongepowered.api.text.format.TextColor;
import org.spongepowered.api.text.format.TextColors;
import org.spongepowered.api.text.format.TextStyle;
import org.spongepowered.api.text.format.TextStyles;
import org.spongepowered.api.text.selector.Selector;
import org.spongepowered.api.text.translation.Translatable;
import org.spongepowered.api.text.translation.Translation;
import java.util.Locale;
/**
* Utility class to work with and create {@link Text}.
*/
public final class Texts {
private static final TextFactory factory = null;
static final Text.Literal EMPTY = new Text.Literal();
private Texts() {
}
/**
* Returns an empty, unformatted {@link Text} instance.
*
* @return An empty text
*/
public static Text of() {
return EMPTY;
}
/**
* Creates a {@link Text} with the specified plain text. The created message
* won't have any formatting or events configured.
*
* @param content The content of the text
* @return The created text
* @see Text.Literal
*/
public static Text.Literal of(String content) {
if (checkNotNull(content, "content").isEmpty()) {
return EMPTY;
}
return new Text.Literal(content);
}
/**
* Creates a new unformatted {@link Text.Translatable} with the given
* {@link Translation} and arguments.
*
* @param translation The translation for the text
* @param args The arguments for the translation
* @return The created text
* @see Text.Translatable
*/
public static Text.Translatable of(Translation translation, Object... args) {
return new Text.Translatable(translation, ImmutableList.copyOf(checkNotNull(args, "args")));
}
/**
* Creates a new unformatted {@link Text.Translatable} from the given
* {@link Translatable}.
*
* @param translatable The translatable for the text
* @param args The arguments for the translation
* @return The created text
* @see Text.Translatable
*/
public static Text.Translatable of(Translatable translatable, Object... args) {
return of(checkNotNull(translatable, "translatable").getTranslation(), args);
}
/**
* Creates a new unformatted {@link Text.Selector} with the given selector.
*
* @param selector The selector for the text
* @return The created text
* @see Text.Selector
*/
public static Text.Selector of(Selector selector) {
return new Text.Selector(selector);
}
/**
* Creates a new unformatted {@link Text.Score} with the given score.
*
* @param score The score for the text
* @return The created text
* @see Text.Score
*/
public static Text.Score of(Score score) {
return new Text.Score(score);
}
/**
* Builds a {@link Text} from a given array of objects.
*
* <p>For instance, you can use this like
* <code>Texts.of(TextColors.DARK_AQUA, "Hi", TextColors.AQUA, "Bye")</code>
* </p>
*
* <p>This will create the correct {@link Text} instance if the input object
* is the input for one of the {@link Text} types or convert the object to a
* string otherwise.</p>
*
* @param objects The object array
* @return The built text object
*/
public static Text of(Object... objects) {
TextBuilder builder = builder();
TextColor color = TextColors.NONE;
TextStyle style = TextStyles.NONE;
for (Object obj : objects) {
if (obj instanceof TextColor) {
color = (TextColor) obj;
} else if (obj instanceof TextStyle) {
style = obj.equals(TextStyles.RESET) ? TextStyles.NONE : style.and((TextStyle) obj);
} else if (obj instanceof Text) {
builder.append((Text) obj);
} else if (obj instanceof TextBuilder) {
builder.append(((TextBuilder) obj).build());
} else {
TextBuilder childBuilder;
if (obj instanceof String) {
childBuilder = Texts.builder((String) obj);
} else if (obj instanceof Translation) {
childBuilder = Texts.builder((Translation) obj);
} else if (obj instanceof Selector) {
childBuilder = Texts.builder((Selector) obj);
} else if (obj instanceof Score) {
childBuilder = Texts.builder((Score) obj);
} else {
childBuilder = Texts.builder(String.valueOf(obj));
}
builder.append(childBuilder.color(color).style(style).build());
}
}
return builder.build();
}
/**
* Creates a {@link TextBuilder} with empty text.
*
* @return A new text builder with empty text
*/
public static TextBuilder builder() {
return new TextBuilder.Literal();
}
/**
* Creates a new unformatted {@link TextBuilder.Literal} with the specified
* content.
*
* @param content The content of the text
* @return The created text builder
* @see Text.Literal
* @see TextBuilder.Literal
*/
public static TextBuilder.Literal builder(String content) {
return new TextBuilder.Literal(content);
}
/**
* Creates a new {@link TextBuilder.Literal} with the formatting and actions
* of the specified {@link Text} and the given content.
*
* @param text The text to apply the properties from
* @param content The content for the text builder
* @return The created text builder
* @see Text.Literal
* @see TextBuilder.Literal
*/
public static TextBuilder.Literal builder(Text text, String content) {
return new TextBuilder.Literal(text, content);
}
/**
* Creates a new unformatted {@link TextBuilder.Translatable} with the given
* {@link Translation} and arguments.
*
* @param translation The translation for the builder
* @param args The arguments for the translation
* @return The created text builder
* @see Text.Translatable
* @see TextBuilder.Translatable
*/
public static TextBuilder.Translatable builder(Translation translation, Object... args) {
return new TextBuilder.Translatable(translation, args);
}
/**
* Creates a new unformatted {@link TextBuilder.Translatable} from the given
* {@link Translatable}.
*
* @param translatable The translatable for the builder
* @param args The arguments for the translation
* @return The created text builder
* @see Text.Translatable
* @see TextBuilder.Translatable
*/
public static TextBuilder.Translatable builder(Translatable translatable, Object... args) {
return new TextBuilder.Translatable(translatable, args);
}
/**
* Creates a new {@link TextBuilder.Translatable} with the formatting and
* actions of the specified {@link Text} and the given {@link Translation}
* and arguments.
*
* @param text The text to apply the properties from
* @param translation The translation for the builder
* @param args The arguments for the translation
* @return The created text builder
* @see Text.Translatable
* @see TextBuilder.Translatable
*/
public static TextBuilder.Translatable builder(Text text, Translation translation, Object... args) {
return new TextBuilder.Translatable(text, translation, args);
}
/**
* Creates a new {@link TextBuilder.Translatable} with the formatting and
* actions of the specified {@link Text} and the given {@link Translatable}.
*
* @param text The text to apply the properties from
* @param translatable The translatable for the builder
* @param args The arguments for the translation
* @return The created text builder
* @see Text.Translatable
* @see TextBuilder.Translatable
*/
public static TextBuilder.Translatable builder(Text text, Translatable translatable, Object... args) {
return new TextBuilder.Translatable(text, translatable, args);
}
/**
* Creates a new unformatted {@link TextBuilder.Selector} with the given
* selector.
*
* @param selector The selector for the builder
* @return The created text builder
* @see Text.Selector
* @see TextBuilder.Selector
*/
public static TextBuilder.Selector builder(Selector selector) {
return new TextBuilder.Selector(selector);
}
/**
* Creates a new {@link TextBuilder.Selector} with the formatting and
* actions of the specified {@link Text} and the given selector.
*
* @param text The text to apply the properties from
* @param selector The selector for the builder
* @return The created text builder
* @see Text.Selector
* @see TextBuilder.Selector
*/
public static TextBuilder.Selector builder(Text text, Selector selector) {
return new TextBuilder.Selector(text, selector);
}
/**
* Creates a new unformatted {@link TextBuilder.Score} with the given score.
*
* @param score The score for the text builder
* @return The created text builder
* @see Text.Score
* @see TextBuilder.Score
*/
public static TextBuilder.Score builder(Score score) {
return new TextBuilder.Score(score);
}
/**
* Creates a new {@link TextBuilder.Score} with the formatting and actions
* of the specified {@link Text} and the given score.
*
* @param text The text to apply the properties from
* @param score The score for the text builder
* @return The created text builder
* @see Text.Score
* @see TextBuilder.Score
*/
public static TextBuilder.Score builder(Text text, Score score) {
return new TextBuilder.Score(text, score);
}
/**
* Joins a sequence of text objects together.
*
* @param texts The texts to join
* @return A text object that joins the given text objects
*/
public static Text join(Text... texts) {
return builder().append(texts).build();
}
/**
* Joins a sequence of text objects together.
*
* @param texts The texts to join
* @return A text object that joins the given text objects
*/
public static Text join(Iterable<? extends Text> texts) {
return builder().append(texts).build();
}
/**
* Joins a sequence of text objects together along with a separator.
*
* @param separator The separator
* @param texts The text to join
* @return A text object that joins the given text objects<|fim▁hole|> return of();
case 1:
return texts[0];
default:
TextBuilder builder = builder();
boolean appendSeparator = false;
for (Text text : texts) {
if (appendSeparator) {
builder.append(separator);
} else {
appendSeparator = true;
}
builder.append(text);
}
return builder.build();
}
}
/**
* Parses the specified JSON text and returns the parsed result.
*
* @param json The valid JSON text
* @return The parsed text
* @throws IllegalArgumentException If the JSON is invalid
*/
public static Text parseJson(String json) throws IllegalArgumentException {
return factory.parseJson(json);
}
/**
* Parses the specified JSON text and returns the parsed result.
*
* <p>Unlike {@link #parseJson(String)} this will ignore some formatting
* errors and parse the JSON data more leniently.</p>
*
* @param json The JSON text
* @return The parsed text
* @throws IllegalArgumentException If the JSON couldn't be parsed
*/
public static Text parseJsonLenient(String json) throws IllegalArgumentException {
return factory.parseJsonLenient(json);
}
/**
* Returns a plain text representation of the {@link Text} without any
* formatting.
*
* @param text The text to convert
* @return The text converted to plain text
*/
public static String toPlain(Text text) {
return factory.toPlain(text);
}
/**
* Returns a JSON representation of the {@link Text} as used in commands.
*
* @param text The text to convert
* @return The text converted to JSON
*/
public static String toJson(Text text) {
return factory.toJson(text);
}
/**
* Returns a plain text representation of the {@link Text} without any
* formatting.
*
* @param text The text to convert
* @return The text converted to plain text
*/
public static String toPlain(Text text, Locale locale) {
return factory.toPlain(text, locale);
}
/**
* Returns a JSON representation of the {@link Text} as used in commands.
*
* @param text The text to convert
* @return The text converted to JSON
*/
public static String toJson(Text text, Locale locale) {
return factory.toJson(text, locale);
}
/**
* Returns the default legacy formatting character.
*
* @return The legacy formatting character
* @deprecated Legacy formatting codes are being phased out of Minecraft
*/
@Deprecated
public static char getLegacyChar() {
return factory.getLegacyChar();
}
/**
* Creates a Message from a legacy string using the default legacy.
*
* @param text The text to be converted as a String
* @return The converted Message
* @deprecated Legacy formatting codes are being phased out of Minecraft
*/
@Deprecated
@SuppressWarnings("deprecation")
public static Text.Literal fromLegacy(String text) {
return fromLegacy(text, getLegacyChar());
}
/**
* Creates a Message from a legacy string, given a color character.
*
* @param text The text to be converted as a String
* @param color The color character to be replaced
* @return The converted Message
* @deprecated Legacy formatting codes are being phased out of Minecraft
*/
@Deprecated
public static Text.Literal fromLegacy(String text, char color) {
return factory.parseLegacyMessage(text, color);
}
/**
* Removes the legacy formatting character from a legacy string.
*
* @param text The legacy text as a String
* @return The stripped text
* @deprecated Legacy formatting codes are being phased out of Minecraft
*/
@Deprecated
@SuppressWarnings("deprecation")
public static String stripCodes(String text) {
return stripCodes(text, getLegacyChar());
}
/**
* Removes the legacy formatting character from a legacy string.
*
* @param text The legacy text as a String
* @param color The color character to be replaced
* @return The stripped text
* @deprecated Legacy formatting codes are being phased out of Minecraft
*/
@Deprecated
public static String stripCodes(String text, char color) {
return factory.stripLegacyCodes(text, color);
}
/**
* Replaces the given formatting character with the default legacy
* formatting character from a legacy string.
*
* @param text The legacy text as a String
* @param from The color character to be replaced
* @return The replaced text
* @deprecated Legacy formatting codes are being phased out of Minecraft
*/
@Deprecated
@SuppressWarnings("deprecation")
public static String replaceCodes(String text, char from) {
return replaceCodes(text, from, getLegacyChar());
}
/**
* Replaces the given formatting character with another given formatting
* character from a legacy string.
*
* @param text The legacy text as a String
* @param from The color character to be replaced
* @param to The color character to replace with
* @return The replaced text
* @deprecated Legacy formatting codes are being phased out of Minecraft
*/
@Deprecated
public static String replaceCodes(String text, char from, char to) {
return factory.replaceLegacyCodes(text, from, to);
}
/**
* Returns a representation of the {@link Text} using the legacy color
* codes.
*
* @param text The text to convert
* @return The text converted to the old color codes
* @deprecated Legacy formatting codes are being phased out of Minecraft
*/
@Deprecated
@SuppressWarnings("deprecation")
public static String toLegacy(Text text) {
return toLegacy(text, getLegacyChar());
}
/**
* Returns a representation of the {@link Text} using the legacy color
* codes.
*
* @param text The text to convert
* @param code The legacy char to use for the message
* @return The text converted to the old color codes
* @deprecated Legacy formatting codes are being phased out of Minecraft
*/
@Deprecated
public static String toLegacy(Text text, char code) {
return factory.toLegacy(text, code);
}
/**
* Returns a representation of the {@link Text} using the legacy color
* codes.
*
* @param text The text to convert
* @param code The legacy char to use for the message
* @param locale The language to return this representation in
* @return The text converted to the old color codes
* @deprecated Legacy formatting codes are being phased out of Minecraft
*/
@Deprecated
public static String toLegacy(Text text, char code, Locale locale) {
return factory.toLegacy(text, code, locale);
}
}<|fim▁end|>
|
*/
public static Text join(Text separator, Text... texts) {
switch (texts.length) {
case 0:
|
<|file_name|>TaskExecutor.java<|end_file_name|><|fim▁begin|>package net.sf.jabref.gui.util;
import javafx.concurrent.Task;
/**
* An object that executes submitted {@link Task}s. This
* interface provides a way of decoupling task submission from the
* mechanics of how each task will be run, including details of thread
* use, scheduling, thread pooling, etc.<|fim▁hole|> * Runs the given task.
*
* @param task the task to run
* @param <V> type of return value of the task
*/
<V> void execute(BackgroundTask<V> task);
}<|fim▁end|>
|
*/
public interface TaskExecutor {
/**
|
<|file_name|>hrtb-higher-ranker-supertraits-transitive.rs<|end_file_name|><|fim▁begin|>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test HRTB supertraits with several levels of expansion required.
trait Foo<'tcx>
{
fn foo(&'tcx self) -> &'tcx isize;
}
trait Bar<'ccx>
: for<'tcx> Foo<'tcx>
{
fn bar(&'ccx self) -> &'ccx isize;
}
trait Baz
: for<'ccx> Bar<'ccx>
{
fn dummy(&self);
}
trait Qux
: Bar<'static>
{
fn dummy(&self);
}
fn want_foo_for_any_tcx<F>(f: &F)
where F : for<'tcx> Foo<'tcx>
{
}<|fim▁hole|> where B : for<'ccx> Bar<'ccx>
{
}
fn want_baz<B>(b: &B)
where B : Baz
{
want_foo_for_any_tcx(b);
want_bar_for_any_ccx(b);
}
fn want_qux<B>(b: &B)
where B : Qux
{
want_foo_for_any_tcx(b);
want_bar_for_any_ccx(b); //~ ERROR E0277
}
fn main() {}<|fim▁end|>
|
fn want_bar_for_any_ccx<B>(b: &B)
|
<|file_name|>deriving-clone-enum.rs<|end_file_name|><|fim▁begin|>// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#[derive(Clone)]
enum E {
A,
B(()),
C
}
pub fn main() {<|fim▁hole|> let _ = E::A.clone();
}<|fim▁end|>
| |
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>#![feature(test)]
extern crate test;
extern crate rand;
extern crate regex;
extern crate zip;
pub mod base;<|fim▁hole|><|fim▁end|>
|
pub mod mcts;
|
<|file_name|>Environment.js<|end_file_name|><|fim▁begin|>define(
[
'solarfield/lightship-js/src/Solarfield/Lightship/Environment',
'solarfield/ok-kit-js/src/Solarfield/Ok/ObjectUtils'
],
function (LightshipEnvironment, ObjectUtils) {
"use strict";
var Environment = ObjectUtils.extend(LightshipEnvironment, {
});
return Environment;
}<|fim▁hole|><|fim▁end|>
|
);
|
<|file_name|>mouthdetection.py<|end_file_name|><|fim▁begin|>"""
input: a loaded image;
output: [[x,y],[width,height]] of the detected mouth area
"""
import cv
def findmouth(img):
# INITIALIZE: loading the classifiers
haarFace = cv.Load('haarcascade_frontalface_default.xml')
haarMouth = cv.Load('haarcascade_mouth.xml')
# running the classifiers
storage = cv.CreateMemStorage()
detectedFace = cv.HaarDetectObjects(img, haarFace, storage)
detectedMouth = cv.HaarDetectObjects(img, haarMouth, storage)
# FACE: find the largest detected face as detected face<|fim▁hole|> maxFace = 0
if detectedFace:
for face in detectedFace: # face: [0][0]: x; [0][1]: y; [0][2]: width; [0][3]: height
if face[0][3]* face[0][2] > maxFaceSize:
maxFaceSize = face[0][3]* face[0][2]
maxFace = face
if maxFace == 0: # did not detect face
return 2
def mouth_in_lower_face(mouth,face):
# if the mouth is in the lower 2/5 of the face
# and the lower edge of mouth is above that of the face
# and the horizontal center of the mouth is the center of the face
if (mouth[0][1] > face[0][1] + face[0][3] * 3 / float(5)
and mouth[0][1] + mouth[0][3] < face[0][1] + face[0][3]
and abs((mouth[0][0] + mouth[0][2] / float(2))
- (face[0][0] + face[0][2] / float(2))) < face[0][2] / float(10)):
return True
else:
return False
# FILTER MOUTH
filteredMouth = []
if detectedMouth:
for mouth in detectedMouth:
if mouth_in_lower_face(mouth,maxFace):
filteredMouth.append(mouth)
maxMouthSize = 0
for mouth in filteredMouth:
if mouth[0][3]* mouth[0][2] > maxMouthSize:
maxMouthSize = mouth[0][3]* mouth[0][2]
maxMouth = mouth
try:
return maxMouth
except UnboundLocalError:
return 2<|fim▁end|>
|
maxFaceSize = 0
|
<|file_name|>manifests.py<|end_file_name|><|fim▁begin|>"""Manifest clonning tools.."""
import json
import requests
import six
import time
import uuid
import zipfile
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import padding
from nailgun import entities
from robottelo.cli.subscription import Subscription
from robottelo.config import settings
from robottelo.constants import INTERFACE_API, INTERFACE_CLI
from robottelo.decorators.func_locker import lock_function
from robottelo.ssh import upload_file
class ManifestCloner(object):
"""Manifest clonning utility class."""
def __init__(self, template=None, signing_key=None):
self.template = template
self.signing_key = signing_key
def _download_manifest_info(self):
"""Download and cache the manifest information."""
self.template = requests.get(settings.fake_manifest.url).content
self.signing_key = requests.get(settings.fake_manifest.key_url).content
self.private_key = serialization.load_pem_private_key(
self.signing_key,
password=None,
backend=default_backend()
)
def clone(self):
"""Clones a RedHat-manifest file.
Change the consumer ``uuid`` and sign the new manifest with
signing key. The certificate for the key must be installed on the
candlepin server in order to accept uploading the cloned
manifest.
:return: A file-like object (``BytesIO`` on Python 3 and
``StringIO`` on Python 2) with the contents of the cloned
manifest.
"""
if self.signing_key is None or self.template is None:
self._download_manifest_info()
template_zip = zipfile.ZipFile(six.BytesIO(self.template))
# Extract the consumer_export.zip from the template manifest.
consumer_export_zip = zipfile.ZipFile(
six.BytesIO(template_zip.read('consumer_export.zip')))
# Generate a new consumer_export.zip file changing the consumer
# uuid.
consumer_export = six.BytesIO()
with zipfile.ZipFile(consumer_export, 'w') as new_consumer_export_zip:
for name in consumer_export_zip.namelist():
if name == 'export/consumer.json':
consumer_data = json.loads(
consumer_export_zip.read(name).decode('utf-8'))
consumer_data['uuid'] = six.text_type(uuid.uuid1())
new_consumer_export_zip.writestr(
name,
json.dumps(consumer_data)
)
else:
new_consumer_export_zip.writestr(
name,
consumer_export_zip.read(name)
)
# Generate a new manifest.zip file with the generated
# consumer_export.zip and new signature.
manifest = six.BytesIO()
with zipfile.ZipFile(
manifest, 'w', zipfile.ZIP_DEFLATED) as manifest_zip:
consumer_export.seek(0)
manifest_zip.writestr(
'consumer_export.zip',
consumer_export.read()
)
consumer_export.seek(0)
signer = self.private_key.signer(
padding.PKCS1v15(), hashes.SHA256())
signer.update(consumer_export.read())
manifest_zip.writestr(
'signature',
signer.finalize()
)
# Make sure that the file-like object is at the beginning and
# ready to be read.
manifest.seek(0)
return manifest
def original(self):
"""Returns the original manifest as a file-like object.
Be aware that using the original manifest and not removing it
afterwards will make impossible to import it on any other Organization.
Make sure to close the returned file-like object in order to clean up
the memory used to store it.
"""
if self.signing_key is None or self.template is None:
self._download_manifest_info()
return six.BytesIO(self.template)
# Cache the ManifestCloner in order to avoid downloading the manifest template
# every single time.
_manifest_cloner = ManifestCloner()
class Manifest(object):
"""Class that holds the contents of a manifest with a generated filename
based on ``time.time``.
To ensure that the manifest content is closed use this class as a context
manager with the ``with`` statement::
with Manifest() as manifest:
# my fancy stuff
"""
def __init__(self, content=None, filename=None):
self._content = content
self.filename = filename
if self._content is None:
self._content = _manifest_cloner.clone()
if self.filename is None:
self.filename = u'/var/tmp/manifest-{0}.zip'.format(
int(time.time()))
@property
def content(self):
if not self._content.closed:
# Make sure that the content is always ready to read
self._content.seek(0)
return self._content
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
if not self.content.closed:
self.content.close()
def clone():
"""Clone the cached manifest and return a ``Manifest`` object.
Is hightly recommended to use this with the ``with`` statement to make that
the content of the manifest (file-like object) is closed properly::
with clone() as manifest:
# my fancy stuff
"""
return Manifest()
def original_manifest():
"""Returns a ``Manifest`` object filed with the template manifest.
Make sure to remove the manifest after its usage otherwiser the Satellite 6
server will not accept it anymore on any other organization.
Is hightly recommended to use this with the ``with`` statement to make that
the content of the manifest (file-like object) is closed properly::
<|fim▁hole|> return Manifest(_manifest_cloner.original())
@lock_function
def upload_manifest_locked(org_id, manifest, interface=INTERFACE_API):
"""Upload a manifest with locking, using the requested interface.
:type org_id: int
:type manifest: robottelo.manifests.Manifest
:type interface: str
:returns: the upload result
Note: The manifest uploading is strictly locked only when using this
function
Usage::
# for API interface
manifest = manifests.clone()
upload_manifest_locked(org_id, manifest, interface=INTERFACE_API)
# for CLI interface
manifest = manifests.clone()
upload_manifest_locked(org_id, manifest, interface=INTERFACE_CLI)
# or in one line with default interface
result = upload_manifest_locked(org_id, manifests.clone())
subscription_id = result[id']
"""
if interface not in [INTERFACE_API, INTERFACE_CLI]:
raise ValueError(
'upload manifest with interface "{0}" not supported'
.format(interface)
)
if interface == INTERFACE_API:
with manifest:
result = entities.Subscription().upload(
data={'organization_id': org_id},
files={'content': manifest.content},
)
else:
# interface is INTERFACE_CLI
with manifest:
upload_file(manifest.content, manifest.filename)
result = Subscription.upload({
'file': manifest.filename,
'organization-id': org_id,
})
return result<|fim▁end|>
|
with original_manifest() as manifest:
# my fancy stuff
"""
|
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::fmt;
use std::pin::Pin;
use anyhow::{Context, Error};
use edenapi_types::ToWire;
use futures::{stream::TryStreamExt, FutureExt, Stream};
use gotham::{
handler::{HandlerError as GothamHandlerError, HandlerFuture},
middleware::state::StateMiddleware,
pipeline::{new_pipeline, single::single_pipeline},
router::{
builder::RouterBuilder,
builder::{build_router as gotham_build_router, DefineSingleRoute, DrawRoutes},
Router,
},
state::{FromState, State},
};
use gotham_derive::StateData;
use gotham_ext::{
content_encoding::ContentEncoding,
error::{ErrorFormatter, HttpError},
middleware::scuba::ScubaMiddlewareState,
response::{build_response, encode_stream, ResponseTryStreamExt, StreamBody, TryIntoResponse},
state_ext::StateExt,
};
use hyper::{Body, Response};
use mime::Mime;
use serde::{Deserialize, Serialize};
use crate::context::ServerContext;
use crate::middleware::RequestContext;
use crate::utils::{cbor_mime, get_repo, parse_wire_request, to_cbor_bytes};
mod bookmarks;
mod capabilities;
mod clone;
mod commit;
mod files;
mod handler;
mod history;
mod land;
mod lookup;
mod pull;
mod repos;
mod trees;
pub(crate) use handler::{EdenApiHandler, HandlerError, HandlerResult, PathExtractorWithRepo};
/// Enum identifying the EdenAPI method that each handler corresponds to.
/// Used to identify the handler for logging and stats collection.
#[derive(Copy, Clone)]
pub enum EdenApiMethod {
Capabilities,
Files,
Files2,
Lookup,
UploadFile,
UploadHgFilenodes,
UploadTrees,
UploadHgChangesets,
UploadBonsaiChangeset,
Trees,
History,
CommitLocationToHash,
CommitHashToLocation,
CommitRevlogData,
CommitHashLookup,
Clone,
Bookmarks,
SetBookmark,
LandStack,
PullFastForwardMaster,
PullLazy,
EphemeralPrepare,
FetchSnapshot,
CommitGraph,
DownloadFile,
CommitMutations,
}
impl fmt::Display for EdenApiMethod {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let name = match self {
Self::Capabilities => "capabilities",
Self::Files => "files",
Self::Files2 => "files2",
Self::Trees => "trees",
Self::History => "history",
Self::CommitLocationToHash => "commit_location_to_hash",
Self::CommitHashToLocation => "commit_hash_to_location",
Self::CommitRevlogData => "commit_revlog_data",
Self::CommitHashLookup => "commit_hash_lookup",
Self::CommitGraph => "commit_graph",
Self::Clone => "clone",
Self::Bookmarks => "bookmarks",
Self::SetBookmark => "set_bookmark",
Self::LandStack => "land_stack",
Self::Lookup => "lookup",
Self::UploadFile => "upload_file",
Self::PullFastForwardMaster => "pull_fast_forward_master",
Self::PullLazy => "pull_lazy",
Self::UploadHgFilenodes => "upload_filenodes",
Self::UploadTrees => "upload_trees",
Self::UploadHgChangesets => "upload_hg_changesets",
Self::UploadBonsaiChangeset => "upload_bonsai_changeset",
Self::EphemeralPrepare => "ephemeral_prepare",
Self::FetchSnapshot => "fetch_snapshot",
Self::DownloadFile => "download_file",
Self::CommitMutations => "commit_mutations",<|fim▁hole|>
/// Information about the handler that served the request.
///
/// This should be inserted into the request's `State` by each handler. It will
/// typically be used by middlware for request logging and stats reporting.
#[derive(Default, StateData, Clone)]
pub struct HandlerInfo {
pub repo: Option<String>,
pub method: Option<EdenApiMethod>,
}
impl HandlerInfo {
pub fn new(repo: impl ToString, method: EdenApiMethod) -> Self {
Self {
repo: Some(repo.to_string()),
method: Some(method),
}
}
}
/// JSON representation of an error to send to the client.
#[derive(Clone, Serialize, Debug, Deserialize)]
struct JsonError {
message: String,
request_id: String,
}
struct JsonErrorFomatter;
impl ErrorFormatter for JsonErrorFomatter {
type Body = Vec<u8>;
fn format(&self, error: &Error, state: &State) -> Result<(Self::Body, Mime), Error> {
let message = format!("{:#}", error);
// Package the error message into a JSON response.
let res = JsonError {
message,
request_id: state.short_request_id().to_string(),
};
let body = serde_json::to_vec(&res).context("Failed to serialize error")?;
Ok((body, mime::APPLICATION_JSON))
}
}
/// Macro to create a Gotham handler function from an async function.
///
/// The expected signature of the input function is:
/// ```rust,ignore
/// async fn handler(state: &mut State) -> Result<impl TryIntoResponse, HttpError>
/// ```
///
/// The resulting wrapped function will have the signaure:
/// ```rust,ignore
/// fn wrapped(mut state: State) -> Pin<Box<HandlerFuture>>
/// ```
macro_rules! define_handler {
($name:ident, $func:path) => {
fn $name(mut state: State) -> Pin<Box<HandlerFuture>> {
async move {
let res = $func(&mut state).await;
build_response(res, state, &JsonErrorFomatter)
}
.boxed()
}
};
}
define_handler!(repos_handler, repos::repos);
define_handler!(trees_handler, trees::trees);
define_handler!(capabilities_handler, capabilities::capabilities_handler);
define_handler!(commit_hash_to_location_handler, commit::hash_to_location);
define_handler!(commit_revlog_data_handler, commit::revlog_data);
define_handler!(clone_handler, clone::clone_data);
define_handler!(upload_file_handler, files::upload_file);
define_handler!(pull_fast_forward_master, pull::pull_fast_forward_master);
define_handler!(pull_lazy, pull::pull_lazy);
fn health_handler(state: State) -> (State, &'static str) {
if ServerContext::borrow_from(&state).will_exit() {
(state, "EXITING")
} else {
(state, "I_AM_ALIVE")
}
}
async fn handler_wrapper<Handler: EdenApiHandler>(
mut state: State,
) -> Result<(State, Response<Body>), (State, GothamHandlerError)> {
let res = async {
let path = Handler::PathExtractor::take_from(&mut state);
let query_string = Handler::QueryStringExtractor::take_from(&mut state);
let content_encoding = ContentEncoding::from_state(&state);
state.put(HandlerInfo::new(path.repo(), Handler::API_METHOD));
let rctx = RequestContext::borrow_from(&mut state).clone();
let sctx = ServerContext::borrow_from(&mut state);
let repo = get_repo(&sctx, &rctx, path.repo(), None).await?;
let request = parse_wire_request::<<Handler::Request as ToWire>::Wire>(&mut state).await?;
let sampling_rate = Handler::sampling_rate(&request);
if sampling_rate.get() > 1 {
ScubaMiddlewareState::try_set_sampling_rate(&mut state, sampling_rate);
}
match Handler::handler(repo, path, query_string, request).await {
Ok(responses) => Ok(encode_response_stream(responses, content_encoding)),
Err(HandlerError::E500(err)) => Err(HttpError::e500(err)),
}
}
.await;
build_response(res, state, &JsonErrorFomatter)
}
/// Encode a stream of EdenAPI responses into its final on-wire representation.
///
/// This involves converting each item to its wire format, CBOR serializing them, and then
/// optionally compressing the resulting byte stream based on the specified Content-Encoding.
pub fn encode_response_stream<S, T>(stream: S, encoding: ContentEncoding) -> impl TryIntoResponse
where
S: Stream<Item = Result<T, Error>> + Send + 'static,
T: ToWire + Send + 'static,
{
let stream = stream.and_then(|item| async move { to_cbor_bytes(&item.to_wire()) });
let stream = encode_stream(stream, encoding, None).capture_first_err();
StreamBody::new(stream, cbor_mime())
}
// We use a struct here (rather than just a global function) just for the convenience
// of writing `Handlers::setup::<MyHandler>(route)`
// instead of `setup_handler::<MyHandler, _, _>(route)`, to make things clearer.
struct Handlers<C, P> {
_phantom: (std::marker::PhantomData<C>, std::marker::PhantomData<P>),
}
impl<C, P> Handlers<C, P>
where
C: gotham::pipeline::chain::PipelineHandleChain<P> + Copy + Send + Sync + 'static,
P: std::panic::RefUnwindSafe + Send + Sync + 'static,
{
fn setup<Handler: EdenApiHandler>(route: &mut RouterBuilder<C, P>) {
route
.request(
vec![Handler::HTTP_METHOD],
&format!("/:repo{}", Handler::ENDPOINT),
)
.with_path_extractor::<Handler::PathExtractor>()
.with_query_string_extractor::<Handler::QueryStringExtractor>()
.to_async(handler_wrapper::<Handler>);
}
}
pub fn build_router(ctx: ServerContext) -> Router {
let pipeline = new_pipeline().add(StateMiddleware::new(ctx)).build();
let (chain, pipelines) = single_pipeline(pipeline);
gotham_build_router(chain, pipelines, |route| {
route.get("/health_check").to(health_handler);
route.get("/repos").to(repos_handler);
Handlers::setup::<commit::EphemeralPrepareHandler>(route);
Handlers::setup::<commit::UploadHgChangesetsHandler>(route);
Handlers::setup::<commit::UploadBonsaiChangesetHandler>(route);
Handlers::setup::<commit::LocationToHashHandler>(route);
Handlers::setup::<commit::HashLookupHandler>(route);
Handlers::setup::<files::FilesHandler>(route);
Handlers::setup::<files::Files2Handler>(route);
Handlers::setup::<files::UploadHgFilenodesHandler>(route);
Handlers::setup::<bookmarks::BookmarksHandler>(route);
Handlers::setup::<bookmarks::SetBookmarkHandler>(route);
Handlers::setup::<land::LandStackHandler>(route);
Handlers::setup::<history::HistoryHandler>(route);
Handlers::setup::<lookup::LookupHandler>(route);
Handlers::setup::<trees::UploadTreesHandler>(route);
Handlers::setup::<commit::FetchSnapshotHandler>(route);
Handlers::setup::<commit::GraphHandler>(route);
Handlers::setup::<files::DownloadFileHandler>(route);
Handlers::setup::<commit::CommitMutationsHandler>(route);
route.get("/:repo/health_check").to(health_handler);
route
.get("/:repo/capabilities")
.with_path_extractor::<capabilities::CapabilitiesParams>()
.to(capabilities_handler);
route
.post("/:repo/trees")
.with_path_extractor::<trees::TreeParams>()
.to(trees_handler);
route
.post("/:repo/commit/hash_to_location")
.with_path_extractor::<commit::HashToLocationParams>()
.to(commit_hash_to_location_handler);
route
.post("/:repo/commit/revlog_data")
.with_path_extractor::<commit::RevlogDataParams>()
.to(commit_revlog_data_handler);
route
.post("/:repo/clone")
.with_path_extractor::<clone::CloneParams>()
.to(clone_handler);
route
.post("/:repo/pull_fast_forward_master")
.with_path_extractor::<pull::PullFastForwardParams>()
.to(pull_fast_forward_master);
route
.post("/:repo/pull_lazy")
.with_path_extractor::<pull::PullLazyParams>()
.to(pull_lazy);
route
.put("/:repo/upload/file/:idtype/:id")
.with_path_extractor::<files::UploadFileParams>()
.with_query_string_extractor::<files::UploadFileQueryString>()
.to(upload_file_handler);
})
}<|fim▁end|>
|
};
write!(f, "{}", name)
}
}
|
<|file_name|>home.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
'''
Copyright (c) 2015 Heidelberg University Library
Distributed under the GNU GPL v3. For full terms see the file
LICENSE.md
'''
from ompannouncements import Announcements
def index():
a = Announcements(myconf, db, locale)
news_list = a.create_announcement_list()<|fim▁hole|><|fim▁end|>
|
return locals()
|
<|file_name|>parse-form-child-xml.js<|end_file_name|><|fim▁begin|>define(function (require) {
'use strict';
var $ = require('jquery');
var _ = require('underscore');
var XMLSerialiser = new window.XMLSerializer();
function xmlNodeReducer (memo, node) {
return memo + XMLSerialiser.serializeToString(node);
}
/**
* @typedef {Object} XMLParseResult
*
* @property {string} * - String representation of Either the value or subform Form definitions.
*/
/**
* Takes a xml node and turns it into the format required for FORMS
*
* @param {Node} xmlNode - The XML Node of the subform element.
* @return {XMLParseResult} - The result of parsing the subform node<|fim▁hole|> var children = $xmlNode.children();
result[$xmlNode.prop('nodeName')] = children.length ? _.reduce(children, xmlNodeReducer, '') : $xmlNode.text();
return result;
};
});<|fim▁end|>
|
*/
return function parseFormChildXML (xmlNode) {
var result = {};
var $xmlNode = $(xmlNode);
|
<|file_name|>generate-apache-config.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
import sys, os
from optparse import OptionParser
option_parser = OptionParser()
option_parser.add_option('--install-root',default='/opt/graphite/',
help="The base directory of the graphite installation")
option_parser.add_option('--libs',default=None,
help="The directory where the graphite python package is installed (default is system site-packages)")
(options,args) = option_parser.parse_args()
install_root = options.install_root
if not install_root.endswith('/'):
install_root += '/'
<|fim▁hole|>python_path = [ os.path.join(install_root,'webapp') ]
if options.libs:
python_path.append( options.libs )
import django
django_root = django.__path__[0]
vhost = open('misc/template-vhost.conf').read()
vhost = vhost.replace('@INSTALL_ROOT@', install_root)
vhost = vhost.replace('@PYTHON_PATH@', str(python_path))
vhost = vhost.replace('@DJANGO_ROOT@', django_root)
fh = open('graphite-vhost.conf','w')
fh.write(vhost)
fh.close()
print "Generated graphite-vhost.conf"
print "Put this file in your apache installation's vhost include directory."
print "NOTE: you must ensure that mod_python is properly configured before using Graphite."<|fim▁end|>
|
if not os.path.isdir(install_root):
print "Graphite does not appear to be installed at %s, do you need to specify a different --install-root?" % install_root
sys.exit(1)
|
<|file_name|>gradientwidget.cpp<|end_file_name|><|fim▁begin|>#include "gradientwidget.h"
#include "ui_gradientwidget.h"
GradientWidget::GradientWidget(QWidget *parent) :
AbstractWidget(parent),
ui(new Ui::GradientWidget)
{
ui->setupUi(this);
connect(ui->nextButton,SIGNAL(clicked(bool)),this,SLOT(nextClick(bool)));
hide();
}
GradientWidget::~GradientWidget()
{
delete ui;
}
void GradientWidget::showEvent(QShowEvent *)
{
ui->graphicsView->setScene(new QGraphicsScene);
}
<|fim▁hole|>void GradientWidget::execute()
{
module.mod_main();
m_picture renPic;
renPic.width = module.p_width;
renPic.height = module.p_height;
renPic.data = module.HDR;
ui->graphicsView->scene()->addPixmap(QPixmap::fromImage(picToImg(renPic)));
ui->graphicsView->scene()->update();
}<|fim▁end|>
| |
<|file_name|>toggleLang.js<|end_file_name|><|fim▁begin|>// get the languange parameter in the URL (i for case insensitive;
//exec for test for a match in a string and return thr first match)
function getURLParameter(key) {
var result = new RegExp(key + '=([^&]*)', 'i').exec(window.location.search);
return result && result[1] || '';
}<|fim▁hole|>//
function toggleLang(lang) {
var lang = lang || 'de';
document.location = document.location.pathname + '?lang=' + lang;
}
// set UR
var lang = getURLParameter('lang') || 'de';
$('#lang').ready(function() {
$('#lang li').each(function() {
var li = $(this)[0];
if (li.id == lang) $(this).addClass('selected');
});
});<|fim▁end|>
| |
<|file_name|>queues.go<|end_file_name|><|fim▁begin|>package servicebus
// 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.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/autorest/validation"
"github.com/Azure/go-autorest/tracing"
"net/http"
)
// QueuesClient is the client for the Queues methods of the Servicebus service.
type QueuesClient struct {
BaseClient
}
// NewQueuesClient creates an instance of the QueuesClient client.
func NewQueuesClient(subscriptionID string) QueuesClient {
return NewQueuesClientWithBaseURI(DefaultBaseURI, subscriptionID)
}
// NewQueuesClientWithBaseURI creates an instance of the QueuesClient client using a custom endpoint. Use this when
// interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack).
func NewQueuesClientWithBaseURI(baseURI string, subscriptionID string) QueuesClient {
return QueuesClient{NewWithBaseURI(baseURI, subscriptionID)}
}
// CreateOrUpdate creates or updates a Service Bus queue. This operation is idempotent.
// Parameters:
// resourceGroupName - name of the Resource group within the Azure subscription.
// namespaceName - the namespace name
// queueName - the queue name.
// parameters - parameters supplied to create or update a queue resource.
func (client QueuesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, namespaceName string, queueName string, parameters SBQueue) (result SBQueue, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/QueuesClient.CreateOrUpdate")
defer func() {
sc := -1
if result.Response.Response != nil {
sc = result.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
if err := validation.Validate([]validation.Validation{
{TargetValue: resourceGroupName,
Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil},
{Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}},
{TargetValue: namespaceName,
Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil},
{Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}},
{TargetValue: queueName,
Constraints: []validation.Constraint{{Target: "queueName", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil {
return result, validation.NewError("servicebus.QueuesClient", "CreateOrUpdate", err.Error())
}
req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, namespaceName, queueName, parameters)
if err != nil {
err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "CreateOrUpdate", nil, "Failure preparing request")
return
}
resp, err := client.CreateOrUpdateSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "CreateOrUpdate", resp, "Failure sending request")
return
}
result, err = client.CreateOrUpdateResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "CreateOrUpdate", resp, "Failure responding to request")
return
}
return
}
// CreateOrUpdatePreparer prepares the CreateOrUpdate request.
func (client QueuesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, namespaceName string, queueName string, parameters SBQueue) (*http.Request, error) {
pathParameters := map[string]interface{}{
"namespaceName": autorest.Encode("path", namespaceName),
"queueName": autorest.Encode("path", queueName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2021-06-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
parameters.SystemData = nil
preparer := autorest.CreatePreparer(
autorest.AsContentType("application/json; charset=utf-8"),
autorest.AsPut(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/queues/{queueName}", pathParameters),
autorest.WithJSON(parameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the
// http.Response Body if it receives an error.
func (client QueuesClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) {
return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}
// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always
// closes the http.Response Body.
func (client QueuesClient) CreateOrUpdateResponder(resp *http.Response) (result SBQueue, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// CreateOrUpdateAuthorizationRule creates an authorization rule for a queue.
// Parameters:
// resourceGroupName - name of the Resource group within the Azure subscription.
// namespaceName - the namespace name
// queueName - the queue name.
// authorizationRuleName - the authorization rule name.
// parameters - the shared access authorization rule.
func (client QueuesClient) CreateOrUpdateAuthorizationRule(ctx context.Context, resourceGroupName string, namespaceName string, queueName string, authorizationRuleName string, parameters SBAuthorizationRule) (result SBAuthorizationRule, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/QueuesClient.CreateOrUpdateAuthorizationRule")
defer func() {
sc := -1
if result.Response.Response != nil {
sc = result.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
if err := validation.Validate([]validation.Validation{
{TargetValue: resourceGroupName,
Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil},
{Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}},
{TargetValue: namespaceName,
Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil},
{Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}},
{TargetValue: queueName,
Constraints: []validation.Constraint{{Target: "queueName", Name: validation.MinLength, Rule: 1, Chain: nil}}},
{TargetValue: authorizationRuleName,
Constraints: []validation.Constraint{{Target: "authorizationRuleName", Name: validation.MaxLength, Rule: 50, Chain: nil},
{Target: "authorizationRuleName", Name: validation.MinLength, Rule: 1, Chain: nil}}},
{TargetValue: parameters,
Constraints: []validation.Constraint{{Target: "parameters.SBAuthorizationRuleProperties", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "parameters.SBAuthorizationRuleProperties.Rights", Name: validation.Null, Rule: true, Chain: nil}}}}}}); err != nil {
return result, validation.NewError("servicebus.QueuesClient", "CreateOrUpdateAuthorizationRule", err.Error())
}
req, err := client.CreateOrUpdateAuthorizationRulePreparer(ctx, resourceGroupName, namespaceName, queueName, authorizationRuleName, parameters)
if err != nil {
err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "CreateOrUpdateAuthorizationRule", nil, "Failure preparing request")
return
}
resp, err := client.CreateOrUpdateAuthorizationRuleSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "CreateOrUpdateAuthorizationRule", resp, "Failure sending request")
return
}
result, err = client.CreateOrUpdateAuthorizationRuleResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "CreateOrUpdateAuthorizationRule", resp, "Failure responding to request")
return
}
return
}
// CreateOrUpdateAuthorizationRulePreparer prepares the CreateOrUpdateAuthorizationRule request.
func (client QueuesClient) CreateOrUpdateAuthorizationRulePreparer(ctx context.Context, resourceGroupName string, namespaceName string, queueName string, authorizationRuleName string, parameters SBAuthorizationRule) (*http.Request, error) {
pathParameters := map[string]interface{}{
"authorizationRuleName": autorest.Encode("path", authorizationRuleName),
"namespaceName": autorest.Encode("path", namespaceName),
"queueName": autorest.Encode("path", queueName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2021-06-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
parameters.SystemData = nil
preparer := autorest.CreatePreparer(
autorest.AsContentType("application/json; charset=utf-8"),
autorest.AsPut(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/queues/{queueName}/authorizationRules/{authorizationRuleName}", pathParameters),
autorest.WithJSON(parameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// CreateOrUpdateAuthorizationRuleSender sends the CreateOrUpdateAuthorizationRule request. The method will close the
// http.Response Body if it receives an error.
func (client QueuesClient) CreateOrUpdateAuthorizationRuleSender(req *http.Request) (*http.Response, error) {
return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}
// CreateOrUpdateAuthorizationRuleResponder handles the response to the CreateOrUpdateAuthorizationRule request. The method always
// closes the http.Response Body.
func (client QueuesClient) CreateOrUpdateAuthorizationRuleResponder(resp *http.Response) (result SBAuthorizationRule, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// Delete deletes a queue from the specified namespace in a resource group.
// Parameters:
// resourceGroupName - name of the Resource group within the Azure subscription.
// namespaceName - the namespace name
// queueName - the queue name.
func (client QueuesClient) Delete(ctx context.Context, resourceGroupName string, namespaceName string, queueName string) (result autorest.Response, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/QueuesClient.Delete")
defer func() {
sc := -1
if result.Response != nil {
sc = result.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
if err := validation.Validate([]validation.Validation{
{TargetValue: resourceGroupName,
Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil},
{Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}},
{TargetValue: namespaceName,
Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil},
{Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}},
{TargetValue: queueName,
Constraints: []validation.Constraint{{Target: "queueName", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil {
return result, validation.NewError("servicebus.QueuesClient", "Delete", err.Error())
}
req, err := client.DeletePreparer(ctx, resourceGroupName, namespaceName, queueName)
if err != nil {
err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "Delete", nil, "Failure preparing request")
return
}
resp, err := client.DeleteSender(req)
if err != nil {
result.Response = resp
err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "Delete", resp, "Failure sending request")
return
}
result, err = client.DeleteResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "Delete", resp, "Failure responding to request")
return
}
return
}
// DeletePreparer prepares the Delete request.
func (client QueuesClient) DeletePreparer(ctx context.Context, resourceGroupName string, namespaceName string, queueName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"namespaceName": autorest.Encode("path", namespaceName),
"queueName": autorest.Encode("path", queueName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2021-06-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsDelete(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/queues/{queueName}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// DeleteSender sends the Delete request. The method will close the
// http.Response Body if it receives an error.
func (client QueuesClient) DeleteSender(req *http.Request) (*http.Response, error) {
return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}
// DeleteResponder handles the response to the Delete request. The method always
// closes the http.Response Body.
func (client QueuesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent),
autorest.ByClosing())
result.Response = resp
return
}
// DeleteAuthorizationRule deletes a queue authorization rule.
// Parameters:
// resourceGroupName - name of the Resource group within the Azure subscription.
// namespaceName - the namespace name
// queueName - the queue name.
// authorizationRuleName - the authorization rule name.
func (client QueuesClient) DeleteAuthorizationRule(ctx context.Context, resourceGroupName string, namespaceName string, queueName string, authorizationRuleName string) (result autorest.Response, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/QueuesClient.DeleteAuthorizationRule")
defer func() {
sc := -1
if result.Response != nil {
sc = result.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
if err := validation.Validate([]validation.Validation{
{TargetValue: resourceGroupName,
Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil},
{Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}},
{TargetValue: namespaceName,
Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil},
{Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}},
{TargetValue: queueName,
Constraints: []validation.Constraint{{Target: "queueName", Name: validation.MinLength, Rule: 1, Chain: nil}}},
{TargetValue: authorizationRuleName,
Constraints: []validation.Constraint{{Target: "authorizationRuleName", Name: validation.MaxLength, Rule: 50, Chain: nil},
{Target: "authorizationRuleName", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil {
return result, validation.NewError("servicebus.QueuesClient", "DeleteAuthorizationRule", err.Error())
}
req, err := client.DeleteAuthorizationRulePreparer(ctx, resourceGroupName, namespaceName, queueName, authorizationRuleName)
if err != nil {
err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "DeleteAuthorizationRule", nil, "Failure preparing request")
return
}
resp, err := client.DeleteAuthorizationRuleSender(req)
if err != nil {
result.Response = resp
err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "DeleteAuthorizationRule", resp, "Failure sending request")
return
}
result, err = client.DeleteAuthorizationRuleResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "DeleteAuthorizationRule", resp, "Failure responding to request")
return
}
return
}
// DeleteAuthorizationRulePreparer prepares the DeleteAuthorizationRule request.
func (client QueuesClient) DeleteAuthorizationRulePreparer(ctx context.Context, resourceGroupName string, namespaceName string, queueName string, authorizationRuleName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"authorizationRuleName": autorest.Encode("path", authorizationRuleName),
"namespaceName": autorest.Encode("path", namespaceName),
"queueName": autorest.Encode("path", queueName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2021-06-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsDelete(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/queues/{queueName}/authorizationRules/{authorizationRuleName}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// DeleteAuthorizationRuleSender sends the DeleteAuthorizationRule request. The method will close the
// http.Response Body if it receives an error.
func (client QueuesClient) DeleteAuthorizationRuleSender(req *http.Request) (*http.Response, error) {
return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}
// DeleteAuthorizationRuleResponder handles the response to the DeleteAuthorizationRule request. The method always
// closes the http.Response Body.
func (client QueuesClient) DeleteAuthorizationRuleResponder(resp *http.Response) (result autorest.Response, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent),
autorest.ByClosing())
result.Response = resp
return
}
// Get returns a description for the specified queue.
// Parameters:
// resourceGroupName - name of the Resource group within the Azure subscription.
// namespaceName - the namespace name
// queueName - the queue name.
func (client QueuesClient) Get(ctx context.Context, resourceGroupName string, namespaceName string, queueName string) (result SBQueue, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/QueuesClient.Get")
defer func() {
sc := -1
if result.Response.Response != nil {
sc = result.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
if err := validation.Validate([]validation.Validation{
{TargetValue: resourceGroupName,
Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil},
{Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}},
{TargetValue: namespaceName,
Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil},
{Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}},
{TargetValue: queueName,
Constraints: []validation.Constraint{{Target: "queueName", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil {
return result, validation.NewError("servicebus.QueuesClient", "Get", err.Error())
}
req, err := client.GetPreparer(ctx, resourceGroupName, namespaceName, queueName)
if err != nil {
err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "Get", nil, "Failure preparing request")
return
}
resp, err := client.GetSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "Get", resp, "Failure sending request")
return
}
result, err = client.GetResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "Get", resp, "Failure responding to request")
return
}
return
}
// GetPreparer prepares the Get request.
func (client QueuesClient) GetPreparer(ctx context.Context, resourceGroupName string, namespaceName string, queueName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"namespaceName": autorest.Encode("path", namespaceName),
"queueName": autorest.Encode("path", queueName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2021-06-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/queues/{queueName}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetSender sends the Get request. The method will close the
// http.Response Body if it receives an error.
func (client QueuesClient) GetSender(req *http.Request) (*http.Response, error) {
return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}
// GetResponder handles the response to the Get request. The method always
// closes the http.Response Body.
func (client QueuesClient) GetResponder(resp *http.Response) (result SBQueue, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// GetAuthorizationRule gets an authorization rule for a queue by rule name.
// Parameters:
// resourceGroupName - name of the Resource group within the Azure subscription.
// namespaceName - the namespace name
// queueName - the queue name.
// authorizationRuleName - the authorization rule name.
func (client QueuesClient) GetAuthorizationRule(ctx context.Context, resourceGroupName string, namespaceName string, queueName string, authorizationRuleName string) (result SBAuthorizationRule, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/QueuesClient.GetAuthorizationRule")
defer func() {
sc := -1
if result.Response.Response != nil {
sc = result.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
if err := validation.Validate([]validation.Validation{
{TargetValue: resourceGroupName,
Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil},
{Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}},
{TargetValue: namespaceName,
Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil},
{Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}},
{TargetValue: queueName,
Constraints: []validation.Constraint{{Target: "queueName", Name: validation.MinLength, Rule: 1, Chain: nil}}},
{TargetValue: authorizationRuleName,
Constraints: []validation.Constraint{{Target: "authorizationRuleName", Name: validation.MaxLength, Rule: 50, Chain: nil},
{Target: "authorizationRuleName", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil {
return result, validation.NewError("servicebus.QueuesClient", "GetAuthorizationRule", err.Error())
}
req, err := client.GetAuthorizationRulePreparer(ctx, resourceGroupName, namespaceName, queueName, authorizationRuleName)
if err != nil {
err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "GetAuthorizationRule", nil, "Failure preparing request")
return
}
resp, err := client.GetAuthorizationRuleSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "GetAuthorizationRule", resp, "Failure sending request")
return
}
result, err = client.GetAuthorizationRuleResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "GetAuthorizationRule", resp, "Failure responding to request")
return
}
return
}
// GetAuthorizationRulePreparer prepares the GetAuthorizationRule request.
func (client QueuesClient) GetAuthorizationRulePreparer(ctx context.Context, resourceGroupName string, namespaceName string, queueName string, authorizationRuleName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"authorizationRuleName": autorest.Encode("path", authorizationRuleName),
"namespaceName": autorest.Encode("path", namespaceName),
"queueName": autorest.Encode("path", queueName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2021-06-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/queues/{queueName}/authorizationRules/{authorizationRuleName}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetAuthorizationRuleSender sends the GetAuthorizationRule request. The method will close the
// http.Response Body if it receives an error.
func (client QueuesClient) GetAuthorizationRuleSender(req *http.Request) (*http.Response, error) {
return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}
// GetAuthorizationRuleResponder handles the response to the GetAuthorizationRule request. The method always
// closes the http.Response Body.
func (client QueuesClient) GetAuthorizationRuleResponder(resp *http.Response) (result SBAuthorizationRule, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// ListAuthorizationRules gets all authorization rules for a queue.
// Parameters:
// resourceGroupName - name of the Resource group within the Azure subscription.
// namespaceName - the namespace name
// queueName - the queue name.
func (client QueuesClient) ListAuthorizationRules(ctx context.Context, resourceGroupName string, namespaceName string, queueName string) (result SBAuthorizationRuleListResultPage, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/QueuesClient.ListAuthorizationRules")
defer func() {
sc := -1
if result.sarlr.Response.Response != nil {
sc = result.sarlr.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
if err := validation.Validate([]validation.Validation{
{TargetValue: resourceGroupName,
Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil},
{Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}},
{TargetValue: namespaceName,
Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil},
{Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}},
{TargetValue: queueName,
Constraints: []validation.Constraint{{Target: "queueName", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil {
return result, validation.NewError("servicebus.QueuesClient", "ListAuthorizationRules", err.Error())
}
result.fn = client.listAuthorizationRulesNextResults
req, err := client.ListAuthorizationRulesPreparer(ctx, resourceGroupName, namespaceName, queueName)
if err != nil {
err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "ListAuthorizationRules", nil, "Failure preparing request")
return
}
resp, err := client.ListAuthorizationRulesSender(req)
if err != nil {
result.sarlr.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "ListAuthorizationRules", resp, "Failure sending request")
return
}
result.sarlr, err = client.ListAuthorizationRulesResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "ListAuthorizationRules", resp, "Failure responding to request")
return
}
if result.sarlr.hasNextLink() && result.sarlr.IsEmpty() {
err = result.NextWithContext(ctx)
return
}
return
}
// ListAuthorizationRulesPreparer prepares the ListAuthorizationRules request.
func (client QueuesClient) ListAuthorizationRulesPreparer(ctx context.Context, resourceGroupName string, namespaceName string, queueName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"namespaceName": autorest.Encode("path", namespaceName),
"queueName": autorest.Encode("path", queueName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2021-06-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/queues/{queueName}/authorizationRules", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListAuthorizationRulesSender sends the ListAuthorizationRules request. The method will close the
// http.Response Body if it receives an error.
func (client QueuesClient) ListAuthorizationRulesSender(req *http.Request) (*http.Response, error) {
return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}
// ListAuthorizationRulesResponder handles the response to the ListAuthorizationRules request. The method always
// closes the http.Response Body.
func (client QueuesClient) ListAuthorizationRulesResponder(resp *http.Response) (result SBAuthorizationRuleListResult, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// listAuthorizationRulesNextResults retrieves the next set of results, if any.
func (client QueuesClient) listAuthorizationRulesNextResults(ctx context.Context, lastResults SBAuthorizationRuleListResult) (result SBAuthorizationRuleListResult, err error) {
req, err := lastResults.sBAuthorizationRuleListResultPreparer(ctx)
if err != nil {
return result, autorest.NewErrorWithError(err, "servicebus.QueuesClient", "listAuthorizationRulesNextResults", nil, "Failure preparing next results request")
}
if req == nil {
return
}
resp, err := client.ListAuthorizationRulesSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "servicebus.QueuesClient", "listAuthorizationRulesNextResults", resp, "Failure sending next results request")
}
result, err = client.ListAuthorizationRulesResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "listAuthorizationRulesNextResults", resp, "Failure responding to next results request")
}
return
}
// ListAuthorizationRulesComplete enumerates all values, automatically crossing page boundaries as required.
func (client QueuesClient) ListAuthorizationRulesComplete(ctx context.Context, resourceGroupName string, namespaceName string, queueName string) (result SBAuthorizationRuleListResultIterator, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/QueuesClient.ListAuthorizationRules")
defer func() {
sc := -1
if result.Response().Response.Response != nil {
sc = result.page.Response().Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
result.page, err = client.ListAuthorizationRules(ctx, resourceGroupName, namespaceName, queueName)
return
}
// ListByNamespace gets the queues within a namespace.
// Parameters:
// resourceGroupName - name of the Resource group within the Azure subscription.
// namespaceName - the namespace name
// skip - skip is only used if a previous operation returned a partial result. If a previous response contains
// a nextLink element, the value of the nextLink element will include a skip parameter that specifies a
// starting point to use for subsequent calls.
// top - may be used to limit the number of results to the most recent N usageDetails.
func (client QueuesClient) ListByNamespace(ctx context.Context, resourceGroupName string, namespaceName string, skip *int32, top *int32) (result SBQueueListResultPage, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/QueuesClient.ListByNamespace")
defer func() {
sc := -1
if result.sqlr.Response.Response != nil {
sc = result.sqlr.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
if err := validation.Validate([]validation.Validation{
{TargetValue: resourceGroupName,
Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil},
{Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}},
{TargetValue: namespaceName,
Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil},
{Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}},
{TargetValue: skip,
Constraints: []validation.Constraint{{Target: "skip", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "skip", Name: validation.InclusiveMaximum, Rule: int64(1000), Chain: nil},
{Target: "skip", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil},
}}}},
{TargetValue: top,
Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMaximum, Rule: int64(1000), Chain: nil},
{Target: "top", Name: validation.InclusiveMinimum, Rule: int64(1), Chain: nil},
}}}}}); err != nil {
return result, validation.NewError("servicebus.QueuesClient", "ListByNamespace", err.Error())
}
result.fn = client.listByNamespaceNextResults
req, err := client.ListByNamespacePreparer(ctx, resourceGroupName, namespaceName, skip, top)
if err != nil {
err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "ListByNamespace", nil, "Failure preparing request")
return
}
resp, err := client.ListByNamespaceSender(req)
if err != nil {
result.sqlr.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "ListByNamespace", resp, "Failure sending request")
return
}
result.sqlr, err = client.ListByNamespaceResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "ListByNamespace", resp, "Failure responding to request")
return
}
if result.sqlr.hasNextLink() && result.sqlr.IsEmpty() {
err = result.NextWithContext(ctx)
return
}
return
}
// ListByNamespacePreparer prepares the ListByNamespace request.
func (client QueuesClient) ListByNamespacePreparer(ctx context.Context, resourceGroupName string, namespaceName string, skip *int32, top *int32) (*http.Request, error) {
pathParameters := map[string]interface{}{
"namespaceName": autorest.Encode("path", namespaceName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2021-06-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
if skip != nil {
queryParameters["$skip"] = autorest.Encode("query", *skip)
}
if top != nil {
queryParameters["$top"] = autorest.Encode("query", *top)
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/queues", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListByNamespaceSender sends the ListByNamespace request. The method will close the
// http.Response Body if it receives an error.
func (client QueuesClient) ListByNamespaceSender(req *http.Request) (*http.Response, error) {
return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}
// ListByNamespaceResponder handles the response to the ListByNamespace request. The method always
// closes the http.Response Body.
func (client QueuesClient) ListByNamespaceResponder(resp *http.Response) (result SBQueueListResult, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// listByNamespaceNextResults retrieves the next set of results, if any.
func (client QueuesClient) listByNamespaceNextResults(ctx context.Context, lastResults SBQueueListResult) (result SBQueueListResult, err error) {
req, err := lastResults.sBQueueListResultPreparer(ctx)<|fim▁hole|> }
if req == nil {
return
}
resp, err := client.ListByNamespaceSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "servicebus.QueuesClient", "listByNamespaceNextResults", resp, "Failure sending next results request")
}
result, err = client.ListByNamespaceResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "listByNamespaceNextResults", resp, "Failure responding to next results request")
}
return
}
// ListByNamespaceComplete enumerates all values, automatically crossing page boundaries as required.
func (client QueuesClient) ListByNamespaceComplete(ctx context.Context, resourceGroupName string, namespaceName string, skip *int32, top *int32) (result SBQueueListResultIterator, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/QueuesClient.ListByNamespace")
defer func() {
sc := -1
if result.Response().Response.Response != nil {
sc = result.page.Response().Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
result.page, err = client.ListByNamespace(ctx, resourceGroupName, namespaceName, skip, top)
return
}
// ListKeys primary and secondary connection strings to the queue.
// Parameters:
// resourceGroupName - name of the Resource group within the Azure subscription.
// namespaceName - the namespace name
// queueName - the queue name.
// authorizationRuleName - the authorization rule name.
func (client QueuesClient) ListKeys(ctx context.Context, resourceGroupName string, namespaceName string, queueName string, authorizationRuleName string) (result AccessKeys, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/QueuesClient.ListKeys")
defer func() {
sc := -1
if result.Response.Response != nil {
sc = result.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
if err := validation.Validate([]validation.Validation{
{TargetValue: resourceGroupName,
Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil},
{Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}},
{TargetValue: namespaceName,
Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil},
{Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}},
{TargetValue: queueName,
Constraints: []validation.Constraint{{Target: "queueName", Name: validation.MinLength, Rule: 1, Chain: nil}}},
{TargetValue: authorizationRuleName,
Constraints: []validation.Constraint{{Target: "authorizationRuleName", Name: validation.MaxLength, Rule: 50, Chain: nil},
{Target: "authorizationRuleName", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil {
return result, validation.NewError("servicebus.QueuesClient", "ListKeys", err.Error())
}
req, err := client.ListKeysPreparer(ctx, resourceGroupName, namespaceName, queueName, authorizationRuleName)
if err != nil {
err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "ListKeys", nil, "Failure preparing request")
return
}
resp, err := client.ListKeysSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "ListKeys", resp, "Failure sending request")
return
}
result, err = client.ListKeysResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "ListKeys", resp, "Failure responding to request")
return
}
return
}
// ListKeysPreparer prepares the ListKeys request.
func (client QueuesClient) ListKeysPreparer(ctx context.Context, resourceGroupName string, namespaceName string, queueName string, authorizationRuleName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"authorizationRuleName": autorest.Encode("path", authorizationRuleName),
"namespaceName": autorest.Encode("path", namespaceName),
"queueName": autorest.Encode("path", queueName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2021-06-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsPost(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/queues/{queueName}/authorizationRules/{authorizationRuleName}/ListKeys", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListKeysSender sends the ListKeys request. The method will close the
// http.Response Body if it receives an error.
func (client QueuesClient) ListKeysSender(req *http.Request) (*http.Response, error) {
return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}
// ListKeysResponder handles the response to the ListKeys request. The method always
// closes the http.Response Body.
func (client QueuesClient) ListKeysResponder(resp *http.Response) (result AccessKeys, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// RegenerateKeys regenerates the primary or secondary connection strings to the queue.
// Parameters:
// resourceGroupName - name of the Resource group within the Azure subscription.
// namespaceName - the namespace name
// queueName - the queue name.
// authorizationRuleName - the authorization rule name.
// parameters - parameters supplied to regenerate the authorization rule.
func (client QueuesClient) RegenerateKeys(ctx context.Context, resourceGroupName string, namespaceName string, queueName string, authorizationRuleName string, parameters RegenerateAccessKeyParameters) (result AccessKeys, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/QueuesClient.RegenerateKeys")
defer func() {
sc := -1
if result.Response.Response != nil {
sc = result.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
if err := validation.Validate([]validation.Validation{
{TargetValue: resourceGroupName,
Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil},
{Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}},
{TargetValue: namespaceName,
Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil},
{Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}},
{TargetValue: queueName,
Constraints: []validation.Constraint{{Target: "queueName", Name: validation.MinLength, Rule: 1, Chain: nil}}},
{TargetValue: authorizationRuleName,
Constraints: []validation.Constraint{{Target: "authorizationRuleName", Name: validation.MaxLength, Rule: 50, Chain: nil},
{Target: "authorizationRuleName", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil {
return result, validation.NewError("servicebus.QueuesClient", "RegenerateKeys", err.Error())
}
req, err := client.RegenerateKeysPreparer(ctx, resourceGroupName, namespaceName, queueName, authorizationRuleName, parameters)
if err != nil {
err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "RegenerateKeys", nil, "Failure preparing request")
return
}
resp, err := client.RegenerateKeysSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "RegenerateKeys", resp, "Failure sending request")
return
}
result, err = client.RegenerateKeysResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "RegenerateKeys", resp, "Failure responding to request")
return
}
return
}
// RegenerateKeysPreparer prepares the RegenerateKeys request.
func (client QueuesClient) RegenerateKeysPreparer(ctx context.Context, resourceGroupName string, namespaceName string, queueName string, authorizationRuleName string, parameters RegenerateAccessKeyParameters) (*http.Request, error) {
pathParameters := map[string]interface{}{
"authorizationRuleName": autorest.Encode("path", authorizationRuleName),
"namespaceName": autorest.Encode("path", namespaceName),
"queueName": autorest.Encode("path", queueName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2021-06-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsContentType("application/json; charset=utf-8"),
autorest.AsPost(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/queues/{queueName}/authorizationRules/{authorizationRuleName}/regenerateKeys", pathParameters),
autorest.WithJSON(parameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// RegenerateKeysSender sends the RegenerateKeys request. The method will close the
// http.Response Body if it receives an error.
func (client QueuesClient) RegenerateKeysSender(req *http.Request) (*http.Response, error) {
return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}
// RegenerateKeysResponder handles the response to the RegenerateKeys request. The method always
// closes the http.Response Body.
func (client QueuesClient) RegenerateKeysResponder(resp *http.Response) (result AccessKeys, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}<|fim▁end|>
|
if err != nil {
return result, autorest.NewErrorWithError(err, "servicebus.QueuesClient", "listByNamespaceNextResults", nil, "Failure preparing next results request")
|
<|file_name|>simple.cost.import.setup.ts<|end_file_name|><|fim▁begin|>import {Component, OnInit, ElementRef,} from '@angular/core';
import {FileSelect} from './file.select';
import {NgIf} from '@angular/common';
import {NgForm} from '@angular/common';
import {CostImport, CostImportService} from '../../../services/cost-import-service';
import {FourcastService} from '../../../services/fourcast-service';
import {FileUploader} from './file-uploader';
import {FileItem} from './file-uploader';
const TEMPLATE: string = require('./simple.import.setup.html');
const URL = 'http://127.0.0.1:8081/rest/$upload';
@Component({
selector: 'simple-demo',
template: TEMPLATE,
directives: [FileSelect],
styles: [`
.active {
background-color: red;
}
.disabled {
color: gray;
border: medium solid gray;
}
`],
providers: [FileUploader, CostImportService, FourcastService]
})
export class SimpleCostImportSetup implements OnInit {
isOn = true;
isDisabled = false;
importId: string;
private _file: File;
public isUploaded: boolean = false;
constructor( uploader: FileUploader, public importService: CostImportService){}
public isFileSelected: boolean = false;
typeNames = CostImport.typeNames;
model: CostImport = new CostImport();
ngOnInit(){
this.model.division = ''
}
onFileSelected(event){
console.log('File selected', event);
this._file = event['file'];
this.isFileSelected = true
this.model.importFileName = this._file.name;
//console.log('File selected 2: ', this.model.importFileName)
}
updateCostImport(fileId:string){
console.log('FileId (update): ', fileId)
this.importService.updateCostImportHdr(this.model, fileId)
.subscribe((res) =>{
var temp = JSON.stringify(res);
console.log("Update cost import header result: ",res);
this.importId = res['id'];
this.isUploaded = true;
//console.log('File content: ', text);
});
}
processCostImport(importId:string){
}
onImportFileClicked(){
console.log("Button clicked");
let uploader = new FileUploader();
uploader.uploadFile(this._file);
uploader.emitter.subscribe((data) => {
console.log("Upload event: ", data);
let response = JSON.parse(data['response']);
let fileId = response['ID'];
console.log('FileId (clicked): ', fileId)
this.updateCostImport(fileId);
});
//this.uploadFile(this._file);
}
onImportTypeChange(event){<|fim▁hole|> switch (true){
case event.target[0].selected:
this.model.isSupplierInvoices = true;
break;
case event.target[1].selected:
this.model.isPayrollWeekly = true;
break;
case event.target[2].selected:
this.model.isPayrollMonthly = true;
break;
}
}
testUpdate(){
let url:string = "http://127.0.0.1:8081/processImport";
let xhr=new XMLHttpRequest();
let formdata=new FormData();
formdata.append('ID',this.importId);
xhr.addEventListener("load", function (evt) {
let responseStr = evt.currentTarget['response'];
let res = JSON.parse(responseStr);
let id = res['ID'];
console.log("Response: ", res['ID']);
nextStep(id);
})
xhr.open('POST', url, true);
xhr.send(formdata);
function nextStep(id: string){
let url:string = "http://127.0.0.1:8081/processData";
let xhr=new XMLHttpRequest();
let formdata=new FormData();
formdata.append('ID',id);
xhr.addEventListener("load", function (evt) {
console.log(evt);
})
xhr.open('POST', url, true);
xhr.send(formdata);
}
}
}<|fim▁end|>
|
this.model.isSupplierInvoices = false;
this.model.isPayrollWeekly = false;
this.model.isPayrollMonthly = false;
|
<|file_name|>bitcoin_cmn.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" ?><!DOCTYPE TS><TS language="cmn" version="2.0">
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About Horuscoin Core</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+39"/>
<source><b>Horuscoin Core</b> version</source>
<translation type="unfinished"/>
</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="../utilitydialog.cpp" line="+29"/>
<source>Copyright</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The Horuscoin Core developers</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+30"/>
<source>Double-click to edit address or label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&New</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Copy</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+52"/>
<source>C&lose</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+74"/>
<source>&Copy Address</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="-41"/>
<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 type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-27"/>
<source>&Delete</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../addressbookpage.cpp" line="-30"/>
<source>Choose the address to send coins to</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Choose the address to receive coins with</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>C&hoose</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>sending addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>receiving addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>These are your Horuscoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>These are your Horuscoin addresses for receiving payments. It is recommended to use a new receiving address for each transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Copy &Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>&Edit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+194"/>
<source>Export Address List</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Exporting Failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>There was an error trying to save the address list to %1.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+168"/>
<source>Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+40"/>
<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 type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR HORUSCOINS</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 type="unfinished"/>
</message>
<message>
<location line="-56"/>
<source>Horuscoin Core will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your Horuscoins from being stolen by malware infecting your computer.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+42"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-54"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<location line="+48"/>
<source>The supplied passphrases do not match.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-37"/>
<source>Wallet unlock failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<location line="+11"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation type="unfinished"/>
</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="+295"/>
<source>Sign &message...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+335"/>
<source>Synchronizing with network...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-407"/>
<source>&Overview</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-137"/>
<source>Node</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+138"/>
<source>Show general overview of wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>&Transactions</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>E&xit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Show information about Horuscoin Core</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<location line="+2"/>
<source>About &Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Show information about Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>&Encrypt Wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>&Sending addresses...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>&Receiving addresses...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Open &URI...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+325"/>
<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="-405"/>
<source>Send coins to a Horuscoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>Modify configuration options for Horuscoin Core</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Backup wallet to another location</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation type="unfinished"/>
</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="+430"/>
<source>Horuscoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-643"/>
<source>Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+146"/>
<source>&Send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Receive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+46"/>
<location line="+2"/>
<source>&Show / Hide</source>
<translation type="unfinished"/>
</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 Horuscoin 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 Horuscoin addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+48"/>
<source>&File</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>&Settings</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>&Help</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Tabs toolbar</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-284"/>
<location line="+376"/>
<source>[testnet]</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-401"/>
<source>Horuscoin Core</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+163"/>
<source>Request payments (generates QR codes and horuscoin: URIs)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<location line="+2"/>
<source>&About Horuscoin Core</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Show the list of used sending addresses and labels</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Show the list of used receiving addresses and labels</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Open a horuscoin: URI or payment request</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>&Command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show the Horuscoin Core help message to get a list with possible Horuscoin Core command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+159"/>
<location line="+5"/>
<source>Horuscoin client</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+142"/>
<source>%n active connection(s) to Horuscoin network</source>
<translation type="unfinished"><numerusform></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="+23"/>
<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="+21"/>
<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="+27"/>
<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="-85"/>
<source>Up to date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+34"/>
<source>Catching up...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+130"/>
<source>Sent transaction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Incoming transaction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+69"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoin.cpp" line="+438"/>
<source>A fatal error occurred. Horuscoin Core can no longer continue safely and will quit.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+119"/>
<source>Network Alert</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<location filename="../forms/coincontroldialog.ui" line="+14"/>
<source>Coin Control Address Selection</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+34"/>
<source>Quantity:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Bytes:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+45"/>
<source>Amount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Priority:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+45"/>
<source>Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>Low Output:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+48"/>
<source>After Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>Change:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+63"/>
<source>(un)select all</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Tree mode</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>List mode</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+52"/>
<source>Amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Confirmations</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Confirmed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Priority</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="+42"/>
<source>Copy address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<location line="+26"/>
<source>Copy amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-25"/>
<source>Copy transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Lock unspent</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Unlock unspent</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>Copy quantity</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Copy fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+323"/>
<source>highest</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>higher</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>high</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>medium-high</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>medium</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>low-medium</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>low</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>lower</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>lowest</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>(%1 locked)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>none</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+140"/>
<source>Dust</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>yes</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>no</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>This label turns red, if the transaction size is greater than 1000 bytes.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<location line="+5"/>
<source>This means a fee of at least %1 per kB is required.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-4"/>
<source>Can vary +/- 1 byte per input.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Transactions with higher priority are more likely to get included into a block.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if the priority is smaller than "medium".</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>This label turns red, if any recipient receives an amount smaller than %1.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<location line="+4"/>
<source>This means a fee of at least %1 is required.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-3"/>
<source>Amounts below 0.546 times the minimum relay fee are shown as dust.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>This label turns red, if the change is smaller than %1.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+43"/>
<location line="+66"/>
<source>(no label)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-9"/>
<source>change from %1 (%2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>(change)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address list entry</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>The address associated with this address list entry. This can only be modified for sending addresses.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-10"/>
<source>&Address</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+28"/>
<source>New receiving address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid Horuscoin address.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>FreespaceChecker</name>
<message>
<location filename="../intro.cpp" line="+65"/>
<source>A new data directory will be created.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>name</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Directory already exists. Add %1 if you intend to create a new directory here.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Path already exists, and is not a directory.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Cannot create data directory here.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>HelpMessageDialog</name>
<message>
<location filename="../forms/helpmessagedialog.ui" line="+19"/>
<source>Horuscoin Core - Command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../utilitydialog.cpp" line="+38"/>
<source>Horuscoin Core</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "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>
<message>
<location line="+1"/>
<source>Choose data directory on startup (default: 0)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>Intro</name>
<message>
<location filename="../forms/intro.ui" line="+14"/>
<source>Welcome</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Welcome to Horuscoin Core.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+26"/>
<source>As this is the first time the program is launched, you can choose where Horuscoin Core will store its data.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Horuscoin Core will download and store a copy of the Horuscoin block chain. At least %1GB of data will be stored in this directory, and it will grow over time. The wallet will also be stored in this directory.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Use the default data directory</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Use a custom data directory:</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../intro.cpp" line="+85"/>
<source>Horuscoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: Specified data directory "%1" can not be created.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Error</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>GB of free space available</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>(of %1GB needed)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OpenURIDialog</name>
<message>
<location filename="../forms/openuridialog.ui" line="+14"/>
<source>Open URI</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Open payment request from URI or file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>URI:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Select payment request file</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../openuridialog.cpp" line="+47"/>
<source>Select payment request file to open</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<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 Horuscoin Core after logging in to the system.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Start Horuscoin Core on system login</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Size of &database cache</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>MB</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Number of script &verification threads</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<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="+58"/>
<source>Connect to the Horuscoin network through a SOCKS proxy.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy (default proxy):</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+34"/>
<source>IP address of the proxy (e.g. IPv4: 127.0.0.1 / IPv6: ::1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+224"/>
<source>Active command-line options that override above options:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+43"/>
<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="-323"/>
<source>&Network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Automatically open the Horuscoin 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="+19"/>
<source>Proxy &IP:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>&Port:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<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 Horuscoin Core.</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 Horuscoin addresses in the transaction list or not.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Whether to show coin control features or not.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Display coin &control features (experts only)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+136"/>
<source>&OK</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+67"/>
<source>default</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+57"/>
<source>none</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+75"/>
<source>Confirm options reset</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<location line="+29"/>
<source>Client restart required to activate changes.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-29"/>
<source>Client will be shutdown, do you want to proceed?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+33"/>
<source>This change would require a client restart.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+34"/>
<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 type="unfinished"/>
</message>
<message>
<location line="+50"/>
<location line="+231"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the Horuscoin network after a connection is established, but this process has not completed yet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-155"/>
<source>Unconfirmed:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-83"/>
<source>Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+51"/>
<source>Confirmed:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Your current spendable balance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the spendable balance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<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="+16"/>
<source>Total:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Your current total balance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source><b>Recent transactions</b></source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../overviewpage.cpp" line="+120"/>
<location line="+1"/>
<source>out of sync</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+403"/>
<location line="+13"/>
<source>URI handling</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>URI can not be parsed! This can be caused by an invalid Horuscoin address or malformed URI parameters.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+96"/>
<source>Requested payment amount of %1 is too small (considered dust).</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-221"/>
<location line="+212"/>
<location line="+13"/>
<location line="+95"/>
<location line="+18"/>
<location line="+16"/>
<source>Payment request error</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-353"/>
<source>Cannot start horuscoin: click-to-pay handler</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+58"/>
<source>Net manager warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Your active proxy doesn't support SOCKS5, which is required for payment requests via proxy.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+52"/>
<source>Payment request fetch URL is invalid: %1</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Payment request file handling</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Payment request file can not be read or processed! This can be caused by an invalid payment request file.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+73"/>
<source>Unverified payment requests to custom payment scripts are unsupported.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>Refund from %1</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+43"/>
<source>Error communicating with %1: %2</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>Payment request can not be parsed or processed!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Bad response from server %1</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+33"/>
<source>Payment acknowledged</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-11"/>
<source>Network request error</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>QObject</name>
<message>
<location filename="../bitcoin.cpp" line="+71"/>
<location line="+11"/>
<source>Horuscoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: Specified data directory "%1" does not exist.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-12"/>
<source>Error: Invalid combination of -regtest and -testnet.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../guiutil.cpp" line="+82"/>
<source>Enter a Horuscoin address (e.g. DJ7zB7c5BsB9UJLy1rKQtY7c6CQfGiaRLM)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>QRImageWidget</name>
<message>
<location filename="../receiverequestdialog.cpp" line="+36"/>
<source>&Save Image...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Copy Image</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Save QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>PNG Image (*.png)</source>
<translation type="unfinished"/>
</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="+23"/>
<location line="+36"/>
<location line="+23"/>
<location line="+23"/>
<location filename="../rpcconsole.cpp" line="+359"/>
<source>N/A</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-223"/>
<source>Client version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-10"/>
<source>Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>General</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+53"/>
<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>Name</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Number of connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<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="+24"/>
<source>&Console</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+72"/>
<source>&Network Traffic</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+52"/>
<source>&Clear</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Totals</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+64"/>
<source>In:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+80"/>
<source>Out:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-521"/>
<source>Build date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+206"/>
<source>Debug log file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Open the Horuscoin Core 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="+76"/>
<source>Clear console</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-30"/>
<source>Welcome to the Horuscoin Core RPC console.</source>
<translation type="unfinished"/>
</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>
<message>
<location line="+122"/>
<source>%1 B</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1 KB</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1 MB</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1 GB</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>%1 m</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>%1 h</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1 h %2 m</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ReceiveCoinsDialog</name>
<message>
<location filename="../forms/receivecoinsdialog.ui" line="+107"/>
<source>&Amount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-16"/>
<source>&Label:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-37"/>
<source>&Message:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-20"/>
<source>Reuse one of the previously used receiving addresses. Reusing addresses has security and privacy issues. Do not use this unless re-generating a payment request made before.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>R&euse an existing receiving address (not recommended)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<location line="+23"/>
<source>An optional message to attach to the payment request, which will be displayed when the request is opened. Note: The message will not be sent with the payment over the Horuscoin network.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-7"/>
<location line="+21"/>
<source>An optional label to associate with the new receiving address.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-7"/>
<source>Use this form to request payments. All fields are <b>optional</b>.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<location line="+22"/>
<source>An optional amount to request. Leave this empty or zero to not request a specific amount.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>Clear all fields of the form.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Clear</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+78"/>
<source>Requested payments history</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-98"/>
<source>&Request payment</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+120"/>
<source>Show the selected request (does the same as double clicking an entry)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Show</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Remove the selected entries from the list</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Remove</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../receivecoinsdialog.cpp" line="+38"/>
<source>Copy label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ReceiveRequestDialog</name>
<message>
<location filename="../forms/receiverequestdialog.ui" line="+29"/>
<source>QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+46"/>
<source>Copy &URI</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Copy &Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Save Image...</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../receiverequestdialog.cpp" line="+56"/>
<source>Request payment to %1</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Payment information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>URI</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error encoding URI into QR Code.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>RecentRequestsTableModel</name>
<message>
<location filename="../recentrequeststablemodel.cpp" line="+24"/>
<source>Date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+38"/>
<source>(no label)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>(no message)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>(no amount)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+380"/>
<location line="+80"/>
<source>Send Coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+76"/>
<source>Coin Control Features</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>Inputs...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>automatically selected</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Insufficient funds!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+89"/>
<source>Quantity:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Bytes:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+48"/>
<source>Amount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>Priority:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+48"/>
<source>Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>Low Output:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+48"/>
<source>After Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>Change:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+44"/>
<source>If this is activated, but the change address is empty or invalid, change will be sent to a newly generated address.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Custom change address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+164"/>
<source>Send to multiple recipients at once</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-23"/>
<source>Clear all fields of the form.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+52"/>
<source>Balance:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-78"/>
<source>Confirm the send action</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-229"/>
<source>Confirm send coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-74"/>
<location line="+5"/>
<location line="+5"/>
<location line="+4"/>
<source>%1 to %2</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-121"/>
<source>Copy quantity</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+170"/>
<source>Total Amount %1 (= %2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>or</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+203"/>
<source>The recipient address is not valid, please recheck.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>The amount to pay must be larger than 0.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>The amount exceeds your balance.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Transaction creation failed!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>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="+113"/>
<source>Warning: Invalid Horuscoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>(no label)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-11"/>
<source>Warning: Unknown change address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-367"/>
<source>Are you sure you want to send?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>added as transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+171"/>
<source>Payment request expired</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Invalid payment address %1</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+131"/>
<location line="+521"/>
<location line="+536"/>
<source>A&mount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1152"/>
<source>Pay &To:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>The address to send the payment to (e.g. DJ7zB7c5BsB9UJLy1rKQtY7c6CQfGiaRLM)</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+30"/>
<source>Enter a label for this address to add it to your address book</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+57"/>
<source>&Label:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-50"/>
<source>Choose previously used address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-40"/>
<source>This is a normal payment.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+50"/>
<source>Alt+A</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<location line="+524"/>
<location line="+536"/>
<source>Remove this entry</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1008"/>
<source>Message:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+968"/><|fim▁hole|> <message>
<location line="-991"/>
<source>Enter a label for this address to add it to the list of used addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+33"/>
<source>A message that was attached to the horuscoin: URI which will be stored with the transaction for your reference. Note: This message will not be sent over the Horuscoin network.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+426"/>
<source>This is an unverified payment request.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<location line="+532"/>
<source>Pay To:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-498"/>
<location line="+536"/>
<source>Memo:</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ShutdownWindow</name>
<message>
<location filename="../utilitydialog.cpp" line="+48"/>
<source>Horuscoin Core is shutting down...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Do not shut down the computer until this window disappears.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>&Sign Message</source>
<translation type="unfinished"/>
</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. DJ7zB7c5BsB9UJLy1rKQtY7c6CQfGiaRLM)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<location line="+210"/>
<source>Choose previously used address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-200"/>
<location line="+210"/>
<source>Alt+A</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-200"/>
<source>Paste address from clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation type="unfinished"/>
</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 Horuscoin 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="+143"/>
<source>Clear &All</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-84"/>
<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. DJ7zB7c5BsB9UJLy1rKQtY7c6CQfGiaRLM)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<source>Verify the message to ensure it was signed with the specified Horuscoin 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="+30"/>
<source>Enter a Horuscoin address (e.g. DJ7zB7c5BsB9UJLy1rKQtY7c6CQfGiaRLM)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Click "Sign Message" to generate signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+84"/>
<location line="+80"/>
<source>The entered address is invalid.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-80"/>
<location line="+8"/>
<location line="+72"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-80"/>
<location line="+80"/>
<source>The entered address does not refer to a key.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-72"/>
<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="+58"/>
<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="+28"/>
<source>Horuscoin Core</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>The Horuscoin Core developers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>[testnet]</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TrafficGraphWidget</name>
<message>
<location filename="../trafficgraphwidget.cpp" line="+79"/>
<source>KB/s</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+28"/>
<source>Open until %1</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>%1/offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+53"/>
<source>Credit</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="-125"/>
<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="+53"/>
<source>Debit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-62"/>
<source>Transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<location line="+9"/>
<source>Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-7"/>
<source>Comment</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>Merchant</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Generated coins must mature %1 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="+8"/>
<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 type="unfinished"/>
</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="-232"/>
<source>, has not been successfully broadcast yet</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+234"/>
<source>Date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>Immature (%1 confirmations, will be available after %2)</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+16"/>
<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 type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Offline (%1 confirmations)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-22"/>
<location line="+25"/>
<source>Confirmed (%1 confirmations)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-22"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+62"/>
<source>Received with</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+199"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+57"/>
<location line="+16"/>
<source>All</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Enter address or label to search</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Min amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+142"/>
<source>Export Transaction History</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Exporting Failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the transaction history to %1.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Exporting Successful</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The transaction history was successfully saved to %1.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-22"/>
<source>Comma separated file (*.csv)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Confirmed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+107"/>
<source>Range:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>WalletFrame</name>
<message>
<location filename="../walletframe.cpp" line="+26"/>
<source>No wallet has been loaded.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+245"/>
<source>Send Coins</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<location filename="../walletview.cpp" line="+43"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Export the data in the current tab to a file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+181"/>
<source>Backup Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Wallet Data (*.dat)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Backup Failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to %1.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>The wallet data was successfully saved to %1.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Backup Successful</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>horuscoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+221"/>
<source>Usage:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-54"/>
<source>List commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-14"/>
<source>Get help for a command</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+26"/>
<source>Options:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>Specify configuration file (default: horuscoin.conf)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Specify pid file (default: horuscoind.pid)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-9"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-26"/>
<source>Listen for connections on <port> (default: 22556 or testnet: 44556)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-51"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+84"/>
<source>Specify your own public address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-148"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-36"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+34"/>
<source>Listen for JSON-RPC connections on <port> (default: 22555 or testnet: 44555)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+45"/>
<source>Accept command line and JSON-RPC commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+80"/>
<source>Run in the background as a daemon and accept commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+39"/>
<source>Use the test network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-118"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-95"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=horuscoinrpc
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 "Horuscoin Alert" [email protected]
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Acceptable ciphers (default: TLSv1.2+HIGH:TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<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. Horuscoin Core is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Enter regression test mode, which uses a special chain in which blocks can be solved instantly. This is intended for regression testing tools and app development.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Enter regression test mode, which uses a special chain in which blocks can be solved instantly.</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="+6"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<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>Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: -proxy)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<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: Please check that your computer's date and time are correct! If your clock is wrong Horuscoin Core will not work properly.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade.</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="+9"/>
<source><category> can be:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Horuscoin Core Daemon</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Horuscoin Core RPC client version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<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="+1"/>
<source>Connect through SOCKS proxy</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Connect to JSON-RPC on <port> (default: 22555 or testnet: 44555)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<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 not load the wallet and disable wallet RPC calls</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="+1"/>
<source>Fee per kB to add to transactions you send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<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="+1"/>
<source>If <category> is not supplied, output all debugging information.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Incorrect or no genesis block found. Wrong datadir for network?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Invalid -onion address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Not enough file descriptors available.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Prepend debug output with timestamp (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>RPC client options:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Rebuild block chain index from current blk000??.dat files</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Select SOCKS version for -proxy (4 or 5, default: 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Send command to Horuscoin Core server</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Set maximum block size in bytes (default: %d)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Specify wallet file (within data directory)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Start Horuscoin Core server</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>This is intended for regression testing tools and app development.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Usage (deprecated, use horuscoin-cli):</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Verifying blocks...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Verifying wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Wait for RPC server to start</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Wallet %s resides outside data directory %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Wallet options:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Warning: Deprecated argument -debugnet ignored, use -debug=net</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>You need to rebuild the database using -reindex to change -txindex</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-79"/>
<source>Imports blocks from external blk000??.dat file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-105"/>
<source>Execute command when a relevant alert is received or we see a really long fork (%s in cmd is replaced by message)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Output debugging information (default: 0, supplying <category> is optional)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: %d)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<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="+89"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<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="+9"/>
<source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<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 type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>System error: </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<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="+8"/>
<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="+2"/>
<source>Username for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-58"/>
<source>Password for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-70"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+80"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-132"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+161"/>
<source>Upgrade wallet to latest format</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-24"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-11"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+38"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-30"/>
<source>Server certificate file (default: server.cert)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>This help message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-107"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+60"/>
<source>Loading addresses...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-37"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat: Wallet requires newer version of Horuscoin Core</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+98"/>
<source>Wallet needed to be rewritten: restart Horuscoin Core to complete</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-100"/>
<source>Error loading wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<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="-101"/>
<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="+48"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-6"/>
<source>Insufficient funds</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Loading block index...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-62"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-32"/>
<source>Unable to bind to %s on this computer. Horuscoin Core is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+95"/>
<source>Loading wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-56"/>
<source>Cannot downgrade wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Cannot write default address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+67"/>
<source>Rescanning...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-58"/>
<source>Done loading</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+85"/>
<source>To use the %s option</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-77"/>
<source>Error</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-35"/>
<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 type="unfinished"/>
</message>
</context>
</TS><|fim▁end|>
|
<source>This is a verified payment request.</source>
<translation type="unfinished"/>
</message>
|
<|file_name|>StreamCalcKryoTest.java<|end_file_name|><|fim▁begin|>package statzall.codec;
import static org.junit.Assert.*;
import org.junit.Test;
import statzall.Cast;
import statzall.StreamCalc;
import statzall.codec.StreamCalcKryo;
<|fim▁hole|> @Test
public void test() {
StreamCalc calc = new StreamCalc(10, 10);
StreamCalcKryo target = new StreamCalcKryo();
calc.add(1D, 2D, 3D, 4D, 5D, 6D, 7D, 8D, 9D);
byte[] buff = target.write(calc);
StreamCalc read = target.read(buff);
assertEquals(9.0D, Cast.as(read.snapshot().get("q009"), Double.class), 0.0D);
}
}<|fim▁end|>
|
public class StreamCalcKryoTest {
|
<|file_name|>exec_unix.go<|end_file_name|><|fim▁begin|>//go:build !windows
// +build !windows<|fim▁hole|>import (
"log"
"os/exec"
"syscall"
"time"
)
// KillGrace is the amount of time we allow a process to shutdown before
// sending a SIGKILL.
const KillGrace = 5 * time.Second
// WaitTimeout waits for the given command to finish with a timeout.
// It assumes the command has already been started.
// If the command times out, it attempts to kill the process.
func WaitTimeout(c *exec.Cmd, timeout time.Duration) error {
var kill *time.Timer
term := time.AfterFunc(timeout, func() {
err := c.Process.Signal(syscall.SIGTERM)
if err != nil {
log.Printf("E! [agent] Error terminating process: %s", err)
return
}
kill = time.AfterFunc(KillGrace, func() {
err := c.Process.Kill()
if err != nil {
log.Printf("E! [agent] Error killing process: %s", err)
return
}
})
})
err := c.Wait()
// Shutdown all timers
if kill != nil {
kill.Stop()
}
termSent := !term.Stop()
// If the process exited without error treat it as success. This allows a
// process to do a clean shutdown on signal.
if err == nil {
return nil
}
// If SIGTERM was sent then treat any process error as a timeout.
if termSent {
return ErrTimeout
}
// Otherwise there was an error unrelated to termination.
return err
}<|fim▁end|>
|
package internal
|
<|file_name|>grid.inlinedit.js<|end_file_name|><|fim▁begin|>;(function($){
/**
* jqGrid extension for manipulating Grid Data
* Tony Tomov [email protected]
* http://trirand.com/blog/
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl-2.0.html
**/
//jsHint options
/*global alert, $, jQuery */
"use strict";
$.jgrid.inlineEdit = $.jgrid.inlineEdit || {};
$.jgrid.extend({
//Editing
editRow : function(rowid,keys,oneditfunc,successfunc, url, extraparam, aftersavefunc,errorfunc, afterrestorefunc) {
// Compatible mode old versions
var o={}, args = $.makeArray(arguments).slice(1);
if( $.type(args[0]) === "object" ) {
o = args[0];
} else {
if (typeof keys !== "undefined") { o.keys = keys; }
if ($.isFunction(oneditfunc)) { o.oneditfunc = oneditfunc; }
if ($.isFunction(successfunc)) { o.successfunc = successfunc; }
if (typeof url !== "undefined") { o.url = url; }
if (typeof extraparam !== "undefined") { o.extraparam = extraparam; }
if ($.isFunction(aftersavefunc)) { o.aftersavefunc = aftersavefunc; }
if ($.isFunction(errorfunc)) { o.errorfunc = errorfunc; }
if ($.isFunction(afterrestorefunc)) { o.afterrestorefunc = afterrestorefunc; }
// last two not as param, but as object (sorry)
//if (typeof restoreAfterError !== "undefined") { o.restoreAfterError = restoreAfterError; }
//if (typeof mtype !== "undefined") { o.mtype = mtype || "POST"; }
}
o = $.extend(true, {
keys : false,
oneditfunc: null,
successfunc: null,
url: null,
extraparam: {},
aftersavefunc: null,
errorfunc: null,
afterrestorefunc: null,
restoreAfterError: true,
mtype: "POST"
}, $.jgrid.inlineEdit, o );
// End compatible
return this.each(function(){
var $t = this, nm, tmp, editable, cnt=0, focus=null, svr={}, ind,cm;
if (!$t.grid ) { return; }
ind = $($t).jqGrid("getInd",rowid,true);
if( ind === false ) {return;}
editable = $(ind).attr("editable") || "0";
if (editable == "0" && !$(ind).hasClass("not-editable-row")) {
cm = $t.p.colModel;
$('td[role="gridcell"]',ind).each( function(i) {
nm = cm[i].name;
var treeg = $t.p.treeGrid===true && nm == $t.p.ExpandColumn;
if(treeg) { tmp = $("span:first",this).html();}
else {
try {
tmp = $.unformat.call($t,this,{rowId:rowid, colModel:cm[i]},i);
} catch (_) {
tmp = ( cm[i].edittype && cm[i].edittype == 'textarea' ) ? $(this).text() : $(this).html();
}
}
if ( nm != 'cb' && nm != 'subgrid' && nm != 'rn') {
if($t.p.autoencode) { tmp = $.jgrid.htmlDecode(tmp); }
svr[nm]=tmp;
if(cm[i].editable===true) {
if(focus===null) { focus = i; }
if (treeg) { $("span:first",this).html(""); }
else { $(this).html(""); }
var opt = $.extend({},cm[i].editoptions || {},{id:rowid+"_"+nm,name:nm});
if(!cm[i].edittype) { cm[i].edittype = "text"; }
if(tmp == " " || tmp == " " || (tmp.length==1 && tmp.charCodeAt(0)==160) ) {tmp='';}
var elc = $.jgrid.createEl.call($t,cm[i].edittype,opt,tmp,true,$.extend({},$.jgrid.ajaxOptions,$t.p.ajaxSelectOptions || {}));
$(elc).addClass("editable");
if(treeg) { $("span:first",this).append(elc); }
else { $(this).append(elc); }
//Again IE
if(cm[i].edittype == "select" && typeof(cm[i].editoptions)!=="undefined" && cm[i].editoptions.multiple===true && typeof(cm[i].editoptions.dataUrl)==="undefined" && $.browser.msie) {
$(elc).width($(elc).width());
}
cnt++;
}
}
});
if(cnt > 0) {
svr.id = rowid; $t.p.savedRow.push(svr);
$(ind).attr("editable","1");
$("td:eq("+focus+") input",ind).focus();
if(o.keys===true) {
$(ind).bind("keydown",function(e) {
if (e.keyCode === 27) {
$($t).jqGrid("restoreRow",rowid, o.afterrestorefunc);
if($t.p._inlinenav) {
try {
$($t).jqGrid('showAddEditButtons');
} catch (eer1) {}
}
return false;
}
if (e.keyCode === 13) {
var ta = e.target;
if(ta.tagName == 'TEXTAREA') { return true; }
if( $($t).jqGrid("saveRow", rowid, o ) ) {
if($t.p._inlinenav) {
try {
$($t).jqGrid('showAddEditButtons');
} catch (eer2) {}
}
}
return false;
}
});
}
$($t).triggerHandler("jqGridInlineEditRow", [rowid, o]);
if( $.isFunction(o.oneditfunc)) { o.oneditfunc.call($t, rowid); }
}
}
});
},
saveRow : function(rowid, successfunc, url, extraparam, aftersavefunc,errorfunc, afterrestorefunc) {
// Compatible mode old versions
var args = $.makeArray(arguments).slice(1), o = {};
if( $.type(args[0]) === "object" ) {
o = args[0];
} else {
if ($.isFunction(successfunc)) { o.successfunc = successfunc; }
if (typeof url !== "undefined") { o.url = url; }
if (typeof extraparam !== "undefined") { o.extraparam = extraparam; }
if ($.isFunction(aftersavefunc)) { o.aftersavefunc = aftersavefunc; }
if ($.isFunction(errorfunc)) { o.errorfunc = errorfunc; }
if ($.isFunction(afterrestorefunc)) { o.afterrestorefunc = afterrestorefunc; }
}
o = $.extend(true, {
successfunc: null,
url: null,
extraparam: {},
aftersavefunc: null,
errorfunc: null,
afterrestorefunc: null,
restoreAfterError: true,
mtype: "POST"
}, $.jgrid.inlineEdit, o );
// End compatible
var success = false;
var $t = this[0], nm, tmp={}, tmp2={}, tmp3= {}, editable, fr, cv, ind;
if (!$t.grid ) { return success; }
ind = $($t).jqGrid("getInd",rowid,true);
if(ind === false) {return success;}
editable = $(ind).attr("editable");
o.url = o.url ? o.url : $t.p.editurl;
if (editable==="1") {
var cm;
$('td[role="gridcell"]',ind).each(function(i) {
cm = $t.p.colModel[i];
nm = cm.name;
if ( nm != 'cb' && nm != 'subgrid' && cm.editable===true && nm != 'rn' && !$(this).hasClass('not-editable-cell')) {
switch (cm.edittype) {
case "checkbox":
var cbv = ["Yes","No"];
if(cm.editoptions ) {
cbv = cm.editoptions.value.split(":");
}
tmp[nm]= $("input",this).is(":checked") ? cbv[0] : cbv[1];
break;
case 'text':
case 'password':
case 'textarea':
case "button" :
tmp[nm]=$("input, textarea",this).val();
break;
case 'select':
if(!cm.editoptions.multiple) {
tmp[nm] = $("select option:selected",this).val();
tmp2[nm] = $("select option:selected", this).text();
} else {
var sel = $("select",this), selectedText = [];
tmp[nm] = $(sel).val();
if(tmp[nm]) { tmp[nm]= tmp[nm].join(","); } else { tmp[nm] =""; }
$("select option:selected",this).each(
function(i,selected){
selectedText[i] = $(selected).text();
}
);
tmp2[nm] = selectedText.join(",");
}
if(cm.formatter && cm.formatter == 'select') { tmp2={}; }
break;
case 'custom' :
try {
if(cm.editoptions && $.isFunction(cm.editoptions.custom_value)) {
tmp[nm] = cm.editoptions.custom_value.call($t, $(".customelement",this),'get');
if (tmp[nm] === undefined) { throw "e2"; }
} else { throw "e1"; }
} catch (e) {
if (e=="e1") { $.jgrid.info_dialog($.jgrid.errors.errcap,"function 'custom_value' "+$.jgrid.edit.msg.nodefined,$.jgrid.edit.bClose); }
if (e=="e2") { $.jgrid.info_dialog($.jgrid.errors.errcap,"function 'custom_value' "+$.jgrid.edit.msg.novalue,$.jgrid.edit.bClose); }
else { $.jgrid.info_dialog($.jgrid.errors.errcap,e.message,$.jgrid.edit.bClose); }
}
break;
}
cv = $.jgrid.checkValues(tmp[nm],i,$t);
if(cv[0] === false) {
cv[1] = tmp[nm] + " " + cv[1];
return false;
}
if($t.p.autoencode) { tmp[nm] = $.jgrid.htmlEncode(tmp[nm]); }
if(o.url !== 'clientArray' && cm.editoptions && cm.editoptions.NullIfEmpty === true) {
if(tmp[nm] === "") {
tmp3[nm] = 'null';
}
}
}
});
if (cv[0] === false){
try {
var positions = $.jgrid.findPos($("#"+$.jgrid.jqID(rowid), $t.grid.bDiv)[0]);
$.jgrid.info_dialog($.jgrid.errors.errcap,cv[1],$.jgrid.edit.bClose,{left:positions[0],top:positions[1]});
} catch (e) {
alert(cv[1]);
}
return success;
}
var idname, opers, oper;
opers = $t.p.prmNames;
oper = opers.oper;
idname = opers.id;
if(tmp) {
tmp[oper] = opers.editoper;
tmp[idname] = rowid;
if(typeof($t.p.inlineData) == 'undefined') { $t.p.inlineData ={}; }
tmp = $.extend({},tmp,$t.p.inlineData,o.extraparam);
}
if (o.url == 'clientArray') {
tmp = $.extend({},tmp, tmp2);
if($t.p.autoencode) {
$.each(tmp,function(n,v){
tmp[n] = $.jgrid.htmlDecode(v);
});
}
var resp = $($t).jqGrid("setRowData",rowid,tmp);
$(ind).attr("editable","0");
for( var k=0;k<$t.p.savedRow.length;k++) {
if( $t.p.savedRow[k].id == rowid) {fr = k; break;}
}
if(fr >= 0) { $t.p.savedRow.splice(fr,1); }
$($t).triggerHandler("jqGridInlineAfterSaveRow", [rowid, resp, tmp, o]);
if( $.isFunction(o.aftersavefunc) ) { o.aftersavefunc.call($t, rowid,resp, o); }
success = true;
$(ind).unbind("keydown");
} else {
$("#lui_"+$.jgrid.jqID($t.p.id)).show();
tmp3 = $.extend({},tmp,tmp3);
tmp3[idname] = $.jgrid.stripPref($t.p.idPrefix, tmp3[idname]);
$.ajax($.extend({
url:o.url,
data: $.isFunction($t.p.serializeRowData) ? $t.p.serializeRowData.call($t, tmp3) : tmp3,
type: o.mtype,
async : false, //?!?
complete: function(res,stat){
$("#lui_"+$.jgrid.jqID($t.p.id)).hide();
if (stat === "success"){
var ret = true, sucret;
sucret = $($t).triggerHandler("jqGridInlineSuccessSaveRow", [res, rowid, o]);
if (!$.isArray(sucret)) {sucret = [true, tmp];}
if (sucret[0] && $.isFunction(o.successfunc)) {sucret = o.successfunc.call($t, res);}
if($.isArray(sucret)) {
// expect array - status, data, rowid
ret = sucret[0];
tmp = sucret[1] ? sucret[1] : tmp;
} else {
ret = sucret;
}
if (ret===true) {
if($t.p.autoencode) {
$.each(tmp,function(n,v){
tmp[n] = $.jgrid.htmlDecode(v);
});
}
tmp = $.extend({},tmp, tmp2);
$($t).jqGrid("setRowData",rowid,tmp);
$(ind).attr("editable","0");
for( var k=0;k<$t.p.savedRow.length;k++) {
if( $t.p.savedRow[k].id == rowid) {fr = k; break;}
}
if(fr >= 0) { $t.p.savedRow.splice(fr,1); }
$($t).triggerHandler("jqGridInlineAfterSaveRow", [rowid, res, tmp, o]);
if( $.isFunction(o.aftersavefunc) ) { o.aftersavefunc.call($t, rowid,res); }
success = true;
$(ind).unbind("keydown");
} else {
$($t).triggerHandler("jqGridInlineErrorSaveRow", [rowid, res, stat, null, o]);<|fim▁hole|> if($.isFunction(o.errorfunc) ) {
o.errorfunc.call($t, rowid, res, stat, null);
}
if(o.restoreAfterError === true) {
$($t).jqGrid("restoreRow",rowid, o.afterrestorefunc);
}
}
}
},
error:function(res,stat,err){
$("#lui_"+$.jgrid.jqID($t.p.id)).hide();
$($t).triggerHandler("jqGridInlineErrorSaveRow", [rowid, res, stat, err, o]);
if($.isFunction(o.errorfunc) ) {
o.errorfunc.call($t, rowid, res, stat, err);
} else {
var rT = res.responseText || res.statusText;
try {
$.jgrid.info_dialog($.jgrid.errors.errcap,'<div class="ui-state-error">'+ rT +'</div>', $.jgrid.edit.bClose,{buttonalign:'right'});
} catch(e) {
alert(rT);
}
}
if(o.restoreAfterError === true) {
$($t).jqGrid("restoreRow",rowid, o.afterrestorefunc);
}
}
}, $.jgrid.ajaxOptions, $t.p.ajaxRowOptions || {}));
}
}
return success;
},
restoreRow : function(rowid, afterrestorefunc) {
// Compatible mode old versions
var args = $.makeArray(arguments).slice(1), o={};
if( $.type(args[0]) === "object" ) {
o = args[0];
} else {
if ($.isFunction(afterrestorefunc)) { o.afterrestorefunc = afterrestorefunc; }
}
o = $.extend(true, $.jgrid.inlineEdit, o );
// End compatible
return this.each(function(){
var $t= this, fr, ind, ares={};
if (!$t.grid ) { return; }
ind = $($t).jqGrid("getInd",rowid,true);
if(ind === false) {return;}
for( var k=0;k<$t.p.savedRow.length;k++) {
if( $t.p.savedRow[k].id == rowid) {fr = k; break;}
}
if(fr >= 0) {
if($.isFunction($.fn.datepicker)) {
try {
$("input.hasDatepicker","#"+$.jgrid.jqID(ind.id)).datepicker('hide');
} catch (e) {}
}
$.each($t.p.colModel, function(){
if(this.editable === true && this.name in $t.p.savedRow[fr] ) {
ares[this.name] = $t.p.savedRow[fr][this.name];
}
});
$($t).jqGrid("setRowData",rowid,ares);
$(ind).attr("editable","0").unbind("keydown");
$t.p.savedRow.splice(fr,1);
if($("#"+$.jgrid.jqID(rowid), "#"+$.jgrid.jqID($t.p.id)).hasClass("jqgrid-new-row")){
setTimeout(function(){$($t).jqGrid("delRowData",rowid);},0);
}
}
$($t).triggerHandler("jqGridInlineAfterRestoreRow", [rowid]);
if ($.isFunction(o.afterrestorefunc))
{
o.afterrestorefunc.call($t, rowid);
}
});
},
addRow : function ( p ) {
p = $.extend(true, {
rowID : "new_row",
initdata : {},
position :"first",
useDefValues : true,
useFormatter : false,
addRowParams : {extraparam:{}}
},p || {});
return this.each(function(){
if (!this.grid ) { return; }
var $t = this;
if(p.useDefValues === true) {
$($t.p.colModel).each(function(){
if( this.editoptions && this.editoptions.defaultValue ) {
var opt = this.editoptions.defaultValue,
tmp = $.isFunction(opt) ? opt.call($t) : opt;
p.initdata[this.name] = tmp;
}
});
}
$($t).jqGrid('addRowData', p.rowID, p.initdata, p.position);
p.rowID = $t.p.idPrefix + p.rowID;
$("#"+$.jgrid.jqID(p.rowID), "#"+$.jgrid.jqID($t.p.id)).addClass("jqgrid-new-row");
if(p.useFormatter) {
$("#"+$.jgrid.jqID(p.rowID)+" .ui-inline-edit", "#"+$.jgrid.jqID($t.p.id)).click();
} else {
var opers = $t.p.prmNames,
oper = opers.oper;
p.addRowParams.extraparam[oper] = opers.addoper;
$($t).jqGrid('editRow', p.rowID, p.addRowParams);
$($t).jqGrid('setSelection', p.rowID);
}
});
},
inlineNav : function (elem, o) {
o = $.extend({
edit: true,
editicon: "ui-icon-pencil",
add: true,
addicon:"ui-icon-plus",
save: true,
saveicon:"ui-icon-disk",
cancel: true,
cancelicon:"ui-icon-cancel",
addParams : {useFormatter : false,rowID : "new_row"},
editParams : {},
restoreAfterSelect : true
}, $.jgrid.nav, o ||{});
return this.each(function(){
if (!this.grid ) { return; }
var $t = this, onSelect, gID = $.jgrid.jqID($t.p.id);
$t.p._inlinenav = true;
// detect the formatactions column
if(o.addParams.useFormatter === true) {
var cm = $t.p.colModel,i;
for (i = 0; i<cm.length; i++) {
if(cm[i].formatter && cm[i].formatter === "actions" ) {
if(cm[i].formatoptions) {
var defaults = {
keys:false,
onEdit : null,
onSuccess: null,
afterSave:null,
onError: null,
afterRestore: null,
extraparam: {},
url: null
},
ap = $.extend( defaults, cm[i].formatoptions );
o.addParams.addRowParams = {
"keys" : ap.keys,
"oneditfunc" : ap.onEdit,
"successfunc" : ap.onSuccess,
"url" : ap.url,
"extraparam" : ap.extraparam,
"aftersavefunc" : ap.afterSavef,
"errorfunc": ap.onError,
"afterrestorefunc" : ap.afterRestore
};
}
break;
}
}
}
if(o.add) {
$($t).jqGrid('navButtonAdd', elem,{
caption : o.addtext,
title : o.addtitle,
buttonicon : o.addicon,
id : $t.p.id+"_iladd",
onClickButton : function () {
$($t).jqGrid('addRow', o.addParams);
if(!o.addParams.useFormatter) {
$("#"+gID+"_ilsave").removeClass('ui-state-disabled');
$("#"+gID+"_ilcancel").removeClass('ui-state-disabled');
$("#"+gID+"_iladd").addClass('ui-state-disabled');
$("#"+gID+"_iledit").addClass('ui-state-disabled');
}
}
});
}
if(o.edit) {
$($t).jqGrid('navButtonAdd', elem,{
caption : o.edittext,
title : o.edittitle,
buttonicon : o.editicon,
id : $t.p.id+"_iledit",
onClickButton : function () {
var sr = $($t).jqGrid('getGridParam','selrow');
if(sr) {
$($t).jqGrid('editRow', sr, o.editParams);
$("#"+gID+"_ilsave").removeClass('ui-state-disabled');
$("#"+gID+"_ilcancel").removeClass('ui-state-disabled');
$("#"+gID+"_iladd").addClass('ui-state-disabled');
$("#"+gID+"_iledit").addClass('ui-state-disabled');
} else {
$.jgrid.viewModal("#alertmod",{gbox:"#gbox_"+gID,jqm:true});$("#jqg_alrt").focus();
}
}
});
}
if(o.save) {
$($t).jqGrid('navButtonAdd', elem,{
caption : o.savetext || '',
title : o.savetitle || 'Save row',
buttonicon : o.saveicon,
id : $t.p.id+"_ilsave",
onClickButton : function () {
var sr = $t.p.savedRow[0].id;
if(sr) {
var opers = $t.p.prmNames,
oper = opers.oper;
if(!o.editParams.extraparam) {
o.editParams.extraparam = {};
}
if($("#"+$.jgrid.jqID(sr), "#"+gID ).hasClass("jqgrid-new-row")) {
o.editParams.extraparam[oper] = opers.addoper;
} else {
o.editParams.extraparam[oper] = opers.editoper;
}
if( $($t).jqGrid('saveRow', sr, o.editParams) ) {
$($t).jqGrid('showAddEditButtons');
}
} else {
$.jgrid.viewModal("#alertmod",{gbox:"#gbox_"+gID,jqm:true});$("#jqg_alrt").focus();
}
}
});
$("#"+gID+"_ilsave").addClass('ui-state-disabled');
}
if(o.cancel) {
$($t).jqGrid('navButtonAdd', elem,{
caption : o.canceltext || '',
title : o.canceltitle || 'Cancel row editing',
buttonicon : o.cancelicon,
id : $t.p.id+"_ilcancel",
onClickButton : function () {
var sr = $t.p.savedRow[0].id;
if(sr) {
$($t).jqGrid('restoreRow', sr, o.editParams);
$($t).jqGrid('showAddEditButtons');
} else {
$.jgrid.viewModal("#alertmod",{gbox:"#gbox_"+gID,jqm:true});$("#jqg_alrt").focus();
}
}
});
$("#"+gID+"_ilcancel").addClass('ui-state-disabled');
}
if(o.restoreAfterSelect === true) {
if($.isFunction($t.p.beforeSelectRow)) {
onSelect = $t.p.beforeSelectRow;
} else {
onSelect = false;
}
$t.p.beforeSelectRow = function(id, stat) {
var ret = true;
if($t.p.savedRow.length > 0 && $t.p._inlinenav===true && ( id !== $t.p.selrow && $t.p.selrow !==null) ) {
if($t.p.selrow == o.addParams.rowID ) {
$($t).jqGrid('delRowData', $t.p.selrow);
} else {
$($t).jqGrid('restoreRow', $t.p.selrow, o.editParams);
}
$($t).jqGrid('showAddEditButtons');
}
if(onSelect) {
ret = onSelect.call($t, id, stat);
}
return ret;
};
}
});
},
showAddEditButtons : function() {
return this.each(function(){
if (!this.grid ) { return; }
var gID = $.jgrid.jqID(this.p.id);
$("#"+gID+"_ilsave").addClass('ui-state-disabled');
$("#"+gID+"_ilcancel").addClass('ui-state-disabled');
$("#"+gID+"_iladd").removeClass('ui-state-disabled');
$("#"+gID+"_iledit").removeClass('ui-state-disabled');
});
}
//end inline edit
});
})(jQuery);<|fim▁end|>
| |
<|file_name|>some.js<|end_file_name|><|fim▁begin|>var makeIterator = require('../function/makeIterator_');
/**
* Array some
*/
/**
* Description
* @method some
* @param {} arr
* @param {} callback
* @param {} thisObj
* @return result
*/
function some(arr, callback, thisObj) {
callback = makeIterator(callback, thisObj);
var result = false;
if (arr == null) {
return result;
}<|fim▁hole|>
var i = -1, len = arr.length;
while (++i < len) {
// we iterate over sparse items since there is no way to make it
// work properly on IE 7-8. see #64
if ( callback(arr[i], i, arr) ) {
result = true;
break;
}
}
return result;
}
module.exports = some;<|fim▁end|>
| |
<|file_name|>RunConfigurationUsageTriggerCollector.java<|end_file_name|><|fim▁begin|>// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.execution.impl.statistics;
import com.intellij.execution.Executor;
import com.intellij.execution.configurations.ConfigurationFactory;
import com.intellij.execution.configurations.ConfigurationType;
import com.intellij.execution.configurations.RunConfiguration;
import com.intellij.execution.executors.ExecutorGroup;
import com.intellij.execution.target.TargetEnvironmentAwareRunProfile;
import com.intellij.execution.target.TargetEnvironmentConfiguration;
import com.intellij.execution.target.TargetEnvironmentType;
import com.intellij.execution.target.TargetEnvironmentsManager;
import com.intellij.internal.statistic.IdeActivityDefinition;
import com.intellij.internal.statistic.StructuredIdeActivity;
import com.intellij.internal.statistic.eventLog.EventLogGroup;
import com.intellij.internal.statistic.eventLog.events.*;
import com.intellij.internal.statistic.eventLog.validator.ValidationResultType;
import com.intellij.internal.statistic.eventLog.validator.rules.EventContext;
import com.intellij.internal.statistic.eventLog.validator.rules.impl.CustomValidationRule;
import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector;
import com.intellij.internal.statistic.utils.PluginInfo;
import com.intellij.internal.statistic.utils.PluginInfoDetectorKt;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.concurrency.NonUrgentExecutor;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collections;
import java.util.List;
import static com.intellij.execution.impl.statistics.RunConfigurationTypeUsagesCollector.createFeatureUsageData;
public final class RunConfigurationUsageTriggerCollector extends CounterUsagesCollector {
public static final String GROUP_NAME = "run.configuration.exec";
private static final EventLogGroup GROUP = new EventLogGroup(GROUP_NAME, 62);
private static final ObjectEventField ADDITIONAL_FIELD = EventFields.createAdditionalDataField(GROUP_NAME, "started");
private static final StringEventField EXECUTOR = EventFields.StringValidatedByCustomRule("executor", "run_config_executor");
private static final StringEventField TARGET =
EventFields.StringValidatedByCustomRule("target", RunConfigurationUsageTriggerCollector.RunTargetValidator.RULE_ID);
private static final EnumEventField<RunConfigurationFinishType> FINISH_TYPE =
EventFields.Enum("finish_type", RunConfigurationFinishType.class);
private static final IdeActivityDefinition ACTIVITY_GROUP = GROUP.registerIdeActivity(null,
new EventField<?>[]{ADDITIONAL_FIELD, EXECUTOR,
TARGET,
RunConfigurationTypeUsagesCollector.FACTORY_FIELD,
RunConfigurationTypeUsagesCollector.ID_FIELD,
EventFields.PluginInfo},
new EventField<?>[]{FINISH_TYPE});
public static final VarargEventId UI_SHOWN_STAGE = ACTIVITY_GROUP.registerStage("ui.shown");
@Override
public EventLogGroup getGroup() {
return GROUP;
}
@NotNull
public static StructuredIdeActivity trigger(@NotNull Project project,
@NotNull ConfigurationFactory factory,
@NotNull Executor executor,
@Nullable RunConfiguration runConfiguration) {
return ACTIVITY_GROUP
.startedAsync(project, () -> ReadAction.nonBlocking(() -> buildContext(project, factory, executor, runConfiguration))
.expireWith(project)
.submit(NonUrgentExecutor.getInstance()));
}
private static @NotNull List<EventPair<?>> buildContext(@NotNull Project project,
@NotNull ConfigurationFactory factory,
@NotNull Executor executor,
@Nullable RunConfiguration runConfiguration) {
final ConfigurationType configurationType = factory.getType();
List<EventPair<?>> eventPairs = createFeatureUsageData(configurationType, factory);
ExecutorGroup<?> group = ExecutorGroup.getGroupIfProxy(executor);
eventPairs.add(EXECUTOR.with(group != null ? group.getId() : executor.getId()));
if (runConfiguration instanceof FusAwareRunConfiguration) {
List<EventPair<?>> additionalData = ((FusAwareRunConfiguration)runConfiguration).getAdditionalUsageData();
ObjectEventData objectEventData = new ObjectEventData(additionalData);
eventPairs.add(ADDITIONAL_FIELD.with(objectEventData));
}
if (runConfiguration instanceof TargetEnvironmentAwareRunProfile) {
String defaultTargetName = ((TargetEnvironmentAwareRunProfile)runConfiguration).getDefaultTargetName();
if (defaultTargetName != null) {
TargetEnvironmentConfiguration target = TargetEnvironmentsManager.getInstance(project).getTargets().findByName(defaultTargetName);
if (target != null) {
eventPairs.add(TARGET.with(target.getTypeId()));
}
}
}
return eventPairs;
}
public static void logProcessFinished(@Nullable StructuredIdeActivity activity,
RunConfigurationFinishType finishType) {
if (activity != null) {
activity.finished(() -> Collections.singletonList(FINISH_TYPE.with(finishType)));
}
}
public static class RunConfigurationExecutorUtilValidator extends CustomValidationRule {
@Override
public boolean acceptRuleId(@Nullable String ruleId) {
return "run_config_executor".equals(ruleId);
}
@NotNull
@Override
protected ValidationResultType doValidate(@NotNull String data, @NotNull EventContext context) {
for (Executor executor : Executor.EXECUTOR_EXTENSION_NAME.getExtensions()) {
if (StringUtil.equals(executor.getId(), data)) {
final PluginInfo info = PluginInfoDetectorKt.getPluginInfo(executor.getClass());
return info.isSafeToReport() ? ValidationResultType.ACCEPTED : ValidationResultType.THIRD_PARTY;
}<|fim▁hole|> }
}
public static class RunTargetValidator extends CustomValidationRule {
public static final String RULE_ID = "run_target";
@Override
public boolean acceptRuleId(@Nullable String ruleId) {
return RULE_ID.equals(ruleId);
}
@NotNull
@Override
protected ValidationResultType doValidate(@NotNull String data, @NotNull EventContext context) {
for (TargetEnvironmentType<?> type : TargetEnvironmentType.EXTENSION_NAME.getExtensions()) {
if (StringUtil.equals(type.getId(), data)) {
final PluginInfo info = PluginInfoDetectorKt.getPluginInfo(type.getClass());
return info.isSafeToReport() ? ValidationResultType.ACCEPTED : ValidationResultType.THIRD_PARTY;
}
}
return ValidationResultType.REJECTED;
}
}
public enum RunConfigurationFinishType {FAILED_TO_START, UNKNOWN}
}<|fim▁end|>
|
}
return ValidationResultType.REJECTED;
|
<|file_name|>egg_info.py<|end_file_name|><|fim▁begin|>"""setuptools.command.egg_info
Create a distribution's .egg-info directory and contents"""
from distutils.filelist import FileList as _FileList
from distutils.errors import DistutilsInternalError
from distutils.util import convert_path
from distutils import log
import distutils.errors
import distutils.filelist
import os
import re
import sys
import io
import warnings
import time
import collections
from setuptools import Command
from setuptools.command.sdist import sdist
from setuptools.command.sdist import walk_revctrl
from setuptools.command.setopt import edit_config
from setuptools.command import bdist_egg
from pkg_resources import (
parse_requirements, safe_name, parse_version,
safe_version, yield_lines, EntryPoint, iter_entry_points, to_filename)
import setuptools.unicode_utils as unicode_utils
from setuptools.glob import glob
from setuptools.extern import packaging
from setuptools import SetuptoolsDeprecationWarning
def translate_pattern(glob):
"""
Translate a file path glob like '*.txt' in to a regular expression.
This differs from fnmatch.translate which allows wildcards to match
directory separators. It also knows about '**/' which matches any number of
directories.
"""
pat = ''
# This will split on '/' within [character classes]. This is deliberate.
chunks = glob.split(os.path.sep)
sep = re.escape(os.sep)
valid_char = '[^%s]' % (sep,)
for c, chunk in enumerate(chunks):
last_chunk = c == len(chunks) - 1
# Chunks that are a literal ** are globstars. They match anything.
if chunk == '**':
if last_chunk:
# Match anything if this is the last component
pat += '.*'
else:
# Match '(name/)*'
pat += '(?:%s+%s)*' % (valid_char, sep)
continue # Break here as the whole path component has been handled
# Find any special characters in the remainder
i = 0
chunk_len = len(chunk)
while i < chunk_len:
char = chunk[i]
if char == '*':
# Match any number of name characters
pat += valid_char + '*'
elif char == '?':
# Match a name character
pat += valid_char
elif char == '[':
# Character class
inner_i = i + 1
# Skip initial !/] chars
if inner_i < chunk_len and chunk[inner_i] == '!':
inner_i = inner_i + 1
if inner_i < chunk_len and chunk[inner_i] == ']':
inner_i = inner_i + 1
# Loop till the closing ] is found
while inner_i < chunk_len and chunk[inner_i] != ']':
inner_i = inner_i + 1
if inner_i >= chunk_len:
# Got to the end of the string without finding a closing ]
# Do not treat this as a matching group, but as a literal [
pat += re.escape(char)
else:
# Grab the insides of the [brackets]
inner = chunk[i + 1:inner_i]
char_class = ''
# Class negation
if inner[0] == '!':
char_class = '^'
inner = inner[1:]
char_class += re.escape(inner)
pat += '[%s]' % (char_class,)
# Skip to the end ]
i = inner_i
else:
pat += re.escape(char)
i += 1
# Join each chunk with the dir separator
if not last_chunk:
pat += sep
pat += r'\Z'
return re.compile(pat, flags=re.MULTILINE | re.DOTALL)
class InfoCommon:
tag_build = None
tag_date = None
@property
def name(self):
return safe_name(self.distribution.get_name())
def tagged_version(self):
return safe_version(self._maybe_tag(self.distribution.get_version()))
def _maybe_tag(self, version):
"""
egg_info may be called more than once for a distribution,
in which case the version string already contains all tags.
"""
return (
version if self.vtags and version.endswith(self.vtags)
else version + self.vtags
)
def tags(self):
version = ''
if self.tag_build:
version += self.tag_build
if self.tag_date:
version += time.strftime("-%Y%m%d")
return version
vtags = property(tags)
class egg_info(InfoCommon, Command):
description = "create a distribution's .egg-info directory"
user_options = [
('egg-base=', 'e', "directory containing .egg-info directories"
" (default: top of the source tree)"),
('tag-date', 'd', "Add date stamp (e.g. 20050528) to version number"),
('tag-build=', 'b', "Specify explicit tag to add to version number"),
('no-date', 'D', "Don't include date stamp [default]"),
]
boolean_options = ['tag-date']
negative_opt = {
'no-date': 'tag-date',
}
def initialize_options(self):
self.egg_base = None
self.egg_name = None
self.egg_info = None
self.egg_version = None
self.broken_egg_info = False
####################################
# allow the 'tag_svn_revision' to be detected and
# set, supporting sdists built on older Setuptools.
@property
def tag_svn_revision(self):
pass
@tag_svn_revision.setter
def tag_svn_revision(self, value):
pass
####################################
def save_version_info(self, filename):
"""
Materialize the value of date into the
build tag. Install build keys in a deterministic order
to avoid arbitrary reordering on subsequent builds.
"""
egg_info = collections.OrderedDict()
# follow the order these keys would have been added
# when PYTHONHASHSEED=0
egg_info['tag_build'] = self.tags()
egg_info['tag_date'] = 0
edit_config(filename, dict(egg_info=egg_info))
def finalize_options(self):
# Note: we need to capture the current value returned
# by `self.tagged_version()`, so we can later update
# `self.distribution.metadata.version` without
# repercussions.
self.egg_name = self.name
self.egg_version = self.tagged_version()
parsed_version = parse_version(self.egg_version)
try:
is_version = isinstance(parsed_version, packaging.version.Version)
spec = (
"%s==%s" if is_version else "%s===%s"
)
list(
parse_requirements(spec % (self.egg_name, self.egg_version))
)
except ValueError as e:
raise distutils.errors.DistutilsOptionError(
"Invalid distribution name or version syntax: %s-%s" %
(self.egg_name, self.egg_version)
) from e
if self.egg_base is None:
dirs = self.distribution.package_dir
self.egg_base = (dirs or {}).get('', os.curdir)
self.ensure_dirname('egg_base')
self.egg_info = to_filename(self.egg_name) + '.egg-info'
if self.egg_base != os.curdir:
self.egg_info = os.path.join(self.egg_base, self.egg_info)
if '-' in self.egg_name:
self.check_broken_egg_info()
# Set package version for the benefit of dumber commands
# (e.g. sdist, bdist_wininst, etc.)
#
self.distribution.metadata.version = self.egg_version
# If we bootstrapped around the lack of a PKG-INFO, as might be the
# case in a fresh checkout, make sure that any special tags get added
# to the version info
#
pd = self.distribution._patched_dist
if pd is not None and pd.key == self.egg_name.lower():
pd._version = self.egg_version
pd._parsed_version = parse_version(self.egg_version)
self.distribution._patched_dist = None
def write_or_delete_file(self, what, filename, data, force=False):
"""Write `data` to `filename` or delete if empty
If `data` is non-empty, this routine is the same as ``write_file()``.
If `data` is empty but not ``None``, this is the same as calling
``delete_file(filename)`. If `data` is ``None``, then this is a no-op
unless `filename` exists, in which case a warning is issued about the
orphaned file (if `force` is false), or deleted (if `force` is true).
"""
if data:
self.write_file(what, filename, data)
elif os.path.exists(filename):
if data is None and not force:
log.warn(
"%s not set in setup(), but %s exists", what, filename
)
return
else:
self.delete_file(filename)
def write_file(self, what, filename, data):
"""Write `data` to `filename` (if not a dry run) after announcing it
`what` is used in a log message to identify what is being written
to the file.
"""
log.info("writing %s to %s", what, filename)
data = data.encode("utf-8")
if not self.dry_run:
f = open(filename, 'wb')
f.write(data)
f.close()
def delete_file(self, filename):<|fim▁hole|> log.info("deleting %s", filename)
if not self.dry_run:
os.unlink(filename)
def run(self):
self.mkpath(self.egg_info)
os.utime(self.egg_info, None)
installer = self.distribution.fetch_build_egg
for ep in iter_entry_points('egg_info.writers'):
ep.require(installer=installer)
writer = ep.resolve()
writer(self, ep.name, os.path.join(self.egg_info, ep.name))
# Get rid of native_libs.txt if it was put there by older bdist_egg
nl = os.path.join(self.egg_info, "native_libs.txt")
if os.path.exists(nl):
self.delete_file(nl)
self.find_sources()
def find_sources(self):
"""Generate SOURCES.txt manifest file"""
manifest_filename = os.path.join(self.egg_info, "SOURCES.txt")
mm = manifest_maker(self.distribution)
mm.manifest = manifest_filename
mm.run()
self.filelist = mm.filelist
def check_broken_egg_info(self):
bei = self.egg_name + '.egg-info'
if self.egg_base != os.curdir:
bei = os.path.join(self.egg_base, bei)
if os.path.exists(bei):
log.warn(
"-" * 78 + '\n'
"Note: Your current .egg-info directory has a '-' in its name;"
'\nthis will not work correctly with "setup.py develop".\n\n'
'Please rename %s to %s to correct this problem.\n' + '-' * 78,
bei, self.egg_info
)
self.broken_egg_info = self.egg_info
self.egg_info = bei # make it work for now
class FileList(_FileList):
# Implementations of the various MANIFEST.in commands
def process_template_line(self, line):
# Parse the line: split it up, make sure the right number of words
# is there, and return the relevant words. 'action' is always
# defined: it's the first word of the line. Which of the other
# three are defined depends on the action; it'll be either
# patterns, (dir and patterns), or (dir_pattern).
(action, patterns, dir, dir_pattern) = self._parse_template_line(line)
# OK, now we know that the action is valid and we have the
# right number of words on the line for that action -- so we
# can proceed with minimal error-checking.
if action == 'include':
self.debug_print("include " + ' '.join(patterns))
for pattern in patterns:
if not self.include(pattern):
log.warn("warning: no files found matching '%s'", pattern)
elif action == 'exclude':
self.debug_print("exclude " + ' '.join(patterns))
for pattern in patterns:
if not self.exclude(pattern):
log.warn(("warning: no previously-included files "
"found matching '%s'"), pattern)
elif action == 'global-include':
self.debug_print("global-include " + ' '.join(patterns))
for pattern in patterns:
if not self.global_include(pattern):
log.warn(("warning: no files found matching '%s' "
"anywhere in distribution"), pattern)
elif action == 'global-exclude':
self.debug_print("global-exclude " + ' '.join(patterns))
for pattern in patterns:
if not self.global_exclude(pattern):
log.warn(("warning: no previously-included files matching "
"'%s' found anywhere in distribution"),
pattern)
elif action == 'recursive-include':
self.debug_print("recursive-include %s %s" %
(dir, ' '.join(patterns)))
for pattern in patterns:
if not self.recursive_include(dir, pattern):
log.warn(("warning: no files found matching '%s' "
"under directory '%s'"),
pattern, dir)
elif action == 'recursive-exclude':
self.debug_print("recursive-exclude %s %s" %
(dir, ' '.join(patterns)))
for pattern in patterns:
if not self.recursive_exclude(dir, pattern):
log.warn(("warning: no previously-included files matching "
"'%s' found under directory '%s'"),
pattern, dir)
elif action == 'graft':
self.debug_print("graft " + dir_pattern)
if not self.graft(dir_pattern):
log.warn("warning: no directories found matching '%s'",
dir_pattern)
elif action == 'prune':
self.debug_print("prune " + dir_pattern)
if not self.prune(dir_pattern):
log.warn(("no previously-included directories found "
"matching '%s'"), dir_pattern)
else:
raise DistutilsInternalError(
"this cannot happen: invalid action '%s'" % action)
def _remove_files(self, predicate):
"""
Remove all files from the file list that match the predicate.
Return True if any matching files were removed
"""
found = False
for i in range(len(self.files) - 1, -1, -1):
if predicate(self.files[i]):
self.debug_print(" removing " + self.files[i])
del self.files[i]
found = True
return found
def include(self, pattern):
"""Include files that match 'pattern'."""
found = [f for f in glob(pattern) if not os.path.isdir(f)]
self.extend(found)
return bool(found)
def exclude(self, pattern):
"""Exclude files that match 'pattern'."""
match = translate_pattern(pattern)
return self._remove_files(match.match)
def recursive_include(self, dir, pattern):
"""
Include all files anywhere in 'dir/' that match the pattern.
"""
full_pattern = os.path.join(dir, '**', pattern)
found = [f for f in glob(full_pattern, recursive=True)
if not os.path.isdir(f)]
self.extend(found)
return bool(found)
def recursive_exclude(self, dir, pattern):
"""
Exclude any file anywhere in 'dir/' that match the pattern.
"""
match = translate_pattern(os.path.join(dir, '**', pattern))
return self._remove_files(match.match)
def graft(self, dir):
"""Include all files from 'dir/'."""
found = [
item
for match_dir in glob(dir)
for item in distutils.filelist.findall(match_dir)
]
self.extend(found)
return bool(found)
def prune(self, dir):
"""Filter out files from 'dir/'."""
match = translate_pattern(os.path.join(dir, '**'))
return self._remove_files(match.match)
def global_include(self, pattern):
"""
Include all files anywhere in the current directory that match the
pattern. This is very inefficient on large file trees.
"""
if self.allfiles is None:
self.findall()
match = translate_pattern(os.path.join('**', pattern))
found = [f for f in self.allfiles if match.match(f)]
self.extend(found)
return bool(found)
def global_exclude(self, pattern):
"""
Exclude all files anywhere that match the pattern.
"""
match = translate_pattern(os.path.join('**', pattern))
return self._remove_files(match.match)
def append(self, item):
if item.endswith('\r'): # Fix older sdists built on Windows
item = item[:-1]
path = convert_path(item)
if self._safe_path(path):
self.files.append(path)
def extend(self, paths):
self.files.extend(filter(self._safe_path, paths))
def _repair(self):
"""
Replace self.files with only safe paths
Because some owners of FileList manipulate the underlying
``files`` attribute directly, this method must be called to
repair those paths.
"""
self.files = list(filter(self._safe_path, self.files))
def _safe_path(self, path):
enc_warn = "'%s' not %s encodable -- skipping"
# To avoid accidental trans-codings errors, first to unicode
u_path = unicode_utils.filesys_decode(path)
if u_path is None:
log.warn("'%s' in unexpected encoding -- skipping" % path)
return False
# Must ensure utf-8 encodability
utf8_path = unicode_utils.try_encode(u_path, "utf-8")
if utf8_path is None:
log.warn(enc_warn, path, 'utf-8')
return False
try:
# accept is either way checks out
if os.path.exists(u_path) or os.path.exists(utf8_path):
return True
# this will catch any encode errors decoding u_path
except UnicodeEncodeError:
log.warn(enc_warn, path, sys.getfilesystemencoding())
class manifest_maker(sdist):
template = "MANIFEST.in"
def initialize_options(self):
self.use_defaults = 1
self.prune = 1
self.manifest_only = 1
self.force_manifest = 1
def finalize_options(self):
pass
def run(self):
self.filelist = FileList()
if not os.path.exists(self.manifest):
self.write_manifest() # it must exist so it'll get in the list
self.add_defaults()
if os.path.exists(self.template):
self.read_template()
self.prune_file_list()
self.filelist.sort()
self.filelist.remove_duplicates()
self.write_manifest()
def _manifest_normalize(self, path):
path = unicode_utils.filesys_decode(path)
return path.replace(os.sep, '/')
def write_manifest(self):
"""
Write the file list in 'self.filelist' to the manifest file
named by 'self.manifest'.
"""
self.filelist._repair()
# Now _repairs should encodability, but not unicode
files = [self._manifest_normalize(f) for f in self.filelist.files]
msg = "writing manifest file '%s'" % self.manifest
self.execute(write_file, (self.manifest, files), msg)
def warn(self, msg):
if not self._should_suppress_warning(msg):
sdist.warn(self, msg)
@staticmethod
def _should_suppress_warning(msg):
"""
suppress missing-file warnings from sdist
"""
return re.match(r"standard file .*not found", msg)
def add_defaults(self):
sdist.add_defaults(self)
self.check_license()
self.filelist.append(self.template)
self.filelist.append(self.manifest)
rcfiles = list(walk_revctrl())
if rcfiles:
self.filelist.extend(rcfiles)
elif os.path.exists(self.manifest):
self.read_manifest()
if os.path.exists("setup.py"):
# setup.py should be included by default, even if it's not
# the script called to create the sdist
self.filelist.append("setup.py")
ei_cmd = self.get_finalized_command('egg_info')
self.filelist.graft(ei_cmd.egg_info)
def prune_file_list(self):
build = self.get_finalized_command('build')
base_dir = self.distribution.get_fullname()
self.filelist.prune(build.build_base)
self.filelist.prune(base_dir)
sep = re.escape(os.sep)
self.filelist.exclude_pattern(r'(^|' + sep + r')(RCS|CVS|\.svn)' + sep,
is_regex=1)
def write_file(filename, contents):
"""Create a file with the specified name and write 'contents' (a
sequence of strings without line terminators) to it.
"""
contents = "\n".join(contents)
# assuming the contents has been vetted for utf-8 encoding
contents = contents.encode("utf-8")
with open(filename, "wb") as f: # always write POSIX-style manifest
f.write(contents)
def write_pkg_info(cmd, basename, filename):
log.info("writing %s", filename)
if not cmd.dry_run:
metadata = cmd.distribution.metadata
metadata.version, oldver = cmd.egg_version, metadata.version
metadata.name, oldname = cmd.egg_name, metadata.name
try:
# write unescaped data to PKG-INFO, so older pkg_resources
# can still parse it
metadata.write_pkg_info(cmd.egg_info)
finally:
metadata.name, metadata.version = oldname, oldver
safe = getattr(cmd.distribution, 'zip_safe', None)
bdist_egg.write_safety_flag(cmd.egg_info, safe)
def warn_depends_obsolete(cmd, basename, filename):
if os.path.exists(filename):
log.warn(
"WARNING: 'depends.txt' is not used by setuptools 0.6!\n"
"Use the install_requires/extras_require setup() args instead."
)
def _write_requirements(stream, reqs):
lines = yield_lines(reqs or ())
def append_cr(line):
return line + '\n'
lines = map(append_cr, lines)
stream.writelines(lines)
def write_requirements(cmd, basename, filename):
dist = cmd.distribution
data = io.StringIO()
_write_requirements(data, dist.install_requires)
extras_require = dist.extras_require or {}
for extra in sorted(extras_require):
data.write('\n[{extra}]\n'.format(**vars()))
_write_requirements(data, extras_require[extra])
cmd.write_or_delete_file("requirements", filename, data.getvalue())
def write_setup_requirements(cmd, basename, filename):
data = io.StringIO()
_write_requirements(data, cmd.distribution.setup_requires)
cmd.write_or_delete_file("setup-requirements", filename, data.getvalue())
def write_toplevel_names(cmd, basename, filename):
pkgs = dict.fromkeys(
[
k.split('.', 1)[0]
for k in cmd.distribution.iter_distribution_names()
]
)
cmd.write_file("top-level names", filename, '\n'.join(sorted(pkgs)) + '\n')
def overwrite_arg(cmd, basename, filename):
write_arg(cmd, basename, filename, True)
def write_arg(cmd, basename, filename, force=False):
argname = os.path.splitext(basename)[0]
value = getattr(cmd.distribution, argname, None)
if value is not None:
value = '\n'.join(value) + '\n'
cmd.write_or_delete_file(argname, filename, value, force)
def write_entries(cmd, basename, filename):
ep = cmd.distribution.entry_points
if isinstance(ep, str) or ep is None:
data = ep
elif ep is not None:
data = []
for section, contents in sorted(ep.items()):
if not isinstance(contents, str):
contents = EntryPoint.parse_group(section, contents)
contents = '\n'.join(sorted(map(str, contents.values())))
data.append('[%s]\n%s\n\n' % (section, contents))
data = ''.join(data)
cmd.write_or_delete_file('entry points', filename, data, True)
def get_pkg_info_revision():
"""
Get a -r### off of PKG-INFO Version in case this is an sdist of
a subversion revision.
"""
warnings.warn(
"get_pkg_info_revision is deprecated.", EggInfoDeprecationWarning)
if os.path.exists('PKG-INFO'):
with io.open('PKG-INFO') as f:
for line in f:
match = re.match(r"Version:.*-r(\d+)\s*$", line)
if match:
return int(match.group(1))
return 0
class EggInfoDeprecationWarning(SetuptoolsDeprecationWarning):
"""Deprecated behavior warning for EggInfo, bypassing suppression."""<|fim▁end|>
|
"""Delete `filename` (if not a dry run) after announcing it"""
|
<|file_name|>defaulting_test.go<|end_file_name|><|fim▁begin|>/*
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package testing
import (
"math/rand"
"reflect"
"sort"
"testing"
fuzz "github.com/google/gofuzz"
apiv1 "k8s.io/api/core/v1"
extensionsv1beta1 "k8s.io/api/extensions/v1beta1"
roundtrip "k8s.io/apimachinery/pkg/api/apitesting/roundtrip"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/util/diff"
"k8s.io/kubernetes/pkg/api/legacyscheme"
)
type orderedGroupVersionKinds []schema.GroupVersionKind
func (o orderedGroupVersionKinds) Len() int { return len(o) }
func (o orderedGroupVersionKinds) Swap(i, j int) { o[i], o[j] = o[j], o[i] }
func (o orderedGroupVersionKinds) Less(i, j int) bool {
return o[i].String() < o[j].String()
}
// TODO: add a reflexive test that verifies that all SetDefaults functions are registered
func TestDefaulting(t *testing.T) {
// these are the known types with defaulters - you must add to this list if you add a top level defaulter
typesWithDefaulting := map[schema.GroupVersionKind]struct{}{
{Group: "", Version: "v1", Kind: "ConfigMap"}: {},
{Group: "", Version: "v1", Kind: "ConfigMapList"}: {},
{Group: "", Version: "v1", Kind: "Endpoints"}: {},
{Group: "", Version: "v1", Kind: "EndpointsList"}: {},
{Group: "", Version: "v1", Kind: "Namespace"}: {},
{Group: "", Version: "v1", Kind: "NamespaceList"}: {},
{Group: "", Version: "v1", Kind: "Node"}: {},
{Group: "", Version: "v1", Kind: "NodeList"}: {},
{Group: "", Version: "v1", Kind: "PersistentVolume"}: {},
{Group: "", Version: "v1", Kind: "PersistentVolumeList"}: {},
{Group: "", Version: "v1", Kind: "PersistentVolumeClaim"}: {},
{Group: "", Version: "v1", Kind: "PersistentVolumeClaimList"}: {},
{Group: "", Version: "v1", Kind: "Pod"}: {},
{Group: "", Version: "v1", Kind: "PodList"}: {},
{Group: "", Version: "v1", Kind: "PodTemplate"}: {},
{Group: "", Version: "v1", Kind: "PodTemplateList"}: {},
{Group: "", Version: "v1", Kind: "ReplicationController"}: {},
{Group: "", Version: "v1", Kind: "ReplicationControllerList"}: {},
{Group: "", Version: "v1", Kind: "Secret"}: {},
{Group: "", Version: "v1", Kind: "SecretList"}: {},
{Group: "", Version: "v1", Kind: "Service"}: {},
{Group: "", Version: "v1", Kind: "ServiceList"}: {},
{Group: "apps", Version: "v1beta1", Kind: "StatefulSet"}: {},
{Group: "apps", Version: "v1beta1", Kind: "StatefulSetList"}: {},
{Group: "apps", Version: "v1beta2", Kind: "StatefulSet"}: {},
{Group: "apps", Version: "v1beta2", Kind: "StatefulSetList"}: {},
{Group: "apps", Version: "v1", Kind: "StatefulSet"}: {},
{Group: "apps", Version: "v1", Kind: "StatefulSetList"}: {},
{Group: "autoscaling", Version: "v1", Kind: "HorizontalPodAutoscaler"}: {},
{Group: "autoscaling", Version: "v1", Kind: "HorizontalPodAutoscalerList"}: {},
{Group: "autoscaling", Version: "v2beta1", Kind: "HorizontalPodAutoscaler"}: {},
{Group: "autoscaling", Version: "v2beta1", Kind: "HorizontalPodAutoscalerList"}: {},
{Group: "batch", Version: "v1", Kind: "Job"}: {},
{Group: "batch", Version: "v1", Kind: "JobList"}: {},
{Group: "batch", Version: "v1beta1", Kind: "CronJob"}: {},
{Group: "batch", Version: "v1beta1", Kind: "CronJobList"}: {},
{Group: "batch", Version: "v1beta1", Kind: "JobTemplate"}: {},
{Group: "batch", Version: "v2alpha1", Kind: "CronJob"}: {},
{Group: "batch", Version: "v2alpha1", Kind: "CronJobList"}: {},
{Group: "batch", Version: "v2alpha1", Kind: "JobTemplate"}: {},
{Group: "certificates.k8s.io", Version: "v1beta1", Kind: "CertificateSigningRequest"}: {},
{Group: "certificates.k8s.io", Version: "v1beta1", Kind: "CertificateSigningRequestList"}: {},
{Group: "kubeadm.k8s.io", Version: "v1alpha1", Kind: "MasterConfiguration"}: {},
// This object contains only int fields which currently breaks the defaulting test because
// it's pretty stupid. Once we add non integer fields, we should uncomment this.
// {Group: "kubeadm.k8s.io", Version: "v1alpha1", Kind: "NodeConfiguration"}: {},
{Group: "extensions", Version: "v1beta1", Kind: "DaemonSet"}: {},
{Group: "extensions", Version: "v1beta1", Kind: "DaemonSetList"}: {},
{Group: "apps", Version: "v1beta2", Kind: "DaemonSet"}: {},
{Group: "apps", Version: "v1beta2", Kind: "DaemonSetList"}: {},
{Group: "apps", Version: "v1", Kind: "DaemonSet"}: {},
{Group: "apps", Version: "v1", Kind: "DaemonSetList"}: {},
{Group: "extensions", Version: "v1beta1", Kind: "Deployment"}: {},
{Group: "extensions", Version: "v1beta1", Kind: "DeploymentList"}: {},
{Group: "apps", Version: "v1beta1", Kind: "Deployment"}: {},
{Group: "apps", Version: "v1beta1", Kind: "DeploymentList"}: {},
{Group: "apps", Version: "v1beta2", Kind: "Deployment"}: {},
{Group: "apps", Version: "v1beta2", Kind: "DeploymentList"}: {},
{Group: "apps", Version: "v1", Kind: "Deployment"}: {},
{Group: "apps", Version: "v1", Kind: "DeploymentList"}: {},
{Group: "extensions", Version: "v1beta1", Kind: "PodSecurityPolicy"}: {},
{Group: "extensions", Version: "v1beta1", Kind: "PodSecurityPolicyList"}: {},
{Group: "apps", Version: "v1beta2", Kind: "ReplicaSet"}: {},
{Group: "apps", Version: "v1beta2", Kind: "ReplicaSetList"}: {},
{Group: "apps", Version: "v1", Kind: "ReplicaSet"}: {},
{Group: "apps", Version: "v1", Kind: "ReplicaSetList"}: {},
{Group: "extensions", Version: "v1beta1", Kind: "ReplicaSet"}: {},
{Group: "extensions", Version: "v1beta1", Kind: "ReplicaSetList"}: {},
{Group: "extensions", Version: "v1beta1", Kind: "NetworkPolicy"}: {},
{Group: "extensions", Version: "v1beta1", Kind: "NetworkPolicyList"}: {},
{Group: "policy", Version: "v1beta1", Kind: "PodSecurityPolicy"}: {},
{Group: "policy", Version: "v1beta1", Kind: "PodSecurityPolicyList"}: {},
{Group: "rbac.authorization.k8s.io", Version: "v1alpha1", Kind: "ClusterRoleBinding"}: {},
{Group: "rbac.authorization.k8s.io", Version: "v1alpha1", Kind: "ClusterRoleBindingList"}: {},
{Group: "rbac.authorization.k8s.io", Version: "v1alpha1", Kind: "RoleBinding"}: {},
{Group: "rbac.authorization.k8s.io", Version: "v1alpha1", Kind: "RoleBindingList"}: {},<|fim▁hole|> {Group: "rbac.authorization.k8s.io", Version: "v1", Kind: "ClusterRoleBinding"}: {},
{Group: "rbac.authorization.k8s.io", Version: "v1", Kind: "ClusterRoleBindingList"}: {},
{Group: "rbac.authorization.k8s.io", Version: "v1", Kind: "RoleBinding"}: {},
{Group: "rbac.authorization.k8s.io", Version: "v1", Kind: "RoleBindingList"}: {},
{Group: "settings.k8s.io", Version: "v1alpha1", Kind: "PodPreset"}: {},
{Group: "settings.k8s.io", Version: "v1alpha1", Kind: "PodPresetList"}: {},
{Group: "admissionregistration.k8s.io", Version: "v1beta1", Kind: "ValidatingWebhookConfiguration"}: {},
{Group: "admissionregistration.k8s.io", Version: "v1beta1", Kind: "ValidatingWebhookConfigurationList"}: {},
{Group: "admissionregistration.k8s.io", Version: "v1beta1", Kind: "MutatingWebhookConfiguration"}: {},
{Group: "admissionregistration.k8s.io", Version: "v1beta1", Kind: "MutatingWebhookConfigurationList"}: {},
{Group: "networking.k8s.io", Version: "v1", Kind: "NetworkPolicy"}: {},
{Group: "networking.k8s.io", Version: "v1", Kind: "NetworkPolicyList"}: {},
{Group: "storage.k8s.io", Version: "v1beta1", Kind: "StorageClass"}: {},
{Group: "storage.k8s.io", Version: "v1beta1", Kind: "StorageClassList"}: {},
{Group: "storage.k8s.io", Version: "v1", Kind: "StorageClass"}: {},
{Group: "storage.k8s.io", Version: "v1", Kind: "StorageClassList"}: {},
{Group: "authentication.k8s.io", Version: "v1", Kind: "TokenRequest"}: {},
}
f := fuzz.New().NilChance(.5).NumElements(1, 1).RandSource(rand.NewSource(1))
f.Funcs(
func(s *runtime.RawExtension, c fuzz.Continue) {},
func(s *metav1.LabelSelector, c fuzz.Continue) {
c.FuzzNoCustom(s)
s.MatchExpressions = nil // need to fuzz this specially
},
func(s *metav1.ListOptions, c fuzz.Continue) {
c.FuzzNoCustom(s)
s.LabelSelector = "" // need to fuzz requirement strings specially
s.FieldSelector = "" // need to fuzz requirement strings specially
},
func(s *extensionsv1beta1.ScaleStatus, c fuzz.Continue) {
c.FuzzNoCustom(s)
s.TargetSelector = "" // need to fuzz requirement strings specially
},
)
scheme := legacyscheme.Scheme
var testTypes orderedGroupVersionKinds
for gvk := range scheme.AllKnownTypes() {
if gvk.Version == runtime.APIVersionInternal {
continue
}
testTypes = append(testTypes, gvk)
}
sort.Sort(testTypes)
for _, gvk := range testTypes {
_, expectedChanged := typesWithDefaulting[gvk]
iter := 0
changedOnce := false
for {
if iter > *roundtrip.FuzzIters {
if !expectedChanged || changedOnce {
break
}
if iter > 300 {
t.Errorf("expected %s to trigger defaulting due to fuzzing", gvk)
break
}
// if we expected defaulting, continue looping until the fuzzer gives us one
// at worst, we will timeout
}
iter++
src, err := scheme.New(gvk)
if err != nil {
t.Fatal(err)
}
f.Fuzz(src)
src.GetObjectKind().SetGroupVersionKind(schema.GroupVersionKind{})
original := src.DeepCopyObject()
// get internal
withDefaults := src.DeepCopyObject()
scheme.Default(withDefaults.(runtime.Object))
if !reflect.DeepEqual(original, withDefaults) {
changedOnce = true
if !expectedChanged {
t.Errorf("{Group: \"%s\", Version: \"%s\", Kind: \"%s\"} did not expect defaults to be set - update expected or check defaulter registering: %s", gvk.Group, gvk.Version, gvk.Kind, diff.ObjectReflectDiff(original, withDefaults))
}
}
}
}
}
func BenchmarkPodDefaulting(b *testing.B) {
f := fuzz.New().NilChance(.5).NumElements(1, 1).RandSource(rand.NewSource(1))
items := make([]apiv1.Pod, 100)
for i := range items {
f.Fuzz(&items[i])
}
scheme := legacyscheme.Scheme
b.ResetTimer()
for i := 0; i < b.N; i++ {
pod := &items[i%len(items)]
scheme.Default(pod)
}
b.StopTimer()
}<|fim▁end|>
|
{Group: "rbac.authorization.k8s.io", Version: "v1beta1", Kind: "ClusterRoleBinding"}: {},
{Group: "rbac.authorization.k8s.io", Version: "v1beta1", Kind: "ClusterRoleBindingList"}: {},
{Group: "rbac.authorization.k8s.io", Version: "v1beta1", Kind: "RoleBinding"}: {},
{Group: "rbac.authorization.k8s.io", Version: "v1beta1", Kind: "RoleBindingList"}: {},
|
<|file_name|>convert_web_app.cc<|end_file_name|><|fim▁begin|>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/convert_web_app.h"
#include <cmath>
#include <limits>
#include <string>
#include <vector>
#include "base/base64.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/json/json_file_value_serializer.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/scoped_temp_dir.h"
#include "base/stringprintf.h"
#include "base/time.h"
#include "base/utf_string_conversions.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/extensions/extension_manifest_constants.h"
#include "chrome/common/extensions/extension_file_util.h"
#include "chrome/common/web_apps.h"
#include "crypto/sha2.h"
#include "googleurl/src/gurl.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/gfx/codec/png_codec.h"
namespace keys = extension_manifest_keys;
using base::Time;
namespace {
const char kIconsDirName[] = "icons";
// Create the public key for the converted web app.
//
// Web apps are not signed, but the public key for an extension doubles as
// its unique identity, and we need one of those. A web app's unique identity
// is its manifest URL, so we hash that to create a public key. There will be
// no corresponding private key, which means that these extensions cannot be
// auto-updated using ExtensionUpdater. But Chrome does notice updates to the
// manifest and regenerates these extensions.
std::string GenerateKey(const GURL& manifest_url) {
char raw[crypto::kSHA256Length] = {0};
std::string key;
crypto::SHA256HashString(manifest_url.spec().c_str(), raw,
crypto::kSHA256Length);
base::Base64Encode(std::string(raw, crypto::kSHA256Length), &key);
return key;
}
}
// Generates a version for the converted app using the current date. This isn't
// really needed, but it seems like useful information.
std::string ConvertTimeToExtensionVersion(const Time& create_time) {
Time::Exploded create_time_exploded;
create_time.UTCExplode(&create_time_exploded);
double micros = static_cast<double>(
(create_time_exploded.millisecond * Time::kMicrosecondsPerMillisecond) +
(create_time_exploded.second * Time::kMicrosecondsPerSecond) +
(create_time_exploded.minute * Time::kMicrosecondsPerMinute) +
(create_time_exploded.hour * Time::kMicrosecondsPerHour));
double day_fraction = micros / Time::kMicrosecondsPerDay;
double stamp = day_fraction * std::numeric_limits<uint16>::max();
// Ghetto-round, since VC++ doesn't have round().
stamp = stamp >= (floor(stamp) + 0.5) ? (stamp + 1) : stamp;
return base::StringPrintf("%i.%i.%i.%i",
create_time_exploded.year,
create_time_exploded.month,
create_time_exploded.day_of_month,
static_cast<uint16>(stamp));
}
scoped_refptr<Extension> ConvertWebAppToExtension(
const WebApplicationInfo& web_app,
const Time& create_time) {
FilePath user_data_temp_dir = extension_file_util::GetUserDataTempDir();
if (user_data_temp_dir.empty()) {
LOG(ERROR) << "Could not get path to profile temporary directory.";
return NULL;
}
<|fim▁hole|> if (!temp_dir.CreateUniqueTempDirUnderPath(user_data_temp_dir)) {
LOG(ERROR) << "Could not create temporary directory.";
return NULL;
}
// Create the manifest
scoped_ptr<DictionaryValue> root(new DictionaryValue);
if (!web_app.is_bookmark_app)
root->SetString(keys::kPublicKey, GenerateKey(web_app.manifest_url));
else
root->SetString(keys::kPublicKey, GenerateKey(web_app.app_url));
root->SetString(keys::kName, UTF16ToUTF8(web_app.title));
root->SetString(keys::kVersion, ConvertTimeToExtensionVersion(create_time));
root->SetString(keys::kDescription, UTF16ToUTF8(web_app.description));
root->SetString(keys::kLaunchWebURL, web_app.app_url.spec());
if (!web_app.launch_container.empty())
root->SetString(keys::kLaunchContainer, web_app.launch_container);
// Add the icons.
DictionaryValue* icons = new DictionaryValue();
root->Set(keys::kIcons, icons);
for (size_t i = 0; i < web_app.icons.size(); ++i) {
std::string size = StringPrintf("%i", web_app.icons[i].width);
std::string icon_path = StringPrintf("%s/%s.png", kIconsDirName,
size.c_str());
icons->SetString(size, icon_path);
}
// Add the permissions.
ListValue* permissions = new ListValue();
root->Set(keys::kPermissions, permissions);
for (size_t i = 0; i < web_app.permissions.size(); ++i) {
permissions->Append(Value::CreateStringValue(web_app.permissions[i]));
}
// Add the URLs.
ListValue* urls = new ListValue();
root->Set(keys::kWebURLs, urls);
for (size_t i = 0; i < web_app.urls.size(); ++i) {
urls->Append(Value::CreateStringValue(web_app.urls[i].spec()));
}
// Write the manifest.
FilePath manifest_path = temp_dir.path().Append(
Extension::kManifestFilename);
JSONFileValueSerializer serializer(manifest_path);
if (!serializer.Serialize(*root)) {
LOG(ERROR) << "Could not serialize manifest.";
return NULL;
}
// Write the icon files.
FilePath icons_dir = temp_dir.path().AppendASCII(kIconsDirName);
if (!file_util::CreateDirectory(icons_dir)) {
LOG(ERROR) << "Could not create icons directory.";
return NULL;
}
for (size_t i = 0; i < web_app.icons.size(); ++i) {
// Skip unfetched bitmaps.
if (web_app.icons[i].data.config() == SkBitmap::kNo_Config)
continue;
FilePath icon_file = icons_dir.AppendASCII(
StringPrintf("%i.png", web_app.icons[i].width));
std::vector<unsigned char> image_data;
if (!gfx::PNGCodec::EncodeBGRASkBitmap(web_app.icons[i].data,
false,
&image_data)) {
LOG(ERROR) << "Could not create icon file.";
return NULL;
}
const char* image_data_ptr = reinterpret_cast<const char*>(&image_data[0]);
if (!file_util::WriteFile(icon_file, image_data_ptr, image_data.size())) {
LOG(ERROR) << "Could not write icon file.";
return NULL;
}
}
// Finally, create the extension object to represent the unpacked directory.
std::string error;
int extension_flags = Extension::STRICT_ERROR_CHECKS;
if (web_app.is_bookmark_app)
extension_flags |= Extension::FROM_BOOKMARK;
scoped_refptr<Extension> extension = Extension::Create(
temp_dir.path(),
Extension::INTERNAL,
*root,
extension_flags,
&error);
if (!extension) {
LOG(ERROR) << error;
return NULL;
}
temp_dir.Take(); // The caller takes ownership of the directory.
return extension;
}<|fim▁end|>
|
ScopedTempDir temp_dir;
|
<|file_name|>21.py<|end_file_name|><|fim▁begin|>class amicable():
def d(self, n):
if n == 1:
return 0
else:
sum_of_factors = 0
for i in range(1, int(n**0.5)+1):
if n % i == 0:
sum_of_factors += i
if n/i != n:
sum_of_factors += int(n/i)<|fim▁hole|>
def __call__(self, n):
sum_of_amicable = 0
for i in range(1, n):
original = i, amicable.d(self, i)
inverse = amicable.d(self, amicable.d(self, i)), amicable.d(self, i)
if (original == inverse) & (amicable.d(self, i) != i):
sum_of_amicable += i
return sum_of_amicable
def main():
euler_21 = amicable()
n=10000
print(euler_21(n))
if __name__ == "__main__":
main()<|fim▁end|>
|
return sum_of_factors
|
<|file_name|>trait-cast-generic.rs<|end_file_name|><|fim▁begin|>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Testing casting of a generic Struct to a Trait with a generic method.
// This is test for issue 10955.
#[allow(unused_variable)];
trait Foo {<|fim▁hole|>
struct Bar<T> {
x: T,
}
impl<T> Foo for Bar<T> { }
pub fn main() {
let a = Bar { x: 1 };
let b = &a as &Foo;
}<|fim▁end|>
|
fn f<A>(a: A) -> A {
a
}
}
|
<|file_name|>server_test.go<|end_file_name|><|fim▁begin|>package server
import (<|fim▁hole|> "testing"
"golang.org/x/net/context"
"github.com/quilt/quilt/api/pb"
"github.com/quilt/quilt/db"
"github.com/quilt/quilt/stitch"
"github.com/stretchr/testify/assert"
)
func checkQuery(t *testing.T, s server, table db.TableType, exp string) {
reply, err := s.Query(context.Background(),
&pb.DBQuery{Table: string(table)})
assert.NoError(t, err)
assert.Equal(t, exp, reply.TableContents, "Wrong query response")
}
func TestMachineResponse(t *testing.T) {
t.Parallel()
conn := db.New()
conn.Txn(db.AllTables...).Run(func(view db.Database) error {
m := view.InsertMachine()
m.Role = db.Master
m.Provider = db.Amazon
m.Size = "size"
m.PublicIP = "8.8.8.8"
m.PrivateIP = "9.9.9.9"
view.Commit(m)
return nil
})
exp := `[{"ID":1,"StitchID":"","Role":"Master","Provider":"Amazon","Region":"",` +
`"Size":"size","DiskSize":0,"SSHKeys":null,"FloatingIP":"",` +
`"Preemptible":false,"CloudID":"","PublicIP":"8.8.8.8",` +
`"PrivateIP":"9.9.9.9","Connected":false}]`
checkQuery(t, server{conn}, db.MachineTable, exp)
}
func TestContainerResponse(t *testing.T) {
t.Parallel()
conn := db.New()
conn.Txn(db.AllTables...).Run(func(view db.Database) error {
c := view.InsertContainer()
c.DockerID = "docker-id"
c.Image = "image"
c.Command = []string{"cmd", "arg"}
c.Labels = []string{"labelA", "labelB"}
view.Commit(c)
return nil
})
exp := `[{"DockerID":"docker-id","Command":["cmd","arg"],` +
`"Labels":["labelA","labelB"],"Created":"0001-01-01T00:00:00Z",` +
`"Image":"image"}]`
checkQuery(t, server{conn}, db.ContainerTable, exp)
}
func TestBadDeployment(t *testing.T) {
conn := db.New()
s := server{conn: conn}
badDeployment := `{`
_, err := s.Deploy(context.Background(),
&pb.DeployRequest{Deployment: badDeployment})
assert.EqualError(t, err, "unexpected end of JSON input")
}
func TestInvalidImage(t *testing.T) {
conn := db.New()
s := server{conn: conn}
testInvalidImage(t, s, "has:morethan:two:colons",
"could not parse container image has:morethan:two:colons: "+
"invalid reference format")
testInvalidImage(t, s, "has-empty-tag:",
"could not parse container image has-empty-tag:: "+
"invalid reference format")
testInvalidImage(t, s, "has-empty-tag::digest",
"could not parse container image has-empty-tag::digest: "+
"invalid reference format")
testInvalidImage(t, s, "hasCapital",
"could not parse container image hasCapital: "+
"invalid reference format: repository name must be lowercase")
}
func testInvalidImage(t *testing.T, s server, img, expErr string) {
deployment := fmt.Sprintf(`
{"Containers":[
{"ID": "1",
"Image": {"Name": "%s"},
"Command":[
"sleep",
"10000"
],
"Env": {}
}]}`, img)
_, err := s.Deploy(context.Background(),
&pb.DeployRequest{Deployment: deployment})
assert.EqualError(t, err, expErr)
}
func TestDeploy(t *testing.T) {
conn := db.New()
s := server{conn: conn}
createMachineDeployment := `
{"Machines":[
{"Provider":"Amazon",
"Role":"Master",
"Size":"m4.large"
}, {"Provider":"Amazon",
"Role":"Worker",
"Size":"m4.large"
}]}`
_, err := s.Deploy(context.Background(),
&pb.DeployRequest{Deployment: createMachineDeployment})
assert.NoError(t, err)
var spec string
conn.Txn(db.AllTables...).Run(func(view db.Database) error {
clst, err := view.GetCluster()
assert.NoError(t, err)
spec = clst.Spec
return nil
})
exp, err := stitch.FromJSON(createMachineDeployment)
assert.NoError(t, err)
actual, err := stitch.FromJSON(spec)
assert.NoError(t, err)
assert.Equal(t, exp, actual)
}
func TestVagrantDeployment(t *testing.T) {
conn := db.New()
s := server{conn: conn}
vagrantDeployment := `
{"Machines":[
{"Provider":"Vagrant",
"Role":"Master",
"Size":"m4.large"
}, {"Provider":"Vagrant",
"Role":"Worker",
"Size":"m4.large"
}]}`
vagrantErrMsg := "The Vagrant provider is in development." +
" The stitch will continue to run, but" +
" probably won't work correctly."
_, err := s.Deploy(context.Background(),
&pb.DeployRequest{Deployment: vagrantDeployment})
assert.Error(t, err, vagrantErrMsg)
var spec string
conn.Txn(db.AllTables...).Run(func(view db.Database) error {
clst, err := view.GetCluster()
assert.NoError(t, err)
spec = clst.Spec
return nil
})
exp, err := stitch.FromJSON(vagrantDeployment)
assert.NoError(t, err)
actual, err := stitch.FromJSON(spec)
assert.NoError(t, err)
assert.Equal(t, exp, actual)
}<|fim▁end|>
|
"fmt"
|
<|file_name|>transcribe.rs<|end_file_name|><|fim▁begin|>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use self::LockstepIterSize::*;
use ast;
use ast::{TokenTree, TtDelimited, TtToken, TtSequence, Ident};
use codemap::{Span, DUMMY_SP};
use diagnostic::SpanHandler;
use ext::tt::macro_parser::{NamedMatch, MatchedSeq, MatchedNonterminal};
use parse::token::{Eof, DocComment, Interpolated, MatchNt, SubstNt};
use parse::token::{Token, NtIdent, SpecialMacroVar};
use parse::token;
use parse::lexer::TokenAndSpan;
use std::rc::Rc;
use std::ops::Add;
use std::collections::HashMap;
///an unzipping of `TokenTree`s
#[derive(Clone)]
struct TtFrame {
forest: TokenTree,
idx: uint,
dotdotdoted: bool,
sep: Option<Token>,
}
#[derive(Clone)]
pub struct TtReader<'a> {
pub sp_diag: &'a SpanHandler,
/// the unzipped tree:
stack: Vec<TtFrame>,
/* for MBE-style macro transcription */
interpolations: HashMap<Ident, Rc<NamedMatch>>,
imported_from: Option<Ident>,
// Some => return imported_from as the next token
crate_name_next: Option<Span>,
repeat_idx: Vec<uint>,
repeat_len: Vec<uint>,
/* cached: */
pub cur_tok: Token,
pub cur_span: Span,
/// Transform doc comments. Only useful in macro invocations
pub desugar_doc_comments: bool,
}
/// This can do Macro-By-Example transcription. On the other hand, if
/// `src` contains no `TtSequence`s, `MatchNt`s or `SubstNt`s, `interp` can
/// (and should) be None.
pub fn new_tt_reader<'a>(sp_diag: &'a SpanHandler,
interp: Option<HashMap<Ident, Rc<NamedMatch>>>,
imported_from: Option<Ident>,
src: Vec<ast::TokenTree>)
-> TtReader<'a> {
new_tt_reader_with_doc_flag(sp_diag, interp, imported_from, src, false)
}
/// The extra `desugar_doc_comments` flag enables reading doc comments
/// like any other attribute which consists of `meta` and surrounding #[ ] tokens.
///
/// This can do Macro-By-Example transcription. On the other hand, if
/// `src` contains no `TtSequence`s, `MatchNt`s or `SubstNt`s, `interp` can
/// (and should) be None.
pub fn new_tt_reader_with_doc_flag<'a>(sp_diag: &'a SpanHandler,
interp: Option<HashMap<Ident, Rc<NamedMatch>>>,
imported_from: Option<Ident>,
src: Vec<ast::TokenTree>,
desugar_doc_comments: bool)
-> TtReader<'a> {
let mut r = TtReader {
sp_diag: sp_diag,
stack: vec!(TtFrame {
forest: TtSequence(DUMMY_SP, Rc::new(ast::SequenceRepetition {
tts: src,
// doesn't matter. This merely holds the root unzipping.
separator: None, op: ast::ZeroOrMore, num_captures: 0
})),
idx: 0,
dotdotdoted: false,
sep: None,
}),
interpolations: match interp { /* just a convenience */
None => HashMap::new(),
Some(x) => x,
},
imported_from: imported_from,
crate_name_next: None,
repeat_idx: Vec::new(),
repeat_len: Vec::new(),
desugar_doc_comments: desugar_doc_comments,
/* dummy values, never read: */
cur_tok: token::Eof,
cur_span: DUMMY_SP,
};
tt_next_token(&mut r); /* get cur_tok and cur_span set up */
r
}
fn lookup_cur_matched_by_matched(r: &TtReader, start: Rc<NamedMatch>) -> Rc<NamedMatch> {
r.repeat_idx.iter().fold(start, |ad, idx| {
match *ad {
MatchedNonterminal(_) => {
// end of the line; duplicate henceforth
ad.clone()
}
MatchedSeq(ref ads, _) => ads[*idx].clone()
}
})
}
fn lookup_cur_matched(r: &TtReader, name: Ident) -> Option<Rc<NamedMatch>> {
let matched_opt = r.interpolations.get(&name).cloned();
matched_opt.map(|s| lookup_cur_matched_by_matched(r, s))
}
#[derive(Clone)]
enum LockstepIterSize {
LisUnconstrained,
LisConstraint(uint, Ident),
LisContradiction(String),
}
impl Add for LockstepIterSize {
type Output = LockstepIterSize;
fn add(self, other: LockstepIterSize) -> LockstepIterSize {
match self {
LisUnconstrained => other,
LisContradiction(_) => self,
LisConstraint(l_len, ref l_id) => match other {
LisUnconstrained => self.clone(),
LisContradiction(_) => other,
LisConstraint(r_len, _) if l_len == r_len => self.clone(),
LisConstraint(r_len, r_id) => {
let l_n = token::get_ident(l_id.clone());
let r_n = token::get_ident(r_id);
LisContradiction(format!("inconsistent lockstep iteration: \
'{:?}' has {} items, but '{:?}' has {}",
l_n, l_len, r_n, r_len).to_string())
}
},
}
}
}
fn lockstep_iter_size(t: &TokenTree, r: &TtReader) -> LockstepIterSize {
match *t {
TtDelimited(_, ref delimed) => {
delimed.tts.iter().fold(LisUnconstrained, |size, tt| {
size + lockstep_iter_size(tt, r)
})
},
TtSequence(_, ref seq) => {
seq.tts.iter().fold(LisUnconstrained, |size, tt| {
size + lockstep_iter_size(tt, r)
})
},
TtToken(_, SubstNt(name, _)) | TtToken(_, MatchNt(name, _, _, _)) =>
match lookup_cur_matched(r, name) {
Some(matched) => match *matched {
MatchedNonterminal(_) => LisUnconstrained,
MatchedSeq(ref ads, _) => LisConstraint(ads.len(), name),
},
_ => LisUnconstrained
},
TtToken(..) => LisUnconstrained,
}
}
/// Return the next token from the TtReader.
/// EFFECT: advances the reader's token field
pub fn tt_next_token(r: &mut TtReader) -> TokenAndSpan {
// FIXME(pcwalton): Bad copy?
let ret_val = TokenAndSpan {
tok: r.cur_tok.clone(),
sp: r.cur_span.clone(),
};
loop {
match r.crate_name_next.take() {
None => (),
Some(sp) => {
r.cur_span = sp;
r.cur_tok = token::Ident(r.imported_from.unwrap(), token::Plain);
return ret_val;
},
}
let should_pop = match r.stack.last() {
None => {
assert_eq!(ret_val.tok, token::Eof);
return ret_val;
}
Some(frame) => {
if frame.idx < frame.forest.len() {
break;
}
!frame.dotdotdoted ||
*r.repeat_idx.last().unwrap() == *r.repeat_len.last().unwrap() - 1
}
};
/* done with this set; pop or repeat? */
if should_pop {
let prev = r.stack.pop().unwrap();
match r.stack.last_mut() {
None => {
r.cur_tok = token::Eof;
return ret_val;
}
Some(frame) => {
frame.idx += 1;
}
}
if prev.dotdotdoted {
r.repeat_idx.pop();
r.repeat_len.pop();
}
} else { /* repeat */
*r.repeat_idx.last_mut().unwrap() += 1u;
r.stack.last_mut().unwrap().idx = 0;
match r.stack.last().unwrap().sep.clone() {
Some(tk) => {
r.cur_tok = tk; /* repeat same span, I guess */
return ret_val;
}
None => {}
}
}
}
loop { /* because it's easiest, this handles `TtDelimited` not starting
with a `TtToken`, even though it won't happen */
let t = {
let frame = r.stack.last().unwrap();
// FIXME(pcwalton): Bad copy.
frame.forest.get_tt(frame.idx)
};
match t {
TtSequence(sp, seq) => {
// FIXME(pcwalton): Bad copy.
match lockstep_iter_size(&TtSequence(sp, seq.clone()),
r) {
LisUnconstrained => {
r.sp_diag.span_fatal(
sp.clone(), /* blame macro writer */
"attempted to repeat an expression \
containing no syntax \
variables matched as repeating at this depth");
}
LisContradiction(ref msg) => {
// FIXME #2887 blame macro invoker instead<|fim▁hole|> if len == 0 {
if seq.op == ast::OneOrMore {
// FIXME #2887 blame invoker
r.sp_diag.span_fatal(sp.clone(),
"this must repeat at least once");
}
r.stack.last_mut().unwrap().idx += 1;
return tt_next_token(r);
}
r.repeat_len.push(len);
r.repeat_idx.push(0);
r.stack.push(TtFrame {
idx: 0,
dotdotdoted: true,
sep: seq.separator.clone(),
forest: TtSequence(sp, seq),
});
}
}
}
// FIXME #2887: think about span stuff here
TtToken(sp, SubstNt(ident, namep)) => {
r.stack.last_mut().unwrap().idx += 1;
match lookup_cur_matched(r, ident) {
None => {
r.cur_span = sp;
r.cur_tok = SubstNt(ident, namep);
return ret_val;
// this can't be 0 length, just like TtDelimited
}
Some(cur_matched) => {
match *cur_matched {
// sidestep the interpolation tricks for ident because
// (a) idents can be in lots of places, so it'd be a pain
// (b) we actually can, since it's a token.
MatchedNonterminal(NtIdent(box sn, b)) => {
r.cur_span = sp;
r.cur_tok = token::Ident(sn, b);
return ret_val;
}
MatchedNonterminal(ref other_whole_nt) => {
// FIXME(pcwalton): Bad copy.
r.cur_span = sp;
r.cur_tok = token::Interpolated((*other_whole_nt).clone());
return ret_val;
}
MatchedSeq(..) => {
r.sp_diag.span_fatal(
r.cur_span, /* blame the macro writer */
&format!("variable '{:?}' is still repeating at this depth",
token::get_ident(ident))[]);
}
}
}
}
}
// TtDelimited or any token that can be unzipped
seq @ TtDelimited(..) | seq @ TtToken(_, MatchNt(..)) => {
// do not advance the idx yet
r.stack.push(TtFrame {
forest: seq,
idx: 0,
dotdotdoted: false,
sep: None
});
// if this could be 0-length, we'd need to potentially recur here
}
TtToken(sp, DocComment(name)) if r.desugar_doc_comments => {
r.stack.push(TtFrame {
forest: TtToken(sp, DocComment(name)),
idx: 0,
dotdotdoted: false,
sep: None
});
}
TtToken(sp, token::SpecialVarNt(SpecialMacroVar::CrateMacroVar)) => {
r.stack.last_mut().unwrap().idx += 1;
if r.imported_from.is_some() {
r.cur_span = sp;
r.cur_tok = token::ModSep;
r.crate_name_next = Some(sp);
return ret_val;
}
// otherwise emit nothing and proceed to the next token
}
TtToken(sp, tok) => {
r.cur_span = sp;
r.cur_tok = tok;
r.stack.last_mut().unwrap().idx += 1;
return ret_val;
}
}
}
}<|fim▁end|>
|
r.sp_diag.span_fatal(sp.clone(), &msg[]);
}
LisConstraint(len, _) => {
|
<|file_name|>c.go<|end_file_name|><|fim▁begin|>// Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package c<|fim▁hole|> "b"
)
type BI interface {
Something(s int64) int64
Another(pxp a.G) int32
}
func BRS(sd *b.ServiceDesc, server BI, xyz int) *b.Service {
return b.RS(sd, server, 7)
}<|fim▁end|>
|
import (
"a"
|
<|file_name|>353DesignSnakeGame.py<|end_file_name|><|fim▁begin|>class SnakeGame:
def __init__(self, width, height, food):
"""
Initialize your data structure here.
@param width - screen width
@param height - screen height
@param food - A list of food positions
E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0].
:type width: int
:type height: int
:type food: List[List[int]]
"""
self.w, self.h = width, height
self.food = food
self.idx = 0
self.snake = collections.deque([(0, 0)])
self.snake_set = set([(0, 0)])
self.game_state = True
def move(self, direction):
"""
Moves the snake.
@param direction - 'U' = Up, 'L' = Left, 'R' = Right, 'D' = Down
@return The game's score after the move. Return -1 if game over.
Game over when snake crosses the screen boundary or bites its body.
:type direction: str
:rtype: int
"""
if not self.game_state: return -1
directions = {'U': (-1, 0), 'L': (0, -1), 'R': (0, 1), 'D': (1, 0)}
head = self.snake[0]
n_x = head[0] + directions[direction][0]
n_y = head[1] + directions[direction][1]
if not (0 <= n_x < self.h and 0 <= n_y < self.w):
self.game_state = False
return -1 <|fim▁hole|> if (n_x, n_y) != self.snake[-1] and (n_x, n_y) in self.snake_set:
self.game_state = False
return -1
if self.idx < len(self.food) and self.food[self.idx] == [n_x, n_y]:
self.idx += 1
else:
self.snake_set.remove(self.snake[-1])
self.snake.pop()
self.snake.appendleft((n_x, n_y))
self.snake_set.add((n_x, n_y))
return self.idx
# Your SnakeGame object will be instantiated and called as such:
# obj = SnakeGame(width, height, food)
# param_1 = obj.move(direction)<|fim▁end|>
| |
<|file_name|>run_pseudo_tasks_slurm.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import sys
import argparse
import datetime
import time
import gettext
from pseudo_cluster.task import Task_record
from pseudo_cluster.tasks_list import Tasks_list
from pseudo_cluster.extended_task import Extended_task_record
from pseudo_cluster.actions_list import Action_list
def get_submit_string(self,time_limit,duration):
"""
Функция генерирует строку для submit
задачи в очередь slurm
"""
s=list()
s.append("sbatch")
#
# Uncomment for debug slurm
#
#s.append("-vv")
s.append("--account=%s" % self.task_class)
s.append("--comment=\"Pseudo cluster emulating task\"")
s.append("--job-name=\"pseudo_cluster|%s|%s\"" % (self.job_id, self.job_name))
try:
limit=self.other["memory_limit"]
except KeyError:
limit="0"
if int(limit) > 0:
s.append("--mem=%d" % int(limit))
s.append("--ntasks=%d" % self.required_cpus)
s.append("--partition=%s" % self.partition)
if self.priority !=0:
s.append("--priority=%d" % self.priority)
if time_limit > 0:
s.append("--time=%d" % time_limit)
#
# Path to this script must be available
# from environment variable PATH
#
s.append(self.path_to_task)
s.append("-t")
s.append(str(duration))
s.append("-s")
s.append(self.task_state)
return s
def get_cancel_string(self):
return [ "scancel" , str(self.actual_task_id) ]
def parse_task_id(self,f,first_line):
"""
Выковыривает ID задачи из файла и первой строчки,
которая была до этого прочитана в файле.
файл не закрывает.
"""
try:
tup=first_line.split(' ')
except:
return False
if (tup[0] == "Submitted") and (tup[1] == "batch"):
self.actual_task_id=int(tup[3])
return True
return False
def main(argv=None):
"""
То, с чего начинается программа
"""
if argv == None:
argv=sys.argv
gettext.install('pseudo-cluster')
parser= argparse.ArgumentParser(
description=_("""
Данная программа осуществляет постановку задач в очередь Slurm.
Список задач получается из файла статистики. При этом программа
ставит задачу в очередь с идентификатором пользователя и группы,
как они были указаны в статистике. Всё используемое задачами
время сжимается согласно коэффициента, и вместо реалного кода
программы, запускавшейся задачи запускается скрипт, который ничего
не делает определённое количество секунд.
"""),
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
epilog=_("Например можно запустить так:\n ")+argv[0]+" --time-compress 30"
)
parser.add_argument(
'--time-compress',
dest='compress_times',
type=int,
required=True,
help=_("Во сколько раз сжимать время. Напиример: 10")
)
parser.add_argument(
'--time-interval',
dest='interval',
type=int,
required=False,
default=2,
help=_("Раз во сколько минут обращаться к системе ведения очередей")
)
parser.add_argument(
'--prefix',
dest='prefix',
required=False,
default="./",
help=_("префикс, по которому находится файл со статистикой")
)
parser.add_argument(
'--path-to-task-script',
dest='path_to_task',
required=False,
default="/usr/local/bin/pseudo_cluster_task.sh",<|fim▁hole|> )
args=parser.parse_args()
if os.geteuid() != 0:
print _("""
Данная программа требует
полномочий пользователя root.
Запустите её от имени пользователя root,
либо с использованием команды sudo.
""")
return 2
#
# Регистрация методов, которые будут вызываться для объекта
# класса Extended_task_record
#
Extended_task_record.get_submit_string=get_submit_string
Extended_task_record.get_cancel_string=get_cancel_string
Extended_task_record.parse_task_id=parse_task_id
tasks_list=Tasks_list()
tasks_list.read_statistics_from_file(args.prefix)
extended_tasks=dict()
num_tasks=len(tasks_list)
begin_time=tasks_list[0].time_submit
last_task=0;
actions_list=Action_list()
while last_task != num_tasks-1:
end_time=begin_time+datetime.timedelta(minutes=args.interval*args.compress_times)
begin_actions_time=datetime.datetime.utcnow()
for i in xrange(0,num_tasks):
if i < last_task:
continue
task=tasks_list[i]
if task.time_submit < begin_time:
last_task=i
if task.time_submit < end_time:
if task.job_id not in extended_tasks:
extended_task=Extended_task_record()
extended_task.fill_by_task(task,args.path_to_task)
actions_list.register_action(extended_task,"submit")
extended_tasks[task.job_id]=extended_task
if (task.time_end < end_time) and (task.task_state == "canceled"):
actions_list.register_action(extended_tasks[task.job_id],"cancel")
actions_list.do_actions(args.compress_times)
print begin_time
print end_time
print "last_task=%d, num_tasks=%d" % (last_task,num_tasks)
delay_value = datetime.datetime.utcnow()- begin_actions_time
if delay_value < datetime.timedelta(minutes=args.interval):
how_much_sleep=args.interval*60-delay_value.total_seconds()
print (_("will sleep %d") % how_much_sleep)
time.sleep(how_much_sleep)
begin_time=end_time
if __name__ == "__main__":
sys.exit(main())<|fim▁end|>
|
help=_("""
Путь до скрипта, который реализует тело задачи
в псевдокластере.
""")
|
<|file_name|>generic-alias-unique.rs<|end_file_name|><|fim▁begin|><|fim▁hole|>// 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
#![feature(box_syntax)]
fn id<T:Send>(t: T) -> T { return t; }
pub fn main() {
let expected: Box<_> = box 100;
let actual = id::<Box<isize>>(expected.clone());
println!("{}", *actual);
assert_eq!(*expected, *actual);
}<|fim▁end|>
|
// 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.
//
|
<|file_name|>os_project.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# Copyright (c) 2015 IBM Corporation
#
# This module 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 software 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 software. If not, see <http://www.gnu.org/licenses/>.
try:
import shade
HAS_SHADE = True
except ImportError:
HAS_SHADE = False
DOCUMENTATION = '''
---
module: os_project
short_description: Manage OpenStack Projects
extends_documentation_fragment: openstack
version_added: "2.0"
author: "Alberto Gireud (@agireud)"
description:
- Manage OpenStack Projects. Projects can be created,
updated or deleted using this module. A project will be updated
if I(name) matches an existing project and I(state) is present.
The value for I(name) cannot be updated without deleting and
re-creating the project.
options:
name:
description:
- Name for the project
required: true
description:
description:
- Description for the project
required: false
default: None
domain_id:
description:
- Domain id to create the project in if the cloud supports domains
required: false
default: None
aliases: ['domain']
enabled:
description:
- Is the project enabled
required: false
default: True
state:
description:
- Should the resource be present or absent.
choices: [present, absent]
default: present
requirements:
- "python >= 2.6"
- "shade"
'''
EXAMPLES = '''
# Create a project
- os_project:
cloud: mycloud
state: present
name: demoproject
description: demodescription
domain_id: demoid
enabled: True
# Delete a project
- os_project:
cloud: mycloud
state: absent
name: demoproject
'''
RETURN = '''
project:
description: Dictionary describing the project.
returned: On success when I(state) is 'present'
type: dictionary
contains:
id:
description: Project ID
type: string
sample: "f59382db809c43139982ca4189404650"
name:
description: Project name
type: string
sample: "demoproject"
description:
description: Project description
type: string
sample: "demodescription"
enabled:
description: Boolean to indicate if project is enabled
type: bool
sample: True
'''
def _needs_update(module, project):
keys = ('description', 'enabled')
for key in keys:
if module.params[key] is not None and module.params[key] != project.get(key):
return True
return False
def _system_state_change(module, project):
state = module.params['state']
if state == 'present':
if project is None:
changed = True<|fim▁hole|> else:
changed = False
elif state == 'absent':
if project is None:
changed=False
else:
changed=True
return changed;
def main():
argument_spec = openstack_full_argument_spec(
name=dict(required=True),
description=dict(required=False, default=None),
domain_id=dict(required=False, default=None, aliases=['domain']),
enabled=dict(default=True, type='bool'),
state=dict(default='present', choices=['absent', 'present'])
)
module_kwargs = openstack_module_kwargs()
module = AnsibleModule(
argument_spec,
supports_check_mode=True,
**module_kwargs
)
if not HAS_SHADE:
module.fail_json(msg='shade is required for this module')
name = module.params['name']
description = module.params['description']
domain = module.params.pop('domain_id')
enabled = module.params['enabled']
state = module.params['state']
try:
if domain:
opcloud = shade.operator_cloud(**module.params)
try:
# We assume admin is passing domain id
dom = opcloud.get_domain(domain)['id']
domain = dom
except:
# If we fail, maybe admin is passing a domain name.
# Note that domains have unique names, just like id.
try:
dom = opcloud.search_domains(filters={'name': domain})[0]['id']
domain = dom
except:
# Ok, let's hope the user is non-admin and passing a sane id
pass
cloud = shade.openstack_cloud(**module.params)
project = cloud.get_project(name)
if module.check_mode:
module.exit_json(changed=_system_state_change(module, project))
if state == 'present':
if project is None:
project = cloud.create_project(
name=name, description=description,
domain_id=domain,
enabled=enabled)
changed = True
else:
if _needs_update(module, project):
project = cloud.update_project(
project['id'], description=description,
enabled=enabled)
changed = True
else:
changed = False
module.exit_json(changed=changed, project=project)
elif state == 'absent':
if project is None:
changed=False
else:
cloud.delete_project(project['id'])
changed=True
module.exit_json(changed=changed)
except shade.OpenStackCloudException as e:
module.fail_json(msg=e.message, extra_data=e.extra_data)
from ansible.module_utils.basic import *
from ansible.module_utils.openstack import *
if __name__ == '__main__':
main()<|fim▁end|>
|
else:
if _needs_update(module, project):
changed = True
|
<|file_name|>webpack-eslint.js<|end_file_name|><|fim▁begin|>const getWebpackConfig = require('./get-webpack-config');
module.exports = {
globals: {
__DEV__: false,
__PROD__: false,
__DEVSERVER__: false,
__CLIENT__: false,
__SERVER__: false,
'process.env.NODE_ENV': false
},
settings: {
'import/resolver': {
webpack: {
config: getWebpackConfig()<|fim▁hole|>};<|fim▁end|>
|
}
}
}
|
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>pub type c_char = u8;
pub type wchar_t = u32;
pub type __u64 = ::c_ulonglong;
s! {
pub struct stat {
pub st_dev: ::dev_t,
pub st_ino: ::ino_t,
pub st_mode: ::c_uint,
pub st_nlink: ::nlink_t,
pub st_uid: ::uid_t,
pub st_gid: ::gid_t,
pub st_rdev: ::dev_t,
__pad1: ::c_ulong,
pub st_size: ::off64_t,
pub st_blksize: ::c_int,
__pad2: ::c_int,
pub st_blocks: ::c_long,
pub st_atime: ::time_t,
pub st_atime_nsec: ::c_long,
pub st_mtime: ::time_t,
pub st_mtime_nsec: ::c_long,
pub st_ctime: ::time_t,
pub st_ctime_nsec: ::c_long,
__unused4: ::c_uint,
__unused5: ::c_uint,
}
pub struct stat64 {
pub st_dev: ::dev_t,
pub st_ino: ::ino_t,
pub st_mode: ::c_uint,
pub st_nlink: ::nlink_t,
pub st_uid: ::uid_t,
pub st_gid: ::gid_t,
pub st_rdev: ::dev_t,
__pad1: ::c_ulong,
pub st_size: ::off64_t,
pub st_blksize: ::c_int,
__pad2: ::c_int,
pub st_blocks: ::c_long,
pub st_atime: ::time_t,
pub st_atime_nsec: ::c_long,
pub st_mtime: ::time_t,
pub st_mtime_nsec: ::c_long,
pub st_ctime: ::time_t,
pub st_ctime_nsec: ::c_long,
__unused4: ::c_uint,
__unused5: ::c_uint,
}
}
pub const O_DIRECT: ::c_int = 0x10000;
pub const O_DIRECTORY: ::c_int = 0x4000;
pub const O_NOFOLLOW: ::c_int = 0x8000;
pub const O_LARGEFILE: ::c_int = 0o400000;
pub const SIGSTKSZ: ::size_t = 16384;
pub const MINSIGSTKSZ: ::size_t = 5120;
// From NDK's asm/hwcap.h
pub const HWCAP_FP: ::c_ulong = 1 << 0;
pub const HWCAP_ASIMD: ::c_ulong = 1 << 1;
pub const HWCAP_EVTSTRM: ::c_ulong = 1 << 2;
pub const HWCAP_AES: ::c_ulong = 1 << 3;
pub const HWCAP_PMULL: ::c_ulong = 1 << 4;
pub const HWCAP_SHA1: ::c_ulong = 1 << 5;
pub const HWCAP_SHA2: ::c_ulong = 1 << 6;
pub const HWCAP_CRC32: ::c_ulong = 1 << 7;
pub const HWCAP_ATOMICS: ::c_ulong = 1 << 8;
pub const HWCAP_FPHP: ::c_ulong = 1 << 9;
pub const HWCAP_ASIMDHP: ::c_ulong = 1 << 10;
pub const HWCAP_CPUID: ::c_ulong = 1 << 11;
pub const HWCAP_ASIMDRDM: ::c_ulong = 1 << 12;
pub const HWCAP_JSCVT: ::c_ulong = 1 << 13;
pub const HWCAP_FCMA: ::c_ulong = 1 << 14;
pub const HWCAP_LRCPC: ::c_ulong = 1 << 15;
pub const HWCAP_DCPOP: ::c_ulong = 1 << 16;
pub const HWCAP_SHA3: ::c_ulong = 1 << 17;
pub const HWCAP_SM3: ::c_ulong = 1 << 18;
pub const HWCAP_SM4: ::c_ulong = 1 << 19;
pub const HWCAP_ASIMDDP: ::c_ulong = 1 << 20;
pub const HWCAP_SHA512: ::c_ulong = 1 << 21;
pub const HWCAP_SVE: ::c_ulong = 1 << 22;
pub const HWCAP_ASIMDFHM: ::c_ulong = 1 << 23;
pub const HWCAP_DIT: ::c_ulong = 1 << 24;
pub const HWCAP_USCAT: ::c_ulong = 1 << 25;
pub const HWCAP_ILRCPC: ::c_ulong = 1 << 26;
pub const HWCAP_FLAGM: ::c_ulong = 1 << 27;
pub const HWCAP_SSBS: ::c_ulong = 1 << 28;
pub const HWCAP_SB: ::c_ulong = 1 << 29;
pub const HWCAP_PACA: ::c_ulong = 1 << 30;
pub const HWCAP_PACG: ::c_ulong = 1 << 31;
pub const HWCAP2_DCPODP: ::c_ulong = 1 << 0;
pub const HWCAP2_SVE2: ::c_ulong = 1 << 1;
pub const HWCAP2_SVEAES: ::c_ulong = 1 << 2;
pub const HWCAP2_SVEPMULL: ::c_ulong = 1 << 3;
pub const HWCAP2_SVEBITPERM: ::c_ulong = 1 << 4;
pub const HWCAP2_SVESHA3: ::c_ulong = 1 << 5;
pub const HWCAP2_SVESM4: ::c_ulong = 1 << 6;
pub const HWCAP2_FLAGM2: ::c_ulong = 1 << 7;
pub const HWCAP2_FRINT: ::c_ulong = 1 << 8;
pub const SYS_io_setup: ::c_long = 0;
pub const SYS_io_destroy: ::c_long = 1;
pub const SYS_io_submit: ::c_long = 2;
pub const SYS_io_cancel: ::c_long = 3;
pub const SYS_io_getevents: ::c_long = 4;
pub const SYS_setxattr: ::c_long = 5;
pub const SYS_lsetxattr: ::c_long = 6;
pub const SYS_fsetxattr: ::c_long = 7;
pub const SYS_getxattr: ::c_long = 8;
pub const SYS_lgetxattr: ::c_long = 9;
pub const SYS_fgetxattr: ::c_long = 10;
pub const SYS_listxattr: ::c_long = 11;
pub const SYS_llistxattr: ::c_long = 12;
pub const SYS_flistxattr: ::c_long = 13;
pub const SYS_removexattr: ::c_long = 14;
pub const SYS_lremovexattr: ::c_long = 15;
pub const SYS_fremovexattr: ::c_long = 16;
pub const SYS_getcwd: ::c_long = 17;
pub const SYS_lookup_dcookie: ::c_long = 18;
pub const SYS_eventfd2: ::c_long = 19;
pub const SYS_epoll_create1: ::c_long = 20;
pub const SYS_epoll_ctl: ::c_long = 21;
pub const SYS_epoll_pwait: ::c_long = 22;
pub const SYS_dup: ::c_long = 23;
pub const SYS_dup3: ::c_long = 24;
pub const SYS_fcntl: ::c_long = 25;
pub const SYS_inotify_init1: ::c_long = 26;
pub const SYS_inotify_add_watch: ::c_long = 27;
pub const SYS_inotify_rm_watch: ::c_long = 28;
pub const SYS_ioctl: ::c_long = 29;
pub const SYS_ioprio_set: ::c_long = 30;
pub const SYS_ioprio_get: ::c_long = 31;
pub const SYS_flock: ::c_long = 32;
pub const SYS_mknodat: ::c_long = 33;
pub const SYS_mkdirat: ::c_long = 34;
pub const SYS_unlinkat: ::c_long = 35;
pub const SYS_symlinkat: ::c_long = 36;
pub const SYS_linkat: ::c_long = 37;
pub const SYS_renameat: ::c_long = 38;
pub const SYS_umount2: ::c_long = 39;
pub const SYS_mount: ::c_long = 40;
pub const SYS_pivot_root: ::c_long = 41;
pub const SYS_nfsservctl: ::c_long = 42;
pub const SYS_fallocate: ::c_long = 47;
pub const SYS_faccessat: ::c_long = 48;
pub const SYS_chdir: ::c_long = 49;
pub const SYS_fchdir: ::c_long = 50;
pub const SYS_chroot: ::c_long = 51;
pub const SYS_fchmod: ::c_long = 52;
pub const SYS_fchmodat: ::c_long = 53;
pub const SYS_fchownat: ::c_long = 54;
pub const SYS_fchown: ::c_long = 55;
pub const SYS_openat: ::c_long = 56;
pub const SYS_close: ::c_long = 57;
pub const SYS_vhangup: ::c_long = 58;
pub const SYS_pipe2: ::c_long = 59;
pub const SYS_quotactl: ::c_long = 60;
pub const SYS_getdents64: ::c_long = 61;
pub const SYS_read: ::c_long = 63;
pub const SYS_write: ::c_long = 64;
pub const SYS_readv: ::c_long = 65;
pub const SYS_writev: ::c_long = 66;
pub const SYS_pread64: ::c_long = 67;
pub const SYS_pwrite64: ::c_long = 68;
pub const SYS_preadv: ::c_long = 69;
pub const SYS_pwritev: ::c_long = 70;
pub const SYS_pselect6: ::c_long = 72;
pub const SYS_ppoll: ::c_long = 73;
pub const SYS_signalfd4: ::c_long = 74;
pub const SYS_vmsplice: ::c_long = 75;
pub const SYS_splice: ::c_long = 76;
pub const SYS_tee: ::c_long = 77;
pub const SYS_readlinkat: ::c_long = 78;
pub const SYS_sync: ::c_long = 81;
pub const SYS_fsync: ::c_long = 82;
pub const SYS_fdatasync: ::c_long = 83;
pub const SYS_sync_file_range: ::c_long = 84;
pub const SYS_timerfd_create: ::c_long = 85;
pub const SYS_timerfd_settime: ::c_long = 86;
pub const SYS_timerfd_gettime: ::c_long = 87;
pub const SYS_utimensat: ::c_long = 88;
pub const SYS_acct: ::c_long = 89;
pub const SYS_capget: ::c_long = 90;
pub const SYS_capset: ::c_long = 91;
pub const SYS_personality: ::c_long = 92;
pub const SYS_exit: ::c_long = 93;
pub const SYS_exit_group: ::c_long = 94;
pub const SYS_waitid: ::c_long = 95;
pub const SYS_set_tid_address: ::c_long = 96;
pub const SYS_unshare: ::c_long = 97;
pub const SYS_futex: ::c_long = 98;
pub const SYS_set_robust_list: ::c_long = 99;
pub const SYS_get_robust_list: ::c_long = 100;
pub const SYS_nanosleep: ::c_long = 101;
pub const SYS_getitimer: ::c_long = 102;
pub const SYS_setitimer: ::c_long = 103;
pub const SYS_kexec_load: ::c_long = 104;
pub const SYS_init_module: ::c_long = 105;
pub const SYS_delete_module: ::c_long = 106;
pub const SYS_timer_create: ::c_long = 107;
pub const SYS_timer_gettime: ::c_long = 108;
pub const SYS_timer_getoverrun: ::c_long = 109;
pub const SYS_timer_settime: ::c_long = 110;
pub const SYS_timer_delete: ::c_long = 111;
pub const SYS_clock_settime: ::c_long = 112;
pub const SYS_clock_gettime: ::c_long = 113;
pub const SYS_clock_getres: ::c_long = 114;
pub const SYS_clock_nanosleep: ::c_long = 115;
pub const SYS_syslog: ::c_long = 116;
pub const SYS_ptrace: ::c_long = 117;
pub const SYS_sched_setparam: ::c_long = 118;
pub const SYS_sched_setscheduler: ::c_long = 119;
pub const SYS_sched_getscheduler: ::c_long = 120;
pub const SYS_sched_getparam: ::c_long = 121;
pub const SYS_sched_setaffinity: ::c_long = 122;
pub const SYS_sched_getaffinity: ::c_long = 123;
pub const SYS_sched_yield: ::c_long = 124;
pub const SYS_sched_get_priority_max: ::c_long = 125;
pub const SYS_sched_get_priority_min: ::c_long = 126;
pub const SYS_sched_rr_get_interval: ::c_long = 127;
pub const SYS_restart_syscall: ::c_long = 128;
pub const SYS_kill: ::c_long = 129;
pub const SYS_tkill: ::c_long = 130;
pub const SYS_tgkill: ::c_long = 131;
pub const SYS_sigaltstack: ::c_long = 132;
pub const SYS_rt_sigsuspend: ::c_long = 133;
pub const SYS_rt_sigaction: ::c_long = 134;
pub const SYS_rt_sigprocmask: ::c_long = 135;
pub const SYS_rt_sigpending: ::c_long = 136;
pub const SYS_rt_sigtimedwait: ::c_long = 137;
pub const SYS_rt_sigqueueinfo: ::c_long = 138;
pub const SYS_rt_sigreturn: ::c_long = 139;
pub const SYS_setpriority: ::c_long = 140;
pub const SYS_getpriority: ::c_long = 141;
pub const SYS_reboot: ::c_long = 142;
pub const SYS_setregid: ::c_long = 143;
pub const SYS_setgid: ::c_long = 144;
pub const SYS_setreuid: ::c_long = 145;
pub const SYS_setuid: ::c_long = 146;
pub const SYS_setresuid: ::c_long = 147;
pub const SYS_getresuid: ::c_long = 148;
pub const SYS_setresgid: ::c_long = 149;
pub const SYS_getresgid: ::c_long = 150;
pub const SYS_setfsuid: ::c_long = 151;
pub const SYS_setfsgid: ::c_long = 152;
pub const SYS_times: ::c_long = 153;
pub const SYS_setpgid: ::c_long = 154;
pub const SYS_getpgid: ::c_long = 155;
pub const SYS_getsid: ::c_long = 156;
pub const SYS_setsid: ::c_long = 157;
pub const SYS_getgroups: ::c_long = 158;
pub const SYS_setgroups: ::c_long = 159;
pub const SYS_uname: ::c_long = 160;
pub const SYS_sethostname: ::c_long = 161;
pub const SYS_setdomainname: ::c_long = 162;
pub const SYS_getrlimit: ::c_long = 163;
pub const SYS_setrlimit: ::c_long = 164;
pub const SYS_getrusage: ::c_long = 165;
pub const SYS_umask: ::c_long = 166;
pub const SYS_prctl: ::c_long = 167;
pub const SYS_getcpu: ::c_long = 168;
pub const SYS_gettimeofday: ::c_long = 169;
pub const SYS_settimeofday: ::c_long = 170;
pub const SYS_adjtimex: ::c_long = 171;
pub const SYS_getpid: ::c_long = 172;
pub const SYS_getppid: ::c_long = 173;
pub const SYS_getuid: ::c_long = 174;
pub const SYS_geteuid: ::c_long = 175;
pub const SYS_getgid: ::c_long = 176;
pub const SYS_getegid: ::c_long = 177;
pub const SYS_gettid: ::c_long = 178;
pub const SYS_sysinfo: ::c_long = 179;
pub const SYS_mq_open: ::c_long = 180;
pub const SYS_mq_unlink: ::c_long = 181;
pub const SYS_mq_timedsend: ::c_long = 182;
pub const SYS_mq_timedreceive: ::c_long = 183;
pub const SYS_mq_notify: ::c_long = 184;
pub const SYS_mq_getsetattr: ::c_long = 185;
pub const SYS_msgget: ::c_long = 186;
pub const SYS_msgctl: ::c_long = 187;
pub const SYS_msgrcv: ::c_long = 188;
pub const SYS_msgsnd: ::c_long = 189;
pub const SYS_semget: ::c_long = 190;
pub const SYS_semctl: ::c_long = 191;
pub const SYS_semtimedop: ::c_long = 192;
pub const SYS_semop: ::c_long = 193;
pub const SYS_shmget: ::c_long = 194;
pub const SYS_shmctl: ::c_long = 195;
pub const SYS_shmat: ::c_long = 196;
pub const SYS_shmdt: ::c_long = 197;
pub const SYS_socket: ::c_long = 198;
pub const SYS_socketpair: ::c_long = 199;
pub const SYS_bind: ::c_long = 200;
pub const SYS_listen: ::c_long = 201;
pub const SYS_accept: ::c_long = 202;
pub const SYS_connect: ::c_long = 203;
pub const SYS_getsockname: ::c_long = 204;
pub const SYS_getpeername: ::c_long = 205;
pub const SYS_sendto: ::c_long = 206;
pub const SYS_recvfrom: ::c_long = 207;
pub const SYS_setsockopt: ::c_long = 208;
pub const SYS_getsockopt: ::c_long = 209;
pub const SYS_shutdown: ::c_long = 210;
pub const SYS_sendmsg: ::c_long = 211;
pub const SYS_recvmsg: ::c_long = 212;
pub const SYS_readahead: ::c_long = 213;
pub const SYS_brk: ::c_long = 214;
pub const SYS_munmap: ::c_long = 215;
pub const SYS_mremap: ::c_long = 216;
pub const SYS_add_key: ::c_long = 217;
pub const SYS_request_key: ::c_long = 218;
pub const SYS_keyctl: ::c_long = 219;
pub const SYS_clone: ::c_long = 220;
pub const SYS_execve: ::c_long = 221;
pub const SYS_swapon: ::c_long = 224;
pub const SYS_swapoff: ::c_long = 225;
pub const SYS_mprotect: ::c_long = 226;
pub const SYS_msync: ::c_long = 227;
pub const SYS_mlock: ::c_long = 228;
pub const SYS_munlock: ::c_long = 229;
pub const SYS_mlockall: ::c_long = 230;
pub const SYS_munlockall: ::c_long = 231;
pub const SYS_mincore: ::c_long = 232;
pub const SYS_madvise: ::c_long = 233;
pub const SYS_remap_file_pages: ::c_long = 234;
pub const SYS_mbind: ::c_long = 235;
pub const SYS_get_mempolicy: ::c_long = 236;
pub const SYS_set_mempolicy: ::c_long = 237;
pub const SYS_migrate_pages: ::c_long = 238;
pub const SYS_move_pages: ::c_long = 239;
pub const SYS_rt_tgsigqueueinfo: ::c_long = 240;
pub const SYS_perf_event_open: ::c_long = 241;
pub const SYS_accept4: ::c_long = 242;
pub const SYS_recvmmsg: ::c_long = 243;
pub const SYS_arch_specific_syscall: ::c_long = 244;
pub const SYS_wait4: ::c_long = 260;
pub const SYS_prlimit64: ::c_long = 261;
pub const SYS_fanotify_init: ::c_long = 262;
pub const SYS_fanotify_mark: ::c_long = 263;
pub const SYS_name_to_handle_at: ::c_long = 264;
pub const SYS_open_by_handle_at: ::c_long = 265;
pub const SYS_clock_adjtime: ::c_long = 266;
pub const SYS_syncfs: ::c_long = 267;
pub const SYS_setns: ::c_long = 268;
pub const SYS_sendmmsg: ::c_long = 269;
pub const SYS_process_vm_readv: ::c_long = 270;
pub const SYS_process_vm_writev: ::c_long = 271;
pub const SYS_kcmp: ::c_long = 272;
pub const SYS_finit_module: ::c_long = 273;
pub const SYS_sched_setattr: ::c_long = 274;
pub const SYS_sched_getattr: ::c_long = 275;
pub const SYS_renameat2: ::c_long = 276;
pub const SYS_seccomp: ::c_long = 277;
pub const SYS_getrandom: ::c_long = 278;
pub const SYS_memfd_create: ::c_long = 279;
pub const SYS_bpf: ::c_long = 280;
pub const SYS_execveat: ::c_long = 281;
pub const SYS_userfaultfd: ::c_long = 282;
pub const SYS_membarrier: ::c_long = 283;
pub const SYS_mlock2: ::c_long = 284;
pub const SYS_copy_file_range: ::c_long = 285;
pub const SYS_preadv2: ::c_long = 286;
pub const SYS_pwritev2: ::c_long = 287;
pub const SYS_pkey_mprotect: ::c_long = 288;
pub const SYS_pkey_alloc: ::c_long = 289;
pub const SYS_pkey_free: ::c_long = 290;
pub const SYS_syscalls: ::c_long = 436;
cfg_if! {<|fim▁hole|>}<|fim▁end|>
|
if #[cfg(libc_align)] {
mod align;
pub use self::align::*;
}
|
<|file_name|>issue-7911.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.
// ignore-pretty
// (Closes #7911) Test that we can use the same self expression
// with different mutability in macro in two methods
#![allow(unused_variable)] // unused foobar_immut + foobar_mut
trait FooBar {}<|fim▁hole|>impl FooBar for Bar {}
trait Test {
fn get_immut(&self) -> &FooBar;
fn get_mut(&mut self) -> &mut FooBar;
}
macro_rules! generate_test { ($type_:path, $slf:ident, $field:expr) => (
impl Test for $type_ {
fn get_immut(&$slf) -> &FooBar {
&$field as &FooBar
}
fn get_mut(&mut $slf) -> &mut FooBar {
&mut $field as &mut FooBar
}
}
)}
generate_test!(Foo, self, self.bar);
pub fn main() {
let mut foo: Foo = Foo { bar: Bar(42) };
{ let foobar_immut = foo.get_immut(); }
{ let foobar_mut = foo.get_mut(); }
}<|fim▁end|>
|
struct Bar(i32);
struct Foo { bar: Bar }
|
<|file_name|>Subdivision.cpp<|end_file_name|><|fim▁begin|>/*
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2018, assimp team
All rights reserved.
Redistribution and use of this software 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 the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
----------------------------------------------------------------------
*/
#include <assimp/Subdivision.h>
#include <assimp/SceneCombiner.h>
#include <assimp/SpatialSort.h>
#include "ProcessHelper.h"
#include <assimp/Vertex.h>
#include <assimp/ai_assert.h>
#include <stdio.h>
using namespace Assimp;
void mydummy() {}
// ------------------------------------------------------------------------------------------------
/** Subdivider stub class to implement the Catmull-Clarke subdivision algorithm. The
* implementation is basing on recursive refinement. Directly evaluating the result is also
* possible and much quicker, but it depends on lengthy matrix lookup tables. */
// ------------------------------------------------------------------------------------------------
class CatmullClarkSubdivider : public Subdivider
{
public:
void Subdivide (aiMesh* mesh, aiMesh*& out, unsigned int num, bool discard_input);
void Subdivide (aiMesh** smesh, size_t nmesh,
aiMesh** out, unsigned int num, bool discard_input);
// ---------------------------------------------------------------------------
/** Intermediate description of an edge between two corners of a polygon*/
// ---------------------------------------------------------------------------
struct Edge
{
Edge()
: ref(0)
{}
Vertex edge_point, midpoint;
unsigned int ref;
};
typedef std::vector<unsigned int> UIntVector;
typedef std::map<uint64_t,Edge> EdgeMap;
// ---------------------------------------------------------------------------
// Hashing function to derive an index into an #EdgeMap from two given
// 'unsigned int' vertex coordinates (!!distinct coordinates - same
// vertex position == same index!!).
// NOTE - this leads to rare hash collisions if a) sizeof(unsigned int)>4
// and (id[0]>2^32-1 or id[0]>2^32-1).
// MAKE_EDGE_HASH() uses temporaries, so INIT_EDGE_HASH() needs to be put
// at the head of every function which is about to use MAKE_EDGE_HASH().
// Reason is that the hash is that hash construction needs to hold the
// invariant id0<id1 to identify an edge - else two hashes would refer
// to the same edge.
// ---------------------------------------------------------------------------
#define MAKE_EDGE_HASH(id0,id1) (eh_tmp0__=id0,eh_tmp1__=id1,\
(eh_tmp0__<eh_tmp1__?std::swap(eh_tmp0__,eh_tmp1__):mydummy()),(uint64_t)eh_tmp0__^((uint64_t)eh_tmp1__<<32u))
#define INIT_EDGE_HASH_TEMPORARIES()\
unsigned int eh_tmp0__, eh_tmp1__;
private:
void InternSubdivide (const aiMesh* const * smesh,
size_t nmesh,aiMesh** out, unsigned int num);
};
// ------------------------------------------------------------------------------------------------
// Construct a subdivider of a specific type
Subdivider* Subdivider::Create (Algorithm algo)
{
switch (algo)
{
case CATMULL_CLARKE:
return new CatmullClarkSubdivider();
};
ai_assert(false);
return NULL; // shouldn't happen
}
// ------------------------------------------------------------------------------------------------
// Call the Catmull Clark subdivision algorithm for one mesh
void CatmullClarkSubdivider::Subdivide (
aiMesh* mesh,
aiMesh*& out,
unsigned int num,
bool discard_input
)
{
ai_assert(mesh != out);
Subdivide(&mesh,1,&out,num,discard_input);
}
// ------------------------------------------------------------------------------------------------
// Call the Catmull Clark subdivision algorithm for multiple meshes
void CatmullClarkSubdivider::Subdivide (
aiMesh** smesh,
size_t nmesh,
aiMesh** out,
unsigned int num,
bool discard_input
)
{
ai_assert( NULL != smesh );
ai_assert( NULL != out );
// course, both regions may not overlap
ai_assert(smesh<out || smesh+nmesh>out+nmesh);
if (!num) {
// No subdivision at all. Need to copy all the meshes .. argh.
if (discard_input) {
for (size_t s = 0; s < nmesh; ++s) {
out[s] = smesh[s];
smesh[s] = NULL;
}
}
else {
for (size_t s = 0; s < nmesh; ++s) {
SceneCombiner::Copy(out+s,smesh[s]);
}
}
return;
}
std::vector<aiMesh*> inmeshes;
std::vector<aiMesh*> outmeshes;
std::vector<unsigned int> maptbl;
inmeshes.reserve(nmesh);
outmeshes.reserve(nmesh);
maptbl.reserve(nmesh);
// Remove pure line and point meshes from the working set to reduce the
// number of edge cases the subdivider is forced to deal with. Line and
// point meshes are simply passed through.
for (size_t s = 0; s < nmesh; ++s) {
aiMesh* i = smesh[s];
// FIX - mPrimitiveTypes might not yet be initialized
if (i->mPrimitiveTypes && (i->mPrimitiveTypes & (aiPrimitiveType_LINE|aiPrimitiveType_POINT))==i->mPrimitiveTypes) {
ASSIMP_LOG_DEBUG("Catmull-Clark Subdivider: Skipping pure line/point mesh");
if (discard_input) {
out[s] = i;
smesh[s] = NULL;
}
else {
SceneCombiner::Copy(out+s,i);
}
continue;
}
outmeshes.push_back(NULL);inmeshes.push_back(i);
maptbl.push_back(static_cast<unsigned int>(s));
}
// Do the actual subdivision on the preallocated storage. InternSubdivide
// *always* assumes that enough storage is available, it does not bother
// checking any ranges.
ai_assert(inmeshes.size()==outmeshes.size()&&inmeshes.size()==maptbl.size());
if (inmeshes.empty()) {
ASSIMP_LOG_WARN("Catmull-Clark Subdivider: Pure point/line scene, I can't do anything");
return;
}
InternSubdivide(&inmeshes.front(),inmeshes.size(),&outmeshes.front(),num);
for (unsigned int i = 0; i < maptbl.size(); ++i) {
ai_assert(nullptr != outmeshes[i]);
out[maptbl[i]] = outmeshes[i];
}
if (discard_input) {
for (size_t s = 0; s < nmesh; ++s) {
delete smesh[s];
}
}
}
// ------------------------------------------------------------------------------------------------
// Note - this is an implementation of the standard (recursive) Cm-Cl algorithm without further
// optimizations (except we're using some nice LUTs). A description of the algorithm can be found
// here: http://en.wikipedia.org/wiki/Catmull-Clark_subdivision_surface
//
// The code is mostly O(n), however parts are O(nlogn) which is therefore the algorithm's
// expected total runtime complexity. The implementation is able to work in-place on the same
// mesh arrays. Calling #InternSubdivide() directly is not encouraged. The code can operate<|fim▁hole|>// in-place unless 'smesh' and 'out' are equal (no strange overlaps or reorderings).
// Previous data is replaced/deleted then.
// ------------------------------------------------------------------------------------------------
void CatmullClarkSubdivider::InternSubdivide (
const aiMesh* const * smesh,
size_t nmesh,
aiMesh** out,
unsigned int num
)
{
ai_assert(NULL != smesh && NULL != out);
INIT_EDGE_HASH_TEMPORARIES();
// no subdivision requested or end of recursive refinement
if (!num) {
return;
}
UIntVector maptbl;
SpatialSort spatial;
// ---------------------------------------------------------------------
// 0. Offset table to index all meshes continuously, generate a spatially
// sorted representation of all vertices in all meshes.
// ---------------------------------------------------------------------
typedef std::pair<unsigned int,unsigned int> IntPair;
std::vector<IntPair> moffsets(nmesh);
unsigned int totfaces = 0, totvert = 0;
for (size_t t = 0; t < nmesh; ++t) {
const aiMesh* mesh = smesh[t];
spatial.Append(mesh->mVertices,mesh->mNumVertices,sizeof(aiVector3D),false);
moffsets[t] = IntPair(totfaces,totvert);
totfaces += mesh->mNumFaces;
totvert += mesh->mNumVertices;
}
spatial.Finalize();
const unsigned int num_unique = spatial.GenerateMappingTable(maptbl,ComputePositionEpsilon(smesh,nmesh));
#define FLATTEN_VERTEX_IDX(mesh_idx, vert_idx) (moffsets[mesh_idx].second+vert_idx)
#define FLATTEN_FACE_IDX(mesh_idx, face_idx) (moffsets[mesh_idx].first+face_idx)
// ---------------------------------------------------------------------
// 1. Compute the centroid point for all faces
// ---------------------------------------------------------------------
std::vector<Vertex> centroids(totfaces);
unsigned int nfacesout = 0;
for (size_t t = 0, n = 0; t < nmesh; ++t) {
const aiMesh* mesh = smesh[t];
for (unsigned int i = 0; i < mesh->mNumFaces;++i,++n)
{
const aiFace& face = mesh->mFaces[i];
Vertex& c = centroids[n];
for (unsigned int a = 0; a < face.mNumIndices;++a) {
c += Vertex(mesh,face.mIndices[a]);
}
c /= static_cast<float>(face.mNumIndices);
nfacesout += face.mNumIndices;
}
}
{
// we want edges to go away before the recursive calls so begin a new scope
EdgeMap edges;
// ---------------------------------------------------------------------
// 2. Set each edge point to be the average of all neighbouring
// face points and original points. Every edge exists twice
// if there is a neighboring face.
// ---------------------------------------------------------------------
for (size_t t = 0; t < nmesh; ++t) {
const aiMesh* mesh = smesh[t];
for (unsigned int i = 0; i < mesh->mNumFaces;++i) {
const aiFace& face = mesh->mFaces[i];
for (unsigned int p =0; p< face.mNumIndices; ++p) {
const unsigned int id[] = {
face.mIndices[p],
face.mIndices[p==face.mNumIndices-1?0:p+1]
};
const unsigned int mp[] = {
maptbl[FLATTEN_VERTEX_IDX(t,id[0])],
maptbl[FLATTEN_VERTEX_IDX(t,id[1])]
};
Edge& e = edges[MAKE_EDGE_HASH(mp[0],mp[1])];
e.ref++;
if (e.ref<=2) {
if (e.ref==1) { // original points (end points) - add only once
e.edge_point = e.midpoint = Vertex(mesh,id[0])+Vertex(mesh,id[1]);
e.midpoint *= 0.5f;
}
e.edge_point += centroids[FLATTEN_FACE_IDX(t,i)];
}
}
}
}
// ---------------------------------------------------------------------
// 3. Normalize edge points
// ---------------------------------------------------------------------
{unsigned int bad_cnt = 0;
for (EdgeMap::iterator it = edges.begin(); it != edges.end(); ++it) {
if ((*it).second.ref < 2) {
ai_assert((*it).second.ref);
++bad_cnt;
}
(*it).second.edge_point *= 1.f/((*it).second.ref+2.f);
}
if (bad_cnt) {
// Report the number of bad edges. bad edges are referenced by less than two
// faces in the mesh. They occur at outer model boundaries in non-closed
// shapes.
ASSIMP_LOG_DEBUG_F("Catmull-Clark Subdivider: got ", bad_cnt, " bad edges touching only one face (totally ",
static_cast<unsigned int>(edges.size()), " edges). ");
}}
// ---------------------------------------------------------------------
// 4. Compute a vertex-face adjacency table. We can't reuse the code
// from VertexTriangleAdjacency because we need the table for multiple
// meshes and out vertex indices need to be mapped to distinct values
// first.
// ---------------------------------------------------------------------
UIntVector faceadjac(nfacesout), cntadjfac(maptbl.size(),0), ofsadjvec(maptbl.size()+1,0); {
for (size_t t = 0; t < nmesh; ++t) {
const aiMesh* const minp = smesh[t];
for (unsigned int i = 0; i < minp->mNumFaces; ++i) {
const aiFace& f = minp->mFaces[i];
for (unsigned int n = 0; n < f.mNumIndices; ++n) {
++cntadjfac[maptbl[FLATTEN_VERTEX_IDX(t,f.mIndices[n])]];
}
}
}
unsigned int cur = 0;
for (size_t i = 0; i < cntadjfac.size(); ++i) {
ofsadjvec[i+1] = cur;
cur += cntadjfac[i];
}
for (size_t t = 0; t < nmesh; ++t) {
const aiMesh* const minp = smesh[t];
for (unsigned int i = 0; i < minp->mNumFaces; ++i) {
const aiFace& f = minp->mFaces[i];
for (unsigned int n = 0; n < f.mNumIndices; ++n) {
faceadjac[ofsadjvec[1+maptbl[FLATTEN_VERTEX_IDX(t,f.mIndices[n])]]++] = FLATTEN_FACE_IDX(t,i);
}
}
}
// check the other way round for consistency
#ifdef ASSIMP_BUILD_DEBUG
for (size_t t = 0; t < ofsadjvec.size()-1; ++t) {
for (unsigned int m = 0; m < cntadjfac[t]; ++m) {
const unsigned int fidx = faceadjac[ofsadjvec[t]+m];
ai_assert(fidx < totfaces);
for (size_t n = 1; n < nmesh; ++n) {
if (moffsets[n].first > fidx) {
const aiMesh* msh = smesh[--n];
const aiFace& f = msh->mFaces[fidx-moffsets[n].first];
bool haveit = false;
for (unsigned int i = 0; i < f.mNumIndices; ++i) {
if (maptbl[FLATTEN_VERTEX_IDX(n,f.mIndices[i])]==(unsigned int)t) {
haveit = true;
break;
}
}
ai_assert(haveit);
if (!haveit) {
ASSIMP_LOG_DEBUG("Catmull-Clark Subdivider: Index not used");
}
break;
}
}
}
}
#endif
}
#define GET_ADJACENT_FACES_AND_CNT(vidx,fstartout,numout) \
fstartout = &faceadjac[ofsadjvec[vidx]], numout = cntadjfac[vidx]
typedef std::pair<bool,Vertex> TouchedOVertex;
std::vector<TouchedOVertex > new_points(num_unique,TouchedOVertex(false,Vertex()));
// ---------------------------------------------------------------------
// 5. Spawn a quad from each face point to the corresponding edge points
// the original points being the fourth quad points.
// ---------------------------------------------------------------------
for (size_t t = 0; t < nmesh; ++t) {
const aiMesh* const minp = smesh[t];
aiMesh* const mout = out[t] = new aiMesh();
for (unsigned int a = 0; a < minp->mNumFaces; ++a) {
mout->mNumFaces += minp->mFaces[a].mNumIndices;
}
// We need random access to the old face buffer, so reuse is not possible.
mout->mFaces = new aiFace[mout->mNumFaces];
mout->mNumVertices = mout->mNumFaces*4;
mout->mVertices = new aiVector3D[mout->mNumVertices];
// quads only, keep material index
mout->mPrimitiveTypes = aiPrimitiveType_POLYGON;
mout->mMaterialIndex = minp->mMaterialIndex;
if (minp->HasNormals()) {
mout->mNormals = new aiVector3D[mout->mNumVertices];
}
if (minp->HasTangentsAndBitangents()) {
mout->mTangents = new aiVector3D[mout->mNumVertices];
mout->mBitangents = new aiVector3D[mout->mNumVertices];
}
for(unsigned int i = 0; minp->HasTextureCoords(i); ++i) {
mout->mTextureCoords[i] = new aiVector3D[mout->mNumVertices];
mout->mNumUVComponents[i] = minp->mNumUVComponents[i];
}
for(unsigned int i = 0; minp->HasVertexColors(i); ++i) {
mout->mColors[i] = new aiColor4D[mout->mNumVertices];
}
mout->mNumVertices = mout->mNumFaces<<2u;
for (unsigned int i = 0, v = 0, n = 0; i < minp->mNumFaces;++i) {
const aiFace& face = minp->mFaces[i];
for (unsigned int a = 0; a < face.mNumIndices;++a) {
// Get a clean new face.
aiFace& faceOut = mout->mFaces[n++];
faceOut.mIndices = new unsigned int [faceOut.mNumIndices = 4];
// Spawn a new quadrilateral (ccw winding) for this original point between:
// a) face centroid
centroids[FLATTEN_FACE_IDX(t,i)].SortBack(mout,faceOut.mIndices[0]=v++);
// b) adjacent edge on the left, seen from the centroid
const Edge& e0 = edges[MAKE_EDGE_HASH(maptbl[FLATTEN_VERTEX_IDX(t,face.mIndices[a])],
maptbl[FLATTEN_VERTEX_IDX(t,face.mIndices[a==face.mNumIndices-1?0:a+1])
])]; // fixme: replace with mod face.mNumIndices?
// c) adjacent edge on the right, seen from the centroid
const Edge& e1 = edges[MAKE_EDGE_HASH(maptbl[FLATTEN_VERTEX_IDX(t,face.mIndices[a])],
maptbl[FLATTEN_VERTEX_IDX(t,face.mIndices[!a?face.mNumIndices-1:a-1])
])]; // fixme: replace with mod face.mNumIndices?
e0.edge_point.SortBack(mout,faceOut.mIndices[3]=v++);
e1.edge_point.SortBack(mout,faceOut.mIndices[1]=v++);
// d= original point P with distinct index i
// F := 0
// R := 0
// n := 0
// for each face f containing i
// F := F+ centroid of f
// R := R+ midpoint of edge of f from i to i+1
// n := n+1
//
// (F+2R+(n-3)P)/n
const unsigned int org = maptbl[FLATTEN_VERTEX_IDX(t,face.mIndices[a])];
TouchedOVertex& ov = new_points[org];
if (!ov.first) {
ov.first = true;
const unsigned int* adj; unsigned int cnt;
GET_ADJACENT_FACES_AND_CNT(org,adj,cnt);
if (cnt < 3) {
ov.second = Vertex(minp,face.mIndices[a]);
}
else {
Vertex F,R;
for (unsigned int o = 0; o < cnt; ++o) {
ai_assert(adj[o] < totfaces);
F += centroids[adj[o]];
// adj[0] is a global face index - search the face in the mesh list
const aiMesh* mp = NULL;
size_t nidx;
if (adj[o] < moffsets[0].first) {
mp = smesh[nidx=0];
}
else {
for (nidx = 1; nidx<= nmesh; ++nidx) {
if (nidx == nmesh ||moffsets[nidx].first > adj[o]) {
mp = smesh[--nidx];
break;
}
}
}
ai_assert(adj[o]-moffsets[nidx].first < mp->mNumFaces);
const aiFace& f = mp->mFaces[adj[o]-moffsets[nidx].first];
bool haveit = false;
// find our original point in the face
for (unsigned int m = 0; m < f.mNumIndices; ++m) {
if (maptbl[FLATTEN_VERTEX_IDX(nidx,f.mIndices[m])] == org) {
// add *both* edges. this way, we can be sure that we add
// *all* adjacent edges to R. In a closed shape, every
// edge is added twice - so we simply leave out the
// factor 2.f in the amove formula and get the right
// result.
const Edge& c0 = edges[MAKE_EDGE_HASH(org,maptbl[FLATTEN_VERTEX_IDX(
nidx,f.mIndices[!m?f.mNumIndices-1:m-1])])];
// fixme: replace with mod face.mNumIndices?
const Edge& c1 = edges[MAKE_EDGE_HASH(org,maptbl[FLATTEN_VERTEX_IDX(
nidx,f.mIndices[m==f.mNumIndices-1?0:m+1])])];
// fixme: replace with mod face.mNumIndices?
R += c0.midpoint+c1.midpoint;
haveit = true;
break;
}
}
// this invariant *must* hold if the vertex-to-face adjacency table is valid
ai_assert(haveit);
if ( !haveit ) {
ASSIMP_LOG_WARN( "OBJ: no name for material library specified." );
}
}
const float div = static_cast<float>(cnt), divsq = 1.f/(div*div);
ov.second = Vertex(minp,face.mIndices[a])*((div-3.f) / div) + R*divsq + F*divsq;
}
}
ov.second.SortBack(mout,faceOut.mIndices[2]=v++);
}
}
}
} // end of scope for edges, freeing its memory
// ---------------------------------------------------------------------
// 7. Apply the next subdivision step.
// ---------------------------------------------------------------------
if (num != 1) {
std::vector<aiMesh*> tmp(nmesh);
InternSubdivide (out,nmesh,&tmp.front(),num-1);
for (size_t i = 0; i < nmesh; ++i) {
delete out[i];
out[i] = tmp[i];
}
}
}<|fim▁end|>
| |
<|file_name|>smove.js<|end_file_name|><|fim▁begin|>try {
await kuzzle.ms.sadd('set1', ['foo', 'bar', 'baz']);
await kuzzle.ms.sadd('set2', ['qux']);
await kuzzle.ms.smove('set1', 'set2', 'foo');
// Prints: [ 'bar', 'baz' ]
console.log(await kuzzle.ms.smembers('set1'));<|fim▁hole|>} catch (error) {
console.error(error.message);
}<|fim▁end|>
|
// Prints: [ 'foo', 'qux' ]
console.log(await kuzzle.ms.smembers('set2'));
|
<|file_name|>HolidayVillageTwoTone.js<|end_file_name|><|fim▁begin|>import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";<|fim▁hole|> opacity: ".3"
}, "0"), /*#__PURE__*/_jsx("path", {
d: "m8 4-6 6v10h12V10L8 4zm4 14H9v-3H7v3H4v-7.17l4-4 4 4V18zm-3-5H7v-2h2v2zm9 7V8.35L13.65 4h-2.83L16 9.18V20h2zm4 0V6.69L19.31 4h-2.83L20 7.52V20h2z"
}, "1")], 'HolidayVillageTwoTone');<|fim▁end|>
|
export default createSvgIcon([/*#__PURE__*/_jsx("path", {
d: "m8 6.83-4 4V18h3v-3h2v3h3v-7.17l-4-4zM9 13H7v-2h2v2z",
|
<|file_name|>tap.js<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|>
|
"use strict";require("retape")(require("./index"))
|
<|file_name|>josu.js<|end_file_name|><|fim▁begin|>// フォーマット
var koyomi = require('../..').create();<|fim▁hole|>
// 序数 (CC:経過日数)
eq(format(20150101, 'CC'), '1');
eq(format(20150101, 'CC>0'), '1st');
eq(format(20150102, 'CC>0'), '2nd');
eq(format(20150103, 'CC>0'), '3rd');
eq(format(20150104, 'CC>0'), '4th');
eq(format(20150105, 'CC>0'), '5th');
eq(format(20150106, 'CC>0'), '6th');
eq(format(20150107, 'CC>0'), '7th');
eq(format(20150108, 'CC>0'), '8th');
eq(format(20150109, 'CC>0'), '9th');
eq(format(20150110, 'CC>0'), '10th');
eq(format(20150111, 'CC>0'), '11th');
eq(format(20150112, 'CC>0'), '12th');
eq(format(20150113, 'CC>0'), '13th');
eq(format(20150114, 'CC>0'), '14th');
eq(format(20150115, 'CC>0'), '15th');
eq(format(20150116, 'CC>0'), '16th');
eq(format(20150117, 'CC>0'), '17th');
eq(format(20150118, 'CC>0'), '18th');
eq(format(20150119, 'CC>0'), '19th');
eq(format(20150120, 'CC>0'), '20th');
eq(format(20150121, 'CC>0'), '21st');
eq(format(20150122, 'CC>0'), '22nd');
eq(format(20150123, 'CC>0'), '23rd');
eq(format(20150124, 'CC>0'), '24th');
eq(format(20150125, 'CC>0'), '25th');
eq(format(20150126, 'CC>0'), '26th');
eq(format(20150127, 'CC>0'), '27th');
eq(format(20150128, 'CC>0'), '28th');
eq(format(20150129, 'CC>0'), '29th');
eq(format(20150130, 'CC>0'), '30th');
eq(format(20150131, 'CC>0'), '31st');
eq(format(20150201, 'CC>0'), '32nd');
eq(format(20150202, 'CC>0'), '33rd');
eq(format(20150203, 'CC>0'), '34th');
eq(format(20150204, 'CC>0'), '35th');
eq(format(20150205, 'CC>0'), '36th');
eq(format(20150206, 'CC>0'), '37th');
eq(format(20150207, 'CC>0'), '38th');
eq(format(20150208, 'CC>0'), '39th');
eq(format(20150209, 'CC>0'), '40th');
eq(format(20150210, 'CC>0'), '41st');
eq(format(20150211, 'CC>0'), '42nd');
eq(format(20150212, 'CC>0'), '43rd');
eq(format(20150213, 'CC>0'), '44th');
eq(format(20150214, 'CC>0'), '45th');
eq(format(20150215, 'CC>0'), '46th');
eq(format(20150216, 'CC>0'), '47th');
eq(format(20150217, 'CC>0'), '48th');
eq(format(20150218, 'CC>0'), '49th');
eq(format(20150219, 'CC>0'), '50th');
eq(format(20150220, 'CC>0'), '51st');
eq(format(20150221, 'CC>0'), '52nd');
eq(format(20150222, 'CC>0'), '53rd');
eq(format(20150223, 'CC>0'), '54th');
eq(format(20150224, 'CC>0'), '55th');
eq(format(20150225, 'CC>0'), '56th');
eq(format(20150226, 'CC>0'), '57th');
eq(format(20150227, 'CC>0'), '58th');
eq(format(20150228, 'CC>0'), '59th');
eq(format(20150301, 'CC>0'), '60th');
eq(format(20150302, 'CC>0'), '61st');
eq(format(20150303, 'CC>0'), '62nd');
eq(format(20150304, 'CC>0'), '63rd');
eq(format(20150305, 'CC>0'), '64th');
eq(format(20150306, 'CC>0'), '65th');
eq(format(20150307, 'CC>0'), '66th');
eq(format(20150308, 'CC>0'), '67th');
eq(format(20150309, 'CC>0'), '68th');
eq(format(20150310, 'CC>0'), '69th');
eq(format(20150311, 'CC>0'), '70th');
eq(format(20150312, 'CC>0'), '71st');
eq(format(20150313, 'CC>0'), '72nd');
eq(format(20150314, 'CC>0'), '73rd');
eq(format(20150315, 'CC>0'), '74th');
eq(format(20150316, 'CC>0'), '75th');
eq(format(20150317, 'CC>0'), '76th');
eq(format(20150318, 'CC>0'), '77th');
eq(format(20150319, 'CC>0'), '78th');
eq(format(20150320, 'CC>0'), '79th');
eq(format(20150321, 'CC>0'), '80th');
eq(format(20150322, 'CC>0'), '81st');
eq(format(20150323, 'CC>0'), '82nd');
eq(format(20150324, 'CC>0'), '83rd');
eq(format(20150325, 'CC>0'), '84th');
eq(format(20150326, 'CC>0'), '85th');
eq(format(20150327, 'CC>0'), '86th');
eq(format(20150328, 'CC>0'), '87th');
eq(format(20150329, 'CC>0'), '88th');
eq(format(20150330, 'CC>0'), '89th');
eq(format(20150331, 'CC>0'), '90th');
eq(format(20150401, 'CC>0'), '91st');
eq(format(20150402, 'CC>0'), '92nd');
eq(format(20150403, 'CC>0'), '93rd');
eq(format(20150404, 'CC>0'), '94th');
eq(format(20150405, 'CC>0'), '95th');
eq(format(20150406, 'CC>0'), '96th');
eq(format(20150407, 'CC>0'), '97th');
eq(format(20150408, 'CC>0'), '98th');
eq(format(20150409, 'CC>0'), '99th');
eq(format(20150410, 'CC>0'), '100th');
eq(format(20150411, 'CC>0'), '101st');
eq(format(20150412, 'CC>0'), '102nd');
eq(format(20150413, 'CC>0'), '103rd');
eq(format(20150414, 'CC>0'), '104th');
eq(format(20150415, 'CC>0'), '105th');
eq(format(20150416, 'CC>0'), '106th');
eq(format(20150417, 'CC>0'), '107th');
eq(format(20150418, 'CC>0'), '108th');
eq(format(20150419, 'CC>0'), '109th');
eq(format(20150420, 'CC>0'), '110th');
eq(format(20150421, 'CC>0'), '111th');
eq(format(20150422, 'CC>0'), '112th');
eq(format(20150423, 'CC>0'), '113th');
eq(format(20150424, 'CC>0'), '114th');
eq(format(20150425, 'CC>0'), '115th');
eq(format(20150426, 'CC>0'), '116th');
eq(format(20150427, 'CC>0'), '117th');
eq(format(20150428, 'CC>0'), '118th');
eq(format(20150429, 'CC>0'), '119th');
eq(format(20150430, 'CC>0'), '120th');
eq(format(20150501, 'CC>0'), '121st');
eq(format(20150502, 'CC>0'), '122nd');
eq(format(20150503, 'CC>0'), '123rd');
eq(format(20150504, 'CC>0'), '124th');
eq(format(20150505, 'CC>0'), '125th');
eq(format(20150506, 'CC>0'), '126th');
eq(format(20150507, 'CC>0'), '127th');
eq(format(20150508, 'CC>0'), '128th');
eq(format(20150509, 'CC>0'), '129th');
eq(format(20150510, 'CC>0'), '130th');
eq(format(20150511, 'CC>0'), '131st');
eq(format(20150512, 'CC>0'), '132nd');
eq(format(20150513, 'CC>0'), '133rd');
eq(format(20150514, 'CC>0'), '134th');
eq(format(20150515, 'CC>0'), '135th');
eq(format(20150516, 'CC>0'), '136th');
eq(format(20150517, 'CC>0'), '137th');
eq(format(20150518, 'CC>0'), '138th');
eq(format(20150519, 'CC>0'), '139th');
eq(format(20150520, 'CC>0'), '140th');
eq(format(20150521, 'CC>0'), '141st');
eq(format(20150522, 'CC>0'), '142nd');
eq(format(20150523, 'CC>0'), '143rd');
eq(format(20150524, 'CC>0'), '144th');
eq(format(20150525, 'CC>0'), '145th');
eq(format(20150526, 'CC>0'), '146th');
eq(format(20150527, 'CC>0'), '147th');
eq(format(20150528, 'CC>0'), '148th');
eq(format(20150529, 'CC>0'), '149th');
eq(format(20150530, 'CC>0'), '150th');
eq(format(20150531, 'CC>0'), '151st');
eq(format(20150601, 'CC>0'), '152nd');
eq(format(20150602, 'CC>0'), '153rd');
eq(format(20150603, 'CC>0'), '154th');
eq(format(20150604, 'CC>0'), '155th');
eq(format(20150605, 'CC>0'), '156th');
eq(format(20150606, 'CC>0'), '157th');
eq(format(20150607, 'CC>0'), '158th');
eq(format(20150608, 'CC>0'), '159th');
eq(format(20150609, 'CC>0'), '160th');
eq(format(20150610, 'CC>0'), '161st');
eq(format(20150611, 'CC>0'), '162nd');
eq(format(20150612, 'CC>0'), '163rd');
eq(format(20150613, 'CC>0'), '164th');
eq(format(20150614, 'CC>0'), '165th');
eq(format(20150615, 'CC>0'), '166th');
eq(format(20150616, 'CC>0'), '167th');
eq(format(20150617, 'CC>0'), '168th');
eq(format(20150618, 'CC>0'), '169th');
eq(format(20150619, 'CC>0'), '170th');
eq(format(20150620, 'CC>0'), '171st');
eq(format(20150621, 'CC>0'), '172nd');
eq(format(20150622, 'CC>0'), '173rd');
eq(format(20150623, 'CC>0'), '174th');
eq(format(20150624, 'CC>0'), '175th');
eq(format(20150625, 'CC>0'), '176th');
eq(format(20150626, 'CC>0'), '177th');
eq(format(20150627, 'CC>0'), '178th');
eq(format(20150628, 'CC>0'), '179th');
eq(format(20150629, 'CC>0'), '180th');
eq(format(20150630, 'CC>0'), '181st');
eq(format(20150701, 'CC>0'), '182nd');
eq(format(20150702, 'CC>0'), '183rd');
eq(format(20150703, 'CC>0'), '184th');
eq(format(20150704, 'CC>0'), '185th');
eq(format(20150705, 'CC>0'), '186th');
eq(format(20150706, 'CC>0'), '187th');
eq(format(20150707, 'CC>0'), '188th');
eq(format(20150708, 'CC>0'), '189th');
eq(format(20150709, 'CC>0'), '190th');
eq(format(20150710, 'CC>0'), '191st');
eq(format(20150711, 'CC>0'), '192nd');
eq(format(20150712, 'CC>0'), '193rd');
eq(format(20150713, 'CC>0'), '194th');
eq(format(20150714, 'CC>0'), '195th');
eq(format(20150715, 'CC>0'), '196th');
eq(format(20150716, 'CC>0'), '197th');
eq(format(20150717, 'CC>0'), '198th');
eq(format(20150718, 'CC>0'), '199th');
eq(format(20150719, 'CC>0'), '200th');
eq(format(20150720, 'CC>0'), '201st');
eq(format(20150721, 'CC>0'), '202nd');
eq(format(20150722, 'CC>0'), '203rd');
eq(format(20150723, 'CC>0'), '204th');
eq(format(20150724, 'CC>0'), '205th');
eq(format(20150725, 'CC>0'), '206th');
eq(format(20150726, 'CC>0'), '207th');
eq(format(20150727, 'CC>0'), '208th');
eq(format(20150728, 'CC>0'), '209th');
eq(format(20150729, 'CC>0'), '210th');
eq(format(20150730, 'CC>0'), '211th');
eq(format(20150731, 'CC>0'), '212th');
eq(format(20150801, 'CC>0'), '213th');
eq(format(20150802, 'CC>0'), '214th');
eq(format(20150803, 'CC>0'), '215th');
eq(format(20150804, 'CC>0'), '216th');
eq(format(20150805, 'CC>0'), '217th');
eq(format(20150806, 'CC>0'), '218th');
eq(format(20150807, 'CC>0'), '219th');
eq(format(20150808, 'CC>0'), '220th');
eq(format(20150809, 'CC>0'), '221st');
eq(format(20150810, 'CC>0'), '222nd');
eq(format(20150811, 'CC>0'), '223rd');
eq(format(20150812, 'CC>0'), '224th');
eq(format(20150813, 'CC>0'), '225th');
eq(format(20150814, 'CC>0'), '226th');
eq(format(20150815, 'CC>0'), '227th');
eq(format(20150816, 'CC>0'), '228th');
eq(format(20150817, 'CC>0'), '229th');
eq(format(20150818, 'CC>0'), '230th');
eq(format(20150819, 'CC>0'), '231st');
eq(format(20150820, 'CC>0'), '232nd');
eq(format(20150821, 'CC>0'), '233rd');
eq(format(20150822, 'CC>0'), '234th');
eq(format(20150823, 'CC>0'), '235th');
eq(format(20150824, 'CC>0'), '236th');
eq(format(20150825, 'CC>0'), '237th');
eq(format(20150826, 'CC>0'), '238th');
eq(format(20150827, 'CC>0'), '239th');
eq(format(20150828, 'CC>0'), '240th');
eq(format(20150829, 'CC>0'), '241st');
eq(format(20150830, 'CC>0'), '242nd');
eq(format(20150831, 'CC>0'), '243rd');
eq(format(20150901, 'CC>0'), '244th');
eq(format(20150902, 'CC>0'), '245th');
eq(format(20150903, 'CC>0'), '246th');
eq(format(20150904, 'CC>0'), '247th');
eq(format(20150905, 'CC>0'), '248th');
eq(format(20150906, 'CC>0'), '249th');
eq(format(20150907, 'CC>0'), '250th');
eq(format(20150908, 'CC>0'), '251st');
eq(format(20150909, 'CC>0'), '252nd');
eq(format(20150910, 'CC>0'), '253rd');
eq(format(20150911, 'CC>0'), '254th');
eq(format(20150912, 'CC>0'), '255th');
eq(format(20150913, 'CC>0'), '256th');
eq(format(20150914, 'CC>0'), '257th');
eq(format(20150915, 'CC>0'), '258th');
eq(format(20150916, 'CC>0'), '259th');
eq(format(20150917, 'CC>0'), '260th');
eq(format(20150918, 'CC>0'), '261st');
eq(format(20150919, 'CC>0'), '262nd');
eq(format(20150920, 'CC>0'), '263rd');
eq(format(20150921, 'CC>0'), '264th');
eq(format(20150922, 'CC>0'), '265th');
eq(format(20150923, 'CC>0'), '266th');
eq(format(20150924, 'CC>0'), '267th');
eq(format(20150925, 'CC>0'), '268th');
eq(format(20150926, 'CC>0'), '269th');
eq(format(20150927, 'CC>0'), '270th');
eq(format(20150928, 'CC>0'), '271st');
eq(format(20150929, 'CC>0'), '272nd');
eq(format(20150930, 'CC>0'), '273rd');
eq(format(20151001, 'CC>0'), '274th');
eq(format(20151002, 'CC>0'), '275th');
eq(format(20151003, 'CC>0'), '276th');
eq(format(20151004, 'CC>0'), '277th');
eq(format(20151005, 'CC>0'), '278th');
eq(format(20151006, 'CC>0'), '279th');
eq(format(20151007, 'CC>0'), '280th');
eq(format(20151008, 'CC>0'), '281st');
eq(format(20151009, 'CC>0'), '282nd');
eq(format(20151010, 'CC>0'), '283rd');
eq(format(20151011, 'CC>0'), '284th');
eq(format(20151012, 'CC>0'), '285th');
eq(format(20151013, 'CC>0'), '286th');
eq(format(20151014, 'CC>0'), '287th');
eq(format(20151015, 'CC>0'), '288th');
eq(format(20151016, 'CC>0'), '289th');
eq(format(20151017, 'CC>0'), '290th');
eq(format(20151018, 'CC>0'), '291st');
eq(format(20151019, 'CC>0'), '292nd');
eq(format(20151020, 'CC>0'), '293rd');
eq(format(20151021, 'CC>0'), '294th');
eq(format(20151022, 'CC>0'), '295th');
eq(format(20151023, 'CC>0'), '296th');
eq(format(20151024, 'CC>0'), '297th');
eq(format(20151025, 'CC>0'), '298th');
eq(format(20151026, 'CC>0'), '299th');
eq(format(20151027, 'CC>0'), '300th');
eq(format(20151028, 'CC>0'), '301st');
eq(format(20151029, 'CC>0'), '302nd');
eq(format(20151030, 'CC>0'), '303rd');
eq(format(20151031, 'CC>0'), '304th');
eq(format(20151101, 'CC>0'), '305th');
eq(format(20151102, 'CC>0'), '306th');
eq(format(20151103, 'CC>0'), '307th');
eq(format(20151104, 'CC>0'), '308th');
eq(format(20151105, 'CC>0'), '309th');
eq(format(20151106, 'CC>0'), '310th');
eq(format(20151107, 'CC>0'), '311th');
eq(format(20151108, 'CC>0'), '312th');
eq(format(20151109, 'CC>0'), '313th');
eq(format(20151110, 'CC>0'), '314th');
eq(format(20151111, 'CC>0'), '315th');
eq(format(20151112, 'CC>0'), '316th');
eq(format(20151113, 'CC>0'), '317th');
eq(format(20151114, 'CC>0'), '318th');
eq(format(20151115, 'CC>0'), '319th');
eq(format(20151116, 'CC>0'), '320th');
eq(format(20151117, 'CC>0'), '321st');
eq(format(20151118, 'CC>0'), '322nd');
eq(format(20151119, 'CC>0'), '323rd');
eq(format(20151120, 'CC>0'), '324th');
eq(format(20151121, 'CC>0'), '325th');
eq(format(20151122, 'CC>0'), '326th');
eq(format(20151123, 'CC>0'), '327th');
eq(format(20151124, 'CC>0'), '328th');
eq(format(20151125, 'CC>0'), '329th');
eq(format(20151126, 'CC>0'), '330th');
eq(format(20151127, 'CC>0'), '331st');
eq(format(20151128, 'CC>0'), '332nd');
eq(format(20151129, 'CC>0'), '333rd');
eq(format(20151130, 'CC>0'), '334th');
eq(format(20151201, 'CC>0'), '335th');
eq(format(20151202, 'CC>0'), '336th');
eq(format(20151203, 'CC>0'), '337th');
eq(format(20151204, 'CC>0'), '338th');
eq(format(20151205, 'CC>0'), '339th');
eq(format(20151206, 'CC>0'), '340th');
eq(format(20151207, 'CC>0'), '341st');
eq(format(20151208, 'CC>0'), '342nd');
eq(format(20151209, 'CC>0'), '343rd');
eq(format(20151210, 'CC>0'), '344th');
eq(format(20151211, 'CC>0'), '345th');
eq(format(20151212, 'CC>0'), '346th');
eq(format(20151213, 'CC>0'), '347th');
eq(format(20151214, 'CC>0'), '348th');
eq(format(20151215, 'CC>0'), '349th');
eq(format(20151216, 'CC>0'), '350th');
eq(format(20151217, 'CC>0'), '351st');
eq(format(20151218, 'CC>0'), '352nd');
eq(format(20151219, 'CC>0'), '353rd');
eq(format(20151220, 'CC>0'), '354th');
eq(format(20151221, 'CC>0'), '355th');
eq(format(20151222, 'CC>0'), '356th');
eq(format(20151223, 'CC>0'), '357th');
eq(format(20151224, 'CC>0'), '358th');
eq(format(20151225, 'CC>0'), '359th');
eq(format(20151226, 'CC>0'), '360th');
eq(format(20151227, 'CC>0'), '361st');
eq(format(20151228, 'CC>0'), '362nd');
eq(format(20151229, 'CC>0'), '363rd');
eq(format(20151230, 'CC>0'), '364th');
eq(format(20151231, 'CC>0'), '365th');
// 文字列の序数
eq(format(20150101, 'GG>0'), '平成');
eq(format(20000101, 'y>0'), '00th');
eq(format(20010101, 'y>0'), '01st');<|fim▁end|>
|
var format = koyomi.format.bind(koyomi);
var eq = require('assert').equal;
koyomi.startMonth = 1;
|
<|file_name|>package-info.java<|end_file_name|><|fim▁begin|>/**
* Purpose of package - find largest number from 2 and 3 numbers.
* @since 1.0<|fim▁hole|>
package ru.skuznetsov;<|fim▁end|>
|
* @author skuznetsov
* @version 2.0
*/
|
<|file_name|>test_keepalived_state_change.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015 Red Hat 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.
import os
import mock
from oslo_config import cfg
from oslo_utils import uuidutils
from neutron.agent.l3 import keepalived_state_change
from neutron.tests.functional import base
<|fim▁hole|> super(TestKeepalivedStateChange, self).setUp()
cfg.CONF.register_opt(
cfg.StrOpt('metadata_proxy_socket',
default='$state_path/metadata_proxy',
help=_('Location of Metadata Proxy UNIX domain '
'socket')))
self.router_id = uuidutils.generate_uuid()
self.conf_dir = self.get_default_temp_dir().path
self.cidr = '169.254.128.1/24'
self.interface_name = 'interface'
self.monitor = keepalived_state_change.MonitorDaemon(
self.get_temp_file_path('monitor.pid'),
self.router_id,
1,
2,
'namespace',
self.conf_dir,
self.interface_name,
self.cidr)
mock.patch.object(self.monitor, 'notify_agent').start()
self.line = '1: %s inet %s' % (self.interface_name, self.cidr)
def test_parse_and_handle_event_wrong_device_completes_without_error(self):
self.monitor.parse_and_handle_event(
'1: wrong_device inet wrong_cidr')
def _get_state(self):
with open(os.path.join(self.monitor.conf_dir, 'state')) as state_file:
return state_file.read()
def test_parse_and_handle_event_writes_to_file(self):
self.monitor.parse_and_handle_event('Deleted %s' % self.line)
self.assertEqual('backup', self._get_state())
self.monitor.parse_and_handle_event(self.line)
self.assertEqual('master', self._get_state())
def test_parse_and_handle_event_fails_writing_state(self):
with mock.patch.object(
self.monitor, 'write_state_change', side_effect=OSError):
self.monitor.parse_and_handle_event(self.line)
def test_parse_and_handle_event_fails_notifying_agent(self):
with mock.patch.object(
self.monitor, 'notify_agent', side_effect=Exception):
self.monitor.parse_and_handle_event(self.line)<|fim▁end|>
|
class TestKeepalivedStateChange(base.BaseSudoTestCase):
def setUp(self):
|
<|file_name|>extract_frames.py<|end_file_name|><|fim▁begin|>import cv2
import fitparse
import os
fname = 'V0280048.MP4'
fitfile ='2018-06-01-12-13-33.fit'
vidcap = cv2.VideoCapture(fname)
success,image = vidcap.read()
success
count = 0
if success:
stream = fname.split('.')[-2]
os.mkdir(stream)
while success:
cv2.imwrite("{}/{}_frame{}.jpg".format(stream,stream,count), image) # save frame as JPEG file
success,image = vidcap.read()
print('Read a new frame: ', success)
count += 1
#parse metadata
fields_to_extract=['timestamp','enhanced_altitude','enhanced_speed','utc_timestamp','timestamp_ms','heading','velocity']
fields_to_convert=['position_lat','position_long']
meta = {}
for key in fields_to_extract+fields_to_convert:
meta[key]=[]
ff=fitparse.FitFile('2018-06-01-12-13-33.fit')
for i,m in enumerate(ff.get_messages('gps_metadata')):
for f in m.fields:
if f.name in fields_to_extract:
meta[f.name].append(f.value)
if f.name in fields_to_convert:
meta[f.name].append(f.value*180.0/2**31)
import pandas
metadata = pandas.DataFrame()
for key in fields_to_extract+fields_to_convert:
metadata[key]=pandas.Series(meta[key])<|fim▁hole|><|fim▁end|>
|
metadata.to_csv('{}_metadata.csv'.format(stream))
|
<|file_name|>ast_to_dict.py<|end_file_name|><|fim▁begin|>from typing import Any, Collection, Dict, List, Optional, overload
from ..language import Node, OperationType
from ..pyutils import is_iterable
__all__ = ["ast_to_dict"]
@overload
def ast_to_dict(
node: Node, locations: bool = False, cache: Optional[Dict[Node, Any]] = None
) -> Dict:
...
@overload
def ast_to_dict(
node: Collection[Node],
locations: bool = False,
cache: Optional[Dict[Node, Any]] = None,
) -> List[Node]:
...
@overload
def ast_to_dict(
node: OperationType,
locations: bool = False,
cache: Optional[Dict[Node, Any]] = None,
) -> str:<|fim▁hole|>def ast_to_dict(
node: Any, locations: bool = False, cache: Optional[Dict[Node, Any]] = None
) -> Any:
"""Convert a language AST to a nested Python dictionary.
Set `location` to True in order to get the locations as well.
"""
"""Convert a node to a nested Python dictionary."""
if isinstance(node, Node):
if cache is None:
cache = {}
elif node in cache:
return cache[node]
cache[node] = res = {}
res.update(
{
key: ast_to_dict(getattr(node, key), locations, cache)
for key in ("kind",) + node.keys[1:]
}
)
if locations:
loc = node.loc
if loc:
res["loc"] = dict(start=loc.start, end=loc.end)
return res
if is_iterable(node):
return [ast_to_dict(sub_node, locations, cache) for sub_node in node]
if isinstance(node, OperationType):
return node.value
return node<|fim▁end|>
|
...
|
<|file_name|>cs_npc.cpp<|end_file_name|><|fim▁begin|>/*
* Copyright (C) 2008-2019 TrinityCore <https://www.trinitycore.org/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* ScriptData
Name: npc_commandscript
%Complete: 100
Comment: All npc related commands
Category: commandscripts
EndScriptData */
#include "ScriptMgr.h"
#include "Chat.h"
#include "CreatureAI.h"
#include "CreatureGroups.h"
#include "DatabaseEnv.h"
#include "FollowMovementGenerator.h"
#include "GameTime.h"
#include "Language.h"
#include "Log.h"
#include "Map.h"
#include "MotionMaster.h"
#include "MovementDefines.h"
#include "ObjectAccessor.h"
#include "ObjectMgr.h"
#include "Pet.h"
#include "Player.h"
#include "RBAC.h"
#include "Transport.h"
#include "World.h"
#include "WorldSession.h"
#include <boost/core/demangle.hpp>
#include <typeinfo>
bool HandleNpcSpawnGroup(ChatHandler* handler, char const* args)
{
if (!*args)
return false;
bool ignoreRespawn = false;
bool force = false;
uint32 groupId = 0;
// Decode arguments
char* arg = strtok((char*)args, " ");
while (arg)
{
std::string thisArg = arg;
std::transform(thisArg.begin(), thisArg.end(), thisArg.begin(), ::tolower);
if (thisArg == "ignorerespawn")
ignoreRespawn = true;
else if (thisArg == "force")
force = true;
else if (thisArg.empty() || !(std::count_if(thisArg.begin(), thisArg.end(), ::isdigit) == (int)thisArg.size()))
return false;
else
groupId = atoi(thisArg.c_str());
arg = strtok(nullptr, " ");
}
Player* player = handler->GetSession()->GetPlayer();
std::vector <WorldObject*> creatureList;
if (!player->GetMap()->SpawnGroupSpawn(groupId, ignoreRespawn, force, &creatureList))
{
handler->PSendSysMessage(LANG_SPAWNGROUP_BADGROUP, groupId);
handler->SetSentErrorMessage(true);
return false;
}
handler->PSendSysMessage(LANG_SPAWNGROUP_SPAWNCOUNT, creatureList.size());
return true;
}
bool HandleNpcDespawnGroup(ChatHandler* handler, char const* args)
{
if (!*args)
return false;
bool deleteRespawnTimes = false;
uint32 groupId = 0;
// Decode arguments
char* arg = strtok((char*)args, " ");
while (arg)
{
std::string thisArg = arg;
std::transform(thisArg.begin(), thisArg.end(), thisArg.begin(), ::tolower);
if (thisArg == "removerespawntime")
deleteRespawnTimes = true;
else if (thisArg.empty() || !(std::count_if(thisArg.begin(), thisArg.end(), ::isdigit) == (int)thisArg.size()))
return false;
else
groupId = atoi(thisArg.c_str());
arg = strtok(nullptr, " ");
}
Player* player = handler->GetSession()->GetPlayer();
size_t n = 0;
if (!player->GetMap()->SpawnGroupDespawn(groupId, deleteRespawnTimes, &n))
{
handler->PSendSysMessage(LANG_SPAWNGROUP_BADGROUP, groupId);
handler->SetSentErrorMessage(true);
return false;
}
handler->PSendSysMessage("Despawned a total of %zu objects.", n);
return true;
}
class npc_commandscript : public CommandScript
{
public:
npc_commandscript() : CommandScript("npc_commandscript") { }
std::vector<ChatCommand> GetCommands() const override
{
static std::vector<ChatCommand> npcAddCommandTable =
{
{ "formation", rbac::RBAC_PERM_COMMAND_NPC_ADD_FORMATION, false, &HandleNpcAddFormationCommand, "" },
{ "item", rbac::RBAC_PERM_COMMAND_NPC_ADD_ITEM, false, &HandleNpcAddVendorItemCommand, "" },
{ "move", rbac::RBAC_PERM_COMMAND_NPC_ADD_MOVE, false, &HandleNpcAddMoveCommand, "" },
{ "temp", rbac::RBAC_PERM_COMMAND_NPC_ADD_TEMP, false, &HandleNpcAddTempSpawnCommand, "" },
//{ "weapon", rbac::RBAC_PERM_COMMAND_NPC_ADD_WEAPON, false, &HandleNpcAddWeaponCommand, "" },
{ "", rbac::RBAC_PERM_COMMAND_NPC_ADD, false, &HandleNpcAddCommand, "" },
};
static std::vector<ChatCommand> npcDeleteCommandTable =
{
{ "item", rbac::RBAC_PERM_COMMAND_NPC_DELETE_ITEM, false, &HandleNpcDeleteVendorItemCommand, "" },
{ "", rbac::RBAC_PERM_COMMAND_NPC_DELETE, false, &HandleNpcDeleteCommand, "" },
};
static std::vector<ChatCommand> npcFollowCommandTable =
{
{ "stop", rbac::RBAC_PERM_COMMAND_NPC_FOLLOW_STOP, false, &HandleNpcUnFollowCommand, "" },
{ "", rbac::RBAC_PERM_COMMAND_NPC_FOLLOW, false, &HandleNpcFollowCommand, "" },
};
static std::vector<ChatCommand> npcSetCommandTable =
{
{ "allowmove", rbac::RBAC_PERM_COMMAND_NPC_SET_ALLOWMOVE, false, &HandleNpcSetAllowMovementCommand, "" },
{ "entry", rbac::RBAC_PERM_COMMAND_NPC_SET_ENTRY, false, &HandleNpcSetEntryCommand, "" },
{ "factionid", rbac::RBAC_PERM_COMMAND_NPC_SET_FACTIONID, false, &HandleNpcSetFactionIdCommand, "" },
{ "flag", rbac::RBAC_PERM_COMMAND_NPC_SET_FLAG, false, &HandleNpcSetFlagCommand, "" },
{ "level", rbac::RBAC_PERM_COMMAND_NPC_SET_LEVEL, false, &HandleNpcSetLevelCommand, "" },
{ "link", rbac::RBAC_PERM_COMMAND_NPC_SET_LINK, false, &HandleNpcSetLinkCommand, "" },
{ "model", rbac::RBAC_PERM_COMMAND_NPC_SET_MODEL, false, &HandleNpcSetModelCommand, "" },
{ "movetype", rbac::RBAC_PERM_COMMAND_NPC_SET_MOVETYPE, false, &HandleNpcSetMoveTypeCommand, "" },
{ "phase", rbac::RBAC_PERM_COMMAND_NPC_SET_PHASE, false, &HandleNpcSetPhaseCommand, "" },
{ "spawndist", rbac::RBAC_PERM_COMMAND_NPC_SET_SPAWNDIST, false, &HandleNpcSetSpawnDistCommand, "" },
{ "spawntime", rbac::RBAC_PERM_COMMAND_NPC_SET_SPAWNTIME, false, &HandleNpcSetSpawnTimeCommand, "" },
{ "data", rbac::RBAC_PERM_COMMAND_NPC_SET_DATA, false, &HandleNpcSetDataCommand, "" },
};
static std::vector<ChatCommand> npcCommandTable =
{
{ "info", rbac::RBAC_PERM_COMMAND_NPC_INFO, false, &HandleNpcInfoCommand, "" },
{ "near", rbac::RBAC_PERM_COMMAND_NPC_NEAR, false, &HandleNpcNearCommand, "" },
{ "move", rbac::RBAC_PERM_COMMAND_NPC_MOVE, false, &HandleNpcMoveCommand, "" },
{ "playemote", rbac::RBAC_PERM_COMMAND_NPC_PLAYEMOTE, false, &HandleNpcPlayEmoteCommand, "" },
{ "say", rbac::RBAC_PERM_COMMAND_NPC_SAY, false, &HandleNpcSayCommand, "" },
{ "textemote", rbac::RBAC_PERM_COMMAND_NPC_TEXTEMOTE, false, &HandleNpcTextEmoteCommand, "" },
{ "whisper", rbac::RBAC_PERM_COMMAND_NPC_WHISPER, false, &HandleNpcWhisperCommand, "" },
{ "yell", rbac::RBAC_PERM_COMMAND_NPC_YELL, false, &HandleNpcYellCommand, "" },
{ "tame", rbac::RBAC_PERM_COMMAND_NPC_TAME, false, &HandleNpcTameCommand, "" },
{ "spawngroup", rbac::RBAC_PERM_COMMAND_NPC_SPAWNGROUP, false, &HandleNpcSpawnGroup, "" },
{ "despawngroup", rbac::RBAC_PERM_COMMAND_NPC_DESPAWNGROUP, false, &HandleNpcDespawnGroup, "" },
{ "add", rbac::RBAC_PERM_COMMAND_NPC_ADD, false, nullptr, "", npcAddCommandTable },
{ "delete", rbac::RBAC_PERM_COMMAND_NPC_DELETE, false, nullptr, "", npcDeleteCommandTable },
{ "follow", rbac::RBAC_PERM_COMMAND_NPC_FOLLOW, false, nullptr, "", npcFollowCommandTable },
{ "set", rbac::RBAC_PERM_COMMAND_NPC_SET, false, nullptr, "", npcSetCommandTable },
{ "evade", rbac::RBAC_PERM_COMMAND_NPC_EVADE, false, &HandleNpcEvadeCommand, "" },
{ "showloot", rbac::RBAC_PERM_COMMAND_NPC_SHOWLOOT, false, &HandleNpcShowLootCommand, "" },
};
static std::vector<ChatCommand> commandTable =
{
{ "npc", rbac::RBAC_PERM_COMMAND_NPC, false, nullptr, "", npcCommandTable },
};
return commandTable;
}
//add spawn of creature
static bool HandleNpcAddCommand(ChatHandler* handler, char const* args)
{
if (!*args)
return false;
char* charID = handler->extractKeyFromLink((char*)args, "Hcreature_entry");
if (!charID)
return false;
uint32 id = atoul(charID);
if (!sObjectMgr->GetCreatureTemplate(id))
return false;
Player* chr = handler->GetSession()->GetPlayer();
Map* map = chr->GetMap();
if (Transport* trans = chr->GetTransport())
{
ObjectGuid::LowType guid = map->GenerateLowGuid<HighGuid::Unit>();
CreatureData& data = sObjectMgr->NewOrExistCreatureData(guid);
data.spawnId = guid;
data.id = id;
data.phaseMask = chr->GetPhaseMaskForSpawn();
data.spawnPoint.Relocate(chr->GetTransOffsetX(), chr->GetTransOffsetY(), chr->GetTransOffsetZ(), chr->GetTransOffsetO());
if (Creature* creature = trans->CreateNPCPassenger(guid, &data))
{
creature->SaveToDB(trans->GetGOInfo()->moTransport.mapID, 1 << map->GetSpawnMode(), chr->GetPhaseMaskForSpawn());
sObjectMgr->AddCreatureToGrid(guid, &data);
}
return true;
}
Creature* creature = new Creature();
if (!creature->Create(map->GenerateLowGuid<HighGuid::Unit>(), map, chr->GetPhaseMaskForSpawn(), id, *chr))
{
delete creature;
return false;
}
creature->SaveToDB(map->GetId(), (1 << map->GetSpawnMode()), chr->GetPhaseMaskForSpawn());
ObjectGuid::LowType db_guid = creature->GetSpawnId();
// To call _LoadGoods(); _LoadQuests(); CreateTrainerSpells()
// current "creature" variable is deleted and created fresh new, otherwise old values might trigger asserts or cause undefined behavior
creature->CleanupsBeforeDelete();
delete creature;
creature = new Creature();
if (!creature->LoadFromDB(db_guid, map, true, true))
{
delete creature;
return false;
}
sObjectMgr->AddCreatureToGrid(db_guid, sObjectMgr->GetCreatureData(db_guid));
return true;
}
//add item in vendorlist
static bool HandleNpcAddVendorItemCommand(ChatHandler* handler, char const* args)
{
if (!*args)
return false;
char* pitem = handler->extractKeyFromLink((char*)args, "Hitem");
if (!pitem)
{
handler->SendSysMessage(LANG_COMMAND_NEEDITEMSEND);
handler->SetSentErrorMessage(true);
return false;
}
int32 item_int = atol(pitem);
if (item_int <= 0)
return false;
uint32 itemId = item_int;
char* fmaxcount = strtok(nullptr, " "); //add maxcount, default: 0
uint32 maxcount = 0;
if (fmaxcount)
maxcount = atoul(fmaxcount);
char* fincrtime = strtok(nullptr, " "); //add incrtime, default: 0
uint32 incrtime = 0;
if (fincrtime)
incrtime = atoul(fincrtime);
char* fextendedcost = strtok(nullptr, " "); //add ExtendedCost, default: 0
uint32 extendedcost = fextendedcost ? atoul(fextendedcost) : 0;
Creature* vendor = handler->getSelectedCreature();
if (!vendor)
{
handler->SendSysMessage(LANG_SELECT_CREATURE);
handler->SetSentErrorMessage(true);
return false;
}
uint32 vendor_entry = vendor->GetEntry();
if (!sObjectMgr->IsVendorItemValid(vendor_entry, itemId, maxcount, incrtime, extendedcost, handler->GetSession()->GetPlayer()))
{
handler->SetSentErrorMessage(true);
return false;
}
sObjectMgr->AddVendorItem(vendor_entry, itemId, maxcount, incrtime, extendedcost);
ItemTemplate const* itemTemplate = sObjectMgr->GetItemTemplate(itemId);
handler->PSendSysMessage(LANG_ITEM_ADDED_TO_LIST, itemId, itemTemplate->Name1.c_str(), maxcount, incrtime, extendedcost);
return true;
}
//add move for creature
static bool HandleNpcAddMoveCommand(ChatHandler* handler, char const* args)
{
if (!*args)
return false;
char* guidStr = strtok((char*)args, " ");
char* waitStr = strtok((char*)nullptr, " ");
ObjectGuid::LowType lowGuid = atoul(guidStr);
// attempt check creature existence by DB data
CreatureData const* data = sObjectMgr->GetCreatureData(lowGuid);
if (!data)
{
handler->PSendSysMessage(LANG_COMMAND_CREATGUIDNOTFOUND, lowGuid);
handler->SetSentErrorMessage(true);
return false;
}
int wait = waitStr ? atoi(waitStr) : 0;
if (wait < 0)
wait = 0;
// Update movement type
PreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_UPD_CREATURE_MOVEMENT_TYPE);
stmt->setUInt8(0, uint8(WAYPOINT_MOTION_TYPE));
stmt->setUInt32(1, lowGuid);
WorldDatabase.Execute(stmt);
handler->SendSysMessage(LANG_WAYPOINT_ADDED);
return true;
}
static bool HandleNpcSetAllowMovementCommand(ChatHandler* handler, char const* /*args*/)
{
if (sWorld->getAllowMovement())
{
sWorld->SetAllowMovement(false);
handler->SendSysMessage(LANG_CREATURE_MOVE_DISABLED);
}
else
{
sWorld->SetAllowMovement(true);
handler->SendSysMessage(LANG_CREATURE_MOVE_ENABLED);
}
return true;
}
static bool HandleNpcSetEntryCommand(ChatHandler* handler, char const* args)
{
if (!*args)
return false;
uint32 newEntryNum = atoul(args);
if (!newEntryNum)
return false;
Unit* unit = handler->getSelectedUnit();
if (!unit || unit->GetTypeId() != TYPEID_UNIT)
{
handler->SendSysMessage(LANG_SELECT_CREATURE);
handler->SetSentErrorMessage(true);
return false;
}
Creature* creature = unit->ToCreature();
if (creature->UpdateEntry(newEntryNum))
handler->SendSysMessage(LANG_DONE);
else
handler->SendSysMessage(LANG_ERROR);
return true;
}
//change level of creature or pet
static bool HandleNpcSetLevelCommand(ChatHandler* handler, char const* args)
{
if (!*args)
return false;
uint8 lvl = (uint8) atoi(args);
if (lvl < 1 || lvl > sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL) + 3)
{
handler->SendSysMessage(LANG_BAD_VALUE);
handler->SetSentErrorMessage(true);
return false;
}
Creature* creature = handler->getSelectedCreature();
if (!creature || creature->IsPet())
{
handler->SendSysMessage(LANG_SELECT_CREATURE);
handler->SetSentErrorMessage(true);
return false;
}
creature->SetMaxHealth(100 + 30*lvl);
creature->SetHealth(100 + 30*lvl);
creature->SetLevel(lvl);
creature->SaveToDB();
return true;
}
static bool HandleNpcDeleteCommand(ChatHandler* handler, char const* args)
{
Creature* creature = nullptr;
if (*args)
{
// number or [name] Shift-click form |color|Hcreature:creature_guid|h[name]|h|r
char* cId = handler->extractKeyFromLink((char*)args, "Hcreature");
if (!cId)
return false;
ObjectGuid::LowType lowguid = atoul(cId);
if (!lowguid)
return false;
// force respawn to make sure we find something
handler->GetSession()->GetPlayer()->GetMap()->ForceRespawn(SPAWN_TYPE_CREATURE, lowguid);
// then try to find it
creature = handler->GetCreatureFromPlayerMapByDbGuid(lowguid);
}
else
creature = handler->getSelectedCreature();
if (!creature || creature->IsPet() || creature->IsTotem())
{
handler->SendSysMessage(LANG_SELECT_CREATURE);
handler->SetSentErrorMessage(true);
return false;
}
if (TempSummon* summon = creature->ToTempSummon())
summon->UnSummon();
else
{
// Delete the creature
creature->CombatStop();
creature->DeleteFromDB();
creature->AddObjectToRemoveList();
}
handler->SendSysMessage(LANG_COMMAND_DELCREATMESSAGE);
return true;
}
//del item from vendor list
static bool HandleNpcDeleteVendorItemCommand(ChatHandler* handler, char const* args)
{
if (!*args)
return false;
Creature* vendor = handler->getSelectedCreature();
if (!vendor || !vendor->IsVendor())
{
handler->SendSysMessage(LANG_COMMAND_VENDORSELECTION);
handler->SetSentErrorMessage(true);
return false;
}
char* pitem = handler->extractKeyFromLink((char*)args, "Hitem");
if (!pitem)
{
handler->SendSysMessage(LANG_COMMAND_NEEDITEMSEND);
handler->SetSentErrorMessage(true);
return false;
}
uint32 itemId = atoul(pitem);
if (!sObjectMgr->RemoveVendorItem(vendor->GetEntry(), itemId))
{
handler->PSendSysMessage(LANG_ITEM_NOT_IN_LIST, itemId);
handler->SetSentErrorMessage(true);
return false;
}
ItemTemplate const* itemTemplate = sObjectMgr->GetItemTemplate(itemId);
handler->PSendSysMessage(LANG_ITEM_DELETED_FROM_LIST, itemId, itemTemplate->Name1.c_str());
return true;
}
//set faction of creature
static bool HandleNpcSetFactionIdCommand(ChatHandler* handler, char const* args)
{
if (!*args)
return false;
uint32 factionId = atoul(args);
if (!sFactionTemplateStore.LookupEntry(factionId))
{
handler->PSendSysMessage(LANG_WRONG_FACTION, factionId);
handler->SetSentErrorMessage(true);
return false;
}
Creature* creature = handler->getSelectedCreature();
if (!creature)
{
handler->SendSysMessage(LANG_SELECT_CREATURE);
handler->SetSentErrorMessage(true);
return false;
}
creature->SetFaction(factionId);
// Faction is set in creature_template - not inside creature
// Update in memory..
if (CreatureTemplate const* cinfo = creature->GetCreatureTemplate())<|fim▁hole|>
// ..and DB
PreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_UPD_CREATURE_FACTION);
stmt->setUInt16(0, uint16(factionId));
stmt->setUInt32(1, creature->GetEntry());
WorldDatabase.Execute(stmt);
return true;
}
//set npcflag of creature
static bool HandleNpcSetFlagCommand(ChatHandler* handler, char const* args)
{
if (!*args)
return false;
uint32 npcFlags = (uint32) atoi(args);
Creature* creature = handler->getSelectedCreature();
if (!creature)
{
handler->SendSysMessage(LANG_SELECT_CREATURE);
handler->SetSentErrorMessage(true);
return false;
}
creature->SetUInt32Value(UNIT_NPC_FLAGS, npcFlags);
PreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_UPD_CREATURE_NPCFLAG);
stmt->setUInt32(0, npcFlags);
stmt->setUInt32(1, creature->GetEntry());
WorldDatabase.Execute(stmt);
handler->SendSysMessage(LANG_VALUE_SAVED_REJOIN);
return true;
}
//set data of creature for testing scripting
static bool HandleNpcSetDataCommand(ChatHandler* handler, char const* args)
{
if (!*args)
return false;
char* arg1 = strtok((char*)args, " ");
char* arg2 = strtok((char*)nullptr, "");
if (!arg1 || !arg2)
return false;
uint32 data_1 = (uint32)atoi(arg1);
uint32 data_2 = (uint32)atoi(arg2);
if (!data_1 || !data_2)
return false;
Creature* creature = handler->getSelectedCreature();
if (!creature)
{
handler->SendSysMessage(LANG_SELECT_CREATURE);
handler->SetSentErrorMessage(true);
return false;
}
creature->AI()->SetData(data_1, data_2);
std::string AIorScript = !creature->GetAIName().empty() ? "AI type: " + creature->GetAIName() : (!creature->GetScriptName().empty() ? "Script Name: " + creature->GetScriptName() : "No AI or Script Name Set");
handler->PSendSysMessage(LANG_NPC_SETDATA, creature->GetGUID().GetCounter(), creature->GetEntry(), creature->GetName().c_str(), data_1, data_2, AIorScript.c_str());
return true;
}
//npc follow handling
static bool HandleNpcFollowCommand(ChatHandler* handler, char const* /*args*/)
{
Player* player = handler->GetSession()->GetPlayer();
Creature* creature = handler->getSelectedCreature();
if (!creature)
{
handler->PSendSysMessage(LANG_SELECT_CREATURE);
handler->SetSentErrorMessage(true);
return false;
}
// Follow player - Using pet's default dist and angle
creature->GetMotionMaster()->MoveFollow(player, PET_FOLLOW_DIST, creature->GetFollowAngle());
handler->PSendSysMessage(LANG_CREATURE_FOLLOW_YOU_NOW, creature->GetName().c_str());
return true;
}
static bool HandleNpcInfoCommand(ChatHandler* handler, char const* /*args*/)
{
Creature* target = handler->getSelectedCreature();
if (!target)
{
handler->SendSysMessage(LANG_SELECT_CREATURE);
handler->SetSentErrorMessage(true);
return false;
}
CreatureTemplate const* cInfo = target->GetCreatureTemplate();
uint32 faction = target->GetFaction();
uint32 npcflags = target->GetUInt32Value(UNIT_NPC_FLAGS);
uint32 mechanicImmuneMask = cInfo->MechanicImmuneMask;
uint32 displayid = target->GetDisplayId();
uint32 nativeid = target->GetNativeDisplayId();
uint32 entry = target->GetEntry();
int64 curRespawnDelay = target->GetRespawnCompatibilityMode() ? target->GetRespawnTimeEx() - GameTime::GetGameTime() : target->GetMap()->GetCreatureRespawnTime(target->GetSpawnId()) - GameTime::GetGameTime();
if (curRespawnDelay < 0)
curRespawnDelay = 0;
std::string curRespawnDelayStr = secsToTimeString(uint64(curRespawnDelay), true);
std::string defRespawnDelayStr = secsToTimeString(target->GetRespawnDelay(), true);
handler->PSendSysMessage(LANG_NPCINFO_CHAR, target->GetName().c_str(), target->GetSpawnId(), target->GetGUID().GetCounter(), entry, faction, npcflags, displayid, nativeid);
if (target->GetCreatureData() && target->GetCreatureData()->spawnGroupData->groupId)
{
SpawnGroupTemplateData const* const groupData = target->GetCreatureData()->spawnGroupData;
handler->PSendSysMessage(LANG_SPAWNINFO_GROUP_ID, groupData->name.c_str(), groupData->groupId, groupData->flags, target->GetMap()->IsSpawnGroupActive(groupData->groupId));
}
handler->PSendSysMessage(LANG_SPAWNINFO_COMPATIBILITY_MODE, target->GetRespawnCompatibilityMode());
handler->PSendSysMessage(LANG_NPCINFO_LEVEL, target->getLevel());
handler->PSendSysMessage(LANG_NPCINFO_EQUIPMENT, target->GetCurrentEquipmentId(), target->GetOriginalEquipmentId());
handler->PSendSysMessage(LANG_NPCINFO_HEALTH, target->GetCreateHealth(), target->GetMaxHealth(), target->GetHealth());
handler->PSendSysMessage(LANG_NPCINFO_MOVEMENT_DATA, target->GetMovementTemplate().ToString().c_str());
handler->PSendSysMessage(LANG_NPCINFO_UNIT_FIELD_FLAGS, target->GetUInt32Value(UNIT_FIELD_FLAGS));
for (UnitFlags flag : EnumUtils::Iterate<UnitFlags>())
if (target->GetUInt32Value(UNIT_FIELD_FLAGS) & flag)
handler->PSendSysMessage("* %s (0x%X)", EnumUtils::ToTitle(flag), flag);
handler->PSendSysMessage(LANG_NPCINFO_FLAGS, target->GetUInt32Value(UNIT_FIELD_FLAGS_2), target->GetUInt32Value(UNIT_DYNAMIC_FLAGS), target->GetFaction());
handler->PSendSysMessage(LANG_COMMAND_RAWPAWNTIMES, defRespawnDelayStr.c_str(), curRespawnDelayStr.c_str());
handler->PSendSysMessage(LANG_NPCINFO_LOOT, cInfo->lootid, cInfo->pickpocketLootId, cInfo->SkinLootId);
handler->PSendSysMessage(LANG_NPCINFO_DUNGEON_ID, target->GetInstanceId());
handler->PSendSysMessage(LANG_NPCINFO_PHASEMASK, target->GetPhaseMask());
handler->PSendSysMessage(LANG_NPCINFO_ARMOR, target->GetArmor());
handler->PSendSysMessage(LANG_NPCINFO_POSITION, target->GetPositionX(), target->GetPositionY(), target->GetPositionZ());
handler->PSendSysMessage(LANG_OBJECTINFO_AIINFO, target->GetAIName().c_str(), target->GetScriptName().c_str());
handler->PSendSysMessage(LANG_NPCINFO_REACTSTATE, DescribeReactState(target->GetReactState()));
if (CreatureAI const* ai = target->AI())
handler->PSendSysMessage(LANG_OBJECTINFO_AITYPE, boost::core::demangle(typeid(*ai).name()).c_str());
handler->PSendSysMessage(LANG_NPCINFO_FLAGS_EXTRA, cInfo->flags_extra);
for (CreatureFlagsExtra flag : EnumUtils::Iterate<CreatureFlagsExtra>())
if (cInfo->flags_extra & flag)
handler->PSendSysMessage("* %s (0x%X)", EnumUtils::ToTitle(flag), flag);
for (NPCFlags flag : EnumUtils::Iterate<NPCFlags>())
if (npcflags & flag)
handler->PSendSysMessage("* %s (0x%X)", EnumUtils::ToTitle(flag), flag);
handler->PSendSysMessage(LANG_NPCINFO_MECHANIC_IMMUNE, mechanicImmuneMask);
for (Mechanics m : EnumUtils::Iterate<Mechanics>())
if (m && (mechanicImmuneMask & (1 << (m-1))))
handler->PSendSysMessage("* %s (0x%X)", EnumUtils::ToTitle(m), m);
return true;
}
static bool HandleNpcNearCommand(ChatHandler* handler, char const* args)
{
float distance = (!*args) ? 10.0f : float((atof(args)));
uint32 count = 0;
Player* player = handler->GetSession()->GetPlayer();
PreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_CREATURE_NEAREST);
stmt->setFloat(0, player->GetPositionX());
stmt->setFloat(1, player->GetPositionY());
stmt->setFloat(2, player->GetPositionZ());
stmt->setUInt32(3, player->GetMapId());
stmt->setFloat(4, player->GetPositionX());
stmt->setFloat(5, player->GetPositionY());
stmt->setFloat(6, player->GetPositionZ());
stmt->setFloat(7, distance * distance);
PreparedQueryResult result = WorldDatabase.Query(stmt);
if (result)
{
do
{
Field* fields = result->Fetch();
ObjectGuid::LowType guid = fields[0].GetUInt32();
uint32 entry = fields[1].GetUInt32();
float x = fields[2].GetFloat();
float y = fields[3].GetFloat();
float z = fields[4].GetFloat();
uint16 mapId = fields[5].GetUInt16();
CreatureTemplate const* creatureTemplate = sObjectMgr->GetCreatureTemplate(entry);
if (!creatureTemplate)
continue;
handler->PSendSysMessage(LANG_CREATURE_LIST_CHAT, guid, guid, creatureTemplate->Name.c_str(), x, y, z, mapId, "", "");
++count;
}
while (result->NextRow());
}
handler->PSendSysMessage(LANG_COMMAND_NEAR_NPC_MESSAGE, distance, count);
return true;
}
//move selected creature
static bool HandleNpcMoveCommand(ChatHandler* handler, char const* args)
{
ObjectGuid::LowType lowguid = 0;
Creature* creature = handler->getSelectedCreature();
Player const* player = handler->GetSession()->GetPlayer();
if (!player)
return false;
if (creature)
lowguid = creature->GetSpawnId();
else
{
// number or [name] Shift-click form |color|Hcreature:creature_guid|h[name]|h|r
char* cId = handler->extractKeyFromLink((char*)args, "Hcreature");
if (!cId)
return false;
lowguid = atoul(cId);
}
// Attempting creature load from DB data
CreatureData const* data = sObjectMgr->GetCreatureData(lowguid);
if (!data)
{
handler->PSendSysMessage(LANG_COMMAND_CREATGUIDNOTFOUND, lowguid);
handler->SetSentErrorMessage(true);
return false;
}
if (player->GetMapId() != data->spawnPoint.GetMapId())
{
handler->PSendSysMessage(LANG_COMMAND_CREATUREATSAMEMAP, lowguid);
handler->SetSentErrorMessage(true);
return false;
}
// update position in memory
sObjectMgr->RemoveCreatureFromGrid(lowguid, data);
const_cast<CreatureData*>(data)->spawnPoint.Relocate(*player);
sObjectMgr->AddCreatureToGrid(lowguid, data);
// update position in DB
PreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_UPD_CREATURE_POSITION);
stmt->setFloat(0, player->GetPositionX());
stmt->setFloat(1, player->GetPositionY());
stmt->setFloat(2, player->GetPositionZ());
stmt->setFloat(3, player->GetOrientation());
stmt->setUInt32(4, lowguid);
WorldDatabase.Execute(stmt);
// respawn selected creature at the new location
if (creature)
{
if (creature->IsAlive())
creature->setDeathState(JUST_DIED);
creature->Respawn(true);
if (!creature->GetRespawnCompatibilityMode())
creature->AddObjectToRemoveList();
}
handler->PSendSysMessage(LANG_COMMAND_CREATUREMOVED);
return true;
}
//play npc emote
static bool HandleNpcPlayEmoteCommand(ChatHandler* handler, char const* args)
{
uint32 emote = atoi((char*)args);
Creature* target = handler->getSelectedCreature();
if (!target)
{
handler->SendSysMessage(LANG_SELECT_CREATURE);
handler->SetSentErrorMessage(true);
return false;
}
target->SetUInt32Value(UNIT_NPC_EMOTESTATE, emote);
return true;
}
//set model of creature
static bool HandleNpcSetModelCommand(ChatHandler* handler, char const* args)
{
if (!*args)
return false;
uint32 displayId = atoul(args);
Creature* creature = handler->getSelectedCreature();
if (!creature || creature->IsPet())
{
handler->SendSysMessage(LANG_SELECT_CREATURE);
handler->SetSentErrorMessage(true);
return false;
}
if (!sCreatureDisplayInfoStore.LookupEntry(displayId))
{
handler->PSendSysMessage(LANG_COMMAND_INVALID_PARAM, args);
handler->SetSentErrorMessage(true);
return false;
}
creature->SetDisplayId(displayId);
creature->SetNativeDisplayId(displayId);
creature->SaveToDB();
return true;
}
/**HandleNpcSetMoveTypeCommand
* Set the movement type for an NPC.<br/>
* <br/>
* Valid movement types are:
* <ul>
* <li> stay - NPC wont move </li>
* <li> random - NPC will move randomly according to the spawndist </li>
* <li> way - NPC will move with given waypoints set </li>
* </ul>
* additional parameter: NODEL - so no waypoints are deleted, if you
* change the movement type
*/
static bool HandleNpcSetMoveTypeCommand(ChatHandler* handler, char const* args)
{
if (!*args)
return false;
// 3 arguments:
// GUID (optional - you can also select the creature)
// stay|random|way (determines the kind of movement)
// NODEL (optional - tells the system NOT to delete any waypoints)
// this is very handy if you want to do waypoints, that are
// later switched on/off according to special events (like escort
// quests, etc)
char* guid_str = strtok((char*)args, " ");
char* type_str = strtok((char*)nullptr, " ");
char* dontdel_str = strtok((char*)nullptr, " ");
bool doNotDelete = false;
if (!guid_str)
return false;
ObjectGuid::LowType lowguid = 0;
Creature* creature = nullptr;
if (dontdel_str)
{
//TC_LOG_ERROR("misc", "DEBUG: All 3 params are set");
// All 3 params are set
// GUID
// type
// doNotDEL
if (stricmp(dontdel_str, "NODEL") == 0)
{
//TC_LOG_ERROR("misc", "DEBUG: doNotDelete = true;");
doNotDelete = true;
}
}
else
{
// Only 2 params - but maybe NODEL is set
if (type_str)
{
TC_LOG_ERROR("misc", "DEBUG: Only 2 params ");
if (stricmp(type_str, "NODEL") == 0)
{
//TC_LOG_ERROR("misc", "DEBUG: type_str, NODEL ");
doNotDelete = true;
type_str = nullptr;
}
}
}
if (!type_str) // case .setmovetype $move_type (with selected creature)
{
type_str = guid_str;
creature = handler->getSelectedCreature();
if (!creature || creature->IsPet())
return false;
lowguid = creature->GetSpawnId();
}
else // case .setmovetype #creature_guid $move_type (with selected creature)
{
lowguid = atoul(guid_str);
if (lowguid)
creature = handler->GetCreatureFromPlayerMapByDbGuid(lowguid);
// attempt check creature existence by DB data
if (!creature)
{
CreatureData const* data = sObjectMgr->GetCreatureData(lowguid);
if (!data)
{
handler->PSendSysMessage(LANG_COMMAND_CREATGUIDNOTFOUND, lowguid);
handler->SetSentErrorMessage(true);
return false;
}
}
else
{
lowguid = creature->GetSpawnId();
}
}
// now lowguid is low guid really existed creature
// and creature point (maybe) to this creature or nullptr
MovementGeneratorType move_type;
std::string type = type_str;
if (type == "stay")
move_type = IDLE_MOTION_TYPE;
else if (type == "random")
move_type = RANDOM_MOTION_TYPE;
else if (type == "way")
move_type = WAYPOINT_MOTION_TYPE;
else
return false;
// update movement type
//if (doNotDelete == false)
// WaypointMgr.DeletePath(lowguid);
if (creature)
{
// update movement type
if (doNotDelete == false)
creature->LoadPath(0);
creature->SetDefaultMovementType(move_type);
creature->GetMotionMaster()->Initialize();
if (creature->IsAlive()) // dead creature will reset movement generator at respawn
{
creature->setDeathState(JUST_DIED);
creature->Respawn();
}
creature->SaveToDB();
}
if (doNotDelete == false)
{
handler->PSendSysMessage(LANG_MOVE_TYPE_SET, type_str);
}
else
{
handler->PSendSysMessage(LANG_MOVE_TYPE_SET_NODEL, type_str);
}
return true;
}
//npc phasemask handling
//change phasemask of creature or pet
static bool HandleNpcSetPhaseCommand(ChatHandler* handler, char const* args)
{
if (!*args)
return false;
uint32 phasemask = atoul(args);
if (phasemask == 0)
{
handler->SendSysMessage(LANG_BAD_VALUE);
handler->SetSentErrorMessage(true);
return false;
}
Creature* creature = handler->getSelectedCreature();
if (!creature)
{
handler->SendSysMessage(LANG_SELECT_CREATURE);
handler->SetSentErrorMessage(true);
return false;
}
creature->SetPhaseMask(phasemask, true);
if (!creature->IsPet())
creature->SaveToDB();
return true;
}
//set spawn dist of creature
static bool HandleNpcSetSpawnDistCommand(ChatHandler* handler, char const* args)
{
if (!*args)
return false;
float option = (float)(atof((char*)args));
if (option < 0.0f)
{
handler->SendSysMessage(LANG_BAD_VALUE);
return false;
}
MovementGeneratorType mtype = IDLE_MOTION_TYPE;
if (option >0.0f)
mtype = RANDOM_MOTION_TYPE;
Creature* creature = handler->getSelectedCreature();
ObjectGuid::LowType guidLow = 0;
if (creature)
guidLow = creature->GetSpawnId();
else
return false;
creature->SetRespawnRadius((float)option);
creature->SetDefaultMovementType(mtype);
creature->GetMotionMaster()->Initialize();
if (creature->IsAlive()) // dead creature will reset movement generator at respawn
{
creature->setDeathState(JUST_DIED);
creature->Respawn();
}
PreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_UPD_CREATURE_SPAWN_DISTANCE);
stmt->setFloat(0, option);
stmt->setUInt8(1, uint8(mtype));
stmt->setUInt32(2, guidLow);
WorldDatabase.Execute(stmt);
handler->PSendSysMessage(LANG_COMMAND_SPAWNDIST, option);
return true;
}
//spawn time handling
static bool HandleNpcSetSpawnTimeCommand(ChatHandler* handler, char const* args)
{
if (!*args)
return false;
char* stime = strtok((char*)args, " ");
if (!stime)
return false;
int spawnTime = atoi(stime);
if (spawnTime < 0)
{
handler->SendSysMessage(LANG_BAD_VALUE);
handler->SetSentErrorMessage(true);
return false;
}
Creature* creature = handler->getSelectedCreature();
ObjectGuid::LowType guidLow = 0;
if (creature)
guidLow = creature->GetSpawnId();
else
return false;
PreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_UPD_CREATURE_SPAWN_TIME_SECS);
stmt->setUInt32(0, uint32(spawnTime));
stmt->setUInt32(1, guidLow);
WorldDatabase.Execute(stmt);
creature->SetRespawnDelay((uint32)spawnTime);
handler->PSendSysMessage(LANG_COMMAND_SPAWNTIME, spawnTime);
return true;
}
static bool HandleNpcSayCommand(ChatHandler* handler, char const* args)
{
if (!*args)
return false;
Creature* creature = handler->getSelectedCreature();
if (!creature)
{
handler->SendSysMessage(LANG_SELECT_CREATURE);
handler->SetSentErrorMessage(true);
return false;
}
creature->Say(args, LANG_UNIVERSAL);
// make some emotes
char lastchar = args[strlen(args) - 1];
switch (lastchar)
{
case '?': creature->HandleEmoteCommand(EMOTE_ONESHOT_QUESTION); break;
case '!': creature->HandleEmoteCommand(EMOTE_ONESHOT_EXCLAMATION); break;
default: creature->HandleEmoteCommand(EMOTE_ONESHOT_TALK); break;
}
return true;
}
//show text emote by creature in chat
static bool HandleNpcTextEmoteCommand(ChatHandler* handler, char const* args)
{
if (!*args)
return false;
Creature* creature = handler->getSelectedCreature();
if (!creature)
{
handler->SendSysMessage(LANG_SELECT_CREATURE);
handler->SetSentErrorMessage(true);
return false;
}
creature->TextEmote(args);
return true;
}
// npc unfollow handling
static bool HandleNpcUnFollowCommand(ChatHandler* handler, char const* /*args*/)
{
Player* player = handler->GetSession()->GetPlayer();
Creature* creature = handler->getSelectedCreature();
if (!creature)
{
handler->PSendSysMessage(LANG_SELECT_CREATURE);
handler->SetSentErrorMessage(true);
return false;
}
MovementGenerator* movement = creature->GetMotionMaster()->GetMovementGenerator([player](MovementGenerator const* a) -> bool
{
if (a->GetMovementGeneratorType() == FOLLOW_MOTION_TYPE)
{
FollowMovementGenerator const* followMovement = dynamic_cast<FollowMovementGenerator const*>(a);
return followMovement && followMovement->GetTarget() == player;
}
return false;
});
if (!movement)
{
handler->PSendSysMessage(LANG_CREATURE_NOT_FOLLOW_YOU, creature->GetName().c_str());
handler->SetSentErrorMessage(true);
return false;
}
creature->GetMotionMaster()->Remove(movement);
handler->PSendSysMessage(LANG_CREATURE_NOT_FOLLOW_YOU_NOW, creature->GetName().c_str());
return true;
}
// make npc whisper to player
static bool HandleNpcWhisperCommand(ChatHandler* handler, char const* args)
{
if (!*args)
{
handler->SendSysMessage(LANG_CMD_SYNTAX);
handler->SetSentErrorMessage(true);
return false;
}
char* receiver_str = strtok((char*)args, " ");
char* text = strtok(nullptr, "");
if (!receiver_str || !text)
{
handler->SendSysMessage(LANG_CMD_SYNTAX);
handler->SetSentErrorMessage(true);
return false;
}
Creature* creature = handler->getSelectedCreature();
if (!creature)
{
handler->SendSysMessage(LANG_SELECT_CREATURE);
handler->SetSentErrorMessage(true);
return false;
}
ObjectGuid receiver_guid(HighGuid::Player, uint32(atoul(receiver_str)));
// check online security
Player* receiver = ObjectAccessor::FindPlayer(receiver_guid);
if (handler->HasLowerSecurity(receiver, ObjectGuid::Empty))
return false;
creature->Whisper(text, LANG_UNIVERSAL, receiver);
return true;
}
static bool HandleNpcYellCommand(ChatHandler* handler, char const* args)
{
if (!*args)
{
handler->SendSysMessage(LANG_CMD_SYNTAX);
handler->SetSentErrorMessage(true);
return false;
}
Creature* creature = handler->getSelectedCreature();
if (!creature)
{
handler->SendSysMessage(LANG_SELECT_CREATURE);
handler->SetSentErrorMessage(true);
return false;
}
creature->Yell(args, LANG_UNIVERSAL);
// make an emote
creature->HandleEmoteCommand(EMOTE_ONESHOT_SHOUT);
return true;
}
// add creature, temp only
static bool HandleNpcAddTempSpawnCommand(ChatHandler* handler, char const* args)
{
if (!*args)
return false;
bool loot = false;
char const* spawntype_str = strtok((char*)args, " ");
char const* entry_str = strtok(nullptr, "");
if (stricmp(spawntype_str, "LOOT") == 0)
loot = true;
else if (stricmp(spawntype_str, "NOLOOT") == 0)
loot = false;
else
entry_str = args;
char* charID = handler->extractKeyFromLink((char*)entry_str, "Hcreature_entry");
if (!charID)
return false;
Player* chr = handler->GetSession()->GetPlayer();
uint32 id = atoul(charID);
if (!id)
return false;
if (!sObjectMgr->GetCreatureTemplate(id))
return false;
chr->SummonCreature(id, *chr, loot ? TEMPSUMMON_CORPSE_TIMED_DESPAWN : TEMPSUMMON_CORPSE_DESPAWN, 30 * IN_MILLISECONDS);
return true;
}
//npc tame handling
static bool HandleNpcTameCommand(ChatHandler* handler, char const* /*args*/)
{
Creature* creatureTarget = handler->getSelectedCreature();
if (!creatureTarget || creatureTarget->IsPet())
{
handler->PSendSysMessage (LANG_SELECT_CREATURE);
handler->SetSentErrorMessage (true);
return false;
}
Player* player = handler->GetSession()->GetPlayer();
if (player->GetPetGUID())
{
handler->SendSysMessage (LANG_YOU_ALREADY_HAVE_PET);
handler->SetSentErrorMessage (true);
return false;
}
CreatureTemplate const* cInfo = creatureTarget->GetCreatureTemplate();
if (!cInfo->IsTameable (player->CanTameExoticPets()))
{
handler->PSendSysMessage (LANG_CREATURE_NON_TAMEABLE, cInfo->Entry);
handler->SetSentErrorMessage (true);
return false;
}
// Everything looks OK, create new pet
Pet* pet = player->CreateTamedPetFrom(creatureTarget);
if (!pet)
{
handler->PSendSysMessage (LANG_CREATURE_NON_TAMEABLE, cInfo->Entry);
handler->SetSentErrorMessage (true);
return false;
}
// place pet before player
float x, y, z;
player->GetClosePoint (x, y, z, creatureTarget->GetCombatReach(), CONTACT_DISTANCE);
pet->Relocate(x, y, z, float(M_PI) - player->GetOrientation());
// set pet to defensive mode by default (some classes can't control controlled pets in fact).
pet->SetReactState(REACT_DEFENSIVE);
// calculate proper level
uint8 level = std::max<uint8>(player->getLevel()-5, creatureTarget->getLevel());
// prepare visual effect for levelup
pet->SetUInt32Value(UNIT_FIELD_LEVEL, level - 1);
// add to world
pet->GetMap()->AddToMap(pet->ToCreature());
// visual effect for levelup
pet->SetUInt32Value(UNIT_FIELD_LEVEL, level);
// caster have pet now
player->SetMinion(pet, true);
pet->SavePetToDB(PET_SAVE_AS_CURRENT);
player->PetSpellInitialize();
return true;
}
static bool HandleNpcEvadeCommand(ChatHandler* handler, char const* args)
{
Creature* creatureTarget = handler->getSelectedCreature();
if (!creatureTarget || creatureTarget->IsPet())
{
handler->PSendSysMessage(LANG_SELECT_CREATURE);
handler->SetSentErrorMessage(true);
return false;
}
if (!creatureTarget->IsAIEnabled())
{
handler->PSendSysMessage(LANG_CREATURE_NOT_AI_ENABLED);
handler->SetSentErrorMessage(true);
return false;
}
char* type_str = args ? strtok((char*)args, " ") : nullptr;
char* force_str = args ? strtok(nullptr, " ") : nullptr;
CreatureAI::EvadeReason why = CreatureAI::EVADE_REASON_OTHER;
bool force = false;
if (type_str)
{
if (stricmp(type_str, "NO_HOSTILES") == 0 || stricmp(type_str, "EVADE_REASON_NO_HOSTILES") == 0)
why = CreatureAI::EVADE_REASON_NO_HOSTILES;
else if (stricmp(type_str, "BOUNDARY") == 0 || stricmp(type_str, "EVADE_REASON_BOUNDARY") == 0)
why = CreatureAI::EVADE_REASON_BOUNDARY;
else if (stricmp(type_str, "SEQUENCE_BREAK") == 0 || stricmp(type_str, "EVADE_REASON_SEQUENCE_BREAK") == 0)
why = CreatureAI::EVADE_REASON_SEQUENCE_BREAK;
else if (stricmp(type_str, "FORCE") == 0)
force = true;
if (!force && force_str)
if (stricmp(force_str, "FORCE") == 0)
force = true;
}
if (force)
creatureTarget->ClearUnitState(UNIT_STATE_EVADE);
creatureTarget->AI()->EnterEvadeMode(why);
return true;
}
static void _ShowLootEntry(ChatHandler* handler, uint32 itemId, uint8 itemCount, bool alternateString = false)
{
ItemTemplate const* itemTemplate = sObjectMgr->GetItemTemplate(itemId);
ItemLocale const* itemLocale = sObjectMgr->GetItemLocale(itemId);
char const* name = nullptr;
if (itemLocale)
name = itemLocale->Name[handler->GetSessionDbcLocale()].c_str();
if ((!name || !*name) && itemTemplate)
name = itemTemplate->Name1.c_str();
if (!name)
name = "Unknown item";
handler->PSendSysMessage(alternateString ? LANG_COMMAND_NPC_SHOWLOOT_ENTRY_2 : LANG_COMMAND_NPC_SHOWLOOT_ENTRY,
itemCount, ItemQualityColors[itemTemplate ? itemTemplate->Quality : uint32(ITEM_QUALITY_POOR)], itemId, name, itemId);
}
static void _IterateNotNormalLootMap(ChatHandler* handler, NotNormalLootItemMap const& map, std::vector<LootItem> const& items)
{
for (NotNormalLootItemMap::value_type const& pair : map)
{
if (!pair.second)
continue;
ObjectGuid guid = ObjectGuid::Create<HighGuid::Player>(pair.first);
Player const* player = ObjectAccessor::FindConnectedPlayer(guid);
handler->PSendSysMessage(LANG_COMMAND_NPC_SHOWLOOT_SUBLABEL, player ? player->GetName() : Trinity::StringFormat("Offline player (GuidLow 0x%08x)", pair.first).c_str(), pair.second->size());
for (auto it = pair.second->cbegin(); it != pair.second->cend(); ++it)
{
LootItem const& item = items[it->index];
if (!(it->is_looted) && !item.is_looted)
_ShowLootEntry(handler, item.itemid, item.count, true);
}
}
}
static bool HandleNpcShowLootCommand(ChatHandler* handler, char const* args)
{
Creature* creatureTarget = handler->getSelectedCreature();
if (!creatureTarget || creatureTarget->IsPet())
{
handler->PSendSysMessage(LANG_SELECT_CREATURE);
handler->SetSentErrorMessage(true);
return false;
}
Loot const& loot = creatureTarget->loot;
if (!creatureTarget->isDead() || loot.empty())
{
handler->PSendSysMessage(LANG_COMMAND_NOT_DEAD_OR_NO_LOOT, creatureTarget->GetName());
handler->SetSentErrorMessage(true);
return false;
}
handler->PSendSysMessage(LANG_COMMAND_NPC_SHOWLOOT_HEADER, creatureTarget->GetName(), creatureTarget->GetEntry());
handler->PSendSysMessage(LANG_COMMAND_NPC_SHOWLOOT_MONEY, loot.gold / GOLD, (loot.gold%GOLD) / SILVER, loot.gold%SILVER);
if (strcmp(args, "all")) // nonzero from strcmp <-> not equal
{
handler->PSendSysMessage(LANG_COMMAND_NPC_SHOWLOOT_LABEL, "Standard items", loot.items.size());
for (LootItem const& item : loot.items)
if (!item.is_looted)
_ShowLootEntry(handler, item.itemid, item.count);
handler->PSendSysMessage(LANG_COMMAND_NPC_SHOWLOOT_LABEL, "Quest items", loot.quest_items.size());
for (LootItem const& item : loot.quest_items)
if (!item.is_looted)
_ShowLootEntry(handler, item.itemid, item.count);
}
else
{
handler->PSendSysMessage(LANG_COMMAND_NPC_SHOWLOOT_LABEL, "Standard items", loot.items.size());
for (LootItem const& item : loot.items)
if (!item.is_looted && !item.freeforall && item.conditions.empty())
_ShowLootEntry(handler, item.itemid, item.count);
if (!loot.GetPlayerQuestItems().empty())
{
handler->PSendSysMessage(LANG_COMMAND_NPC_SHOWLOOT_LABEL_2, "Per-player quest items");
_IterateNotNormalLootMap(handler, loot.GetPlayerQuestItems(), loot.quest_items);
}
if (!loot.GetPlayerFFAItems().empty())
{
handler->PSendSysMessage(LANG_COMMAND_NPC_SHOWLOOT_LABEL_2, "FFA items per allowed player");
_IterateNotNormalLootMap(handler, loot.GetPlayerFFAItems(), loot.items);
}
if (!loot.GetPlayerNonQuestNonFFAConditionalItems().empty())
{
handler->PSendSysMessage(LANG_COMMAND_NPC_SHOWLOOT_LABEL_2, "Per-player conditional items");
_IterateNotNormalLootMap(handler, loot.GetPlayerNonQuestNonFFAConditionalItems(), loot.items);
}
}
return true;
}
static bool HandleNpcAddFormationCommand(ChatHandler* handler, char const* args)
{
if (!*args)
return false;
ObjectGuid::LowType leaderGUID = atoul(args);
Creature* creature = handler->getSelectedCreature();
if (!creature || !creature->GetSpawnId())
{
handler->SendSysMessage(LANG_SELECT_CREATURE);
handler->SetSentErrorMessage(true);
return false;
}
ObjectGuid::LowType lowguid = creature->GetSpawnId();
if (creature->GetFormation())
{
handler->PSendSysMessage("Selected creature is already member of group %u", creature->GetFormation()->GetLeaderSpawnId());
return false;
}
if (!lowguid)
return false;
Player* chr = handler->GetSession()->GetPlayer();
float followAngle = (creature->GetAbsoluteAngle(chr) - chr->GetOrientation()) * 180.0f / float(M_PI);
float followDist = std::sqrt(std::pow(chr->GetPositionX() - creature->GetPositionX(), 2.f) + std::pow(chr->GetPositionY() - creature->GetPositionY(), 2.f));
uint32 groupAI = 0;
sFormationMgr->AddFormationMember(lowguid, followAngle, followDist, leaderGUID, groupAI);
creature->SearchFormation();
PreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_INS_CREATURE_FORMATION);
stmt->setUInt32(0, leaderGUID);
stmt->setUInt32(1, lowguid);
stmt->setFloat (2, followAngle);
stmt->setFloat (3, followDist);
stmt->setUInt32(4, groupAI);
WorldDatabase.Execute(stmt);
handler->PSendSysMessage("Creature %u added to formation with leader %u", lowguid, leaderGUID);
return true;
}
static bool HandleNpcSetLinkCommand(ChatHandler* handler, char const* args)
{
if (!*args)
return false;
ObjectGuid::LowType linkguid = atoul(args);
Creature* creature = handler->getSelectedCreature();
if (!creature)
{
handler->SendSysMessage(LANG_SELECT_CREATURE);
handler->SetSentErrorMessage(true);
return false;
}
if (!creature->GetSpawnId())
{
handler->PSendSysMessage("Selected creature %u isn't in creature table", creature->GetGUID().GetCounter());
handler->SetSentErrorMessage(true);
return false;
}
if (!sObjectMgr->SetCreatureLinkedRespawn(creature->GetSpawnId(), linkguid))
{
handler->PSendSysMessage("Selected creature can't link with guid '%u'", linkguid);
handler->SetSentErrorMessage(true);
return false;
}
handler->PSendSysMessage("LinkGUID '%u' added to creature with DBTableGUID: '%u'", linkguid, creature->GetSpawnId());
return true;
}
/// @todo NpcCommands that need to be fixed :
static bool HandleNpcAddWeaponCommand(ChatHandler* /*handler*/, char const* /*args*/)
{
/*if (!*args)
return false;
uint64 guid = handler->GetSession()->GetPlayer()->GetSelection();
if (guid == 0)
{
handler->SendSysMessage(LANG_NO_SELECTION);
return true;
}
Creature* creature = ObjectAccessor::GetCreature(*handler->GetSession()->GetPlayer(), guid);
if (!creature)
{
handler->SendSysMessage(LANG_SELECT_CREATURE);
return true;
}
char* pSlotID = strtok((char*)args, " ");
if (!pSlotID)
return false;
char* pItemID = strtok(nullptr, " ");
if (!pItemID)
return false;
uint32 ItemID = atoi(pItemID);
uint32 SlotID = atoi(pSlotID);
ItemTemplate* tmpItem = sObjectMgr->GetItemTemplate(ItemID);
bool added = false;
if (tmpItem)
{
switch (SlotID)
{
case 1:
creature->SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_DISPLAY, ItemID);
added = true;
break;
case 2:
creature->SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_DISPLAY_01, ItemID);
added = true;
break;
case 3:
creature->SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_DISPLAY_02, ItemID);
added = true;
break;
default:
handler->PSendSysMessage(LANG_ITEM_SLOT_NOT_EXIST, SlotID);
added = false;
break;
}
if (added)
handler->PSendSysMessage(LANG_ITEM_ADDED_TO_SLOT, ItemID, tmpItem->Name1, SlotID);
}
else
{
handler->PSendSysMessage(LANG_ITEM_NOT_FOUND, ItemID);
return true;
}
*/
return true;
}
};
void AddSC_npc_commandscript()
{
new npc_commandscript();
}<|fim▁end|>
|
const_cast<CreatureTemplate*>(cinfo)->faction = factionId;
|
<|file_name|>V3Changed.cpp<|end_file_name|><|fim▁begin|>// -*- mode: C++; c-file-style: "cc-mode" -*-
//*************************************************************************
// DESCRIPTION: Verilator: Add temporaries, such as for changed nodes
//
// Code available from: http://www.veripool.org/verilator
//
//*************************************************************************
//
// Copyright 2003-2013 by Wilson Snyder. This program is free software; you can
// redistribute it and/or modify it under the terms of either the GNU
// Lesser General Public License Version 3 or the Perl Artistic License
// Version 2.0.
//
// Verilator 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.
//
//*************************************************************************
// V3Changed's Transformations:
//
// Each module:
// Each combo block
// For each variable that comes from combo block and is generated AFTER a usage
// Add __Vlast_{var} to local section, init to current value (just use array?)
// Change = if any var != last.
// If a signal is used as a clock in this module or any
// module *below*, and it isn't a input to this module,
// we need to indicate a new clock has been created.
//
//*************************************************************************
#include "config_build.h"
#include "verilatedos.h"
#include <cstdio>
#include <cstdarg>
#include <unistd.h>
#include <algorithm>
#include <set>
#include "V3Global.h"
#include "V3Ast.h"
#include "V3Changed.h"
#include "V3EmitCBase.h"
//######################################################################
// Changed state, as a visitor of each AstNode
class ChangedVisitor : public AstNVisitor {
private:
// NODE STATE
// Entire netlist:
// AstVarScope::user1() -> bool. True indicates processed
AstUser1InUse m_inuser1;
// STATE
AstNodeModule* m_topModp; // Top module
AstScope* m_scopetopp; // Scope under TOPSCOPE
AstCFunc* m_chgFuncp; // Change function we're building
// CONSTANTS
enum MiscConsts {
DETECTARRAY_MAX_INDEXES = 256 // How many indexes before error
// Ok to increase this, but may result in much slower model
};
// METHODS
static int debug() {<|fim▁hole|> return level;
}
AstNode* aselIfNeeded(bool isArray, int index, AstNode* childp) {
if (isArray) {
return new AstArraySel(childp->fileline(), childp,
new AstConst(childp->fileline(), index));
} else {
return childp;
}
}
void genChangeDet(AstVarScope* vscp) {
#ifdef NEW_ORDERING
vscp->v3fatalSrc("Not applicable\n");
#endif
AstVar* varp = vscp->varp();
vscp->v3warn(IMPERFECTSCH,"Imperfect scheduling of variable: "<<vscp);
AstUnpackArrayDType* arrayp = varp->dtypeSkipRefp()->castUnpackArrayDType();
AstStructDType *structp = varp->dtypeSkipRefp()->castStructDType();
bool isArray = arrayp;
bool isStruct = structp && structp->packed();
int elements = isArray ? arrayp->elementsConst() : 1;
if (isArray && (elements > DETECTARRAY_MAX_INDEXES)) {
vscp->v3warn(E_DETECTARRAY, "Unsupported: Can't detect more than "<<cvtToStr(DETECTARRAY_MAX_INDEXES)
<<" array indexes (probably with UNOPTFLAT warning suppressed): "<<varp->prettyName()<<endl
<<vscp->warnMore()
<<"... Could recompile with DETECTARRAY_MAX_INDEXES increased to at least "<<cvtToStr(elements));
} else if (!isArray && !isStruct
&& !varp->dtypeSkipRefp()->castBasicDType()) {
if (debug()) varp->dumpTree(cout,"-DETECTARRAY-");
vscp->v3warn(E_DETECTARRAY, "Unsupported: Can't detect changes on complex variable (probably with UNOPTFLAT warning suppressed): "<<varp->prettyName());
} else {
string newvarname = "__Vchglast__"+vscp->scopep()->nameDotless()+"__"+varp->shortName();
// Create: VARREF(_last)
// ASSIGN(VARREF(_last), VARREF(var))
// ...
// CHANGEDET(VARREF(_last), VARREF(var))
AstVar* newvarp = new AstVar (varp->fileline(), AstVarType::MODULETEMP, newvarname, varp);
m_topModp->addStmtp(newvarp);
AstVarScope* newvscp = new AstVarScope(vscp->fileline(), m_scopetopp, newvarp);
m_scopetopp->addVarp(newvscp);
for (int index=0; index<elements; ++index) {
AstChangeDet* changep
= new AstChangeDet (vscp->fileline(),
aselIfNeeded(isArray, index,
new AstVarRef(vscp->fileline(), vscp, false)),
aselIfNeeded(isArray, index,
new AstVarRef(vscp->fileline(), newvscp, false)),
false);
m_chgFuncp->addStmtsp(changep);
AstAssign* initp
= new AstAssign (vscp->fileline(),
aselIfNeeded(isArray, index,
new AstVarRef(vscp->fileline(), newvscp, true)),
aselIfNeeded(isArray, index,
new AstVarRef(vscp->fileline(), vscp, false)));
m_chgFuncp->addFinalsp(initp);
}
}
}
// VISITORS
virtual void visit(AstNodeModule* nodep, AstNUser*) {
UINFO(4," MOD "<<nodep<<endl);
if (nodep->isTop()) {
m_topModp = nodep;
}
nodep->iterateChildren(*this);
}
virtual void visit(AstTopScope* nodep, AstNUser*) {
UINFO(4," TS "<<nodep<<endl);
// Clearing
AstNode::user1ClearTree();
// Create the change detection function
AstScope* scopep = nodep->scopep();
if (!scopep) nodep->v3fatalSrc("No scope found on top level, perhaps you have no statements?\n");
m_scopetopp = scopep;
// Create change detection function
m_chgFuncp = new AstCFunc(nodep->fileline(), "_change_request", scopep, "IData");
m_chgFuncp->argTypes(EmitCBaseVisitor::symClassVar());
m_chgFuncp->symProlog(true);
m_chgFuncp->declPrivate(true);
m_scopetopp->addActivep(m_chgFuncp);
// We need at least one change detect so we know to emit the correct code
m_chgFuncp->addStmtsp(new AstChangeDet(nodep->fileline(), NULL, NULL, false));
//
nodep->iterateChildren(*this);
}
virtual void visit(AstVarScope* nodep, AstNUser*) {
if (nodep->isCircular()) {
UINFO(8," CIRC "<<nodep<<endl);
if (!nodep->user1SetOnce()) {
genChangeDet(nodep);
}
}
}
//--------------------
// Default: Just iterate
virtual void visit(AstNode* nodep, AstNUser*) {
nodep->iterateChildren(*this);
}
public:
// CONSTUCTORS
ChangedVisitor(AstNetlist* nodep) {
m_topModp = NULL;
m_chgFuncp = NULL;
m_scopetopp = NULL;
nodep->accept(*this);
}
virtual ~ChangedVisitor() {}
};
//######################################################################
// Changed class functions
void V3Changed::changedAll(AstNetlist* nodep) {
UINFO(2,__FUNCTION__<<": "<<endl);
ChangedVisitor visitor (nodep);
}<|fim▁end|>
|
static int level = -1;
if (VL_UNLIKELY(level < 0)) level = v3Global.opt.debugSrcLevel(__FILE__);
|
<|file_name|>trace_event_importer.py<|end_file_name|><|fim▁begin|># Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be<|fim▁hole|>
from telemetry import timeline_model
def Import(data):
trace = json.loads(data) # pylint: disable=W0612
model = timeline_model.TimelineModel()
# TODO(nduca): Actually import things.
return model<|fim▁end|>
|
# found in the LICENSE file.
import json
|
<|file_name|>background.js<|end_file_name|><|fim▁begin|>chrome.runtime.onInstalled.addListener(function(details){
if(details.reason == "install"){
console.log("This is a first install!");
}else if(details.reason == "update"){
var thisVersion = chrome.runtime.getManifest().version;
console.log("Updated from " + details.previousVersion + " to " + thisVersion + "!");
}
});
//Redirect from Valve's version of gamehighlightplayer.js to our stub file. We need this to prevent errors.
chrome.webRequest.onBeforeRequest.addListener(
function(details) {
console.log('this ran');
if( details.url.indexOf("gamehighlightplayer.js")>-1){<|fim▁hole|>
},
{urls: ["*://*.steamstatic.com/*"]},
["blocking"]);<|fim▁end|>
|
return {redirectUrl: "chrome-extension://"+chrome.runtime.id+"/js/gamehighlightplayer_stub.js" };
}
|
<|file_name|>test_simple.py<|end_file_name|><|fim▁begin|>#coding: utf-8
import os
import time
from . import test_util
def test_add_file():
test_util.mkfile(1, 'a.md', 'add a file')
test_util.verify_result()
def test_add_file_t():
test_util.mkfile(2, 'l/m/n/test.md', 'add l/m/n/test.md')
test_util.verify_result()
def test_add_dir():
test_util.mkdir(1, 'ad')
test_util.verify_result()
def test_add_dir_t():
test_util.mkdir(2, 'tt/ee/st')
test_util.verify_result()
def test_modify_file():
test_util.modfile(1, 'a.md', 'modify a.md')
test_util.verify_result()
def test_rm_file():
test_util.rmfile(1, 'a.md')
test_util.verify_result()<|fim▁hole|>
def test_rename_file():
test_util.mkfile(2, 'b.md', 'add b.md')
time.sleep(1)
test_util.move(2, 'b.md', 'b_bak.md')
test_util.verify_result()
def test_rename_dir():
test_util.mkdir(2, 'ab')
time.sleep(1)
test_util.move(2, 'ab', 'ab_bak')
test_util.verify_result()
def test_each():
test_util.mkdir(1, 'abc1')
test_util.mkfile(1, 'abc1/c.md', 'add abc1/c.md')
time.sleep(1)
test_util.mkdir(2, 'bcd1')
test_util.mkfile(2, 'bcd1/d.md', 'add bcd1/d.md')
test_util.verify_result()
def test_unsync_resync():
test_util.desync_cli1()
test_util.rmdir(1, 'abc1')
test_util.modfile(1, 'bcd1/d.md', 'modify bcd1/d.md to test unsync resync')
test_util.sync_cli1()
test_util.verify_result()
if not os.path.exists(test_util.getpath(1, 'abc1')):
assert False, 'dir abc1 should be recreated when resync'
if len(os.listdir(test_util.getpath(1, 'bcd1'))) != 2:
assert False, 'should generate conflict file for bcd1/d.md when resync'
def test_modify_timestamp():
test_util.touch(1, 'bcd1/d.md')
test_util.verify_result()<|fim▁end|>
|
def test_rm_dir():
test_util.rmdir(1, 'ad')
test_util.verify_result()
|
<|file_name|>mine.js<|end_file_name|><|fim▁begin|>exports.login = function* (ctx) {
const result = yield ctx.service.mine.login(ctx.request.body);
if (!result) {
ctx.status = 400;
ctx.body = {
status: 400,
msg: `please check your username and password`,
}
return;
}
ctx.body = {
access_token: result.access_token,
msg: 'login success',
};
ctx.status = 200;
}
exports.signup = function* (ctx) {
const result = yield ctx.service.mine.signup(ctx.request.body);
if (!result.result) {
ctx.status = 400;
ctx.body = {
status: 400,
msg: result.msg,
}
return;
}
ctx.status = 201;
ctx.body = {
status: 201,
msg: 'success',
}
}
<|fim▁hole|> ctx.status = 200;
ctx.body = {
status: 200,
msg: 'there is no info for current user',
}
return;
}
ctx.body = info;
ctx.status = 200;
}
exports.statistics = function* (ctx) {
const info = yield ctx.service.mine.statistics(ctx.auth.user_id);
if (info == null) {
ctx.status = 200;
ctx.body = {
shares_count: 0,
friends_count: 0,
helpful_count: 0,
};
return;
}
ctx.body = info;
ctx.status = 200;
}
exports.accounts = function* (ctx) {
const accounts = yield ctx.service.mine.accounts(ctx.auth.user_id);
ctx.body = accounts;
ctx.status = 200;
}
exports.update = function* (ctx) {
let profile = ctx.request.body;
profile.id = ctx.auth.user_id;
const result = yield ctx.service.mine.update(profile);
if (result) {
ctx.status = 204;
return;
}
ctx.status = 500;
ctx.body = {
msg: 'update profile failed',
}
}
exports.avatar = function* (ctx) {
const parts = ctx.multipart();
const { filename, error } = yield ctx.service.mine.avatar(parts, `avatar/${ctx.auth.user_id}`);
if (error) {
ctx.status = 500;
ctx.body = {
status: 500,
msg: 'update avatar failed',
};
return false;
}
ctx.status = 200;
ctx.body = {
filename,
msg: 'success',
}
}<|fim▁end|>
|
exports.info = function* (ctx) {
const info = yield ctx.service.mine.info(ctx.auth.user_id);
if (info == null) {
|
<|file_name|>index.ts<|end_file_name|><|fim▁begin|>import _ from 'lodash';
import path from 'path';
import log from '../log';
import consoleStamp from 'console-stamp';
process.env.NODE_ENV = _.defaultTo(process.env.NODE_ENV, 'development');
const ENV = {
dev: process.env.NODE_ENV === 'development',
prod: process.env.NODE_ENV === 'production',
value: <string>process.env.NODE_ENV,
};
export const HTTP_CODES = {
HTTP_SUCCESS: 200,
HTTP_PERMANENT_REDIRECT: 301,
HTTP_TEMPORARY_REDIRECT: 302,
HTTP_CLIENT_ERROR: 400,
HTTP_INVALID_TOKEN: 401,
HTTP_NOT_AUTHORIZED: 403,
HTTP_NOT_FOUND: 404,
HTTP_SERVER_ERROR: 500,
};
export const redirects = [
{
pattern: '^/example',
to: '/new/example',
status: HTTP_CODES.HTTP_PERMANENT_REDIRECT,
},
];
const configDefaults = {
development: {
ENV,
PORT: '3000',
IP: 'localhost',
logLevel: log.LOG_LEVEL.TRACE,
root: path.resolve(`${__dirname}/../..`),
},
production: {
ENV,
PORT: <string>process.env.PORT,
IP: 'mysite.com',
logLevel: log.LOG_LEVEL.WARN,
root: path.resolve(`${__dirname}/../..`),
},
};
<|fim▁hole|> config = configDefaults.production;
}
consoleStamp(console, { pattern: 'dd/mmm/yyyy:HH:MM:ss o' });
log.setLogLevel(config.logLevel);
export { config };<|fim▁end|>
|
let config = configDefaults.development;
if (ENV.prod) {
|
<|file_name|>Session.py<|end_file_name|><|fim▁begin|>import sys
import logging
import pexpect
class Session(object):
NO_SESSION = 1
SESSION_AVAILABLE = 2
PRIVILEDGE_MODE = 3
CONFIGURATION_MODE = 4
def __init__(self, hostname, username='', password='', enable_username='', enable_password=''):
''' Sets up configuration to be transfered '''
self.hostname = hostname
self.username = username
self.password = password
self.enable_username = enable_username
self.enable_password = enable_password
self.session = None
self.session_state = Session.NO_SESSION
self.session_lf = ''
self.session_prompt = ''
self._login_status = False
self._enable_status = False
def login(self):
''' Attempt to Login to Device '''
if(self._login_status):
return True
COMMAND = "ssh %s@%s" % (self.username, self.hostname)
self.session = pexpect.spawn(COMMAND)
self.session.logfile = open('/var/log/campus_ztp_icx_sshlog', 'w')
i = self.session.expect(['timed out', 'assword:', 'yes/no', 'failed', pexpect.TIMEOUT],
timeout=30)
if i == 0:
print("SSH Connection to '%s' timed out" % self.hostname)
self._login_status = False
return False
if i == 1:
self.session.sendline(self.password)
if i == 2:
self.session.sendline('yes')
self.session.expect('assword:')
self.session.sendline(self.password)
if i == 3:
print("Known key failed to match device key!\r\n")
self._login_status = False
return False
if i == 4:
print("Failed to connect!\r\n")
self._login_status = False
return False
# Should be logged in at this point
i = self.session.expect(['assword:', '>', '#', pexpect.TIMEOUT], timeout=15)
if i == 0:
# incorrect credentials
# TODO: Terminate Login
print("Invalid login username/password for '%s'" % self.hostname)
self._login_status = False
return False
if i == 1:
self.session_state = Session.SESSION_AVAILABLE
if i == 2:
self.session_state = Session.PRIVILEDGE_MODE
if i == 3:
print("Failed to connect!\r\n")
self._login_status = False
return False
self.session_prompt = "%s" % self.session.before.split()[-1]
self._login_status = True
return True
def sendline(self, line):
''' Wrapper function to add LF or not '''
self.session.sendline('%s%s' % (line, self.session_lf))
<|fim▁hole|> if(self._enable_status):
return True
if self.session_state == Session.SESSION_AVAILABLE:
prompt = self.session_prompt
self.sendline('enable')
c = self.session.expect(['assword:', 'Name:', '%s#' % prompt, pexpect.TIMEOUT])
if c == 0:
# is just asking for enable password
self.sendline(self.enable_password)
if c == 1:
# is asking for username and password
self.sendline(self.enable_username)
self.session.expect('assword:')
self.sendline(self.enable_password)
if c == 2:
# there is no enable password
self.session_state = Session.PRIVILEDGE_MODE
self._enable_status = True
return True
if c == 3:
sys.stderr.write("Timeout trying to enter enable mode\r\n")
self._enable_status = False
return False
# double check we are in enable mode
i = self.session.expect(['assword:', 'Name:', '%s>' % prompt, '%s#' % prompt])
if i < 3:
# incorrect credentials
# TODO: Terminate Login
sys.stderr.write("Invalid enable username/password!\r\n")
self._enable_status = False
return False
self.session_state = Session.PRIVILEDGE_MODE
self._enable_status = True
return True
if self.session_state == Session.PRIVILEDGE_MODE:
self._enable_status = True
return True
raise Exception("Trying to enter enable mode while State is not "
"Available or already in priviledge mode")
return False
def enter_configuration_mode(self):
''' enters configuration mode '''
if self.session_state == Session.PRIVILEDGE_MODE:
prompt = "\(config\)#"
sys.stdout.write("Entering Configuration mode on %s\r\n" % self.hostname)
self.sendline('configure terminal')
i = self.session.expect([prompt, pexpect.TIMEOUT], timeout=5)
if i == 0:
self.session_state = Session.CONFIGURATION_MODE
return True
sys.stderr.write("Failed to enter configuration mode")
return False
else:
raise Exception("Attempted to enter configuration mode when device "
"was not in priviledge mode on '%s'" % self.hostname)
def exit_configuration_mode(self):
''' exits configuration mode '''
if self.session_state == Session.CONFIGURATION_MODE:
sys.stdout.write("Exiting Configuration mode on %s\r\n" % self.hostname)
self.sendline('end')
self.session.expect('#')
self.sendline('')
self.session.expect('#')
sys.stdout.write("Exiting Configuration mode successful\r\n")
self.session_state = Session.PRIVILEDGE_MODE
else:
raise Exception("Attempted to exit configuration mode when device "
"was not in configuration mode on '%s'" % self.hostname)
def create_crypto_keys(self, keytype='rsa', modulus=2048):
'''generates ssh keys. keytype can be either rsa or dsa, modules can be 1024 or 2048'''
assert (modulus == 1024 or modulus == 2048)
assert (keytype == 'dsa' or keytype == 'rsa')
if self.session_state == Session.CONFIGURATION_MODE:
sys.stdout.write("Configuring crypto keys on %s\r\n" % self.hostname)
self.sendline('crypto key generate %s modulus %d' % (keytype, modulus))
i = self.session.expect(['zeroize it', 'created', pexpect.TIMEOUT], timeout=120)
if i == 0:
self.sendline('crypto key zeroize rsa')
self.session.expect('deleted')
self.sendline('crypto key generate %s modulus %d' % (keytype, modulus))
j = self.session.expect(['created', pexpect.TIMEOUT], timeout=120)
if j == 0:
self.sendline('')
return True
sys.stderr.write("Timed out creating keys\r\n")
if i == 1:
self.sendline('')
return True
sys.stderr.write("Timed out creating keys\r\n")
return False
else:
raise Exception("Attempted to configuration crypto keys when device "
"was not in configuration mode on '%s'" % self.hostname)
def page_on(self):
if self.session_state == Session.PRIVILEDGE_MODE:
prompt = "%s#" % self.session_prompt
self.sendline('page')
self.session.expect(prompt)
def page_skip(self):
if self.session_state == Session.PRIVILEDGE_MODE:
prompt = "%s#" % self.session_prompt
self.sendline('skip')
self.session.expect(prompt)
def send_line(self, line):
''' Set an arbitrary cli command - output is sent to stdout'''
prompt = "%s#" % self.session_prompt
if self.session_state == Session.CONFIGURATION_MODE:
prompt = r'%s\((.).+\)#' % self.session_prompt
self.sendline(line)
i = 0
# Record any output from the command
output = []
c = self.session.expect([prompt, pexpect.EOF, pexpect.TIMEOUT])
# skip first line, as it's just a repeat of the command
output.append(self.session.before)
return output
def set_hostname(self, hostname):
''' Set Hostname for testing '''
sys.stdout.write("Setting hostname on %s\r\n" % self.hostname)
if self.session_state == Session.CONFIGURATION_MODE:
self.sendline("hostname %s" % hostname)
self.session.expect('#')
return True
else:
raise Exception("Attempted to configuration hostname while device "
"was not in configuration mode on '%s'" % self.hostname)
def upgrade_code_by_tftp(self, tftp_server, filename, towhere):
''' Upgrades code to a location specified by 'towhere' '''
assert(towhere == 'primary' or towhere == 'secondary' or towhere == 'bootrom')
sys.stdout.write("Upgrading %s on %s\r\n" % (towhere, self.hostname))
if self.session_state == Session.PRIVILEDGE_MODE:
self.session.sendline('copy tftp flash %s %s %s' % (tftp_server, filename, towhere))
self.session.sendline('\r\n')
i = self.session.expect(['Done.', 'Error', 'please wait', pexpect.TIMEOUT],
timeout=300)
if i == 1:
sys.stderr.write("TFTP error occurred trying to update %s code on %s\r\n" %
(towhere, self.hostname))
return False
if i == 2:
sys.stderr.write("Flash is busy during %s code upgrade on %s\r\n" %
(towhere, self.hostname))
return False
if i == 3:
sys.stderr.write("Timeout trying to update %s code on %s\r\n" %
(towhere, self.hostname))
return False
sys.stdout.write("Upgrade of %s code successful on %s\r\n" % (towhere, self.hostname))
return True
raise Exception("Attempted to upgrade %s code while device was "
"not in priviledge mode on '%s'" % (towhere, self.hostname))
return False
def upgrade_bootcode_by_tftp(self, tftp_server, filename):
''' Upgrades boot code '''
return self.upgrade_code_by_tftp(tftp_server, filename, 'bootrom')
def reload(self, writemem=True):
''' reload device '''
logging.debug("Reloading '%s'" % self.hostname)
if self.session_state == Session.PRIVILEDGE_MODE:
if writemem:
self.session.sendline('write memory')
self.session.expect('#')
self.session.sendline('reload')
i = self.session.expect(['\):',pexpect.TIMEOUT],timeout=2)
if i == 1: # FCX FIX
self.session.send('\r\n')
self.session.expect('\):',timeout=2)
self.session.send('y')
i = self.session.expect(['\):', pexpect.EOF],timeout=2)
if i == 0:
self.session.sendline('y')
self.session.sendline('')
self.session.close()
self.session_state = Session.NO_SESSION
else:
logging.warning("Attempted to logout when device was not priviledge "
"mode on '%s'" % self.hostname)
def logout(self):
''' logout of device '''
self.sendline('exit')
self.sendline('exit')
self.session.close()
self.session_state = Session.NO_SESSION
self._login_status = False
self._enable_status = False
return
# Or is this better?
if self.session_state == Session.PRIVILEDGE_MODE:
self.sendline('logout')
self.session.expect(pexpect.EOF)
self.session_state = Session.NO_SESSION
else:
logging.warning("Attempted to logout when device was not priviledge "
"mode on '%s'" % self.hostname)<|fim▁end|>
|
def enter_enable_mode(self):
''' enters enable mode '''
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.