repo_name
stringlengths
6
100
path
stringlengths
4
294
copies
stringlengths
1
5
size
stringlengths
4
6
content
stringlengths
606
896k
license
stringclasses
15 values
rbaindourov/v8-inspector
Source/build/scripts/template_expander.py
64
2836
# Copyright (C) 2013 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 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import os import sys _current_dir = os.path.dirname(os.path.realpath(__file__)) # jinja2 is in chromium's third_party directory # Insert at front to override system libraries, and after path[0] == script dir sys.path.insert(1, os.path.join(_current_dir, *([os.pardir] * 4))) import jinja2 def apply_template(path_to_template, params, filters=None): dirname, basename = os.path.split(path_to_template) path_to_templates = os.path.join(_current_dir, 'templates') jinja_env = jinja2.Environment( loader=jinja2.FileSystemLoader([dirname, path_to_templates]), keep_trailing_newline=True, # newline-terminate generated files lstrip_blocks=True, # so can indent control flow tags trim_blocks=True) # so don't need {%- -%} everywhere if filters: jinja_env.filters.update(filters) template = jinja_env.get_template(basename) return template.render(params) def use_jinja(template_file_name, filters=None): def real_decorator(generator): def generator_internal(*args, **kwargs): parameters = generator(*args, **kwargs) return apply_template(template_file_name, parameters, filters=filters) generator_internal.func_name = generator.func_name return generator_internal return real_decorator
bsd-3-clause
odb9402/OPPA
oppa/Helper/tools.py
1
5111
import os import time import glob import re from ..calculateError import run as calculateError from ..loadParser.parseLabel import run as parseLabel from ..loadParser.loadPeak import run as loadPeak """ These methods are common parts of learning processes which are in learn****param.py. """ def parallel_learning(MAX_CORE, learning_process, learning_processes): """ :param MAX_CORE: :param learning_process: :param learning_processes: :return: """ if len(learning_processes) < MAX_CORE - 1: learning_processes.append(learning_process) learning_process.start() else: keep_wait = True while True: time.sleep(0.1) if not (keep_wait is True): break else: for process in reversed(learning_processes): if process.is_alive() is False: learning_processes.remove(process) learning_processes.append(learning_process) learning_process.start() keep_wait = False break def return_accuracy(final, kry_file, result_file, valid_set): """ :param final: :param kry_file: :param result_file: :param valid_set: :return: """ if not valid_set: print "there are no matched validation set :p\n" exit() else: if not os.path.exists(result_file): return 0.0 peaks = loadPeak(result_file) if kry_file is None: error_num, label_num = calculateError(peaks, parseLabel(valid_set, result_file)) else: error_num, label_num = 0, 0 peaks_by_chr = [] containor = [] for index in range(len(peaks)): if not (index + 1 == len(peaks)): if peaks[index]['chr'] != peaks[index + 1]['chr']: containor.append(peaks[index]) peaks_by_chr.append(containor) containor = [] else: containor.append(peaks[index]) else: peaks_by_chr.append(containor) ## Output for each chromosomes which have the same copy number. for peak_by_chr in peaks_by_chr: if len(peak_by_chr) > 0: chromosome = peak_by_chr[0]['chr'] label = parseLabel(valid_set, result_file,input_chromosome=chromosome\ ,cpNum_file_name=kry_file) print chromosome + " ====================== " temp_error, temp_label = calculateError(peak_by_chr, label) error_num += temp_error label_num += temp_label print "============================\n" if (temp_error is 0) and (temp_label is 0): error_num += label label_num += label if os.path.isfile(result_file) and (not final): os.remove(result_file) elif final: print result_file + " is stored." else: print "there is no result file.." if label_num is 0: return 0.0 if final: print "Test Score ::" + str(1 - error_num / label_num) +"\n\n" return (1 - error_num / label_num) def extract_chr_cpNum(chromosome_list, input_file, control_file, cpNum_controls, cpNum_files, kry_file, test_set, validation_set, PATH, tool_name=None): """ This module extracts chromosome and copy number from a input file name. Also, it makes directories which takes result files. It will be used in start sections of each learning sources ( learn***params.py ) :param PATH: :param chromosome_list: :param control_fil :param cpNum_controls: :param cpNum_files: :param input_file: :param kry_file: :param test_set: :param validation_set: :param tool_name: :return: """ if kry_file is None: for label in validation_set + test_set: chromosome_list.append(label.split(':')[0]) chromosome_list = sorted(list(set(chromosome_list))) for chromosome in chromosome_list: output_dir = PATH + '/'+ tool_name +'/' + chromosome + '/' if not os.path.exists(PATH + '/'+ tool_name +'/' + chromosome): os.makedirs(output_dir) else: cpNum_files = glob.glob(PATH + "/" + input_file.split(".")[0] + ".CP[1-9].bam") cpNum_controls = glob.glob(PATH + "/" + control_file.split(".")[0] + ".CP[1-9].bam") str_cpnum_list = [] for cp in cpNum_files: str_cpnum_list.append(re.search("CP[1-9]", cp).group(0)) for str_cpnum in str_cpnum_list: output_dir = PATH + '/'+ tool_name +'/' + str_cpnum + '/' if not os.path.exists(PATH + '/'+ tool_name +'/' + str_cpnum): os.makedirs(output_dir) return chromosome_list, cpNum_controls, cpNum_files
mit
sahilTakiar/spark
examples/src/main/python/mllib/stratified_sampling_example.py
128
1368
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from __future__ import print_function from pyspark import SparkContext if __name__ == "__main__": sc = SparkContext(appName="StratifiedSamplingExample") # SparkContext # $example on$ # an RDD of any key value pairs data = sc.parallelize([(1, 'a'), (1, 'b'), (2, 'c'), (2, 'd'), (2, 'e'), (3, 'f')]) # specify the exact fraction desired from each key as a dictionary fractions = {1: 0.1, 2: 0.6, 3: 0.3} approxSample = data.sampleByKey(False, fractions) # $example off$ for each in approxSample.collect(): print(each) sc.stop()
apache-2.0
EvanK/ansible
lib/ansible/modules/network/illumos/dladm_linkprop.py
52
7820
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2016, Adam Števko <adam.stevko@gmail.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: dladm_linkprop short_description: Manage link properties on Solaris/illumos systems. description: - Set / reset link properties on Solaris/illumos systems. version_added: "2.3" author: Adam Števko (@xen0l) options: link: description: - Link interface name. required: true aliases: [ "nic", "interface" ] property: description: - Specifies the name of the property we want to manage. required: true aliases: [ "name" ] value: description: - Specifies the value we want to set for the link property. required: false temporary: description: - Specifies that lin property configuration is temporary. Temporary link property configuration does not persist across reboots. required: false type: bool default: false state: description: - Set or reset the property value. required: false default: "present" choices: [ "present", "absent", "reset" ] ''' EXAMPLES = ''' - name: Set 'maxbw' to 100M on e1000g1 dladm_linkprop: name=e1000g1 property=maxbw value=100M state=present - name: Set 'mtu' to 9000 on e1000g1 dladm_linkprop: name=e1000g1 property=mtu value=9000 - name: Reset 'mtu' property on e1000g1 dladm_linkprop: name=e1000g1 property=mtu state=reset ''' RETURN = ''' property: description: property name returned: always type: str sample: mtu state: description: state of the target returned: always type: str sample: present temporary: description: specifies if operation will persist across reboots returned: always type: bool sample: True link: description: link name returned: always type: str sample: e100g0 value: description: property value returned: always type: str sample: 9000 ''' from ansible.module_utils.basic import AnsibleModule class LinkProp(object): def __init__(self, module): self.module = module self.link = module.params['link'] self.property = module.params['property'] self.value = module.params['value'] self.temporary = module.params['temporary'] self.state = module.params['state'] self.dladm_bin = self.module.get_bin_path('dladm', True) def property_exists(self): cmd = [self.dladm_bin] cmd.append('show-linkprop') cmd.append('-p') cmd.append(self.property) cmd.append(self.link) (rc, _, _) = self.module.run_command(cmd) if rc == 0: return True else: self.module.fail_json(msg='Unknown property "%s" on link %s' % (self.property, self.link), property=self.property, link=self.link) def property_is_modified(self): cmd = [self.dladm_bin] cmd.append('show-linkprop') cmd.append('-c') cmd.append('-o') cmd.append('value,default') cmd.append('-p') cmd.append(self.property) cmd.append(self.link) (rc, out, _) = self.module.run_command(cmd) out = out.rstrip() (value, default) = out.split(':') if rc == 0 and value == default: return True else: return False def property_is_readonly(self): cmd = [self.dladm_bin] cmd.append('show-linkprop') cmd.append('-c') cmd.append('-o') cmd.append('perm') cmd.append('-p') cmd.append(self.property) cmd.append(self.link) (rc, out, _) = self.module.run_command(cmd) out = out.rstrip() if rc == 0 and out == 'r-': return True else: return False def property_is_set(self): cmd = [self.dladm_bin] cmd.append('show-linkprop') cmd.append('-c') cmd.append('-o') cmd.append('value') cmd.append('-p') cmd.append(self.property) cmd.append(self.link) (rc, out, _) = self.module.run_command(cmd) out = out.rstrip() if rc == 0 and self.value == out: return True else: return False def set_property(self): cmd = [self.dladm_bin] cmd.append('set-linkprop') if self.temporary: cmd.append('-t') cmd.append('-p') cmd.append(self.property + '=' + self.value) cmd.append(self.link) return self.module.run_command(cmd) def reset_property(self): cmd = [self.dladm_bin] cmd.append('reset-linkprop') if self.temporary: cmd.append('-t') cmd.append('-p') cmd.append(self.property) cmd.append(self.link) return self.module.run_command(cmd) def main(): module = AnsibleModule( argument_spec=dict( link=dict(required=True, default=None, type='str', aliases=['nic', 'interface']), property=dict(required=True, type='str', aliases=['name']), value=dict(required=False, type='str'), temporary=dict(default=False, type='bool'), state=dict( default='present', choices=['absent', 'present', 'reset']), ), required_if=[ ['state', 'present', ['value']], ], supports_check_mode=True ) linkprop = LinkProp(module) rc = None out = '' err = '' result = {} result['property'] = linkprop.property result['link'] = linkprop.link result['state'] = linkprop.state if linkprop.value: result['value'] = linkprop.value if linkprop.state == 'absent' or linkprop.state == 'reset': if linkprop.property_exists(): if not linkprop.property_is_modified(): if module.check_mode: module.exit_json(changed=True) (rc, out, err) = linkprop.reset_property() if rc != 0: module.fail_json(property=linkprop.property, link=linkprop.link, msg=err, rc=rc) elif linkprop.state == 'present': if linkprop.property_exists(): if not linkprop.property_is_readonly(): if not linkprop.property_is_set(): if module.check_mode: module.exit_json(changed=True) (rc, out, err) = linkprop.set_property() if rc != 0: module.fail_json(property=linkprop.property, link=linkprop.link, msg=err, rc=rc) else: module.fail_json(msg='Property "%s" is read-only!' % (linkprop.property), property=linkprop.property, link=linkprop.link) if rc is None: result['changed'] = False else: result['changed'] = True if out: result['stdout'] = out if err: result['stderr'] = err module.exit_json(**result) if __name__ == '__main__': main()
gpl-3.0
tangentlabs/wagtail
wagtail/wagtailforms/views.py
10
4274
import datetime import csv from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.core.exceptions import PermissionDenied from django.http import HttpResponse from django.shortcuts import get_object_or_404, render, redirect from django.utils.encoding import smart_str from django.utils.translation import ugettext as _ from wagtail.wagtailcore.models import Page from wagtail.wagtailforms.models import FormSubmission, get_forms_for_user from wagtail.wagtailforms.forms import SelectDateForm from wagtail.wagtailadmin import messages def index(request): p = request.GET.get("p", 1) form_pages = get_forms_for_user(request.user) paginator = Paginator(form_pages, 20) try: form_pages = paginator.page(p) except PageNotAnInteger: form_pages = paginator.page(1) except EmptyPage: form_pages = paginator.page(paginator.num_pages) return render(request, 'wagtailforms/index.html', { 'form_pages': form_pages, }) def delete_submission(request, page_id, submission_id): if not get_forms_for_user(request.user).filter(id=page_id).exists(): raise PermissionDenied submission = get_object_or_404(FormSubmission, id=submission_id) page = get_object_or_404(Page, id=page_id) if request.method == 'POST': submission.delete() messages.success(request, _("Submission deleted.")) return redirect('wagtailforms:list_submissions', page_id) return render(request, 'wagtailforms/confirm_delete.html', { 'page': page, 'submission': submission }) def list_submissions(request, page_id): form_page = get_object_or_404(Page, id=page_id).specific if not get_forms_for_user(request.user).filter(id=page_id).exists(): raise PermissionDenied data_fields = [ (field.clean_name, field.label) for field in form_page.form_fields.all() ] submissions = FormSubmission.objects.filter(page=form_page) select_date_form = SelectDateForm(request.GET) if select_date_form.is_valid(): date_from = select_date_form.cleaned_data.get('date_from') date_to = select_date_form.cleaned_data.get('date_to') # careful: date_to should be increased by 1 day since the submit_time # is a time so it will always be greater if date_to: date_to += datetime.timedelta(days=1) if date_from and date_to: submissions = submissions.filter(submit_time__range=[date_from, date_to]) elif date_from and not date_to: submissions = submissions.filter(submit_time__gte=date_from) elif not date_from and date_to: submissions = submissions.filter(submit_time__lte=date_to) if request.GET.get('action') == 'CSV': # return a CSV instead response = HttpResponse(content_type='text/csv; charset=utf-8') response['Content-Disposition'] = 'attachment;filename=export.csv' writer = csv.writer(response) header_row = ['Submission date'] + [label for name, label in data_fields] writer.writerow(header_row) for s in submissions: data_row = [s.submit_time] form_data = s.get_data() for name, label in data_fields: data_row.append(smart_str(form_data.get(name))) writer.writerow(data_row) return response p = request.GET.get('p', 1) paginator = Paginator(submissions, 20) try: submissions = paginator.page(p) except PageNotAnInteger: submissions = paginator.page(1) except EmptyPage: submissions = paginator.page(paginator.num_pages) data_headings = [label for name, label in data_fields] data_rows = [] for s in submissions: form_data = s.get_data() data_row = [s.submit_time] + [form_data.get(name) for name, label in data_fields] data_rows.append({ "model_id": s.id, "fields": data_row }) return render(request, 'wagtailforms/index_submissions.html', { 'form_page': form_page, 'select_date_form': select_date_form, 'submissions': submissions, 'data_headings': data_headings, 'data_rows': data_rows })
bsd-3-clause
IronLanguages/ironpython2
Src/StdLib/Lib/site-packages/win32/test/test_pywintypes.py
2
3632
import sys import unittest import pywintypes import time from pywin32_testutil import str2bytes, ob2memory import datetime import operator class TestCase(unittest.TestCase): def testPyTimeFormat(self): struct_current = time.localtime() pytime_current = pywintypes.Time(struct_current) # try and test all the standard parts of the format # Note we used to include '%Z' testing, but that was pretty useless as # it always returned the local timezone. format_strings = "%a %A %b %B %c %d %H %I %j %m %M %p %S %U %w %W %x %X %y %Y" for fmt in format_strings.split(): v1 = pytime_current.Format(fmt) v2 = time.strftime(fmt, struct_current) self.assertEquals(v1, v2, "format %s failed - %r != %r" % (fmt, v1, v2)) def testPyTimePrint(self): # This used to crash with an invalid, or too early time. # We don't really want to check that it does cause a ValueError # (as hopefully this wont be true forever). So either working, or # ValueError is OK. try: t = pywintypes.Time(-2) t.Format() except ValueError: return def testTimeInDict(self): d = {} d['t1'] = pywintypes.Time(1) self.failUnlessEqual(d['t1'], pywintypes.Time(1)) def testPyTimeCompare(self): t1 = pywintypes.Time(100) t1_2 = pywintypes.Time(100) t2 = pywintypes.Time(101) self.failUnlessEqual(t1, t1_2) self.failUnless(t1 <= t1_2) self.failUnless(t1_2 >= t1) self.failIfEqual(t1, t2) self.failUnless(t1 < t2) self.failUnless(t2 > t1 ) def testTimeTuple(self): now = datetime.datetime.now() # has usec... # timetuple() lost usec - pt must be <=... pt = pywintypes.Time(now.timetuple()) # *sob* - only if we have a datetime object can we compare like this. if isinstance(pt, datetime.datetime): self.failUnless(pt <= now) def testTimeTuplems(self): now = datetime.datetime.now() # has usec... tt = now.timetuple() + (now.microsecond // 1000,) pt = pywintypes.Time(tt) # we can't compare if using the old type, as it loses all sub-second res. if isinstance(pt, datetime.datetime): self.failUnlessEqual(now, pt) def testPyTimeFromTime(self): t1 = pywintypes.Time(time.time()) self.failUnless(pywintypes.Time(t1) is t1) def testGUID(self): s = "{00020400-0000-0000-C000-000000000046}" iid = pywintypes.IID(s) iid2 = pywintypes.IID(ob2memory(iid), True) self.assertEquals(iid, iid2) self.assertRaises(ValueError, pywintypes.IID, str2bytes('00'), True) # too short self.assertRaises(TypeError, pywintypes.IID, 0, True) # no buffer def testGUIDRichCmp(self): s = "{00020400-0000-0000-C000-000000000046}" iid = pywintypes.IID(s) self.failIf(s==None) self.failIf(None==s) self.failUnless(s!=None) self.failUnless(None!=s) if sys.version_info > (3,0): self.assertRaises(TypeError, operator.gt, None, s) self.assertRaises(TypeError, operator.gt, s, None) self.assertRaises(TypeError, operator.lt, None, s) self.assertRaises(TypeError, operator.lt, s, None) def testGUIDInDict(self): s = "{00020400-0000-0000-C000-000000000046}" iid = pywintypes.IID(s) d = dict(item=iid) self.failUnlessEqual(d['item'], iid) if __name__ == '__main__': unittest.main()
apache-2.0
DCGM/EmotionService
src/clusterFaces.py
1
5407
#!/usr/bin/env python from __future__ import print_function import time import argparse import cv2 import os from operator import itemgetter from collections import defaultdict from scipy.cluster.hierarchy import linkage, fcluster from scipy.spatial.distance import pdist import numpy as np import caffe from classifySoftmax import Net from classifyStream import createNet def parseArgs(): parser = argparse.ArgumentParser() parser.add_argument('-n', '--net', required=True, help='Caffe net model.') parser.add_argument('--per-track', default=8, type=int, help='Images used per face track.') parser.add_argument('--crop-scale', default=1, type=float, help='Face scale factor of the input facial crops.') parser.add_argument('-i', '--input-list', required=True, help='File produced by processVideo.py') parser.add_argument( '-c', '--cpu', action='store_true', help='Set cpu mode for classification (default gpu mode)') parser.add_argument( '--image-dir', required=True, help='Directory with facial crops produced by processVideo.py.') parser.add_argument( '-o', '--output-file', required=True, help='Output file name.') parser.add_argument( '--layer-extract', required=True, help='Network layer which will be used for identification.') parser.add_argument('-t', '--threshold', required=False, default=0.7, type=float, help='Threshold controlls size of clusters.') return parser.parse_args() def compactDistanceMatrix(distances, identities): uniqeIdentities = np.unique(identities) outputDistances = [] for i, identity in enumerate(uniqeIdentities): outputDistances.append( distances[:, identities == identity].min(axis=1)) distances = np.vstack(outputDistances) outputDistances = [] for i, identity in enumerate(uniqeIdentities): outputDistances.append( distances[:, identities == identity].min(axis=1)) outputDistances = np.vstack(outputDistances) return outputDistances, uniqeIdentities def makeCollage(images): side = int((len(images)) ** 0.5 + 1) res = images[0].shape collage = np.zeros( (side * res[0], side * res[1], res[2]), dtype=images[0].dtype) for pos, image in enumerate(images): p0 = (pos / side) * res[0] p1 = (pos % side) * res[1] print(pos, p0, p1) collage[p0:p0 + res[0], p1:p1 + res[1], :] = image return collage def readDetection(input_list): faces = defaultdict(list) with open(input_list, 'r') as f: for line in f: words = line.split() face = [int(x) for x in words[0:2]] faces[face[1]].append(face) return faces def main(): args = parseArgs() # read detections faces = readDetection(args.input_list) if args.cpu: print("CPU mode set") caffe.set_mode_cpu() else: print("GPU mode set") caffe.set_mode_gpu() net = createNet(args.net, args.crop_scale) net.loadNet(batchSize=args.per_track) dim = net.net.blobs[args.layer_extract].data.reshape(args.per_track, -1).shape[1] trackFeatures = np.zeros((len(faces), dim)).astype(np.float32) allImages = [] # create representations for face tracks for key in faces: face_id = int(key) print('Working on', key) cropList = faces[key] step = max(1, int(len(cropList) / args.per_track + 0.5)) cropList = cropList[step / 2::step] images = [] for cropFrame, cropID in cropList: cropName = 'face_{:06d}_{:04}.jpg'.format(cropFrame, key) cropName = os.path.join(args.image_dir, cropName) img = cv2.imread(cropName) images.append(img) images = images[0:args.per_track] for i in range(args.per_track - len(images)): images.append(images[0]) net.classifyImages(images) trackFeatures[face_id, :] = np.mean( net.net.blobs[args.layer_extract].data.reshape(args.per_track, -1), axis=0) allImages.append(images[args.per_track / 2]) print('Have features. ', trackFeatures.shape) distances = pdist(trackFeatures, 'cosine') Z = linkage(distances, method='complete') print('Max distance: ', trackFeatures.max()) clusterCount = 2 clusters = fcluster(Z, t=args.threshold, criterion='distance') #clusterCount, criterion='maxclust') with open(args.output_file + '.mapping', 'w') as outF: for i in range(len(clusters)): print(i, clusters[i], file=outF) for ID in range(np.unique(clusters).size): try: idx = np.nonzero(clusters == ID + 1)[0].tolist() collage = [allImages[i] for i in idx] collage = makeCollage(collage) cv2.imwrite( '{}_cluster_{:04d}.jpg'.format(args.output_file,ID), collage) #cv2.imshow('cluster {}'.format(ID), collage) #cv2.waitKey(1000) except: pass if __name__ == '__main__': main()
bsd-2-clause
ozzmeister00/mazeGeneration
mazeGame_hard.py
1
6271
''' Hard version of the maze game, which only shows the grid immediately around the player First iteration, moved the logic around after this was first done to support a multiple-difficulties mazeGame ''' import maze import random import time verbDict = {'up':['up','u','north','n'], 'down':['down', 'd', 'south', 's'], 'left':['left', 'l', 'west', 'w'], 'right':['right', 'r', 'east', 'e']} directions = ['up','down','left','right'] def checkDirection(dir, currCell): if dir == 'up' and currCell.up: return True elif dir == 'down' and currCell.down: return True elif dir == 'left' and currCell.left: return True elif dir == 'right' and currCell.right: return True return False def drawGrid(grid, currY, currX, sleepTime = 0.5): ''' Special drawGrid function specific to a 3x3 visible grid of maze super hard-coded, oh god I'm so sorry ''' # top string = '+--' if grid[0][1].down and grid[0][1].visited: string += '+ ' else: string += '+--' string += '+--+\n' string += '|##' if grid[0][1].left and grid[0][1].visited: string += ' ' else: string += '|' if grid[0][1].visited: string += grid[0][1].string else: string += '##' if grid[0][1].right and grid[0][1].visited: string += ' ' else: string += '|' string += '##|\n' # middle for x in range(len(grid[0])): if grid[1][x].down and grid[1][x].visited: string += '+ ' else: string += '+--' string += '+\n' if grid[1][0].visited: if grid[1][0].left: string += ' ' else: string += '|' string += grid[1][0].string else: string += '|##' if grid[1][1].left: string += ' ' else: string += '|' string += '0 ' if grid[1][1].right: string += ' ' else: string += '|' if grid[1][2].visited: string += grid[1][2].string if grid[1][2].right: string += ' ' else: string += '|' else: string += '##|' string += '\n' for x in range(len(grid[0])): if grid[1][x].visited: if grid[1][x].up: string += '+ ' else: string += '+--' else: string += '+--' string += '+\n' # bottom string += '|##' if grid[2][1].left: string += ' ' else: string += '|' if grid[2][1].visited: string += grid[2][1].string else: string += '##' if grid[2][1].right: string += ' ' else: string += '|' string += '##|\n' # bottomest string += '+--' if grid[2][1].up: string += '+ ' else: string += '+--' string += '+--+\n' print(string) testGrid = [] for y in range(3): testGrid.append([]) for x in range(3): testGrid[y].append(maze.Cell(y, x)) currMaze = maze.Maze() currMaze.drawGrid() bail = False counter = 0 while not bail: if currMaze.currLoc[1] == currMaze.width: bail = True if not bail: visibleGrid = [] for y in range(3): visibleGrid.append([]) for x in range(3): visibleGrid[y].append(maze.Cell(y, x)) currMaze.grid[currMaze.currLoc[0]][currMaze.currLoc[1]].visited = True currCell = currMaze.grid[currMaze.currLoc[0]][currMaze.currLoc[1]] visibleGrid[1][1] = currCell top = bottom = currMaze.currLoc[0] left = right = currMaze.currLoc[1] neighbors = [] sampleGrid = currMaze.grid # mark all neighbors as visited for direction in directions: if checkDirection(direction, currCell): neighbor = currMaze.getNeighbor(currCell.location[0], currCell.location[1], direction) if neighbor[0][0] < currMaze.height and neighbor[0][1] < currMaze.width: sampleGrid[neighbor[0][0]][neighbor[0][1]].visited = True if checkDirection('up', currCell): top += 1 visibleGrid[2][1] = sampleGrid[top][currMaze.currLoc[1]] if checkDirection('down', currCell): bottom -= 1 visibleGrid[0][1] = sampleGrid[bottom][currMaze.currLoc[1]] if checkDirection('left', currCell): left -= 1 visibleGrid[1][0] = sampleGrid[currMaze.currLoc[0]][left] if checkDirection('right', currCell): right += 1 if right < currMaze.width: visibleGrid[1][2] = sampleGrid[currMaze.currLoc[0]][right] drawGrid(visibleGrid, 1, 1, sleepTime=.5) ui = input('> ') if 'exit' in ui: bail = True currMaze.grid[currMaze.currLoc[0]][currMaze.currLoc[1]].visited = True currCell = currMaze.grid[currMaze.currLoc[0]][currMaze.currLoc[1]] # up if ui in verbDict['down']: if currCell.up: currMaze.currLoc[0] += 1 # down if ui in verbDict['up']: if currCell.down: currMaze.currLoc[0] -= 1 # left if ui in verbDict['left']: if currCell.left: currMaze.currLoc[1] -= 1 # right if ui in verbDict['right']: if currCell.right: currMaze.currLoc[1] += 1 # mark if ui.split(' ')[0] == 'mark': markString = ui.split(' ')[1] if len(markString) == 1: currMaze.grid[currMaze.currLoc[0]][currMaze.currLoc[1]].string = ' {0}'.format(markString) else: print('You can mark with only one character.') if 'draw' in ui: currMaze.drawGrid() counter += 1 currMaze.drawGrid() print('You completed the maze in {0} steps'.format(counter))
gpl-3.0
tapomayukh/projects_in_python
sandbox_tapo/src/refs/google-python-exercises/copyspecial/solution/copyspecial.py
206
2584
#!/usr/bin/python # Copyright 2010 Google Inc. # Licensed under the Apache License, Version 2.0 # http://www.apache.org/licenses/LICENSE-2.0 # Google's Python Class # http://code.google.com/edu/languages/google-python-class/ import sys import re import os import shutil import commands """Copy Special exercise """ # +++your code here+++ # Write functions and modify main() to call them # LAB(begin solution) def get_special_paths(dirname): """Given a dirname, returns a list of all its special files.""" result = [] paths = os.listdir(dirname) # list of paths in that dir for fname in paths: match = re.search(r'__(\w+)__', fname) if match: result.append(os.path.abspath(os.path.join(dirname, fname))) return result def copy_to(paths, to_dir): """Copy all of the given files to the given dir, creating it if necessary.""" if not os.path.exists(to_dir): os.mkdir(to_dir) for path in paths: fname = os.path.basename(path) shutil.copy(path, os.path.join(to_dir, fname)) # could error out if already exists os.path.exists(): def zip_to(paths, zipfile): """Zip up all of the given files into a new zip file with the given name.""" cmd = 'zip -j ' + zipfile + ' ' + ' '.join(paths) print "Command I'm going to do:" + cmd (status, output) = commands.getstatusoutput(cmd) # If command had a problem (status is non-zero), # print its output to stderr and exit. if status: sys.stderr.write(output) sys.exit(1) # LAB(end solution) def main(): # This basic command line argument parsing code is provided. # Add code to call your functions below. # Make a list of command line arguments, omitting the [0] element # which is the script itself. args = sys.argv[1:] if not args: print "usage: [--todir dir][--tozip zipfile] dir [dir ...]"; sys.exit(1) # todir and tozip are either set from command line # or left as the empty string. # The args array is left just containing the dirs. todir = '' if args[0] == '--todir': todir = args[1] del args[0:2] tozip = '' if args[0] == '--tozip': tozip = args[1] del args[0:2] if len(args) == 0: print "error: must specify one or more dirs" sys.exit(1) # +++your code here+++ # Call your functions # LAB(begin solution) # Gather all the special files paths = [] for dirname in args: paths.extend(get_special_paths(dirname)) if todir: copy_to(paths, todir) elif tozip: zip_to(paths, tozip) else: print '\n'.join(paths) # LAB(end solution) if __name__ == "__main__": main()
mit
xxhank/namebench
nb_third_party/dns/rdtypes/ANY/RP.py
248
3275
# Copyright (C) 2003-2007, 2009, 2010 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. import dns.exception import dns.rdata import dns.name class RP(dns.rdata.Rdata): """RP record @ivar mbox: The responsible person's mailbox @type mbox: dns.name.Name object @ivar txt: The owner name of a node with TXT records, or the root name if no TXT records are associated with this RP. @type txt: dns.name.Name object @see: RFC 1183""" __slots__ = ['mbox', 'txt'] def __init__(self, rdclass, rdtype, mbox, txt): super(RP, self).__init__(rdclass, rdtype) self.mbox = mbox self.txt = txt def to_text(self, origin=None, relativize=True, **kw): mbox = self.mbox.choose_relativity(origin, relativize) txt = self.txt.choose_relativity(origin, relativize) return "%s %s" % (str(mbox), str(txt)) def from_text(cls, rdclass, rdtype, tok, origin = None, relativize = True): mbox = tok.get_name() txt = tok.get_name() mbox = mbox.choose_relativity(origin, relativize) txt = txt.choose_relativity(origin, relativize) tok.get_eol() return cls(rdclass, rdtype, mbox, txt) from_text = classmethod(from_text) def to_wire(self, file, compress = None, origin = None): self.mbox.to_wire(file, None, origin) self.txt.to_wire(file, None, origin) def to_digestable(self, origin = None): return self.mbox.to_digestable(origin) + \ self.txt.to_digestable(origin) def from_wire(cls, rdclass, rdtype, wire, current, rdlen, origin = None): (mbox, cused) = dns.name.from_wire(wire[: current + rdlen], current) current += cused rdlen -= cused if rdlen <= 0: raise dns.exception.FormError (txt, cused) = dns.name.from_wire(wire[: current + rdlen], current) if cused != rdlen: raise dns.exception.FormError if not origin is None: mbox = mbox.relativize(origin) txt = txt.relativize(origin) return cls(rdclass, rdtype, mbox, txt) from_wire = classmethod(from_wire) def choose_relativity(self, origin = None, relativize = True): self.mbox = self.mbox.choose_relativity(origin, relativize) self.txt = self.txt.choose_relativity(origin, relativize) def _cmp(self, other): v = cmp(self.mbox, other.mbox) if v == 0: v = cmp(self.txt, other.txt) return v
apache-2.0
ryfeus/lambda-packs
Pdf_docx_pptx_xlsx_epub_png/source/pip/_vendor/requests/packages/chardet/big5freq.py
3133
82594
######################## BEGIN LICENSE BLOCK ######################## # The Original Code is Mozilla Communicator client code. # # The Initial Developer of the Original Code is # Netscape Communications Corporation. # Portions created by the Initial Developer are Copyright (C) 1998 # the Initial Developer. All Rights Reserved. # # Contributor(s): # Mark Pilgrim - port to Python # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA # 02110-1301 USA ######################### END LICENSE BLOCK ######################### # Big5 frequency table # by Taiwan's Mandarin Promotion Council # <http://www.edu.tw:81/mandr/> # # 128 --> 0.42261 # 256 --> 0.57851 # 512 --> 0.74851 # 1024 --> 0.89384 # 2048 --> 0.97583 # # Ideal Distribution Ratio = 0.74851/(1-0.74851) =2.98 # Random Distribution Ration = 512/(5401-512)=0.105 # # Typical Distribution Ratio about 25% of Ideal one, still much higher than RDR BIG5_TYPICAL_DISTRIBUTION_RATIO = 0.75 #Char to FreqOrder table BIG5_TABLE_SIZE = 5376 Big5CharToFreqOrder = ( 1,1801,1506, 255,1431, 198, 9, 82, 6,5008, 177, 202,3681,1256,2821, 110, # 16 3814, 33,3274, 261, 76, 44,2114, 16,2946,2187,1176, 659,3971, 26,3451,2653, # 32 1198,3972,3350,4202, 410,2215, 302, 590, 361,1964, 8, 204, 58,4510,5009,1932, # 48 63,5010,5011, 317,1614, 75, 222, 159,4203,2417,1480,5012,3555,3091, 224,2822, # 64 3682, 3, 10,3973,1471, 29,2787,1135,2866,1940, 873, 130,3275,1123, 312,5013, # 80 4511,2052, 507, 252, 682,5014, 142,1915, 124, 206,2947, 34,3556,3204, 64, 604, # 96 5015,2501,1977,1978, 155,1991, 645, 641,1606,5016,3452, 337, 72, 406,5017, 80, # 112 630, 238,3205,1509, 263, 939,1092,2654, 756,1440,1094,3453, 449, 69,2987, 591, # 128 179,2096, 471, 115,2035,1844, 60, 50,2988, 134, 806,1869, 734,2036,3454, 180, # 144 995,1607, 156, 537,2907, 688,5018, 319,1305, 779,2145, 514,2379, 298,4512, 359, # 160 2502, 90,2716,1338, 663, 11, 906,1099,2553, 20,2441, 182, 532,1716,5019, 732, # 176 1376,4204,1311,1420,3206, 25,2317,1056, 113, 399, 382,1950, 242,3455,2474, 529, # 192 3276, 475,1447,3683,5020, 117, 21, 656, 810,1297,2300,2334,3557,5021, 126,4205, # 208 706, 456, 150, 613,4513, 71,1118,2037,4206, 145,3092, 85, 835, 486,2115,1246, # 224 1426, 428, 727,1285,1015, 800, 106, 623, 303,1281,5022,2128,2359, 347,3815, 221, # 240 3558,3135,5023,1956,1153,4207, 83, 296,1199,3093, 192, 624, 93,5024, 822,1898, # 256 2823,3136, 795,2065, 991,1554,1542,1592, 27, 43,2867, 859, 139,1456, 860,4514, # 272 437, 712,3974, 164,2397,3137, 695, 211,3037,2097, 195,3975,1608,3559,3560,3684, # 288 3976, 234, 811,2989,2098,3977,2233,1441,3561,1615,2380, 668,2077,1638, 305, 228, # 304 1664,4515, 467, 415,5025, 262,2099,1593, 239, 108, 300, 200,1033, 512,1247,2078, # 320 5026,5027,2176,3207,3685,2682, 593, 845,1062,3277, 88,1723,2038,3978,1951, 212, # 336 266, 152, 149, 468,1899,4208,4516, 77, 187,5028,3038, 37, 5,2990,5029,3979, # 352 5030,5031, 39,2524,4517,2908,3208,2079, 55, 148, 74,4518, 545, 483,1474,1029, # 368 1665, 217,1870,1531,3138,1104,2655,4209, 24, 172,3562, 900,3980,3563,3564,4519, # 384 32,1408,2824,1312, 329, 487,2360,2251,2717, 784,2683, 4,3039,3351,1427,1789, # 400 188, 109, 499,5032,3686,1717,1790, 888,1217,3040,4520,5033,3565,5034,3352,1520, # 416 3687,3981, 196,1034, 775,5035,5036, 929,1816, 249, 439, 38,5037,1063,5038, 794, # 432 3982,1435,2301, 46, 178,3278,2066,5039,2381,5040, 214,1709,4521, 804, 35, 707, # 448 324,3688,1601,2554, 140, 459,4210,5041,5042,1365, 839, 272, 978,2262,2580,3456, # 464 2129,1363,3689,1423, 697, 100,3094, 48, 70,1231, 495,3139,2196,5043,1294,5044, # 480 2080, 462, 586,1042,3279, 853, 256, 988, 185,2382,3457,1698, 434,1084,5045,3458, # 496 314,2625,2788,4522,2335,2336, 569,2285, 637,1817,2525, 757,1162,1879,1616,3459, # 512 287,1577,2116, 768,4523,1671,2868,3566,2526,1321,3816, 909,2418,5046,4211, 933, # 528 3817,4212,2053,2361,1222,4524, 765,2419,1322, 786,4525,5047,1920,1462,1677,2909, # 544 1699,5048,4526,1424,2442,3140,3690,2600,3353,1775,1941,3460,3983,4213, 309,1369, # 560 1130,2825, 364,2234,1653,1299,3984,3567,3985,3986,2656, 525,1085,3041, 902,2001, # 576 1475, 964,4527, 421,1845,1415,1057,2286, 940,1364,3141, 376,4528,4529,1381, 7, # 592 2527, 983,2383, 336,1710,2684,1846, 321,3461, 559,1131,3042,2752,1809,1132,1313, # 608 265,1481,1858,5049, 352,1203,2826,3280, 167,1089, 420,2827, 776, 792,1724,3568, # 624 4214,2443,3281,5050,4215,5051, 446, 229, 333,2753, 901,3818,1200,1557,4530,2657, # 640 1921, 395,2754,2685,3819,4216,1836, 125, 916,3209,2626,4531,5052,5053,3820,5054, # 656 5055,5056,4532,3142,3691,1133,2555,1757,3462,1510,2318,1409,3569,5057,2146, 438, # 672 2601,2910,2384,3354,1068, 958,3043, 461, 311,2869,2686,4217,1916,3210,4218,1979, # 688 383, 750,2755,2627,4219, 274, 539, 385,1278,1442,5058,1154,1965, 384, 561, 210, # 704 98,1295,2556,3570,5059,1711,2420,1482,3463,3987,2911,1257, 129,5060,3821, 642, # 720 523,2789,2790,2658,5061, 141,2235,1333, 68, 176, 441, 876, 907,4220, 603,2602, # 736 710, 171,3464, 404, 549, 18,3143,2398,1410,3692,1666,5062,3571,4533,2912,4534, # 752 5063,2991, 368,5064, 146, 366, 99, 871,3693,1543, 748, 807,1586,1185, 22,2263, # 768 379,3822,3211,5065,3212, 505,1942,2628,1992,1382,2319,5066, 380,2362, 218, 702, # 784 1818,1248,3465,3044,3572,3355,3282,5067,2992,3694, 930,3283,3823,5068, 59,5069, # 800 585, 601,4221, 497,3466,1112,1314,4535,1802,5070,1223,1472,2177,5071, 749,1837, # 816 690,1900,3824,1773,3988,1476, 429,1043,1791,2236,2117, 917,4222, 447,1086,1629, # 832 5072, 556,5073,5074,2021,1654, 844,1090, 105, 550, 966,1758,2828,1008,1783, 686, # 848 1095,5075,2287, 793,1602,5076,3573,2603,4536,4223,2948,2302,4537,3825, 980,2503, # 864 544, 353, 527,4538, 908,2687,2913,5077, 381,2629,1943,1348,5078,1341,1252, 560, # 880 3095,5079,3467,2870,5080,2054, 973, 886,2081, 143,4539,5081,5082, 157,3989, 496, # 896 4224, 57, 840, 540,2039,4540,4541,3468,2118,1445, 970,2264,1748,1966,2082,4225, # 912 3144,1234,1776,3284,2829,3695, 773,1206,2130,1066,2040,1326,3990,1738,1725,4226, # 928 279,3145, 51,1544,2604, 423,1578,2131,2067, 173,4542,1880,5083,5084,1583, 264, # 944 610,3696,4543,2444, 280, 154,5085,5086,5087,1739, 338,1282,3096, 693,2871,1411, # 960 1074,3826,2445,5088,4544,5089,5090,1240, 952,2399,5091,2914,1538,2688, 685,1483, # 976 4227,2475,1436, 953,4228,2055,4545, 671,2400, 79,4229,2446,3285, 608, 567,2689, # 992 3469,4230,4231,1691, 393,1261,1792,2401,5092,4546,5093,5094,5095,5096,1383,1672, # 1008 3827,3213,1464, 522,1119, 661,1150, 216, 675,4547,3991,1432,3574, 609,4548,2690, # 1024 2402,5097,5098,5099,4232,3045, 0,5100,2476, 315, 231,2447, 301,3356,4549,2385, # 1040 5101, 233,4233,3697,1819,4550,4551,5102, 96,1777,1315,2083,5103, 257,5104,1810, # 1056 3698,2718,1139,1820,4234,2022,1124,2164,2791,1778,2659,5105,3097, 363,1655,3214, # 1072 5106,2993,5107,5108,5109,3992,1567,3993, 718, 103,3215, 849,1443, 341,3357,2949, # 1088 1484,5110,1712, 127, 67, 339,4235,2403, 679,1412, 821,5111,5112, 834, 738, 351, # 1104 2994,2147, 846, 235,1497,1881, 418,1993,3828,2719, 186,1100,2148,2756,3575,1545, # 1120 1355,2950,2872,1377, 583,3994,4236,2581,2995,5113,1298,3699,1078,2557,3700,2363, # 1136 78,3829,3830, 267,1289,2100,2002,1594,4237, 348, 369,1274,2197,2178,1838,4552, # 1152 1821,2830,3701,2757,2288,2003,4553,2951,2758, 144,3358, 882,4554,3995,2759,3470, # 1168 4555,2915,5114,4238,1726, 320,5115,3996,3046, 788,2996,5116,2831,1774,1327,2873, # 1184 3997,2832,5117,1306,4556,2004,1700,3831,3576,2364,2660, 787,2023, 506, 824,3702, # 1200 534, 323,4557,1044,3359,2024,1901, 946,3471,5118,1779,1500,1678,5119,1882,4558, # 1216 165, 243,4559,3703,2528, 123, 683,4239, 764,4560, 36,3998,1793, 589,2916, 816, # 1232 626,1667,3047,2237,1639,1555,1622,3832,3999,5120,4000,2874,1370,1228,1933, 891, # 1248 2084,2917, 304,4240,5121, 292,2997,2720,3577, 691,2101,4241,1115,4561, 118, 662, # 1264 5122, 611,1156, 854,2386,1316,2875, 2, 386, 515,2918,5123,5124,3286, 868,2238, # 1280 1486, 855,2661, 785,2216,3048,5125,1040,3216,3578,5126,3146, 448,5127,1525,5128, # 1296 2165,4562,5129,3833,5130,4242,2833,3579,3147, 503, 818,4001,3148,1568, 814, 676, # 1312 1444, 306,1749,5131,3834,1416,1030, 197,1428, 805,2834,1501,4563,5132,5133,5134, # 1328 1994,5135,4564,5136,5137,2198, 13,2792,3704,2998,3149,1229,1917,5138,3835,2132, # 1344 5139,4243,4565,2404,3580,5140,2217,1511,1727,1120,5141,5142, 646,3836,2448, 307, # 1360 5143,5144,1595,3217,5145,5146,5147,3705,1113,1356,4002,1465,2529,2530,5148, 519, # 1376 5149, 128,2133, 92,2289,1980,5150,4003,1512, 342,3150,2199,5151,2793,2218,1981, # 1392 3360,4244, 290,1656,1317, 789, 827,2365,5152,3837,4566, 562, 581,4004,5153, 401, # 1408 4567,2252, 94,4568,5154,1399,2794,5155,1463,2025,4569,3218,1944,5156, 828,1105, # 1424 4245,1262,1394,5157,4246, 605,4570,5158,1784,2876,5159,2835, 819,2102, 578,2200, # 1440 2952,5160,1502, 436,3287,4247,3288,2836,4005,2919,3472,3473,5161,2721,2320,5162, # 1456 5163,2337,2068, 23,4571, 193, 826,3838,2103, 699,1630,4248,3098, 390,1794,1064, # 1472 3581,5164,1579,3099,3100,1400,5165,4249,1839,1640,2877,5166,4572,4573, 137,4250, # 1488 598,3101,1967, 780, 104, 974,2953,5167, 278, 899, 253, 402, 572, 504, 493,1339, # 1504 5168,4006,1275,4574,2582,2558,5169,3706,3049,3102,2253, 565,1334,2722, 863, 41, # 1520 5170,5171,4575,5172,1657,2338, 19, 463,2760,4251, 606,5173,2999,3289,1087,2085, # 1536 1323,2662,3000,5174,1631,1623,1750,4252,2691,5175,2878, 791,2723,2663,2339, 232, # 1552 2421,5176,3001,1498,5177,2664,2630, 755,1366,3707,3290,3151,2026,1609, 119,1918, # 1568 3474, 862,1026,4253,5178,4007,3839,4576,4008,4577,2265,1952,2477,5179,1125, 817, # 1584 4254,4255,4009,1513,1766,2041,1487,4256,3050,3291,2837,3840,3152,5180,5181,1507, # 1600 5182,2692, 733, 40,1632,1106,2879, 345,4257, 841,2531, 230,4578,3002,1847,3292, # 1616 3475,5183,1263, 986,3476,5184, 735, 879, 254,1137, 857, 622,1300,1180,1388,1562, # 1632 4010,4011,2954, 967,2761,2665,1349, 592,2134,1692,3361,3003,1995,4258,1679,4012, # 1648 1902,2188,5185, 739,3708,2724,1296,1290,5186,4259,2201,2202,1922,1563,2605,2559, # 1664 1871,2762,3004,5187, 435,5188, 343,1108, 596, 17,1751,4579,2239,3477,3709,5189, # 1680 4580, 294,3582,2955,1693, 477, 979, 281,2042,3583, 643,2043,3710,2631,2795,2266, # 1696 1031,2340,2135,2303,3584,4581, 367,1249,2560,5190,3585,5191,4582,1283,3362,2005, # 1712 240,1762,3363,4583,4584, 836,1069,3153, 474,5192,2149,2532, 268,3586,5193,3219, # 1728 1521,1284,5194,1658,1546,4260,5195,3587,3588,5196,4261,3364,2693,1685,4262, 961, # 1744 1673,2632, 190,2006,2203,3841,4585,4586,5197, 570,2504,3711,1490,5198,4587,2633, # 1760 3293,1957,4588, 584,1514, 396,1045,1945,5199,4589,1968,2449,5200,5201,4590,4013, # 1776 619,5202,3154,3294, 215,2007,2796,2561,3220,4591,3221,4592, 763,4263,3842,4593, # 1792 5203,5204,1958,1767,2956,3365,3712,1174, 452,1477,4594,3366,3155,5205,2838,1253, # 1808 2387,2189,1091,2290,4264, 492,5206, 638,1169,1825,2136,1752,4014, 648, 926,1021, # 1824 1324,4595, 520,4596, 997, 847,1007, 892,4597,3843,2267,1872,3713,2405,1785,4598, # 1840 1953,2957,3103,3222,1728,4265,2044,3714,4599,2008,1701,3156,1551, 30,2268,4266, # 1856 5207,2027,4600,3589,5208, 501,5209,4267, 594,3478,2166,1822,3590,3479,3591,3223, # 1872 829,2839,4268,5210,1680,3157,1225,4269,5211,3295,4601,4270,3158,2341,5212,4602, # 1888 4271,5213,4015,4016,5214,1848,2388,2606,3367,5215,4603, 374,4017, 652,4272,4273, # 1904 375,1140, 798,5216,5217,5218,2366,4604,2269, 546,1659, 138,3051,2450,4605,5219, # 1920 2254, 612,1849, 910, 796,3844,1740,1371, 825,3845,3846,5220,2920,2562,5221, 692, # 1936 444,3052,2634, 801,4606,4274,5222,1491, 244,1053,3053,4275,4276, 340,5223,4018, # 1952 1041,3005, 293,1168, 87,1357,5224,1539, 959,5225,2240, 721, 694,4277,3847, 219, # 1968 1478, 644,1417,3368,2666,1413,1401,1335,1389,4019,5226,5227,3006,2367,3159,1826, # 1984 730,1515, 184,2840, 66,4607,5228,1660,2958, 246,3369, 378,1457, 226,3480, 975, # 2000 4020,2959,1264,3592, 674, 696,5229, 163,5230,1141,2422,2167, 713,3593,3370,4608, # 2016 4021,5231,5232,1186, 15,5233,1079,1070,5234,1522,3224,3594, 276,1050,2725, 758, # 2032 1126, 653,2960,3296,5235,2342, 889,3595,4022,3104,3007, 903,1250,4609,4023,3481, # 2048 3596,1342,1681,1718, 766,3297, 286, 89,2961,3715,5236,1713,5237,2607,3371,3008, # 2064 5238,2962,2219,3225,2880,5239,4610,2505,2533, 181, 387,1075,4024, 731,2190,3372, # 2080 5240,3298, 310, 313,3482,2304, 770,4278, 54,3054, 189,4611,3105,3848,4025,5241, # 2096 1230,1617,1850, 355,3597,4279,4612,3373, 111,4280,3716,1350,3160,3483,3055,4281, # 2112 2150,3299,3598,5242,2797,4026,4027,3009, 722,2009,5243,1071, 247,1207,2343,2478, # 2128 1378,4613,2010, 864,1437,1214,4614, 373,3849,1142,2220, 667,4615, 442,2763,2563, # 2144 3850,4028,1969,4282,3300,1840, 837, 170,1107, 934,1336,1883,5244,5245,2119,4283, # 2160 2841, 743,1569,5246,4616,4284, 582,2389,1418,3484,5247,1803,5248, 357,1395,1729, # 2176 3717,3301,2423,1564,2241,5249,3106,3851,1633,4617,1114,2086,4285,1532,5250, 482, # 2192 2451,4618,5251,5252,1492, 833,1466,5253,2726,3599,1641,2842,5254,1526,1272,3718, # 2208 4286,1686,1795, 416,2564,1903,1954,1804,5255,3852,2798,3853,1159,2321,5256,2881, # 2224 4619,1610,1584,3056,2424,2764, 443,3302,1163,3161,5257,5258,4029,5259,4287,2506, # 2240 3057,4620,4030,3162,2104,1647,3600,2011,1873,4288,5260,4289, 431,3485,5261, 250, # 2256 97, 81,4290,5262,1648,1851,1558, 160, 848,5263, 866, 740,1694,5264,2204,2843, # 2272 3226,4291,4621,3719,1687, 950,2479, 426, 469,3227,3720,3721,4031,5265,5266,1188, # 2288 424,1996, 861,3601,4292,3854,2205,2694, 168,1235,3602,4293,5267,2087,1674,4622, # 2304 3374,3303, 220,2565,1009,5268,3855, 670,3010, 332,1208, 717,5269,5270,3603,2452, # 2320 4032,3375,5271, 513,5272,1209,2882,3376,3163,4623,1080,5273,5274,5275,5276,2534, # 2336 3722,3604, 815,1587,4033,4034,5277,3605,3486,3856,1254,4624,1328,3058,1390,4035, # 2352 1741,4036,3857,4037,5278, 236,3858,2453,3304,5279,5280,3723,3859,1273,3860,4625, # 2368 5281, 308,5282,4626, 245,4627,1852,2480,1307,2583, 430, 715,2137,2454,5283, 270, # 2384 199,2883,4038,5284,3606,2727,1753, 761,1754, 725,1661,1841,4628,3487,3724,5285, # 2400 5286, 587, 14,3305, 227,2608, 326, 480,2270, 943,2765,3607, 291, 650,1884,5287, # 2416 1702,1226, 102,1547, 62,3488, 904,4629,3489,1164,4294,5288,5289,1224,1548,2766, # 2432 391, 498,1493,5290,1386,1419,5291,2056,1177,4630, 813, 880,1081,2368, 566,1145, # 2448 4631,2291,1001,1035,2566,2609,2242, 394,1286,5292,5293,2069,5294, 86,1494,1730, # 2464 4039, 491,1588, 745, 897,2963, 843,3377,4040,2767,2884,3306,1768, 998,2221,2070, # 2480 397,1827,1195,1970,3725,3011,3378, 284,5295,3861,2507,2138,2120,1904,5296,4041, # 2496 2151,4042,4295,1036,3490,1905, 114,2567,4296, 209,1527,5297,5298,2964,2844,2635, # 2512 2390,2728,3164, 812,2568,5299,3307,5300,1559, 737,1885,3726,1210, 885, 28,2695, # 2528 3608,3862,5301,4297,1004,1780,4632,5302, 346,1982,2222,2696,4633,3863,1742, 797, # 2544 1642,4043,1934,1072,1384,2152, 896,4044,3308,3727,3228,2885,3609,5303,2569,1959, # 2560 4634,2455,1786,5304,5305,5306,4045,4298,1005,1308,3728,4299,2729,4635,4636,1528, # 2576 2610, 161,1178,4300,1983, 987,4637,1101,4301, 631,4046,1157,3229,2425,1343,1241, # 2592 1016,2243,2570, 372, 877,2344,2508,1160, 555,1935, 911,4047,5307, 466,1170, 169, # 2608 1051,2921,2697,3729,2481,3012,1182,2012,2571,1251,2636,5308, 992,2345,3491,1540, # 2624 2730,1201,2071,2406,1997,2482,5309,4638, 528,1923,2191,1503,1874,1570,2369,3379, # 2640 3309,5310, 557,1073,5311,1828,3492,2088,2271,3165,3059,3107, 767,3108,2799,4639, # 2656 1006,4302,4640,2346,1267,2179,3730,3230, 778,4048,3231,2731,1597,2667,5312,4641, # 2672 5313,3493,5314,5315,5316,3310,2698,1433,3311, 131, 95,1504,4049, 723,4303,3166, # 2688 1842,3610,2768,2192,4050,2028,2105,3731,5317,3013,4051,1218,5318,3380,3232,4052, # 2704 4304,2584, 248,1634,3864, 912,5319,2845,3732,3060,3865, 654, 53,5320,3014,5321, # 2720 1688,4642, 777,3494,1032,4053,1425,5322, 191, 820,2121,2846, 971,4643, 931,3233, # 2736 135, 664, 783,3866,1998, 772,2922,1936,4054,3867,4644,2923,3234, 282,2732, 640, # 2752 1372,3495,1127, 922, 325,3381,5323,5324, 711,2045,5325,5326,4055,2223,2800,1937, # 2768 4056,3382,2224,2255,3868,2305,5327,4645,3869,1258,3312,4057,3235,2139,2965,4058, # 2784 4059,5328,2225, 258,3236,4646, 101,1227,5329,3313,1755,5330,1391,3314,5331,2924, # 2800 2057, 893,5332,5333,5334,1402,4305,2347,5335,5336,3237,3611,5337,5338, 878,1325, # 2816 1781,2801,4647, 259,1385,2585, 744,1183,2272,4648,5339,4060,2509,5340, 684,1024, # 2832 4306,5341, 472,3612,3496,1165,3315,4061,4062, 322,2153, 881, 455,1695,1152,1340, # 2848 660, 554,2154,4649,1058,4650,4307, 830,1065,3383,4063,4651,1924,5342,1703,1919, # 2864 5343, 932,2273, 122,5344,4652, 947, 677,5345,3870,2637, 297,1906,1925,2274,4653, # 2880 2322,3316,5346,5347,4308,5348,4309, 84,4310, 112, 989,5349, 547,1059,4064, 701, # 2896 3613,1019,5350,4311,5351,3497, 942, 639, 457,2306,2456, 993,2966, 407, 851, 494, # 2912 4654,3384, 927,5352,1237,5353,2426,3385, 573,4312, 680, 921,2925,1279,1875, 285, # 2928 790,1448,1984, 719,2168,5354,5355,4655,4065,4066,1649,5356,1541, 563,5357,1077, # 2944 5358,3386,3061,3498, 511,3015,4067,4068,3733,4069,1268,2572,3387,3238,4656,4657, # 2960 5359, 535,1048,1276,1189,2926,2029,3167,1438,1373,2847,2967,1134,2013,5360,4313, # 2976 1238,2586,3109,1259,5361, 700,5362,2968,3168,3734,4314,5363,4315,1146,1876,1907, # 2992 4658,2611,4070, 781,2427, 132,1589, 203, 147, 273,2802,2407, 898,1787,2155,4071, # 3008 4072,5364,3871,2803,5365,5366,4659,4660,5367,3239,5368,1635,3872, 965,5369,1805, # 3024 2699,1516,3614,1121,1082,1329,3317,4073,1449,3873, 65,1128,2848,2927,2769,1590, # 3040 3874,5370,5371, 12,2668, 45, 976,2587,3169,4661, 517,2535,1013,1037,3240,5372, # 3056 3875,2849,5373,3876,5374,3499,5375,2612, 614,1999,2323,3877,3110,2733,2638,5376, # 3072 2588,4316, 599,1269,5377,1811,3735,5378,2700,3111, 759,1060, 489,1806,3388,3318, # 3088 1358,5379,5380,2391,1387,1215,2639,2256, 490,5381,5382,4317,1759,2392,2348,5383, # 3104 4662,3878,1908,4074,2640,1807,3241,4663,3500,3319,2770,2349, 874,5384,5385,3501, # 3120 3736,1859, 91,2928,3737,3062,3879,4664,5386,3170,4075,2669,5387,3502,1202,1403, # 3136 3880,2969,2536,1517,2510,4665,3503,2511,5388,4666,5389,2701,1886,1495,1731,4076, # 3152 2370,4667,5390,2030,5391,5392,4077,2702,1216, 237,2589,4318,2324,4078,3881,4668, # 3168 4669,2703,3615,3504, 445,4670,5393,5394,5395,5396,2771, 61,4079,3738,1823,4080, # 3184 5397, 687,2046, 935, 925, 405,2670, 703,1096,1860,2734,4671,4081,1877,1367,2704, # 3200 3389, 918,2106,1782,2483, 334,3320,1611,1093,4672, 564,3171,3505,3739,3390, 945, # 3216 2641,2058,4673,5398,1926, 872,4319,5399,3506,2705,3112, 349,4320,3740,4082,4674, # 3232 3882,4321,3741,2156,4083,4675,4676,4322,4677,2408,2047, 782,4084, 400, 251,4323, # 3248 1624,5400,5401, 277,3742, 299,1265, 476,1191,3883,2122,4324,4325,1109, 205,5402, # 3264 2590,1000,2157,3616,1861,5403,5404,5405,4678,5406,4679,2573, 107,2484,2158,4085, # 3280 3507,3172,5407,1533, 541,1301, 158, 753,4326,2886,3617,5408,1696, 370,1088,4327, # 3296 4680,3618, 579, 327, 440, 162,2244, 269,1938,1374,3508, 968,3063, 56,1396,3113, # 3312 2107,3321,3391,5409,1927,2159,4681,3016,5410,3619,5411,5412,3743,4682,2485,5413, # 3328 2804,5414,1650,4683,5415,2613,5416,5417,4086,2671,3392,1149,3393,4087,3884,4088, # 3344 5418,1076, 49,5419, 951,3242,3322,3323, 450,2850, 920,5420,1812,2805,2371,4328, # 3360 1909,1138,2372,3885,3509,5421,3243,4684,1910,1147,1518,2428,4685,3886,5422,4686, # 3376 2393,2614, 260,1796,3244,5423,5424,3887,3324, 708,5425,3620,1704,5426,3621,1351, # 3392 1618,3394,3017,1887, 944,4329,3395,4330,3064,3396,4331,5427,3744, 422, 413,1714, # 3408 3325, 500,2059,2350,4332,2486,5428,1344,1911, 954,5429,1668,5430,5431,4089,2409, # 3424 4333,3622,3888,4334,5432,2307,1318,2512,3114, 133,3115,2887,4687, 629, 31,2851, # 3440 2706,3889,4688, 850, 949,4689,4090,2970,1732,2089,4335,1496,1853,5433,4091, 620, # 3456 3245, 981,1242,3745,3397,1619,3746,1643,3326,2140,2457,1971,1719,3510,2169,5434, # 3472 3246,5435,5436,3398,1829,5437,1277,4690,1565,2048,5438,1636,3623,3116,5439, 869, # 3488 2852, 655,3890,3891,3117,4092,3018,3892,1310,3624,4691,5440,5441,5442,1733, 558, # 3504 4692,3747, 335,1549,3065,1756,4336,3748,1946,3511,1830,1291,1192, 470,2735,2108, # 3520 2806, 913,1054,4093,5443,1027,5444,3066,4094,4693, 982,2672,3399,3173,3512,3247, # 3536 3248,1947,2807,5445, 571,4694,5446,1831,5447,3625,2591,1523,2429,5448,2090, 984, # 3552 4695,3749,1960,5449,3750, 852, 923,2808,3513,3751, 969,1519, 999,2049,2325,1705, # 3568 5450,3118, 615,1662, 151, 597,4095,2410,2326,1049, 275,4696,3752,4337, 568,3753, # 3584 3626,2487,4338,3754,5451,2430,2275, 409,3249,5452,1566,2888,3514,1002, 769,2853, # 3600 194,2091,3174,3755,2226,3327,4339, 628,1505,5453,5454,1763,2180,3019,4096, 521, # 3616 1161,2592,1788,2206,2411,4697,4097,1625,4340,4341, 412, 42,3119, 464,5455,2642, # 3632 4698,3400,1760,1571,2889,3515,2537,1219,2207,3893,2643,2141,2373,4699,4700,3328, # 3648 1651,3401,3627,5456,5457,3628,2488,3516,5458,3756,5459,5460,2276,2092, 460,5461, # 3664 4701,5462,3020, 962, 588,3629, 289,3250,2644,1116, 52,5463,3067,1797,5464,5465, # 3680 5466,1467,5467,1598,1143,3757,4342,1985,1734,1067,4702,1280,3402, 465,4703,1572, # 3696 510,5468,1928,2245,1813,1644,3630,5469,4704,3758,5470,5471,2673,1573,1534,5472, # 3712 5473, 536,1808,1761,3517,3894,3175,2645,5474,5475,5476,4705,3518,2929,1912,2809, # 3728 5477,3329,1122, 377,3251,5478, 360,5479,5480,4343,1529, 551,5481,2060,3759,1769, # 3744 2431,5482,2930,4344,3330,3120,2327,2109,2031,4706,1404, 136,1468,1479, 672,1171, # 3760 3252,2308, 271,3176,5483,2772,5484,2050, 678,2736, 865,1948,4707,5485,2014,4098, # 3776 2971,5486,2737,2227,1397,3068,3760,4708,4709,1735,2931,3403,3631,5487,3895, 509, # 3792 2854,2458,2890,3896,5488,5489,3177,3178,4710,4345,2538,4711,2309,1166,1010, 552, # 3808 681,1888,5490,5491,2972,2973,4099,1287,1596,1862,3179, 358, 453, 736, 175, 478, # 3824 1117, 905,1167,1097,5492,1854,1530,5493,1706,5494,2181,3519,2292,3761,3520,3632, # 3840 4346,2093,4347,5495,3404,1193,2489,4348,1458,2193,2208,1863,1889,1421,3331,2932, # 3856 3069,2182,3521, 595,2123,5496,4100,5497,5498,4349,1707,2646, 223,3762,1359, 751, # 3872 3121, 183,3522,5499,2810,3021, 419,2374, 633, 704,3897,2394, 241,5500,5501,5502, # 3888 838,3022,3763,2277,2773,2459,3898,1939,2051,4101,1309,3122,2246,1181,5503,1136, # 3904 2209,3899,2375,1446,4350,2310,4712,5504,5505,4351,1055,2615, 484,3764,5506,4102, # 3920 625,4352,2278,3405,1499,4353,4103,5507,4104,4354,3253,2279,2280,3523,5508,5509, # 3936 2774, 808,2616,3765,3406,4105,4355,3123,2539, 526,3407,3900,4356, 955,5510,1620, # 3952 4357,2647,2432,5511,1429,3766,1669,1832, 994, 928,5512,3633,1260,5513,5514,5515, # 3968 1949,2293, 741,2933,1626,4358,2738,2460, 867,1184, 362,3408,1392,5516,5517,4106, # 3984 4359,1770,1736,3254,2934,4713,4714,1929,2707,1459,1158,5518,3070,3409,2891,1292, # 4000 1930,2513,2855,3767,1986,1187,2072,2015,2617,4360,5519,2574,2514,2170,3768,2490, # 4016 3332,5520,3769,4715,5521,5522, 666,1003,3023,1022,3634,4361,5523,4716,1814,2257, # 4032 574,3901,1603, 295,1535, 705,3902,4362, 283, 858, 417,5524,5525,3255,4717,4718, # 4048 3071,1220,1890,1046,2281,2461,4107,1393,1599, 689,2575, 388,4363,5526,2491, 802, # 4064 5527,2811,3903,2061,1405,2258,5528,4719,3904,2110,1052,1345,3256,1585,5529, 809, # 4080 5530,5531,5532, 575,2739,3524, 956,1552,1469,1144,2328,5533,2329,1560,2462,3635, # 4096 3257,4108, 616,2210,4364,3180,2183,2294,5534,1833,5535,3525,4720,5536,1319,3770, # 4112 3771,1211,3636,1023,3258,1293,2812,5537,5538,5539,3905, 607,2311,3906, 762,2892, # 4128 1439,4365,1360,4721,1485,3072,5540,4722,1038,4366,1450,2062,2648,4367,1379,4723, # 4144 2593,5541,5542,4368,1352,1414,2330,2935,1172,5543,5544,3907,3908,4724,1798,1451, # 4160 5545,5546,5547,5548,2936,4109,4110,2492,2351, 411,4111,4112,3637,3333,3124,4725, # 4176 1561,2674,1452,4113,1375,5549,5550, 47,2974, 316,5551,1406,1591,2937,3181,5552, # 4192 1025,2142,3125,3182, 354,2740, 884,2228,4369,2412, 508,3772, 726,3638, 996,2433, # 4208 3639, 729,5553, 392,2194,1453,4114,4726,3773,5554,5555,2463,3640,2618,1675,2813, # 4224 919,2352,2975,2353,1270,4727,4115, 73,5556,5557, 647,5558,3259,2856,2259,1550, # 4240 1346,3024,5559,1332, 883,3526,5560,5561,5562,5563,3334,2775,5564,1212, 831,1347, # 4256 4370,4728,2331,3909,1864,3073, 720,3910,4729,4730,3911,5565,4371,5566,5567,4731, # 4272 5568,5569,1799,4732,3774,2619,4733,3641,1645,2376,4734,5570,2938, 669,2211,2675, # 4288 2434,5571,2893,5572,5573,1028,3260,5574,4372,2413,5575,2260,1353,5576,5577,4735, # 4304 3183, 518,5578,4116,5579,4373,1961,5580,2143,4374,5581,5582,3025,2354,2355,3912, # 4320 516,1834,1454,4117,2708,4375,4736,2229,2620,1972,1129,3642,5583,2776,5584,2976, # 4336 1422, 577,1470,3026,1524,3410,5585,5586, 432,4376,3074,3527,5587,2594,1455,2515, # 4352 2230,1973,1175,5588,1020,2741,4118,3528,4737,5589,2742,5590,1743,1361,3075,3529, # 4368 2649,4119,4377,4738,2295, 895, 924,4378,2171, 331,2247,3076, 166,1627,3077,1098, # 4384 5591,1232,2894,2231,3411,4739, 657, 403,1196,2377, 542,3775,3412,1600,4379,3530, # 4400 5592,4740,2777,3261, 576, 530,1362,4741,4742,2540,2676,3776,4120,5593, 842,3913, # 4416 5594,2814,2032,1014,4121, 213,2709,3413, 665, 621,4380,5595,3777,2939,2435,5596, # 4432 2436,3335,3643,3414,4743,4381,2541,4382,4744,3644,1682,4383,3531,1380,5597, 724, # 4448 2282, 600,1670,5598,1337,1233,4745,3126,2248,5599,1621,4746,5600, 651,4384,5601, # 4464 1612,4385,2621,5602,2857,5603,2743,2312,3078,5604, 716,2464,3079, 174,1255,2710, # 4480 4122,3645, 548,1320,1398, 728,4123,1574,5605,1891,1197,3080,4124,5606,3081,3082, # 4496 3778,3646,3779, 747,5607, 635,4386,4747,5608,5609,5610,4387,5611,5612,4748,5613, # 4512 3415,4749,2437, 451,5614,3780,2542,2073,4388,2744,4389,4125,5615,1764,4750,5616, # 4528 4390, 350,4751,2283,2395,2493,5617,4391,4126,2249,1434,4127, 488,4752, 458,4392, # 4544 4128,3781, 771,1330,2396,3914,2576,3184,2160,2414,1553,2677,3185,4393,5618,2494, # 4560 2895,2622,1720,2711,4394,3416,4753,5619,2543,4395,5620,3262,4396,2778,5621,2016, # 4576 2745,5622,1155,1017,3782,3915,5623,3336,2313, 201,1865,4397,1430,5624,4129,5625, # 4592 5626,5627,5628,5629,4398,1604,5630, 414,1866, 371,2595,4754,4755,3532,2017,3127, # 4608 4756,1708, 960,4399, 887, 389,2172,1536,1663,1721,5631,2232,4130,2356,2940,1580, # 4624 5632,5633,1744,4757,2544,4758,4759,5634,4760,5635,2074,5636,4761,3647,3417,2896, # 4640 4400,5637,4401,2650,3418,2815, 673,2712,2465, 709,3533,4131,3648,4402,5638,1148, # 4656 502, 634,5639,5640,1204,4762,3649,1575,4763,2623,3783,5641,3784,3128, 948,3263, # 4672 121,1745,3916,1110,5642,4403,3083,2516,3027,4132,3785,1151,1771,3917,1488,4133, # 4688 1987,5643,2438,3534,5644,5645,2094,5646,4404,3918,1213,1407,2816, 531,2746,2545, # 4704 3264,1011,1537,4764,2779,4405,3129,1061,5647,3786,3787,1867,2897,5648,2018, 120, # 4720 4406,4407,2063,3650,3265,2314,3919,2678,3419,1955,4765,4134,5649,3535,1047,2713, # 4736 1266,5650,1368,4766,2858, 649,3420,3920,2546,2747,1102,2859,2679,5651,5652,2000, # 4752 5653,1111,3651,2977,5654,2495,3921,3652,2817,1855,3421,3788,5655,5656,3422,2415, # 4768 2898,3337,3266,3653,5657,2577,5658,3654,2818,4135,1460, 856,5659,3655,5660,2899, # 4784 2978,5661,2900,3922,5662,4408, 632,2517, 875,3923,1697,3924,2296,5663,5664,4767, # 4800 3028,1239, 580,4768,4409,5665, 914, 936,2075,1190,4136,1039,2124,5666,5667,5668, # 4816 5669,3423,1473,5670,1354,4410,3925,4769,2173,3084,4137, 915,3338,4411,4412,3339, # 4832 1605,1835,5671,2748, 398,3656,4413,3926,4138, 328,1913,2860,4139,3927,1331,4414, # 4848 3029, 937,4415,5672,3657,4140,4141,3424,2161,4770,3425, 524, 742, 538,3085,1012, # 4864 5673,5674,3928,2466,5675, 658,1103, 225,3929,5676,5677,4771,5678,4772,5679,3267, # 4880 1243,5680,4142, 963,2250,4773,5681,2714,3658,3186,5682,5683,2596,2332,5684,4774, # 4896 5685,5686,5687,3536, 957,3426,2547,2033,1931,2941,2467, 870,2019,3659,1746,2780, # 4912 2781,2439,2468,5688,3930,5689,3789,3130,3790,3537,3427,3791,5690,1179,3086,5691, # 4928 3187,2378,4416,3792,2548,3188,3131,2749,4143,5692,3428,1556,2549,2297, 977,2901, # 4944 2034,4144,1205,3429,5693,1765,3430,3189,2125,1271, 714,1689,4775,3538,5694,2333, # 4960 3931, 533,4417,3660,2184, 617,5695,2469,3340,3539,2315,5696,5697,3190,5698,5699, # 4976 3932,1988, 618, 427,2651,3540,3431,5700,5701,1244,1690,5702,2819,4418,4776,5703, # 4992 3541,4777,5704,2284,1576, 473,3661,4419,3432, 972,5705,3662,5706,3087,5707,5708, # 5008 4778,4779,5709,3793,4145,4146,5710, 153,4780, 356,5711,1892,2902,4420,2144, 408, # 5024 803,2357,5712,3933,5713,4421,1646,2578,2518,4781,4782,3934,5714,3935,4422,5715, # 5040 2416,3433, 752,5716,5717,1962,3341,2979,5718, 746,3030,2470,4783,4423,3794, 698, # 5056 4784,1893,4424,3663,2550,4785,3664,3936,5719,3191,3434,5720,1824,1302,4147,2715, # 5072 3937,1974,4425,5721,4426,3192, 823,1303,1288,1236,2861,3542,4148,3435, 774,3938, # 5088 5722,1581,4786,1304,2862,3939,4787,5723,2440,2162,1083,3268,4427,4149,4428, 344, # 5104 1173, 288,2316, 454,1683,5724,5725,1461,4788,4150,2597,5726,5727,4789, 985, 894, # 5120 5728,3436,3193,5729,1914,2942,3795,1989,5730,2111,1975,5731,4151,5732,2579,1194, # 5136 425,5733,4790,3194,1245,3796,4429,5734,5735,2863,5736, 636,4791,1856,3940, 760, # 5152 1800,5737,4430,2212,1508,4792,4152,1894,1684,2298,5738,5739,4793,4431,4432,2213, # 5168 479,5740,5741, 832,5742,4153,2496,5743,2980,2497,3797, 990,3132, 627,1815,2652, # 5184 4433,1582,4434,2126,2112,3543,4794,5744, 799,4435,3195,5745,4795,2113,1737,3031, # 5200 1018, 543, 754,4436,3342,1676,4796,4797,4154,4798,1489,5746,3544,5747,2624,2903, # 5216 4155,5748,5749,2981,5750,5751,5752,5753,3196,4799,4800,2185,1722,5754,3269,3270, # 5232 1843,3665,1715, 481, 365,1976,1857,5755,5756,1963,2498,4801,5757,2127,3666,3271, # 5248 433,1895,2064,2076,5758, 602,2750,5759,5760,5761,5762,5763,3032,1628,3437,5764, # 5264 3197,4802,4156,2904,4803,2519,5765,2551,2782,5766,5767,5768,3343,4804,2905,5769, # 5280 4805,5770,2864,4806,4807,1221,2982,4157,2520,5771,5772,5773,1868,1990,5774,5775, # 5296 5776,1896,5777,5778,4808,1897,4158, 318,5779,2095,4159,4437,5780,5781, 485,5782, # 5312 938,3941, 553,2680, 116,5783,3942,3667,5784,3545,2681,2783,3438,3344,2820,5785, # 5328 3668,2943,4160,1747,2944,2983,5786,5787, 207,5788,4809,5789,4810,2521,5790,3033, # 5344 890,3669,3943,5791,1878,3798,3439,5792,2186,2358,3440,1652,5793,5794,5795, 941, # 5360 2299, 208,3546,4161,2020, 330,4438,3944,2906,2499,3799,4439,4811,5796,5797,5798, # 5376 #last 512 #Everything below is of no interest for detection purpose 2522,1613,4812,5799,3345,3945,2523,5800,4162,5801,1637,4163,2471,4813,3946,5802, # 5392 2500,3034,3800,5803,5804,2195,4814,5805,2163,5806,5807,5808,5809,5810,5811,5812, # 5408 5813,5814,5815,5816,5817,5818,5819,5820,5821,5822,5823,5824,5825,5826,5827,5828, # 5424 5829,5830,5831,5832,5833,5834,5835,5836,5837,5838,5839,5840,5841,5842,5843,5844, # 5440 5845,5846,5847,5848,5849,5850,5851,5852,5853,5854,5855,5856,5857,5858,5859,5860, # 5456 5861,5862,5863,5864,5865,5866,5867,5868,5869,5870,5871,5872,5873,5874,5875,5876, # 5472 5877,5878,5879,5880,5881,5882,5883,5884,5885,5886,5887,5888,5889,5890,5891,5892, # 5488 5893,5894,5895,5896,5897,5898,5899,5900,5901,5902,5903,5904,5905,5906,5907,5908, # 5504 5909,5910,5911,5912,5913,5914,5915,5916,5917,5918,5919,5920,5921,5922,5923,5924, # 5520 5925,5926,5927,5928,5929,5930,5931,5932,5933,5934,5935,5936,5937,5938,5939,5940, # 5536 5941,5942,5943,5944,5945,5946,5947,5948,5949,5950,5951,5952,5953,5954,5955,5956, # 5552 5957,5958,5959,5960,5961,5962,5963,5964,5965,5966,5967,5968,5969,5970,5971,5972, # 5568 5973,5974,5975,5976,5977,5978,5979,5980,5981,5982,5983,5984,5985,5986,5987,5988, # 5584 5989,5990,5991,5992,5993,5994,5995,5996,5997,5998,5999,6000,6001,6002,6003,6004, # 5600 6005,6006,6007,6008,6009,6010,6011,6012,6013,6014,6015,6016,6017,6018,6019,6020, # 5616 6021,6022,6023,6024,6025,6026,6027,6028,6029,6030,6031,6032,6033,6034,6035,6036, # 5632 6037,6038,6039,6040,6041,6042,6043,6044,6045,6046,6047,6048,6049,6050,6051,6052, # 5648 6053,6054,6055,6056,6057,6058,6059,6060,6061,6062,6063,6064,6065,6066,6067,6068, # 5664 6069,6070,6071,6072,6073,6074,6075,6076,6077,6078,6079,6080,6081,6082,6083,6084, # 5680 6085,6086,6087,6088,6089,6090,6091,6092,6093,6094,6095,6096,6097,6098,6099,6100, # 5696 6101,6102,6103,6104,6105,6106,6107,6108,6109,6110,6111,6112,6113,6114,6115,6116, # 5712 6117,6118,6119,6120,6121,6122,6123,6124,6125,6126,6127,6128,6129,6130,6131,6132, # 5728 6133,6134,6135,6136,6137,6138,6139,6140,6141,6142,6143,6144,6145,6146,6147,6148, # 5744 6149,6150,6151,6152,6153,6154,6155,6156,6157,6158,6159,6160,6161,6162,6163,6164, # 5760 6165,6166,6167,6168,6169,6170,6171,6172,6173,6174,6175,6176,6177,6178,6179,6180, # 5776 6181,6182,6183,6184,6185,6186,6187,6188,6189,6190,6191,6192,6193,6194,6195,6196, # 5792 6197,6198,6199,6200,6201,6202,6203,6204,6205,6206,6207,6208,6209,6210,6211,6212, # 5808 6213,6214,6215,6216,6217,6218,6219,6220,6221,6222,6223,3670,6224,6225,6226,6227, # 5824 6228,6229,6230,6231,6232,6233,6234,6235,6236,6237,6238,6239,6240,6241,6242,6243, # 5840 6244,6245,6246,6247,6248,6249,6250,6251,6252,6253,6254,6255,6256,6257,6258,6259, # 5856 6260,6261,6262,6263,6264,6265,6266,6267,6268,6269,6270,6271,6272,6273,6274,6275, # 5872 6276,6277,6278,6279,6280,6281,6282,6283,6284,6285,4815,6286,6287,6288,6289,6290, # 5888 6291,6292,4816,6293,6294,6295,6296,6297,6298,6299,6300,6301,6302,6303,6304,6305, # 5904 6306,6307,6308,6309,6310,6311,4817,4818,6312,6313,6314,6315,6316,6317,6318,4819, # 5920 6319,6320,6321,6322,6323,6324,6325,6326,6327,6328,6329,6330,6331,6332,6333,6334, # 5936 6335,6336,6337,4820,6338,6339,6340,6341,6342,6343,6344,6345,6346,6347,6348,6349, # 5952 6350,6351,6352,6353,6354,6355,6356,6357,6358,6359,6360,6361,6362,6363,6364,6365, # 5968 6366,6367,6368,6369,6370,6371,6372,6373,6374,6375,6376,6377,6378,6379,6380,6381, # 5984 6382,6383,6384,6385,6386,6387,6388,6389,6390,6391,6392,6393,6394,6395,6396,6397, # 6000 6398,6399,6400,6401,6402,6403,6404,6405,6406,6407,6408,6409,6410,3441,6411,6412, # 6016 6413,6414,6415,6416,6417,6418,6419,6420,6421,6422,6423,6424,6425,4440,6426,6427, # 6032 6428,6429,6430,6431,6432,6433,6434,6435,6436,6437,6438,6439,6440,6441,6442,6443, # 6048 6444,6445,6446,6447,6448,6449,6450,6451,6452,6453,6454,4821,6455,6456,6457,6458, # 6064 6459,6460,6461,6462,6463,6464,6465,6466,6467,6468,6469,6470,6471,6472,6473,6474, # 6080 6475,6476,6477,3947,3948,6478,6479,6480,6481,3272,4441,6482,6483,6484,6485,4442, # 6096 6486,6487,6488,6489,6490,6491,6492,6493,6494,6495,6496,4822,6497,6498,6499,6500, # 6112 6501,6502,6503,6504,6505,6506,6507,6508,6509,6510,6511,6512,6513,6514,6515,6516, # 6128 6517,6518,6519,6520,6521,6522,6523,6524,6525,6526,6527,6528,6529,6530,6531,6532, # 6144 6533,6534,6535,6536,6537,6538,6539,6540,6541,6542,6543,6544,6545,6546,6547,6548, # 6160 6549,6550,6551,6552,6553,6554,6555,6556,2784,6557,4823,6558,6559,6560,6561,6562, # 6176 6563,6564,6565,6566,6567,6568,6569,3949,6570,6571,6572,4824,6573,6574,6575,6576, # 6192 6577,6578,6579,6580,6581,6582,6583,4825,6584,6585,6586,3950,2785,6587,6588,6589, # 6208 6590,6591,6592,6593,6594,6595,6596,6597,6598,6599,6600,6601,6602,6603,6604,6605, # 6224 6606,6607,6608,6609,6610,6611,6612,4826,6613,6614,6615,4827,6616,6617,6618,6619, # 6240 6620,6621,6622,6623,6624,6625,4164,6626,6627,6628,6629,6630,6631,6632,6633,6634, # 6256 3547,6635,4828,6636,6637,6638,6639,6640,6641,6642,3951,2984,6643,6644,6645,6646, # 6272 6647,6648,6649,4165,6650,4829,6651,6652,4830,6653,6654,6655,6656,6657,6658,6659, # 6288 6660,6661,6662,4831,6663,6664,6665,6666,6667,6668,6669,6670,6671,4166,6672,4832, # 6304 3952,6673,6674,6675,6676,4833,6677,6678,6679,4167,6680,6681,6682,3198,6683,6684, # 6320 6685,6686,6687,6688,6689,6690,6691,6692,6693,6694,6695,6696,6697,4834,6698,6699, # 6336 6700,6701,6702,6703,6704,6705,6706,6707,6708,6709,6710,6711,6712,6713,6714,6715, # 6352 6716,6717,6718,6719,6720,6721,6722,6723,6724,6725,6726,6727,6728,6729,6730,6731, # 6368 6732,6733,6734,4443,6735,6736,6737,6738,6739,6740,6741,6742,6743,6744,6745,4444, # 6384 6746,6747,6748,6749,6750,6751,6752,6753,6754,6755,6756,6757,6758,6759,6760,6761, # 6400 6762,6763,6764,6765,6766,6767,6768,6769,6770,6771,6772,6773,6774,6775,6776,6777, # 6416 6778,6779,6780,6781,4168,6782,6783,3442,6784,6785,6786,6787,6788,6789,6790,6791, # 6432 4169,6792,6793,6794,6795,6796,6797,6798,6799,6800,6801,6802,6803,6804,6805,6806, # 6448 6807,6808,6809,6810,6811,4835,6812,6813,6814,4445,6815,6816,4446,6817,6818,6819, # 6464 6820,6821,6822,6823,6824,6825,6826,6827,6828,6829,6830,6831,6832,6833,6834,6835, # 6480 3548,6836,6837,6838,6839,6840,6841,6842,6843,6844,6845,6846,4836,6847,6848,6849, # 6496 6850,6851,6852,6853,6854,3953,6855,6856,6857,6858,6859,6860,6861,6862,6863,6864, # 6512 6865,6866,6867,6868,6869,6870,6871,6872,6873,6874,6875,6876,6877,3199,6878,6879, # 6528 6880,6881,6882,4447,6883,6884,6885,6886,6887,6888,6889,6890,6891,6892,6893,6894, # 6544 6895,6896,6897,6898,6899,6900,6901,6902,6903,6904,4170,6905,6906,6907,6908,6909, # 6560 6910,6911,6912,6913,6914,6915,6916,6917,6918,6919,6920,6921,6922,6923,6924,6925, # 6576 6926,6927,4837,6928,6929,6930,6931,6932,6933,6934,6935,6936,3346,6937,6938,4838, # 6592 6939,6940,6941,4448,6942,6943,6944,6945,6946,4449,6947,6948,6949,6950,6951,6952, # 6608 6953,6954,6955,6956,6957,6958,6959,6960,6961,6962,6963,6964,6965,6966,6967,6968, # 6624 6969,6970,6971,6972,6973,6974,6975,6976,6977,6978,6979,6980,6981,6982,6983,6984, # 6640 6985,6986,6987,6988,6989,6990,6991,6992,6993,6994,3671,6995,6996,6997,6998,4839, # 6656 6999,7000,7001,7002,3549,7003,7004,7005,7006,7007,7008,7009,7010,7011,7012,7013, # 6672 7014,7015,7016,7017,7018,7019,7020,7021,7022,7023,7024,7025,7026,7027,7028,7029, # 6688 7030,4840,7031,7032,7033,7034,7035,7036,7037,7038,4841,7039,7040,7041,7042,7043, # 6704 7044,7045,7046,7047,7048,7049,7050,7051,7052,7053,7054,7055,7056,7057,7058,7059, # 6720 7060,7061,7062,7063,7064,7065,7066,7067,7068,7069,7070,2985,7071,7072,7073,7074, # 6736 7075,7076,7077,7078,7079,7080,4842,7081,7082,7083,7084,7085,7086,7087,7088,7089, # 6752 7090,7091,7092,7093,7094,7095,7096,7097,7098,7099,7100,7101,7102,7103,7104,7105, # 6768 7106,7107,7108,7109,7110,7111,7112,7113,7114,7115,7116,7117,7118,4450,7119,7120, # 6784 7121,7122,7123,7124,7125,7126,7127,7128,7129,7130,7131,7132,7133,7134,7135,7136, # 6800 7137,7138,7139,7140,7141,7142,7143,4843,7144,7145,7146,7147,7148,7149,7150,7151, # 6816 7152,7153,7154,7155,7156,7157,7158,7159,7160,7161,7162,7163,7164,7165,7166,7167, # 6832 7168,7169,7170,7171,7172,7173,7174,7175,7176,7177,7178,7179,7180,7181,7182,7183, # 6848 7184,7185,7186,7187,7188,4171,4172,7189,7190,7191,7192,7193,7194,7195,7196,7197, # 6864 7198,7199,7200,7201,7202,7203,7204,7205,7206,7207,7208,7209,7210,7211,7212,7213, # 6880 7214,7215,7216,7217,7218,7219,7220,7221,7222,7223,7224,7225,7226,7227,7228,7229, # 6896 7230,7231,7232,7233,7234,7235,7236,7237,7238,7239,7240,7241,7242,7243,7244,7245, # 6912 7246,7247,7248,7249,7250,7251,7252,7253,7254,7255,7256,7257,7258,7259,7260,7261, # 6928 7262,7263,7264,7265,7266,7267,7268,7269,7270,7271,7272,7273,7274,7275,7276,7277, # 6944 7278,7279,7280,7281,7282,7283,7284,7285,7286,7287,7288,7289,7290,7291,7292,7293, # 6960 7294,7295,7296,4844,7297,7298,7299,7300,7301,7302,7303,7304,7305,7306,7307,7308, # 6976 7309,7310,7311,7312,7313,7314,7315,7316,4451,7317,7318,7319,7320,7321,7322,7323, # 6992 7324,7325,7326,7327,7328,7329,7330,7331,7332,7333,7334,7335,7336,7337,7338,7339, # 7008 7340,7341,7342,7343,7344,7345,7346,7347,7348,7349,7350,7351,7352,7353,4173,7354, # 7024 7355,4845,7356,7357,7358,7359,7360,7361,7362,7363,7364,7365,7366,7367,7368,7369, # 7040 7370,7371,7372,7373,7374,7375,7376,7377,7378,7379,7380,7381,7382,7383,7384,7385, # 7056 7386,7387,7388,4846,7389,7390,7391,7392,7393,7394,7395,7396,7397,7398,7399,7400, # 7072 7401,7402,7403,7404,7405,3672,7406,7407,7408,7409,7410,7411,7412,7413,7414,7415, # 7088 7416,7417,7418,7419,7420,7421,7422,7423,7424,7425,7426,7427,7428,7429,7430,7431, # 7104 7432,7433,7434,7435,7436,7437,7438,7439,7440,7441,7442,7443,7444,7445,7446,7447, # 7120 7448,7449,7450,7451,7452,7453,4452,7454,3200,7455,7456,7457,7458,7459,7460,7461, # 7136 7462,7463,7464,7465,7466,7467,7468,7469,7470,7471,7472,7473,7474,4847,7475,7476, # 7152 7477,3133,7478,7479,7480,7481,7482,7483,7484,7485,7486,7487,7488,7489,7490,7491, # 7168 7492,7493,7494,7495,7496,7497,7498,7499,7500,7501,7502,3347,7503,7504,7505,7506, # 7184 7507,7508,7509,7510,7511,7512,7513,7514,7515,7516,7517,7518,7519,7520,7521,4848, # 7200 7522,7523,7524,7525,7526,7527,7528,7529,7530,7531,7532,7533,7534,7535,7536,7537, # 7216 7538,7539,7540,7541,7542,7543,7544,7545,7546,7547,7548,7549,3801,4849,7550,7551, # 7232 7552,7553,7554,7555,7556,7557,7558,7559,7560,7561,7562,7563,7564,7565,7566,7567, # 7248 7568,7569,3035,7570,7571,7572,7573,7574,7575,7576,7577,7578,7579,7580,7581,7582, # 7264 7583,7584,7585,7586,7587,7588,7589,7590,7591,7592,7593,7594,7595,7596,7597,7598, # 7280 7599,7600,7601,7602,7603,7604,7605,7606,7607,7608,7609,7610,7611,7612,7613,7614, # 7296 7615,7616,4850,7617,7618,3802,7619,7620,7621,7622,7623,7624,7625,7626,7627,7628, # 7312 7629,7630,7631,7632,4851,7633,7634,7635,7636,7637,7638,7639,7640,7641,7642,7643, # 7328 7644,7645,7646,7647,7648,7649,7650,7651,7652,7653,7654,7655,7656,7657,7658,7659, # 7344 7660,7661,7662,7663,7664,7665,7666,7667,7668,7669,7670,4453,7671,7672,7673,7674, # 7360 7675,7676,7677,7678,7679,7680,7681,7682,7683,7684,7685,7686,7687,7688,7689,7690, # 7376 7691,7692,7693,7694,7695,7696,7697,3443,7698,7699,7700,7701,7702,4454,7703,7704, # 7392 7705,7706,7707,7708,7709,7710,7711,7712,7713,2472,7714,7715,7716,7717,7718,7719, # 7408 7720,7721,7722,7723,7724,7725,7726,7727,7728,7729,7730,7731,3954,7732,7733,7734, # 7424 7735,7736,7737,7738,7739,7740,7741,7742,7743,7744,7745,7746,7747,7748,7749,7750, # 7440 3134,7751,7752,4852,7753,7754,7755,4853,7756,7757,7758,7759,7760,4174,7761,7762, # 7456 7763,7764,7765,7766,7767,7768,7769,7770,7771,7772,7773,7774,7775,7776,7777,7778, # 7472 7779,7780,7781,7782,7783,7784,7785,7786,7787,7788,7789,7790,7791,7792,7793,7794, # 7488 7795,7796,7797,7798,7799,7800,7801,7802,7803,7804,7805,4854,7806,7807,7808,7809, # 7504 7810,7811,7812,7813,7814,7815,7816,7817,7818,7819,7820,7821,7822,7823,7824,7825, # 7520 4855,7826,7827,7828,7829,7830,7831,7832,7833,7834,7835,7836,7837,7838,7839,7840, # 7536 7841,7842,7843,7844,7845,7846,7847,3955,7848,7849,7850,7851,7852,7853,7854,7855, # 7552 7856,7857,7858,7859,7860,3444,7861,7862,7863,7864,7865,7866,7867,7868,7869,7870, # 7568 7871,7872,7873,7874,7875,7876,7877,7878,7879,7880,7881,7882,7883,7884,7885,7886, # 7584 7887,7888,7889,7890,7891,4175,7892,7893,7894,7895,7896,4856,4857,7897,7898,7899, # 7600 7900,2598,7901,7902,7903,7904,7905,7906,7907,7908,4455,7909,7910,7911,7912,7913, # 7616 7914,3201,7915,7916,7917,7918,7919,7920,7921,4858,7922,7923,7924,7925,7926,7927, # 7632 7928,7929,7930,7931,7932,7933,7934,7935,7936,7937,7938,7939,7940,7941,7942,7943, # 7648 7944,7945,7946,7947,7948,7949,7950,7951,7952,7953,7954,7955,7956,7957,7958,7959, # 7664 7960,7961,7962,7963,7964,7965,7966,7967,7968,7969,7970,7971,7972,7973,7974,7975, # 7680 7976,7977,7978,7979,7980,7981,4859,7982,7983,7984,7985,7986,7987,7988,7989,7990, # 7696 7991,7992,7993,7994,7995,7996,4860,7997,7998,7999,8000,8001,8002,8003,8004,8005, # 7712 8006,8007,8008,8009,8010,8011,8012,8013,8014,8015,8016,4176,8017,8018,8019,8020, # 7728 8021,8022,8023,4861,8024,8025,8026,8027,8028,8029,8030,8031,8032,8033,8034,8035, # 7744 8036,4862,4456,8037,8038,8039,8040,4863,8041,8042,8043,8044,8045,8046,8047,8048, # 7760 8049,8050,8051,8052,8053,8054,8055,8056,8057,8058,8059,8060,8061,8062,8063,8064, # 7776 8065,8066,8067,8068,8069,8070,8071,8072,8073,8074,8075,8076,8077,8078,8079,8080, # 7792 8081,8082,8083,8084,8085,8086,8087,8088,8089,8090,8091,8092,8093,8094,8095,8096, # 7808 8097,8098,8099,4864,4177,8100,8101,8102,8103,8104,8105,8106,8107,8108,8109,8110, # 7824 8111,8112,8113,8114,8115,8116,8117,8118,8119,8120,4178,8121,8122,8123,8124,8125, # 7840 8126,8127,8128,8129,8130,8131,8132,8133,8134,8135,8136,8137,8138,8139,8140,8141, # 7856 8142,8143,8144,8145,4865,4866,8146,8147,8148,8149,8150,8151,8152,8153,8154,8155, # 7872 8156,8157,8158,8159,8160,8161,8162,8163,8164,8165,4179,8166,8167,8168,8169,8170, # 7888 8171,8172,8173,8174,8175,8176,8177,8178,8179,8180,8181,4457,8182,8183,8184,8185, # 7904 8186,8187,8188,8189,8190,8191,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201, # 7920 8202,8203,8204,8205,8206,8207,8208,8209,8210,8211,8212,8213,8214,8215,8216,8217, # 7936 8218,8219,8220,8221,8222,8223,8224,8225,8226,8227,8228,8229,8230,8231,8232,8233, # 7952 8234,8235,8236,8237,8238,8239,8240,8241,8242,8243,8244,8245,8246,8247,8248,8249, # 7968 8250,8251,8252,8253,8254,8255,8256,3445,8257,8258,8259,8260,8261,8262,4458,8263, # 7984 8264,8265,8266,8267,8268,8269,8270,8271,8272,4459,8273,8274,8275,8276,3550,8277, # 8000 8278,8279,8280,8281,8282,8283,8284,8285,8286,8287,8288,8289,4460,8290,8291,8292, # 8016 8293,8294,8295,8296,8297,8298,8299,8300,8301,8302,8303,8304,8305,8306,8307,4867, # 8032 8308,8309,8310,8311,8312,3551,8313,8314,8315,8316,8317,8318,8319,8320,8321,8322, # 8048 8323,8324,8325,8326,4868,8327,8328,8329,8330,8331,8332,8333,8334,8335,8336,8337, # 8064 8338,8339,8340,8341,8342,8343,8344,8345,8346,8347,8348,8349,8350,8351,8352,8353, # 8080 8354,8355,8356,8357,8358,8359,8360,8361,8362,8363,4869,4461,8364,8365,8366,8367, # 8096 8368,8369,8370,4870,8371,8372,8373,8374,8375,8376,8377,8378,8379,8380,8381,8382, # 8112 8383,8384,8385,8386,8387,8388,8389,8390,8391,8392,8393,8394,8395,8396,8397,8398, # 8128 8399,8400,8401,8402,8403,8404,8405,8406,8407,8408,8409,8410,4871,8411,8412,8413, # 8144 8414,8415,8416,8417,8418,8419,8420,8421,8422,4462,8423,8424,8425,8426,8427,8428, # 8160 8429,8430,8431,8432,8433,2986,8434,8435,8436,8437,8438,8439,8440,8441,8442,8443, # 8176 8444,8445,8446,8447,8448,8449,8450,8451,8452,8453,8454,8455,8456,8457,8458,8459, # 8192 8460,8461,8462,8463,8464,8465,8466,8467,8468,8469,8470,8471,8472,8473,8474,8475, # 8208 8476,8477,8478,4180,8479,8480,8481,8482,8483,8484,8485,8486,8487,8488,8489,8490, # 8224 8491,8492,8493,8494,8495,8496,8497,8498,8499,8500,8501,8502,8503,8504,8505,8506, # 8240 8507,8508,8509,8510,8511,8512,8513,8514,8515,8516,8517,8518,8519,8520,8521,8522, # 8256 8523,8524,8525,8526,8527,8528,8529,8530,8531,8532,8533,8534,8535,8536,8537,8538, # 8272 8539,8540,8541,8542,8543,8544,8545,8546,8547,8548,8549,8550,8551,8552,8553,8554, # 8288 8555,8556,8557,8558,8559,8560,8561,8562,8563,8564,4872,8565,8566,8567,8568,8569, # 8304 8570,8571,8572,8573,4873,8574,8575,8576,8577,8578,8579,8580,8581,8582,8583,8584, # 8320 8585,8586,8587,8588,8589,8590,8591,8592,8593,8594,8595,8596,8597,8598,8599,8600, # 8336 8601,8602,8603,8604,8605,3803,8606,8607,8608,8609,8610,8611,8612,8613,4874,3804, # 8352 8614,8615,8616,8617,8618,8619,8620,8621,3956,8622,8623,8624,8625,8626,8627,8628, # 8368 8629,8630,8631,8632,8633,8634,8635,8636,8637,8638,2865,8639,8640,8641,8642,8643, # 8384 8644,8645,8646,8647,8648,8649,8650,8651,8652,8653,8654,8655,8656,4463,8657,8658, # 8400 8659,4875,4876,8660,8661,8662,8663,8664,8665,8666,8667,8668,8669,8670,8671,8672, # 8416 8673,8674,8675,8676,8677,8678,8679,8680,8681,4464,8682,8683,8684,8685,8686,8687, # 8432 8688,8689,8690,8691,8692,8693,8694,8695,8696,8697,8698,8699,8700,8701,8702,8703, # 8448 8704,8705,8706,8707,8708,8709,2261,8710,8711,8712,8713,8714,8715,8716,8717,8718, # 8464 8719,8720,8721,8722,8723,8724,8725,8726,8727,8728,8729,8730,8731,8732,8733,4181, # 8480 8734,8735,8736,8737,8738,8739,8740,8741,8742,8743,8744,8745,8746,8747,8748,8749, # 8496 8750,8751,8752,8753,8754,8755,8756,8757,8758,8759,8760,8761,8762,8763,4877,8764, # 8512 8765,8766,8767,8768,8769,8770,8771,8772,8773,8774,8775,8776,8777,8778,8779,8780, # 8528 8781,8782,8783,8784,8785,8786,8787,8788,4878,8789,4879,8790,8791,8792,4880,8793, # 8544 8794,8795,8796,8797,8798,8799,8800,8801,4881,8802,8803,8804,8805,8806,8807,8808, # 8560 8809,8810,8811,8812,8813,8814,8815,3957,8816,8817,8818,8819,8820,8821,8822,8823, # 8576 8824,8825,8826,8827,8828,8829,8830,8831,8832,8833,8834,8835,8836,8837,8838,8839, # 8592 8840,8841,8842,8843,8844,8845,8846,8847,4882,8848,8849,8850,8851,8852,8853,8854, # 8608 8855,8856,8857,8858,8859,8860,8861,8862,8863,8864,8865,8866,8867,8868,8869,8870, # 8624 8871,8872,8873,8874,8875,8876,8877,8878,8879,8880,8881,8882,8883,8884,3202,8885, # 8640 8886,8887,8888,8889,8890,8891,8892,8893,8894,8895,8896,8897,8898,8899,8900,8901, # 8656 8902,8903,8904,8905,8906,8907,8908,8909,8910,8911,8912,8913,8914,8915,8916,8917, # 8672 8918,8919,8920,8921,8922,8923,8924,4465,8925,8926,8927,8928,8929,8930,8931,8932, # 8688 4883,8933,8934,8935,8936,8937,8938,8939,8940,8941,8942,8943,2214,8944,8945,8946, # 8704 8947,8948,8949,8950,8951,8952,8953,8954,8955,8956,8957,8958,8959,8960,8961,8962, # 8720 8963,8964,8965,4884,8966,8967,8968,8969,8970,8971,8972,8973,8974,8975,8976,8977, # 8736 8978,8979,8980,8981,8982,8983,8984,8985,8986,8987,8988,8989,8990,8991,8992,4885, # 8752 8993,8994,8995,8996,8997,8998,8999,9000,9001,9002,9003,9004,9005,9006,9007,9008, # 8768 9009,9010,9011,9012,9013,9014,9015,9016,9017,9018,9019,9020,9021,4182,9022,9023, # 8784 9024,9025,9026,9027,9028,9029,9030,9031,9032,9033,9034,9035,9036,9037,9038,9039, # 8800 9040,9041,9042,9043,9044,9045,9046,9047,9048,9049,9050,9051,9052,9053,9054,9055, # 8816 9056,9057,9058,9059,9060,9061,9062,9063,4886,9064,9065,9066,9067,9068,9069,4887, # 8832 9070,9071,9072,9073,9074,9075,9076,9077,9078,9079,9080,9081,9082,9083,9084,9085, # 8848 9086,9087,9088,9089,9090,9091,9092,9093,9094,9095,9096,9097,9098,9099,9100,9101, # 8864 9102,9103,9104,9105,9106,9107,9108,9109,9110,9111,9112,9113,9114,9115,9116,9117, # 8880 9118,9119,9120,9121,9122,9123,9124,9125,9126,9127,9128,9129,9130,9131,9132,9133, # 8896 9134,9135,9136,9137,9138,9139,9140,9141,3958,9142,9143,9144,9145,9146,9147,9148, # 8912 9149,9150,9151,4888,9152,9153,9154,9155,9156,9157,9158,9159,9160,9161,9162,9163, # 8928 9164,9165,9166,9167,9168,9169,9170,9171,9172,9173,9174,9175,4889,9176,9177,9178, # 8944 9179,9180,9181,9182,9183,9184,9185,9186,9187,9188,9189,9190,9191,9192,9193,9194, # 8960 9195,9196,9197,9198,9199,9200,9201,9202,9203,4890,9204,9205,9206,9207,9208,9209, # 8976 9210,9211,9212,9213,9214,9215,9216,9217,9218,9219,9220,9221,9222,4466,9223,9224, # 8992 9225,9226,9227,9228,9229,9230,9231,9232,9233,9234,9235,9236,9237,9238,9239,9240, # 9008 9241,9242,9243,9244,9245,4891,9246,9247,9248,9249,9250,9251,9252,9253,9254,9255, # 9024 9256,9257,4892,9258,9259,9260,9261,4893,4894,9262,9263,9264,9265,9266,9267,9268, # 9040 9269,9270,9271,9272,9273,4467,9274,9275,9276,9277,9278,9279,9280,9281,9282,9283, # 9056 9284,9285,3673,9286,9287,9288,9289,9290,9291,9292,9293,9294,9295,9296,9297,9298, # 9072 9299,9300,9301,9302,9303,9304,9305,9306,9307,9308,9309,9310,9311,9312,9313,9314, # 9088 9315,9316,9317,9318,9319,9320,9321,9322,4895,9323,9324,9325,9326,9327,9328,9329, # 9104 9330,9331,9332,9333,9334,9335,9336,9337,9338,9339,9340,9341,9342,9343,9344,9345, # 9120 9346,9347,4468,9348,9349,9350,9351,9352,9353,9354,9355,9356,9357,9358,9359,9360, # 9136 9361,9362,9363,9364,9365,9366,9367,9368,9369,9370,9371,9372,9373,4896,9374,4469, # 9152 9375,9376,9377,9378,9379,4897,9380,9381,9382,9383,9384,9385,9386,9387,9388,9389, # 9168 9390,9391,9392,9393,9394,9395,9396,9397,9398,9399,9400,9401,9402,9403,9404,9405, # 9184 9406,4470,9407,2751,9408,9409,3674,3552,9410,9411,9412,9413,9414,9415,9416,9417, # 9200 9418,9419,9420,9421,4898,9422,9423,9424,9425,9426,9427,9428,9429,3959,9430,9431, # 9216 9432,9433,9434,9435,9436,4471,9437,9438,9439,9440,9441,9442,9443,9444,9445,9446, # 9232 9447,9448,9449,9450,3348,9451,9452,9453,9454,9455,9456,9457,9458,9459,9460,9461, # 9248 9462,9463,9464,9465,9466,9467,9468,9469,9470,9471,9472,4899,9473,9474,9475,9476, # 9264 9477,4900,9478,9479,9480,9481,9482,9483,9484,9485,9486,9487,9488,3349,9489,9490, # 9280 9491,9492,9493,9494,9495,9496,9497,9498,9499,9500,9501,9502,9503,9504,9505,9506, # 9296 9507,9508,9509,9510,9511,9512,9513,9514,9515,9516,9517,9518,9519,9520,4901,9521, # 9312 9522,9523,9524,9525,9526,4902,9527,9528,9529,9530,9531,9532,9533,9534,9535,9536, # 9328 9537,9538,9539,9540,9541,9542,9543,9544,9545,9546,9547,9548,9549,9550,9551,9552, # 9344 9553,9554,9555,9556,9557,9558,9559,9560,9561,9562,9563,9564,9565,9566,9567,9568, # 9360 9569,9570,9571,9572,9573,9574,9575,9576,9577,9578,9579,9580,9581,9582,9583,9584, # 9376 3805,9585,9586,9587,9588,9589,9590,9591,9592,9593,9594,9595,9596,9597,9598,9599, # 9392 9600,9601,9602,4903,9603,9604,9605,9606,9607,4904,9608,9609,9610,9611,9612,9613, # 9408 9614,4905,9615,9616,9617,9618,9619,9620,9621,9622,9623,9624,9625,9626,9627,9628, # 9424 9629,9630,9631,9632,4906,9633,9634,9635,9636,9637,9638,9639,9640,9641,9642,9643, # 9440 4907,9644,9645,9646,9647,9648,9649,9650,9651,9652,9653,9654,9655,9656,9657,9658, # 9456 9659,9660,9661,9662,9663,9664,9665,9666,9667,9668,9669,9670,9671,9672,4183,9673, # 9472 9674,9675,9676,9677,4908,9678,9679,9680,9681,4909,9682,9683,9684,9685,9686,9687, # 9488 9688,9689,9690,4910,9691,9692,9693,3675,9694,9695,9696,2945,9697,9698,9699,9700, # 9504 9701,9702,9703,9704,9705,4911,9706,9707,9708,9709,9710,9711,9712,9713,9714,9715, # 9520 9716,9717,9718,9719,9720,9721,9722,9723,9724,9725,9726,9727,9728,9729,9730,9731, # 9536 9732,9733,9734,9735,4912,9736,9737,9738,9739,9740,4913,9741,9742,9743,9744,9745, # 9552 9746,9747,9748,9749,9750,9751,9752,9753,9754,9755,9756,9757,9758,4914,9759,9760, # 9568 9761,9762,9763,9764,9765,9766,9767,9768,9769,9770,9771,9772,9773,9774,9775,9776, # 9584 9777,9778,9779,9780,9781,9782,4915,9783,9784,9785,9786,9787,9788,9789,9790,9791, # 9600 9792,9793,4916,9794,9795,9796,9797,9798,9799,9800,9801,9802,9803,9804,9805,9806, # 9616 9807,9808,9809,9810,9811,9812,9813,9814,9815,9816,9817,9818,9819,9820,9821,9822, # 9632 9823,9824,9825,9826,9827,9828,9829,9830,9831,9832,9833,9834,9835,9836,9837,9838, # 9648 9839,9840,9841,9842,9843,9844,9845,9846,9847,9848,9849,9850,9851,9852,9853,9854, # 9664 9855,9856,9857,9858,9859,9860,9861,9862,9863,9864,9865,9866,9867,9868,4917,9869, # 9680 9870,9871,9872,9873,9874,9875,9876,9877,9878,9879,9880,9881,9882,9883,9884,9885, # 9696 9886,9887,9888,9889,9890,9891,9892,4472,9893,9894,9895,9896,9897,3806,9898,9899, # 9712 9900,9901,9902,9903,9904,9905,9906,9907,9908,9909,9910,9911,9912,9913,9914,4918, # 9728 9915,9916,9917,4919,9918,9919,9920,9921,4184,9922,9923,9924,9925,9926,9927,9928, # 9744 9929,9930,9931,9932,9933,9934,9935,9936,9937,9938,9939,9940,9941,9942,9943,9944, # 9760 9945,9946,4920,9947,9948,9949,9950,9951,9952,9953,9954,9955,4185,9956,9957,9958, # 9776 9959,9960,9961,9962,9963,9964,9965,4921,9966,9967,9968,4473,9969,9970,9971,9972, # 9792 9973,9974,9975,9976,9977,4474,9978,9979,9980,9981,9982,9983,9984,9985,9986,9987, # 9808 9988,9989,9990,9991,9992,9993,9994,9995,9996,9997,9998,9999,10000,10001,10002,10003, # 9824 10004,10005,10006,10007,10008,10009,10010,10011,10012,10013,10014,10015,10016,10017,10018,10019, # 9840 10020,10021,4922,10022,4923,10023,10024,10025,10026,10027,10028,10029,10030,10031,10032,10033, # 9856 10034,10035,10036,10037,10038,10039,10040,10041,10042,10043,10044,10045,10046,10047,10048,4924, # 9872 10049,10050,10051,10052,10053,10054,10055,10056,10057,10058,10059,10060,10061,10062,10063,10064, # 9888 10065,10066,10067,10068,10069,10070,10071,10072,10073,10074,10075,10076,10077,10078,10079,10080, # 9904 10081,10082,10083,10084,10085,10086,10087,4475,10088,10089,10090,10091,10092,10093,10094,10095, # 9920 10096,10097,4476,10098,10099,10100,10101,10102,10103,10104,10105,10106,10107,10108,10109,10110, # 9936 10111,2174,10112,10113,10114,10115,10116,10117,10118,10119,10120,10121,10122,10123,10124,10125, # 9952 10126,10127,10128,10129,10130,10131,10132,10133,10134,10135,10136,10137,10138,10139,10140,3807, # 9968 4186,4925,10141,10142,10143,10144,10145,10146,10147,4477,4187,10148,10149,10150,10151,10152, # 9984 10153,4188,10154,10155,10156,10157,10158,10159,10160,10161,4926,10162,10163,10164,10165,10166, #10000 10167,10168,10169,10170,10171,10172,10173,10174,10175,10176,10177,10178,10179,10180,10181,10182, #10016 10183,10184,10185,10186,10187,10188,10189,10190,10191,10192,3203,10193,10194,10195,10196,10197, #10032 10198,10199,10200,4478,10201,10202,10203,10204,4479,10205,10206,10207,10208,10209,10210,10211, #10048 10212,10213,10214,10215,10216,10217,10218,10219,10220,10221,10222,10223,10224,10225,10226,10227, #10064 10228,10229,10230,10231,10232,10233,10234,4927,10235,10236,10237,10238,10239,10240,10241,10242, #10080 10243,10244,10245,10246,10247,10248,10249,10250,10251,10252,10253,10254,10255,10256,10257,10258, #10096 10259,10260,10261,10262,10263,10264,10265,10266,10267,10268,10269,10270,10271,10272,10273,4480, #10112 4928,4929,10274,10275,10276,10277,10278,10279,10280,10281,10282,10283,10284,10285,10286,10287, #10128 10288,10289,10290,10291,10292,10293,10294,10295,10296,10297,10298,10299,10300,10301,10302,10303, #10144 10304,10305,10306,10307,10308,10309,10310,10311,10312,10313,10314,10315,10316,10317,10318,10319, #10160 10320,10321,10322,10323,10324,10325,10326,10327,10328,10329,10330,10331,10332,10333,10334,4930, #10176 10335,10336,10337,10338,10339,10340,10341,10342,4931,10343,10344,10345,10346,10347,10348,10349, #10192 10350,10351,10352,10353,10354,10355,3088,10356,2786,10357,10358,10359,10360,4189,10361,10362, #10208 10363,10364,10365,10366,10367,10368,10369,10370,10371,10372,10373,10374,10375,4932,10376,10377, #10224 10378,10379,10380,10381,10382,10383,10384,10385,10386,10387,10388,10389,10390,10391,10392,4933, #10240 10393,10394,10395,4934,10396,10397,10398,10399,10400,10401,10402,10403,10404,10405,10406,10407, #10256 10408,10409,10410,10411,10412,3446,10413,10414,10415,10416,10417,10418,10419,10420,10421,10422, #10272 10423,4935,10424,10425,10426,10427,10428,10429,10430,4936,10431,10432,10433,10434,10435,10436, #10288 10437,10438,10439,10440,10441,10442,10443,4937,10444,10445,10446,10447,4481,10448,10449,10450, #10304 10451,10452,10453,10454,10455,10456,10457,10458,10459,10460,10461,10462,10463,10464,10465,10466, #10320 10467,10468,10469,10470,10471,10472,10473,10474,10475,10476,10477,10478,10479,10480,10481,10482, #10336 10483,10484,10485,10486,10487,10488,10489,10490,10491,10492,10493,10494,10495,10496,10497,10498, #10352 10499,10500,10501,10502,10503,10504,10505,4938,10506,10507,10508,10509,10510,2552,10511,10512, #10368 10513,10514,10515,10516,3447,10517,10518,10519,10520,10521,10522,10523,10524,10525,10526,10527, #10384 10528,10529,10530,10531,10532,10533,10534,10535,10536,10537,10538,10539,10540,10541,10542,10543, #10400 4482,10544,4939,10545,10546,10547,10548,10549,10550,10551,10552,10553,10554,10555,10556,10557, #10416 10558,10559,10560,10561,10562,10563,10564,10565,10566,10567,3676,4483,10568,10569,10570,10571, #10432 10572,3448,10573,10574,10575,10576,10577,10578,10579,10580,10581,10582,10583,10584,10585,10586, #10448 10587,10588,10589,10590,10591,10592,10593,10594,10595,10596,10597,10598,10599,10600,10601,10602, #10464 10603,10604,10605,10606,10607,10608,10609,10610,10611,10612,10613,10614,10615,10616,10617,10618, #10480 10619,10620,10621,10622,10623,10624,10625,10626,10627,4484,10628,10629,10630,10631,10632,4940, #10496 10633,10634,10635,10636,10637,10638,10639,10640,10641,10642,10643,10644,10645,10646,10647,10648, #10512 10649,10650,10651,10652,10653,10654,10655,10656,4941,10657,10658,10659,2599,10660,10661,10662, #10528 10663,10664,10665,10666,3089,10667,10668,10669,10670,10671,10672,10673,10674,10675,10676,10677, #10544 10678,10679,10680,4942,10681,10682,10683,10684,10685,10686,10687,10688,10689,10690,10691,10692, #10560 10693,10694,10695,10696,10697,4485,10698,10699,10700,10701,10702,10703,10704,4943,10705,3677, #10576 10706,10707,10708,10709,10710,10711,10712,4944,10713,10714,10715,10716,10717,10718,10719,10720, #10592 10721,10722,10723,10724,10725,10726,10727,10728,4945,10729,10730,10731,10732,10733,10734,10735, #10608 10736,10737,10738,10739,10740,10741,10742,10743,10744,10745,10746,10747,10748,10749,10750,10751, #10624 10752,10753,10754,10755,10756,10757,10758,10759,10760,10761,4946,10762,10763,10764,10765,10766, #10640 10767,4947,4948,10768,10769,10770,10771,10772,10773,10774,10775,10776,10777,10778,10779,10780, #10656 10781,10782,10783,10784,10785,10786,10787,10788,10789,10790,10791,10792,10793,10794,10795,10796, #10672 10797,10798,10799,10800,10801,10802,10803,10804,10805,10806,10807,10808,10809,10810,10811,10812, #10688 10813,10814,10815,10816,10817,10818,10819,10820,10821,10822,10823,10824,10825,10826,10827,10828, #10704 10829,10830,10831,10832,10833,10834,10835,10836,10837,10838,10839,10840,10841,10842,10843,10844, #10720 10845,10846,10847,10848,10849,10850,10851,10852,10853,10854,10855,10856,10857,10858,10859,10860, #10736 10861,10862,10863,10864,10865,10866,10867,10868,10869,10870,10871,10872,10873,10874,10875,10876, #10752 10877,10878,4486,10879,10880,10881,10882,10883,10884,10885,4949,10886,10887,10888,10889,10890, #10768 10891,10892,10893,10894,10895,10896,10897,10898,10899,10900,10901,10902,10903,10904,10905,10906, #10784 10907,10908,10909,10910,10911,10912,10913,10914,10915,10916,10917,10918,10919,4487,10920,10921, #10800 10922,10923,10924,10925,10926,10927,10928,10929,10930,10931,10932,4950,10933,10934,10935,10936, #10816 10937,10938,10939,10940,10941,10942,10943,10944,10945,10946,10947,10948,10949,4488,10950,10951, #10832 10952,10953,10954,10955,10956,10957,10958,10959,4190,10960,10961,10962,10963,10964,10965,10966, #10848 10967,10968,10969,10970,10971,10972,10973,10974,10975,10976,10977,10978,10979,10980,10981,10982, #10864 10983,10984,10985,10986,10987,10988,10989,10990,10991,10992,10993,10994,10995,10996,10997,10998, #10880 10999,11000,11001,11002,11003,11004,11005,11006,3960,11007,11008,11009,11010,11011,11012,11013, #10896 11014,11015,11016,11017,11018,11019,11020,11021,11022,11023,11024,11025,11026,11027,11028,11029, #10912 11030,11031,11032,4951,11033,11034,11035,11036,11037,11038,11039,11040,11041,11042,11043,11044, #10928 11045,11046,11047,4489,11048,11049,11050,11051,4952,11052,11053,11054,11055,11056,11057,11058, #10944 4953,11059,11060,11061,11062,11063,11064,11065,11066,11067,11068,11069,11070,11071,4954,11072, #10960 11073,11074,11075,11076,11077,11078,11079,11080,11081,11082,11083,11084,11085,11086,11087,11088, #10976 11089,11090,11091,11092,11093,11094,11095,11096,11097,11098,11099,11100,11101,11102,11103,11104, #10992 11105,11106,11107,11108,11109,11110,11111,11112,11113,11114,11115,3808,11116,11117,11118,11119, #11008 11120,11121,11122,11123,11124,11125,11126,11127,11128,11129,11130,11131,11132,11133,11134,4955, #11024 11135,11136,11137,11138,11139,11140,11141,11142,11143,11144,11145,11146,11147,11148,11149,11150, #11040 11151,11152,11153,11154,11155,11156,11157,11158,11159,11160,11161,4956,11162,11163,11164,11165, #11056 11166,11167,11168,11169,11170,11171,11172,11173,11174,11175,11176,11177,11178,11179,11180,4957, #11072 11181,11182,11183,11184,11185,11186,4958,11187,11188,11189,11190,11191,11192,11193,11194,11195, #11088 11196,11197,11198,11199,11200,3678,11201,11202,11203,11204,11205,11206,4191,11207,11208,11209, #11104 11210,11211,11212,11213,11214,11215,11216,11217,11218,11219,11220,11221,11222,11223,11224,11225, #11120 11226,11227,11228,11229,11230,11231,11232,11233,11234,11235,11236,11237,11238,11239,11240,11241, #11136 11242,11243,11244,11245,11246,11247,11248,11249,11250,11251,4959,11252,11253,11254,11255,11256, #11152 11257,11258,11259,11260,11261,11262,11263,11264,11265,11266,11267,11268,11269,11270,11271,11272, #11168 11273,11274,11275,11276,11277,11278,11279,11280,11281,11282,11283,11284,11285,11286,11287,11288, #11184 11289,11290,11291,11292,11293,11294,11295,11296,11297,11298,11299,11300,11301,11302,11303,11304, #11200 11305,11306,11307,11308,11309,11310,11311,11312,11313,11314,3679,11315,11316,11317,11318,4490, #11216 11319,11320,11321,11322,11323,11324,11325,11326,11327,11328,11329,11330,11331,11332,11333,11334, #11232 11335,11336,11337,11338,11339,11340,11341,11342,11343,11344,11345,11346,11347,4960,11348,11349, #11248 11350,11351,11352,11353,11354,11355,11356,11357,11358,11359,11360,11361,11362,11363,11364,11365, #11264 11366,11367,11368,11369,11370,11371,11372,11373,11374,11375,11376,11377,3961,4961,11378,11379, #11280 11380,11381,11382,11383,11384,11385,11386,11387,11388,11389,11390,11391,11392,11393,11394,11395, #11296 11396,11397,4192,11398,11399,11400,11401,11402,11403,11404,11405,11406,11407,11408,11409,11410, #11312 11411,4962,11412,11413,11414,11415,11416,11417,11418,11419,11420,11421,11422,11423,11424,11425, #11328 11426,11427,11428,11429,11430,11431,11432,11433,11434,11435,11436,11437,11438,11439,11440,11441, #11344 11442,11443,11444,11445,11446,11447,11448,11449,11450,11451,11452,11453,11454,11455,11456,11457, #11360 11458,11459,11460,11461,11462,11463,11464,11465,11466,11467,11468,11469,4963,11470,11471,4491, #11376 11472,11473,11474,11475,4964,11476,11477,11478,11479,11480,11481,11482,11483,11484,11485,11486, #11392 11487,11488,11489,11490,11491,11492,4965,11493,11494,11495,11496,11497,11498,11499,11500,11501, #11408 11502,11503,11504,11505,11506,11507,11508,11509,11510,11511,11512,11513,11514,11515,11516,11517, #11424 11518,11519,11520,11521,11522,11523,11524,11525,11526,11527,11528,11529,3962,11530,11531,11532, #11440 11533,11534,11535,11536,11537,11538,11539,11540,11541,11542,11543,11544,11545,11546,11547,11548, #11456 11549,11550,11551,11552,11553,11554,11555,11556,11557,11558,11559,11560,11561,11562,11563,11564, #11472 4193,4194,11565,11566,11567,11568,11569,11570,11571,11572,11573,11574,11575,11576,11577,11578, #11488 11579,11580,11581,11582,11583,11584,11585,11586,11587,11588,11589,11590,11591,4966,4195,11592, #11504 11593,11594,11595,11596,11597,11598,11599,11600,11601,11602,11603,11604,3090,11605,11606,11607, #11520 11608,11609,11610,4967,11611,11612,11613,11614,11615,11616,11617,11618,11619,11620,11621,11622, #11536 11623,11624,11625,11626,11627,11628,11629,11630,11631,11632,11633,11634,11635,11636,11637,11638, #11552 11639,11640,11641,11642,11643,11644,11645,11646,11647,11648,11649,11650,11651,11652,11653,11654, #11568 11655,11656,11657,11658,11659,11660,11661,11662,11663,11664,11665,11666,11667,11668,11669,11670, #11584 11671,11672,11673,11674,4968,11675,11676,11677,11678,11679,11680,11681,11682,11683,11684,11685, #11600 11686,11687,11688,11689,11690,11691,11692,11693,3809,11694,11695,11696,11697,11698,11699,11700, #11616 11701,11702,11703,11704,11705,11706,11707,11708,11709,11710,11711,11712,11713,11714,11715,11716, #11632 11717,11718,3553,11719,11720,11721,11722,11723,11724,11725,11726,11727,11728,11729,11730,4969, #11648 11731,11732,11733,11734,11735,11736,11737,11738,11739,11740,4492,11741,11742,11743,11744,11745, #11664 11746,11747,11748,11749,11750,11751,11752,4970,11753,11754,11755,11756,11757,11758,11759,11760, #11680 11761,11762,11763,11764,11765,11766,11767,11768,11769,11770,11771,11772,11773,11774,11775,11776, #11696 11777,11778,11779,11780,11781,11782,11783,11784,11785,11786,11787,11788,11789,11790,4971,11791, #11712 11792,11793,11794,11795,11796,11797,4972,11798,11799,11800,11801,11802,11803,11804,11805,11806, #11728 11807,11808,11809,11810,4973,11811,11812,11813,11814,11815,11816,11817,11818,11819,11820,11821, #11744 11822,11823,11824,11825,11826,11827,11828,11829,11830,11831,11832,11833,11834,3680,3810,11835, #11760 11836,4974,11837,11838,11839,11840,11841,11842,11843,11844,11845,11846,11847,11848,11849,11850, #11776 11851,11852,11853,11854,11855,11856,11857,11858,11859,11860,11861,11862,11863,11864,11865,11866, #11792 11867,11868,11869,11870,11871,11872,11873,11874,11875,11876,11877,11878,11879,11880,11881,11882, #11808 11883,11884,4493,11885,11886,11887,11888,11889,11890,11891,11892,11893,11894,11895,11896,11897, #11824 11898,11899,11900,11901,11902,11903,11904,11905,11906,11907,11908,11909,11910,11911,11912,11913, #11840 11914,11915,4975,11916,11917,11918,11919,11920,11921,11922,11923,11924,11925,11926,11927,11928, #11856 11929,11930,11931,11932,11933,11934,11935,11936,11937,11938,11939,11940,11941,11942,11943,11944, #11872 11945,11946,11947,11948,11949,4976,11950,11951,11952,11953,11954,11955,11956,11957,11958,11959, #11888 11960,11961,11962,11963,11964,11965,11966,11967,11968,11969,11970,11971,11972,11973,11974,11975, #11904 11976,11977,11978,11979,11980,11981,11982,11983,11984,11985,11986,11987,4196,11988,11989,11990, #11920 11991,11992,4977,11993,11994,11995,11996,11997,11998,11999,12000,12001,12002,12003,12004,12005, #11936 12006,12007,12008,12009,12010,12011,12012,12013,12014,12015,12016,12017,12018,12019,12020,12021, #11952 12022,12023,12024,12025,12026,12027,12028,12029,12030,12031,12032,12033,12034,12035,12036,12037, #11968 12038,12039,12040,12041,12042,12043,12044,12045,12046,12047,12048,12049,12050,12051,12052,12053, #11984 12054,12055,12056,12057,12058,12059,12060,12061,4978,12062,12063,12064,12065,12066,12067,12068, #12000 12069,12070,12071,12072,12073,12074,12075,12076,12077,12078,12079,12080,12081,12082,12083,12084, #12016 12085,12086,12087,12088,12089,12090,12091,12092,12093,12094,12095,12096,12097,12098,12099,12100, #12032 12101,12102,12103,12104,12105,12106,12107,12108,12109,12110,12111,12112,12113,12114,12115,12116, #12048 12117,12118,12119,12120,12121,12122,12123,4979,12124,12125,12126,12127,12128,4197,12129,12130, #12064 12131,12132,12133,12134,12135,12136,12137,12138,12139,12140,12141,12142,12143,12144,12145,12146, #12080 12147,12148,12149,12150,12151,12152,12153,12154,4980,12155,12156,12157,12158,12159,12160,4494, #12096 12161,12162,12163,12164,3811,12165,12166,12167,12168,12169,4495,12170,12171,4496,12172,12173, #12112 12174,12175,12176,3812,12177,12178,12179,12180,12181,12182,12183,12184,12185,12186,12187,12188, #12128 12189,12190,12191,12192,12193,12194,12195,12196,12197,12198,12199,12200,12201,12202,12203,12204, #12144 12205,12206,12207,12208,12209,12210,12211,12212,12213,12214,12215,12216,12217,12218,12219,12220, #12160 12221,4981,12222,12223,12224,12225,12226,12227,12228,12229,12230,12231,12232,12233,12234,12235, #12176 4982,12236,12237,12238,12239,12240,12241,12242,12243,12244,12245,4983,12246,12247,12248,12249, #12192 4984,12250,12251,12252,12253,12254,12255,12256,12257,12258,12259,12260,12261,12262,12263,12264, #12208 4985,12265,4497,12266,12267,12268,12269,12270,12271,12272,12273,12274,12275,12276,12277,12278, #12224 12279,12280,12281,12282,12283,12284,12285,12286,12287,4986,12288,12289,12290,12291,12292,12293, #12240 12294,12295,12296,2473,12297,12298,12299,12300,12301,12302,12303,12304,12305,12306,12307,12308, #12256 12309,12310,12311,12312,12313,12314,12315,12316,12317,12318,12319,3963,12320,12321,12322,12323, #12272 12324,12325,12326,12327,12328,12329,12330,12331,12332,4987,12333,12334,12335,12336,12337,12338, #12288 12339,12340,12341,12342,12343,12344,12345,12346,12347,12348,12349,12350,12351,12352,12353,12354, #12304 12355,12356,12357,12358,12359,3964,12360,12361,12362,12363,12364,12365,12366,12367,12368,12369, #12320 12370,3965,12371,12372,12373,12374,12375,12376,12377,12378,12379,12380,12381,12382,12383,12384, #12336 12385,12386,12387,12388,12389,12390,12391,12392,12393,12394,12395,12396,12397,12398,12399,12400, #12352 12401,12402,12403,12404,12405,12406,12407,12408,4988,12409,12410,12411,12412,12413,12414,12415, #12368 12416,12417,12418,12419,12420,12421,12422,12423,12424,12425,12426,12427,12428,12429,12430,12431, #12384 12432,12433,12434,12435,12436,12437,12438,3554,12439,12440,12441,12442,12443,12444,12445,12446, #12400 12447,12448,12449,12450,12451,12452,12453,12454,12455,12456,12457,12458,12459,12460,12461,12462, #12416 12463,12464,4989,12465,12466,12467,12468,12469,12470,12471,12472,12473,12474,12475,12476,12477, #12432 12478,12479,12480,4990,12481,12482,12483,12484,12485,12486,12487,12488,12489,4498,12490,12491, #12448 12492,12493,12494,12495,12496,12497,12498,12499,12500,12501,12502,12503,12504,12505,12506,12507, #12464 12508,12509,12510,12511,12512,12513,12514,12515,12516,12517,12518,12519,12520,12521,12522,12523, #12480 12524,12525,12526,12527,12528,12529,12530,12531,12532,12533,12534,12535,12536,12537,12538,12539, #12496 12540,12541,12542,12543,12544,12545,12546,12547,12548,12549,12550,12551,4991,12552,12553,12554, #12512 12555,12556,12557,12558,12559,12560,12561,12562,12563,12564,12565,12566,12567,12568,12569,12570, #12528 12571,12572,12573,12574,12575,12576,12577,12578,3036,12579,12580,12581,12582,12583,3966,12584, #12544 12585,12586,12587,12588,12589,12590,12591,12592,12593,12594,12595,12596,12597,12598,12599,12600, #12560 12601,12602,12603,12604,12605,12606,12607,12608,12609,12610,12611,12612,12613,12614,12615,12616, #12576 12617,12618,12619,12620,12621,12622,12623,12624,12625,12626,12627,12628,12629,12630,12631,12632, #12592 12633,12634,12635,12636,12637,12638,12639,12640,12641,12642,12643,12644,12645,12646,4499,12647, #12608 12648,12649,12650,12651,12652,12653,12654,12655,12656,12657,12658,12659,12660,12661,12662,12663, #12624 12664,12665,12666,12667,12668,12669,12670,12671,12672,12673,12674,12675,12676,12677,12678,12679, #12640 12680,12681,12682,12683,12684,12685,12686,12687,12688,12689,12690,12691,12692,12693,12694,12695, #12656 12696,12697,12698,4992,12699,12700,12701,12702,12703,12704,12705,12706,12707,12708,12709,12710, #12672 12711,12712,12713,12714,12715,12716,12717,12718,12719,12720,12721,12722,12723,12724,12725,12726, #12688 12727,12728,12729,12730,12731,12732,12733,12734,12735,12736,12737,12738,12739,12740,12741,12742, #12704 12743,12744,12745,12746,12747,12748,12749,12750,12751,12752,12753,12754,12755,12756,12757,12758, #12720 12759,12760,12761,12762,12763,12764,12765,12766,12767,12768,12769,12770,12771,12772,12773,12774, #12736 12775,12776,12777,12778,4993,2175,12779,12780,12781,12782,12783,12784,12785,12786,4500,12787, #12752 12788,12789,12790,12791,12792,12793,12794,12795,12796,12797,12798,12799,12800,12801,12802,12803, #12768 12804,12805,12806,12807,12808,12809,12810,12811,12812,12813,12814,12815,12816,12817,12818,12819, #12784 12820,12821,12822,12823,12824,12825,12826,4198,3967,12827,12828,12829,12830,12831,12832,12833, #12800 12834,12835,12836,12837,12838,12839,12840,12841,12842,12843,12844,12845,12846,12847,12848,12849, #12816 12850,12851,12852,12853,12854,12855,12856,12857,12858,12859,12860,12861,4199,12862,12863,12864, #12832 12865,12866,12867,12868,12869,12870,12871,12872,12873,12874,12875,12876,12877,12878,12879,12880, #12848 12881,12882,12883,12884,12885,12886,12887,4501,12888,12889,12890,12891,12892,12893,12894,12895, #12864 12896,12897,12898,12899,12900,12901,12902,12903,12904,12905,12906,12907,12908,12909,12910,12911, #12880 12912,4994,12913,12914,12915,12916,12917,12918,12919,12920,12921,12922,12923,12924,12925,12926, #12896 12927,12928,12929,12930,12931,12932,12933,12934,12935,12936,12937,12938,12939,12940,12941,12942, #12912 12943,12944,12945,12946,12947,12948,12949,12950,12951,12952,12953,12954,12955,12956,1772,12957, #12928 12958,12959,12960,12961,12962,12963,12964,12965,12966,12967,12968,12969,12970,12971,12972,12973, #12944 12974,12975,12976,12977,12978,12979,12980,12981,12982,12983,12984,12985,12986,12987,12988,12989, #12960 12990,12991,12992,12993,12994,12995,12996,12997,4502,12998,4503,12999,13000,13001,13002,13003, #12976 4504,13004,13005,13006,13007,13008,13009,13010,13011,13012,13013,13014,13015,13016,13017,13018, #12992 13019,13020,13021,13022,13023,13024,13025,13026,13027,13028,13029,3449,13030,13031,13032,13033, #13008 13034,13035,13036,13037,13038,13039,13040,13041,13042,13043,13044,13045,13046,13047,13048,13049, #13024 13050,13051,13052,13053,13054,13055,13056,13057,13058,13059,13060,13061,13062,13063,13064,13065, #13040 13066,13067,13068,13069,13070,13071,13072,13073,13074,13075,13076,13077,13078,13079,13080,13081, #13056 13082,13083,13084,13085,13086,13087,13088,13089,13090,13091,13092,13093,13094,13095,13096,13097, #13072 13098,13099,13100,13101,13102,13103,13104,13105,13106,13107,13108,13109,13110,13111,13112,13113, #13088 13114,13115,13116,13117,13118,3968,13119,4995,13120,13121,13122,13123,13124,13125,13126,13127, #13104 4505,13128,13129,13130,13131,13132,13133,13134,4996,4506,13135,13136,13137,13138,13139,4997, #13120 13140,13141,13142,13143,13144,13145,13146,13147,13148,13149,13150,13151,13152,13153,13154,13155, #13136 13156,13157,13158,13159,4998,13160,13161,13162,13163,13164,13165,13166,13167,13168,13169,13170, #13152 13171,13172,13173,13174,13175,13176,4999,13177,13178,13179,13180,13181,13182,13183,13184,13185, #13168 13186,13187,13188,13189,13190,13191,13192,13193,13194,13195,13196,13197,13198,13199,13200,13201, #13184 13202,13203,13204,13205,13206,5000,13207,13208,13209,13210,13211,13212,13213,13214,13215,13216, #13200 13217,13218,13219,13220,13221,13222,13223,13224,13225,13226,13227,4200,5001,13228,13229,13230, #13216 13231,13232,13233,13234,13235,13236,13237,13238,13239,13240,3969,13241,13242,13243,13244,3970, #13232 13245,13246,13247,13248,13249,13250,13251,13252,13253,13254,13255,13256,13257,13258,13259,13260, #13248 13261,13262,13263,13264,13265,13266,13267,13268,3450,13269,13270,13271,13272,13273,13274,13275, #13264 13276,5002,13277,13278,13279,13280,13281,13282,13283,13284,13285,13286,13287,13288,13289,13290, #13280 13291,13292,13293,13294,13295,13296,13297,13298,13299,13300,13301,13302,3813,13303,13304,13305, #13296 13306,13307,13308,13309,13310,13311,13312,13313,13314,13315,13316,13317,13318,13319,13320,13321, #13312 13322,13323,13324,13325,13326,13327,13328,4507,13329,13330,13331,13332,13333,13334,13335,13336, #13328 13337,13338,13339,13340,13341,5003,13342,13343,13344,13345,13346,13347,13348,13349,13350,13351, #13344 13352,13353,13354,13355,13356,13357,13358,13359,13360,13361,13362,13363,13364,13365,13366,13367, #13360 5004,13368,13369,13370,13371,13372,13373,13374,13375,13376,13377,13378,13379,13380,13381,13382, #13376 13383,13384,13385,13386,13387,13388,13389,13390,13391,13392,13393,13394,13395,13396,13397,13398, #13392 13399,13400,13401,13402,13403,13404,13405,13406,13407,13408,13409,13410,13411,13412,13413,13414, #13408 13415,13416,13417,13418,13419,13420,13421,13422,13423,13424,13425,13426,13427,13428,13429,13430, #13424 13431,13432,4508,13433,13434,13435,4201,13436,13437,13438,13439,13440,13441,13442,13443,13444, #13440 13445,13446,13447,13448,13449,13450,13451,13452,13453,13454,13455,13456,13457,5005,13458,13459, #13456 13460,13461,13462,13463,13464,13465,13466,13467,13468,13469,13470,4509,13471,13472,13473,13474, #13472 13475,13476,13477,13478,13479,13480,13481,13482,13483,13484,13485,13486,13487,13488,13489,13490, #13488 13491,13492,13493,13494,13495,13496,13497,13498,13499,13500,13501,13502,13503,13504,13505,13506, #13504 13507,13508,13509,13510,13511,13512,13513,13514,13515,13516,13517,13518,13519,13520,13521,13522, #13520 13523,13524,13525,13526,13527,13528,13529,13530,13531,13532,13533,13534,13535,13536,13537,13538, #13536 13539,13540,13541,13542,13543,13544,13545,13546,13547,13548,13549,13550,13551,13552,13553,13554, #13552 13555,13556,13557,13558,13559,13560,13561,13562,13563,13564,13565,13566,13567,13568,13569,13570, #13568 13571,13572,13573,13574,13575,13576,13577,13578,13579,13580,13581,13582,13583,13584,13585,13586, #13584 13587,13588,13589,13590,13591,13592,13593,13594,13595,13596,13597,13598,13599,13600,13601,13602, #13600 13603,13604,13605,13606,13607,13608,13609,13610,13611,13612,13613,13614,13615,13616,13617,13618, #13616 13619,13620,13621,13622,13623,13624,13625,13626,13627,13628,13629,13630,13631,13632,13633,13634, #13632 13635,13636,13637,13638,13639,13640,13641,13642,5006,13643,13644,13645,13646,13647,13648,13649, #13648 13650,13651,5007,13652,13653,13654,13655,13656,13657,13658,13659,13660,13661,13662,13663,13664, #13664 13665,13666,13667,13668,13669,13670,13671,13672,13673,13674,13675,13676,13677,13678,13679,13680, #13680 13681,13682,13683,13684,13685,13686,13687,13688,13689,13690,13691,13692,13693,13694,13695,13696, #13696 13697,13698,13699,13700,13701,13702,13703,13704,13705,13706,13707,13708,13709,13710,13711,13712, #13712 13713,13714,13715,13716,13717,13718,13719,13720,13721,13722,13723,13724,13725,13726,13727,13728, #13728 13729,13730,13731,13732,13733,13734,13735,13736,13737,13738,13739,13740,13741,13742,13743,13744, #13744 13745,13746,13747,13748,13749,13750,13751,13752,13753,13754,13755,13756,13757,13758,13759,13760, #13760 13761,13762,13763,13764,13765,13766,13767,13768,13769,13770,13771,13772,13773,13774,3273,13775, #13776 13776,13777,13778,13779,13780,13781,13782,13783,13784,13785,13786,13787,13788,13789,13790,13791, #13792 13792,13793,13794,13795,13796,13797,13798,13799,13800,13801,13802,13803,13804,13805,13806,13807, #13808 13808,13809,13810,13811,13812,13813,13814,13815,13816,13817,13818,13819,13820,13821,13822,13823, #13824 13824,13825,13826,13827,13828,13829,13830,13831,13832,13833,13834,13835,13836,13837,13838,13839, #13840 13840,13841,13842,13843,13844,13845,13846,13847,13848,13849,13850,13851,13852,13853,13854,13855, #13856 13856,13857,13858,13859,13860,13861,13862,13863,13864,13865,13866,13867,13868,13869,13870,13871, #13872 13872,13873,13874,13875,13876,13877,13878,13879,13880,13881,13882,13883,13884,13885,13886,13887, #13888 13888,13889,13890,13891,13892,13893,13894,13895,13896,13897,13898,13899,13900,13901,13902,13903, #13904 13904,13905,13906,13907,13908,13909,13910,13911,13912,13913,13914,13915,13916,13917,13918,13919, #13920 13920,13921,13922,13923,13924,13925,13926,13927,13928,13929,13930,13931,13932,13933,13934,13935, #13936 13936,13937,13938,13939,13940,13941,13942,13943,13944,13945,13946,13947,13948,13949,13950,13951, #13952 13952,13953,13954,13955,13956,13957,13958,13959,13960,13961,13962,13963,13964,13965,13966,13967, #13968 13968,13969,13970,13971,13972) #13973 # flake8: noqa
mit
trivoldus28/pulsarch-verilog
tools/local/bas-release/bas,3.9-SunOS-i386/lib/python/lib/python2.4/lib-old/fmt.py
9
18532
# Text formatting abstractions # Note -- this module is obsolete, it's too slow anyway import string import Para # A formatter back-end object has one method that is called by the formatter: # addpara(p), where p is a paragraph object. For example: # Formatter back-end to do nothing at all with the paragraphs class NullBackEnd: # def __init__(self): pass # def addpara(self, p): pass # def bgn_anchor(self, id): pass # def end_anchor(self, id): pass # Formatter back-end to collect the paragraphs in a list class SavingBackEnd(NullBackEnd): # def __init__(self): self.paralist = [] # def addpara(self, p): self.paralist.append(p) # def hitcheck(self, h, v): hits = [] for p in self.paralist: if p.top <= v <= p.bottom: for id in p.hitcheck(h, v): if id not in hits: hits.append(id) return hits # def extract(self): text = '' for p in self.paralist: text = text + (p.extract()) return text # def extractpart(self, long1, long2): if long1 > long2: long1, long2 = long2, long1 para1, pos1 = long1 para2, pos2 = long2 text = '' while para1 < para2: ptext = self.paralist[para1].extract() text = text + ptext[pos1:] pos1 = 0 para1 = para1 + 1 ptext = self.paralist[para2].extract() return text + ptext[pos1:pos2] # def whereis(self, d, h, v): total = 0 for i in range(len(self.paralist)): p = self.paralist[i] result = p.whereis(d, h, v) if result is not None: return i, result return None # def roundtowords(self, long1, long2): i, offset = long1 text = self.paralist[i].extract() while offset > 0 and text[offset-1] != ' ': offset = offset-1 long1 = i, offset # i, offset = long2 text = self.paralist[i].extract() n = len(text) while offset < n-1 and text[offset] != ' ': offset = offset+1 long2 = i, offset # return long1, long2 # def roundtoparagraphs(self, long1, long2): long1 = long1[0], 0 long2 = long2[0], len(self.paralist[long2[0]].extract()) return long1, long2 # Formatter back-end to send the text directly to the drawing object class WritingBackEnd(NullBackEnd): # def __init__(self, d, width): self.d = d self.width = width self.lineno = 0 # def addpara(self, p): self.lineno = p.render(self.d, 0, self.lineno, self.width) # A formatter receives a stream of formatting instructions and assembles # these into a stream of paragraphs on to a back-end. The assembly is # parametrized by a text measurement object, which must match the output # operations of the back-end. The back-end is responsible for splitting # paragraphs up in lines of a given maximum width. (This is done because # in a windowing environment, when the window size changes, there is no # need to redo the assembly into paragraphs, but the splitting into lines # must be done taking the new window size into account.) # Formatter base class. Initialize it with a text measurement object, # which is used for text measurements, and a back-end object, # which receives the completed paragraphs. The formatting methods are: # setfont(font) # setleftindent(nspaces) # setjust(type) where type is 'l', 'c', 'r', or 'lr' # flush() # vspace(nlines) # needvspace(nlines) # addword(word, nspaces) class BaseFormatter: # def __init__(self, d, b): # Drawing object used for text measurements self.d = d # # BackEnd object receiving completed paragraphs self.b = b # # Parameters of the formatting model self.leftindent = 0 self.just = 'l' self.font = None self.blanklines = 0 # # Parameters derived from the current font self.space = d.textwidth(' ') self.line = d.lineheight() self.ascent = d.baseline() self.descent = self.line - self.ascent # # Parameter derived from the default font self.n_space = self.space # # Current paragraph being built self.para = None self.nospace = 1 # # Font to set on the next word self.nextfont = None # def newpara(self): return Para.Para() # def setfont(self, font): if font is None: return self.font = self.nextfont = font d = self.d d.setfont(font) self.space = d.textwidth(' ') self.line = d.lineheight() self.ascent = d.baseline() self.descent = self.line - self.ascent # def setleftindent(self, nspaces): self.leftindent = int(self.n_space * nspaces) if self.para: hang = self.leftindent - self.para.indent_left if hang > 0 and self.para.getlength() <= hang: self.para.makehangingtag(hang) self.nospace = 1 else: self.flush() # def setrightindent(self, nspaces): self.rightindent = int(self.n_space * nspaces) if self.para: self.para.indent_right = self.rightindent self.flush() # def setjust(self, just): self.just = just if self.para: self.para.just = self.just # def flush(self): if self.para: self.b.addpara(self.para) self.para = None if self.font is not None: self.d.setfont(self.font) self.nospace = 1 # def vspace(self, nlines): self.flush() if nlines > 0: self.para = self.newpara() tuple = None, '', 0, 0, 0, int(nlines*self.line), 0 self.para.words.append(tuple) self.flush() self.blanklines = self.blanklines + nlines # def needvspace(self, nlines): self.flush() # Just to be sure if nlines > self.blanklines: self.vspace(nlines - self.blanklines) # def addword(self, text, space): if self.nospace and not text: return self.nospace = 0 self.blanklines = 0 if not self.para: self.para = self.newpara() self.para.indent_left = self.leftindent self.para.just = self.just self.nextfont = self.font space = int(space * self.space) self.para.words.append((self.nextfont, text, self.d.textwidth(text), space, space, self.ascent, self.descent)) self.nextfont = None # def bgn_anchor(self, id): if not self.para: self.nospace = 0 self.addword('', 0) self.para.bgn_anchor(id) # def end_anchor(self, id): if not self.para: self.nospace = 0 self.addword('', 0) self.para.end_anchor(id) # Measuring object for measuring text as viewed on a tty class NullMeasurer: # def __init__(self): pass # def setfont(self, font): pass # def textwidth(self, text): return len(text) # def lineheight(self): return 1 # def baseline(self): return 0 # Drawing object for writing plain ASCII text to a file class FileWriter: # def __init__(self, fp): self.fp = fp self.lineno, self.colno = 0, 0 # def setfont(self, font): pass # def text(self, (h, v), str): if not str: return if '\n' in str: raise ValueError, 'can\'t write \\n' while self.lineno < v: self.fp.write('\n') self.colno, self.lineno = 0, self.lineno + 1 while self.lineno > v: # XXX This should never happen... self.fp.write('\033[A') # ANSI up arrow self.lineno = self.lineno - 1 if self.colno < h: self.fp.write(' ' * (h - self.colno)) elif self.colno > h: self.fp.write('\b' * (self.colno - h)) self.colno = h self.fp.write(str) self.colno = h + len(str) # Formatting class to do nothing at all with the data class NullFormatter(BaseFormatter): # def __init__(self): d = NullMeasurer() b = NullBackEnd() BaseFormatter.__init__(self, d, b) # Formatting class to write directly to a file class WritingFormatter(BaseFormatter): # def __init__(self, fp, width): dm = NullMeasurer() dw = FileWriter(fp) b = WritingBackEnd(dw, width) BaseFormatter.__init__(self, dm, b) self.blanklines = 1 # # Suppress multiple blank lines def needvspace(self, nlines): BaseFormatter.needvspace(self, min(1, nlines)) # A "FunnyFormatter" writes ASCII text with a twist: *bold words*, # _italic text_ and _underlined words_, and `quoted text'. # It assumes that the fonts are 'r', 'i', 'b', 'u', 'q': (roman, # italic, bold, underline, quote). # Moreover, if the font is in upper case, the text is converted to # UPPER CASE. class FunnyFormatter(WritingFormatter): # def flush(self): if self.para: finalize(self.para) WritingFormatter.flush(self) # Surrounds *bold words* and _italic text_ in a paragraph with # appropriate markers, fixing the size (assuming these characters' # width is 1). openchar = \ {'b':'*', 'i':'_', 'u':'_', 'q':'`', 'B':'*', 'I':'_', 'U':'_', 'Q':'`'} closechar = \ {'b':'*', 'i':'_', 'u':'_', 'q':'\'', 'B':'*', 'I':'_', 'U':'_', 'Q':'\''} def finalize(para): oldfont = curfont = 'r' para.words.append(('r', '', 0, 0, 0, 0)) # temporary, deleted at end for i in range(len(para.words)): fo, te, wi = para.words[i][:3] if fo is not None: curfont = fo if curfont != oldfont: if closechar.has_key(oldfont): c = closechar[oldfont] j = i-1 while j > 0 and para.words[j][1] == '': j = j-1 fo1, te1, wi1 = para.words[j][:3] te1 = te1 + c wi1 = wi1 + len(c) para.words[j] = (fo1, te1, wi1) + \ para.words[j][3:] if openchar.has_key(curfont) and te: c = openchar[curfont] te = c + te wi = len(c) + wi para.words[i] = (fo, te, wi) + \ para.words[i][3:] if te: oldfont = curfont else: oldfont = 'r' if curfont in string.uppercase: te = string.upper(te) para.words[i] = (fo, te, wi) + para.words[i][3:] del para.words[-1] # Formatter back-end to draw the text in a window. # This has an option to draw while the paragraphs are being added, # to minimize the delay before the user sees anything. # This manages the entire "document" of the window. class StdwinBackEnd(SavingBackEnd): # def __init__(self, window, drawnow): self.window = window self.drawnow = drawnow self.width = window.getwinsize()[0] self.selection = None self.height = 0 window.setorigin(0, 0) window.setdocsize(0, 0) self.d = window.begindrawing() SavingBackEnd.__init__(self) # def finish(self): self.d.close() self.d = None self.window.setdocsize(0, self.height) # def addpara(self, p): self.paralist.append(p) if self.drawnow: self.height = \ p.render(self.d, 0, self.height, self.width) else: p.layout(self.width) p.left = 0 p.top = self.height p.right = self.width p.bottom = self.height + p.height self.height = p.bottom # def resize(self): self.window.change((0, 0), (self.width, self.height)) self.width = self.window.getwinsize()[0] self.height = 0 for p in self.paralist: p.layout(self.width) p.left = 0 p.top = self.height p.right = self.width p.bottom = self.height + p.height self.height = p.bottom self.window.change((0, 0), (self.width, self.height)) self.window.setdocsize(0, self.height) # def redraw(self, area): d = self.window.begindrawing() (left, top), (right, bottom) = area d.erase(area) d.cliprect(area) for p in self.paralist: if top < p.bottom and p.top < bottom: v = p.render(d, p.left, p.top, p.right) if self.selection: self.invert(d, self.selection) d.close() # def setselection(self, new): if new: long1, long2 = new pos1 = long1[:3] pos2 = long2[:3] new = pos1, pos2 if new != self.selection: d = self.window.begindrawing() if self.selection: self.invert(d, self.selection) if new: self.invert(d, new) d.close() self.selection = new # def getselection(self): return self.selection # def extractselection(self): if self.selection: a, b = self.selection return self.extractpart(a, b) else: return None # def invert(self, d, region): long1, long2 = region if long1 > long2: long1, long2 = long2, long1 para1, pos1 = long1 para2, pos2 = long2 while para1 < para2: self.paralist[para1].invert(d, pos1, None) pos1 = None para1 = para1 + 1 self.paralist[para2].invert(d, pos1, pos2) # def search(self, prog): import re, string if type(prog) is type(''): prog = re.compile(string.lower(prog)) if self.selection: iold = self.selection[0][0] else: iold = -1 hit = None for i in range(len(self.paralist)): if i == iold or i < iold and hit: continue p = self.paralist[i] text = string.lower(p.extract()) match = prog.search(text) if match: a, b = match.group(0) long1 = i, a long2 = i, b hit = long1, long2 if i > iold: break if hit: self.setselection(hit) i = hit[0][0] p = self.paralist[i] self.window.show((p.left, p.top), (p.right, p.bottom)) return 1 else: return 0 # def showanchor(self, id): for i in range(len(self.paralist)): p = self.paralist[i] if p.hasanchor(id): long1 = i, 0 long2 = i, len(p.extract()) hit = long1, long2 self.setselection(hit) self.window.show( (p.left, p.top), (p.right, p.bottom)) break # GL extensions class GLFontCache: # def __init__(self): self.reset() self.setfont('') # def reset(self): self.fontkey = None self.fonthandle = None self.fontinfo = None self.fontcache = {} # def close(self): self.reset() # def setfont(self, fontkey): if fontkey == '': fontkey = 'Times-Roman 12' elif ' ' not in fontkey: fontkey = fontkey + ' 12' if fontkey == self.fontkey: return if self.fontcache.has_key(fontkey): handle = self.fontcache[fontkey] else: import string i = string.index(fontkey, ' ') name, sizestr = fontkey[:i], fontkey[i:] size = eval(sizestr) key1 = name + ' 1' key = name + ' ' + `size` # NB key may differ from fontkey! if self.fontcache.has_key(key): handle = self.fontcache[key] else: if self.fontcache.has_key(key1): handle = self.fontcache[key1] else: import fm handle = fm.findfont(name) self.fontcache[key1] = handle handle = handle.scalefont(size) self.fontcache[fontkey] = \ self.fontcache[key] = handle self.fontkey = fontkey if self.fonthandle != handle: self.fonthandle = handle self.fontinfo = handle.getfontinfo() handle.setfont() class GLMeasurer(GLFontCache): # def textwidth(self, text): return self.fonthandle.getstrwidth(text) # def baseline(self): return self.fontinfo[6] - self.fontinfo[3] # def lineheight(self): return self.fontinfo[6] class GLWriter(GLFontCache): # # NOTES: # (1) Use gl.ortho2 to use X pixel coordinates! # def text(self, (h, v), text): import gl, fm gl.cmov2i(h, v + self.fontinfo[6] - self.fontinfo[3]) fm.prstr(text) # def setfont(self, fontkey): oldhandle = self.fonthandle GLFontCache.setfont(fontkey) if self.fonthandle != oldhandle: handle.setfont() class GLMeasurerWriter(GLMeasurer, GLWriter): pass class GLBackEnd(SavingBackEnd): # def __init__(self, wid): import gl gl.winset(wid) self.wid = wid self.width = gl.getsize()[1] self.height = 0 self.d = GLMeasurerWriter() SavingBackEnd.__init__(self) # def finish(self): pass # def addpara(self, p): self.paralist.append(p) self.height = p.render(self.d, 0, self.height, self.width) # def redraw(self): import gl gl.winset(self.wid) width = gl.getsize()[1] if width != self.width: setdocsize = 1 self.width = width for p in self.paralist: p.top = p.bottom = None d = self.d v = 0 for p in self.paralist: v = p.render(d, 0, v, width)
gpl-2.0
LTHeaven/PokemonGo-Map
pogom/pgoapi/auth_ptc.py
3
3552
""" pgoapi - Pokemon Go API Copyright (c) 2016 tjado <https://github.com/tejado> 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. Author: tjado <https://github.com/tejado> """ import re import json import logging import requests from auth import Auth class AuthPtc(Auth): PTC_LOGIN_URL = 'https://sso.pokemon.com/sso/login?service=https%3A%2F%2Fsso.pokemon.com%2Fsso%2Foauth2.0%2FcallbackAuthorize' PTC_LOGIN_OAUTH = 'https://sso.pokemon.com/sso/oauth2.0/accessToken' PTC_LOGIN_CLIENT_SECRET = 'w8ScCUXJQc6kXKw8FiOhd8Fixzht18Dq3PEVkUCP5ZPxtgyWsbTvWHFLm2wNY0JR' def __init__(self): Auth.__init__(self) self._auth_provider = 'ptc' self._session = requests.session() self._session.verify = True def login(self, username, password): self.log.info('PTC login for: %s', username) head = {'User-Agent': 'niantic'} r = self._session.get(self.PTC_LOGIN_URL, headers=head) jdata = json.loads(r.content) data = { 'lt': jdata['lt'], 'execution': jdata['execution'], '_eventId': 'submit', 'username': username, 'password': password[:15], } r1 = self._session.post(self.PTC_LOGIN_URL, data=data, headers=head) ticket = None try: ticket = re.sub('.*ticket=', '', r1.history[0].headers['Location']) except Exception,e: try: self.log.error('Could not retrieve token: %s', r1.json()['errors'][0]) except Exception as e: self.log.error('Could not retrieve token! (%s)', str(e)) return False data1 = { 'client_id': 'mobile-app_pokemon-go', 'redirect_uri': 'https://www.nianticlabs.com/pokemongo/error', 'client_secret': self.PTC_LOGIN_CLIENT_SECRET, 'grant_type': 'refresh_token', 'code': ticket, } r2 = self._session.post(self.PTC_LOGIN_OAUTH, data=data1) access_token = re.sub('&expires.*', '', r2.content) access_token = re.sub('.*access_token=', '', access_token) if '-sso.pokemon.com' in access_token: self.log.info('PTC Login successful') self.log.debug('PTC Session Token: %s', access_token[:25]) self._auth_token = access_token else: self.log.info('Seems not to be a PTC Session Token... login failed :(') return False self._login = True return True
mit
andresailer/DIRAC
Core/scripts/dirac-info.py
2
2553
#!/usr/bin/env python ######################################################################## # File : dirac-info # Author : Andrei Tsaregorodtsev ######################################################################## """ Report info about local DIRAC installation """ __RCSID__ = "$Id$" import os import DIRAC from DIRAC import gConfig from DIRAC.Core.Base import Script from DIRAC.Core.Security.ProxyInfo import getProxyInfo from DIRAC.ConfigurationSystem.Client.Helpers.Registry import getVOForGroup from DIRAC.Core.Utilities.PrettyPrint import printTable Script.setUsageMessage('\n'.join([__doc__.split('\n')[1], 'Usage:', ' %s [option|cfgfile] ... Site' % Script.scriptName, ])) Script.parseCommandLine(ignoreErrors=True) args = Script.getPositionalArgs() records = [] records.append(('Setup', gConfig.getValue('/DIRAC/Setup', 'Unknown'))) records.append(('ConfigurationServer', gConfig.getValue('/DIRAC/Configuration/Servers', []))) records.append(('Installation path', DIRAC.rootPath)) if os.path.exists(os.path.join(DIRAC.rootPath, DIRAC.getPlatform(), 'bin', 'mysql')): records.append(('Installation type', 'server')) else: records.append(('Installation type', 'client')) records.append(('Platform', DIRAC.getPlatform())) ret = getProxyInfo(disableVOMS=True) if ret['OK']: if 'group' in ret['Value']: vo = getVOForGroup(ret['Value']['group']) else: vo = getVOForGroup('') if not vo: vo = "None" records.append(('VirtualOrganization', vo)) if 'identity' in ret['Value']: records.append(('User DN', ret['Value']['identity'])) if 'secondsLeft' in ret['Value']: records.append(('Proxy validity, secs', {'Value': str(ret['Value']['secondsLeft']), 'Just': 'L'})) if gConfig.getValue('/DIRAC/Security/UseServerCertificate', True): records.append(('Use Server Certificate', 'Yes')) else: records.append(('Use Server Certificate', 'No')) if gConfig.getValue('/DIRAC/Security/SkipCAChecks', False): records.append(('Skip CA Checks', 'Yes')) else: records.append(('Skip CA Checks', 'No')) try: import gfalthr # pylint: disable=import-error records.append(('gfal version', gfalthr.gfal_version())) except BaseException: pass try: import lcg_util # pylint: disable=import-error records.append(('lcg_util version', lcg_util.lcg_util_version())) except BaseException: pass records.append(('DIRAC version', DIRAC.version)) fields = ['Option', 'Value'] print printTable(fields, records, numbering=False) print
gpl-3.0
giovtorres/docker-centos7-slurm
tests/test_dockerfile.py
1
2157
import subprocess import time import pytest import testinfra @pytest.fixture(scope="session") def host(request): test_image = "docker-centos7-slurm:spec-test" subprocess.check_call(["docker", "build", "-t", test_image, "."]) docker_id = subprocess.check_output( ["docker", "run", "-d", "-it", "-h", "ernie", test_image] ).decode().strip() yield testinfra.get_host("docker://" + docker_id) subprocess.check_call(["docker", "rm", "-f", docker_id]) @pytest.fixture def Slow(): def slow(check, timeout=30): timeout_at = time.time() + timeout while True: try: assert check() except AssertionError as e: if time.time() < timeout_at: time.sleep(1) else: raise e else: return return slow def test_tini_is_installed(host): cmd = host.run("tini --version") assert "0.18.0" in cmd.stdout def test_slurm_user_group_exists(host): assert host.group("slurm").exists assert host.user("slurm").group == "slurm" @pytest.mark.parametrize("version, semver", [ ("3.5", "3.5.6"), ("3.6", "3.6.8"), ("3.7", "3.7.5"), ("3.8", "3.8.0") ]) def test_python_is_installed(host, version, semver): cmd = host.run(f"python{version} --version") assert semver in cmd.stdout def test_mariadb_is_listening(host, Slow): Slow(lambda: host.socket("tcp://3306").is_listening) @pytest.mark.parametrize("filename", ["slurm.conf", "slurmdbd.conf"]) def test_slurm_config_exists(host, filename): assert host.file(f"/etc/slurm/{filename}").exists assert host.file(f"/etc/slurm/{filename}").is_file def test_slurmd_is_listening(host, Slow): Slow(lambda: host.socket("tcp://6817").is_listening) def test_slurmdbd_is_listening(host, Slow): Slow(lambda: host.socket("tcp://6818").is_listening) def test_slurmctld_is_listening(host, Slow): Slow(lambda: host.socket("tcp://6819").is_listening) def test_slurmd_version(host): cmd = host.run("scontrol show config | grep SLURM_VERSION") assert "19.05.4" in cmd.stdout
mit
datalogics/scons
test/CVS.py
2
10521
#!/usr/bin/env python # # __COPYRIGHT__ # # 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. # __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" """ Test fetching source files from CVS. """ import os import os.path import TestSCons test = TestSCons.TestSCons() cvs = test.where_is('cvs') if not cvs: test.skip_test("Could not find 'cvs'; skipping test(s).\n") test.subdir('CVS', 'import', ['import', 'sub'], 'work1', 'work2') foo_aaa_in = os.path.join('foo', 'aaa.in') foo_bbb_in = os.path.join('foo', 'bbb.in') foo_ccc_in = os.path.join('foo', 'ccc.in') foo_sub_ddd_in = os.path.join('foo', 'sub', 'ddd.in') foo_sub_ddd_out = os.path.join('foo', 'sub', 'ddd.out') foo_sub_eee_in = os.path.join('foo', 'sub', 'eee.in') foo_sub_eee_out = os.path.join('foo', 'sub', 'eee.out') foo_sub_fff_in = os.path.join('foo', 'sub', 'fff.in') foo_sub_fff_out = os.path.join('foo', 'sub', 'fff.out') foo_sub_all = os.path.join('foo', 'sub', 'all') sub_SConscript = os.path.join('sub', 'SConscript') sub_ddd_in = os.path.join('sub', 'ddd.in') sub_ddd_out = os.path.join('sub', 'ddd.out') sub_eee_in = os.path.join('sub', 'eee.in') sub_eee_out = os.path.join('sub', 'eee.out') sub_fff_in = os.path.join('sub', 'fff.in') sub_fff_out = os.path.join('sub', 'fff.out') sub_all = os.path.join('sub', 'all') # Set up the CVS repository. cvsroot = test.workpath('CVS') os.environ['CVSROOT'] = cvsroot test.run(program = cvs, arguments = 'init') test.write(['import', 'aaa.in'], "import/aaa.in\n") test.write(['import', 'bbb.in'], "import/bbb.in\n") test.write(['import', 'ccc.in'], "import/ccc.in\n") test.write(['import', 'sub', 'SConscript'], """\ Import("env") env.Cat('ddd.out', 'ddd.in') env.Cat('eee.out', 'eee.in') env.Cat('fff.out', 'fff.in') env.Cat('all', ['ddd.out', 'eee.out', 'fff.out']) """) test.write(['import', 'sub', 'ddd.in'], "import/sub/ddd.in\n") test.write(['import', 'sub', 'eee.in'], "import/sub/eee.in\n") test.write(['import', 'sub', 'fff.in'], "import/sub/fff.in\n") test.run(chdir = 'import', program = cvs, arguments = '-q import -m import foo v v-r') # Test the most straightforward CVS checkouts, using the module name. test.write(['work1', 'SConstruct'], """ import os def cat(env, source, target): target = str(target[0]) source = map(str, source) f = open(target, "wb") for src in source: f.write(open(src, "rb").read()) f.close() env = Environment(ENV = { 'PATH' : os.environ['PATH'], 'EDITOR' : os.environ.get('EDITOR', 'ed') }, BUILDERS={'Cat':Builder(action=cat)}) env.Prepend(CVSFLAGS='-Q') env.Cat('aaa.out', 'foo/aaa.in') env.Cat('bbb.out', 'foo/bbb.in') env.Cat('ccc.out', 'foo/ccc.in') env.Cat('all', ['aaa.out', 'bbb.out', 'ccc.out']) env.SourceCode('.', env.CVS(r'%(cvsroot)s')) SConscript('foo/sub/SConscript', "env") """ % locals()) test.subdir(['work1', 'foo']) test.write(['work1', 'foo', 'bbb.in'], "work1/foo/bbb.in\n") test.subdir(['work1', 'foo', 'sub',]) test.write(['work1', 'foo', 'sub', 'eee.in'], "work1/foo/sub/eee.in\n") test.run(chdir = 'work1', arguments = '.', stdout = test.wrap_stdout(read_str = """\ cvs -Q -d %(cvsroot)s co foo/sub/SConscript """ % locals(), build_str = """\ cvs -Q -d %(cvsroot)s co foo/aaa.in cat(["aaa.out"], ["%(foo_aaa_in)s"]) cat(["bbb.out"], ["%(foo_bbb_in)s"]) cvs -Q -d %(cvsroot)s co foo/ccc.in cat(["ccc.out"], ["%(foo_ccc_in)s"]) cat(["all"], ["aaa.out", "bbb.out", "ccc.out"]) cvs -Q -d %(cvsroot)s co foo/sub/ddd.in cat(["%(foo_sub_ddd_out)s"], ["%(foo_sub_ddd_in)s"]) cat(["%(foo_sub_eee_out)s"], ["%(foo_sub_eee_in)s"]) cvs -Q -d %(cvsroot)s co foo/sub/fff.in cat(["%(foo_sub_fff_out)s"], ["%(foo_sub_fff_in)s"]) cat(["%(foo_sub_all)s"], ["%(foo_sub_ddd_out)s", "%(foo_sub_eee_out)s", "%(foo_sub_fff_out)s"]) """ % locals())) # Checking things back out of CVS apparently messes with the line # endings, so read the result files in non-binary mode. test.must_match(['work1', 'all'], "import/aaa.in\nwork1/foo/bbb.in\nimport/ccc.in\n", mode='r') test.must_match(['work1', 'foo', 'sub', 'all'], "import/sub/ddd.in\nwork1/foo/sub/eee.in\nimport/sub/fff.in\n", mode='r') test.must_be_writable(test.workpath('work1', 'foo', 'sub', 'SConscript')) test.must_be_writable(test.workpath('work1', 'foo', 'aaa.in')) test.must_be_writable(test.workpath('work1', 'foo', 'ccc.in')) test.must_be_writable(test.workpath('work1', 'foo', 'sub', 'ddd.in')) test.must_be_writable(test.workpath('work1', 'foo', 'sub', 'fff.in')) # Test CVS checkouts when the module name is specified. test.write(['work2', 'SConstruct'], """ import os def cat(env, source, target): target = str(target[0]) source = map(str, source) f = open(target, "wb") for src in source: f.write(open(src, "rb").read()) f.close() env = Environment(ENV = { 'PATH' : os.environ['PATH'], 'EDITOR' : os.environ.get('EDITOR', 'ed') }, BUILDERS={'Cat':Builder(action=cat)}) env.Prepend(CVSFLAGS='-q') env.Cat('aaa.out', 'aaa.in') env.Cat('bbb.out', 'bbb.in') env.Cat('ccc.out', 'ccc.in') env.Cat('all', ['aaa.out', 'bbb.out', 'ccc.out']) env.SourceCode('.', env.CVS(r'%(cvsroot)s', 'foo')) SConscript('sub/SConscript', "env") """ % locals()) test.write(['work2', 'bbb.in'], "work2/bbb.in\n") test.subdir(['work2', 'sub']) test.write(['work2', 'sub', 'eee.in'], "work2/sub/eee.in\n") test.run(chdir = 'work2', arguments = '.', stdout = test.wrap_stdout(read_str = """\ cvs -q -d %(cvsroot)s co -d sub foo/sub/SConscript U sub/SConscript """ % locals(), build_str = """\ cvs -q -d %(cvsroot)s co -d . foo/aaa.in U ./aaa.in cat(["aaa.out"], ["aaa.in"]) cat(["bbb.out"], ["bbb.in"]) cvs -q -d %(cvsroot)s co -d . foo/ccc.in U ./ccc.in cat(["ccc.out"], ["ccc.in"]) cat(["all"], ["aaa.out", "bbb.out", "ccc.out"]) cvs -q -d %(cvsroot)s co -d sub foo/sub/ddd.in U sub/ddd.in cat(["%(sub_ddd_out)s"], ["%(sub_ddd_in)s"]) cat(["%(sub_eee_out)s"], ["%(sub_eee_in)s"]) cvs -q -d %(cvsroot)s co -d sub foo/sub/fff.in U sub/fff.in cat(["%(sub_fff_out)s"], ["%(sub_fff_in)s"]) cat(["%(sub_all)s"], ["%(sub_ddd_out)s", "%(sub_eee_out)s", "%(sub_fff_out)s"]) """ % locals())) # Checking things back out of CVS apparently messes with the line # endings, so read the result files in non-binary mode. test.must_match(['work2', 'all'], "import/aaa.in\nwork2/bbb.in\nimport/ccc.in\n", mode='r') test.must_match(['work2', 'sub', 'all'], "import/sub/ddd.in\nwork2/sub/eee.in\nimport/sub/fff.in\n", mode='r') test.must_be_writable(test.workpath('work2', 'sub', 'SConscript')) test.must_be_writable(test.workpath('work2', 'aaa.in')) test.must_be_writable(test.workpath('work2', 'ccc.in')) test.must_be_writable(test.workpath('work2', 'sub', 'ddd.in')) test.must_be_writable(test.workpath('work2', 'sub', 'fff.in')) # Test checking out specific file name(s), and expanding # the repository name with a variable. test.subdir(['work3']) test.write(['work3', 'SConstruct'], """\ import os def cat(env, source, target): target = str(target[0]) source = map(str, source) f = open(target, "wb") for src in source: f.write(open(src, "rb").read()) f.close() env = Environment(ENV = { 'PATH' : os.environ['PATH'], 'EDITOR' : os.environ.get('EDITOR', 'ed') }, BUILDERS={'Cat':Builder(action=cat)}, CVSROOT=r'%s') env.Prepend(CVSFLAGS='-q') env.Cat('aaa.out', 'aaa.in') env.Cat('bbb.out', 'bbb.in') env.Cat('ccc.out', 'ccc.in') env.Cat('all', ['aaa.out', 'bbb.out', 'ccc.out']) cvs = env.CVS('$CVSROOT', 'foo') #env.SourceCode('.', cvs) env.SourceCode('aaa.in', cvs) env.SourceCode('bbb.in', cvs) env.SourceCode('ccc.in', cvs) """ % cvsroot) test.run(chdir = 'work3', arguments = '.', stdout = test.wrap_stdout(build_str = """\ cvs -q -d %(cvsroot)s co -d . foo/aaa.in U ./aaa.in cat(["aaa.out"], ["aaa.in"]) cvs -q -d %(cvsroot)s co -d . foo/bbb.in U ./bbb.in cat(["bbb.out"], ["bbb.in"]) cvs -q -d %(cvsroot)s co -d . foo/ccc.in U ./ccc.in cat(["ccc.out"], ["ccc.in"]) cat(["all"], ["aaa.out", "bbb.out", "ccc.out"]) """ % locals())) test.must_match(['work3', 'aaa.out'], "import/aaa.in\n", mode='r') test.must_match(['work3', 'bbb.out'], "import/bbb.in\n", mode='r') test.must_match(['work3', 'ccc.out'], "import/ccc.in\n", mode='r') test.must_match(['work3', 'all'], "import/aaa.in\nimport/bbb.in\nimport/ccc.in\n", mode='r') # Test CVS checkouts from a remote server (Tigris.org). #test.subdir(['work4']) # #test.write(['work4', 'SConstruct'], """\ #import os #env = Environment(ENV = { 'PATH' : os.environ['PATH'] }) ## We used to use the SourceForge server, but SourceForge has restrictions ## that make them deny access on occasion. Leave the incantation here ## in case we need to use it again some day. ##cvs = env.CVS(':pserver:anonymous@cvs.sourceforge.net:/cvsroot/scons') #cvs = env.CVS(':pserver:anoncvs@cvs.tigris.org:/cvs') #env.SourceCode('.', cvs) #env.Install('install', 'scons/SConstruct') #""") # #test.run(chdir = 'work4', arguments = '.') # #test.must_exist(test.workpath('work4', 'install', 'SConstruct')) test.pass_test()
mit
facebook/mysql-5.6
xtrabackup/test/kewpie/percona_tests/xtrabackup_disabled/bug817132_test.py
24
5425
#! /usr/bin/env python # -*- mode: python; indent-tabs-mode: nil; -*- # vim:expandtab:shiftwidth=2:tabstop=2:smarttab: # # Copyright (C) 2011 Patrick Crews # # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA import os import sys import time import shutil from lib.util.mysqlBaseTestCase import mysqlBaseTestCase def skip_checks(system_manager): """ We do some pre-test checks to see if we need to skip a test or not """ # innobackupex --copy-back without explicit --ibbackup specification # defaults to 'xtrabackup'. So any build configurations other than xtradb51 # would fail in Jenkins. if os.path.basename(system_manager.xtrabackup_path) != "xtrabackup": return True, "Test only works with xtradb51. --ibbackup spec defaults to xtrabackup" else: return False, '' server_requirements = [[]] servers = [] server_manager = None test_executor = None # we explicitly use the --no-timestamp option # here. We will be using a generic / vanilla backup dir backup_path = None class basicTest(mysqlBaseTestCase): def setUp(self): master_server = servers[0] # assumption that this is 'master' backup_path = os.path.join(master_server.vardir, '_xtrabackup') # remove backup path if os.path.exists(backup_path): shutil.rmtree(backup_path) def test_bug817132(self): """ --copy-back without explicit --ibbackup specification defaults to 'xtrabackup'. """ self.servers = servers logging = test_executor.logging if servers[0].type not in ['mysql','percona']: return else: innobackupex = test_executor.system_manager.innobackupex_path xtrabackup = test_executor.system_manager.xtrabackup_path master_server = servers[0] # assumption that this is 'master' backup_path = os.path.join(master_server.vardir, '_xtrabackup') output_path = os.path.join(master_server.vardir, 'innobackupex.out') exec_path = os.path.dirname(innobackupex) # populate our server with a test bed test_cmd = "./gentest.pl --gendata=conf/percona/percona.zz" retcode, output = self.execute_randgen(test_cmd, test_executor, master_server) # take a backup cmd = [ innobackupex , "--defaults-file=%s" %master_server.cnf_file , "--parallel=8" , "--user=root" , "--port=%d" %master_server.master_port , "--host=127.0.0.1" , "--no-timestamp" , "--ibbackup=%s" %xtrabackup , backup_path ] cmd = " ".join(cmd) retcode, output = self.execute_cmd(cmd, output_path, exec_path, True) self.assertTrue(retcode==0,output) # stop the server master_server.stop() # do prepare on backup cmd = [ innobackupex , "--apply-log" , "--no-timestamp" , "--use-memory=500M" , "--ibbackup=%s" %xtrabackup , backup_path ] cmd = " ".join(cmd) retcode, output = self.execute_cmd(cmd, output_path, exec_path, True) self.assertTrue(retcode==0,output) # remove old datadir shutil.rmtree(master_server.datadir) os.mkdir(master_server.datadir) # We add xtrabackup to PATH tmp_path = os.environ['PATH'] tmp_path = "%s:%s" %(os.path.dirname(xtrabackup),tmp_path) os.environ['PATH'] = tmp_path # restore from backup cmd = [ innobackupex , "--defaults-file=%s" %master_server.cnf_file , "--copy-back" # We don't use --ibbackup here #, "--ibbackup=%s" %(xtrabackup) , "--socket=%s" %master_server.socket_file , backup_path ] cmd = " ".join(cmd) retcode, output = self.execute_cmd(cmd, output_path, exec_path, True) self.assertEqual(retcode,0, output) # restart server (and ensure it doesn't crash) master_server.start() self.assertEqual(master_server.status,1, 'Server failed restart from restored datadir...') # Check the server is ok query = "SELECT COUNT(*) FROM test.DD" expected_output = ((100L,),) retcode, output = self.execute_query(query, master_server) self.assertEqual(output, expected_output, msg = "%s || %s" %(output, expected_output))
gpl-2.0
nesdis/djongo
tests/django_tests/tests/v22/tests/auth_tests/test_remote_user.py
31
11327
from datetime import datetime from django.conf import settings from django.contrib.auth import authenticate from django.contrib.auth.backends import RemoteUserBackend from django.contrib.auth.middleware import RemoteUserMiddleware from django.contrib.auth.models import User from django.test import TestCase, modify_settings, override_settings from django.utils import timezone @override_settings(ROOT_URLCONF='auth_tests.urls') class RemoteUserTest(TestCase): middleware = 'django.contrib.auth.middleware.RemoteUserMiddleware' backend = 'django.contrib.auth.backends.RemoteUserBackend' header = 'REMOTE_USER' email_header = 'REMOTE_EMAIL' # Usernames to be passed in REMOTE_USER for the test_known_user test case. known_user = 'knownuser' known_user2 = 'knownuser2' def setUp(self): self.patched_settings = modify_settings( AUTHENTICATION_BACKENDS={'append': self.backend}, MIDDLEWARE={'append': self.middleware}, ) self.patched_settings.enable() def tearDown(self): self.patched_settings.disable() def test_no_remote_user(self): """ Tests requests where no remote user is specified and insures that no users get created. """ num_users = User.objects.count() response = self.client.get('/remote_user/') self.assertTrue(response.context['user'].is_anonymous) self.assertEqual(User.objects.count(), num_users) response = self.client.get('/remote_user/', **{self.header: None}) self.assertTrue(response.context['user'].is_anonymous) self.assertEqual(User.objects.count(), num_users) response = self.client.get('/remote_user/', **{self.header: ''}) self.assertTrue(response.context['user'].is_anonymous) self.assertEqual(User.objects.count(), num_users) def test_unknown_user(self): """ Tests the case where the username passed in the header does not exist as a User. """ num_users = User.objects.count() response = self.client.get('/remote_user/', **{self.header: 'newuser'}) self.assertEqual(response.context['user'].username, 'newuser') self.assertEqual(User.objects.count(), num_users + 1) User.objects.get(username='newuser') # Another request with same user should not create any new users. response = self.client.get('/remote_user/', **{self.header: 'newuser'}) self.assertEqual(User.objects.count(), num_users + 1) def test_known_user(self): """ Tests the case where the username passed in the header is a valid User. """ User.objects.create(username='knownuser') User.objects.create(username='knownuser2') num_users = User.objects.count() response = self.client.get('/remote_user/', **{self.header: self.known_user}) self.assertEqual(response.context['user'].username, 'knownuser') self.assertEqual(User.objects.count(), num_users) # A different user passed in the headers causes the new user # to be logged in. response = self.client.get('/remote_user/', **{self.header: self.known_user2}) self.assertEqual(response.context['user'].username, 'knownuser2') self.assertEqual(User.objects.count(), num_users) def test_last_login(self): """ A user's last_login is set the first time they make a request but not updated in subsequent requests with the same session. """ user = User.objects.create(username='knownuser') # Set last_login to something so we can determine if it changes. default_login = datetime(2000, 1, 1) if settings.USE_TZ: default_login = default_login.replace(tzinfo=timezone.utc) user.last_login = default_login user.save() response = self.client.get('/remote_user/', **{self.header: self.known_user}) self.assertNotEqual(default_login, response.context['user'].last_login) user = User.objects.get(username='knownuser') user.last_login = default_login user.save() response = self.client.get('/remote_user/', **{self.header: self.known_user}) self.assertEqual(default_login, response.context['user'].last_login) def test_header_disappears(self): """ A logged in user is logged out automatically when the REMOTE_USER header disappears during the same browser session. """ User.objects.create(username='knownuser') # Known user authenticates response = self.client.get('/remote_user/', **{self.header: self.known_user}) self.assertEqual(response.context['user'].username, 'knownuser') # During the session, the REMOTE_USER header disappears. Should trigger logout. response = self.client.get('/remote_user/') self.assertTrue(response.context['user'].is_anonymous) # verify the remoteuser middleware will not remove a user # authenticated via another backend User.objects.create_user(username='modeluser', password='foo') self.client.login(username='modeluser', password='foo') authenticate(username='modeluser', password='foo') response = self.client.get('/remote_user/') self.assertEqual(response.context['user'].username, 'modeluser') def test_user_switch_forces_new_login(self): """ If the username in the header changes between requests that the original user is logged out """ User.objects.create(username='knownuser') # Known user authenticates response = self.client.get('/remote_user/', **{self.header: self.known_user}) self.assertEqual(response.context['user'].username, 'knownuser') # During the session, the REMOTE_USER changes to a different user. response = self.client.get('/remote_user/', **{self.header: "newnewuser"}) # The current user is not the prior remote_user. # In backends that create a new user, username is "newnewuser" # In backends that do not create new users, it is '' (anonymous user) self.assertNotEqual(response.context['user'].username, 'knownuser') def test_inactive_user(self): User.objects.create(username='knownuser', is_active=False) response = self.client.get('/remote_user/', **{self.header: 'knownuser'}) self.assertTrue(response.context['user'].is_anonymous) class RemoteUserNoCreateBackend(RemoteUserBackend): """Backend that doesn't create unknown users.""" create_unknown_user = False class RemoteUserNoCreateTest(RemoteUserTest): """ Contains the same tests as RemoteUserTest, but using a custom auth backend class that doesn't create unknown users. """ backend = 'auth_tests.test_remote_user.RemoteUserNoCreateBackend' def test_unknown_user(self): num_users = User.objects.count() response = self.client.get('/remote_user/', **{self.header: 'newuser'}) self.assertTrue(response.context['user'].is_anonymous) self.assertEqual(User.objects.count(), num_users) class AllowAllUsersRemoteUserBackendTest(RemoteUserTest): """Backend that allows inactive users.""" backend = 'django.contrib.auth.backends.AllowAllUsersRemoteUserBackend' def test_inactive_user(self): user = User.objects.create(username='knownuser', is_active=False) response = self.client.get('/remote_user/', **{self.header: self.known_user}) self.assertEqual(response.context['user'].username, user.username) class CustomRemoteUserBackend(RemoteUserBackend): """ Backend that overrides RemoteUserBackend methods. """ def clean_username(self, username): """ Grabs username before the @ character. """ return username.split('@')[0] def configure_user(self, request, user): """ Sets user's email address using the email specified in an HTTP header. """ user.email = request.META.get(RemoteUserTest.email_header, '') user.save() return user class RemoteUserCustomTest(RemoteUserTest): """ Tests a custom RemoteUserBackend subclass that overrides the clean_username and configure_user methods. """ backend = 'auth_tests.test_remote_user.CustomRemoteUserBackend' # REMOTE_USER strings with email addresses for the custom backend to # clean. known_user = 'knownuser@example.com' known_user2 = 'knownuser2@example.com' def test_known_user(self): """ The strings passed in REMOTE_USER should be cleaned and the known users should not have been configured with an email address. """ super().test_known_user() self.assertEqual(User.objects.get(username='knownuser').email, '') self.assertEqual(User.objects.get(username='knownuser2').email, '') def test_unknown_user(self): """ The unknown user created should be configured with an email address provided in the request header. """ num_users = User.objects.count() response = self.client.get('/remote_user/', **{ self.header: 'newuser', self.email_header: 'user@example.com', }) self.assertEqual(response.context['user'].username, 'newuser') self.assertEqual(response.context['user'].email, 'user@example.com') self.assertEqual(User.objects.count(), num_users + 1) newuser = User.objects.get(username='newuser') self.assertEqual(newuser.email, 'user@example.com') class CustomHeaderMiddleware(RemoteUserMiddleware): """ Middleware that overrides custom HTTP auth user header. """ header = 'HTTP_AUTHUSER' class CustomHeaderRemoteUserTest(RemoteUserTest): """ Tests a custom RemoteUserMiddleware subclass with custom HTTP auth user header. """ middleware = ( 'auth_tests.test_remote_user.CustomHeaderMiddleware' ) header = 'HTTP_AUTHUSER' class PersistentRemoteUserTest(RemoteUserTest): """ PersistentRemoteUserMiddleware keeps the user logged in even if the subsequent calls do not contain the header value. """ middleware = 'django.contrib.auth.middleware.PersistentRemoteUserMiddleware' require_header = False def test_header_disappears(self): """ A logged in user is kept logged in even if the REMOTE_USER header disappears during the same browser session. """ User.objects.create(username='knownuser') # Known user authenticates response = self.client.get('/remote_user/', **{self.header: self.known_user}) self.assertEqual(response.context['user'].username, 'knownuser') # Should stay logged in if the REMOTE_USER header disappears. response = self.client.get('/remote_user/') self.assertFalse(response.context['user'].is_anonymous) self.assertEqual(response.context['user'].username, 'knownuser')
agpl-3.0
veridiam/Madcow-Waaltz
build/lib/madcow/modules/megahal.py
8
4744
"""MegaHAL Interface""" import re import os import time import sys from madcow.util import Module from madcow.util.text import * import shutil class MegaHALError(Exception): """Base MegaHAL Error""" class InvalidID(MegaHALError): """Raised when an invalid ID is supplied""" class Uninitialized(MegaHALError): """Raised if MegaHAL is not initialized""" class BuildError(MegaHALError): """Raised when we try to build MegaHAL and it blows up""" class MegaHAL(object): """MegaHAL Interface""" badchars_re = re.compile(r'[^a-z0-9_.]', re.I) update_freq = 1 * 60 * 60 # 1 hour update_max = 50 def __init__(self, basedir, logger=None, srcdb=None): self.basedir = basedir self.brain = None self.last_updated = None self.last_changed = None self.updates = 0 self.log = logger self.srcdb = srcdb def setid(self, id): id = encode(id) id = self.badchars_re.sub('', id).lower() if not id: raise InvalidID(u'invalid or missing brain id') brain = os.path.join(self.basedir, id) exists = os.path.exists(brain) if self.brain: if not exists: raise InvalidID(u'unknown brain: ' + id) megahal.save() self.log.info('saved brain') if not exists: os.makedirs(brain) self.log.info(u'made megahal directory: ' + brain) for filename in os.listdir(self.srcdb): if filename.startswith('megahal.'): shutil.copy(os.path.join(self.srcdb, filename), os.path.join(brain, filename)) self.log.debug('initializing brain with: ' + brain) megahal.init(brain) self.brain = brain return u'set brain to: ' + id def process(self, line): if not self.brain: raise Uninitialized('meghal is not initialized') if line == '#save': self.update() return 'I saved the brain' line = encode(line) response = decode(megahal.process(line)) self.last_changed = time.time() self.updates += 1 self.update_sentinel() return response def update_sentinel(self): if not self.last_updated: self.last_updated = time.time() update = False if self.last_changed - self.last_updated > self.update_freq: update = True self.log.debug('updating megahal because enough time has passed') if self.updates > self.update_max: update = True self.log.debug('updating because enough updates have happened') if update: self.update() def update(self): megahal.save() megahal.init(self.brain) self.last_updated = time.time() self.updates = 0 class Main(Module): pattern = re.compile(r'^\s*(brain|mh)\s+(.+?)\s*$', re.I) allow_threading = False help = u'\n'.join([ u'mh <line> - talk to megahal', u'brain <name> - switch to megahal brain', u'mh #save - force sync of brain to disk', ]) def init(self): src = os.path.join(self.madcow.prefix, 'include', 'pymegahal') # if megahal.so doesn't exist, let's try to build it global megahal try: import cmegahal as megahal except ImportError: self.log.warn("couldn't find cmegahal.so, i will try to build it") from subprocess import Popen, PIPE, STDOUT from tempfile import mkdtemp from shutil import rmtree tmp = mkdtemp() try: p = Popen([sys.executable, 'setup.py', 'build', '--build-base', tmp, '--build-lib', self.madcow.base], cwd=src, stdout=PIPE, stderr=STDOUT) for line in p.stdout: self.log.warn(line) p.wait() finally: if os.path.exists(tmp): rmtree(tmp) # let's try that again, shall we? try: import cmegahal as megahal except ImportError: raise BuildError('could not build MegaHAL automatically') # create the bot with a default personality default = os.path.join(self.madcow.base, 'db', 'megahal') self.megahal = MegaHAL(basedir=default, logger=self.log, srcdb=os.path.join(src, 'db')) self.megahal.setid('madcow') def response(self, nick, args, kwargs): command = args[0].lower() if command == u'brain': return self.megahal.setid(args[1]) elif command == u'mh': return self.megahal.process(args[1])
gpl-3.0
programa-stic/barf-project
tests/core/__init__.py
98
1345
# Copyright (c) 2014, Fundacion Dr. Manuel Sadosky # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # 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 HOLDER 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.
bsd-2-clause
tachang/xhtml2pdf
tests/test_utils.py
89
8136
#-*- coding: utf-8 -*- from reportlab.lib.colors import Color from unittest import TestCase from xhtml2pdf.util import getCoords, getColor, getSize, getFrameDimensions, \ getPos, getBox from xhtml2pdf.tags import int_to_roman class UtilsCoordTestCase(TestCase): def test_getCoords_simple(self): res = getCoords(1, 1, 10, 10, (10,10)) self.assertEqual(res, (1, -1, 10, 10)) # A second time - it's memoized! res = getCoords(1, 1, 10, 10, (10,10)) self.assertEqual(res, (1, -1, 10, 10)) def test_getCoords_x_lt_0(self): res = getCoords(-1, 1, 10, 10, (10,10)) self.assertEqual(res, (9, -1, 10, 10)) def test_getCoords_y_lt_0(self): res = getCoords(1, -1, 10, 10, (10,10)) self.assertEqual(res, (1, -9, 10, 10)) def test_getCoords_w_and_h_none(self): res = getCoords(1, 1, None, None, (10,10)) self.assertEqual(res, (1, 9)) def test_getCoords_w_lt_0(self): res = getCoords(1, 1, -1, 10, (10,10)) self.assertEqual(res, (1, -1, 8, 10)) def test_getCoords_h_lt_0(self): res = getCoords(1, 1, 10, -1, (10,10)) self.assertEqual(res, (1, 1, 10, 8)) class UtilsColorTestCase(TestCase): def test_get_color_simple(self): res = getColor('red') self.assertEqual(res, Color(1,0,0,1)) # Testing it being memoized properly res = getColor('red') self.assertEqual(res, Color(1,0,0,1)) def test_get_color_from_color(self): # Noop if argument is already a color res = getColor(Color(1,0,0,1)) self.assertEqual(res, Color(1,0,0,1)) def test_get_transparent_color(self): res = getColor('transparent', default='TOKEN') self.assertEqual(res, 'TOKEN') res = getColor('none', default='TOKEN') self.assertEqual(res, 'TOKEN') def test_get_color_for_none(self): res = getColor(None, default='TOKEN') self.assertEqual(res, 'TOKEN') def test_get_color_for_RGB(self): res = getColor('#FF0000') self.assertEqual(res, Color(1,0,0,1)) def test_get_color_for_RGB_with_len_4(self): res = getColor('#F00') self.assertEqual(res, Color(1,0,0,1)) def test_get_color_for_CSS_RGB_function(self): # It's regexp based, let's try common cases. res = getColor('rgb(255,0,0)') self.assertEqual(res, Color(1,0,0,1)) res = getColor('<css function: rgb(255,0,0)>') self.assertEqual(res, Color(1,0,0,1)) class UtilsGetSizeTestCase(TestCase): def test_get_size_simple(self): res = getSize('12pt') self.assertEqual(res, 12.00) # Memoized... res = getSize('12pt') self.assertEqual(res, 12.00) def test_get_size_for_none(self): res = getSize(None, relative='TOKEN') self.assertEqual(res, 'TOKEN') def test_get_size_for_float(self): res = getSize(12.00) self.assertEqual(res, 12.00) def test_get_size_for_tuple(self): # TODO: This is a really strange case. Probably should not work this way. res = getSize(("12", ".12")) self.assertEqual(res, 12.12) def test_get_size_for_cm(self): res = getSize("1cm") self.assertEqual(res, 28.346456692913385) def test_get_size_for_mm(self): res = getSize("1mm") self.assertEqual(res, 2.8346456692913385) def test_get_size_for_i(self): res = getSize("1i") self.assertEqual(res, 72.00) def test_get_size_for_in(self): res = getSize("1in") self.assertEqual(res, 72.00) def test_get_size_for_inch(self): res = getSize("1in") self.assertEqual(res, 72.00) def test_get_size_for_pc(self): res = getSize("1pc") self.assertEqual(res, 12.00) def test_get_size_for_none_str(self): res = getSize("none") self.assertEqual(res, 0.0) res = getSize("0") self.assertEqual(res, 0.0) res = getSize("auto") # Really? self.assertEqual(res, 0.0) class PisaDimensionTestCase(TestCase): def test_FrameDimensions_left_top_width_height(self): #builder = pisaCSSBuilder(mediumSet=['all']) dims = { 'left': '10pt', 'top': '20pt', 'width': '30pt', 'height': '40pt', } expected = (10.0, 20.0, 30.0, 40.0) result = getFrameDimensions(dims, 100, 200) self.assertEquals(expected, result) def test_FrameDimensions_left_top_bottom_right(self): dims = { 'left': '10pt', 'top': '20pt', 'bottom': '30pt', 'right': '40pt', } expected = (10.0, 20.0, 50.0, 150.0) result = getFrameDimensions(dims, 100, 200) self.assertEquals(expected, result) def test_FrameDimensions_bottom_right_width_height(self): dims = { 'bottom': '10pt', 'right': '20pt', 'width': '70pt', 'height': '80pt', } expected = (10.0, 110.0, 70.0, 80.0) result = getFrameDimensions(dims, 100, 200) self.assertEquals(expected, result) def test_FrameDimensions_left_top_width_height_with_margin(self): dims = { 'left': '10pt', 'top': '20pt', 'width': '70pt', 'height': '80pt', 'margin-top': '10pt', 'margin-left': '15pt', 'margin-bottom': '20pt', 'margin-right': '25pt', } expected = (25.0, 30.0, 30.0, 50.0) result = getFrameDimensions(dims, 100, 200) self.assertEquals(expected, result) def test_FrameDimensions_bottom_right_width_height_with_margin(self): dims = { 'bottom': '10pt', 'right': '20pt', 'width': '70pt', 'height': '80pt', 'margin-top': '10pt', 'margin-left': '15pt', 'margin-bottom': '20pt', 'margin-right': '25pt', } expected = (25.0, 120.0, 30.0, 50.0) result = getFrameDimensions(dims, 100, 200) self.assertEquals(expected, result) def test_frame_dimensions_for_box_len_eq_4(self): dims = { '-pdf-frame-box': ['12pt','12,pt','12pt','12pt'] } expected = [12.0, 12.0, 12.0, 12.0] result = getFrameDimensions(dims, 100, 200) self.assertEqual(result, expected) def test_trame_dimentions_for_height_without_top_or_bottom(self): dims = { 'left': '10pt', #'top': '20pt', 'width': '30pt', 'height': '40pt', } expected = (10.0, 0.0, 30.0, 200.0) result = getFrameDimensions(dims, 100, 200) self.assertEquals(expected, result) def test_trame_dimentions_for_width_without_left_or_right(self): dims = { #'left': '10pt', 'top': '20pt', 'width': '30pt', 'height': '40pt', } expected = (0.0, 20.0, 100.0, 40.0) result = getFrameDimensions(dims, 100, 200) self.assertEquals(expected, result) class GetPosTestCase(TestCase): def test_get_pos_simple(self): res = getBox("1pt 1pt 10pt 10pt", (10,10)) self.assertEqual(res,(1.0, -1.0, 10, 10)) def test_get_pos_raising(self): raised = False try: getBox("1pt 1pt 10pt", (10,10)) except Exception: raised = True self.assertTrue(raised) class TestTagUtils(TestCase): def test_roman_numeral_conversion(self): self.assertEqual("I", int_to_roman(1)) self.assertEqual("L", int_to_roman(50)) self.assertEqual("XLII", int_to_roman(42)) self.assertEqual("XXVI", int_to_roman(26))
apache-2.0
xianggong/m2c_unit_test
test/operator/post_decrement_short16/compile.py
1861
4430
#!/usr/bin/python import os import subprocess import re def runCommand(command): p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) p.wait() return iter(p.stdout.readline, b'') def dumpRunCommand(command, dump_file_name, postfix): dumpFile = open(dump_file_name + postfix, "w+") dumpFile.write(command + "\n") for line in runCommand(command.split()): dumpFile.write(line) def rmFile(file_name): cmd = "rm -rf " + file_name runCommand(cmd.split()) def rnm_ir(file_name): # Append all unnamed variable with prefix 'tmp_' ir_file_name = file_name + ".ll" if os.path.isfile(ir_file_name): fo = open(ir_file_name, "rw+") lines = fo.readlines() fo.seek(0) fo.truncate() for line in lines: # Add entry block identifier if "define" in line: line += "entry:\n" # Rename all unnamed variables line = re.sub('\%([0-9]+)', r'%tmp_\1', line.rstrip()) # Also rename branch name line = re.sub('(\;\ \<label\>\:)([0-9]+)', r'tmp_\2:', line.rstrip()) fo.write(line + '\n') def gen_ir(file_name): # Directories root_dir = '../../../' header_dir = root_dir + "inc/" # Headers header = " -I " + header_dir header += " -include " + header_dir + "m2c_buildin_fix.h " header += " -include " + header_dir + "clc/clc.h " header += " -D cl_clang_storage_class_specifiers " gen_ir = "clang -S -emit-llvm -O0 -target r600-- -mcpu=verde " cmd_gen_ir = gen_ir + header + file_name + ".cl" dumpRunCommand(cmd_gen_ir, file_name, ".clang.log") def asm_ir(file_name): if os.path.isfile(file_name + ".ll"): # Command to assemble IR to bitcode gen_bc = "llvm-as " gen_bc_src = file_name + ".ll" gen_bc_dst = file_name + ".bc" cmd_gen_bc = gen_bc + gen_bc_src + " -o " + gen_bc_dst runCommand(cmd_gen_bc.split()) def opt_bc(file_name): if os.path.isfile(file_name + ".bc"): # Command to optmize bitcode opt_bc = "opt --mem2reg " opt_ir_src = file_name + ".bc" opt_ir_dst = file_name + ".opt.bc" cmd_opt_bc = opt_bc + opt_ir_src + " -o " + opt_ir_dst runCommand(cmd_opt_bc.split()) def dis_bc(file_name): if os.path.isfile(file_name + ".bc"): # Command to disassemble bitcode dis_bc = "llvm-dis " dis_ir_src = file_name + ".opt.bc" dis_ir_dst = file_name + ".opt.ll" cmd_dis_bc = dis_bc + dis_ir_src + " -o " + dis_ir_dst runCommand(cmd_dis_bc.split()) def m2c_gen(file_name): if os.path.isfile(file_name + ".opt.bc"): # Command to disassemble bitcode m2c_gen = "m2c --llvm2si " m2c_gen_src = file_name + ".opt.bc" cmd_m2c_gen = m2c_gen + m2c_gen_src dumpRunCommand(cmd_m2c_gen, file_name, ".m2c.llvm2si.log") # Remove file if size is 0 if os.path.isfile(file_name + ".opt.s"): if os.path.getsize(file_name + ".opt.s") == 0: rmFile(file_name + ".opt.s") def m2c_bin(file_name): if os.path.isfile(file_name + ".opt.s"): # Command to disassemble bitcode m2c_bin = "m2c --si2bin " m2c_bin_src = file_name + ".opt.s" cmd_m2c_bin = m2c_bin + m2c_bin_src dumpRunCommand(cmd_m2c_bin, file_name, ".m2c.si2bin.log") def main(): # Commands for file in os.listdir("./"): if file.endswith(".cl"): file_name = os.path.splitext(file)[0] # Execute commands gen_ir(file_name) rnm_ir(file_name) asm_ir(file_name) opt_bc(file_name) dis_bc(file_name) m2c_gen(file_name) m2c_bin(file_name) if __name__ == "__main__": main()
gpl-2.0
jaggu303619/asylum-v2.0
openerp/addons/l10n_de/__init__.py
693
1057
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). # # 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/>. # ############################################################################## # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
cosurgi/trunk
examples/mpi/fibres/exampleFibresMPI.py
1
6543
#Example showing how to run 'fiber' (gridNode+girdConnection) in Yade-MPI from yade import utils from yade.gridpfacet import * from yade import mpy as mp # create a Fiber class with attributes of the nodes it consists, the node which corresponds to the centre of mass, and a tuple 'segs' which consists the node pair forming a segment. class Fibre : def __init__(self): self.numseg = 0 self.cntrId = -1 self.nodes = [] self.segs = [] # The usual engines, without the timestepper. (NOTE: will be fixed soon.) O.engines = [ForceResetter(), InsertionSortCollider([Bo1_GridConnection_Aabb(),Bo1_PFacet_Aabb(), Bo1_Subdomain_Aabb()]), InteractionLoop( [Ig2_GridNode_GridNode_GridNodeGeom6D(), Ig2_GridConnection_GridConnection_GridCoGridCoGeom(), Ig2_GridConnection_PFacet_ScGeom(), Ig2_Sphere_PFacet_ScGridCoGeom()], [Ip2_CohFrictMat_CohFrictMat_CohFrictPhys(setCohesionNow=True,setCohesionOnNewContacts=False),Ip2_FrictMat_FrictMat_FrictPhys()], [Law2_ScGeom6D_CohFrictPhys_CohesionMoment(label='fib_self'), Law2_ScGeom_FrictPhys_CundallStrack(), Law2_GridCoGridCoGeom_FrictPhys_CundallStrack()] ), NewtonIntegrator(damping = 0.0, label='newton', gravity = (0, -10, 0)) ] #materials as usual. young = 2e5 O.materials.append(CohFrictMat(young=young,poisson=0.3,density=1050,frictionAngle=radians(20),normalCohesion=1e100,shearCohesion=1e100,momentRotationLaw=True,label='spheremat')) O.materials.append(FrictMat(young=young,poisson=0.3,density=1050,frictionAngle=radians(20),label='frictmat')) O.materials.append(FrictMat(young=young,poisson=0.3,density=5000,frictionAngle=radians(30),label='facetmat')) O.materials.append(CohFrictMat(young=young,poisson=0.3,density=5000,frictionAngle=radians(30),normalCohesion=1e100,shearCohesion=1e100,momentRotationLaw=True,label='facetnode')) r = 2e-04 #fibre radius ntot = 150 # total number of fibers nNodes = 11 # number of nodes per fiber numseg = nNodes-1 #number of segments per fiber. l = 2e-02 # fiber length. nodes = [] #ids of nodes. #the file fibnodes.dat consists of the coordinates of the nodes, generated from fibgen.f90 (python version soon!) nlist = open('fibreNodes.dat', 'r') #insert the gridNodes to the bodyContainer. for l in nlist: for i in range(0, nNodes): nodes.append(O.bodies.append(gridNode([float(l.split()[3*i]), float(l.split()[3*i+1]), float(l.split()[3*i+2])], r, material = 'spheremat', fixed=False))) nlist.close() #insert the gridConnection in the bodyContainer for i in range(0, ntot): for j in range(0,nNodes-1): O.bodies.append(gridConnection(nNodes*i+j, nNodes*i+j+1,r, material='frictmat')) #---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------# # a list of fibers. This is needed for domain decomposition. fibreList = [Fibre() for i in range(ntot)] for i in range(ntot): for j in range(nNodes): fibreList[i].nodes.append(nNodes*i+j) for fib in fibreList: for i in range(len(fib.nodes)-1): fib.segs.append( (fib.nodes[i],fib.nodes[i+1]) ) fib.cntrId = fib.nodes[len(fib.nodes)//2] #---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------# #pfacet walls. These bodies are not included in the worker subdomains (neither pfacet nodes, pfcet connections) ymax = 0.25 xmax = 0.225 zmax = 0.2225 xmin = 1e-10 ymin = -0.05 zmin = 1e-10 color = [255./255.,102./255.,0./255.] wall1=[] wall2=[] O.bodies.append(gridNode([xmin,ymin,zmin],r,fixed=True,material='facetnode')) wall1.append(O.bodies[-1].id) O.bodies.append(gridNode([xmax,ymin,zmin],r,fixed=True,material='facetnode')) wall1.append(O.bodies[-1].id) O.bodies.append(gridNode([xmin,ymin,zmax],r,fixed=True,material='facetnode')) wall1.append(O.bodies[-1].id) O.bodies.append(gridNode([xmax,ymin,zmax],r,fixed=True,material='facetnode')) wall1.append(O.bodies[-1].id) color = [255./255.,102./255.,0./255.] O.bodies.append( gridConnection(wall1[0],wall1[1],r,material='facetmat') ) O.bodies.append( gridConnection(wall1[2],wall1[3],r,material='facetmat') ) O.bodies.append( gridConnection(wall1[2],wall1[1],r,material='facetmat') ) O.bodies.append( gridConnection(wall1[2],wall1[0],r,material='facetmat') ) O.bodies.append( gridConnection(wall1[3],wall1[1],r,material='facetmat') ) O.bodies.append( pfacet(wall1[2],wall1[3],wall1[1],color=color,material='facetmat') ) O.bodies.append( pfacet(wall1[2],wall1[0],wall1[1],color=color,material='facetmat') ) O.bodies.append(gridNode([xmin,ymax,zmin],r,fixed=True,material='facetnode')) wall2.append(O.bodies[-1].id) O.bodies.append(gridNode([xmax,ymax,zmin],r,fixed=True,material='facetnode')) wall2.append(O.bodies[-1].id) O.bodies.append(gridNode([xmin,ymax,zmax],r,fixed=True,material='facetnode')) wall2.append(O.bodies[-1].id) O.bodies.append(gridNode([xmax,ymax,zmax],r,fixed=True,material='facetnode')) wall2.append(O.bodies[-1].id) O.bodies.append( gridConnection(wall2[0],wall2[1],r,material='facetmat') ) O.bodies.append( gridConnection(wall2[2],wall2[3],r,material='facetmat') ) O.bodies.append( gridConnection(wall2[2],wall2[1],r,material='facetmat') ) O.bodies.append( gridConnection(wall2[2],wall2[0],r,material='facetmat') ) O.bodies.append( gridConnection(wall2[3],wall2[1],r,material='facetmat') ) O.bodies.append( pfacet(wall2[2],wall2[3],wall2[1],color=color,material='facetmat') ) O.bodies.append( pfacet(wall2[2],wall2[0],wall2[1],color=color,material='facetmat') ) #set a timestep. O.dt = 1e-05 numThreads = 5 mp.DOMAIN_DECOMPOSITION = True mp.fibreList = fibreList NSTEPS = 500 mp.mpirun(NSTEPS, numThreads) mp.mergeScene() if mp.rank == 0: O.save('fibres.yade') #---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------#
gpl-2.0
HenriqueLR/simple-route
app/seek/views.py
1
3996
#encoding> utf-8 from core.models import Maps, Routes from core.serializers import MapsSerializer, RoutesSerializer from django.http import Http404 from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from django.http import HttpResponse import json from seek.utils import RoutePrice class MapsList(APIView): """ List all Maps, or create a new Map. """ def get(self, request, format=None): maps = Maps.objects.all() serializer = MapsSerializer(maps, many=True) return Response(serializer.data, status=status.HTTP_200_OK) def post(self, request, format=None): maps = MapsSerializer(data=request.data) if maps.is_valid(): maps.save() return Response(maps.data, status=status.HTTP_201_CREATED) return Response(maps.errors, status=status.HTTP_400_BAD_REQUEST) class MapsCustom(APIView): """ Retrieve, update or delete a maps instance. """ def get_object(self, string): try: return Maps.objects.get(name_map=string) except Maps.DoesNotExist: raise Http404 def get(self, request, string, format=None): maps = self.get_object(string) serializer = MapsSerializer(maps) return Response(serializer.data) def put(self, request, string, format=None): maps = self.get_object(string) serializer = MapsSerializer(maps, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self, request, string, format=None): maps = self.get_object(string) maps.delete() return Response(status=status.HTTP_204_NO_CONTENT) class RoutesList(APIView): """ List all Routes, or create a new Route. """ def get(self, request, format=None): routes = Routes.objects.all() serializer = RoutesSerializer(routes, many=True) return Response(serializer.data) def post(self, request, format=None): routes = RoutesSerializer(data=request.data) if routes.is_valid(): routes.save() return Response(routes.data, status=status.HTTP_201_CREATED) return Response(routes.errors, status=status.HTTP_400_BAD_REQUEST) class RoutesCustomName(APIView): """ Retrieve, update or delete a routes instance. """ def get_object(self, pk): try: return Routes.objects.get(id_route=(pk)) except Routes.DoesNotExist: raise Http404 def get(self, request, pk, format=None): routes = self.get_object(pk) serializer = RoutesSerializer(routes) return Response(serializer.data) def put(self, request, pk, format=None): routes = self.get_object(pk) serializer = RoutesSerializer(routes, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self, request, pk, format=None): name = self.get_object(pk) name.delete() return Response(status=status.HTTP_204_NO_CONTENT) def price_route(request): """ Get route information. """ if request.method == 'POST': received_json_data = json.loads(request.body) fuel = float(received_json_data['fuel']) origin = received_json_data['origin'] destination = received_json_data['destination'] autonomy = float(received_json_data['autonomy']) map_data = received_json_data['map'] routes = Routes.objects.filter(id_map__name_map=(map_data)) route_price = RoutePrice(routes) route_price = route_price.calc(origin, destination) if(route_price!=None): distance = float(route_price['distance']) routes = route_price['routes'] price = (distance / autonomy) * fuel result = {'routes': routes, 'distance': distance, 'price': price} return HttpResponse(json.dumps(result), content_type='application/json',status=200) error = {"error":"Mapa pesquisado nao existe."} return HttpResponse(json.dumps(error), content_type='application/json')
mit
yukoba/sympy
sympy/unify/usympy.py
93
4015
""" SymPy interface to Unification engine See sympy.unify for module level docstring See sympy.unify.core for algorithmic docstring """ from __future__ import print_function, division from sympy.core import Basic, Add, Mul, Pow from sympy.matrices import MatAdd, MatMul, MatrixExpr from sympy.sets.sets import Union, Intersection, FiniteSet from sympy.core.operations import AssocOp, LatticeOp from sympy.unify.core import Compound, Variable, CondVariable from sympy.unify import core basic_new_legal = [MatrixExpr] eval_false_legal = [AssocOp, Pow, FiniteSet] illegal = [LatticeOp] def sympy_associative(op): assoc_ops = (AssocOp, MatAdd, MatMul, Union, Intersection, FiniteSet) return any(issubclass(op, aop) for aop in assoc_ops) def sympy_commutative(op): comm_ops = (Add, MatAdd, Union, Intersection, FiniteSet) return any(issubclass(op, cop) for cop in comm_ops) def is_associative(x): return isinstance(x, Compound) and sympy_associative(x.op) def is_commutative(x): if not isinstance(x, Compound): return False if sympy_commutative(x.op): return True if issubclass(x.op, Mul): return all(construct(arg).is_commutative for arg in x.args) def mk_matchtype(typ): def matchtype(x): return (isinstance(x, typ) or isinstance(x, Compound) and issubclass(x.op, typ)) return matchtype def deconstruct(s, variables=()): """ Turn a SymPy object into a Compound """ if s in variables: return Variable(s) if isinstance(s, (Variable, CondVariable)): return s if not isinstance(s, Basic) or s.is_Atom: return s return Compound(s.__class__, tuple(deconstruct(arg, variables) for arg in s.args)) def construct(t): """ Turn a Compound into a SymPy object """ if isinstance(t, (Variable, CondVariable)): return t.arg if not isinstance(t, Compound): return t if any(issubclass(t.op, cls) for cls in eval_false_legal): return t.op(*map(construct, t.args), evaluate=False) elif any(issubclass(t.op, cls) for cls in basic_new_legal): return Basic.__new__(t.op, *map(construct, t.args)) else: return t.op(*map(construct, t.args)) def rebuild(s): """ Rebuild a SymPy expression This removes harm caused by Expr-Rules interactions """ return construct(deconstruct(s)) def unify(x, y, s=None, variables=(), **kwargs): """ Structural unification of two expressions/patterns Examples ======== >>> from sympy.unify.usympy import unify >>> from sympy import Basic, cos >>> from sympy.abc import x, y, z, p, q >>> next(unify(Basic(1, 2), Basic(1, x), variables=[x])) {x: 2} >>> expr = 2*x + y + z >>> pattern = 2*p + q >>> next(unify(expr, pattern, {}, variables=(p, q))) {p: x, q: y + z} Unification supports commutative and associative matching >>> expr = x + y + z >>> pattern = p + q >>> len(list(unify(expr, pattern, {}, variables=(p, q)))) 12 Symbols not indicated to be variables are treated as literal, else they are wild-like and match anything in a sub-expression. >>> expr = x*y*z + 3 >>> pattern = x*y + 3 >>> next(unify(expr, pattern, {}, variables=[x, y])) {x: y, y: x*z} The x and y of the pattern above were in a Mul and matched factors in the Mul of expr. Here, a single symbol matches an entire term: >>> expr = x*y + 3 >>> pattern = p + 3 >>> next(unify(expr, pattern, {}, variables=[p])) {p: x*y} """ decons = lambda x: deconstruct(x, variables) s = s or {} s = dict((decons(k), decons(v)) for k, v in s.items()) ds = core.unify(decons(x), decons(y), s, is_associative=is_associative, is_commutative=is_commutative, **kwargs) for d in ds: yield dict((construct(k), construct(v)) for k, v in d.items())
bsd-3-clause
bratsche/Neutron-Drive
neutron-drive/django/contrib/localflavor/hr/hr_choices.py
91
2810
# -*- coding: utf-8 -*- """ Sources: Croatian Counties: http://en.wikipedia.org/wiki/ISO_3166-2:HR Croatia doesn't have official abbreviations for counties. The ones provided are in common use. """ from django.utils.translation import ugettext_lazy as _ HR_COUNTY_CHOICES = ( ('GZG', _('Grad Zagreb')), (u'BBŽ', _(u'Bjelovarsko-bilogorska županija')), (u'BPŽ', _(u'Brodsko-posavska županija')), (u'DNŽ', _(u'Dubrovačko-neretvanska županija')), (u'IŽ', _(u'Istarska županija')), (u'KŽ', _(u'Karlovačka županija')), (u'KKŽ', _(u'Koprivničko-križevačka županija')), (u'KZŽ', _(u'Krapinsko-zagorska županija')), (u'LSŽ', _(u'Ličko-senjska županija')), (u'MŽ', _(u'Međimurska županija')), (u'OBŽ', _(u'Osječko-baranjska županija')), (u'PSŽ', _(u'Požeško-slavonska županija')), (u'PGŽ', _(u'Primorsko-goranska županija')), (u'SMŽ', _(u'Sisačko-moslavačka županija')), (u'SDŽ', _(u'Splitsko-dalmatinska županija')), (u'ŠKŽ', _(u'Šibensko-kninska županija')), (u'VŽ', _(u'Varaždinska županija')), (u'VPŽ', _(u'Virovitičko-podravska županija')), (u'VSŽ', _(u'Vukovarsko-srijemska županija')), (u'ZDŽ', _(u'Zadarska županija')), (u'ZGŽ', _(u'Zagrebačka županija')), ) """ Sources: http://hr.wikipedia.org/wiki/Dodatak:Popis_registracijskih_oznaka_za_cestovna_vozila_u_Hrvatskoj Only common license plate prefixes are provided. Special cases and obsolete prefixes are omitted. """ HR_LICENSE_PLATE_PREFIX_CHOICES = ( ('BJ', 'BJ'), ('BM', 'BM'), (u'ČK', u'ČK'), ('DA', 'DA'), ('DE', 'DE'), ('DJ', 'DJ'), ('DU', 'DU'), ('GS', 'GS'), ('IM', 'IM'), ('KA', 'KA'), ('KC', 'KC'), ('KR', 'KR'), ('KT', 'KT'), (u'KŽ', u'KŽ'), ('MA', 'MA'), ('NA', 'NA'), ('NG', 'NG'), ('OG', 'OG'), ('OS', 'OS'), ('PU', 'PU'), (u'PŽ', u'PŽ'), ('RI', 'RI'), ('SB', 'SB'), ('SK', 'SK'), ('SL', 'SL'), ('ST', 'ST'), (u'ŠI', u'ŠI'), ('VK', 'VK'), ('VT', 'VT'), ('VU', 'VU'), (u'VŽ', u'VŽ'), ('ZD', 'ZD'), ('ZG', 'ZG'), (u'ŽU', u'ŽU'), ) """ The list includes county and cellular network phone number prefixes. """ HR_PHONE_NUMBER_PREFIX_CHOICES = ( ('1', '01'), ('20', '020'), ('21', '021'), ('22', '022'), ('23', '023'), ('31', '031'), ('32', '032'), ('33', '033'), ('34', '034'), ('35', '035'), ('40', '040'), ('42', '042'), ('43', '043'), ('44', '044'), ('47', '047'), ('48', '048'), ('49', '049'), ('51', '051'), ('52', '052'), ('53', '053'), ('91', '091'), ('92', '092'), ('95', '095'), ('97', '097'), ('98', '098'), ('99', '099'), )
bsd-3-clause
philanthropy-u/edx-platform
common/djangoapps/terrain/stubs/video_source.py
24
1588
""" Serve HTML5 video sources for acceptance tests """ import os from contextlib import contextmanager from logging import getLogger from SimpleHTTPServer import SimpleHTTPRequestHandler from .http import StubHttpService LOGGER = getLogger(__name__) class VideoSourceRequestHandler(SimpleHTTPRequestHandler): """ Request handler for serving video sources locally. """ def translate_path(self, path): """ Remove any extra parameters from the path. For example /gizmo.mp4?1397160769634 becomes /gizmo.mp4 """ root_dir = self.server.config.get('root_dir') path = '{}{}'.format(root_dir, path) return path.split('?')[0] def end_headers(self): """ This is required by hls.js to play hls videos. """ self.send_header('Access-Control-Allow-Origin', '*') SimpleHTTPRequestHandler.end_headers(self) class VideoSourceHttpService(StubHttpService): """ Simple HTTP server for serving HTML5 Video sources locally for tests """ HANDLER_CLASS = VideoSourceRequestHandler def __init__(self, port_num=0): @contextmanager def _remember_cwd(): """ Files are automatically served from the current directory so we need to change it, start the server, then set it back. """ curdir = os.getcwd() try: yield finally: os.chdir(curdir) with _remember_cwd(): StubHttpService.__init__(self, port_num=port_num)
agpl-3.0
patrickcurl/ztruck
dj/lib/python2.7/site-packages/django/conf/locale/az/formats.py
1059
1267
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # from __future__ import unicode_literals # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'j E Y г.' TIME_FORMAT = 'G:i' DATETIME_FORMAT = 'j E Y г. G:i' YEAR_MONTH_FORMAT = 'F Y г.' MONTH_DAY_FORMAT = 'j F' SHORT_DATE_FORMAT = 'd.m.Y' SHORT_DATETIME_FORMAT = 'd.m.Y H:i' FIRST_DAY_OF_WEEK = 1 # Monday # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = [ '%d.%m.%Y', # '25.10.2006' '%d.%m.%y', # '25.10.06' ] DATETIME_INPUT_FORMATS = [ '%d.%m.%Y %H:%M:%S', # '25.10.2006 14:30:59' '%d.%m.%Y %H:%M:%S.%f', # '25.10.2006 14:30:59.000200' '%d.%m.%Y %H:%M', # '25.10.2006 14:30' '%d.%m.%Y', # '25.10.2006' '%d.%m.%y %H:%M:%S', # '25.10.06 14:30:59' '%d.%m.%y %H:%M:%S.%f', # '25.10.06 14:30:59.000200' '%d.%m.%y %H:%M', # '25.10.06 14:30' '%d.%m.%y', # '25.10.06' ] DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '\xa0' # non-breaking space NUMBER_GROUPING = 3
apache-2.0
Anlim/decode-Django
Django-1.5.1/django/contrib/localflavor/no/forms.py
110
2871
""" Norwegian-specific Form helpers """ from __future__ import absolute_import, unicode_literals import re import datetime from django.contrib.localflavor.no.no_municipalities import MUNICIPALITY_CHOICES from django.core.validators import EMPTY_VALUES from django.forms import ValidationError from django.forms.fields import Field, RegexField, Select from django.utils.translation import ugettext_lazy as _ class NOZipCodeField(RegexField): default_error_messages = { 'invalid': _('Enter a zip code in the format XXXX.'), } def __init__(self, max_length=None, min_length=None, *args, **kwargs): super(NOZipCodeField, self).__init__(r'^\d{4}$', max_length, min_length, *args, **kwargs) class NOMunicipalitySelect(Select): """ A Select widget that uses a list of Norwegian municipalities (fylker) as its choices. """ def __init__(self, attrs=None): super(NOMunicipalitySelect, self).__init__(attrs, choices=MUNICIPALITY_CHOICES) class NOSocialSecurityNumber(Field): """ Algorithm is documented at http://no.wikipedia.org/wiki/Personnummer """ default_error_messages = { 'invalid': _('Enter a valid Norwegian social security number.'), } def clean(self, value): super(NOSocialSecurityNumber, self).clean(value) if value in EMPTY_VALUES: return '' if not re.match(r'^\d{11}$', value): raise ValidationError(self.error_messages['invalid']) day = int(value[:2]) month = int(value[2:4]) year2 = int(value[4:6]) inum = int(value[6:9]) self.birthday = None try: if 000 <= inum < 500: self.birthday = datetime.date(1900+year2, month, day) if 500 <= inum < 750 and year2 > 54: self.birthday = datetime.date(1800+year2, month, day) if 500 <= inum < 1000 and year2 < 40: self.birthday = datetime.date(2000+year2, month, day) if 900 <= inum < 1000 and year2 > 39: self.birthday = datetime.date(1900+year2, month, day) except ValueError: raise ValidationError(self.error_messages['invalid']) sexnum = int(value[8]) if sexnum % 2 == 0: self.gender = 'F' else: self.gender = 'M' digits = map(int, list(value)) weight_1 = [3, 7, 6, 1, 8, 9, 4, 5, 2, 1, 0] weight_2 = [5, 4, 3, 2, 7, 6, 5, 4, 3, 2, 1] def multiply_reduce(aval, bval): return sum([(a * b) for (a, b) in zip(aval, bval)]) if multiply_reduce(digits, weight_1) % 11 != 0: raise ValidationError(self.error_messages['invalid']) if multiply_reduce(digits, weight_2) % 11 != 0: raise ValidationError(self.error_messages['invalid']) return value
gpl-2.0
duyetdev/openerp-6.1.1
openerp/addons/account/wizard/account_report_print_journal.py
3
3426
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # 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 osv import osv, fields from lxml import etree class account_print_journal(osv.osv_memory): _inherit = "account.common.journal.report" _name = 'account.print.journal' _description = 'Account Print Journal' _columns = { 'sort_selection': fields.selection([('l.date', 'Date'), ('am.name', 'Journal Entry Number'),], 'Entries Sorted by', required=True), 'journal_ids': fields.many2many('account.journal', 'account_print_journal_journal_rel', 'account_id', 'journal_id', 'Journals', required=True), } _defaults = { 'sort_selection': 'am.name', 'filter': 'filter_period', 'journal_ids': False, } def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False): ''' used to set the domain on 'journal_ids' field: we exclude or only propose the journals of type sale/purchase (+refund) accordingly to the presence of the key 'sale_purchase_only' in the context. ''' if context is None: context = {} res = super(account_print_journal, self).fields_view_get(cr, uid, view_id=view_id, view_type=view_type, context=context, toolbar=toolbar, submenu=submenu) doc = etree.XML(res['arch']) if context.get('sale_purchase_only'): domain ="[('type', 'in', ('sale','purchase','sale_refund','purchase_refund'))]" else: domain ="[]" nodes = doc.xpath("//field[@name='journal_ids']") for node in nodes: node.set('domain', domain) res['arch'] = etree.tostring(doc) return res def _print_report(self, cr, uid, ids, data, context=None): if context is None: context = {} data = self.pre_print_report(cr, uid, ids, data, context=context) data['form'].update(self.read(cr, uid, ids, ['sort_selection'], context=context)[0]) if context.get('sale_purchase_only'): report_name = 'account.journal.period.print.sale.purchase' else: report_name = 'account.journal.period.print' return {'type': 'ir.actions.report.xml', 'report_name': report_name, 'datas': data} account_print_journal() #vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
CapOM/ChromiumGStreamerBackend
tools/telemetry/third_party/gsutilz/third_party/boto/tests/unit/s3/test_uri.py
114
12504
#!/usr/bin/env python # Copyright (c) 2013 Google, 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 boto import tempfile from boto.exception import InvalidUriError from boto import storage_uri from boto.compat import urllib from boto.s3.keyfile import KeyFile from tests.integration.s3.mock_storage_service import MockBucket from tests.integration.s3.mock_storage_service import MockBucketStorageUri from tests.integration.s3.mock_storage_service import MockConnection from tests.unit import unittest """Unit tests for StorageUri interface.""" class UriTest(unittest.TestCase): def test_provider_uri(self): for prov in ('gs', 's3'): uri_str = '%s://' % prov uri = boto.storage_uri(uri_str, validate=False, suppress_consec_slashes=False) self.assertEqual(prov, uri.scheme) self.assertEqual(uri_str, uri.uri) self.assertFalse(hasattr(uri, 'versionless_uri')) self.assertEqual('', uri.bucket_name) self.assertEqual('', uri.object_name) self.assertEqual(None, uri.version_id) self.assertEqual(None, uri.generation) self.assertEqual(uri.names_provider(), True) self.assertEqual(uri.names_container(), True) self.assertEqual(uri.names_bucket(), False) self.assertEqual(uri.names_object(), False) self.assertEqual(uri.names_directory(), False) self.assertEqual(uri.names_file(), False) self.assertEqual(uri.is_stream(), False) self.assertEqual(uri.is_version_specific, False) def test_bucket_uri_no_trailing_slash(self): for prov in ('gs', 's3'): uri_str = '%s://bucket' % prov uri = boto.storage_uri(uri_str, validate=False, suppress_consec_slashes=False) self.assertEqual(prov, uri.scheme) self.assertEqual('%s/' % uri_str, uri.uri) self.assertFalse(hasattr(uri, 'versionless_uri')) self.assertEqual('bucket', uri.bucket_name) self.assertEqual('', uri.object_name) self.assertEqual(None, uri.version_id) self.assertEqual(None, uri.generation) self.assertEqual(uri.names_provider(), False) self.assertEqual(uri.names_container(), True) self.assertEqual(uri.names_bucket(), True) self.assertEqual(uri.names_object(), False) self.assertEqual(uri.names_directory(), False) self.assertEqual(uri.names_file(), False) self.assertEqual(uri.is_stream(), False) self.assertEqual(uri.is_version_specific, False) def test_bucket_uri_with_trailing_slash(self): for prov in ('gs', 's3'): uri_str = '%s://bucket/' % prov uri = boto.storage_uri(uri_str, validate=False, suppress_consec_slashes=False) self.assertEqual(prov, uri.scheme) self.assertEqual(uri_str, uri.uri) self.assertFalse(hasattr(uri, 'versionless_uri')) self.assertEqual('bucket', uri.bucket_name) self.assertEqual('', uri.object_name) self.assertEqual(None, uri.version_id) self.assertEqual(None, uri.generation) self.assertEqual(uri.names_provider(), False) self.assertEqual(uri.names_container(), True) self.assertEqual(uri.names_bucket(), True) self.assertEqual(uri.names_object(), False) self.assertEqual(uri.names_directory(), False) self.assertEqual(uri.names_file(), False) self.assertEqual(uri.is_stream(), False) self.assertEqual(uri.is_version_specific, False) def test_non_versioned_object_uri(self): for prov in ('gs', 's3'): uri_str = '%s://bucket/obj/a/b' % prov uri = boto.storage_uri(uri_str, validate=False, suppress_consec_slashes=False) self.assertEqual(prov, uri.scheme) self.assertEqual(uri_str, uri.uri) self.assertEqual(uri_str, uri.versionless_uri) self.assertEqual('bucket', uri.bucket_name) self.assertEqual('obj/a/b', uri.object_name) self.assertEqual(None, uri.version_id) self.assertEqual(None, uri.generation) self.assertEqual(uri.names_provider(), False) self.assertEqual(uri.names_container(), False) self.assertEqual(uri.names_bucket(), False) self.assertEqual(uri.names_object(), True) self.assertEqual(uri.names_directory(), False) self.assertEqual(uri.names_file(), False) self.assertEqual(uri.is_stream(), False) self.assertEqual(uri.is_version_specific, False) def test_versioned_gs_object_uri(self): uri_str = 'gs://bucket/obj/a/b#1359908801674000' uri = boto.storage_uri(uri_str, validate=False, suppress_consec_slashes=False) self.assertEqual('gs', uri.scheme) self.assertEqual(uri_str, uri.uri) self.assertEqual('gs://bucket/obj/a/b', uri.versionless_uri) self.assertEqual('bucket', uri.bucket_name) self.assertEqual('obj/a/b', uri.object_name) self.assertEqual(None, uri.version_id) self.assertEqual(1359908801674000, uri.generation) self.assertEqual(uri.names_provider(), False) self.assertEqual(uri.names_container(), False) self.assertEqual(uri.names_bucket(), False) self.assertEqual(uri.names_object(), True) self.assertEqual(uri.names_directory(), False) self.assertEqual(uri.names_file(), False) self.assertEqual(uri.is_stream(), False) self.assertEqual(uri.is_version_specific, True) def test_versioned_gs_object_uri_with_legacy_generation_value(self): uri_str = 'gs://bucket/obj/a/b#1' uri = boto.storage_uri(uri_str, validate=False, suppress_consec_slashes=False) self.assertEqual('gs', uri.scheme) self.assertEqual(uri_str, uri.uri) self.assertEqual('gs://bucket/obj/a/b', uri.versionless_uri) self.assertEqual('bucket', uri.bucket_name) self.assertEqual('obj/a/b', uri.object_name) self.assertEqual(None, uri.version_id) self.assertEqual(1, uri.generation) self.assertEqual(uri.names_provider(), False) self.assertEqual(uri.names_container(), False) self.assertEqual(uri.names_bucket(), False) self.assertEqual(uri.names_object(), True) self.assertEqual(uri.names_directory(), False) self.assertEqual(uri.names_file(), False) self.assertEqual(uri.is_stream(), False) self.assertEqual(uri.is_version_specific, True) def test_roundtrip_versioned_gs_object_uri_parsed(self): uri_str = 'gs://bucket/obj#1359908801674000' uri = boto.storage_uri(uri_str, validate=False, suppress_consec_slashes=False) roundtrip_uri = boto.storage_uri(uri.uri, validate=False, suppress_consec_slashes=False) self.assertEqual(uri.uri, roundtrip_uri.uri) self.assertEqual(uri.is_version_specific, True) def test_versioned_s3_object_uri(self): uri_str = 's3://bucket/obj/a/b#eMuM0J15HkJ9QHlktfNP5MfA.oYR2q6S' uri = boto.storage_uri(uri_str, validate=False, suppress_consec_slashes=False) self.assertEqual('s3', uri.scheme) self.assertEqual(uri_str, uri.uri) self.assertEqual('s3://bucket/obj/a/b', uri.versionless_uri) self.assertEqual('bucket', uri.bucket_name) self.assertEqual('obj/a/b', uri.object_name) self.assertEqual('eMuM0J15HkJ9QHlktfNP5MfA.oYR2q6S', uri.version_id) self.assertEqual(None, uri.generation) self.assertEqual(uri.names_provider(), False) self.assertEqual(uri.names_container(), False) self.assertEqual(uri.names_bucket(), False) self.assertEqual(uri.names_object(), True) self.assertEqual(uri.names_directory(), False) self.assertEqual(uri.names_file(), False) self.assertEqual(uri.is_stream(), False) self.assertEqual(uri.is_version_specific, True) def test_explicit_file_uri(self): tmp_dir = tempfile.tempdir or '' uri_str = 'file://%s' % urllib.request.pathname2url(tmp_dir) uri = boto.storage_uri(uri_str, validate=False, suppress_consec_slashes=False) self.assertEqual('file', uri.scheme) self.assertEqual(uri_str, uri.uri) self.assertFalse(hasattr(uri, 'versionless_uri')) self.assertEqual('', uri.bucket_name) self.assertEqual(tmp_dir, uri.object_name) self.assertFalse(hasattr(uri, 'version_id')) self.assertFalse(hasattr(uri, 'generation')) self.assertFalse(hasattr(uri, 'is_version_specific')) self.assertEqual(uri.names_provider(), False) self.assertEqual(uri.names_bucket(), False) # Don't check uri.names_container(), uri.names_directory(), # uri.names_file(), or uri.names_object(), because for file URIs these # functions look at the file system and apparently unit tests run # chroot'd. self.assertEqual(uri.is_stream(), False) def test_implicit_file_uri(self): tmp_dir = tempfile.tempdir or '' uri_str = '%s' % urllib.request.pathname2url(tmp_dir) uri = boto.storage_uri(uri_str, validate=False, suppress_consec_slashes=False) self.assertEqual('file', uri.scheme) self.assertEqual('file://%s' % tmp_dir, uri.uri) self.assertFalse(hasattr(uri, 'versionless_uri')) self.assertEqual('', uri.bucket_name) self.assertEqual(tmp_dir, uri.object_name) self.assertFalse(hasattr(uri, 'version_id')) self.assertFalse(hasattr(uri, 'generation')) self.assertFalse(hasattr(uri, 'is_version_specific')) self.assertEqual(uri.names_provider(), False) self.assertEqual(uri.names_bucket(), False) # Don't check uri.names_container(), uri.names_directory(), # uri.names_file(), or uri.names_object(), because for file URIs these # functions look at the file system and apparently unit tests run # chroot'd. self.assertEqual(uri.is_stream(), False) def test_gs_object_uri_contains_sharp_not_matching_version_syntax(self): uri_str = 'gs://bucket/obj#13a990880167400' uri = boto.storage_uri(uri_str, validate=False, suppress_consec_slashes=False) self.assertEqual('gs', uri.scheme) self.assertEqual(uri_str, uri.uri) self.assertEqual('gs://bucket/obj#13a990880167400', uri.versionless_uri) self.assertEqual('bucket', uri.bucket_name) self.assertEqual('obj#13a990880167400', uri.object_name) self.assertEqual(None, uri.version_id) self.assertEqual(None, uri.generation) self.assertEqual(uri.names_provider(), False) self.assertEqual(uri.names_container(), False) self.assertEqual(uri.names_bucket(), False) self.assertEqual(uri.names_object(), True) self.assertEqual(uri.names_directory(), False) self.assertEqual(uri.names_file(), False) self.assertEqual(uri.is_stream(), False) self.assertEqual(uri.is_version_specific, False) def test_file_containing_colon(self): uri_str = 'abc:def' uri = boto.storage_uri(uri_str, validate=False, suppress_consec_slashes=False) self.assertEqual('file', uri.scheme) self.assertEqual('file://%s' % uri_str, uri.uri) def test_invalid_scheme(self): uri_str = 'mars://bucket/object' try: boto.storage_uri(uri_str, validate=False, suppress_consec_slashes=False) except InvalidUriError as e: self.assertIn('Unrecognized scheme', e.message) if __name__ == '__main__': unittest.main()
bsd-3-clause
mjg2203/edx-platform-seas
lms/djangoapps/instructor_task/tests/test_tasks.py
24
20923
""" Unit tests for LMS instructor-initiated background tasks. Runs tasks on answers to course problems to validate that code paths actually work. """ import json from uuid import uuid4 from mock import Mock, MagicMock, patch from celery.states import SUCCESS, FAILURE from xmodule.modulestore.exceptions import ItemNotFoundError from courseware.models import StudentModule from courseware.tests.factories import StudentModuleFactory from student.tests.factories import UserFactory, CourseEnrollmentFactory from instructor_task.models import InstructorTask from instructor_task.tests.test_base import InstructorTaskModuleTestCase from instructor_task.tests.factories import InstructorTaskFactory from instructor_task.tasks import rescore_problem, reset_problem_attempts, delete_problem_state from instructor_task.tasks_helper import UpdateProblemModuleStateError PROBLEM_URL_NAME = "test_urlname" class TestTaskFailure(Exception): pass class TestInstructorTasks(InstructorTaskModuleTestCase): def setUp(self): super(InstructorTaskModuleTestCase, self).setUp() self.initialize_course() self.instructor = self.create_instructor('instructor') self.problem_url = InstructorTaskModuleTestCase.problem_location(PROBLEM_URL_NAME) def _create_input_entry(self, student_ident=None, use_problem_url=True, course_id=None): """Creates a InstructorTask entry for testing.""" task_id = str(uuid4()) task_input = {} if use_problem_url: task_input['problem_url'] = self.problem_url if student_ident is not None: task_input['student'] = student_ident course_id = course_id or self.course.id instructor_task = InstructorTaskFactory.create(course_id=course_id, requester=self.instructor, task_input=json.dumps(task_input), task_key='dummy value', task_id=task_id) return instructor_task def _get_xmodule_instance_args(self): """ Calculate dummy values for parameters needed for instantiating xmodule instances. """ return {'xqueue_callback_url_prefix': 'dummy_value', 'request_info': {}, } def _run_task_with_mock_celery(self, task_class, entry_id, task_id, expected_failure_message=None): """Submit a task and mock how celery provides a current_task.""" self.current_task = Mock() self.current_task.request = Mock() self.current_task.request.id = task_id self.current_task.update_state = Mock() if expected_failure_message is not None: self.current_task.update_state.side_effect = TestTaskFailure(expected_failure_message) task_args = [entry_id, self._get_xmodule_instance_args()] with patch('instructor_task.tasks_helper._get_current_task') as mock_get_task: mock_get_task.return_value = self.current_task return task_class.apply(task_args, task_id=task_id).get() def _test_missing_current_task(self, task_class): """Check that a task_class fails when celery doesn't provide a current_task.""" task_entry = self._create_input_entry() with self.assertRaises(ValueError): task_class(task_entry.id, self._get_xmodule_instance_args()) def _test_undefined_course(self, task_class): """Run with celery, but with no course defined.""" task_entry = self._create_input_entry(course_id="bogus/course/id") with self.assertRaises(ItemNotFoundError): self._run_task_with_mock_celery(task_class, task_entry.id, task_entry.task_id) def _test_undefined_problem(self, task_class): """Run with celery, but no problem defined.""" task_entry = self._create_input_entry() with self.assertRaises(ItemNotFoundError): self._run_task_with_mock_celery(task_class, task_entry.id, task_entry.task_id) def _test_run_with_task(self, task_class, action_name, expected_num_succeeded, expected_num_skipped=0): """Run a task and check the number of StudentModules processed.""" task_entry = self._create_input_entry() status = self._run_task_with_mock_celery(task_class, task_entry.id, task_entry.task_id) # check return value self.assertEquals(status.get('attempted'), expected_num_succeeded + expected_num_skipped) self.assertEquals(status.get('succeeded'), expected_num_succeeded) self.assertEquals(status.get('skipped'), expected_num_skipped) self.assertEquals(status.get('total'), expected_num_succeeded + expected_num_skipped) self.assertEquals(status.get('action_name'), action_name) self.assertGreater(status.get('duration_ms'), 0) # compare with entry in table: entry = InstructorTask.objects.get(id=task_entry.id) self.assertEquals(json.loads(entry.task_output), status) self.assertEquals(entry.task_state, SUCCESS) def _test_run_with_no_state(self, task_class, action_name): """Run with no StudentModules defined for the current problem.""" self.define_option_problem(PROBLEM_URL_NAME) self._test_run_with_task(task_class, action_name, 0) def _create_students_with_state(self, num_students, state=None, grade=0, max_grade=1): """Create students, a problem, and StudentModule objects for testing""" self.define_option_problem(PROBLEM_URL_NAME) students = [ UserFactory.create(username='robot%d' % i, email='robot+test+%d@edx.org' % i) for i in xrange(num_students) ] for student in students: CourseEnrollmentFactory.create(course_id=self.course.id, user=student) StudentModuleFactory.create(course_id=self.course.id, module_state_key=self.problem_url, student=student, grade=grade, max_grade=max_grade, state=state) return students def _assert_num_attempts(self, students, num_attempts): """Check the number attempts for all students is the same""" for student in students: module = StudentModule.objects.get(course_id=self.course.id, student=student, module_state_key=self.problem_url) state = json.loads(module.state) self.assertEquals(state['attempts'], num_attempts) def _test_run_with_failure(self, task_class, expected_message): """Run a task and trigger an artificial failure with the given message.""" task_entry = self._create_input_entry() self.define_option_problem(PROBLEM_URL_NAME) with self.assertRaises(TestTaskFailure): self._run_task_with_mock_celery(task_class, task_entry.id, task_entry.task_id, expected_message) # compare with entry in table: entry = InstructorTask.objects.get(id=task_entry.id) self.assertEquals(entry.task_state, FAILURE) output = json.loads(entry.task_output) self.assertEquals(output['exception'], 'TestTaskFailure') self.assertEquals(output['message'], expected_message) def _test_run_with_long_error_msg(self, task_class): """ Run with an error message that is so long it will require truncation (as well as the jettisoning of the traceback). """ task_entry = self._create_input_entry() self.define_option_problem(PROBLEM_URL_NAME) expected_message = "x" * 1500 with self.assertRaises(TestTaskFailure): self._run_task_with_mock_celery(task_class, task_entry.id, task_entry.task_id, expected_message) # compare with entry in table: entry = InstructorTask.objects.get(id=task_entry.id) self.assertEquals(entry.task_state, FAILURE) self.assertGreater(1023, len(entry.task_output)) output = json.loads(entry.task_output) self.assertEquals(output['exception'], 'TestTaskFailure') self.assertEquals(output['message'], expected_message[:len(output['message']) - 3] + "...") self.assertTrue('traceback' not in output) def _test_run_with_short_error_msg(self, task_class): """ Run with an error message that is short enough to fit in the output, but long enough that the traceback won't. Confirm that the traceback is truncated. """ task_entry = self._create_input_entry() self.define_option_problem(PROBLEM_URL_NAME) expected_message = "x" * 900 with self.assertRaises(TestTaskFailure): self._run_task_with_mock_celery(task_class, task_entry.id, task_entry.task_id, expected_message) # compare with entry in table: entry = InstructorTask.objects.get(id=task_entry.id) self.assertEquals(entry.task_state, FAILURE) self.assertGreater(1023, len(entry.task_output)) output = json.loads(entry.task_output) self.assertEquals(output['exception'], 'TestTaskFailure') self.assertEquals(output['message'], expected_message) self.assertEquals(output['traceback'][-3:], "...") class TestRescoreInstructorTask(TestInstructorTasks): """Tests problem-rescoring instructor task.""" def test_rescore_missing_current_task(self): self._test_missing_current_task(rescore_problem) def test_rescore_undefined_course(self): self._test_undefined_course(rescore_problem) def test_rescore_undefined_problem(self): self._test_undefined_problem(rescore_problem) def test_rescore_with_no_state(self): self._test_run_with_no_state(rescore_problem, 'rescored') def test_rescore_with_failure(self): self._test_run_with_failure(rescore_problem, 'We expected this to fail') def test_rescore_with_long_error_msg(self): self._test_run_with_long_error_msg(rescore_problem) def test_rescore_with_short_error_msg(self): self._test_run_with_short_error_msg(rescore_problem) def test_rescoring_unrescorable(self): input_state = json.dumps({'done': True}) num_students = 1 self._create_students_with_state(num_students, input_state) task_entry = self._create_input_entry() mock_instance = MagicMock() del mock_instance.rescore_problem with patch('instructor_task.tasks_helper.get_module_for_descriptor_internal') as mock_get_module: mock_get_module.return_value = mock_instance with self.assertRaises(UpdateProblemModuleStateError): self._run_task_with_mock_celery(rescore_problem, task_entry.id, task_entry.task_id) # check values stored in table: entry = InstructorTask.objects.get(id=task_entry.id) output = json.loads(entry.task_output) self.assertEquals(output['exception'], "UpdateProblemModuleStateError") self.assertEquals(output['message'], "Specified problem does not support rescoring.") self.assertGreater(len(output['traceback']), 0) def test_rescoring_success(self): input_state = json.dumps({'done': True}) num_students = 10 self._create_students_with_state(num_students, input_state) task_entry = self._create_input_entry() mock_instance = Mock() mock_instance.rescore_problem = Mock(return_value={'success': 'correct'}) with patch('instructor_task.tasks_helper.get_module_for_descriptor_internal') as mock_get_module: mock_get_module.return_value = mock_instance self._run_task_with_mock_celery(rescore_problem, task_entry.id, task_entry.task_id) # check return value entry = InstructorTask.objects.get(id=task_entry.id) output = json.loads(entry.task_output) self.assertEquals(output.get('attempted'), num_students) self.assertEquals(output.get('succeeded'), num_students) self.assertEquals(output.get('total'), num_students) self.assertEquals(output.get('action_name'), 'rescored') self.assertGreater(output.get('duration_ms'), 0) def test_rescoring_bad_result(self): # Confirm that rescoring does not succeed if "success" key is not an expected value. input_state = json.dumps({'done': True}) num_students = 10 self._create_students_with_state(num_students, input_state) task_entry = self._create_input_entry() mock_instance = Mock() mock_instance.rescore_problem = Mock(return_value={'success': 'bogus'}) with patch('instructor_task.tasks_helper.get_module_for_descriptor_internal') as mock_get_module: mock_get_module.return_value = mock_instance self._run_task_with_mock_celery(rescore_problem, task_entry.id, task_entry.task_id) # check return value entry = InstructorTask.objects.get(id=task_entry.id) output = json.loads(entry.task_output) self.assertEquals(output.get('attempted'), num_students) self.assertEquals(output.get('succeeded'), 0) self.assertEquals(output.get('total'), num_students) self.assertEquals(output.get('action_name'), 'rescored') self.assertGreater(output.get('duration_ms'), 0) def test_rescoring_missing_result(self): # Confirm that rescoring does not succeed if "success" key is not returned. input_state = json.dumps({'done': True}) num_students = 10 self._create_students_with_state(num_students, input_state) task_entry = self._create_input_entry() mock_instance = Mock() mock_instance.rescore_problem = Mock(return_value={'bogus': 'value'}) with patch('instructor_task.tasks_helper.get_module_for_descriptor_internal') as mock_get_module: mock_get_module.return_value = mock_instance self._run_task_with_mock_celery(rescore_problem, task_entry.id, task_entry.task_id) # check return value entry = InstructorTask.objects.get(id=task_entry.id) output = json.loads(entry.task_output) self.assertEquals(output.get('attempted'), num_students) self.assertEquals(output.get('succeeded'), 0) self.assertEquals(output.get('total'), num_students) self.assertEquals(output.get('action_name'), 'rescored') self.assertGreater(output.get('duration_ms'), 0) class TestResetAttemptsInstructorTask(TestInstructorTasks): """Tests instructor task that resets problem attempts.""" def test_reset_missing_current_task(self): self._test_missing_current_task(reset_problem_attempts) def test_reset_undefined_course(self): self._test_undefined_course(reset_problem_attempts) def test_reset_undefined_problem(self): self._test_undefined_problem(reset_problem_attempts) def test_reset_with_no_state(self): self._test_run_with_no_state(reset_problem_attempts, 'reset') def test_reset_with_failure(self): self._test_run_with_failure(reset_problem_attempts, 'We expected this to fail') def test_reset_with_long_error_msg(self): self._test_run_with_long_error_msg(reset_problem_attempts) def test_reset_with_short_error_msg(self): self._test_run_with_short_error_msg(reset_problem_attempts) def test_reset_with_some_state(self): initial_attempts = 3 input_state = json.dumps({'attempts': initial_attempts}) num_students = 10 students = self._create_students_with_state(num_students, input_state) # check that entries were set correctly self._assert_num_attempts(students, initial_attempts) # run the task self._test_run_with_task(reset_problem_attempts, 'reset', num_students) # check that entries were reset self._assert_num_attempts(students, 0) def test_reset_with_zero_attempts(self): initial_attempts = 0 input_state = json.dumps({'attempts': initial_attempts}) num_students = 10 students = self._create_students_with_state(num_students, input_state) # check that entries were set correctly self._assert_num_attempts(students, initial_attempts) # run the task self._test_run_with_task(reset_problem_attempts, 'reset', 0, expected_num_skipped=num_students) # check that entries were reset self._assert_num_attempts(students, 0) def _test_reset_with_student(self, use_email): """Run a reset task for one student, with several StudentModules for the problem defined.""" num_students = 10 initial_attempts = 3 input_state = json.dumps({'attempts': initial_attempts}) students = self._create_students_with_state(num_students, input_state) # check that entries were set correctly for student in students: module = StudentModule.objects.get(course_id=self.course.id, student=student, module_state_key=self.problem_url) state = json.loads(module.state) self.assertEquals(state['attempts'], initial_attempts) if use_email: student_ident = students[3].email else: student_ident = students[3].username task_entry = self._create_input_entry(student_ident) status = self._run_task_with_mock_celery(reset_problem_attempts, task_entry.id, task_entry.task_id) # check return value self.assertEquals(status.get('attempted'), 1) self.assertEquals(status.get('succeeded'), 1) self.assertEquals(status.get('total'), 1) self.assertEquals(status.get('action_name'), 'reset') self.assertGreater(status.get('duration_ms'), 0) # compare with entry in table: entry = InstructorTask.objects.get(id=task_entry.id) self.assertEquals(json.loads(entry.task_output), status) self.assertEquals(entry.task_state, SUCCESS) # check that the correct entry was reset for index, student in enumerate(students): module = StudentModule.objects.get(course_id=self.course.id, student=student, module_state_key=self.problem_url) state = json.loads(module.state) if index == 3: self.assertEquals(state['attempts'], 0) else: self.assertEquals(state['attempts'], initial_attempts) def test_reset_with_student_username(self): self._test_reset_with_student(False) def test_reset_with_student_email(self): self._test_reset_with_student(True) class TestDeleteStateInstructorTask(TestInstructorTasks): """Tests instructor task that deletes problem state.""" def test_delete_missing_current_task(self): self._test_missing_current_task(delete_problem_state) def test_delete_undefined_course(self): self._test_undefined_course(delete_problem_state) def test_delete_undefined_problem(self): self._test_undefined_problem(delete_problem_state) def test_delete_with_no_state(self): self._test_run_with_no_state(delete_problem_state, 'deleted') def test_delete_with_failure(self): self._test_run_with_failure(delete_problem_state, 'We expected this to fail') def test_delete_with_long_error_msg(self): self._test_run_with_long_error_msg(delete_problem_state) def test_delete_with_short_error_msg(self): self._test_run_with_short_error_msg(delete_problem_state) def test_delete_with_some_state(self): # This will create StudentModule entries -- we don't have to worry about # the state inside them. num_students = 10 students = self._create_students_with_state(num_students) # check that entries were created correctly for student in students: StudentModule.objects.get(course_id=self.course.id, student=student, module_state_key=self.problem_url) self._test_run_with_task(delete_problem_state, 'deleted', num_students) # confirm that no state can be found anymore: for student in students: with self.assertRaises(StudentModule.DoesNotExist): StudentModule.objects.get(course_id=self.course.id, student=student, module_state_key=self.problem_url)
agpl-3.0
hanw/p4c
tools/driver/p4c_src/config.py
1
1610
# Copyright 2013-present Barefoot Networks, 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. from __future__ import absolute_import import sys import os class Config(object): """ Config - Configuration data for a 'p4c' tool chain. The common configuration includes the argument parser and the path to the backend configuration file. """ def __init__(self, config_prefix): self.config_prefix = config_prefix or 'p4c' self.target = [] def load_from_config(self, path, argParser): cfg_globals = dict(globals()) cfg_globals['config'] = self cfg_globals['__file__'] = path cfg_globals['argParser'] = argParser data = None f = open(path) try: data = f.read() except: print "error", path f.close() try: exec(compile(data, path, 'exec'), cfg_globals, None) except SystemExit: e = sys.exc_info()[1] if e.args: raise except: import traceback print traceback.format_exc()
apache-2.0
zimmerst/i2py
i2py/ir.py
3
36412
# # Copyright (C) 2005 Christopher J. Stawarz <chris@pseudogreen.org> # # This file is part of i2py. # # i2py 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. # # i2py 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 i2py; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # """ Defines classes representing the nodes and leaves of the abstract syntax tree (AST). Each such class can produce IDL or Python code for itself via its __str__() or pycode() method, respectively. """ import config import error import re from util import * import yacc import i2py_map ################################################################################ # # Abstract base classes # ################################################################################ class Leaf(object): "Base class for leaves of the AST (terminal symbols)" pass class Node(object): "Base class for nodes of the AST (nonterminal symbols)" # Set of symbols that appear in the RHS of the grammar production for this # node _symbols = () def __init__(self, prod): "Creates a new Node from prod (a yacc.YaccProduction instance)" # Validate input (just a sanity check) if not isinstance(prod, yacc.YaccProduction): raise error.InternalError('expecting YaccProduction, got ' + prod.__class__.__name__) # Store line number and create child_list self.lineno = prod.lineno(0) self.child_list = list(prod)[1:] # # Create child_dict # self.child_dict = {} for item in prod.slice[1:]: if item.type not in self.child_dict: # No entry for this symbol in child_dict, so make one self.child_dict[item.type] = item.value else: # There's already an entry for this symbol in child_dict, so the # entry's value must be a list if isinstance(self.child_dict[item.type], list): # Already a list, so append to it self.child_dict[item.type].append(item.value) else: # Make list from previous and current value self.child_dict[item.type] = ([self.child_dict[item.type], item.value]) # For each valid symbol that isn't involved in this instance, make an # entry in child_dict with value None for symbol in self._symbols: if symbol not in self.child_dict: self.child_dict[symbol] = None def __getattr__(self, name): """ Given a symbol name from the right-hand side of the grammar production for this node, returns the corresponding child node. If the production includes multiple instances of the symbol, returns a list of their values (ordered from left to right). If the given symbol is not used in the current instance, returns None. """ return name in self.child_dict and self.child_dict[name] def __getitem__(self, index): """ Returns the child node for the symbol at the corresponding position in the right-hand side of the grammar production for this node. Note that, unlike __getattr__, this function only provides access to symbols actually used in the current instance. """ return self.child_list[index] def __len__(self): """ Returns the number of child nodes in the current instance. This is useful for distinguishing which branch of a grammar production applies to the instance. """ return len(self.child_list) def __str__(self): """ Returns a string containing the IDL code for the AST rooted at this node. """ return ''.join([ str(child) for child in self ]) def pycode(self): """ Returns a string containing the Python code for the AST rooted at this node. """ return ''.join([ pycode(child) for child in self ]) ################################################################################ # # Terminal symbols # ################################################################################ class Newline(Leaf): def __init__(self, raw): rawlines = raw.split('\n') rawlines = [rawlines[0]] + [ l.strip() for l in rawlines[1:] ] self.lines = [] for l in rawlines: if l.strip() == '': l = '' else: if l[:1] == '&': l = ' ' + l if l[len(l) - 1] == '&': l = l + ' ' self.lines.append(l) def __str__(self): return '\n'.join(self.lines) def pycode(self): lines = [] for l in self.lines: # if l.strip()[:1] == ';': # l = l.replace(';', '#', 1) m = re.match(r'\s*(;+)', l) if m: l = l.replace(';', '#', len(m.groups()[0])) else: l = l.replace('&', ';') lines.append(l) return '\n'.join(lines) def asdocstring(self): doc = self.pycode().strip() try: ii = doc.index('#+') jj = doc.index('#-') doc = doc[ii:jj+2] except ValueError: pass doc = '\n'.join([ l.replace('#', '', 1) for l in doc.split('\n') ][1:-1]) if len(doc): return '"""\n%s\n"""' % doc return '' class Name(Leaf): def __init__(self, raw): self.raw = raw def __str__(self): return config.idlnameconv(self.raw) def pycode(self): vmap = i2py_map.get_variable_map(self.raw) if vmap: return vmap.pyname() return pyname(self.raw) class Number(Leaf): def __init__(self, parts): self.parts = parts def __getattr__(self, name): return self.parts[name] def __str__(self): if self.float: return self.float return self.integer def pycode(self): if self.float: s = self.dec if self.exp: s += 'e' if self.expval: s += self.expval else: s += '0' else: if self.val[0] == "'": if self.val[-1].lower() == 'x': s = '0x' + self.val[1:-2].lower() elif self.val[-1].lower() == 'o': s = self.val[1:-2] if s[0] != '0': s = '0' + s elif self.val[-1].lower() == 'b': s = '0b' + self.val[1:-2] else: raise RuntimeError("Invalid numeric literal") elif self.val[0] == '"': s = self.val[1:] if s[0] != '0': s = '0' + s else: s = self.val return s ################################################################################ # # Nonterminal symbols # ################################################################################ class TranslationUnit(Node): def pycode(self): global _classes_used _classes_used = {} import ipdb; ipdb.set_trace() parts = [] if self.statement_list: parts.append(pycode(self.statement_list)) if self.program: parts.append(pycode(self.program)) ec = i2py_map.get_extra_code() if ec: parts.append(ec) for cname in _classes_used: c = _classes_used[cname] if ~hasattr(c, 'init_def'): # bare methods, no class definition or initializer method parts.append(('class %s(%s):\n'% (pycode(cname), config.baseclassname) \ + "\n".join([ pyindent(m) for m in c.methods]))) continue parts.append(('class %s(%s):\n'% (pycode(cname), c.base_classes) \ + "\n".join([ pyindent(m) for m in ['__i2py_tagnames__ = %s\n' % (c.tag_names), c.init_def ] + c.methods]))) if _classes_used: # IDL structs become objects of type I2PY_Struct, or subclasses thereof init_def = 'def __init__(self, *args, **kws):\n' \ + pyindent('self.__dict__.update(zip(self.__i2py_tagnames__, args))\n') \ + pyindent('self.__dict__.update(kws)') get_def = 'def __getitem__(self, key):\n' \ + pyindent('return self.__dict__[self.__i2py_tagnames__[key]]') repr_def = 'def __repr__(self):\n' \ + pyindent('return "%s(%s)" % (self.__class__.__name__,\n') \ + pyindent(pyindent('", ".join("%s=%s" % (k, v) for k, v in self.__dict__.iteritems()))')) parts.append(('class %s(object):\n'% config.baseclassname) \ + pyindent('__i2py_tagnames__ = []') + '\n' \ + pyindent(init_def) + '\n' \ + pyindent(get_def) + '\n' \ + pyindent(repr_def)) parts.append('from %s import *' % config.arraymodule) # import ipdb; ipdb.set_trace() try: nl = self.NEWLINE[0] except TypeError: nl = self.NEWLINE if nl: doc = nl.asdocstring() if doc: parts.append(doc) else: parts[0] = pycode(nl) + parts[0] parts.reverse() return '\n\n'.join(parts) _in_pro = False _in_function = False def find_structure_body(self): # Dig through the AST to find the class definition try: sb = self.structure_body if sb: return sb for child in self.child_list: sb = find_structure_body(child) if sb: return sb except: pass return None def ClassDefinition(name, structbody): """ will this work? """ global _classes_used #import ipdb; ipdb.set_trace() if name not in _classes_used: _classes_used[name] = type("", (), {})() # anonymous type _classes_used[name].methods = [] p = _classes_used[name] bc_names, tag_names, init_body = structbody.structure_field_list.classdef() p.base_classes = ", ".join(bc_names + [config.baseclassname]) p.tag_names = tag_names # header = 'class %s(%s):' % (pycode(name), superclasses) # tag_names = '__i2py_tagnames__ = ' + str(tag_names) init_body = init_body + '\n' + "%s.__init__(self, *args, **kws)\n" % config.baseclassname if hasattr(p, 'init_def'): p.init_def = p.init_def[0] + pyindent(init_body) + p.init_def[1] else: p.init_def = "def __init__(self, *args, **kws):" + '\n' + pyindent(init_body) return '' class SubroutineDefinition(Node): def __str__(self): return '%s %s' % tuple(self) def pycode(self): global _in_pro, _in_function, _classes_used pars = [] keys = [] extra = [] method = False # import ipdb; ipdb.set_trace() plist = self.subroutine_body.parameter_list if self.subroutine_body.method_name.DCOLON is None: name = pycode(self.subroutine_body.method_name) if name[-8:].lower() == '__define': # class definition if plist: print "Class definition with parameters -- probably not allowed!" return ClassDefinition(name[:-8], find_structure_body(self)) else: # Method definition classname, name = map(pycode, self.subroutine_body.method_name.IDENTIFIER) # methodname = pycode(methodname) # classname = pycode(classname) method = True if plist: for p in plist.get_items(): if p.EXTRA: extra = pycode(p.IDENTIFIER) if p.IDENTIFIER else "extra" continue if p.EQUALS: keys.append((pycode(p.IDENTIFIER[0]), pycode(p.IDENTIFIER[1]))) else: pars.append(pycode(p.IDENTIFIER)) fmap = i2py_map.get_subroutine_map(name) if not fmap: inpars = range(1, len(pars)+1) outpars = inpars inkeys = [ k[0] for k in keys ] outkeys = inkeys if self.PRO: _in_pro = True if not fmap: fmap = i2py_map.map_pro(name, inpars=inpars, outpars=outpars, inkeys=inkeys, outkeys=outkeys, method=method) elif self.FUNCTION: _in_function = True if not fmap: fmap = i2py_map.map_func(name, inpars=inpars, inkeys=inkeys, method=method) else: raise RuntimeError("not PRO, not FUNCTION, then what?") try: header, body = fmap.pydef(pars, keys, extra=extra) except i2py_map.Error, e: error.mapping_error(str(e), self.lineno) header, body = '', '' # import ipdb; ipdb.set_trace() body += '\n' + pycode(self.subroutine_body.statement_list) if self.PRO or self.FUNCTION: last = self.subroutine_body.statement_list.get_statements()[-1] jump = last.simple_statement and last.simple_statement.jump_statement if (not jump) or (not jump.RETURN): body += '\nreturn _ret()\n' nl = self.subroutine_body.NEWLINE[0] doc = nl.asdocstring() if doc: nl = '\n' + pyindent(doc) + '\n\n' else: nl = pycode(nl) _in_pro = False _in_function = False # Plain functions if self.subroutine_body.method_name.DCOLON is None: return (header + nl + pyindent(body) + pycode(self.subroutine_body.NEWLINE[1])) # Methods #import ipdb; ipdb.set_trace() # header = header.replace(name, methodname) if classname not in _classes_used: _classes_used[classname] = type("", (), {})() # anonymous type _classes_used[classname].methods = [] p = _classes_used[classname] if name == 'init': header = header.replace('init', '__init__') p.init_def = [header + nl, pyindent(body)] else: p.methods.append(header + nl + pyindent(body) + pycode(self.subroutine_body.NEWLINE[1])) return "" class SubroutineBody(Node): def __str__(self): if self.parameter_list: params = ', ' + str(self.parameter_list) else: params = '' return '%s%s%s%sEND%s' % (self.IDENTIFIER, params, self.NEWLINE[0], indent(self.statement_list), self.NEWLINE[1]) class _CommaSeparatedList(Node): def __str__(self): if len(self) == 1: return str(self[0]) return '%s, %s' % (self[0], self[2]) def pycode(self): if len(self) == 1: return pycode(self[0]) return '%s, %s' % (pycode(self[0]), pycode(self[2])) def classdef(self): if len(self) == 1: return classdef(self[0]) sc0, n0, b0 = classdef(self[0]) sc1, n1, b1 = classdef(self[2]) return sc0+sc1, n0+n1, '%s%s' % (b0, b1) def get_items(self): if len(self) == 1: items = [self[0]] else: items = self[0].get_items() items.append(self[2]) return items class ParameterList(_CommaSeparatedList): pass class LabeledStatement(Node): def __str__(self): if self.NEWLINE: return '%s:%s%s' % (self.IDENTIFIER, self.NEWLINE, self.statement) return '%s: %s' % (self.IDENTIFIER, self.statement) def pycode(self): if self.NEWLINE: nl = pycode(self.NEWLINE) else: nl = '\n' return '%s:%s%s' % (pycomment(self.IDENTIFIER), nl, pycode(self.statement)) class StatementList(Node): def get_statements(self): if not self.statement_list: stmts = [self.statement] else: stmts = self.statement_list.get_statements() stmts.append(self.statement) return stmts class IfStatement(Node): def __str__(self): s = 'IF %s THEN %s' % (self.expression, self.if_clause) if self.else_clause: s += ' ELSE %s' % self.else_clause return s def pycode(self): s = 'if %s:%s' % (pycode(self.expression), pyindent(self.if_clause).rstrip('\n')) if self.else_clause: s += '\nelse:%s' % pyindent(self.else_clause).rstrip('\n') return s class _IfOrElseClause(Node): def __str__(self): if not self.BEGIN: return str(self.statement) return 'BEGIN%s%s%s' % (self.NEWLINE, indent(self.statement_list), self[-1]) def pycode(self): if not self.BEGIN: return '\n' + pycode(self.statement) return pycode(self.NEWLINE) + pycode(self.statement_list) class IfClause(_IfOrElseClause): pass class ElseClause(_IfOrElseClause): pass class SelectionStatement(Node): def pycode(self): body = self.selection_statement_body s = '_expr = %s%s' % (pycode(body.expression), pycode(body.NEWLINE)) if self.CASE: is_switch = False else: is_switch = True s += '_match = False\n' cases, actions = body.selection_clause_list.get_cases_and_actions() key = 'if' first = True for c, a in zip(cases, actions): test = reduce_expression('(%s)' % c) test = '_expr == %s' % test if (not first) and is_switch: test = '_match or (%s)' % test s += '%s %s:%s' % (key, test, pyindent(a)) if is_switch: s += '%s\n' % pyindent('_match = True') if first: if is_switch: key = 'if' else: key = 'elif' first = False if body.ELSE: s += 'else:%s' % pyindent(body.selection_clause) elif not is_switch: s += 'else:\n%s' % pyindent("raise RuntimeError('no match found " + "for expression')") return s class SelectionStatementBody(Node): def __str__(self): s = ' %s OF%s%s' % (self.expression, self.NEWLINE, indent(self.selection_clause_list)) if self.ELSE: s += indent('ELSE %s' % self.selection_clause) return s class SelectionClauseList(Node): def get_cases_and_actions(self): if self.selection_clause_list: cases, actions = self.selection_clause_list.get_cases_and_actions() else: cases = [] actions = [] cases.append(pycode(self.expression)) actions.append(pycode(self.selection_clause)) return (cases, actions) class SelectionClause(Node): def __str__(self): if self.BEGIN: nl = self.NEWLINE[1] stmt = ' BEGIN%s%s END' % (self.NEWLINE[0], indent(self.statement_list, 2)) else: nl = self.NEWLINE if self.statement: stmt = ' %s' % self.statement else: stmt = '' return ':%s%s' % (stmt, nl) def pycode(self): if self.statement_list: return '%s%s%s' % (pycode(self.NEWLINE[0]), pycode(self.statement_list).rstrip('\n'), pycode(self.NEWLINE[1])) if self.statement: return '\n' + pycode(self.statement) + pycode(self.NEWLINE) return '\npass' + pycode(self.NEWLINE) class ForStatement(Node): def __str__(self): if self.BEGIN: stmt = 'BEGIN%s%sENDFOR' % (self.NEWLINE, indent(self.statement_list)) else: stmt = str(self.statement) return 'FOR %s DO %s' % (self.for_index, stmt) def pycode(self): if self.statement: body = self.statement nl = '\n' else: body = self.statement_list nl = pycode(self.NEWLINE) return 'for %s:%s%s' % (pycode(self.for_index), nl, pyindent(body).rstrip('\n')) class ForIndex(Node): def __str__(self): s = '%s = %s, %s' % (self.IDENTIFIER, self.expression[0], self.expression[1]) if len(self.expression) == 3: s += ', %s' % self.expression[2] return s def pycode(self): minval = pycode(self.expression[0]) maxval = pycode(self.expression[1]) if len(self.expression) == 3: incval = pycode(self.expression[2]) else: incval = '1' maxval = reduce_expression('(%s)+(%s)' % (maxval, incval)) s = '%s in arange(%s, %s' % (pycode(self.IDENTIFIER), minval, maxval) if len(self.expression) == 3: s += ', %s' % incval return s + ')' class ForeachStatement(Node): def __str__(self): # ids = self.identifier_list.get_items() # if len(ids) != 2: raise ValueError("Need two identifiers in FOREACH") for_ind = str(self.foreach_index) if self.BEGIN: stmt = 'BEGIN%s%sENDFOREACH' % (self.NEWLINE, indent(self.statement_list)) else: stmt = str(self.statement) return 'FOREACH %s DO %s' % (for_ind, stmt) def pycode(self): # import ipdb; ipdb.set_trace() # ids = self.identifier_list.get_items() # if len(ids) != 2: raise ValueError("Need two identifiers in FOREACH") if self.statement: body = self.statement nl = '\n' else: body = self.statement_list nl = pycode(self.NEWLINE) return 'for %s:%s%s' % (pycode(self.foreach_index), nl, pyindent(body).rstrip('\n')) class ForeachIndex(Node): def __str__(self): # import ipdb; ipdb.set_trace() try: return "%s, %s, %s" % (self.IDENTIFIER[0], self.expression, self.IDENTIFIER[1]) except TypeError: return "%s, %s" % (self.IDENTIFIER, self.expression) def pycode(self): # if self.IDENTIFIER is a list, then there is a KEY which is hard to deal # with properly in the general case. Assume EXPRESSION is a hashtable for now. # import ipdb; ipdb.set_trace() try: if len(self.IDENTIFIER) != 2: raise ValueError("Need two identifiers to FOREACH with key") return "%s, %s in %s.iteritems()" % (pycode(self.IDENTIFIER[1]), pycode(self.IDENTIFIER[0]), pycode(self.expression)) except TypeError: return "%s in %s.itervalues()" % (pycode(self.IDENTIFIER), pycode(self.expression)) class WhileStatement(Node): def __str__(self): if self.BEGIN: stmt = 'BEGIN%s%sENDWHILE' % (self.NEWLINE, indent(self.statement_list)) else: stmt = str(self.statement) return 'WHILE %s DO %s' % (self.expression, stmt) def pycode(self): if self.statement: body = self.statement nl = '\n' else: body = self.statement_list nl = pycode(self.NEWLINE) return 'while %s:%s%s' % (pycode(self.expression), nl, pyindent(body).rstrip('\n')) class RepeatStatement(Node): def __str__(self): if self.BEGIN: stmt = 'BEGIN%s%sENDREP' % (self.NEWLINE, indent(self.statement_list)) else: stmt = str(self.statement) return 'REPEAT %s UNTIL %s' % (stmt, self.expression) def pycode(self): if self.statement: body = self.statement nl = '\n' else: body = self.statement_list nl = pycode(self.NEWLINE) return 'while True:%s%s\n%s' % (nl, pyindent(body).rstrip('\n'), pyindent('if %s: break' % pycode(self.expression))) class SimpleStatement(Node): def __str__(self): return ' '.join([ str(c) for c in self ]) def pycode(self): if self.COMMON: if (not _in_pro) and (not _in_function): error.syntax_error('COMMON outside of PRO or FUNCTION', self.lineno) return '' return 'global ' + ', '.join([ pycode(id) for id in self.identifier_list.get_items()[1:] ]) if len(self) == 1: return Node.pycode(self) return pycomment(str(self)) class IdentifierList(_CommaSeparatedList): pass class JumpStatement(Node): def __str__(self): if self.RETURN and self.expression: return 'RETURN, %s' % self.expression if self.GOTO: return 'GOTO, %s' % self.IDENTIFIER return Node.__str__(self) def pycode(self): if self.GOTO: error.conversion_error('cannot convert GOTO statements; please ' + 'remove them and try again', self.lineno) return pycomment(str(self)) if not self.RETURN: return str(self[0]).lower() if _in_pro: return 'return _ret()' if _in_function: return 'return ' + pycode(self.expression) error.syntax_error('RETURN outside of PRO or FUNCTION', self.lineno) return '' class ProcedureCall(Node): def __str__(self): if not self.argument_list: return str(self.method_or_proc) return '%s, %s' % (self.method_or_proc, self.argument_list) def pycode(self): if self.argument_list: pars, keys, extra = self.argument_list.get_pars_and_keys() else: pars = [] keys = [] extra = [] name = str(self.method_or_proc) fmap = i2py_map.get_subroutine_map(name) if not fmap: keys = [ '%s=%s' % (k[0], k[1]) for k in keys ] return '%s(%s)' % (pycode(self.method_or_proc), ', '.join(pars + keys + extra)) try: return fmap.pycall(pars, keys) except i2py_map.Error, e: error.mapping_error(str(e), self.lineno) return '' class ArgumentList(_CommaSeparatedList): def get_pars_and_keys(self): pars = [] keys = [] extra = [] for a in self.get_items(): if a.EXTRA: # FIXME: implement this! # error.conversion_error("can't handle _EXTRA yet", self.lineno) extra = ['**' + pycode(a[-1])] elif a.DIVIDE: keys.append((pycode(a.IDENTIFIER), 'True')) elif a.IDENTIFIER: keys.append((pycode(a.IDENTIFIER), pycode(a.expression))) else: pars.append(pycode(a.expression)) return (pars, keys, extra) class _SpacedExpression(Node): def __str__(self): if (len(self) == 2) and (not self.NOT): return '%s%s' % tuple(self) return ' '.join([ str(c) for c in self ]) def pycode(self): if (len(self) == 2) and (not self.NOT): return '%s%s' % (pycode(self[0]), pycode(self[1])) return ' '.join([ pycode(c) for c in self ]) class AssignmentStatement(_SpacedExpression): def pycode(self): if (len(self) == 1) or self.assignment_operator.EQUALS: return _SpacedExpression.pycode(self) op = self.assignment_operator.OP_EQUALS lvalue = pycode(self.pointer_expression) rvalue = pycode(self.expression) if op == '#=': return (('%s = transpose(matrixmultiply(transpose(%s), ' + 'transpose(%s)))') % (lvalue, lvalue, rvalue)) augops = {'AND=':'&=', 'MOD=':'%=', 'XOR=':'^=', 'OR=':'|=', '+=':'+=', '-=':'-=', '*=':'*=', '/=':'/=', '^=':'**='} binops = {'EQ=':'==', 'GE=':'>=', 'GT=':'>', 'LE=':'<=', 'LT=':'<', 'NE=':'!='} funcops = {'##=':'matrixmultiply', '<=':'minimum', '>=':'maximum'} if op in augops: return '%s %s %s' % (lvalue, augops[op], rvalue) if op in binops: return '%s = %s %s %s' % (lvalue, lvalue, binops[op], rvalue) return '%s = %s(%s, %s)' % (lvalue, funcops[op], lvalue, rvalue) class IncrementStatement(Node): def pycode(self): if self.PLUSPLUS: op = '+' else: op = '-' return '%s %s= 1' % (pycode(self.pointer_expression), op) class Expression(Node): def pycode(self): if self.assignment_statement: # FIXME: implement this! error.conversion_error("can't handle assignment in expressions yet", self.lineno) return '' return Node.pycode(self) class ConditionalExpression(_SpacedExpression): def pycode(self): if not self.QUESTIONMARK: return _SpacedExpression.pycode(self) #return ('((%s) and [%s] or [%s])[0]' % # (pycode(self.logical_expression), pycode(self.expression), # pycode(self.conditional_expression))) return '%s if %s else %s' % (pycode(self.conditional_expression[0]), pycode(self.logical_expression), pycode(self.conditional_expression[1])) class LogicalExpression(_SpacedExpression): def pycode(self): if len(self) == 1: return _SpacedExpression.pycode(self) if self.AMPAMP: op = 'and' else: op = 'or' return 'logical_%s(%s, %s)' % (op, pycode(self.logical_expression), pycode(self.bitwise_expression)) class BitwiseExpression(_SpacedExpression): def pycode(self): if len(self) == 1: return _SpacedExpression.pycode(self) if self.AND: op = 'and' elif self.OR: op = 'or' else: op = 'xor' return 'bitwise_%s(%s, %s)' % (op, pycode(self.bitwise_expression), pycode(self.relational_expression)) class RelationalExpression(_SpacedExpression): def pycode(self): if len(self) == 1: return _SpacedExpression.pycode(self) if self.EQ: op = '==' elif self.NE: op = '!=' elif self.LE: op = '<=' elif self.LT: op = '<' elif self.GE: op = '>=' else: op = '>' return '%s %s %s' % (pycode(self.relational_expression), op, pycode(self.additive_expression)) class AdditiveExpression(_SpacedExpression): def pycode(self): if (len(self) == 1) or self.PLUS or self.MINUS: return _SpacedExpression.pycode(self) if self.NOT: return 'bitwise_not(%s)' % pycode(self.multiplicative_expression) if self.LESSTHAN: f = '>' # looks wrong, but is correct. else: f = '<' a = pycode(self.additive_expression) m = pycode(self.multiplicative_expression) return 'choose(%s %s %s, (%s, %s))' % (a, f, m, a, m) class MultiplicativeExpression(_SpacedExpression): def pycode(self): if len(self) == 1: return _SpacedExpression.pycode(self) if self.POUND: return ('transpose(matrixmultiply(transpose(%s), transpose(%s)))' % (pycode(self.multiplicative_expression), pycode(self.exponentiative_expression))) if self.POUNDPOUND: return ('matrixmultiply(%s, %s)' % (pycode(self.multiplicative_expression), pycode(self.exponentiative_expression))) if self.TIMES: op = '*' elif self.DIVIDE: op = '/' else: op = '%' return '%s %s %s' % (pycode(self.multiplicative_expression), op, pycode(self.exponentiative_expression)) class ExponentiativeExpression(_SpacedExpression): def pycode(self): if len(self) == 1: return _SpacedExpression.pycode(self) return '%s ** %s' % (pycode(self.exponentiative_expression), pycode(self.unary_expression)) class UnaryExpression(Node): def pycode(self): if self.TILDE: return 'logical_not(%s)' % pycode(self.pointer_expression) if self.increment_statement: # FIXME: implement this! #error.conversion_error("can't handle ++,-- in expressions yet", self.lineno) return '%s #{ %s }#' % (Node.pycode(self.increment_statement.pointer_expression), "".join(pycode(x) for x in self.increment_statement[:])) return Node.pycode(self) class PointerExpression(Node): def pycode(self): if self.TIMES: # FIXME: implement this! #error.conversion_error("can't handle pointers yet", self.lineno) return self.pointer_expression.pycode() return Node.pycode(self) class PostfixExpression(Node): def pycode(self): if self.DOT and self.LPAREN: # import ipdb; ipdb.set_trace() return "%s[%s]" % (pycode(self.postfix_expression), pycode(self.expression)) if self.ARROW: return "%s.%s" % (pycode(self.postfix_expression[0]), pycode(self.postfix_expression[1])) if self.DOT or (not self.method_or_proc): return Node.pycode(self) if self.argument_list: pars, keys, extra = self.argument_list.get_pars_and_keys() else: pars = [] keys = [] extra = [] name = str(self.method_or_proc) fmap = i2py_map.get_subroutine_map(name) if not fmap: keys = [ '%s=%s' % (k[0], k[1]) for k in keys ] return '%s(%s)' % (pycode(self.method_or_proc), ', '.join(pars + keys + extra)) try: return fmap.pycall(pars, keys) except i2py_map.Error, e: error.mapping_error(str(e), self.lineno) return '' class PrimaryExpression(Node): def pycode(self): if self.LBRACE: return pycode(self.structure_body) if self.LBRACKET: return 'array([%s])' % Node.pycode(self) return Node.pycode(self) class SubscriptList(Node): def pycode(self): if len(self) == 1: return pycode(self[0]) return ','.join([pycode(self[2]), pycode(self[0])]) class Subscript(Node): def pycode(self): if self.COLON: if not self.TIMES: ulim = reduce_expression('(%s)+1' % pycode(self.expression[1])) s = '%s:%s' % (pycode(self.expression[0]), ulim) if len(self.expression) == 3: s += ':%s' % pycode(self.expression[2]) return s if len(self.expression) == 1: return '%s:' % pycode(self.expression) return '%s::%s' % (pycode(self.expression[0]), pycode(self.expression[1])) if self.TIMES: return ':' return pycode(self.expression) class ExpressionList(_CommaSeparatedList): pass # Anonymous IDL structures will become instances of the class I2PY_Struct, # and all structure creation will become object instantiation class StructureBody(Node): def __str__(self): if self.IDENTIFIER: s = str(self.IDENTIFIER) if self.COMMA: s += ', %s' % self.structure_field_list return s return Node.__str__(self) def pycode(self): global _classes_used # print "jobbing" # return self.__super__.pycode(self) # import ipdb; ipdb.set_trace() classname = config.baseclassname if self.IDENTIFIER: classname = pycode(self.IDENTIFIER) classbody = pycode(self.structure_field_list) else: classname = config.baseclassname classbody = pycode(self.anonymous_struct_field_list) return '%s(%s)' % (classname, classbody) class StructureFieldList(_CommaSeparatedList): def pycode(self): if self.structure_field.INHERITS: if self.structure_field_list: return pycode(self.structure_field_list) return None if len(self) == 1: return pycode(self[0]) sflist, sf = (pycode(self[0]), pycode(self[2])) if sflist is None: return sf return '%s, %s' % (sflist, sf) class AnonymousStructFieldList(_CommaSeparatedList): pass class StructureField(Node): def __str__(self): if self.INHERITS: return 'INHERITS %s' % self.IDENTIFIER return ''.join([ str(c) for c in self ]) def pycode(self): #import ipdb; ipdb.set_trace() if self.INHERITS: return '' if self.IDENTIFIER: return "%s=%s" % (pycode(self.IDENTIFIER), pycode(self.expression)) return pycode(self.expression) def classdef(self): if self.INHERITS: return [pycode(self.IDENTIFIER)], [], '' return [], [pycode(self.IDENTIFIER)], "self.%s=%s\n" % (pycode(self.IDENTIFIER), pycode(self.expression)) class AnonymousStructField(Node): def pycode(self): return "%s=%s" % (pycode(self.IDENTIFIER), pycode(self.expression)) def classdef(self): return [], [pycode(self.IDENTIFIER)], "self.%s=%s\n" % (pycode(self.IDENTIFIER), pycode(self.expression)) class MethodOrProc(Node): def pycode(self): if self.object_method: return "%s.%s" % (pycode(self.object_method.pointer_expression), pycode(self.object_method.method_name)) return pycode(self.IDENTIFIER) class MethodName(Node): def pycode(self): if self.DCOLON: return ".".join(pycode(x) for x in self.IDENTIFIER) else: return pycode(self.IDENTIFIER)
gpl-2.0
froyobin/horizon
openstack_dashboard/dashboards/project/access_and_security/security_groups/forms.py
4
18887
# Copyright 2012 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Copyright 2012 Nebula, 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 netaddr from django.conf import settings from django.core.urlresolvers import reverse from django.core import validators from django.forms import ValidationError # noqa from django.utils.translation import ugettext_lazy as _ from horizon import exceptions from horizon import forms from horizon import messages from horizon.utils import validators as utils_validators from openstack_dashboard import api from openstack_dashboard.utils import filters class CreateGroup(forms.SelfHandlingForm): name = forms.CharField(label=_("Name"), max_length=255, error_messages={ 'required': _('This field is required.'), 'invalid': _("The string may only contain" " ASCII characters and numbers.")}, validators=[validators.validate_slug]) description = forms.CharField(label=_("Description"), required=False, widget=forms.Textarea(attrs={'rows': 4})) def handle(self, request, data): try: sg = api.network.security_group_create(request, data['name'], data['description']) messages.success(request, _('Successfully created security group: %s') % data['name']) return sg except Exception: redirect = reverse("horizon:project:access_and_security:index") exceptions.handle(request, _('Unable to create security group.'), redirect=redirect) class UpdateGroup(forms.SelfHandlingForm): id = forms.CharField(widget=forms.HiddenInput()) name = forms.CharField(label=_("Name"), max_length=255, error_messages={ 'required': _('This field is required.'), 'invalid': _("The string may only contain" " ASCII characters and numbers.")}, validators=[validators.validate_slug]) description = forms.CharField(label=_("Description"), required=False, widget=forms.Textarea(attrs={'rows': 4})) def handle(self, request, data): try: sg = api.network.security_group_update(request, data['id'], data['name'], data['description']) messages.success(request, _('Successfully updated security group: %s') % data['name']) return sg except Exception: redirect = reverse("horizon:project:access_and_security:index") exceptions.handle(request, _('Unable to update security group.'), redirect=redirect) class AddRule(forms.SelfHandlingForm): id = forms.CharField(widget=forms.HiddenInput()) rule_menu = forms.ChoiceField(label=_('Rule'), widget=forms.Select(attrs={ 'class': 'switchable', 'data-slug': 'rule_menu'})) # "direction" field is enabled only when custom mode. # It is because most common rules in local_settings.py is meaningful # when its direction is 'ingress'. direction = forms.ChoiceField( label=_('Direction'), required=False, widget=forms.Select(attrs={ 'class': 'switched', 'data-switch-on': 'rule_menu', 'data-rule_menu-tcp': _('Direction'), 'data-rule_menu-udp': _('Direction'), 'data-rule_menu-icmp': _('Direction'), 'data-rule_menu-custom': _('Direction'), 'data-rule_menu-all_tcp': _('Direction'), 'data-rule_menu-all_udp': _('Direction'), 'data-rule_menu-all_icmp': _('Direction'), })) ip_protocol = forms.IntegerField( label=_('IP Protocol'), required=False, help_text=_("Enter an integer value between 0 and 255 " "(or -1 which means wildcard)."), validators=[utils_validators.validate_ip_protocol], widget=forms.TextInput(attrs={ 'class': 'switched', 'data-switch-on': 'rule_menu', 'data-rule_menu-custom': _('IP Protocol')})) port_or_range = forms.ChoiceField( label=_('Open Port'), choices=[('port', _('Port')), ('range', _('Port Range'))], widget=forms.Select(attrs={ 'class': 'switchable switched', 'data-slug': 'range', 'data-switch-on': 'rule_menu', 'data-rule_menu-tcp': _('Open Port'), 'data-rule_menu-udp': _('Open Port')})) port = forms.IntegerField(label=_("Port"), required=False, help_text=_("Enter an integer value " "between 1 and 65535."), widget=forms.TextInput(attrs={ 'class': 'switched', 'data-switch-on': 'range', 'data-range-port': _('Port')}), validators=[ utils_validators.validate_port_range]) from_port = forms.IntegerField(label=_("From Port"), required=False, help_text=_("Enter an integer value " "between 1 and 65535."), widget=forms.TextInput(attrs={ 'class': 'switched', 'data-switch-on': 'range', 'data-range-range': _('From Port')}), validators=[ utils_validators.validate_port_range]) to_port = forms.IntegerField(label=_("To Port"), required=False, help_text=_("Enter an integer value " "between 1 and 65535."), widget=forms.TextInput(attrs={ 'class': 'switched', 'data-switch-on': 'range', 'data-range-range': _('To Port')}), validators=[ utils_validators.validate_port_range]) icmp_type = forms.IntegerField(label=_("Type"), required=False, help_text=_("Enter a value for ICMP type " "in the range (-1: 255)"), widget=forms.TextInput(attrs={ 'class': 'switched', 'data-switch-on': 'rule_menu', 'data-rule_menu-icmp': _('Type')}), validators=[ utils_validators.validate_port_range]) icmp_code = forms.IntegerField(label=_("Code"), required=False, help_text=_("Enter a value for ICMP code " "in the range (-1: 255)"), widget=forms.TextInput(attrs={ 'class': 'switched', 'data-switch-on': 'rule_menu', 'data-rule_menu-icmp': _('Code')}), validators=[ utils_validators.validate_port_range]) remote = forms.ChoiceField(label=_('Remote'), choices=[('cidr', _('CIDR')), ('sg', _('Security Group'))], help_text=_('To specify an allowed IP ' 'range, select "CIDR". To ' 'allow access from all ' 'members of another security ' 'group select "Security ' 'Group".'), widget=forms.Select(attrs={ 'class': 'switchable', 'data-slug': 'remote'})) cidr = forms.IPField(label=_("CIDR"), required=False, initial="0.0.0.0/0", help_text=_("Classless Inter-Domain Routing " "(e.g. 192.168.0.0/24)"), version=forms.IPv4 | forms.IPv6, mask=True, widget=forms.TextInput( attrs={'class': 'switched', 'data-switch-on': 'remote', 'data-remote-cidr': _('CIDR')})) security_group = forms.ChoiceField(label=_('Security Group'), required=False, widget=forms.Select(attrs={ 'class': 'switched', 'data-switch-on': 'remote', 'data-remote-sg': _('Security ' 'Group')})) # When cidr is used ethertype is determined from IP version of cidr. # When source group, ethertype needs to be specified explicitly. ethertype = forms.ChoiceField(label=_('Ether Type'), required=False, choices=[('IPv4', _('IPv4')), ('IPv6', _('IPv6'))], widget=forms.Select(attrs={ 'class': 'switched', 'data-slug': 'ethertype', 'data-switch-on': 'remote', 'data-remote-sg': _('Ether Type')})) def __init__(self, *args, **kwargs): sg_list = kwargs.pop('sg_list', []) super(AddRule, self).__init__(*args, **kwargs) # Determine if there are security groups available for the # remote group option; add the choices and enable the option if so. if sg_list: security_groups_choices = sg_list else: security_groups_choices = [("", _("No security groups available"))] self.fields['security_group'].choices = security_groups_choices backend = api.network.security_group_backend(self.request) rules_dict = getattr(settings, 'SECURITY_GROUP_RULES', []) common_rules = [(k, rules_dict[k]['name']) for k in rules_dict if rules_dict[k].get('backend', backend) == backend] common_rules.sort() custom_rules = [('tcp', _('Custom TCP Rule')), ('udp', _('Custom UDP Rule')), ('icmp', _('Custom ICMP Rule'))] if backend == 'neutron': custom_rules.append(('custom', _('Other Protocol'))) self.fields['rule_menu'].choices = custom_rules + common_rules self.rules = rules_dict if backend == 'neutron': self.fields['direction'].choices = [('ingress', _('Ingress')), ('egress', _('Egress'))] else: # direction and ethertype are not supported in Nova secgroup. self.fields['direction'].widget = forms.HiddenInput() self.fields['ethertype'].widget = forms.HiddenInput() # ip_protocol field is to specify arbitrary protocol number # and it is available only for neutron security group. self.fields['ip_protocol'].widget = forms.HiddenInput() def clean(self): cleaned_data = super(AddRule, self).clean() def update_cleaned_data(key, value): cleaned_data[key] = value self.errors.pop(key, None) rule_menu = cleaned_data.get('rule_menu') port_or_range = cleaned_data.get("port_or_range") remote = cleaned_data.get("remote") icmp_type = cleaned_data.get("icmp_type", None) icmp_code = cleaned_data.get("icmp_code", None) from_port = cleaned_data.get("from_port", None) to_port = cleaned_data.get("to_port", None) port = cleaned_data.get("port", None) if rule_menu == 'icmp': update_cleaned_data('ip_protocol', rule_menu) if icmp_type is None: msg = _('The ICMP type is invalid.') raise ValidationError(msg) if icmp_code is None: msg = _('The ICMP code is invalid.') raise ValidationError(msg) if icmp_type not in range(-1, 256): msg = _('The ICMP type not in range (-1, 255)') raise ValidationError(msg) if icmp_code not in range(-1, 256): msg = _('The ICMP code not in range (-1, 255)') raise ValidationError(msg) update_cleaned_data('from_port', icmp_type) update_cleaned_data('to_port', icmp_code) update_cleaned_data('port', None) elif rule_menu == 'tcp' or rule_menu == 'udp': update_cleaned_data('ip_protocol', rule_menu) update_cleaned_data('icmp_code', None) update_cleaned_data('icmp_type', None) if port_or_range == "port": update_cleaned_data('from_port', port) update_cleaned_data('to_port', port) if port is None: msg = _('The specified port is invalid.') raise ValidationError(msg) else: update_cleaned_data('port', None) if from_port is None: msg = _('The "from" port number is invalid.') raise ValidationError(msg) if to_port is None: msg = _('The "to" port number is invalid.') raise ValidationError(msg) if to_port < from_port: msg = _('The "to" port number must be greater than ' 'or equal to the "from" port number.') raise ValidationError(msg) elif rule_menu == 'custom': pass else: cleaned_data['ip_protocol'] = self.rules[rule_menu]['ip_protocol'] cleaned_data['from_port'] = int(self.rules[rule_menu]['from_port']) cleaned_data['to_port'] = int(self.rules[rule_menu]['to_port']) if rule_menu not in ['all_tcp', 'all_udp', 'all_icmp']: direction = self.rules[rule_menu].get('direction') cleaned_data['direction'] = direction # NOTE(amotoki): There are two cases where cleaned_data['direction'] # is empty: (1) Nova Security Group is used. Since "direction" is # HiddenInput, direction field exists but its value is ''. # (2) Template except all_* is used. In this case, the default value # is None. To make sure 'direction' field has 'ingress' or 'egress', # fill this field here if it is not specified. if not cleaned_data['direction']: cleaned_data['direction'] = 'ingress' if remote == "cidr": update_cleaned_data('security_group', None) else: update_cleaned_data('cidr', None) # If cleaned_data does not contain cidr, cidr is already marked # as invalid, so skip the further validation for cidr. # In addition cleaned_data['cidr'] is None means source_group is used. if 'cidr' in cleaned_data and cleaned_data['cidr'] is not None: cidr = cleaned_data['cidr'] if not cidr: msg = _('CIDR must be specified.') self._errors['cidr'] = self.error_class([msg]) else: # If cidr is specified, ethertype is determined from IP address # version. It is used only when Neutron is enabled. ip_ver = netaddr.IPNetwork(cidr).version cleaned_data['ethertype'] = 'IPv6' if ip_ver == 6 else 'IPv4' return cleaned_data def handle(self, request, data): try: rule = api.network.security_group_rule_create( request, filters.get_int_or_uuid(data['id']), data['direction'], data['ethertype'], data['ip_protocol'], data['from_port'], data['to_port'], data['cidr'], data['security_group']) messages.success(request, _('Successfully added rule: %s') % unicode(rule)) return rule except Exception: redirect = reverse("horizon:project:access_and_security:" "security_groups:detail", args=[data['id']]) exceptions.handle(request, _('Unable to add rule to security group.'), redirect=redirect)
apache-2.0
aselle/tensorflow
tensorflow/python/training/monitored_session.py
11
48948
# pylint: disable=g-bad-file-header # Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """A wrapper of Session API which runs hooks.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import abc import sys import six from tensorflow.core.protobuf import config_pb2 from tensorflow.python.framework import errors from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import lookup_ops from tensorflow.python.ops import resources from tensorflow.python.ops import variables from tensorflow.python.platform import tf_logging as logging from tensorflow.python.summary import summary from tensorflow.python.training import basic_session_run_hooks from tensorflow.python.training import coordinator from tensorflow.python.training import queue_runner from tensorflow.python.training import saver as training_saver from tensorflow.python.training import session_manager as sm from tensorflow.python.training import session_run_hook from tensorflow.python.util import function_utils from tensorflow.python.util.tf_export import tf_export # The list of exceptions that we should recover from. Exceptions not in this # list may terminate the job. _PREEMPTION_ERRORS = (errors.AbortedError, errors.UnavailableError) # Value that indicates no value was provided. USE_DEFAULT = object() @tf_export('train.Scaffold') class Scaffold(object): """Structure to create or gather pieces commonly needed to train a model. When you build a model for training you usually need ops to initialize variables, a `Saver` to checkpoint them, an op to collect summaries for the visualizer, and so on. Various libraries built on top of the core TensorFlow library take care of creating some or all of these pieces and storing them in well known collections in the graph. The `Scaffold` class helps pick these pieces from the graph collections, creating and adding them to the collections if needed. If you call the scaffold constructor without any arguments, it will pick pieces from the collections, creating default ones if needed when `scaffold.finalize()` is called. You can pass arguments to the constructor to provide your own pieces. Pieces that you pass to the constructor are not added to the graph collections. The following pieces are directly accessible as attributes of the `Scaffold` object: * `saver`: A `tf.train.Saver` object taking care of saving the variables. Picked from and stored into the `SAVERS` collection in the graph by default. * `init_op`: An op to run to initialize the variables. Picked from and stored into the `INIT_OP` collection in the graph by default. * `ready_op`: An op to verify that the variables are initialized. Picked from and stored into the `READY_OP` collection in the graph by default. * `ready_for_local_init_op`: An op to verify that global state has been initialized and it is alright to run `local_init_op`. Picked from and stored into the `READY_FOR_LOCAL_INIT_OP` collection in the graph by default. This is needed when the initialization of local variables depends on the values of global variables. * `local_init_op`: An op to initialize the local variables. Picked from and stored into the `LOCAL_INIT_OP` collection in the graph by default. * `summary_op`: An op to run and merge the summaries in the graph. Picked from and stored into the `SUMMARY_OP` collection in the graph by default. * `global_step`: A tensor containing the global step counter. Picked from and stored into the `GLOBAL_STEP` collection in the graph by default. You can also pass the following additional pieces to the constructor: * `init_feed_dict`: A session feed dictionary that should be used when running the init op. * `init_fn`: A callable to run after the init op to perform additional initializations. The callable will be called as `init_fn(scaffold, session)`. """ def __init__(self, init_op=None, init_feed_dict=None, init_fn=None, ready_op=None, ready_for_local_init_op=None, local_init_op=None, summary_op=None, saver=None, copy_from_scaffold=None): """Create a scaffold. Args: init_op: Optional op for initializing variables. init_feed_dict: Optional session feed dictionary to use when running the init_op. init_fn: Optional function to use to initialize the model after running the init_op. Will be called as `init_fn(scaffold, session)`. ready_op: Optional op to verify that the variables are initialized. Must return an empty 1D string tensor when the variables are initialized, or a non-empty 1D string tensor listing the names of the non-initialized variables. ready_for_local_init_op: Optional op to verify that the global variables are initialized and `local_init_op` can be run. Must return an empty 1D string tensor when the global variables are initialized, or a non-empty 1D string tensor listing the names of the non-initialized global variables. local_init_op: Optional op to initialize local variables. summary_op: Optional op to gather all summaries. Must return a scalar string tensor containing a serialized `Summary` proto. saver: Optional `tf.train.Saver` object to use to save and restore variables. copy_from_scaffold: Optional scaffold object to copy fields from. Its fields will be overwritten by the provided fields in this function. """ if copy_from_scaffold is not None: if not isinstance(copy_from_scaffold, Scaffold): raise TypeError('copy_from_scaffold is not a Scaffold instance.') # We need _coalesce since Tensor is not converted to bool automatically, # so the common idiom of (a or b) does not work. coalesce = lambda a, b: a if a is not None else b init_op = coalesce(init_op, copy_from_scaffold.init_op) init_feed_dict = coalesce(init_feed_dict, copy_from_scaffold.init_feed_dict) # Use the original init_fn provided by the user to init the new Scaffold. init_fn = coalesce(init_fn, copy_from_scaffold._user_init_fn) # pylint: disable=protected-access ready_op = coalesce(ready_op, copy_from_scaffold.ready_op) ready_for_local_init_op = coalesce( ready_for_local_init_op, copy_from_scaffold.ready_for_local_init_op) local_init_op = coalesce(local_init_op, copy_from_scaffold.local_init_op) summary_op = coalesce(summary_op, copy_from_scaffold.summary_op) saver = coalesce(saver, copy_from_scaffold.saver) # NOTE(touts): modifying the init function to be passed the scaffold is a # hack to make it easy to find the saver. Is there a better way? self._user_init_fn = init_fn if init_fn: self._init_fn = lambda sess: init_fn(self, sess) else: self._init_fn = None self._init_op = init_op self._init_feed_dict = init_feed_dict self._ready_op = ready_op self._ready_for_local_init_op = ready_for_local_init_op self._local_init_op = local_init_op self._summary_op = summary_op self._saver = saver def finalize(self): """Creates operations if needed and finalizes the graph.""" if self._init_op is None: def default_init_op(): return control_flow_ops.group( variables.global_variables_initializer(), resources.initialize_resources(resources.shared_resources())) self._init_op = Scaffold.get_or_default( 'init_op', ops.GraphKeys.INIT_OP, default_init_op) if self._ready_op is None: def default_ready_op(): return array_ops.concat([ variables.report_uninitialized_variables(), resources.report_uninitialized_resources() ], 0) self._ready_op = Scaffold.get_or_default( 'ready_op', ops.GraphKeys.READY_OP, default_ready_op) if self._ready_for_local_init_op is None: def default_ready_for_local_init_op(): return variables.report_uninitialized_variables( variables.global_variables()) self._ready_for_local_init_op = Scaffold.get_or_default( 'ready_for_local_init_op', ops.GraphKeys.READY_FOR_LOCAL_INIT_OP, default_ready_for_local_init_op) if self._local_init_op is None: self._local_init_op = Scaffold.get_or_default( 'local_init_op', ops.GraphKeys.LOCAL_INIT_OP, Scaffold.default_local_init_op) if self._summary_op is None: self._summary_op = Scaffold.get_or_default('summary_op', ops.GraphKeys.SUMMARY_OP, summary.merge_all) # pylint: disable=g-long-lambda if self._saver is None: self._saver = training_saver._get_saver_or_default() # pylint: disable=protected-access # pylint: enable=g-long-lambda self._saver.build() ops.get_default_graph().finalize() logging.info('Graph was finalized.') return self @property def init_fn(self): return self._init_fn @property def init_op(self): return self._init_op @property def ready_op(self): return self._ready_op @property def ready_for_local_init_op(self): return self._ready_for_local_init_op @property def local_init_op(self): return self._local_init_op @property def summary_op(self): return self._summary_op @property def saver(self): return self._saver @property def init_feed_dict(self): return self._init_feed_dict @staticmethod def get_or_default(arg_name, collection_key, default_constructor): """Get from cache or create a default operation.""" elements = ops.get_collection(collection_key) if elements: if len(elements) > 1: raise RuntimeError('More than one item in the collection "%s". ' 'Please indicate which one to use by passing it to ' 'the tf.Scaffold constructor as: ' 'tf.Scaffold(%s=item to use)', collection_key, arg_name) return elements[0] op = default_constructor() if op is not None: ops.add_to_collection(collection_key, op) return op @staticmethod def default_local_init_op(): """Returns an op that groups the default local init ops. This op is used during session initialization when a Scaffold is initialized without specifying the local_init_op arg. It includes `tf.local_variables_initializer`, `tf.tables_initializer`, and also initializes local session resources. Returns: The default Scaffold local init op. """ return control_flow_ops.group( variables.local_variables_initializer(), lookup_ops.tables_initializer(), resources.initialize_resources(resources.local_resources())) @tf_export('train.MonitoredTrainingSession') def MonitoredTrainingSession(master='', # pylint: disable=invalid-name is_chief=True, checkpoint_dir=None, scaffold=None, hooks=None, chief_only_hooks=None, save_checkpoint_secs=USE_DEFAULT, save_summaries_steps=USE_DEFAULT, save_summaries_secs=USE_DEFAULT, config=None, stop_grace_period_secs=120, log_step_count_steps=100, max_wait_secs=7200, save_checkpoint_steps=USE_DEFAULT, summary_dir=None): """Creates a `MonitoredSession` for training. For a chief, this utility sets proper session initializer/restorer. It also creates hooks related to checkpoint and summary saving. For workers, this utility sets proper session creator which waits for the chief to initialize/restore. Please check `tf.train.MonitoredSession` for more information. Args: master: `String` the TensorFlow master to use. is_chief: If `True`, it will take care of initialization and recovery the underlying TensorFlow session. If `False`, it will wait on a chief to initialize or recover the TensorFlow session. checkpoint_dir: A string. Optional path to a directory where to restore variables. scaffold: A `Scaffold` used for gathering or building supportive ops. If not specified, a default one is created. It's used to finalize the graph. hooks: Optional list of `SessionRunHook` objects. chief_only_hooks: list of `SessionRunHook` objects. Activate these hooks if `is_chief==True`, ignore otherwise. save_checkpoint_secs: The frequency, in seconds, that a checkpoint is saved using a default checkpoint saver. If both `save_checkpoint_steps` and `save_checkpoint_secs` are set to `None`, then the default checkpoint saver isn't used. If both are provided, then only `save_checkpoint_secs` is used. Default 600. save_summaries_steps: The frequency, in number of global steps, that the summaries are written to disk using a default summary saver. If both `save_summaries_steps` and `save_summaries_secs` are set to `None`, then the default summary saver isn't used. Default 100. save_summaries_secs: The frequency, in secs, that the summaries are written to disk using a default summary saver. If both `save_summaries_steps` and `save_summaries_secs` are set to `None`, then the default summary saver isn't used. Default not enabled. config: an instance of `tf.ConfigProto` proto used to configure the session. It's the `config` argument of constructor of `tf.Session`. stop_grace_period_secs: Number of seconds given to threads to stop after `close()` has been called. log_step_count_steps: The frequency, in number of global steps, that the global step/sec is logged. max_wait_secs: Maximum time workers should wait for the session to become available. This should be kept relatively short to help detect incorrect code, but sometimes may need to be increased if the chief takes a while to start up. save_checkpoint_steps: The frequency, in number of global steps, that a checkpoint is saved using a default checkpoint saver. If both `save_checkpoint_steps` and `save_checkpoint_secs` are set to `None`, then the default checkpoint saver isn't used. If both are provided, then only `save_checkpoint_secs` is used. Default not enabled. summary_dir: A string. Optional path to a directory where to save summaries. If None, checkpoint_dir is used instead. Returns: A `MonitoredSession` object. """ if save_summaries_steps == USE_DEFAULT and save_summaries_secs == USE_DEFAULT: save_summaries_steps = 100 save_summaries_secs = None elif save_summaries_secs == USE_DEFAULT: save_summaries_secs = None elif save_summaries_steps == USE_DEFAULT: save_summaries_steps = None if (save_checkpoint_steps == USE_DEFAULT and save_checkpoint_secs == USE_DEFAULT): save_checkpoint_steps = None save_checkpoint_secs = 600 elif save_checkpoint_secs == USE_DEFAULT: save_checkpoint_secs = None elif save_checkpoint_steps == USE_DEFAULT: save_checkpoint_steps = None scaffold = scaffold or Scaffold() if not is_chief: session_creator = WorkerSessionCreator( scaffold=scaffold, master=master, config=config, max_wait_secs=max_wait_secs) return MonitoredSession(session_creator=session_creator, hooks=hooks or [], stop_grace_period_secs=stop_grace_period_secs) all_hooks = [] if chief_only_hooks: all_hooks.extend(chief_only_hooks) session_creator = ChiefSessionCreator( scaffold=scaffold, checkpoint_dir=checkpoint_dir, master=master, config=config) summary_dir = summary_dir or checkpoint_dir if summary_dir: if log_step_count_steps and log_step_count_steps > 0: all_hooks.append( basic_session_run_hooks.StepCounterHook( output_dir=summary_dir, every_n_steps=log_step_count_steps)) if (save_summaries_steps and save_summaries_steps > 0) or ( save_summaries_secs and save_summaries_secs > 0): all_hooks.append(basic_session_run_hooks.SummarySaverHook( scaffold=scaffold, save_steps=save_summaries_steps, save_secs=save_summaries_secs, output_dir=summary_dir)) if checkpoint_dir: if (save_checkpoint_secs and save_checkpoint_secs > 0) or ( save_checkpoint_steps and save_checkpoint_steps > 0): all_hooks.append(basic_session_run_hooks.CheckpointSaverHook( checkpoint_dir, save_steps=save_checkpoint_steps, save_secs=save_checkpoint_secs, scaffold=scaffold)) if hooks: all_hooks.extend(hooks) return MonitoredSession(session_creator=session_creator, hooks=all_hooks, stop_grace_period_secs=stop_grace_period_secs) @tf_export('train.SessionCreator') class SessionCreator(object): """A factory for tf.Session.""" @abc.abstractmethod def create_session(self): raise NotImplementedError( 'create_session is not implemented for {}.'.format(self)) @tf_export('train.ChiefSessionCreator') class ChiefSessionCreator(SessionCreator): """Creates a tf.Session for a chief.""" def __init__(self, scaffold=None, master='', config=None, checkpoint_dir=None, checkpoint_filename_with_path=None): """Initializes a chief session creator. Args: scaffold: A `Scaffold` used for gathering or building supportive ops. If not specified a default one is created. It's used to finalize the graph. master: `String` representation of the TensorFlow master to use. config: `ConfigProto` proto used to configure the session. checkpoint_dir: A string. Optional path to a directory where to restore variables. checkpoint_filename_with_path: Full file name path to the checkpoint file. """ self._checkpoint_dir = checkpoint_dir self._checkpoint_filename_with_path = checkpoint_filename_with_path self._scaffold = scaffold or Scaffold() self._session_manager = None self._master = master self._config = config def _get_session_manager(self): if self._session_manager: return self._session_manager self._session_manager = sm.SessionManager( local_init_op=self._scaffold.local_init_op, ready_op=self._scaffold.ready_op, ready_for_local_init_op=self._scaffold.ready_for_local_init_op, graph=ops.get_default_graph()) return self._session_manager def create_session(self): self._scaffold.finalize() return self._get_session_manager().prepare_session( self._master, saver=self._scaffold.saver, checkpoint_dir=self._checkpoint_dir, checkpoint_filename_with_path=self._checkpoint_filename_with_path, config=self._config, init_op=self._scaffold.init_op, init_feed_dict=self._scaffold.init_feed_dict, init_fn=self._scaffold.init_fn) @tf_export('train.WorkerSessionCreator') class WorkerSessionCreator(SessionCreator): """Creates a tf.Session for a worker.""" def __init__(self, scaffold=None, master='', config=None, max_wait_secs=30 * 60): """Initializes a worker session creator. Args: scaffold: A `Scaffold` used for gathering or building supportive ops. If not specified a default one is created. It's used to finalize the graph. master: `String` representation of the TensorFlow master to use. config: `ConfigProto` proto used to configure the session. max_wait_secs: Maximum time to wait for the session to become available. """ self._scaffold = scaffold or Scaffold() self._session_manager = None self._master = master self._config = config self._max_wait_secs = max_wait_secs def _get_session_manager(self): if self._session_manager: return self._session_manager self._session_manager = sm.SessionManager( local_init_op=self._scaffold.local_init_op, ready_op=self._scaffold.ready_op, ready_for_local_init_op=self._scaffold.ready_for_local_init_op, graph=ops.get_default_graph()) return self._session_manager def create_session(self): self._scaffold.finalize() return self._get_session_manager().wait_for_session( self._master, config=self._config, max_wait_secs=self._max_wait_secs ) class _MonitoredSession(object): """See `MonitoredSession` or `SingularMonitoredSession`.""" def __init__(self, session_creator, hooks, should_recover, stop_grace_period_secs=120): """Sets up a Monitored or Hooked Session. Args: session_creator: A factory object to create session. Typically a `ChiefSessionCreator` or a `WorkerSessionCreator`. hooks: An iterable of `SessionRunHook' objects. should_recover: A bool. Indicates whether to recover from `AbortedError` and `UnavailableError` or not. stop_grace_period_secs: Number of seconds given to threads to stop after `close()` has been called. """ self._graph_was_finalized = ops.get_default_graph().finalized self._hooks = hooks or [] for h in self._hooks: h.begin() # Create the session. self._coordinated_creator = self._CoordinatedSessionCreator( session_creator=session_creator or ChiefSessionCreator(), hooks=self._hooks, stop_grace_period_secs=stop_grace_period_secs) if should_recover: self._sess = _RecoverableSession(self._coordinated_creator) else: self._sess = self._coordinated_creator.create_session() @property def graph(self): """The graph that was launched in this session.""" if self._tf_sess() is None: return None return self._tf_sess().graph def run(self, fetches, feed_dict=None, options=None, run_metadata=None): """Run ops in the monitored session. This method is completely compatible with the `tf.Session.run()` method. Args: fetches: Same as `tf.Session.run()`. feed_dict: Same as `tf.Session.run()`. options: Same as `tf.Session.run()`. run_metadata: Same as `tf.Session.run()`. Returns: Same as `tf.Session.run()`. """ return self._sess.run(fetches, feed_dict=feed_dict, options=options, run_metadata=run_metadata) def run_step_fn(self, step_fn): """Run ops using a step function. Args: step_fn: A function or a method with a single argument of type `StepContext`. The function may use methods of the argument to perform computations with access to a raw session. The returned value of the `step_fn` will be returned from `run_step_fn`, unless a stop is requested. In that case, the next `should_stop` call will return True. Example usage: ```python with tf.Graph().as_default(): c = tf.placeholder(dtypes.float32) v = tf.add(c, 4.0) w = tf.add(c, 0.5) def step_fn(step_context): a = step_context.session.run(fetches=v, feed_dict={c: 0.5}) if a <= 4.5: step_context.request_stop() return step_context.run_with_hooks(fetches=w, feed_dict={c: 0.1}) with tf.MonitoredSession() as session: while not session.should_stop(): a = session.run_step_fn(step_fn) ``` Hooks interact with the `run_with_hooks()` call inside the `step_fn` as they do with a `MonitoredSession.run` call. Returns: Returns the returned value of `step_fn`. Raises: StopIteration: if `step_fn` has called `request_stop()`. It may be caught by `with tf.MonitoredSession()` to close the session. ValueError: if `step_fn` doesn't have a single argument called `step_context`. It may also optionally have `self` for cases when it belongs to an object. """ step_fn_arguments = function_utils.fn_args(step_fn) if step_fn_arguments != ('step_context',) and step_fn_arguments != ( 'self', 'step_context', ): raise ValueError( '`step_fn` may either have one `step_context` argument, or' ' `self` and `step_context` arguments if it\'s an instance' ' method. Got {} instead.'.format(step_fn_arguments)) # `self._sess` is either `_RecoverableSession` or a `_CoordinatedSession`. # Setting `run_with_hooks` to `None` will cause `run_with_hooks` to be # `_CoordinatedSession.run` downstream in either case. This allows # `_PREEMPTION_ERRORS` to propage from within `step_fn` to # `_RecoverableSession.run_step_fn`. return self._sess.run_step_fn(step_fn, self._tf_sess(), run_with_hooks=None) class StepContext(object): """Control flow instrument for the `step_fn` from `run_step_fn()`. Users of `step_fn` may perform `run()` calls without running hooks by accessing the `session`. A `run()` call with hooks may be performed using `run_with_hooks()`. Computation flow can be interrupted using `request_stop()`. """ def __init__(self, session, run_with_hooks_fn): """Initializes the `step_context` argument for a `step_fn` invocation. Args: session: An instance of `tf.Session`. run_with_hooks_fn: A function for running fetches and hooks. """ self._session = session self._run_with_hooks_fn = run_with_hooks_fn @property def session(self): return self._session def run_with_hooks(self, *args, **kwargs): """Same as `MonitoredSession.run`. Accepts the same arguments.""" return self._run_with_hooks_fn(*args, **kwargs) def request_stop(self): """Exit the training loop by causing `should_stop()` to return `True`. Causes `step_fn` to exit by raising an exception. Raises: StopIteration """ raise StopIteration('step_fn has requested the iterations to stop.') def should_stop(self): return self._sess is None or self._sess.should_stop() def close(self): self._close_internal() def __enter__(self): return self def __exit__(self, exception_type, exception_value, traceback): if exception_type in [errors.OutOfRangeError, StopIteration]: exception_type = None self._close_internal(exception_type) # __exit__ should return True to suppress an exception. return exception_type is None class _CoordinatedSessionCreator(SessionCreator): """Factory for the _RecoverableSession.""" def __init__(self, session_creator, hooks, stop_grace_period_secs): self._session_creator = session_creator self._hooks = hooks self.coord = None self.tf_sess = None self._stop_grace_period_secs = stop_grace_period_secs def create_session(self): """Creates a coordinated session.""" # Keep the tf_sess for unit testing. self.tf_sess = self._session_creator.create_session() # We don't want coordinator to suppress any exception. self.coord = coordinator.Coordinator(clean_stop_exception_types=[]) queue_runner.start_queue_runners(sess=self.tf_sess, coord=self.coord) # Inform the hooks that a new session has been created. for hook in self._hooks: hook.after_create_session(self.tf_sess, self.coord) return _CoordinatedSession( _HookedSession(self.tf_sess, self._hooks), self.coord, self._stop_grace_period_secs) def _close_internal(self, exception_type=None): try: if not exception_type: for h in self._hooks: h.end(self._coordinated_creator.tf_sess) finally: try: if self._sess is None: raise RuntimeError('Session is already closed.') self._sess.close() finally: self._sess = None self._coordinated_creator.tf_sess = None self._coordinated_creator.coord = None if not self._graph_was_finalized: ops.get_default_graph()._unsafe_unfinalize() # pylint: disable=protected-access def _is_closed(self): """Return True if the monitored session is closed. For tests only. Returns: A boolean. """ return self._coordinated_creator.tf_sess is None def _tf_sess(self): return self._coordinated_creator.tf_sess @tf_export('train.MonitoredSession') class MonitoredSession(_MonitoredSession): """Session-like object that handles initialization, recovery and hooks. Example usage: ```python saver_hook = CheckpointSaverHook(...) summary_hook = SummarySaverHook(...) with MonitoredSession(session_creator=ChiefSessionCreator(...), hooks=[saver_hook, summary_hook]) as sess: while not sess.should_stop(): sess.run(train_op) ``` Initialization: At creation time the monitored session does following things in given order: * calls `hook.begin()` for each given hook * finalizes the graph via `scaffold.finalize()` * create session * initializes the model via initialization ops provided by `Scaffold` * restores variables if a checkpoint exists * launches queue runners * calls `hook.after_create_session()` Run: When `run()` is called, the monitored session does following things: * calls `hook.before_run()` * calls TensorFlow `session.run()` with merged fetches and feed_dict * calls `hook.after_run()` * returns result of `session.run()` asked by user * if `AbortedError` or `UnavailableError` occurs, it recovers or reinitializes the session before executing the run() call again Exit: At the `close()`, the monitored session does following things in order: * calls `hook.end()` * closes the queue runners and the session * suppresses `OutOfRange` error which indicates that all inputs have been processed if the monitored_session is used as a context How to set `tf.Session` arguments: * In most cases you can set session arguments as follows: ```python MonitoredSession( session_creator=ChiefSessionCreator(master=..., config=...)) ``` * In distributed setting for a non-chief worker, you can use following: ```python MonitoredSession( session_creator=WorkerSessionCreator(master=..., config=...)) ``` See `MonitoredTrainingSession` for an example usage based on chief or worker. Note: This is not a `tf.Session`. For example, it cannot do following: * it cannot be set as default session. * it cannot be sent to saver.save. * it cannot be sent to tf.train.start_queue_runners. Args: session_creator: A factory object to create session. Typically a `ChiefSessionCreator` which is the default one. hooks: An iterable of `SessionRunHook' objects. Returns: A MonitoredSession object. """ def __init__(self, session_creator=None, hooks=None, stop_grace_period_secs=120): super(MonitoredSession, self).__init__( session_creator, hooks, should_recover=True, stop_grace_period_secs=stop_grace_period_secs) @tf_export('train.SingularMonitoredSession') class SingularMonitoredSession(_MonitoredSession): """Session-like object that handles initialization, restoring, and hooks. Please note that this utility is not recommended for distributed settings. For distributed settings, please use `tf.train.MonitoredSession`. The differences between `MonitoredSession` and `SingularMonitoredSession` are: * `MonitoredSession` handles `AbortedError` and `UnavailableError` for distributed settings, but `SingularMonitoredSession` does not. * `MonitoredSession` can be created in `chief` or `worker` modes. `SingularMonitoredSession` is always created as `chief`. * You can access the raw `tf.Session` object used by `SingularMonitoredSession`, whereas in MonitoredSession the raw session is private. This can be used: - To `run` without hooks. - To save and restore. * All other functionality is identical. Example usage: ```python saver_hook = CheckpointSaverHook(...) summary_hook = SummarySaverHook(...) with SingularMonitoredSession(hooks=[saver_hook, summary_hook]) as sess: while not sess.should_stop(): sess.run(train_op) ``` Initialization: At creation time the hooked session does following things in given order: * calls `hook.begin()` for each given hook * finalizes the graph via `scaffold.finalize()` * create session * initializes the model via initialization ops provided by `Scaffold` * restores variables if a checkpoint exists * launches queue runners Run: When `run()` is called, the hooked session does following things: * calls `hook.before_run()` * calls TensorFlow `session.run()` with merged fetches and feed_dict * calls `hook.after_run()` * returns result of `session.run()` asked by user Exit: At the `close()`, the hooked session does following things in order: * calls `hook.end()` * closes the queue runners and the session * suppresses `OutOfRange` error which indicates that all inputs have been processed if the `SingularMonitoredSession` is used as a context. """ def __init__(self, hooks=None, scaffold=None, master='', config=None, checkpoint_dir=None, stop_grace_period_secs=120, checkpoint_filename_with_path=None): """Creates a SingularMonitoredSession. Args: hooks: An iterable of `SessionRunHook' objects. scaffold: A `Scaffold` used for gathering or building supportive ops. If not specified a default one is created. It's used to finalize the graph. master: `String` representation of the TensorFlow master to use. config: `ConfigProto` proto used to configure the session. checkpoint_dir: A string. Optional path to a directory where to restore variables. stop_grace_period_secs: Number of seconds given to threads to stop after `close()` has been called. checkpoint_filename_with_path: A string. Optional path to a checkpoint file from which to restore variables. """ session_creator = ChiefSessionCreator( scaffold=scaffold, master=master, config=config, checkpoint_dir=checkpoint_dir, checkpoint_filename_with_path=checkpoint_filename_with_path) super(SingularMonitoredSession, self).__init__( session_creator, hooks, should_recover=False, stop_grace_period_secs=stop_grace_period_secs) def raw_session(self): """Returns underlying `TensorFlow.Session` object.""" return self._tf_sess() class _WrappedSession(object): """Wrapper around a `tf.Session`. This wrapper is used as a base class for various session wrappers that provide additional functionality such as monitoring, coordination, and recovery. In addition to the methods exported by `SessionInterface` the wrapper provides a method to check for stop and never raises exceptions from calls to `close()`. """ def __init__(self, sess): """Creates a `_WrappedSession`. Args: sess: A `tf.Session` or `_WrappedSession` object. The wrapped session. """ self._sess = sess self._wrapped_is_stoppable = isinstance(self._sess, _WrappedSession) @property def graph(self): return self._sess.graph @property def sess_str(self): return self._sess.sess_str def should_stop(self): """Return true if this session should not be used anymore. Always return True if the session was closed. Returns: True if the session should stop, False otherwise. """ if self._check_stop(): return True if self._sess: return self._wrapped_is_stoppable and self._sess.should_stop() return True def _check_stop(self): """Hook for subclasses to provide their own stop condition. Returns: True if the session should stop, False otherwise. """ return False def close(self): if self._sess: try: self._sess.close() except _PREEMPTION_ERRORS: pass finally: self._sess = None def run(self, *args, **kwargs): return self._sess.run(*args, **kwargs) def run_step_fn(self, step_fn, raw_session, run_with_hooks): # `_RecoverableSession` sets `run_with_hooks` to `_CoordinatedSession.run`. # It is `None` when called from `_CoordinatedSession`. In that case # `self.run` is `_CoordinatedSession.run`. run_with_hooks = run_with_hooks or self.run return step_fn(_MonitoredSession.StepContext(raw_session, run_with_hooks)) class _RecoverableSession(_WrappedSession): """A wrapped session that recreates a session upon certain kinds of errors. The constructor is passed a SessionCreator object, not a session. Calls to `run()` are delegated to the wrapped session. If a call raises the exception `tf.errors.AbortedError` or `tf.errors.UnavailableError`, the wrapped session is closed, and a new one is created by calling the factory again. """ def __init__(self, sess_creator): """Create a new `_RecoverableSession`. The value returned by calling `sess_creator.create_session()` will be the session wrapped by this recoverable session. Args: sess_creator: A 'SessionCreator' to be wrapped by recoverable. """ self._sess_creator = sess_creator _WrappedSession.__init__(self, self._create_session()) def _create_session(self): while True: try: return self._sess_creator.create_session() except _PREEMPTION_ERRORS as e: logging.info('An error was raised while a session was being created. ' 'This may be due to a preemption of a connected worker ' 'or parameter server. A new session will be created. ' 'Error: %s', e) def _check_stop(self): try: if self._sess: return self._sess._check_stop() # pylint: disable=protected-access else: return True except _PREEMPTION_ERRORS as e: logging.info('An error was raised while considering whether the ' 'session is complete. This may be due to a preemption in ' 'a connected worker or parameter server. The current ' 'session will be closed and a new session will be ' 'created. Error: %s', e) self.close() self._sess = self._create_session() # Since we have just recreated the session, the overall computation should # not stop: return False except Exception: # pylint: disable=broad-except # `should_stop` should return True instead of raising an exception. return True def run(self, fetches, feed_dict=None, options=None, run_metadata=None): while True: try: if not self._sess: self._sess = self._create_session() return self._sess.run(fetches, feed_dict=feed_dict, options=options, run_metadata=run_metadata) except _PREEMPTION_ERRORS as e: logging.info('An error was raised. This may be due to a preemption in ' 'a connected worker or parameter server. The current ' 'session will be closed and a new session will be ' 'created. Error: %s', e) self.close() self._sess = None def run_step_fn(self, step_fn, raw_session, run_with_hooks): while True: try: if not self._sess: self._sess = self._create_session() run_with_hooks = self._sess.run return self._sess.run_step_fn(step_fn, raw_session, run_with_hooks) except _PREEMPTION_ERRORS as e: logging.info('An error was raised. This may be due to a preemption in ' 'a connected worker or parameter server. The current ' 'session will be closed and a new session will be ' 'created. Error: %s', e) self.close() self._sess = None class _CoordinatedSession(_WrappedSession): """A wrapped session that works with a `tf.Coordinator`. Calls to `run()` are delegated to the wrapped session. If a call raises an exception, the exception is reported to the coordinator. In addition, after each call to `run()` this session ask the coordinator if the session should stop. In that case it will will join all the threads registered with the coordinator before returning. If the coordinator was requested to stop with an exception, that exception will be re-raised from the call to `run()`. """ def __init__(self, sess, coord, stop_grace_period_secs=120): """Create a new `_CoordinatedSession`. Args: sess: A `tf.Session` object. The wrapped session. coord: A `tf.train.Coordinator` object. stop_grace_period_secs: Number of seconds given to threads to stop after `close()` has been called. """ _WrappedSession.__init__(self, sess) self._coord = coord self._stop_grace_period_secs = stop_grace_period_secs def _check_stop(self): # If the coordinator was asked to stop due to an exception, then it needs # to be propagated to this stack. self._coord.raise_requested_exception() # At this point, no exceptions are recorded in the coordinator. return self._coord.should_stop() def close(self): self._coord.request_stop() try: self._coord.join( stop_grace_period_secs=self._stop_grace_period_secs, ignore_live_threads=True) finally: try: _WrappedSession.close(self) except Exception: # pylint: disable=broad-except # We intentionally suppress exceptions from the close() here since # useful exceptions are already reported by join(). pass def run(self, *args, **kwargs): try: return self._sess.run(*args, **kwargs) except _PREEMPTION_ERRORS: raise except Exception: # pylint: disable=broad-except # A non-preemption error could have been caused by a preemption error # in the coordinator. If this is the case, raise that exception instead, # since it's the root cause. Otherwise, stick to the `original_exc_info`. original_exc_info = sys.exc_info() try: self._coord.raise_requested_exception() except _PREEMPTION_ERRORS: raise except Exception: # pylint: disable=broad-except raise six.reraise(*original_exc_info) else: raise six.reraise(*original_exc_info) class _HookedSession(_WrappedSession): """A _WrappedSession that calls hooks during calls to run(). The list of hooks to call is passed in the constructor. Before each call to `run()` the session calls the `before_run()` method of the hooks, which can return additional ops or tensors to run. These are added to the arguments of the call to `run()`. When the `run()` call finishes, the session calls the `after_run()` methods of the hooks, passing the values returned by the `run()` call corresponding to the ops and tensors that each hook requested. If any call to the hooks, requests stop via run_context the session will be marked as needing to stop and its `should_stop()` method will now return `True`. """ def __init__(self, sess, hooks): """Initializes a _HookedSession object. Args: sess: A `tf.Session` or a `_WrappedSession` object. hooks: An iterable of `SessionRunHook' objects. """ _WrappedSession.__init__(self, sess) self._hooks = hooks self._should_stop = False def _check_stop(self): """See base class.""" return self._should_stop def run(self, fetches, feed_dict=None, options=None, run_metadata=None): """See base class.""" if self.should_stop(): raise RuntimeError('Run called even after should_stop requested.') actual_fetches = {'caller': fetches} run_context = session_run_hook.SessionRunContext( original_args=session_run_hook.SessionRunArgs(fetches, feed_dict), session=self._sess) options = options or config_pb2.RunOptions() feed_dict = self._call_hook_before_run(run_context, actual_fetches, feed_dict, options) # Do session run. run_metadata = run_metadata or config_pb2.RunMetadata() outputs = _WrappedSession.run(self, fetches=actual_fetches, feed_dict=feed_dict, options=options, run_metadata=run_metadata) for hook in self._hooks: hook.after_run( run_context, session_run_hook.SessionRunValues( results=outputs[hook] if hook in outputs else None, options=options, run_metadata=run_metadata)) self._should_stop = self._should_stop or run_context.stop_requested return outputs['caller'] def _call_hook_before_run(self, run_context, fetch_dict, user_feed_dict, options): """Calls hooks.before_run and handles requests from hooks.""" hook_feeds = {} for hook in self._hooks: request = hook.before_run(run_context) if request is not None: if request.fetches is not None: fetch_dict[hook] = request.fetches if request.feed_dict: self._raise_if_feeds_intersects( hook_feeds, request.feed_dict, 'Same tensor is fed by two hooks.') hook_feeds.update(request.feed_dict) if request.options: self._merge_run_options(options, request.options) if not hook_feeds: return user_feed_dict if not user_feed_dict: return hook_feeds self._raise_if_feeds_intersects( user_feed_dict, hook_feeds, 'Same tensor is fed by a SessionRunHook and user.') hook_feeds.update(user_feed_dict) return hook_feeds def _raise_if_feeds_intersects(self, feeds1, feeds2, message): intersection = set(feeds1.keys()) & set(feeds2.keys()) if intersection: raise RuntimeError(message + ' Conflict(s): ' + str(list(intersection))) def _merge_run_options(self, options, incoming_options): """Merge two instances of RunOptions into the first one. During the merger, the numerical fields including trace_level, timeout_in_ms, inter_op_thread_pool are set to the larger one of the two. The boolean value is set to the logical OR of the two. debug_tensor_watch_opts of the original options is extended with that from the incoming one. Args: options: The options to merge into. incoming_options: The options to be merged into the first argument. """ options.trace_level = max(options.trace_level, incoming_options.trace_level) options.timeout_in_ms = max(options.timeout_in_ms, incoming_options.timeout_in_ms) options.inter_op_thread_pool = max(options.inter_op_thread_pool, incoming_options.inter_op_thread_pool) options.output_partition_graphs = max( options.output_partition_graphs, incoming_options.output_partition_graphs) options.debug_options.debug_tensor_watch_opts.extend( incoming_options.debug_options.debug_tensor_watch_opts)
apache-2.0
supergis/QGIS
python/ext-libs/pygments/lexers/_mapping.py
68
36995
# -*- coding: utf-8 -*- """ pygments.lexers._mapping ~~~~~~~~~~~~~~~~~~~~~~~~ Lexer mapping defintions. This file is generated by itself. Everytime you change something on a builtin lexer defintion, run this script from the lexers folder to update it. Do not alter the LEXERS dictionary by hand. :copyright: Copyright 2006-2013 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ LEXERS = { 'ABAPLexer': ('pygments.lexers.other', 'ABAP', ('abap',), ('*.abap',), ('text/x-abap',)), 'ActionScript3Lexer': ('pygments.lexers.web', 'ActionScript 3', ('as3', 'actionscript3'), ('*.as',), ('application/x-actionscript', 'text/x-actionscript', 'text/actionscript')), 'ActionScriptLexer': ('pygments.lexers.web', 'ActionScript', ('as', 'actionscript'), ('*.as',), ('application/x-actionscript3', 'text/x-actionscript3', 'text/actionscript3')), 'AdaLexer': ('pygments.lexers.compiled', 'Ada', ('ada', 'ada95ada2005'), ('*.adb', '*.ads', '*.ada'), ('text/x-ada',)), 'AntlrActionScriptLexer': ('pygments.lexers.parsers', 'ANTLR With ActionScript Target', ('antlr-as', 'antlr-actionscript'), ('*.G', '*.g'), ()), 'AntlrCSharpLexer': ('pygments.lexers.parsers', 'ANTLR With C# Target', ('antlr-csharp', 'antlr-c#'), ('*.G', '*.g'), ()), 'AntlrCppLexer': ('pygments.lexers.parsers', 'ANTLR With CPP Target', ('antlr-cpp',), ('*.G', '*.g'), ()), 'AntlrJavaLexer': ('pygments.lexers.parsers', 'ANTLR With Java Target', ('antlr-java',), ('*.G', '*.g'), ()), 'AntlrLexer': ('pygments.lexers.parsers', 'ANTLR', ('antlr',), (), ()), 'AntlrObjectiveCLexer': ('pygments.lexers.parsers', 'ANTLR With ObjectiveC Target', ('antlr-objc',), ('*.G', '*.g'), ()), 'AntlrPerlLexer': ('pygments.lexers.parsers', 'ANTLR With Perl Target', ('antlr-perl',), ('*.G', '*.g'), ()), 'AntlrPythonLexer': ('pygments.lexers.parsers', 'ANTLR With Python Target', ('antlr-python',), ('*.G', '*.g'), ()), 'AntlrRubyLexer': ('pygments.lexers.parsers', 'ANTLR With Ruby Target', ('antlr-ruby', 'antlr-rb'), ('*.G', '*.g'), ()), 'ApacheConfLexer': ('pygments.lexers.text', 'ApacheConf', ('apacheconf', 'aconf', 'apache'), ('.htaccess', 'apache.conf', 'apache2.conf'), ('text/x-apacheconf',)), 'AppleScriptLexer': ('pygments.lexers.other', 'AppleScript', ('applescript',), ('*.applescript',), ()), 'AspectJLexer': ('pygments.lexers.jvm', 'AspectJ', ('aspectj',), ('*.aj',), ('text/x-aspectj',)), 'AsymptoteLexer': ('pygments.lexers.other', 'Asymptote', ('asy', 'asymptote'), ('*.asy',), ('text/x-asymptote',)), 'AutoItLexer': ('pygments.lexers.other', 'AutoIt', ('autoit', 'Autoit'), ('*.au3',), ('text/x-autoit',)), 'AutohotkeyLexer': ('pygments.lexers.other', 'autohotkey', ('ahk',), ('*.ahk', '*.ahkl'), ('text/x-autohotkey',)), 'AwkLexer': ('pygments.lexers.other', 'Awk', ('awk', 'gawk', 'mawk', 'nawk'), ('*.awk',), ('application/x-awk',)), 'BBCodeLexer': ('pygments.lexers.text', 'BBCode', ('bbcode',), (), ('text/x-bbcode',)), 'BaseMakefileLexer': ('pygments.lexers.text', 'Base Makefile', ('basemake',), (), ()), 'BashLexer': ('pygments.lexers.shell', 'Bash', ('bash', 'sh', 'ksh'), ('*.sh', '*.ksh', '*.bash', '*.ebuild', '*.eclass', '.bashrc', 'bashrc', '.bash_*', 'bash_*'), ('application/x-sh', 'application/x-shellscript')), 'BashSessionLexer': ('pygments.lexers.shell', 'Bash Session', ('console',), ('*.sh-session',), ('application/x-shell-session',)), 'BatchLexer': ('pygments.lexers.shell', 'Batchfile', ('bat',), ('*.bat', '*.cmd'), ('application/x-dos-batch',)), 'BefungeLexer': ('pygments.lexers.other', 'Befunge', ('befunge',), ('*.befunge',), ('application/x-befunge',)), 'BlitzMaxLexer': ('pygments.lexers.compiled', 'BlitzMax', ('blitzmax', 'bmax'), ('*.bmx',), ('text/x-bmx',)), 'BooLexer': ('pygments.lexers.dotnet', 'Boo', ('boo',), ('*.boo',), ('text/x-boo',)), 'BrainfuckLexer': ('pygments.lexers.other', 'Brainfuck', ('brainfuck', 'bf'), ('*.bf', '*.b'), ('application/x-brainfuck',)), 'BroLexer': ('pygments.lexers.other', 'Bro', ('bro',), ('*.bro',), ()), 'BugsLexer': ('pygments.lexers.math', 'BUGS', ('bugs', 'winbugs', 'openbugs'), ('*.bug',), ()), 'CLexer': ('pygments.lexers.compiled', 'C', ('c',), ('*.c', '*.h', '*.idc'), ('text/x-chdr', 'text/x-csrc')), 'CMakeLexer': ('pygments.lexers.text', 'CMake', ('cmake',), ('*.cmake', 'CMakeLists.txt'), ('text/x-cmake',)), 'CObjdumpLexer': ('pygments.lexers.asm', 'c-objdump', ('c-objdump',), ('*.c-objdump',), ('text/x-c-objdump',)), 'CSharpAspxLexer': ('pygments.lexers.dotnet', 'aspx-cs', ('aspx-cs',), ('*.aspx', '*.asax', '*.ascx', '*.ashx', '*.asmx', '*.axd'), ()), 'CSharpLexer': ('pygments.lexers.dotnet', 'C#', ('csharp', 'c#'), ('*.cs',), ('text/x-csharp',)), 'Ca65Lexer': ('pygments.lexers.asm', 'ca65', ('ca65',), ('*.s',), ()), 'CbmBasicV2Lexer': ('pygments.lexers.other', 'CBM BASIC V2', ('cbmbas',), ('*.bas',), ()), 'CeylonLexer': ('pygments.lexers.jvm', 'Ceylon', ('ceylon',), ('*.ceylon',), ('text/x-ceylon',)), 'Cfengine3Lexer': ('pygments.lexers.other', 'CFEngine3', ('cfengine3', 'cf3'), ('*.cf',), ()), 'CheetahHtmlLexer': ('pygments.lexers.templates', 'HTML+Cheetah', ('html+cheetah', 'html+spitfire'), (), ('text/html+cheetah', 'text/html+spitfire')), 'CheetahJavascriptLexer': ('pygments.lexers.templates', 'JavaScript+Cheetah', ('js+cheetah', 'javascript+cheetah', 'js+spitfire', 'javascript+spitfire'), (), ('application/x-javascript+cheetah', 'text/x-javascript+cheetah', 'text/javascript+cheetah', 'application/x-javascript+spitfire', 'text/x-javascript+spitfire', 'text/javascript+spitfire')), 'CheetahLexer': ('pygments.lexers.templates', 'Cheetah', ('cheetah', 'spitfire'), ('*.tmpl', '*.spt'), ('application/x-cheetah', 'application/x-spitfire')), 'CheetahXmlLexer': ('pygments.lexers.templates', 'XML+Cheetah', ('xml+cheetah', 'xml+spitfire'), (), ('application/xml+cheetah', 'application/xml+spitfire')), 'ClojureLexer': ('pygments.lexers.jvm', 'Clojure', ('clojure', 'clj'), ('*.clj',), ('text/x-clojure', 'application/x-clojure')), 'CobolFreeformatLexer': ('pygments.lexers.compiled', 'COBOLFree', ('cobolfree',), ('*.cbl', '*.CBL'), ()), 'CobolLexer': ('pygments.lexers.compiled', 'COBOL', ('cobol',), ('*.cob', '*.COB', '*.cpy', '*.CPY'), ('text/x-cobol',)), 'CoffeeScriptLexer': ('pygments.lexers.web', 'CoffeeScript', ('coffee-script', 'coffeescript'), ('*.coffee',), ('text/coffeescript',)), 'ColdfusionHtmlLexer': ('pygments.lexers.templates', 'Coldfusion HTML', ('cfm',), ('*.cfm', '*.cfml', '*.cfc'), ('application/x-coldfusion',)), 'ColdfusionLexer': ('pygments.lexers.templates', 'cfstatement', ('cfs',), (), ()), 'CommonLispLexer': ('pygments.lexers.functional', 'Common Lisp', ('common-lisp', 'cl'), ('*.cl', '*.lisp', '*.el'), ('text/x-common-lisp',)), 'CoqLexer': ('pygments.lexers.functional', 'Coq', ('coq',), ('*.v',), ('text/x-coq',)), 'CppLexer': ('pygments.lexers.compiled', 'C++', ('cpp', 'c++'), ('*.cpp', '*.hpp', '*.c++', '*.h++', '*.cc', '*.hh', '*.cxx', '*.hxx', '*.C', '*.H', '*.cp', '*.CPP'), ('text/x-c++hdr', 'text/x-c++src')), 'CppObjdumpLexer': ('pygments.lexers.asm', 'cpp-objdump', ('cpp-objdump', 'c++-objdumb', 'cxx-objdump'), ('*.cpp-objdump', '*.c++-objdump', '*.cxx-objdump'), ('text/x-cpp-objdump',)), 'CrocLexer': ('pygments.lexers.agile', 'Croc', ('croc',), ('*.croc',), ('text/x-crocsrc',)), 'CssDjangoLexer': ('pygments.lexers.templates', 'CSS+Django/Jinja', ('css+django', 'css+jinja'), (), ('text/css+django', 'text/css+jinja')), 'CssErbLexer': ('pygments.lexers.templates', 'CSS+Ruby', ('css+erb', 'css+ruby'), (), ('text/css+ruby',)), 'CssGenshiLexer': ('pygments.lexers.templates', 'CSS+Genshi Text', ('css+genshitext', 'css+genshi'), (), ('text/css+genshi',)), 'CssLexer': ('pygments.lexers.web', 'CSS', ('css',), ('*.css',), ('text/css',)), 'CssPhpLexer': ('pygments.lexers.templates', 'CSS+PHP', ('css+php',), (), ('text/css+php',)), 'CssSmartyLexer': ('pygments.lexers.templates', 'CSS+Smarty', ('css+smarty',), (), ('text/css+smarty',)), 'CudaLexer': ('pygments.lexers.compiled', 'CUDA', ('cuda', 'cu'), ('*.cu', '*.cuh'), ('text/x-cuda',)), 'CythonLexer': ('pygments.lexers.compiled', 'Cython', ('cython', 'pyx'), ('*.pyx', '*.pxd', '*.pxi'), ('text/x-cython', 'application/x-cython')), 'DLexer': ('pygments.lexers.compiled', 'D', ('d',), ('*.d', '*.di'), ('text/x-dsrc',)), 'DObjdumpLexer': ('pygments.lexers.asm', 'd-objdump', ('d-objdump',), ('*.d-objdump',), ('text/x-d-objdump',)), 'DarcsPatchLexer': ('pygments.lexers.text', 'Darcs Patch', ('dpatch',), ('*.dpatch', '*.darcspatch'), ()), 'DartLexer': ('pygments.lexers.web', 'Dart', ('dart',), ('*.dart',), ('text/x-dart',)), 'DebianControlLexer': ('pygments.lexers.text', 'Debian Control file', ('control',), ('control',), ()), 'DelphiLexer': ('pygments.lexers.compiled', 'Delphi', ('delphi', 'pas', 'pascal', 'objectpascal'), ('*.pas',), ('text/x-pascal',)), 'DgLexer': ('pygments.lexers.agile', 'dg', ('dg',), ('*.dg',), ('text/x-dg',)), 'DiffLexer': ('pygments.lexers.text', 'Diff', ('diff', 'udiff'), ('*.diff', '*.patch'), ('text/x-diff', 'text/x-patch')), 'DjangoLexer': ('pygments.lexers.templates', 'Django/Jinja', ('django', 'jinja'), (), ('application/x-django-templating', 'application/x-jinja')), 'DtdLexer': ('pygments.lexers.web', 'DTD', ('dtd',), ('*.dtd',), ('application/xml-dtd',)), 'DuelLexer': ('pygments.lexers.web', 'Duel', ('duel', 'Duel Engine', 'Duel View', 'JBST', 'jbst', 'JsonML+BST'), ('*.duel', '*.jbst'), ('text/x-duel', 'text/x-jbst')), 'DylanConsoleLexer': ('pygments.lexers.compiled', 'Dylan session', ('dylan-console', 'dylan-repl'), ('*.dylan-console',), ('text/x-dylan-console',)), 'DylanLexer': ('pygments.lexers.compiled', 'Dylan', ('dylan',), ('*.dylan', '*.dyl', '*.intr'), ('text/x-dylan',)), 'DylanLidLexer': ('pygments.lexers.compiled', 'DylanLID', ('dylan-lid', 'lid'), ('*.lid', '*.hdp'), ('text/x-dylan-lid',)), 'ECLLexer': ('pygments.lexers.other', 'ECL', ('ecl',), ('*.ecl',), ('application/x-ecl',)), 'ECLexer': ('pygments.lexers.compiled', 'eC', ('ec',), ('*.ec', '*.eh'), ('text/x-echdr', 'text/x-ecsrc')), 'ElixirConsoleLexer': ('pygments.lexers.functional', 'Elixir iex session', ('iex',), (), ('text/x-elixir-shellsession',)), 'ElixirLexer': ('pygments.lexers.functional', 'Elixir', ('elixir', 'ex', 'exs'), ('*.ex', '*.exs'), ('text/x-elixir',)), 'ErbLexer': ('pygments.lexers.templates', 'ERB', ('erb',), (), ('application/x-ruby-templating',)), 'ErlangLexer': ('pygments.lexers.functional', 'Erlang', ('erlang',), ('*.erl', '*.hrl', '*.es', '*.escript'), ('text/x-erlang',)), 'ErlangShellLexer': ('pygments.lexers.functional', 'Erlang erl session', ('erl',), ('*.erl-sh',), ('text/x-erl-shellsession',)), 'EvoqueHtmlLexer': ('pygments.lexers.templates', 'HTML+Evoque', ('html+evoque',), ('*.html',), ('text/html+evoque',)), 'EvoqueLexer': ('pygments.lexers.templates', 'Evoque', ('evoque',), ('*.evoque',), ('application/x-evoque',)), 'EvoqueXmlLexer': ('pygments.lexers.templates', 'XML+Evoque', ('xml+evoque',), ('*.xml',), ('application/xml+evoque',)), 'FSharpLexer': ('pygments.lexers.dotnet', 'FSharp', ('fsharp',), ('*.fs', '*.fsi'), ('text/x-fsharp',)), 'FactorLexer': ('pygments.lexers.agile', 'Factor', ('factor',), ('*.factor',), ('text/x-factor',)), 'FancyLexer': ('pygments.lexers.agile', 'Fancy', ('fancy', 'fy'), ('*.fy', '*.fancypack'), ('text/x-fancysrc',)), 'FantomLexer': ('pygments.lexers.compiled', 'Fantom', ('fan',), ('*.fan',), ('application/x-fantom',)), 'FelixLexer': ('pygments.lexers.compiled', 'Felix', ('felix', 'flx'), ('*.flx', '*.flxh'), ('text/x-felix',)), 'FortranLexer': ('pygments.lexers.compiled', 'Fortran', ('fortran',), ('*.f', '*.f90', '*.F', '*.F90'), ('text/x-fortran',)), 'FoxProLexer': ('pygments.lexers.foxpro', 'FoxPro', ('Clipper', 'XBase'), ('*.PRG', '*.prg'), ()), 'GLShaderLexer': ('pygments.lexers.compiled', 'GLSL', ('glsl',), ('*.vert', '*.frag', '*.geo'), ('text/x-glslsrc',)), 'GasLexer': ('pygments.lexers.asm', 'GAS', ('gas',), ('*.s', '*.S'), ('text/x-gas',)), 'GenshiLexer': ('pygments.lexers.templates', 'Genshi', ('genshi', 'kid', 'xml+genshi', 'xml+kid'), ('*.kid',), ('application/x-genshi', 'application/x-kid')), 'GenshiTextLexer': ('pygments.lexers.templates', 'Genshi Text', ('genshitext',), (), ('application/x-genshi-text', 'text/x-genshi')), 'GettextLexer': ('pygments.lexers.text', 'Gettext Catalog', ('pot', 'po'), ('*.pot', '*.po'), ('application/x-gettext', 'text/x-gettext', 'text/gettext')), 'GherkinLexer': ('pygments.lexers.other', 'Gherkin', ('Cucumber', 'cucumber', 'Gherkin', 'gherkin'), ('*.feature',), ('text/x-gherkin',)), 'GnuplotLexer': ('pygments.lexers.other', 'Gnuplot', ('gnuplot',), ('*.plot', '*.plt'), ('text/x-gnuplot',)), 'GoLexer': ('pygments.lexers.compiled', 'Go', ('go',), ('*.go',), ('text/x-gosrc',)), 'GoodDataCLLexer': ('pygments.lexers.other', 'GoodData-CL', ('gooddata-cl',), ('*.gdc',), ('text/x-gooddata-cl',)), 'GosuLexer': ('pygments.lexers.jvm', 'Gosu', ('gosu',), ('*.gs', '*.gsx', '*.gsp', '*.vark'), ('text/x-gosu',)), 'GosuTemplateLexer': ('pygments.lexers.jvm', 'Gosu Template', ('gst',), ('*.gst',), ('text/x-gosu-template',)), 'GroffLexer': ('pygments.lexers.text', 'Groff', ('groff', 'nroff', 'man'), ('*.[1234567]', '*.man'), ('application/x-troff', 'text/troff')), 'GroovyLexer': ('pygments.lexers.jvm', 'Groovy', ('groovy',), ('*.groovy',), ('text/x-groovy',)), 'HamlLexer': ('pygments.lexers.web', 'Haml', ('haml', 'HAML'), ('*.haml',), ('text/x-haml',)), 'HaskellLexer': ('pygments.lexers.functional', 'Haskell', ('haskell', 'hs'), ('*.hs',), ('text/x-haskell',)), 'HaxeLexer': ('pygments.lexers.web', 'haXe', ('hx', 'haXe'), ('*.hx',), ('text/haxe',)), 'HtmlDjangoLexer': ('pygments.lexers.templates', 'HTML+Django/Jinja', ('html+django', 'html+jinja'), (), ('text/html+django', 'text/html+jinja')), 'HtmlGenshiLexer': ('pygments.lexers.templates', 'HTML+Genshi', ('html+genshi', 'html+kid'), (), ('text/html+genshi',)), 'HtmlLexer': ('pygments.lexers.web', 'HTML', ('html',), ('*.html', '*.htm', '*.xhtml', '*.xslt'), ('text/html', 'application/xhtml+xml')), 'HtmlPhpLexer': ('pygments.lexers.templates', 'HTML+PHP', ('html+php',), ('*.phtml',), ('application/x-php', 'application/x-httpd-php', 'application/x-httpd-php3', 'application/x-httpd-php4', 'application/x-httpd-php5')), 'HtmlSmartyLexer': ('pygments.lexers.templates', 'HTML+Smarty', ('html+smarty',), (), ('text/html+smarty',)), 'HttpLexer': ('pygments.lexers.text', 'HTTP', ('http',), (), ()), 'HxmlLexer': ('pygments.lexers.text', 'Hxml', ('haxeml', 'hxml'), ('*.hxml',), ()), 'HybrisLexer': ('pygments.lexers.other', 'Hybris', ('hybris', 'hy'), ('*.hy', '*.hyb'), ('text/x-hybris', 'application/x-hybris')), 'IDLLexer': ('pygments.lexers.math', 'IDL', ('idl',), ('*.pro',), ('text/idl',)), 'IniLexer': ('pygments.lexers.text', 'INI', ('ini', 'cfg'), ('*.ini', '*.cfg'), ('text/x-ini',)), 'IoLexer': ('pygments.lexers.agile', 'Io', ('io',), ('*.io',), ('text/x-iosrc',)), 'IokeLexer': ('pygments.lexers.jvm', 'Ioke', ('ioke', 'ik'), ('*.ik',), ('text/x-iokesrc',)), 'IrcLogsLexer': ('pygments.lexers.text', 'IRC logs', ('irc',), ('*.weechatlog',), ('text/x-irclog',)), 'JadeLexer': ('pygments.lexers.web', 'Jade', ('jade', 'JADE'), ('*.jade',), ('text/x-jade',)), 'JagsLexer': ('pygments.lexers.math', 'JAGS', ('jags',), ('*.jag', '*.bug'), ()), 'JavaLexer': ('pygments.lexers.jvm', 'Java', ('java',), ('*.java',), ('text/x-java',)), 'JavascriptDjangoLexer': ('pygments.lexers.templates', 'JavaScript+Django/Jinja', ('js+django', 'javascript+django', 'js+jinja', 'javascript+jinja'), (), ('application/x-javascript+django', 'application/x-javascript+jinja', 'text/x-javascript+django', 'text/x-javascript+jinja', 'text/javascript+django', 'text/javascript+jinja')), 'JavascriptErbLexer': ('pygments.lexers.templates', 'JavaScript+Ruby', ('js+erb', 'javascript+erb', 'js+ruby', 'javascript+ruby'), (), ('application/x-javascript+ruby', 'text/x-javascript+ruby', 'text/javascript+ruby')), 'JavascriptGenshiLexer': ('pygments.lexers.templates', 'JavaScript+Genshi Text', ('js+genshitext', 'js+genshi', 'javascript+genshitext', 'javascript+genshi'), (), ('application/x-javascript+genshi', 'text/x-javascript+genshi', 'text/javascript+genshi')), 'JavascriptLexer': ('pygments.lexers.web', 'JavaScript', ('js', 'javascript'), ('*.js',), ('application/javascript', 'application/x-javascript', 'text/x-javascript', 'text/javascript')), 'JavascriptPhpLexer': ('pygments.lexers.templates', 'JavaScript+PHP', ('js+php', 'javascript+php'), (), ('application/x-javascript+php', 'text/x-javascript+php', 'text/javascript+php')), 'JavascriptSmartyLexer': ('pygments.lexers.templates', 'JavaScript+Smarty', ('js+smarty', 'javascript+smarty'), (), ('application/x-javascript+smarty', 'text/x-javascript+smarty', 'text/javascript+smarty')), 'JsonLexer': ('pygments.lexers.web', 'JSON', ('json',), ('*.json',), ('application/json',)), 'JspLexer': ('pygments.lexers.templates', 'Java Server Page', ('jsp',), ('*.jsp',), ('application/x-jsp',)), 'JuliaConsoleLexer': ('pygments.lexers.math', 'Julia console', ('jlcon',), (), ()), 'JuliaLexer': ('pygments.lexers.math', 'Julia', ('julia', 'jl'), ('*.jl',), ('text/x-julia', 'application/x-julia')), 'KconfigLexer': ('pygments.lexers.other', 'Kconfig', ('kconfig', 'menuconfig', 'linux-config', 'kernel-config'), ('Kconfig', '*Config.in*', 'external.in*', 'standard-modules.in'), ('text/x-kconfig',)), 'KokaLexer': ('pygments.lexers.functional', 'Koka', ('koka',), ('*.kk', '*.kki'), ('text/x-koka',)), 'KotlinLexer': ('pygments.lexers.jvm', 'Kotlin', ('kotlin',), ('*.kt',), ('text/x-kotlin',)), 'LassoCssLexer': ('pygments.lexers.templates', 'CSS+Lasso', ('css+lasso',), (), ('text/css+lasso',)), 'LassoHtmlLexer': ('pygments.lexers.templates', 'HTML+Lasso', ('html+lasso',), (), ('text/html+lasso', 'application/x-httpd-lasso', 'application/x-httpd-lasso[89]')), 'LassoJavascriptLexer': ('pygments.lexers.templates', 'JavaScript+Lasso', ('js+lasso', 'javascript+lasso'), (), ('application/x-javascript+lasso', 'text/x-javascript+lasso', 'text/javascript+lasso')), 'LassoLexer': ('pygments.lexers.web', 'Lasso', ('lasso', 'lassoscript'), ('*.lasso', '*.lasso[89]'), ('text/x-lasso',)), 'LassoXmlLexer': ('pygments.lexers.templates', 'XML+Lasso', ('xml+lasso',), (), ('application/xml+lasso',)), 'LighttpdConfLexer': ('pygments.lexers.text', 'Lighttpd configuration file', ('lighty', 'lighttpd'), (), ('text/x-lighttpd-conf',)), 'LiterateHaskellLexer': ('pygments.lexers.functional', 'Literate Haskell', ('lhs', 'literate-haskell'), ('*.lhs',), ('text/x-literate-haskell',)), 'LiveScriptLexer': ('pygments.lexers.web', 'LiveScript', ('live-script', 'livescript'), ('*.ls',), ('text/livescript',)), 'LlvmLexer': ('pygments.lexers.asm', 'LLVM', ('llvm',), ('*.ll',), ('text/x-llvm',)), 'LogosLexer': ('pygments.lexers.compiled', 'Logos', ('logos',), ('*.x', '*.xi', '*.xm', '*.xmi'), ('text/x-logos',)), 'LogtalkLexer': ('pygments.lexers.other', 'Logtalk', ('logtalk',), ('*.lgt',), ('text/x-logtalk',)), 'LuaLexer': ('pygments.lexers.agile', 'Lua', ('lua',), ('*.lua', '*.wlua'), ('text/x-lua', 'application/x-lua')), 'MOOCodeLexer': ('pygments.lexers.other', 'MOOCode', ('moocode',), ('*.moo',), ('text/x-moocode',)), 'MakefileLexer': ('pygments.lexers.text', 'Makefile', ('make', 'makefile', 'mf', 'bsdmake'), ('*.mak', 'Makefile', 'makefile', 'Makefile.*', 'GNUmakefile'), ('text/x-makefile',)), 'MakoCssLexer': ('pygments.lexers.templates', 'CSS+Mako', ('css+mako',), (), ('text/css+mako',)), 'MakoHtmlLexer': ('pygments.lexers.templates', 'HTML+Mako', ('html+mako',), (), ('text/html+mako',)), 'MakoJavascriptLexer': ('pygments.lexers.templates', 'JavaScript+Mako', ('js+mako', 'javascript+mako'), (), ('application/x-javascript+mako', 'text/x-javascript+mako', 'text/javascript+mako')), 'MakoLexer': ('pygments.lexers.templates', 'Mako', ('mako',), ('*.mao',), ('application/x-mako',)), 'MakoXmlLexer': ('pygments.lexers.templates', 'XML+Mako', ('xml+mako',), (), ('application/xml+mako',)), 'MaqlLexer': ('pygments.lexers.other', 'MAQL', ('maql',), ('*.maql',), ('text/x-gooddata-maql', 'application/x-gooddata-maql')), 'MasonLexer': ('pygments.lexers.templates', 'Mason', ('mason',), ('*.m', '*.mhtml', '*.mc', '*.mi', 'autohandler', 'dhandler'), ('application/x-mason',)), 'MatlabLexer': ('pygments.lexers.math', 'Matlab', ('matlab',), ('*.m',), ('text/matlab',)), 'MatlabSessionLexer': ('pygments.lexers.math', 'Matlab session', ('matlabsession',), (), ()), 'MiniDLexer': ('pygments.lexers.agile', 'MiniD', ('minid',), ('*.md',), ('text/x-minidsrc',)), 'ModelicaLexer': ('pygments.lexers.other', 'Modelica', ('modelica',), ('*.mo',), ('text/x-modelica',)), 'Modula2Lexer': ('pygments.lexers.compiled', 'Modula-2', ('modula2', 'm2'), ('*.def', '*.mod'), ('text/x-modula2',)), 'MoinWikiLexer': ('pygments.lexers.text', 'MoinMoin/Trac Wiki markup', ('trac-wiki', 'moin'), (), ('text/x-trac-wiki',)), 'MonkeyLexer': ('pygments.lexers.compiled', 'Monkey', ('monkey',), ('*.monkey',), ('text/x-monkey',)), 'MoonScriptLexer': ('pygments.lexers.agile', 'MoonScript', ('moon', 'moonscript'), ('*.moon',), ('text/x-moonscript', 'application/x-moonscript')), 'MscgenLexer': ('pygments.lexers.other', 'Mscgen', ('mscgen', 'msc'), ('*.msc',), ()), 'MuPADLexer': ('pygments.lexers.math', 'MuPAD', ('mupad',), ('*.mu',), ()), 'MxmlLexer': ('pygments.lexers.web', 'MXML', ('mxml',), ('*.mxml',), ()), 'MySqlLexer': ('pygments.lexers.sql', 'MySQL', ('mysql',), (), ('text/x-mysql',)), 'MyghtyCssLexer': ('pygments.lexers.templates', 'CSS+Myghty', ('css+myghty',), (), ('text/css+myghty',)), 'MyghtyHtmlLexer': ('pygments.lexers.templates', 'HTML+Myghty', ('html+myghty',), (), ('text/html+myghty',)), 'MyghtyJavascriptLexer': ('pygments.lexers.templates', 'JavaScript+Myghty', ('js+myghty', 'javascript+myghty'), (), ('application/x-javascript+myghty', 'text/x-javascript+myghty', 'text/javascript+mygthy')), 'MyghtyLexer': ('pygments.lexers.templates', 'Myghty', ('myghty',), ('*.myt', 'autodelegate'), ('application/x-myghty',)), 'MyghtyXmlLexer': ('pygments.lexers.templates', 'XML+Myghty', ('xml+myghty',), (), ('application/xml+myghty',)), 'NSISLexer': ('pygments.lexers.other', 'NSIS', ('nsis', 'nsi', 'nsh'), ('*.nsi', '*.nsh'), ('text/x-nsis',)), 'NasmLexer': ('pygments.lexers.asm', 'NASM', ('nasm',), ('*.asm', '*.ASM'), ('text/x-nasm',)), 'NemerleLexer': ('pygments.lexers.dotnet', 'Nemerle', ('nemerle',), ('*.n',), ('text/x-nemerle',)), 'NewLispLexer': ('pygments.lexers.functional', 'NewLisp', ('newlisp',), ('*.lsp', '*.nl'), ('text/x-newlisp', 'application/x-newlisp')), 'NewspeakLexer': ('pygments.lexers.other', 'Newspeak', ('newspeak',), ('*.ns2',), ('text/x-newspeak',)), 'NginxConfLexer': ('pygments.lexers.text', 'Nginx configuration file', ('nginx',), (), ('text/x-nginx-conf',)), 'NimrodLexer': ('pygments.lexers.compiled', 'Nimrod', ('nimrod', 'nim'), ('*.nim', '*.nimrod'), ('text/x-nimrod',)), 'NumPyLexer': ('pygments.lexers.math', 'NumPy', ('numpy',), (), ()), 'ObjdumpLexer': ('pygments.lexers.asm', 'objdump', ('objdump',), ('*.objdump',), ('text/x-objdump',)), 'ObjectiveCLexer': ('pygments.lexers.compiled', 'Objective-C', ('objective-c', 'objectivec', 'obj-c', 'objc'), ('*.m', '*.h'), ('text/x-objective-c',)), 'ObjectiveCppLexer': ('pygments.lexers.compiled', 'Objective-C++', ('objective-c++', 'objectivec++', 'obj-c++', 'objc++'), ('*.mm', '*.hh'), ('text/x-objective-c++',)), 'ObjectiveJLexer': ('pygments.lexers.web', 'Objective-J', ('objective-j', 'objectivej', 'obj-j', 'objj'), ('*.j',), ('text/x-objective-j',)), 'OcamlLexer': ('pygments.lexers.functional', 'OCaml', ('ocaml',), ('*.ml', '*.mli', '*.mll', '*.mly'), ('text/x-ocaml',)), 'OctaveLexer': ('pygments.lexers.math', 'Octave', ('octave',), ('*.m',), ('text/octave',)), 'OocLexer': ('pygments.lexers.compiled', 'Ooc', ('ooc',), ('*.ooc',), ('text/x-ooc',)), 'OpaLexer': ('pygments.lexers.functional', 'Opa', ('opa',), ('*.opa',), ('text/x-opa',)), 'OpenEdgeLexer': ('pygments.lexers.other', 'OpenEdge ABL', ('openedge', 'abl', 'progress'), ('*.p', '*.cls'), ('text/x-openedge', 'application/x-openedge')), 'PerlLexer': ('pygments.lexers.agile', 'Perl', ('perl', 'pl'), ('*.pl', '*.pm'), ('text/x-perl', 'application/x-perl')), 'PhpLexer': ('pygments.lexers.web', 'PHP', ('php', 'php3', 'php4', 'php5'), ('*.php', '*.php[345]', '*.inc'), ('text/x-php',)), 'PlPgsqlLexer': ('pygments.lexers.sql', 'PL/pgSQL', ('plpgsql',), (), ('text/x-plpgsql',)), 'PostScriptLexer': ('pygments.lexers.other', 'PostScript', ('postscript',), ('*.ps', '*.eps'), ('application/postscript',)), 'PostgresConsoleLexer': ('pygments.lexers.sql', 'PostgreSQL console (psql)', ('psql', 'postgresql-console', 'postgres-console'), (), ('text/x-postgresql-psql',)), 'PostgresLexer': ('pygments.lexers.sql', 'PostgreSQL SQL dialect', ('postgresql', 'postgres'), (), ('text/x-postgresql',)), 'PovrayLexer': ('pygments.lexers.other', 'POVRay', ('pov',), ('*.pov', '*.inc'), ('text/x-povray',)), 'PowerShellLexer': ('pygments.lexers.shell', 'PowerShell', ('powershell', 'posh', 'ps1'), ('*.ps1',), ('text/x-powershell',)), 'PrologLexer': ('pygments.lexers.compiled', 'Prolog', ('prolog',), ('*.prolog', '*.pro', '*.pl'), ('text/x-prolog',)), 'PropertiesLexer': ('pygments.lexers.text', 'Properties', ('properties',), ('*.properties',), ('text/x-java-properties',)), 'ProtoBufLexer': ('pygments.lexers.other', 'Protocol Buffer', ('protobuf',), ('*.proto',), ()), 'PuppetLexer': ('pygments.lexers.other', 'Puppet', ('puppet',), ('*.pp',), ()), 'PyPyLogLexer': ('pygments.lexers.text', 'PyPy Log', ('pypylog', 'pypy'), ('*.pypylog',), ('application/x-pypylog',)), 'Python3Lexer': ('pygments.lexers.agile', 'Python 3', ('python3', 'py3'), (), ('text/x-python3', 'application/x-python3')), 'Python3TracebackLexer': ('pygments.lexers.agile', 'Python 3.0 Traceback', ('py3tb',), ('*.py3tb',), ('text/x-python3-traceback',)), 'PythonConsoleLexer': ('pygments.lexers.agile', 'Python console session', ('pycon',), (), ('text/x-python-doctest',)), 'PythonLexer': ('pygments.lexers.agile', 'Python', ('python', 'py', 'sage'), ('*.py', '*.pyw', '*.sc', 'SConstruct', 'SConscript', '*.tac', '*.sage'), ('text/x-python', 'application/x-python')), 'PythonTracebackLexer': ('pygments.lexers.agile', 'Python Traceback', ('pytb',), ('*.pytb',), ('text/x-python-traceback',)), 'QmlLexer': ('pygments.lexers.web', 'QML', ('qml', 'Qt Meta Language', 'Qt modeling Language'), ('*.qml',), ('application/x-qml',)), 'RConsoleLexer': ('pygments.lexers.math', 'RConsole', ('rconsole', 'rout'), ('*.Rout',), ()), 'RPMSpecLexer': ('pygments.lexers.other', 'RPMSpec', ('spec',), ('*.spec',), ('text/x-rpm-spec',)), 'RacketLexer': ('pygments.lexers.functional', 'Racket', ('racket', 'rkt'), ('*.rkt', '*.rktl'), ('text/x-racket', 'application/x-racket')), 'RagelCLexer': ('pygments.lexers.parsers', 'Ragel in C Host', ('ragel-c',), ('*.rl',), ()), 'RagelCppLexer': ('pygments.lexers.parsers', 'Ragel in CPP Host', ('ragel-cpp',), ('*.rl',), ()), 'RagelDLexer': ('pygments.lexers.parsers', 'Ragel in D Host', ('ragel-d',), ('*.rl',), ()), 'RagelEmbeddedLexer': ('pygments.lexers.parsers', 'Embedded Ragel', ('ragel-em',), ('*.rl',), ()), 'RagelJavaLexer': ('pygments.lexers.parsers', 'Ragel in Java Host', ('ragel-java',), ('*.rl',), ()), 'RagelLexer': ('pygments.lexers.parsers', 'Ragel', ('ragel',), (), ()), 'RagelObjectiveCLexer': ('pygments.lexers.parsers', 'Ragel in Objective C Host', ('ragel-objc',), ('*.rl',), ()), 'RagelRubyLexer': ('pygments.lexers.parsers', 'Ragel in Ruby Host', ('ragel-ruby', 'ragel-rb'), ('*.rl',), ()), 'RawTokenLexer': ('pygments.lexers.special', 'Raw token data', ('raw',), (), ('application/x-pygments-tokens',)), 'RdLexer': ('pygments.lexers.math', 'Rd', ('rd',), ('*.Rd',), ('text/x-r-doc',)), 'RebolLexer': ('pygments.lexers.other', 'REBOL', ('rebol',), ('*.r', '*.r3'), ('text/x-rebol',)), 'RedcodeLexer': ('pygments.lexers.other', 'Redcode', ('redcode',), ('*.cw',), ()), 'RegeditLexer': ('pygments.lexers.text', 'reg', ('registry',), ('*.reg',), ('text/x-windows-registry',)), 'RhtmlLexer': ('pygments.lexers.templates', 'RHTML', ('rhtml', 'html+erb', 'html+ruby'), ('*.rhtml',), ('text/html+ruby',)), 'RobotFrameworkLexer': ('pygments.lexers.other', 'RobotFramework', ('RobotFramework', 'robotframework'), ('*.txt', '*.robot'), ('text/x-robotframework',)), 'RstLexer': ('pygments.lexers.text', 'reStructuredText', ('rst', 'rest', 'restructuredtext'), ('*.rst', '*.rest'), ('text/x-rst', 'text/prs.fallenstein.rst')), 'RubyConsoleLexer': ('pygments.lexers.agile', 'Ruby irb session', ('rbcon', 'irb'), (), ('text/x-ruby-shellsession',)), 'RubyLexer': ('pygments.lexers.agile', 'Ruby', ('rb', 'ruby', 'duby'), ('*.rb', '*.rbw', 'Rakefile', '*.rake', '*.gemspec', '*.rbx', '*.duby'), ('text/x-ruby', 'application/x-ruby')), 'RustLexer': ('pygments.lexers.compiled', 'Rust', ('rust',), ('*.rs', '*.rc'), ('text/x-rustsrc',)), 'SLexer': ('pygments.lexers.math', 'S', ('splus', 's', 'r'), ('*.S', '*.R', '.Rhistory', '.Rprofile'), ('text/S-plus', 'text/S', 'text/x-r-source', 'text/x-r', 'text/x-R', 'text/x-r-history', 'text/x-r-profile')), 'SMLLexer': ('pygments.lexers.functional', 'Standard ML', ('sml',), ('*.sml', '*.sig', '*.fun'), ('text/x-standardml', 'application/x-standardml')), 'SassLexer': ('pygments.lexers.web', 'Sass', ('sass', 'SASS'), ('*.sass',), ('text/x-sass',)), 'ScalaLexer': ('pygments.lexers.jvm', 'Scala', ('scala',), ('*.scala',), ('text/x-scala',)), 'ScamlLexer': ('pygments.lexers.web', 'Scaml', ('scaml', 'SCAML'), ('*.scaml',), ('text/x-scaml',)), 'SchemeLexer': ('pygments.lexers.functional', 'Scheme', ('scheme', 'scm'), ('*.scm', '*.ss'), ('text/x-scheme', 'application/x-scheme')), 'ScilabLexer': ('pygments.lexers.math', 'Scilab', ('scilab',), ('*.sci', '*.sce', '*.tst'), ('text/scilab',)), 'ScssLexer': ('pygments.lexers.web', 'SCSS', ('scss',), ('*.scss',), ('text/x-scss',)), 'ShellSessionLexer': ('pygments.lexers.shell', 'Shell Session', ('shell-session',), ('*.shell-session',), ('application/x-sh-session',)), 'SmaliLexer': ('pygments.lexers.dalvik', 'Smali', ('smali',), ('*.smali',), ('text/smali',)), 'SmalltalkLexer': ('pygments.lexers.other', 'Smalltalk', ('smalltalk', 'squeak'), ('*.st',), ('text/x-smalltalk',)), 'SmartyLexer': ('pygments.lexers.templates', 'Smarty', ('smarty',), ('*.tpl',), ('application/x-smarty',)), 'SnobolLexer': ('pygments.lexers.other', 'Snobol', ('snobol',), ('*.snobol',), ('text/x-snobol',)), 'SourcePawnLexer': ('pygments.lexers.other', 'SourcePawn', ('sp',), ('*.sp',), ('text/x-sourcepawn',)), 'SourcesListLexer': ('pygments.lexers.text', 'Debian Sourcelist', ('sourceslist', 'sources.list'), ('sources.list',), ()), 'SqlLexer': ('pygments.lexers.sql', 'SQL', ('sql',), ('*.sql',), ('text/x-sql',)), 'SqliteConsoleLexer': ('pygments.lexers.sql', 'sqlite3con', ('sqlite3',), ('*.sqlite3-console',), ('text/x-sqlite3-console',)), 'SquidConfLexer': ('pygments.lexers.text', 'SquidConf', ('squidconf', 'squid.conf', 'squid'), ('squid.conf',), ('text/x-squidconf',)), 'SspLexer': ('pygments.lexers.templates', 'Scalate Server Page', ('ssp',), ('*.ssp',), ('application/x-ssp',)), 'StanLexer': ('pygments.lexers.math', 'Stan', ('stan',), ('*.stan',), ()), 'SystemVerilogLexer': ('pygments.lexers.hdl', 'systemverilog', ('systemverilog', 'sv'), ('*.sv', '*.svh'), ('text/x-systemverilog',)), 'TclLexer': ('pygments.lexers.agile', 'Tcl', ('tcl',), ('*.tcl',), ('text/x-tcl', 'text/x-script.tcl', 'application/x-tcl')), 'TcshLexer': ('pygments.lexers.shell', 'Tcsh', ('tcsh', 'csh'), ('*.tcsh', '*.csh'), ('application/x-csh',)), 'TeaTemplateLexer': ('pygments.lexers.templates', 'Tea', ('tea',), ('*.tea',), ('text/x-tea',)), 'TexLexer': ('pygments.lexers.text', 'TeX', ('tex', 'latex'), ('*.tex', '*.aux', '*.toc'), ('text/x-tex', 'text/x-latex')), 'TextLexer': ('pygments.lexers.special', 'Text only', ('text',), ('*.txt',), ('text/plain',)), 'TreetopLexer': ('pygments.lexers.parsers', 'Treetop', ('treetop',), ('*.treetop', '*.tt'), ()), 'TypeScriptLexer': ('pygments.lexers.web', 'TypeScript', ('ts',), ('*.ts',), ('text/x-typescript',)), 'UrbiscriptLexer': ('pygments.lexers.other', 'UrbiScript', ('urbiscript',), ('*.u',), ('application/x-urbiscript',)), 'VGLLexer': ('pygments.lexers.other', 'VGL', ('vgl',), ('*.rpf',), ()), 'ValaLexer': ('pygments.lexers.compiled', 'Vala', ('vala', 'vapi'), ('*.vala', '*.vapi'), ('text/x-vala',)), 'VbNetAspxLexer': ('pygments.lexers.dotnet', 'aspx-vb', ('aspx-vb',), ('*.aspx', '*.asax', '*.ascx', '*.ashx', '*.asmx', '*.axd'), ()), 'VbNetLexer': ('pygments.lexers.dotnet', 'VB.net', ('vb.net', 'vbnet'), ('*.vb', '*.bas'), ('text/x-vbnet', 'text/x-vba')), 'VelocityHtmlLexer': ('pygments.lexers.templates', 'HTML+Velocity', ('html+velocity',), (), ('text/html+velocity',)), 'VelocityLexer': ('pygments.lexers.templates', 'Velocity', ('velocity',), ('*.vm', '*.fhtml'), ()), 'VelocityXmlLexer': ('pygments.lexers.templates', 'XML+Velocity', ('xml+velocity',), (), ('application/xml+velocity',)), 'VerilogLexer': ('pygments.lexers.hdl', 'verilog', ('verilog', 'v'), ('*.v',), ('text/x-verilog',)), 'VhdlLexer': ('pygments.lexers.hdl', 'vhdl', ('vhdl',), ('*.vhdl', '*.vhd'), ('text/x-vhdl',)), 'VimLexer': ('pygments.lexers.text', 'VimL', ('vim',), ('*.vim', '.vimrc', '.exrc', '.gvimrc', '_vimrc', '_exrc', '_gvimrc', 'vimrc', 'gvimrc'), ('text/x-vim',)), 'XQueryLexer': ('pygments.lexers.web', 'XQuery', ('xquery', 'xqy', 'xq', 'xql', 'xqm'), ('*.xqy', '*.xquery', '*.xq', '*.xql', '*.xqm'), ('text/xquery', 'application/xquery')), 'XmlDjangoLexer': ('pygments.lexers.templates', 'XML+Django/Jinja', ('xml+django', 'xml+jinja'), (), ('application/xml+django', 'application/xml+jinja')), 'XmlErbLexer': ('pygments.lexers.templates', 'XML+Ruby', ('xml+erb', 'xml+ruby'), (), ('application/xml+ruby',)), 'XmlLexer': ('pygments.lexers.web', 'XML', ('xml',), ('*.xml', '*.xsl', '*.rss', '*.xslt', '*.xsd', '*.wsdl'), ('text/xml', 'application/xml', 'image/svg+xml', 'application/rss+xml', 'application/atom+xml')), 'XmlPhpLexer': ('pygments.lexers.templates', 'XML+PHP', ('xml+php',), (), ('application/xml+php',)), 'XmlSmartyLexer': ('pygments.lexers.templates', 'XML+Smarty', ('xml+smarty',), (), ('application/xml+smarty',)), 'XsltLexer': ('pygments.lexers.web', 'XSLT', ('xslt',), ('*.xsl', '*.xslt', '*.xpl'), ('application/xsl+xml', 'application/xslt+xml')), 'XtendLexer': ('pygments.lexers.jvm', 'Xtend', ('xtend',), ('*.xtend',), ('text/x-xtend',)), 'YamlLexer': ('pygments.lexers.text', 'YAML', ('yaml',), ('*.yaml', '*.yml'), ('text/x-yaml',)), } if __name__ == '__main__': import sys import os # lookup lexers found_lexers = [] sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..')) for filename in os.listdir('.'): if filename.endswith('.py') and not filename.startswith('_'): module_name = 'pygments.lexers.%s' % filename[:-3] print module_name module = __import__(module_name, None, None, ['']) for lexer_name in module.__all__: lexer = getattr(module, lexer_name) found_lexers.append( '%r: %r' % (lexer_name, (module_name, lexer.name, tuple(lexer.aliases), tuple(lexer.filenames), tuple(lexer.mimetypes)))) # sort them, that should make the diff files for svn smaller found_lexers.sort() # extract useful sourcecode from this file f = open(__file__) try: content = f.read() finally: f.close() header = content[:content.find('LEXERS = {')] footer = content[content.find("if __name__ == '__main__':"):] # write new file f = open(__file__, 'wb') f.write(header) f.write('LEXERS = {\n %s,\n}\n\n' % ',\n '.join(found_lexers)) f.write(footer) f.close()
gpl-2.0
doomsterinc/odoo
openerp/addons/base/module/wizard/base_language_install.py
447
2738
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # 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 openerp import tools from openerp.osv import osv, fields from openerp.tools.translate import _ class base_language_install(osv.osv_memory): """ Install Language""" _name = "base.language.install" _description = "Install Language" _columns = { 'lang': fields.selection(tools.scan_languages(),'Language', required=True), 'overwrite': fields.boolean('Overwrite Existing Terms', help="If you check this box, your customized translations will be overwritten and replaced by the official ones."), 'state':fields.selection([('init','init'),('done','done')], 'Status', readonly=True), } _defaults = { 'state': 'init', 'overwrite': False } def lang_install(self, cr, uid, ids, context=None): if context is None: context = {} language_obj = self.browse(cr, uid, ids)[0] lang = language_obj.lang if lang: modobj = self.pool.get('ir.module.module') mids = modobj.search(cr, uid, [('state', '=', 'installed')]) if language_obj.overwrite: context = {'overwrite': True} modobj.update_translations(cr, uid, mids, lang, context or {}) self.write(cr, uid, ids, {'state': 'done'}, context=context) return { 'name': _('Language Pack'), 'view_type': 'form', 'view_mode': 'form', 'view_id': False, 'res_model': 'base.language.install', 'domain': [], 'context': dict(context, active_ids=ids), 'type': 'ir.actions.act_window', 'target': 'new', 'res_id': ids and ids[0] or False, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
fw1121/Roary
contrib/roary_plots/roary_plots.py
1
5754
#!/usr/bin/env python # Copyright (C) <2015> EMBL-European Bioinformatics Institute # This program is free software: you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation, either version 3 of # the License, or (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # Neither the institution name nor the name roary_plots # can be used to endorse or promote products derived from # this software without prior written permission. # For written permission, please contact <marco@ebi.ac.uk>. # Products derived from this software may not be called roary_plots # nor may roary_plots appear in their names without prior written # permission of the developers. You should have received a copy # of the GNU General Public License along with this program. # If not, see <http://www.gnu.org/licenses/>. __author__ = "Marco Galardini" __version__ = '0.1.0' def get_options(): import argparse # create the top-level parser description = "Create plots from roary outputs" parser = argparse.ArgumentParser(description = description, prog = 'roary_plots.py') parser.add_argument('tree', action='store', help='Newick Tree file', default='accessory_binary_genes.fa.newick') parser.add_argument('spreadsheet', action='store', help='Roary gene presence/absence spreadsheet', default='gene_presence_absence.csv') parser.add_argument('--version', action='version', version='%(prog)s '+__version__) return parser.parse_args() if __name__ == "__main__": options = get_options() import matplotlib.pyplot as plt import seaborn as sns sns.set_style('white') import os import pandas as pd import numpy as np from Bio import Phylo t = Phylo.read(options.tree, 'newick') # Max distance to create better plots mdist = max([t.distance(t.root, x) for x in t.get_terminals()]) # Load roary roary = pd.read_table(options.spreadsheet, sep=',', low_memory=False) # Set index (group name) roary.set_index('Gene', inplace=True) # Drop the other info columns roary.drop(list(roary.columns[:10]), axis=1, inplace=True) # Transform it in a presence/absence matrix (1/0) roary.replace('.{2,100}', 1, regex=True, inplace=True) roary.replace(np.nan, 0, regex=True, inplace=True) # Sort the matrix by the sum of strains presence idx = roary.sum(axis=1).order(ascending=False).index roary_sorted = roary.ix[idx] # Pangenome frequency plot plt.figure(figsize=(7, 5)) plt.hist(roary.sum(axis=1), roary.shape[1], histtype="stepfilled", alpha=.7) plt.xlabel('Number of genomes') plt.ylabel('Number of genes') sns.despine(left=True, bottom=True) plt.savefig('pangenome_frequency.png') plt.clf() # Sort the matrix according to tip labels in the tree roary_sorted = roary_sorted[[x.name for x in t.get_terminals()]] # Plot presence/absence matrix against the tree with sns.axes_style('whitegrid'): fig = plt.figure(figsize=(17, 10)) ax1=plt.subplot2grid((1,40), (0, 10), colspan=30) a=ax1.matshow(roary_sorted.T, cmap=plt.cm.Blues, vmin=0, vmax=1, aspect='auto', interpolation='none', ) ax1.set_yticks([]) ax1.set_xticks([]) ax1.axis('off') ax = fig.add_subplot(1,2,1) ax=plt.subplot2grid((1,40), (0, 0), colspan=10, axisbg='white') fig.subplots_adjust(wspace=0, hspace=0) ax1.set_title('Roary matrix\n(%d gene clusters)'%roary.shape[0]) Phylo.draw(t, axes=ax, show_confidence=False, label_func=lambda x: None, xticks=([],), yticks=([],), ylabel=('',), xlabel=('',), xlim=(-0.01,mdist+0.01), axis=('off',), title=('parSNP tree\n(%d strains)'%roary.shape[1],), do_show=False, ) plt.savefig('pangenome_matrix.png') plt.clf() # Plot the pangenome pie chart plt.figure(figsize=(10, 10)) core = roary[(roary.sum(axis=1) >= roary.shape[1]*0.99) & (roary.sum(axis=1) <= roary.shape[1] )].shape[0] softcore = roary[(roary.sum(axis=1) >= roary.shape[1]*0.95) & (roary.sum(axis=1) < roary.shape[1]*0.99)].shape[0] shell = roary[(roary.sum(axis=1) >= roary.shape[1]*0.15) & (roary.sum(axis=1) < roary.shape[1]*0.95)].shape[0] cloud = roary[roary.sum(axis=1) < roary.shape[1]*0.15].shape[0] total = roary.shape[0] def my_autopct(pct): val=int(round(pct*total/100.0)) return '{v:d}'.format(v=val) a=plt.pie([core, softcore, shell, cloud], labels=['core\n(%d <= strains <= %d)'%(roary.shape[1]*.99,roary.shape[1]), 'soft-core\n(%d <= strains < %d)'%(roary.shape[1]*.95,roary.shape[1]*.99), 'shell\n(%d <= strains < %d)'%(roary.shape[1]*.15,roary.shape[1]*.95), 'cloud\n(strains < %d)'%(roary.shape[1]*.15)], explode=[0.1, 0.05, 0.02, 0], radius=0.9, colors=[(0, 0, 1, float(x)/total) for x in (core, softcore, shell, cloud)], autopct=my_autopct) plt.savefig('pangenome_pie.png') plt.clf()
gpl-3.0
westinedu/newertrends
django/contrib/gis/tests/distapp/models.py
406
1832
from django.contrib.gis.db import models class SouthTexasCity(models.Model): "City model on projected coordinate system for South Texas." name = models.CharField(max_length=30) point = models.PointField(srid=32140) objects = models.GeoManager() def __unicode__(self): return self.name class SouthTexasCityFt(models.Model): "Same City model as above, but U.S. survey feet are the units." name = models.CharField(max_length=30) point = models.PointField(srid=2278) objects = models.GeoManager() def __unicode__(self): return self.name class AustraliaCity(models.Model): "City model for Australia, using WGS84." name = models.CharField(max_length=30) point = models.PointField() objects = models.GeoManager() def __unicode__(self): return self.name class CensusZipcode(models.Model): "Model for a few South Texas ZIP codes (in original Census NAD83)." name = models.CharField(max_length=5) poly = models.PolygonField(srid=4269) objects = models.GeoManager() def __unicode__(self): return self.name class SouthTexasZipcode(models.Model): "Model for a few South Texas ZIP codes." name = models.CharField(max_length=5) poly = models.PolygonField(srid=32140, null=True) objects = models.GeoManager() def __unicode__(self): return self.name class Interstate(models.Model): "Geodetic model for U.S. Interstates." name = models.CharField(max_length=10) path = models.LineStringField() objects = models.GeoManager() def __unicode__(self): return self.name class SouthTexasInterstate(models.Model): "Projected model for South Texas Interstates." name = models.CharField(max_length=10) path = models.LineStringField(srid=32140) objects = models.GeoManager() def __unicode__(self): return self.name
bsd-3-clause
noroutine/ansible
lib/ansible/modules/utilities/helper/_accelerate.py
29
2723
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2013, James Cammarata <jcammarata@ansible.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['deprecated'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: accelerate removed: True short_description: Enable accelerated mode on remote node deprecated: "Use SSH with ControlPersist instead." description: - This module has been removed, this file is kept for historicaly documentation purposes - This modules launches an ephemeral I(accelerate) daemon on the remote node which Ansible can use to communicate with nodes at high speed. - The daemon listens on a configurable port for a configurable amount of time. - Fireball mode is AES encrypted version_added: "1.3" options: port: description: - TCP port for the socket connection required: false default: 5099 aliases: [] timeout: description: - The number of seconds the socket will wait for data. If none is received when the timeout value is reached, the connection will be closed. required: false default: 300 aliases: [] minutes: description: - The I(accelerate) listener daemon is started on nodes and will stay around for this number of minutes before turning itself off. required: false default: 30 ipv6: description: - The listener daemon on the remote host will bind to the ipv6 localhost socket if this parameter is set to true. required: false default: false multi_key: description: - When enabled, the daemon will open a local socket file which can be used by future daemon executions to upload a new key to the already running daemon, so that multiple users can connect using different keys. This access still requires an ssh connection as the uid for which the daemon is currently running. required: false default: no version_added: "1.6" notes: - See the advanced playbooks chapter for more about using accelerated mode. requirements: - "python >= 2.4" - "python-keyczar" author: "James Cammarata (@jimi-c)" ''' EXAMPLES = ''' # To use accelerate mode, simply add "accelerate: true" to your play. The initial # key exchange and starting up of the daemon will occur over SSH, but all commands and # subsequent actions will be conducted over the raw socket connection using AES encryption - hosts: devservers accelerate: true tasks: - command: /usr/bin/anything '''
gpl-3.0
StefanRijnhart/OpenUpgrade
addons/hr_payroll_account/hr_payroll_account.py
41
10957
#-*- coding:utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved # d$ # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import time from datetime import date, datetime, timedelta from openerp.osv import fields, osv from openerp.tools import config, float_compare from openerp.tools.translate import _ class hr_payslip(osv.osv): ''' Pay Slip ''' _inherit = 'hr.payslip' _description = 'Pay Slip' _columns = { 'period_id': fields.many2one('account.period', 'Force Period',states={'draft': [('readonly', False)]}, readonly=True, domain=[('state','<>','done')], help="Keep empty to use the period of the validation(Payslip) date."), 'journal_id': fields.many2one('account.journal', 'Salary Journal',states={'draft': [('readonly', False)]}, readonly=True, required=True), 'move_id': fields.many2one('account.move', 'Accounting Entry', readonly=True), } def _get_default_journal(self, cr, uid, context=None): model_data = self.pool.get('ir.model.data') res = model_data.search(cr, uid, [('name', '=', 'expenses_journal')]) if res: return model_data.browse(cr, uid, res[0]).res_id return False _defaults = { 'journal_id': _get_default_journal, } def copy(self, cr, uid, id, default=None, context=None): if default is None: default = {} default['move_id'] = False return super(hr_payslip, self).copy(cr, uid, id, default, context=context) def create(self, cr, uid, vals, context=None): if context is None: context = {} if 'journal_id' in context: vals.update({'journal_id': context.get('journal_id')}) return super(hr_payslip, self).create(cr, uid, vals, context=context) def onchange_contract_id(self, cr, uid, ids, date_from, date_to, employee_id=False, contract_id=False, context=None): contract_obj = self.pool.get('hr.contract') res = super(hr_payslip, self).onchange_contract_id(cr, uid, ids, date_from=date_from, date_to=date_to, employee_id=employee_id, contract_id=contract_id, context=context) journal_id = contract_id and contract_obj.browse(cr, uid, contract_id, context=context).journal_id.id or False res['value'].update({'journal_id': journal_id}) return res def cancel_sheet(self, cr, uid, ids, context=None): move_pool = self.pool.get('account.move') move_ids = [] move_to_cancel = [] for slip in self.browse(cr, uid, ids, context=context): if slip.move_id: move_ids.append(slip.move_id.id) if slip.move_id.state == 'posted': move_to_cancel.append(slip.move_id.id) move_pool.button_cancel(cr, uid, move_to_cancel, context=context) move_pool.unlink(cr, uid, move_ids, context=context) return super(hr_payslip, self).cancel_sheet(cr, uid, ids, context=context) def process_sheet(self, cr, uid, ids, context=None): move_pool = self.pool.get('account.move') period_pool = self.pool.get('account.period') precision = self.pool.get('decimal.precision').precision_get(cr, uid, 'Payroll') timenow = time.strftime('%Y-%m-%d') for slip in self.browse(cr, uid, ids, context=context): line_ids = [] debit_sum = 0.0 credit_sum = 0.0 if not slip.period_id: search_periods = period_pool.find(cr, uid, slip.date_to, context=context) period_id = search_periods[0] else: period_id = slip.period_id.id default_partner_id = slip.employee_id.address_home_id.id name = _('Payslip of %s') % (slip.employee_id.name) move = { 'narration': name, 'date': timenow, 'ref': slip.number, 'journal_id': slip.journal_id.id, 'period_id': period_id, } for line in slip.details_by_salary_rule_category: amt = slip.credit_note and -line.total or line.total partner_id = line.salary_rule_id.register_id.partner_id and line.salary_rule_id.register_id.partner_id.id or default_partner_id debit_account_id = line.salary_rule_id.account_debit.id credit_account_id = line.salary_rule_id.account_credit.id if debit_account_id: debit_line = (0, 0, { 'name': line.name, 'date': timenow, 'partner_id': (line.salary_rule_id.register_id.partner_id or line.salary_rule_id.account_debit.type in ('receivable', 'payable')) and partner_id or False, 'account_id': debit_account_id, 'journal_id': slip.journal_id.id, 'period_id': period_id, 'debit': amt > 0.0 and amt or 0.0, 'credit': amt < 0.0 and -amt or 0.0, 'analytic_account_id': line.salary_rule_id.analytic_account_id and line.salary_rule_id.analytic_account_id.id or False, 'tax_code_id': line.salary_rule_id.account_tax_id and line.salary_rule_id.account_tax_id.id or False, 'tax_amount': line.salary_rule_id.account_tax_id and amt or 0.0, }) line_ids.append(debit_line) debit_sum += debit_line[2]['debit'] - debit_line[2]['credit'] if credit_account_id: credit_line = (0, 0, { 'name': line.name, 'date': timenow, 'partner_id': (line.salary_rule_id.register_id.partner_id or line.salary_rule_id.account_credit.type in ('receivable', 'payable')) and partner_id or False, 'account_id': credit_account_id, 'journal_id': slip.journal_id.id, 'period_id': period_id, 'debit': amt < 0.0 and -amt or 0.0, 'credit': amt > 0.0 and amt or 0.0, 'analytic_account_id': line.salary_rule_id.analytic_account_id and line.salary_rule_id.analytic_account_id.id or False, 'tax_code_id': line.salary_rule_id.account_tax_id and line.salary_rule_id.account_tax_id.id or False, 'tax_amount': line.salary_rule_id.account_tax_id and amt or 0.0, }) line_ids.append(credit_line) credit_sum += credit_line[2]['credit'] - credit_line[2]['debit'] if float_compare(credit_sum, debit_sum, precision_digits=precision) == -1: acc_id = slip.journal_id.default_credit_account_id.id if not acc_id: raise osv.except_osv(_('Configuration Error!'),_('The Expense Journal "%s" has not properly configured the Credit Account!')%(slip.journal_id.name)) adjust_credit = (0, 0, { 'name': _('Adjustment Entry'), 'date': timenow, 'partner_id': False, 'account_id': acc_id, 'journal_id': slip.journal_id.id, 'period_id': period_id, 'debit': 0.0, 'credit': debit_sum - credit_sum, }) line_ids.append(adjust_credit) elif float_compare(debit_sum, credit_sum, precision_digits=precision) == -1: acc_id = slip.journal_id.default_debit_account_id.id if not acc_id: raise osv.except_osv(_('Configuration Error!'),_('The Expense Journal "%s" has not properly configured the Debit Account!')%(slip.journal_id.name)) adjust_debit = (0, 0, { 'name': _('Adjustment Entry'), 'date': timenow, 'partner_id': False, 'account_id': acc_id, 'journal_id': slip.journal_id.id, 'period_id': period_id, 'debit': credit_sum - debit_sum, 'credit': 0.0, }) line_ids.append(adjust_debit) move.update({'line_id': line_ids}) move_id = move_pool.create(cr, uid, move, context=context) self.write(cr, uid, [slip.id], {'move_id': move_id, 'period_id' : period_id}, context=context) if slip.journal_id.entry_posted: move_pool.post(cr, uid, [move_id], context=context) return super(hr_payslip, self).process_sheet(cr, uid, [slip.id], context=context) class hr_salary_rule(osv.osv): _inherit = 'hr.salary.rule' _columns = { 'analytic_account_id':fields.many2one('account.analytic.account', 'Analytic Account'), 'account_tax_id':fields.many2one('account.tax.code', 'Tax Code'), 'account_debit': fields.many2one('account.account', 'Debit Account'), 'account_credit': fields.many2one('account.account', 'Credit Account'), } class hr_contract(osv.osv): _inherit = 'hr.contract' _description = 'Employee Contract' _columns = { 'analytic_account_id':fields.many2one('account.analytic.account', 'Analytic Account'), 'journal_id': fields.many2one('account.journal', 'Salary Journal'), } class hr_payslip_run(osv.osv): _inherit = 'hr.payslip.run' _description = 'Payslip Run' _columns = { 'journal_id': fields.many2one('account.journal', 'Salary Journal', states={'draft': [('readonly', False)]}, readonly=True, required=True), } def _get_default_journal(self, cr, uid, context=None): model_data = self.pool.get('ir.model.data') res = model_data.search(cr, uid, [('name', '=', 'expenses_journal')]) if res: return model_data.browse(cr, uid, res[0]).res_id return False _defaults = { 'journal_id': _get_default_journal, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
Laurawly/tvm-1
tutorials/dev/low_level_custom_pass.py
1
6886
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """ Writing a Customized Pass ========================= **Author**: `Jian Weng <https://were.github.io>`_ TVM is a framework that abstracts away the heterogenity of machine learning accelerators. Sometimes users may want customize some analysis and IR transformations to adapt TVM to their own specialized hardware. This tutorial helps users write a customized pass in TVM. Prerequisites ------------- Before reading this tutorial, we assume readers have already known these topics well: - Writing an algorithm in TVM and schedule it. Otherwise, see example tutorials like :ref:`opt-gemm`. - The basic structure of HalideIR. Otherwise, see ``HalideIR/src/ir/IR.h`` to learn what attributes of IR nodes are defined. - Visitor design pattern. Otherwise, check the `Python AST module <https://docs.python.org/3/library/ast.html>`_ to see how an AST visitor is implemented. - How a Schedule is lowered to either an IRModule class or a LLVM module. Otherwise, take a look at ``python/tvm/build_module.py`` to get some basics. """ import tvm from tvm import te import numpy as np ###################################################################### # We first write a very simple vector add and build it with the default schedule. Then, we use # our customized lowering pass to manipulate the IR directly instead of using schedule primitives. # n = tvm.tir.const(128, "int32") a = te.placeholder((n,), name="a") b = te.placeholder((n,), name="b") c = te.compute((n,), lambda i: a[i] + b[i], name="c") sch = te.create_schedule(c.op) ir = tvm.lower(sch, [a, b, c]) print(ir) ###################################################################### # Writing a Pass # -------------- # Essentially, an "IR transformation pass" is a function which maps a statement to a new statement. # Thus, we define this vectorize function and implement it step by step. # ###################################################################### # TVM already provides two class for users to both analyze and transform IR. # # IR Visitor # ~~~~~~~~~~ # We can use ``tvm.tir.stmt_functor.post_order_visit(stmt, func)`` to gather information from the Halide IR. # ``func`` is a function callback. This function will be called before exiting the current IR node, # i.e. post-order visit. Then we leverage side effects to store the result of IR visit, because the # return value of ``func`` will be ignored. # # .. note:: # # You MUST use some array to store the result of IR visit. Even the value is a single variable. # This is mainly due to the constraints in the Python-C runtime. The variable values will be # refreshed every recursion but the array values will be preserved. # loops = [] def find_width8(op): """ Find all the 'tir.For' nodes whose extent can be divided by 8. """ if isinstance(op, tvm.tir.For): if isinstance(op.extent, tvm.tir.IntImm): if op.extent.value % 8 == 0: loops.append(op) ##################################################################### # IR Transformation # ~~~~~~~~~~~~~~~~~ # The transformation interface is slightly different from the visitor interface. There is only a # post-order callback in the visitor, but transformation visitor supports both a pre-order and a # post-order callback. If you want to keep the origin IR node, just return None. If you want to # change the current node to some node, use TVM IR maker interface to build it and return # this value. # # .. note:: # # If the pre-order function is called and returns a value which is not None, the post-order # function will be skipped. # def vectorize8(op): """ Split can vectorize the loops found in `find_width8`. """ if op in loops: extent = op.extent.value name = op.loop_var.name lo, li = te.var(name + ".outer"), te.var(name + ".inner") body = tvm.tir.stmt_functor.substitute(op.body, {op.loop_var: lo * 8 + li}) body = tvm.tir.For(li, 0, 8, tvm.tir.ForKind.VECTORIZED, body) body = tvm.tir.For(lo, 0, extent // 8, tvm.tir.ForKind.SERIAL, body) return body return None @tvm.tir.transform.prim_func_pass(opt_level=0) def vectorize(f, mod, ctx): global loops tvm.tir.stmt_functor.post_order_visit(f.body, find_width8) if not loops: return sf # The last list arugment indicates what kinds of nodes will be transformed. # Thus, in this case only `For` nodes will call `vectorize8` return f.with_body(tvm.tir.stmt_functor.ir_transform(f.body, None, vectorize8, ["tir.For"])) ##################################################################### # Glue to Lowering # ---------------- # So far, we are done with writing this IR transformation pass. What we need to do next is to glue # this pass to TVM's lower pass. # # In this case, we inject the pass written above into the TVM standard lowering # pass by feeding **a list of tuple** as argument to ``tir.add_lower_pass``. "Tuple" indicates different # phases of lowering. In TVM, there are four phases of lowering and user-customized ones will be # called after each phase is done. # # .. note:: # Here are the essential transformations done by each phase: # - Phase 0 generates the raw IR and loop levels. # - Phase 1 flattens the array storage. # - Phase 2 transforms loops, like unroll, vectorization and thread-binding. # - Phase 3 does some cleanup work. # # Thus, a good place to put this transformation pass is just after Phase 1. # with tvm.transform.PassContext(config={"tir.add_lower_pass": [(1, vectorize)]}): print(tvm.lower(sch, [a, b, c])) ##################################################################### # Quick View # ---------- # This tutorial gives a quick view of writing a customized IR transformation pass: # - Use ``tvm.tir.stmt_functor.post_order_visit`` to gather information on each IR nodes. # - Use ``tvm.tir.stmt_functor.ir_transform`` to transform IR nodes. # - Wrap up two above to write an IR-transformation function. # - Use ``tvm.transform.PassContext`` to put this function to TVM lowering pass #
apache-2.0
Nefry/taurus
tests/modules/test_SeleniumExecutor.py
1
18757
from tests import setup_test_logging, BZTestCase, __dir__ from bzt.modules.selenium import SeleniumExecutor from tests.mocks import EngineEmul from bzt.utils import BetterDict import os import shutil import yaml import time setup_test_logging() class TestSeleniumJUnitRunner(BZTestCase): """ java:one/folder/project/list jar:one/folder/list python:one/folder/list """ def test_install_tools(self): """ check installation of selenium-server, junit :return: """ dummy_installation_path = os.path.abspath(__dir__() + "/../../build/tmp/selenium-taurus") base_link = "file://" + __dir__() + "/../data/" shutil.rmtree(os.path.dirname(dummy_installation_path), ignore_errors=True) selenium_server_link = SeleniumExecutor.SELENIUM_DOWNLOAD_LINK SeleniumExecutor.SELENIUM_DOWNLOAD_LINK = base_link + "selenium-server-standalone-2.46.0.jar" junit_link = SeleniumExecutor.JUNIT_DOWNLOAD_LINK SeleniumExecutor.JUNIT_DOWNLOAD_LINK = base_link + "junit-4.12.jar" self.assertFalse(os.path.exists(dummy_installation_path)) obj = SeleniumExecutor() obj.engine = EngineEmul() obj.settings.merge({"selenium-tools": { "junit": {"selenium-server": os.path.join(dummy_installation_path, "selenium-server.jar")}}}) obj.settings.merge({"selenium-tools": { "junit": {"path": os.path.join(dummy_installation_path, "tools", "junit", "junit.jar")}}}) obj.execution = BetterDict() obj.execution.merge({"scenario": {"script": os.path.abspath(__dir__() + "/../../tests/selenium/jar/")}}) obj.prepare() self.assertTrue(os.path.exists(os.path.join(dummy_installation_path, "selenium-server.jar"))) self.assertTrue(os.path.exists(os.path.join(dummy_installation_path, "tools", "junit", "junit.jar"))) SeleniumExecutor.SELENIUM_DOWNLOAD_LINK = selenium_server_link SeleniumExecutor.JUNIT_DOWNLOAD_LINK = junit_link def test_prepare_java_single(self): """ Check if script exists in working dir :return: """ obj = SeleniumExecutor() obj.engine = EngineEmul() obj.execution = BetterDict() obj.execution.merge( {"scenario": {"script": os.path.abspath(__dir__() + "/../../tests/selenium/java/TestBlazemeterFail.java")}}) obj.prepare() self.assertTrue(os.path.exists(os.path.join(obj.runner.working_dir, "TestBlazemeterFail.java"))) self.assertTrue(os.path.exists(os.path.join(obj.runner.working_dir, "TestBlazemeterFail.class"))) self.assertTrue(os.path.exists(os.path.join(obj.runner.working_dir, "compiled.jar"))) def test_prepare_java_folder(self): """ Check if scripts exist in working dir :return: """ obj = SeleniumExecutor() obj.engine = EngineEmul() obj.execution = BetterDict() obj.execution.merge({"scenario": {"script": os.path.abspath(__dir__() + "/../../tests/selenium/java/")}}) obj.prepare() prepared_files = os.listdir(obj.runner.working_dir) java_files = [file for file in prepared_files if file.endswith(".java")] class_files = [file for file in prepared_files if file.endswith(".class")] jars = [file for file in prepared_files if file.endswith(".jar")] self.assertEqual(len(java_files), 2) self.assertEqual(len(class_files), 2) self.assertEqual(len(jars), 1) def test_prepare_java_package(self): """ Check if scripts exist in working dir :return: """ obj = SeleniumExecutor() obj.engine = EngineEmul() obj.execution = BetterDict() obj.execution.merge( {"scenario": {"script": os.path.abspath(__dir__() + "/../../tests/selenium/java_package/")}}) obj.prepare() self.assertTrue(os.path.exists(os.path.join(obj.runner.working_dir, "compiled.jar"))) def test_selenium_startup_shutdown_java_package(self): """ Run tests from package :return: """ obj = SeleniumExecutor() obj.engine = EngineEmul() obj.engine.config.merge(yaml.load(open("tests/yaml/selenium_executor_java_package.yml").read())) obj.engine.config.merge({"provisioning": "local"}) obj.execution = obj.engine.config['execution'] obj.settings.merge(obj.engine.config.get("modules").get("selenium")) obj.prepare() obj.startup() while not obj.check(): time.sleep(1) obj.shutdown() self.assertTrue(os.path.exists(os.path.join(obj.runner.working_dir, "compiled.jar"))) def test_prepare_jar_single(self): """ Check if jar exists in working dir :return: """ obj = SeleniumExecutor() obj.engine = EngineEmul() obj.execution = BetterDict() obj.execution.merge( {"scenario": {"script": os.path.abspath(__dir__() + "/../../tests/selenium/jar/dummy.jar")}}) obj.prepare() self.assertTrue( os.path.exists(os.path.join(obj.runner.working_dir, "dummy.jar"))) def test_prepare_jar_folder(self): """ Check if jars exist in working dir :return: """ obj = SeleniumExecutor() obj.engine = EngineEmul() obj.execution = BetterDict() obj.execution.merge({"scenario": {"script": os.path.abspath(__dir__() + "/../../tests/selenium/jar/")}}) obj.prepare() java_scripts = os.listdir(obj.runner.working_dir) self.assertEqual(len(java_scripts), 2) def test_selenium_startup_shutdown_jar_single(self): """ runt tests from single jar :return: """ obj = SeleniumExecutor() obj.engine = EngineEmul() obj.engine.config.merge(yaml.load(open("tests/yaml/selenium_executor_jar.yml").read())) obj.engine.config.merge({"provisioning": "local"}) obj.execution = obj.engine.config['execution'] obj.execution.merge( {"scenario": {"script": os.path.abspath(__dir__() + "/../../tests/selenium/jar/dummy.jar")}}) obj.settings.merge(obj.engine.config.get("modules").get("selenium")) obj.prepare() obj.startup() while not obj.check(): time.sleep(1) obj.shutdown() prepared_files = os.listdir(obj.runner.working_dir) java_files = [file for file in prepared_files if file.endswith(".java")] class_files = [file for file in prepared_files if file.endswith(".class")] jars = [file for file in prepared_files if file.endswith(".jar")] self.assertEqual(len(java_files), 0) self.assertEqual(len(class_files), 0) self.assertEqual(len(jars), 1) self.assertTrue(os.path.exists(obj.runner.report_file)) def test_selenium_startup_shutdown_jar_folder(self): """ run tests from jars :return: """ obj = SeleniumExecutor() obj.engine = EngineEmul() obj.engine.config.merge(yaml.load(open("tests/yaml/selenium_executor_jar.yml").read())) obj.engine.config.merge({"provisioning": "local"}) obj.execution = obj.engine.config['execution'] obj.settings.merge(obj.engine.config.get("modules").get("selenium")) obj.prepare() obj.startup() while not obj.check(): time.sleep(1) obj.shutdown() prepared_files = os.listdir(obj.runner.working_dir) java_files = [file for file in prepared_files if file.endswith(".java")] class_files = [file for file in prepared_files if file.endswith(".class")] jars = [file for file in prepared_files if file.endswith(".jar")] self.assertEqual(len(java_files), 0) self.assertEqual(len(class_files), 0) self.assertEqual(len(jars), 2) self.assertTrue(os.path.exists(obj.runner.report_file)) def test_selenium_startup_shutdown_java_single(self): """ run tests from single .java file :return: """ obj = SeleniumExecutor() obj.engine = EngineEmul() obj.engine.config.merge(yaml.load(open("tests/yaml/selenium_executor_java.yml").read())) obj.engine.config.merge({"provisioning": "local"}) obj.execution = obj.engine.config['execution'] obj.execution.merge( {"scenario": {"script": os.path.abspath(__dir__() + "/../../tests/selenium/java/TestBlazemeterFail.java")}}) obj.settings.merge(obj.engine.config.get("modules").get("selenium")) obj.prepare() obj.startup() while not obj.check(): time.sleep(1) obj.shutdown() prepared_files = os.listdir(obj.runner.working_dir) java_files = [file for file in prepared_files if file.endswith(".java")] class_files = [file for file in prepared_files if file.endswith(".class")] jars = [file for file in prepared_files if file.endswith(".jar")] self.assertEqual(1, len(java_files)) self.assertEqual(1, len(class_files)) self.assertEqual(1, len(jars)) self.assertTrue(os.path.exists(os.path.join(obj.runner.working_dir, "compiled.jar"))) self.assertTrue(os.path.exists(obj.runner.report_file)) def test_selenium_startup_shutdown_java_folder(self): """ run tests from .java files :return: """ obj = SeleniumExecutor() obj.engine = EngineEmul() obj.engine.config.merge(yaml.load(open("tests/yaml/selenium_executor_java.yml").read())) obj.engine.config.merge({"provisioning": "local"}) obj.execution = obj.engine.config['execution'] obj.settings.merge(obj.engine.config.get("modules").get("selenium")) obj.prepare() obj.startup() while not obj.check(): time.sleep(1) obj.shutdown() prepared_files = os.listdir(obj.runner.working_dir) java_files = [file for file in prepared_files if file.endswith(".java")] class_files = [file for file in prepared_files if file.endswith(".class")] jars = [file for file in prepared_files if file.endswith(".jar")] self.assertEqual(2, len(java_files)) self.assertEqual(2, len(class_files)) self.assertEqual(1, len(jars)) self.assertTrue(os.path.exists(os.path.join(obj.runner.working_dir, "compiled.jar"))) self.assertTrue(os.path.exists(obj.runner.report_file)) def test_not_junit(self): """ Check that JUnit runner fails if no tests were found :return: """ obj = SeleniumExecutor() obj.engine = EngineEmul() obj.engine.config = BetterDict() obj.engine.config.merge( {"execution": {"executor": "selenium", "scenario": {"script": "tests/selenium/invalid/NotJUnittest.java"}}}) obj.execution = obj.engine.config['execution'] obj.prepare() obj.startup() try: while not obj.check(): time.sleep(1) except BaseException as exc: self.assertEqual(exc.args[0], "Test runner JunitTester has failed: There is nothing to test.") obj.shutdown() class TestSeleniumNoseRunner(BZTestCase): def test_selenium_prepare_python_single(self): """ Check if script exists in working dir :return: """ obj = SeleniumExecutor() obj.engine = EngineEmul() obj.execution = BetterDict() obj.execution.merge({"scenario": { "script": os.path.abspath(__dir__() + "/../../tests/selenium/python/test_blazemeter_fail.py")}}) obj.prepare() python_scripts = os.listdir(obj.runner.working_dir) self.assertEqual(len(python_scripts), 1) def test_selenium_prepare_python_folder(self): """ Check if scripts exist in working dir :return: """ obj = SeleniumExecutor() obj.engine = EngineEmul() obj.execution = BetterDict() obj.execution.merge({"scenario": {"script": os.path.abspath(__dir__() + "/../../tests/selenium/python/")}}) obj.prepare() python_scripts = os.listdir(obj.runner.working_dir) self.assertEqual(len(python_scripts), 2) def test_selenium_startup_shutdown_python_single(self): """ run tests from .py file :return: """ obj = SeleniumExecutor() obj.engine = EngineEmul() obj.engine.config = BetterDict() obj.engine.config.merge(yaml.load(open("tests/yaml/selenium_executor_python.yml").read())) obj.engine.config.merge({"provisioning": "local"}) obj.execution = obj.engine.config['execution'] obj.execution.merge({"scenario": { "script": os.path.abspath(__dir__() + "/../../tests/selenium/python/test_blazemeter_fail.py")}}) obj.settings.merge(obj.engine.config.get("modules").get("selenium")) obj.prepare() obj.startup() while not obj.check(): time.sleep(1) obj.shutdown() prepared_files = os.listdir(obj.runner.working_dir) python_files = [file for file in prepared_files if file.endswith(".py")] self.assertEqual(1, len(python_files)) self.assertTrue(os.path.exists(obj.runner.report_file)) def test_selenium_startup_shutdown_python_folder(self): """ run tests from .py files :return: """ obj = SeleniumExecutor() obj.engine = EngineEmul() obj.engine.config = BetterDict() obj.engine.config.merge(yaml.load(open("tests/yaml/selenium_executor_python.yml").read())) obj.engine.config.merge({"provisioning": "local"}) obj.execution = obj.engine.config['execution'] obj.settings.merge(obj.engine.config.get("modules").get("selenium")) obj.prepare() obj.startup() while not obj.check(): time.sleep(1) obj.shutdown() prepared_files = os.listdir(obj.runner.working_dir) python_files = [file for file in prepared_files if file.endswith(".py")] self.assertEqual(2, len(python_files)) self.assertTrue(os.path.exists(obj.runner.report_file)) def runner_fail_no_test_found(self): """ Check that Python Nose runner fails if no tests were found :return: """ obj = SeleniumExecutor() obj.engine = EngineEmul() obj.engine.config = BetterDict() obj.engine.config.merge( {"execution": {"executor": "selenium", "scenario": {"script": "tests/selenium/invalid/dummy.py"}}}) obj.execution = obj.engine.config['execution'] obj.prepare() obj.startup() try: while not obj.check(): time.sleep(1) except BaseException as exc: self.assertEqual(exc.args[0], "Test runner NoseTester has failed: Nothing to test.") obj.shutdown() class TestSeleniumStuff(BZTestCase): def test_empty_scenario(self): """ Raise runtime error when no scenario provided :return: """ obj = SeleniumExecutor() obj.engine = EngineEmul() obj.engine.config = BetterDict() obj.engine.config.merge({"execution": {"executor": "selenium"}}) obj.execution = obj.engine.config['execution'] self.assertRaises(RuntimeError, obj.prepare) def test_javac_fail(self): """ Test RuntimeError when compilation fails :return: """ obj = SeleniumExecutor() obj.engine = EngineEmul() obj.engine.config = BetterDict() obj.engine.config.merge( {"execution": {"executor": "selenium", "scenario": {"script": "tests/selenium/invalid/invalid.java"}}}) obj.execution = obj.engine.config['execution'] self.assertRaises(RuntimeError, obj.prepare) def test_no_supported_files_to_test(self): """ Test RuntimeError raised when no files of known types were found. :return: """ obj = SeleniumExecutor() obj.engine = EngineEmul() obj.engine.config = BetterDict() obj.engine.config.merge( {"execution": {"executor": "selenium", "scenario": {"script": "tests/selenium/invalid/not_found"}}}) obj.execution = obj.engine.config['execution'] self.assertRaises(RuntimeError, obj.prepare) def test_samples_count_annotations(self): """ Test exact number of tests when java annotations used :return: """ obj = SeleniumExecutor() obj.engine = EngineEmul() obj.engine.config = BetterDict() obj.engine.config.merge( {"execution": {"executor": "selenium", "scenario": {"script": "tests/selenium/invalid/SeleniumTest.java"}}}) obj.execution = obj.engine.config['execution'] obj.prepare() obj.startup() while not obj.check(): time.sleep(1) obj.shutdown() with open(obj.kpi_file) as kpi_fds: contents = kpi_fds.read() self.assertEqual(contents.count("--TIME:"), 2) def test_samples_count_testcase(self): """ Test exact number of tests when test class extends JUnit TestCase :return: """ obj = SeleniumExecutor() obj.engine = EngineEmul() obj.engine.config = BetterDict() obj.engine.config.merge( {"execution": {"executor": "selenium", "scenario": {"script": "tests/selenium/invalid/SimpleTest.java"}}}) obj.execution = obj.engine.config['execution'] obj.prepare() obj.startup() while not obj.check(): time.sleep(1) obj.shutdown() with open(obj.kpi_file) as kpi_fds: contents = kpi_fds.read() self.assertEqual(contents.count("--TIME:"), 2) def test_no_test_in_name(self): """ Test exact number of tests when annotations used and no "test" in class name :return: """ obj = SeleniumExecutor() obj.engine = EngineEmul() obj.engine.config = BetterDict() obj.engine.config.merge( {"execution": {"executor": "selenium", "scenario": {"script": "tests/selenium/invalid/selenium1.java"}}}) obj.execution = obj.engine.config['execution'] obj.prepare() obj.startup() while not obj.check(): time.sleep(1) obj.shutdown() with open(obj.kpi_file) as kpi_fds: contents = kpi_fds.read() self.assertEqual(contents.count("--TIME:"), 2)
apache-2.0
theolind/home-assistant
homeassistant/components/sensor/zwave.py
16
3735
""" homeassistant.components.sensor.zwave ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Interfaces with Z-Wave sensors. """ # pylint: disable=import-error from openzwave.network import ZWaveNetwork from pydispatch import dispatcher import homeassistant.components.zwave as zwave from homeassistant.helpers.entity import Entity from homeassistant.const import ( ATTR_BATTERY_LEVEL, STATE_ON, STATE_OFF, TEMP_CELCIUS, TEMP_FAHRENHEIT, ATTR_LOCATION) def setup_platform(hass, config, add_devices, discovery_info=None): """ Sets up Z-Wave sensors. """ node = zwave.NETWORK.nodes[discovery_info[zwave.ATTR_NODE_ID]] value = node.values[discovery_info[zwave.ATTR_VALUE_ID]] value.set_change_verified(False) # if 1 in groups and (zwave.NETWORK.controller.node_id not in # groups[1].associations): # node.groups[1].add_association(zwave.NETWORK.controller.node_id) if value.command_class == zwave.COMMAND_CLASS_SENSOR_BINARY: add_devices([ZWaveBinarySensor(value)]) elif value.command_class == zwave.COMMAND_CLASS_SENSOR_MULTILEVEL: add_devices([ZWaveMultilevelSensor(value)]) class ZWaveSensor(Entity): """ Represents a Z-Wave sensor. """ def __init__(self, sensor_value): self._value = sensor_value self._node = sensor_value.node dispatcher.connect( self._value_changed, ZWaveNetwork.SIGNAL_VALUE_CHANGED) @property def should_poll(self): """ False because we will push our own state to HA when changed. """ return False @property def unique_id(self): """ Returns a unique id. """ return "ZWAVE-{}-{}".format(self._node.node_id, self._value.object_id) @property def name(self): """ Returns the name of the device. """ name = self._node.name or "{} {}".format( self._node.manufacturer_name, self._node.product_name) return "{} {}".format(name, self._value.label) @property def state(self): """ Returns the state of the sensor. """ return self._value.data @property def state_attributes(self): """ Returns the state attributes. """ attrs = { zwave.ATTR_NODE_ID: self._node.node_id, } battery_level = self._node.get_battery_level() if battery_level is not None: attrs[ATTR_BATTERY_LEVEL] = battery_level location = self._node.location if location: attrs[ATTR_LOCATION] = location return attrs @property def unit_of_measurement(self): return self._value.units def _value_changed(self, value): """ Called when a value has changed on the network. """ if self._value.value_id == value.value_id: self.update_ha_state() # pylint: disable=too-few-public-methods class ZWaveBinarySensor(ZWaveSensor): """ Represents a binary sensor within Z-Wave. """ @property def state(self): """ Returns the state of the sensor. """ return STATE_ON if self._value.data else STATE_OFF class ZWaveMultilevelSensor(ZWaveSensor): """ Represents a multi level sensor Z-Wave sensor. """ @property def state(self): """ Returns the state of the sensor. """ value = self._value.data if self._value.units in ('C', 'F'): return round(value, 1) elif isinstance(value, float): return round(value, 2) return value @property def unit_of_measurement(self): unit = self._value.units if unit == 'C': return TEMP_CELCIUS elif unit == 'F': return TEMP_FAHRENHEIT else: return unit
mit
Communities-Communications/cc-odoo
addons/account/wizard/account_report_print_journal.py
378
3440
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # 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 openerp.osv import fields, osv from lxml import etree class account_print_journal(osv.osv_memory): _inherit = "account.common.journal.report" _name = 'account.print.journal' _description = 'Account Print Journal' _columns = { 'sort_selection': fields.selection([('l.date', 'Date'), ('am.name', 'Journal Entry Number'),], 'Entries Sorted by', required=True), 'journal_ids': fields.many2many('account.journal', 'account_print_journal_journal_rel', 'account_id', 'journal_id', 'Journals', required=True), } _defaults = { 'sort_selection': 'am.name', 'filter': 'filter_period', 'journal_ids': False, } def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False): ''' used to set the domain on 'journal_ids' field: we exclude or only propose the journals of type sale/purchase (+refund) accordingly to the presence of the key 'sale_purchase_only' in the context. ''' if context is None: context = {} res = super(account_print_journal, self).fields_view_get(cr, uid, view_id=view_id, view_type=view_type, context=context, toolbar=toolbar, submenu=submenu) doc = etree.XML(res['arch']) if context.get('sale_purchase_only'): domain ="[('type', 'in', ('sale','purchase','sale_refund','purchase_refund'))]" else: domain ="[('type', 'not in', ('sale','purchase','sale_refund','purchase_refund'))]" nodes = doc.xpath("//field[@name='journal_ids']") for node in nodes: node.set('domain', domain) res['arch'] = etree.tostring(doc) return res def _print_report(self, cr, uid, ids, data, context=None): if context is None: context = {} data = self.pre_print_report(cr, uid, ids, data, context=context) data['form'].update(self.read(cr, uid, ids, ['sort_selection'], context=context)[0]) if context.get('sale_purchase_only'): return self.pool['report'].get_action(cr, uid, [], 'account.report_salepurchasejournal', data=data, context=context) else: return self.pool['report'].get_action(cr, uid, [], 'account.report_journal', data=data, context=context) # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
stuntman723/rap-analyzer
rap_analyzer/lib/python2.7/site-packages/pip/_vendor/html5lib/inputstream.py
435
31665
from __future__ import absolute_import, division, unicode_literals from pip._vendor.six import text_type from pip._vendor.six.moves import http_client import codecs import re from .constants import EOF, spaceCharacters, asciiLetters, asciiUppercase from .constants import encodings, ReparseException from . import utils from io import StringIO try: from io import BytesIO except ImportError: BytesIO = StringIO try: from io import BufferedIOBase except ImportError: class BufferedIOBase(object): pass # Non-unicode versions of constants for use in the pre-parser spaceCharactersBytes = frozenset([item.encode("ascii") for item in spaceCharacters]) asciiLettersBytes = frozenset([item.encode("ascii") for item in asciiLetters]) asciiUppercaseBytes = frozenset([item.encode("ascii") for item in asciiUppercase]) spacesAngleBrackets = spaceCharactersBytes | frozenset([b">", b"<"]) invalid_unicode_no_surrogate = "[\u0001-\u0008\u000B\u000E-\u001F\u007F-\u009F\uFDD0-\uFDEF\uFFFE\uFFFF\U0001FFFE\U0001FFFF\U0002FFFE\U0002FFFF\U0003FFFE\U0003FFFF\U0004FFFE\U0004FFFF\U0005FFFE\U0005FFFF\U0006FFFE\U0006FFFF\U0007FFFE\U0007FFFF\U0008FFFE\U0008FFFF\U0009FFFE\U0009FFFF\U000AFFFE\U000AFFFF\U000BFFFE\U000BFFFF\U000CFFFE\U000CFFFF\U000DFFFE\U000DFFFF\U000EFFFE\U000EFFFF\U000FFFFE\U000FFFFF\U0010FFFE\U0010FFFF]" if utils.supports_lone_surrogates: # Use one extra step of indirection and create surrogates with # unichr. Not using this indirection would introduce an illegal # unicode literal on platforms not supporting such lone # surrogates. invalid_unicode_re = re.compile(invalid_unicode_no_surrogate + eval('"\\uD800-\\uDFFF"')) else: invalid_unicode_re = re.compile(invalid_unicode_no_surrogate) non_bmp_invalid_codepoints = set([0x1FFFE, 0x1FFFF, 0x2FFFE, 0x2FFFF, 0x3FFFE, 0x3FFFF, 0x4FFFE, 0x4FFFF, 0x5FFFE, 0x5FFFF, 0x6FFFE, 0x6FFFF, 0x7FFFE, 0x7FFFF, 0x8FFFE, 0x8FFFF, 0x9FFFE, 0x9FFFF, 0xAFFFE, 0xAFFFF, 0xBFFFE, 0xBFFFF, 0xCFFFE, 0xCFFFF, 0xDFFFE, 0xDFFFF, 0xEFFFE, 0xEFFFF, 0xFFFFE, 0xFFFFF, 0x10FFFE, 0x10FFFF]) ascii_punctuation_re = re.compile("[\u0009-\u000D\u0020-\u002F\u003A-\u0040\u005B-\u0060\u007B-\u007E]") # Cache for charsUntil() charsUntilRegEx = {} class BufferedStream(object): """Buffering for streams that do not have buffering of their own The buffer is implemented as a list of chunks on the assumption that joining many strings will be slow since it is O(n**2) """ def __init__(self, stream): self.stream = stream self.buffer = [] self.position = [-1, 0] # chunk number, offset def tell(self): pos = 0 for chunk in self.buffer[:self.position[0]]: pos += len(chunk) pos += self.position[1] return pos def seek(self, pos): assert pos <= self._bufferedBytes() offset = pos i = 0 while len(self.buffer[i]) < offset: offset -= len(self.buffer[i]) i += 1 self.position = [i, offset] def read(self, bytes): if not self.buffer: return self._readStream(bytes) elif (self.position[0] == len(self.buffer) and self.position[1] == len(self.buffer[-1])): return self._readStream(bytes) else: return self._readFromBuffer(bytes) def _bufferedBytes(self): return sum([len(item) for item in self.buffer]) def _readStream(self, bytes): data = self.stream.read(bytes) self.buffer.append(data) self.position[0] += 1 self.position[1] = len(data) return data def _readFromBuffer(self, bytes): remainingBytes = bytes rv = [] bufferIndex = self.position[0] bufferOffset = self.position[1] while bufferIndex < len(self.buffer) and remainingBytes != 0: assert remainingBytes > 0 bufferedData = self.buffer[bufferIndex] if remainingBytes <= len(bufferedData) - bufferOffset: bytesToRead = remainingBytes self.position = [bufferIndex, bufferOffset + bytesToRead] else: bytesToRead = len(bufferedData) - bufferOffset self.position = [bufferIndex, len(bufferedData)] bufferIndex += 1 rv.append(bufferedData[bufferOffset:bufferOffset + bytesToRead]) remainingBytes -= bytesToRead bufferOffset = 0 if remainingBytes: rv.append(self._readStream(remainingBytes)) return b"".join(rv) def HTMLInputStream(source, encoding=None, parseMeta=True, chardet=True): if isinstance(source, http_client.HTTPResponse): # Work around Python bug #20007: read(0) closes the connection. # http://bugs.python.org/issue20007 isUnicode = False elif hasattr(source, "read"): isUnicode = isinstance(source.read(0), text_type) else: isUnicode = isinstance(source, text_type) if isUnicode: if encoding is not None: raise TypeError("Cannot explicitly set an encoding with a unicode string") return HTMLUnicodeInputStream(source) else: return HTMLBinaryInputStream(source, encoding, parseMeta, chardet) class HTMLUnicodeInputStream(object): """Provides a unicode stream of characters to the HTMLTokenizer. This class takes care of character encoding and removing or replacing incorrect byte-sequences and also provides column and line tracking. """ _defaultChunkSize = 10240 def __init__(self, source): """Initialises the HTMLInputStream. HTMLInputStream(source, [encoding]) -> Normalized stream from source for use by html5lib. source can be either a file-object, local filename or a string. The optional encoding parameter must be a string that indicates the encoding. If specified, that encoding will be used, regardless of any BOM or later declaration (such as in a meta element) parseMeta - Look for a <meta> element containing encoding information """ if not utils.supports_lone_surrogates: # Such platforms will have already checked for such # surrogate errors, so no need to do this checking. self.reportCharacterErrors = None self.replaceCharactersRegexp = None elif len("\U0010FFFF") == 1: self.reportCharacterErrors = self.characterErrorsUCS4 self.replaceCharactersRegexp = re.compile(eval('"[\\uD800-\\uDFFF]"')) else: self.reportCharacterErrors = self.characterErrorsUCS2 self.replaceCharactersRegexp = re.compile( eval('"([\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?<![\\uD800-\\uDBFF])[\\uDC00-\\uDFFF])"')) # List of where new lines occur self.newLines = [0] self.charEncoding = ("utf-8", "certain") self.dataStream = self.openStream(source) self.reset() def reset(self): self.chunk = "" self.chunkSize = 0 self.chunkOffset = 0 self.errors = [] # number of (complete) lines in previous chunks self.prevNumLines = 0 # number of columns in the last line of the previous chunk self.prevNumCols = 0 # Deal with CR LF and surrogates split over chunk boundaries self._bufferedCharacter = None def openStream(self, source): """Produces a file object from source. source can be either a file object, local filename or a string. """ # Already a file object if hasattr(source, 'read'): stream = source else: stream = StringIO(source) return stream def _position(self, offset): chunk = self.chunk nLines = chunk.count('\n', 0, offset) positionLine = self.prevNumLines + nLines lastLinePos = chunk.rfind('\n', 0, offset) if lastLinePos == -1: positionColumn = self.prevNumCols + offset else: positionColumn = offset - (lastLinePos + 1) return (positionLine, positionColumn) def position(self): """Returns (line, col) of the current position in the stream.""" line, col = self._position(self.chunkOffset) return (line + 1, col) def char(self): """ Read one character from the stream or queue if available. Return EOF when EOF is reached. """ # Read a new chunk from the input stream if necessary if self.chunkOffset >= self.chunkSize: if not self.readChunk(): return EOF chunkOffset = self.chunkOffset char = self.chunk[chunkOffset] self.chunkOffset = chunkOffset + 1 return char def readChunk(self, chunkSize=None): if chunkSize is None: chunkSize = self._defaultChunkSize self.prevNumLines, self.prevNumCols = self._position(self.chunkSize) self.chunk = "" self.chunkSize = 0 self.chunkOffset = 0 data = self.dataStream.read(chunkSize) # Deal with CR LF and surrogates broken across chunks if self._bufferedCharacter: data = self._bufferedCharacter + data self._bufferedCharacter = None elif not data: # We have no more data, bye-bye stream return False if len(data) > 1: lastv = ord(data[-1]) if lastv == 0x0D or 0xD800 <= lastv <= 0xDBFF: self._bufferedCharacter = data[-1] data = data[:-1] if self.reportCharacterErrors: self.reportCharacterErrors(data) # Replace invalid characters # Note U+0000 is dealt with in the tokenizer data = self.replaceCharactersRegexp.sub("\ufffd", data) data = data.replace("\r\n", "\n") data = data.replace("\r", "\n") self.chunk = data self.chunkSize = len(data) return True def characterErrorsUCS4(self, data): for i in range(len(invalid_unicode_re.findall(data))): self.errors.append("invalid-codepoint") def characterErrorsUCS2(self, data): # Someone picked the wrong compile option # You lose skip = False for match in invalid_unicode_re.finditer(data): if skip: continue codepoint = ord(match.group()) pos = match.start() # Pretty sure there should be endianness issues here if utils.isSurrogatePair(data[pos:pos + 2]): # We have a surrogate pair! char_val = utils.surrogatePairToCodepoint(data[pos:pos + 2]) if char_val in non_bmp_invalid_codepoints: self.errors.append("invalid-codepoint") skip = True elif (codepoint >= 0xD800 and codepoint <= 0xDFFF and pos == len(data) - 1): self.errors.append("invalid-codepoint") else: skip = False self.errors.append("invalid-codepoint") def charsUntil(self, characters, opposite=False): """ Returns a string of characters from the stream up to but not including any character in 'characters' or EOF. 'characters' must be a container that supports the 'in' method and iteration over its characters. """ # Use a cache of regexps to find the required characters try: chars = charsUntilRegEx[(characters, opposite)] except KeyError: if __debug__: for c in characters: assert(ord(c) < 128) regex = "".join(["\\x%02x" % ord(c) for c in characters]) if not opposite: regex = "^%s" % regex chars = charsUntilRegEx[(characters, opposite)] = re.compile("[%s]+" % regex) rv = [] while True: # Find the longest matching prefix m = chars.match(self.chunk, self.chunkOffset) if m is None: # If nothing matched, and it wasn't because we ran out of chunk, # then stop if self.chunkOffset != self.chunkSize: break else: end = m.end() # If not the whole chunk matched, return everything # up to the part that didn't match if end != self.chunkSize: rv.append(self.chunk[self.chunkOffset:end]) self.chunkOffset = end break # If the whole remainder of the chunk matched, # use it all and read the next chunk rv.append(self.chunk[self.chunkOffset:]) if not self.readChunk(): # Reached EOF break r = "".join(rv) return r def unget(self, char): # Only one character is allowed to be ungotten at once - it must # be consumed again before any further call to unget if char is not None: if self.chunkOffset == 0: # unget is called quite rarely, so it's a good idea to do # more work here if it saves a bit of work in the frequently # called char and charsUntil. # So, just prepend the ungotten character onto the current # chunk: self.chunk = char + self.chunk self.chunkSize += 1 else: self.chunkOffset -= 1 assert self.chunk[self.chunkOffset] == char class HTMLBinaryInputStream(HTMLUnicodeInputStream): """Provides a unicode stream of characters to the HTMLTokenizer. This class takes care of character encoding and removing or replacing incorrect byte-sequences and also provides column and line tracking. """ def __init__(self, source, encoding=None, parseMeta=True, chardet=True): """Initialises the HTMLInputStream. HTMLInputStream(source, [encoding]) -> Normalized stream from source for use by html5lib. source can be either a file-object, local filename or a string. The optional encoding parameter must be a string that indicates the encoding. If specified, that encoding will be used, regardless of any BOM or later declaration (such as in a meta element) parseMeta - Look for a <meta> element containing encoding information """ # Raw Stream - for unicode objects this will encode to utf-8 and set # self.charEncoding as appropriate self.rawStream = self.openStream(source) HTMLUnicodeInputStream.__init__(self, self.rawStream) self.charEncoding = (codecName(encoding), "certain") # Encoding Information # Number of bytes to use when looking for a meta element with # encoding information self.numBytesMeta = 512 # Number of bytes to use when using detecting encoding using chardet self.numBytesChardet = 100 # Encoding to use if no other information can be found self.defaultEncoding = "windows-1252" # Detect encoding iff no explicit "transport level" encoding is supplied if (self.charEncoding[0] is None): self.charEncoding = self.detectEncoding(parseMeta, chardet) # Call superclass self.reset() def reset(self): self.dataStream = codecs.getreader(self.charEncoding[0])(self.rawStream, 'replace') HTMLUnicodeInputStream.reset(self) def openStream(self, source): """Produces a file object from source. source can be either a file object, local filename or a string. """ # Already a file object if hasattr(source, 'read'): stream = source else: stream = BytesIO(source) try: stream.seek(stream.tell()) except: stream = BufferedStream(stream) return stream def detectEncoding(self, parseMeta=True, chardet=True): # First look for a BOM # This will also read past the BOM if present encoding = self.detectBOM() confidence = "certain" # If there is no BOM need to look for meta elements with encoding # information if encoding is None and parseMeta: encoding = self.detectEncodingMeta() confidence = "tentative" # Guess with chardet, if avaliable if encoding is None and chardet: confidence = "tentative" try: try: from charade.universaldetector import UniversalDetector except ImportError: from chardet.universaldetector import UniversalDetector buffers = [] detector = UniversalDetector() while not detector.done: buffer = self.rawStream.read(self.numBytesChardet) assert isinstance(buffer, bytes) if not buffer: break buffers.append(buffer) detector.feed(buffer) detector.close() encoding = detector.result['encoding'] self.rawStream.seek(0) except ImportError: pass # If all else fails use the default encoding if encoding is None: confidence = "tentative" encoding = self.defaultEncoding # Substitute for equivalent encodings: encodingSub = {"iso-8859-1": "windows-1252"} if encoding.lower() in encodingSub: encoding = encodingSub[encoding.lower()] return encoding, confidence def changeEncoding(self, newEncoding): assert self.charEncoding[1] != "certain" newEncoding = codecName(newEncoding) if newEncoding in ("utf-16", "utf-16-be", "utf-16-le"): newEncoding = "utf-8" if newEncoding is None: return elif newEncoding == self.charEncoding[0]: self.charEncoding = (self.charEncoding[0], "certain") else: self.rawStream.seek(0) self.reset() self.charEncoding = (newEncoding, "certain") raise ReparseException("Encoding changed from %s to %s" % (self.charEncoding[0], newEncoding)) def detectBOM(self): """Attempts to detect at BOM at the start of the stream. If an encoding can be determined from the BOM return the name of the encoding otherwise return None""" bomDict = { codecs.BOM_UTF8: 'utf-8', codecs.BOM_UTF16_LE: 'utf-16-le', codecs.BOM_UTF16_BE: 'utf-16-be', codecs.BOM_UTF32_LE: 'utf-32-le', codecs.BOM_UTF32_BE: 'utf-32-be' } # Go to beginning of file and read in 4 bytes string = self.rawStream.read(4) assert isinstance(string, bytes) # Try detecting the BOM using bytes from the string encoding = bomDict.get(string[:3]) # UTF-8 seek = 3 if not encoding: # Need to detect UTF-32 before UTF-16 encoding = bomDict.get(string) # UTF-32 seek = 4 if not encoding: encoding = bomDict.get(string[:2]) # UTF-16 seek = 2 # Set the read position past the BOM if one was found, otherwise # set it to the start of the stream self.rawStream.seek(encoding and seek or 0) return encoding def detectEncodingMeta(self): """Report the encoding declared by the meta element """ buffer = self.rawStream.read(self.numBytesMeta) assert isinstance(buffer, bytes) parser = EncodingParser(buffer) self.rawStream.seek(0) encoding = parser.getEncoding() if encoding in ("utf-16", "utf-16-be", "utf-16-le"): encoding = "utf-8" return encoding class EncodingBytes(bytes): """String-like object with an associated position and various extra methods If the position is ever greater than the string length then an exception is raised""" def __new__(self, value): assert isinstance(value, bytes) return bytes.__new__(self, value.lower()) def __init__(self, value): self._position = -1 def __iter__(self): return self def __next__(self): p = self._position = self._position + 1 if p >= len(self): raise StopIteration elif p < 0: raise TypeError return self[p:p + 1] def next(self): # Py2 compat return self.__next__() def previous(self): p = self._position if p >= len(self): raise StopIteration elif p < 0: raise TypeError self._position = p = p - 1 return self[p:p + 1] def setPosition(self, position): if self._position >= len(self): raise StopIteration self._position = position def getPosition(self): if self._position >= len(self): raise StopIteration if self._position >= 0: return self._position else: return None position = property(getPosition, setPosition) def getCurrentByte(self): return self[self.position:self.position + 1] currentByte = property(getCurrentByte) def skip(self, chars=spaceCharactersBytes): """Skip past a list of characters""" p = self.position # use property for the error-checking while p < len(self): c = self[p:p + 1] if c not in chars: self._position = p return c p += 1 self._position = p return None def skipUntil(self, chars): p = self.position while p < len(self): c = self[p:p + 1] if c in chars: self._position = p return c p += 1 self._position = p return None def matchBytes(self, bytes): """Look for a sequence of bytes at the start of a string. If the bytes are found return True and advance the position to the byte after the match. Otherwise return False and leave the position alone""" p = self.position data = self[p:p + len(bytes)] rv = data.startswith(bytes) if rv: self.position += len(bytes) return rv def jumpTo(self, bytes): """Look for the next sequence of bytes matching a given sequence. If a match is found advance the position to the last byte of the match""" newPosition = self[self.position:].find(bytes) if newPosition > -1: # XXX: This is ugly, but I can't see a nicer way to fix this. if self._position == -1: self._position = 0 self._position += (newPosition + len(bytes) - 1) return True else: raise StopIteration class EncodingParser(object): """Mini parser for detecting character encoding from meta elements""" def __init__(self, data): """string - the data to work on for encoding detection""" self.data = EncodingBytes(data) self.encoding = None def getEncoding(self): methodDispatch = ( (b"<!--", self.handleComment), (b"<meta", self.handleMeta), (b"</", self.handlePossibleEndTag), (b"<!", self.handleOther), (b"<?", self.handleOther), (b"<", self.handlePossibleStartTag)) for byte in self.data: keepParsing = True for key, method in methodDispatch: if self.data.matchBytes(key): try: keepParsing = method() break except StopIteration: keepParsing = False break if not keepParsing: break return self.encoding def handleComment(self): """Skip over comments""" return self.data.jumpTo(b"-->") def handleMeta(self): if self.data.currentByte not in spaceCharactersBytes: # if we have <meta not followed by a space so just keep going return True # We have a valid meta element we want to search for attributes hasPragma = False pendingEncoding = None while True: # Try to find the next attribute after the current position attr = self.getAttribute() if attr is None: return True else: if attr[0] == b"http-equiv": hasPragma = attr[1] == b"content-type" if hasPragma and pendingEncoding is not None: self.encoding = pendingEncoding return False elif attr[0] == b"charset": tentativeEncoding = attr[1] codec = codecName(tentativeEncoding) if codec is not None: self.encoding = codec return False elif attr[0] == b"content": contentParser = ContentAttrParser(EncodingBytes(attr[1])) tentativeEncoding = contentParser.parse() if tentativeEncoding is not None: codec = codecName(tentativeEncoding) if codec is not None: if hasPragma: self.encoding = codec return False else: pendingEncoding = codec def handlePossibleStartTag(self): return self.handlePossibleTag(False) def handlePossibleEndTag(self): next(self.data) return self.handlePossibleTag(True) def handlePossibleTag(self, endTag): data = self.data if data.currentByte not in asciiLettersBytes: # If the next byte is not an ascii letter either ignore this # fragment (possible start tag case) or treat it according to # handleOther if endTag: data.previous() self.handleOther() return True c = data.skipUntil(spacesAngleBrackets) if c == b"<": # return to the first step in the overall "two step" algorithm # reprocessing the < byte data.previous() else: # Read all attributes attr = self.getAttribute() while attr is not None: attr = self.getAttribute() return True def handleOther(self): return self.data.jumpTo(b">") def getAttribute(self): """Return a name,value pair for the next attribute in the stream, if one is found, or None""" data = self.data # Step 1 (skip chars) c = data.skip(spaceCharactersBytes | frozenset([b"/"])) assert c is None or len(c) == 1 # Step 2 if c in (b">", None): return None # Step 3 attrName = [] attrValue = [] # Step 4 attribute name while True: if c == b"=" and attrName: break elif c in spaceCharactersBytes: # Step 6! c = data.skip() break elif c in (b"/", b">"): return b"".join(attrName), b"" elif c in asciiUppercaseBytes: attrName.append(c.lower()) elif c is None: return None else: attrName.append(c) # Step 5 c = next(data) # Step 7 if c != b"=": data.previous() return b"".join(attrName), b"" # Step 8 next(data) # Step 9 c = data.skip() # Step 10 if c in (b"'", b'"'): # 10.1 quoteChar = c while True: # 10.2 c = next(data) # 10.3 if c == quoteChar: next(data) return b"".join(attrName), b"".join(attrValue) # 10.4 elif c in asciiUppercaseBytes: attrValue.append(c.lower()) # 10.5 else: attrValue.append(c) elif c == b">": return b"".join(attrName), b"" elif c in asciiUppercaseBytes: attrValue.append(c.lower()) elif c is None: return None else: attrValue.append(c) # Step 11 while True: c = next(data) if c in spacesAngleBrackets: return b"".join(attrName), b"".join(attrValue) elif c in asciiUppercaseBytes: attrValue.append(c.lower()) elif c is None: return None else: attrValue.append(c) class ContentAttrParser(object): def __init__(self, data): assert isinstance(data, bytes) self.data = data def parse(self): try: # Check if the attr name is charset # otherwise return self.data.jumpTo(b"charset") self.data.position += 1 self.data.skip() if not self.data.currentByte == b"=": # If there is no = sign keep looking for attrs return None self.data.position += 1 self.data.skip() # Look for an encoding between matching quote marks if self.data.currentByte in (b'"', b"'"): quoteMark = self.data.currentByte self.data.position += 1 oldPosition = self.data.position if self.data.jumpTo(quoteMark): return self.data[oldPosition:self.data.position] else: return None else: # Unquoted value oldPosition = self.data.position try: self.data.skipUntil(spaceCharactersBytes) return self.data[oldPosition:self.data.position] except StopIteration: # Return the whole remaining value return self.data[oldPosition:] except StopIteration: return None def codecName(encoding): """Return the python codec name corresponding to an encoding or None if the string doesn't correspond to a valid encoding.""" if isinstance(encoding, bytes): try: encoding = encoding.decode("ascii") except UnicodeDecodeError: return None if encoding: canonicalName = ascii_punctuation_re.sub("", encoding).lower() return encodings.get(canonicalName, None) else: return None
mit
dset0x/invenio
invenio/modules/accounts/upgrades/accounts_2015_03_06_namedefaults.py
3
1895
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2015 CERN. # # Invenio 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. # # Invenio 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 Invenio; if not, write to the Free Software Foundation, Inc., # 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. from sqlalchemy import * from sqlalchemy.dialects import mysql from invenio.ext.sqlalchemy import db from invenio.modules.upgrader.api import op depends_on = [u'accounts_2015_03_06_passlib', u'accounts_2015_01_14_add_name_columns'] def info(): return "Default value for family/given names." def do_upgrade(): """Implement your upgrades here.""" m = db.MetaData(bind=db.engine) m.reflect() u = m.tables['user'] conn = db.engine.connect() conn.execute(u.update().where(u.c.family_name == None).values( family_name='')) conn.execute(u.update().where(u.c.given_names == None).values( given_names='')) op.alter_column('user', 'family_name', existing_type=mysql.VARCHAR(length=255), nullable=False, server_default='') op.alter_column('user', 'given_names', existing_type=mysql.VARCHAR(length=255), nullable=False, server_default='') def estimate(): """Estimate running time of upgrade in seconds (optional).""" return 1
gpl-2.0
jacegem/lotto-store
lib/future/backports/email/utils.py
82
14270
# Copyright (C) 2001-2010 Python Software Foundation # Author: Barry Warsaw # Contact: email-sig@python.org """Miscellaneous utilities.""" from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import from future import utils from future.builtins import bytes, int, str __all__ = [ 'collapse_rfc2231_value', 'decode_params', 'decode_rfc2231', 'encode_rfc2231', 'formataddr', 'formatdate', 'format_datetime', 'getaddresses', 'make_msgid', 'mktime_tz', 'parseaddr', 'parsedate', 'parsedate_tz', 'parsedate_to_datetime', 'unquote', ] import os import re if utils.PY2: re.ASCII = 0 import time import base64 import random import socket from future.backports import datetime from future.backports.urllib.parse import quote as url_quote, unquote as url_unquote import warnings from io import StringIO from future.backports.email._parseaddr import quote from future.backports.email._parseaddr import AddressList as _AddressList from future.backports.email._parseaddr import mktime_tz from future.backports.email._parseaddr import parsedate, parsedate_tz, _parsedate_tz from quopri import decodestring as _qdecode # Intrapackage imports from future.backports.email.encoders import _bencode, _qencode from future.backports.email.charset import Charset COMMASPACE = ', ' EMPTYSTRING = '' UEMPTYSTRING = '' CRLF = '\r\n' TICK = "'" specialsre = re.compile(r'[][\\()<>@,:;".]') escapesre = re.compile(r'[\\"]') # How to figure out if we are processing strings that come from a byte # source with undecodable characters. _has_surrogates = re.compile( '([^\ud800-\udbff]|\A)[\udc00-\udfff]([^\udc00-\udfff]|\Z)').search # How to deal with a string containing bytes before handing it to the # application through the 'normal' interface. def _sanitize(string): # Turn any escaped bytes into unicode 'unknown' char. original_bytes = string.encode('ascii', 'surrogateescape') return original_bytes.decode('ascii', 'replace') # Helpers def formataddr(pair, charset='utf-8'): """The inverse of parseaddr(), this takes a 2-tuple of the form (realname, email_address) and returns the string value suitable for an RFC 2822 From, To or Cc header. If the first element of pair is false, then the second element is returned unmodified. Optional charset if given is the character set that is used to encode realname in case realname is not ASCII safe. Can be an instance of str or a Charset-like object which has a header_encode method. Default is 'utf-8'. """ name, address = pair # The address MUST (per RFC) be ascii, so raise an UnicodeError if it isn't. address.encode('ascii') if name: try: name.encode('ascii') except UnicodeEncodeError: if isinstance(charset, str): charset = Charset(charset) encoded_name = charset.header_encode(name) return "%s <%s>" % (encoded_name, address) else: quotes = '' if specialsre.search(name): quotes = '"' name = escapesre.sub(r'\\\g<0>', name) return '%s%s%s <%s>' % (quotes, name, quotes, address) return address def getaddresses(fieldvalues): """Return a list of (REALNAME, EMAIL) for each fieldvalue.""" all = COMMASPACE.join(fieldvalues) a = _AddressList(all) return a.addresslist ecre = re.compile(r''' =\? # literal =? (?P<charset>[^?]*?) # non-greedy up to the next ? is the charset \? # literal ? (?P<encoding>[qb]) # either a "q" or a "b", case insensitive \? # literal ? (?P<atom>.*?) # non-greedy up to the next ?= is the atom \?= # literal ?= ''', re.VERBOSE | re.IGNORECASE) def _format_timetuple_and_zone(timetuple, zone): return '%s, %02d %s %04d %02d:%02d:%02d %s' % ( ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'][timetuple[6]], timetuple[2], ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][timetuple[1] - 1], timetuple[0], timetuple[3], timetuple[4], timetuple[5], zone) def formatdate(timeval=None, localtime=False, usegmt=False): """Returns a date string as specified by RFC 2822, e.g.: Fri, 09 Nov 2001 01:08:47 -0000 Optional timeval if given is a floating point time value as accepted by gmtime() and localtime(), otherwise the current time is used. Optional localtime is a flag that when True, interprets timeval, and returns a date relative to the local timezone instead of UTC, properly taking daylight savings time into account. Optional argument usegmt means that the timezone is written out as an ascii string, not numeric one (so "GMT" instead of "+0000"). This is needed for HTTP, and is only used when localtime==False. """ # Note: we cannot use strftime() because that honors the locale and RFC # 2822 requires that day and month names be the English abbreviations. if timeval is None: timeval = time.time() if localtime: now = time.localtime(timeval) # Calculate timezone offset, based on whether the local zone has # daylight savings time, and whether DST is in effect. if time.daylight and now[-1]: offset = time.altzone else: offset = time.timezone hours, minutes = divmod(abs(offset), 3600) # Remember offset is in seconds west of UTC, but the timezone is in # minutes east of UTC, so the signs differ. if offset > 0: sign = '-' else: sign = '+' zone = '%s%02d%02d' % (sign, hours, minutes // 60) else: now = time.gmtime(timeval) # Timezone offset is always -0000 if usegmt: zone = 'GMT' else: zone = '-0000' return _format_timetuple_and_zone(now, zone) def format_datetime(dt, usegmt=False): """Turn a datetime into a date string as specified in RFC 2822. If usegmt is True, dt must be an aware datetime with an offset of zero. In this case 'GMT' will be rendered instead of the normal +0000 required by RFC2822. This is to support HTTP headers involving date stamps. """ now = dt.timetuple() if usegmt: if dt.tzinfo is None or dt.tzinfo != datetime.timezone.utc: raise ValueError("usegmt option requires a UTC datetime") zone = 'GMT' elif dt.tzinfo is None: zone = '-0000' else: zone = dt.strftime("%z") return _format_timetuple_and_zone(now, zone) def make_msgid(idstring=None, domain=None): """Returns a string suitable for RFC 2822 compliant Message-ID, e.g: <20020201195627.33539.96671@nightshade.la.mastaler.com> Optional idstring if given is a string used to strengthen the uniqueness of the message id. Optional domain if given provides the portion of the message id after the '@'. It defaults to the locally defined hostname. """ timeval = time.time() utcdate = time.strftime('%Y%m%d%H%M%S', time.gmtime(timeval)) pid = os.getpid() randint = random.randrange(100000) if idstring is None: idstring = '' else: idstring = '.' + idstring if domain is None: domain = socket.getfqdn() msgid = '<%s.%s.%s%s@%s>' % (utcdate, pid, randint, idstring, domain) return msgid def parsedate_to_datetime(data): _3to2list = list(_parsedate_tz(data)) dtuple, tz, = [_3to2list[:-1]] + _3to2list[-1:] if tz is None: return datetime.datetime(*dtuple[:6]) return datetime.datetime(*dtuple[:6], tzinfo=datetime.timezone(datetime.timedelta(seconds=tz))) def parseaddr(addr): addrs = _AddressList(addr).addresslist if not addrs: return '', '' return addrs[0] # rfc822.unquote() doesn't properly de-backslash-ify in Python pre-2.3. def unquote(str): """Remove quotes from a string.""" if len(str) > 1: if str.startswith('"') and str.endswith('"'): return str[1:-1].replace('\\\\', '\\').replace('\\"', '"') if str.startswith('<') and str.endswith('>'): return str[1:-1] return str # RFC2231-related functions - parameter encoding and decoding def decode_rfc2231(s): """Decode string according to RFC 2231""" parts = s.split(TICK, 2) if len(parts) <= 2: return None, None, s return parts def encode_rfc2231(s, charset=None, language=None): """Encode string according to RFC 2231. If neither charset nor language is given, then s is returned as-is. If charset is given but not language, the string is encoded using the empty string for language. """ s = url_quote(s, safe='', encoding=charset or 'ascii') if charset is None and language is None: return s if language is None: language = '' return "%s'%s'%s" % (charset, language, s) rfc2231_continuation = re.compile(r'^(?P<name>\w+)\*((?P<num>[0-9]+)\*?)?$', re.ASCII) def decode_params(params): """Decode parameters list according to RFC 2231. params is a sequence of 2-tuples containing (param name, string value). """ # Copy params so we don't mess with the original params = params[:] new_params = [] # Map parameter's name to a list of continuations. The values are a # 3-tuple of the continuation number, the string value, and a flag # specifying whether a particular segment is %-encoded. rfc2231_params = {} name, value = params.pop(0) new_params.append((name, value)) while params: name, value = params.pop(0) if name.endswith('*'): encoded = True else: encoded = False value = unquote(value) mo = rfc2231_continuation.match(name) if mo: name, num = mo.group('name', 'num') if num is not None: num = int(num) rfc2231_params.setdefault(name, []).append((num, value, encoded)) else: new_params.append((name, '"%s"' % quote(value))) if rfc2231_params: for name, continuations in rfc2231_params.items(): value = [] extended = False # Sort by number continuations.sort() # And now append all values in numerical order, converting # %-encodings for the encoded segments. If any of the # continuation names ends in a *, then the entire string, after # decoding segments and concatenating, must have the charset and # language specifiers at the beginning of the string. for num, s, encoded in continuations: if encoded: # Decode as "latin-1", so the characters in s directly # represent the percent-encoded octet values. # collapse_rfc2231_value treats this as an octet sequence. s = url_unquote(s, encoding="latin-1") extended = True value.append(s) value = quote(EMPTYSTRING.join(value)) if extended: charset, language, value = decode_rfc2231(value) new_params.append((name, (charset, language, '"%s"' % value))) else: new_params.append((name, '"%s"' % value)) return new_params def collapse_rfc2231_value(value, errors='replace', fallback_charset='us-ascii'): if not isinstance(value, tuple) or len(value) != 3: return unquote(value) # While value comes to us as a unicode string, we need it to be a bytes # object. We do not want bytes() normal utf-8 decoder, we want a straight # interpretation of the string as character bytes. charset, language, text = value rawbytes = bytes(text, 'raw-unicode-escape') try: return str(rawbytes, charset, errors) except LookupError: # charset is not a known codec. return unquote(text) # # datetime doesn't provide a localtime function yet, so provide one. Code # adapted from the patch in issue 9527. This may not be perfect, but it is # better than not having it. # def localtime(dt=None, isdst=-1): """Return local time as an aware datetime object. If called without arguments, return current time. Otherwise *dt* argument should be a datetime instance, and it is converted to the local time zone according to the system time zone database. If *dt* is naive (that is, dt.tzinfo is None), it is assumed to be in local time. In this case, a positive or zero value for *isdst* causes localtime to presume initially that summer time (for example, Daylight Saving Time) is or is not (respectively) in effect for the specified time. A negative value for *isdst* causes the localtime() function to attempt to divine whether summer time is in effect for the specified time. """ if dt is None: return datetime.datetime.now(datetime.timezone.utc).astimezone() if dt.tzinfo is not None: return dt.astimezone() # We have a naive datetime. Convert to a (localtime) timetuple and pass to # system mktime together with the isdst hint. System mktime will return # seconds since epoch. tm = dt.timetuple()[:-1] + (isdst,) seconds = time.mktime(tm) localtm = time.localtime(seconds) try: delta = datetime.timedelta(seconds=localtm.tm_gmtoff) tz = datetime.timezone(delta, localtm.tm_zone) except AttributeError: # Compute UTC offset and compare with the value implied by tm_isdst. # If the values match, use the zone name implied by tm_isdst. delta = dt - datetime.datetime(*time.gmtime(seconds)[:6]) dst = time.daylight and localtm.tm_isdst > 0 gmtoff = -(time.altzone if dst else time.timezone) if delta == datetime.timedelta(seconds=gmtoff): tz = datetime.timezone(delta, time.tzname[dst]) else: tz = datetime.timezone(delta) return dt.replace(tzinfo=tz)
apache-2.0
marlengit/BitcoinUnlimited
qa/rpc-tests/smartfees.py
1
12639
#!/usr/bin/env python3 # Copyright (c) 2014-2015 The Bitcoin Core developers # Copyright (c) 2015-2016 The Bitcoin Unlimited developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # # Test fee estimation code # from collections import OrderedDict from test_framework.test_framework import BitcoinTestFramework from test_framework.util import * # Construct 2 trivial P2SH's and the ScriptSigs that spend them # So we can create many many transactions without needing to spend # time signing. P2SH_1 = "2MySexEGVzZpRgNQ1JdjdP5bRETznm3roQ2" # P2SH of "OP_1 OP_DROP" P2SH_2 = "2NBdpwq8Aoo1EEKEXPNrKvr5xQr3M9UfcZA" # P2SH of "OP_2 OP_DROP" # Associated ScriptSig's to spend satisfy P2SH_1 and P2SH_2 # 4 bytes of OP_TRUE and push 2-byte redeem script of "OP_1 OP_DROP" or "OP_2 OP_DROP" SCRIPT_SIG = ["0451025175", "0451025275"] def small_txpuzzle_randfee(from_node, conflist, unconflist, amount, min_fee, fee_increment): ''' Create and send a transaction with a random fee. The transaction pays to a trivial P2SH script, and assumes that its inputs are of the same form. The function takes a list of confirmed outputs and unconfirmed outputs and attempts to use the confirmed list first for its inputs. It adds the newly created outputs to the unconfirmed list. Returns (raw transaction, fee) ''' # It's best to exponentially distribute our random fees # because the buckets are exponentially spaced. # Exponentially distributed from 1-128 * fee_increment rand_fee = float(fee_increment)*(1.1892**random.randint(0,28)) # Total fee ranges from min_fee to min_fee + 127*fee_increment fee = min_fee - fee_increment + satoshi_round(rand_fee) inputs = [] total_in = Decimal("0.00000000") while total_in <= (amount + fee) and len(conflist) > 0: t = conflist.pop(0) total_in += t["amount"] inputs.append({ "txid" : t["txid"], "vout" : t["vout"]} ) if total_in <= amount + fee: while total_in <= (amount + fee) and len(unconflist) > 0: t = unconflist.pop(0) total_in += t["amount"] inputs.append({ "txid" : t["txid"], "vout" : t["vout"]} ) if total_in <= amount + fee: raise RuntimeError("Insufficient funds: need %d, have %d"%(amount+fee, total_in)) outputs = {} outputs = OrderedDict([(P2SH_1, total_in - amount - fee), (P2SH_2, amount)]) rawtx = from_node.createrawtransaction(inputs, outputs) # createrawtransaction constructs a transaction that is ready to be signed. # These transactions don't need to be signed, but we still have to insert the ScriptSig # that will satisfy the ScriptPubKey. completetx = rawtx[0:10] inputnum = 0 for inp in inputs: completetx += rawtx[10+82*inputnum:82+82*inputnum] completetx += SCRIPT_SIG[inp["vout"]] completetx += rawtx[84+82*inputnum:92+82*inputnum] inputnum += 1 completetx += rawtx[10+82*inputnum:] txid = from_node.sendrawtransaction(completetx, True) unconflist.append({ "txid" : txid, "vout" : 0 , "amount" : total_in - amount - fee}) unconflist.append({ "txid" : txid, "vout" : 1 , "amount" : amount}) return (completetx, fee) def split_inputs(from_node, txins, txouts, initial_split = False): ''' We need to generate a lot of very small inputs so we can generate a ton of transactions and they will have low priority. This function takes an input from txins, and creates and sends a transaction which splits the value into 2 outputs which are appended to txouts. ''' prevtxout = txins.pop() inputs = [] inputs.append({ "txid" : prevtxout["txid"], "vout" : prevtxout["vout"] }) half_change = satoshi_round(prevtxout["amount"]/2) rem_change = prevtxout["amount"] - half_change - Decimal("0.00001000") outputs = OrderedDict([(P2SH_1, half_change), (P2SH_2, rem_change)]) rawtx = from_node.createrawtransaction(inputs, outputs) # If this is the initial split we actually need to sign the transaction # Otherwise we just need to insert the property ScriptSig if (initial_split) : completetx = from_node.signrawtransaction(rawtx)["hex"] else : completetx = rawtx[0:82] + SCRIPT_SIG[prevtxout["vout"]] + rawtx[84:] txid = from_node.sendrawtransaction(completetx, True) txouts.append({ "txid" : txid, "vout" : 0 , "amount" : half_change}) txouts.append({ "txid" : txid, "vout" : 1 , "amount" : rem_change}) def check_estimates(node, fees_seen, max_invalid, print_estimates = True): ''' This function calls estimatefee and verifies that the estimates meet certain invariants. ''' all_estimates = [ node.estimatefee(i) for i in range(1,26) ] if print_estimates: print([str(all_estimates[e-1]) for e in [1,2,3,6,15,25]]) delta = 1.0e-6 # account for rounding error last_e = max(fees_seen) for e in [x for x in all_estimates if x >= 0]: # Estimates should be within the bounds of what transactions fees actually were: if float(e)+delta < min(fees_seen) or float(e)-delta > max(fees_seen): raise AssertionError("Estimated fee (%f) out of range (%f,%f)" %(float(e), min(fees_seen), max(fees_seen))) # Estimates should be monotonically decreasing if float(e)-delta > last_e: raise AssertionError("Estimated fee (%f) larger than last fee (%f) for lower number of confirms" %(float(e),float(last_e))) last_e = e valid_estimate = False invalid_estimates = 0 for i,e in enumerate(all_estimates): # estimate is for i+1 if e >= 0: valid_estimate = True # estimatesmartfee should return the same result assert_equal(node.estimatesmartfee(i+1)["feerate"], e) else: invalid_estimates += 1 # estimatesmartfee should still be valid approx_estimate = node.estimatesmartfee(i+1)["feerate"] answer_found = node.estimatesmartfee(i+1)["blocks"] assert(approx_estimate > 0) assert(answer_found > i+1) # Once we're at a high enough confirmation count that we can give an estimate # We should have estimates for all higher confirmation counts if valid_estimate: raise AssertionError("Invalid estimate appears at higher confirm count than valid estimate") # Check on the expected number of different confirmation counts # that we might not have valid estimates for if invalid_estimates > max_invalid: raise AssertionError("More than (%d) invalid estimates"%(max_invalid)) return all_estimates class EstimateFeeTest(BitcoinTestFramework): def setup_network(self): ''' We'll setup the network to have 3 nodes that all mine with different parameters. But first we need to use one node to create a lot of small low priority outputs which we will use to generate our transactions. ''' self.nodes = [] # Use node0 to mine blocks for input splitting self.nodes.append(start_node(0, self.options.tmpdir, ["-maxorphantx=1000", "-relaypriority=0", "-whitelist=127.0.0.1"])) print("This test is time consuming, please be patient") print("Splitting inputs to small size so we can generate low priority tx's") self.txouts = [] self.txouts2 = [] # Split a coinbase into two transaction puzzle outputs split_inputs(self.nodes[0], self.nodes[0].listunspent(0), self.txouts, True) # Mine while (len(self.nodes[0].getrawmempool()) > 0): self.nodes[0].generate(1) # Repeatedly split those 2 outputs, doubling twice for each rep # Use txouts to monitor the available utxo, since these won't be tracked in wallet reps = 0 while (reps < 5): #Double txouts to txouts2 while (len(self.txouts)>0): split_inputs(self.nodes[0], self.txouts, self.txouts2) while (len(self.nodes[0].getrawmempool()) > 0): self.nodes[0].generate(1) #Double txouts2 to txouts while (len(self.txouts2)>0): split_inputs(self.nodes[0], self.txouts2, self.txouts) while (len(self.nodes[0].getrawmempool()) > 0): self.nodes[0].generate(1) reps += 1 print("Finished splitting") # Now we can connect the other nodes, didn't want to connect them earlier # so the estimates would not be affected by the splitting transactions # Node1 mines small blocks but that are bigger than the expected transaction rate, # and allows free transactions. # NOTE: the CreateNewBlock code starts counting block size at 1,000 bytes, # (17k is room enough for 110 or so transactions) self.nodes.append(start_node(1, self.options.tmpdir, ["-blockprioritysize=1500", "-blockmaxsize=17000", "-maxorphantx=1000", "-relaypriority=0", "-debug=estimatefee"])) connect_nodes(self.nodes[1], 0) # Node2 is a stingy miner, that # produces too small blocks (room for only 55 or so transactions) node2args = ["-blockprioritysize=0", "-blockmaxsize=8000", "-maxorphantx=1000", "-relaypriority=0"] self.nodes.append(start_node(2, self.options.tmpdir, node2args)) connect_nodes(self.nodes[0], 2) connect_nodes(self.nodes[2], 1) self.is_network_split = False self.sync_all() def transact_and_mine(self, numblocks, mining_node): min_fee = Decimal("0.00001") # We will now mine numblocks blocks generating on average 100 transactions between each block # We shuffle our confirmed txout set before each set of transactions # small_txpuzzle_randfee will use the transactions that have inputs already in the chain when possible # resorting to tx's that depend on the mempool when those run out for i in range(numblocks): random.shuffle(self.confutxo) for j in range(random.randrange(100-50,100+50)): from_index = random.randint(1,2) (txhex, fee) = small_txpuzzle_randfee(self.nodes[from_index], self.confutxo, self.memutxo, Decimal("0.005"), min_fee, min_fee) tx_kbytes = (len(txhex) // 2) / 1000.0 self.fees_per_kb.append(float(fee)/tx_kbytes) sync_mempools(self.nodes[0:3],.1) mined = mining_node.getblock(mining_node.generate(1)[0],True)["tx"] sync_blocks(self.nodes[0:3],.1) # update which txouts are confirmed newmem = [] for utx in self.memutxo: if utx["txid"] in mined: self.confutxo.append(utx) else: newmem.append(utx) self.memutxo = newmem def run_test(self): self.fees_per_kb = [] self.memutxo = [] self.confutxo = self.txouts # Start with the set of confirmed txouts after splitting print("Will output estimates for 1/2/3/6/15/25 blocks") for i in range(2): print("Creating transactions and mining them with a block size that can't keep up") # Create transactions and mine 10 small blocks with node 2, but create txs faster than we can mine self.transact_and_mine(10, self.nodes[2]) check_estimates(self.nodes[1], self.fees_per_kb, 14) print("Creating transactions and mining them at a block size that is just big enough") # Generate transactions while mining 10 more blocks, this time with node1 # which mines blocks with capacity just above the rate that transactions are being created self.transact_and_mine(10, self.nodes[1]) check_estimates(self.nodes[1], self.fees_per_kb, 2) # Finish by mining a normal-sized block: while len(self.nodes[1].getrawmempool()) > 0: self.nodes[1].generate(1) sync_blocks(self.nodes[0:3],.1) print("Final estimates after emptying mempools") check_estimates(self.nodes[1], self.fees_per_kb, 2) if __name__ == '__main__': EstimateFeeTest().main()
mit
theflofly/tensorflow
tensorflow/python/tools/print_selective_registration_header_test.py
24
7356
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for print_selective_registration_header.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import sys from google.protobuf import text_format from tensorflow.core.framework import graph_pb2 from tensorflow.python.framework import test_util from tensorflow.python.platform import gfile from tensorflow.python.platform import test from tensorflow.python.tools import selective_registration_header_lib # Note that this graph def is not valid to be loaded - its inputs are not # assigned correctly in all cases. GRAPH_DEF_TXT = """ node: { name: "node_1" op: "Reshape" input: [ "none", "none" ] device: "/cpu:0" attr: { key: "T" value: { type: DT_FLOAT } } } node: { name: "node_2" op: "MatMul" input: [ "none", "none" ] device: "/cpu:0" attr: { key: "T" value: { type: DT_FLOAT } } attr: { key: "transpose_a" value: { b: false } } attr: { key: "transpose_b" value: { b: false } } } node: { name: "node_3" op: "MatMul" input: [ "none", "none" ] device: "/cpu:0" attr: { key: "T" value: { type: DT_DOUBLE } } attr: { key: "transpose_a" value: { b: false } } attr: { key: "transpose_b" value: { b: false } } } """ # AccumulateNV2 is included because it should be included in the header despite # lacking a kernel (it's rewritten by AccumulateNV2RemovePass; see # core/common_runtime/accumulate_n_optimizer.cc. GRAPH_DEF_TXT_2 = """ node: { name: "node_4" op: "BiasAdd" input: [ "none", "none" ] device: "/cpu:0" attr: { key: "T" value: { type: DT_FLOAT } } } node: { name: "node_5" op: "AccumulateNV2" attr: { key: "T" value: { type: DT_INT32 } } attr: { key : "N" value: { i: 3 } } } """ class PrintOpFilegroupTest(test.TestCase): def setUp(self): _, self.script_name = os.path.split(sys.argv[0]) def WriteGraphFiles(self, graphs): fnames = [] for i, graph in enumerate(graphs): fname = os.path.join(self.get_temp_dir(), 'graph%s.pb' % i) with gfile.GFile(fname, 'wb') as f: f.write(graph.SerializeToString()) fnames.append(fname) return fnames def testGetOps(self): default_ops = 'NoOp:NoOp,_Recv:RecvOp,_Send:SendOp' graphs = [ text_format.Parse(d, graph_pb2.GraphDef()) for d in [GRAPH_DEF_TXT, GRAPH_DEF_TXT_2] ] ops_and_kernels = selective_registration_header_lib.get_ops_and_kernels( 'rawproto', self.WriteGraphFiles(graphs), default_ops) matmul_prefix = '' if test_util.IsMklEnabled(): matmul_prefix = 'Mkl' self.assertListEqual( [ ('AccumulateNV2', None), # ('BiasAdd', 'BiasOp<CPUDevice, float>'), # ('MatMul', matmul_prefix + 'MatMulOp<CPUDevice, double, false >'), # ('MatMul', matmul_prefix + 'MatMulOp<CPUDevice, float, false >'), # ('NoOp', 'NoOp'), # ('Reshape', 'ReshapeOp'), # ('_Recv', 'RecvOp'), # ('_Send', 'SendOp'), # ], ops_and_kernels) graphs[0].node[0].ClearField('device') graphs[0].node[2].ClearField('device') ops_and_kernels = selective_registration_header_lib.get_ops_and_kernels( 'rawproto', self.WriteGraphFiles(graphs), default_ops) self.assertListEqual( [ ('AccumulateNV2', None), # ('BiasAdd', 'BiasOp<CPUDevice, float>'), # ('MatMul', matmul_prefix + 'MatMulOp<CPUDevice, double, false >'), # ('MatMul', matmul_prefix + 'MatMulOp<CPUDevice, float, false >'), # ('NoOp', 'NoOp'), # ('Reshape', 'ReshapeOp'), # ('_Recv', 'RecvOp'), # ('_Send', 'SendOp'), # ], ops_and_kernels) def testAll(self): default_ops = 'all' graphs = [ text_format.Parse(d, graph_pb2.GraphDef()) for d in [GRAPH_DEF_TXT, GRAPH_DEF_TXT_2] ] ops_and_kernels = selective_registration_header_lib.get_ops_and_kernels( 'rawproto', self.WriteGraphFiles(graphs), default_ops) header = selective_registration_header_lib.get_header_from_ops_and_kernels( ops_and_kernels, include_all_ops_and_kernels=True) self.assertListEqual( [ '// This file was autogenerated by %s' % self.script_name, '#ifndef OPS_TO_REGISTER', # '#define OPS_TO_REGISTER', # '#define SHOULD_REGISTER_OP(op) true', # '#define SHOULD_REGISTER_OP_KERNEL(clz) true', # '#define SHOULD_REGISTER_OP_GRADIENT true', # '#endif' ], header.split('\n')) self.assertListEqual( header.split('\n'), selective_registration_header_lib.get_header( self.WriteGraphFiles(graphs), 'rawproto', default_ops).split('\n')) def testGetSelectiveHeader(self): default_ops = '' graphs = [text_format.Parse(GRAPH_DEF_TXT_2, graph_pb2.GraphDef())] expected = '''// This file was autogenerated by %s #ifndef OPS_TO_REGISTER #define OPS_TO_REGISTER namespace { constexpr const char* skip(const char* x) { return (*x) ? (*x == ' ' ? skip(x + 1) : x) : x; } constexpr bool isequal(const char* x, const char* y) { return (*skip(x) && *skip(y)) ? (*skip(x) == *skip(y) && isequal(skip(x) + 1, skip(y) + 1)) : (!*skip(x) && !*skip(y)); } template<int N> struct find_in { static constexpr bool f(const char* x, const char* const y[N]) { return isequal(x, y[0]) || find_in<N - 1>::f(x, y + 1); } }; template<> struct find_in<0> { static constexpr bool f(const char* x, const char* const y[]) { return false; } }; } // end namespace constexpr const char* kNecessaryOpKernelClasses[] = { "BiasOp<CPUDevice, float>", }; #define SHOULD_REGISTER_OP_KERNEL(clz) (find_in<sizeof(kNecessaryOpKernelClasses) / sizeof(*kNecessaryOpKernelClasses)>::f(clz, kNecessaryOpKernelClasses)) constexpr inline bool ShouldRegisterOp(const char op[]) { return false || isequal(op, "AccumulateNV2") || isequal(op, "BiasAdd") ; } #define SHOULD_REGISTER_OP(op) ShouldRegisterOp(op) #define SHOULD_REGISTER_OP_GRADIENT false #endif''' % self.script_name header = selective_registration_header_lib.get_header( self.WriteGraphFiles(graphs), 'rawproto', default_ops) print(header) self.assertListEqual(expected.split('\n'), header.split('\n')) if __name__ == '__main__': test.main()
apache-2.0
VielSoft/odoo
addons/account_followup/account_followup.py
79
29624
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # 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 openerp import api from openerp.osv import fields, osv from lxml import etree from openerp.tools.translate import _ class followup(osv.osv): _name = 'account_followup.followup' _description = 'Account Follow-up' _rec_name = 'name' _columns = { 'followup_line': fields.one2many('account_followup.followup.line', 'followup_id', 'Follow-up', copy=True), 'company_id': fields.many2one('res.company', 'Company', required=True), 'name': fields.related('company_id', 'name', string = "Name", readonly=True, type="char"), } _defaults = { 'company_id': lambda s, cr, uid, c: s.pool.get('res.company')._company_default_get(cr, uid, 'account_followup.followup', context=c), } _sql_constraints = [('company_uniq', 'unique(company_id)', 'Only one follow-up per company is allowed')] class followup_line(osv.osv): def _get_default_template(self, cr, uid, ids, context=None): try: return self.pool.get('ir.model.data').get_object_reference(cr, uid, 'account_followup', 'email_template_account_followup_default')[1] except ValueError: return False _name = 'account_followup.followup.line' _description = 'Follow-up Criteria' _columns = { 'name': fields.char('Follow-Up Action', required=True), 'sequence': fields.integer('Sequence', help="Gives the sequence order when displaying a list of follow-up lines."), 'delay': fields.integer('Due Days', help="The number of days after the due date of the invoice to wait before sending the reminder. Could be negative if you want to send a polite alert beforehand.", required=True), 'followup_id': fields.many2one('account_followup.followup', 'Follow Ups', required=True, ondelete="cascade"), 'description': fields.text('Printed Message', translate=True), 'send_email':fields.boolean('Send an Email', help="When processing, it will send an email"), 'send_letter':fields.boolean('Send a Letter', help="When processing, it will print a letter"), 'manual_action':fields.boolean('Manual Action', help="When processing, it will set the manual action to be taken for that customer. "), 'manual_action_note':fields.text('Action To Do', placeholder="e.g. Give a phone call, check with others , ..."), 'manual_action_responsible_id':fields.many2one('res.users', 'Assign a Responsible', ondelete='set null'), 'email_template_id':fields.many2one('email.template', 'Email Template', ondelete='set null'), } _order = 'delay' _sql_constraints = [('days_uniq', 'unique(followup_id, delay)', 'Days of the follow-up levels must be different')] _defaults = { 'send_email': True, 'send_letter': True, 'manual_action':False, 'description': """ Dear %(partner_name)s, Exception made if there was a mistake of ours, it seems that the following amount stays unpaid. Please, take appropriate measures in order to carry out this payment in the next 8 days. Would your payment have been carried out after this mail was sent, please ignore this message. Do not hesitate to contact our accounting department. Best Regards, """, 'email_template_id': _get_default_template, } def _check_description(self, cr, uid, ids, context=None): lang = self.pool['res.users'].browse(cr, uid, uid, context=context).lang for line in self.browse(cr, uid, ids, context=dict(context or {}, lang=lang)): if line.description: try: line.description % {'partner_name': '', 'date':'', 'user_signature': '', 'company_name': ''} except: return False return True _constraints = [ (_check_description, 'Your description is invalid, use the right legend or %% if you want to use the percent character.', ['description']), ] class account_move_line(osv.osv): def _get_result(self, cr, uid, ids, name, arg, context=None): res = {} for aml in self.browse(cr, uid, ids, context=context): res[aml.id] = aml.debit - aml.credit return res _inherit = 'account.move.line' _columns = { 'followup_line_id': fields.many2one('account_followup.followup.line', 'Follow-up Level', ondelete='restrict'), #restrict deletion of the followup line 'followup_date': fields.date('Latest Follow-up', select=True), 'result':fields.function(_get_result, type='float', method=True, string="Balance") #'balance' field is not the same } class res_partner(osv.osv): def fields_view_get(self, cr, uid, view_id=None, view_type=None, context=None, toolbar=False, submenu=False): res = super(res_partner, self).fields_view_get(cr, uid, view_id=view_id, view_type=view_type, context=context, toolbar=toolbar, submenu=submenu) context = context or {} if view_type == 'form' and context.get('Followupfirst'): doc = etree.XML(res['arch'], parser=None, base_url=None) first_node = doc.xpath("//page[@name='followup_tab']") root = first_node[0].getparent() root.insert(0, first_node[0]) res['arch'] = etree.tostring(doc, encoding="utf-8") return res def _get_latest(self, cr, uid, ids, names, arg, context=None, company_id=None): res={} if company_id == None: company = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id else: company = self.pool.get('res.company').browse(cr, uid, company_id, context=context) for partner in self.browse(cr, uid, ids, context=context): amls = partner.unreconciled_aml_ids latest_date = False latest_level = False latest_days = False latest_level_without_lit = False latest_days_without_lit = False for aml in amls: if (aml.company_id == company) and (aml.followup_line_id != False) and (not latest_days or latest_days < aml.followup_line_id.delay): latest_days = aml.followup_line_id.delay latest_level = aml.followup_line_id.id if (aml.company_id == company) and (not latest_date or latest_date < aml.followup_date): latest_date = aml.followup_date if (aml.company_id == company) and (aml.blocked == False) and (aml.followup_line_id != False and (not latest_days_without_lit or latest_days_without_lit < aml.followup_line_id.delay)): latest_days_without_lit = aml.followup_line_id.delay latest_level_without_lit = aml.followup_line_id.id res[partner.id] = {'latest_followup_date': latest_date, 'latest_followup_level_id': latest_level, 'latest_followup_level_id_without_lit': latest_level_without_lit} return res @api.cr_uid_ids_context def do_partner_manual_action(self, cr, uid, partner_ids, context=None): #partner_ids -> res.partner for partner in self.browse(cr, uid, partner_ids, context=context): #Check action: check if the action was not empty, if not add action_text= "" if partner.payment_next_action: action_text = (partner.payment_next_action or '') + "\n" + (partner.latest_followup_level_id_without_lit.manual_action_note or '') else: action_text = partner.latest_followup_level_id_without_lit.manual_action_note or '' #Check date: only change when it did not exist already action_date = partner.payment_next_action_date or fields.date.context_today(self, cr, uid, context=context) # Check responsible: if partner has not got a responsible already, take from follow-up responsible_id = False if partner.payment_responsible_id: responsible_id = partner.payment_responsible_id.id else: p = partner.latest_followup_level_id_without_lit.manual_action_responsible_id responsible_id = p and p.id or False self.write(cr, uid, [partner.id], {'payment_next_action_date': action_date, 'payment_next_action': action_text, 'payment_responsible_id': responsible_id}) def do_partner_print(self, cr, uid, wizard_partner_ids, data, context=None): #wizard_partner_ids are ids from special view, not from res.partner if not wizard_partner_ids: return {} data['partner_ids'] = wizard_partner_ids datas = { 'ids': wizard_partner_ids, 'model': 'account_followup.followup', 'form': data } return self.pool['report'].get_action(cr, uid, [], 'account_followup.report_followup', data=datas, context=context) @api.cr_uid_ids_context def do_partner_mail(self, cr, uid, partner_ids, context=None): if context is None: context = {} ctx = context.copy() ctx['followup'] = True #partner_ids are res.partner ids # If not defined by latest follow-up level, it will be the default template if it can find it mtp = self.pool.get('email.template') unknown_mails = 0 for partner in self.browse(cr, uid, partner_ids, context=ctx): partners_to_email = [child for child in partner.child_ids if child.type == 'invoice' and child.email] if not partners_to_email and partner.email: partners_to_email = [partner] if partners_to_email: level = partner.latest_followup_level_id_without_lit for partner_to_email in partners_to_email: if level and level.send_email and level.email_template_id and level.email_template_id.id: mtp.send_mail(cr, uid, level.email_template_id.id, partner_to_email.id, context=ctx) else: mail_template_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'account_followup', 'email_template_account_followup_default') mtp.send_mail(cr, uid, mail_template_id[1], partner_to_email.id, context=ctx) if partner not in partners_to_email: self.message_post(cr, uid, [partner.id], body=_('Overdue email sent to %s' % ', '.join(['%s <%s>' % (partner.name, partner.email) for partner in partners_to_email])), context=context) else: unknown_mails = unknown_mails + 1 action_text = _("Email not sent because of email address of partner not filled in") if partner.payment_next_action_date: payment_action_date = min(fields.date.context_today(self, cr, uid, context=ctx), partner.payment_next_action_date) else: payment_action_date = fields.date.context_today(self, cr, uid, context=ctx) if partner.payment_next_action: payment_next_action = partner.payment_next_action + " \n " + action_text else: payment_next_action = action_text self.write(cr, uid, [partner.id], {'payment_next_action_date': payment_action_date, 'payment_next_action': payment_next_action}, context=ctx) return unknown_mails def get_followup_table_html(self, cr, uid, ids, context=None): """ Build the html tables to be included in emails send to partners, when reminding them their overdue invoices. :param ids: [id] of the partner for whom we are building the tables :rtype: string """ from report import account_followup_print assert len(ids) == 1 if context is None: context = {} partner = self.browse(cr, uid, ids[0], context=context).commercial_partner_id #copy the context to not change global context. Overwrite it because _() looks for the lang in local variable 'context'. #Set the language to use = the partner language context = dict(context, lang=partner.lang) followup_table = '' if partner.unreconciled_aml_ids: company = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id current_date = fields.date.context_today(self, cr, uid, context=context) rml_parse = account_followup_print.report_rappel(cr, uid, "followup_rml_parser") final_res = rml_parse._lines_get_with_partner(partner, company.id) for currency_dict in final_res: currency = currency_dict.get('line', [{'currency_id': company.currency_id}])[0]['currency_id'] followup_table += ''' <table border="2" width=100%%> <tr> <td>''' + _("Invoice Date") + '''</td> <td>''' + _("Description") + '''</td> <td>''' + _("Reference") + '''</td> <td>''' + _("Due Date") + '''</td> <td>''' + _("Amount") + " (%s)" % (currency.symbol) + '''</td> <td>''' + _("Lit.") + '''</td> </tr> ''' total = 0 for aml in currency_dict['line']: block = aml['blocked'] and 'X' or ' ' total += aml['balance'] strbegin = "<TD>" strend = "</TD>" date = aml['date_maturity'] or aml['date'] if date <= current_date and aml['balance'] > 0: strbegin = "<TD><B>" strend = "</B></TD>" followup_table +="<TR>" + strbegin + str(aml['date']) + strend + strbegin + aml['name'] + strend + strbegin + (aml['ref'] or '') + strend + strbegin + str(date) + strend + strbegin + str(aml['balance']) + strend + strbegin + block + strend + "</TR>" total = reduce(lambda x, y: x+y['balance'], currency_dict['line'], 0.00) total = rml_parse.formatLang(total, dp='Account', currency_obj=currency) followup_table += '''<tr> </tr> </table> <center>''' + _("Amount due") + ''' : %s </center>''' % (total) return followup_table def write(self, cr, uid, ids, vals, context=None): if vals.get("payment_responsible_id", False): for part in self.browse(cr, uid, ids, context=context): if part.payment_responsible_id <> vals["payment_responsible_id"]: #Find partner_id of user put as responsible responsible_partner_id = self.pool.get("res.users").browse(cr, uid, vals['payment_responsible_id'], context=context).partner_id.id self.pool.get("mail.thread").message_post(cr, uid, 0, body = _("You became responsible to do the next action for the payment follow-up of") + " <b><a href='#id=" + str(part.id) + "&view_type=form&model=res.partner'> " + part.name + " </a></b>", type = 'comment', subtype = "mail.mt_comment", context = context, model = 'res.partner', res_id = part.id, partner_ids = [responsible_partner_id]) return super(res_partner, self).write(cr, uid, ids, vals, context=context) def action_done(self, cr, uid, ids, context=None): return self.write(cr, uid, ids, {'payment_next_action_date': False, 'payment_next_action':'', 'payment_responsible_id': False}, context=context) def do_button_print(self, cr, uid, ids, context=None): assert(len(ids) == 1) company_id = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.id #search if the partner has accounting entries to print. If not, it may not be present in the #psql view the report is based on, so we need to stop the user here. if not self.pool.get('account.move.line').search(cr, uid, [ ('partner_id', '=', ids[0]), ('account_id.type', '=', 'receivable'), ('reconcile_id', '=', False), ('state', '!=', 'draft'), ('company_id', '=', company_id), '|', ('date_maturity', '=', False), ('date_maturity', '<=', fields.date.context_today(self, cr, uid)), ], context=context): raise osv.except_osv(_('Error!'),_("The partner does not have any accounting entries to print in the overdue report for the current company.")) self.message_post(cr, uid, [ids[0]], body=_('Printed overdue payments report'), context=context) #build the id of this partner in the psql view. Could be replaced by a search with [('company_id', '=', company_id),('partner_id', '=', ids[0])] wizard_partner_ids = [ids[0] * 10000 + company_id] followup_ids = self.pool.get('account_followup.followup').search(cr, uid, [('company_id', '=', company_id)], context=context) if not followup_ids: raise osv.except_osv(_('Error!'),_("There is no followup plan defined for the current company.")) data = { 'date': fields.date.today(), 'followup_id': followup_ids[0], } #call the print overdue report on this partner return self.do_partner_print(cr, uid, wizard_partner_ids, data, context=context) def _get_amounts_and_date(self, cr, uid, ids, name, arg, context=None): ''' Function that computes values for the followup functional fields. Note that 'payment_amount_due' is similar to 'credit' field on res.partner except it filters on user's company. ''' res = {} company = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id current_date = fields.date.context_today(self, cr, uid, context=context) for partner in self.browse(cr, uid, ids, context=context): worst_due_date = False amount_due = amount_overdue = 0.0 for aml in partner.unreconciled_aml_ids: if (aml.company_id == company): date_maturity = aml.date_maturity or aml.date if not worst_due_date or date_maturity < worst_due_date: worst_due_date = date_maturity amount_due += aml.result if (date_maturity <= current_date): amount_overdue += aml.result res[partner.id] = {'payment_amount_due': amount_due, 'payment_amount_overdue': amount_overdue, 'payment_earliest_due_date': worst_due_date} return res def _get_followup_overdue_query(self, cr, uid, args, overdue_only=False, context=None): ''' This function is used to build the query and arguments to use when making a search on functional fields * payment_amount_due * payment_amount_overdue Basically, the query is exactly the same except that for overdue there is an extra clause in the WHERE. :param args: arguments given to the search in the usual domain notation (list of tuples) :param overdue_only: option to add the extra argument to filter on overdue accounting entries or not :returns: a tuple with * the query to execute as first element * the arguments for the execution of this query :rtype: (string, []) ''' company_id = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.id having_where_clause = ' AND '.join(map(lambda x: '(SUM(bal2) %s %%s)' % (x[1]), args)) having_values = [x[2] for x in args] query = self.pool.get('account.move.line')._query_get(cr, uid, context=context) overdue_only_str = overdue_only and 'AND date_maturity <= NOW()' or '' return ('''SELECT pid AS partner_id, SUM(bal2) FROM (SELECT CASE WHEN bal IS NOT NULL THEN bal ELSE 0.0 END AS bal2, p.id as pid FROM (SELECT (debit-credit) AS bal, partner_id FROM account_move_line l WHERE account_id IN (SELECT id FROM account_account WHERE type=\'receivable\' AND active) ''' + overdue_only_str + ''' AND reconcile_id IS NULL AND company_id = %s AND ''' + query + ''') AS l RIGHT JOIN res_partner p ON p.id = partner_id ) AS pl GROUP BY pid HAVING ''' + having_where_clause, [company_id] + having_values) def _payment_overdue_search(self, cr, uid, obj, name, args, context=None): if not args: return [] query, query_args = self._get_followup_overdue_query(cr, uid, args, overdue_only=True, context=context) cr.execute(query, query_args) res = cr.fetchall() if not res: return [('id','=','0')] return [('id','in', [x[0] for x in res])] def _payment_earliest_date_search(self, cr, uid, obj, name, args, context=None): if not args: return [] company_id = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.id having_where_clause = ' AND '.join(map(lambda x: '(MIN(l.date_maturity) %s %%s)' % (x[1]), args)) having_values = [x[2] for x in args] query = self.pool.get('account.move.line')._query_get(cr, uid, context=context) cr.execute('SELECT partner_id FROM account_move_line l '\ 'WHERE account_id IN '\ '(SELECT id FROM account_account '\ 'WHERE type=\'receivable\' AND active) '\ 'AND l.company_id = %s ' 'AND reconcile_id IS NULL '\ 'AND '+query+' '\ 'AND partner_id IS NOT NULL '\ 'GROUP BY partner_id HAVING '+ having_where_clause, [company_id] + having_values) res = cr.fetchall() if not res: return [('id','=','0')] return [('id','in', [x[0] for x in res])] def _payment_due_search(self, cr, uid, obj, name, args, context=None): if not args: return [] query, query_args = self._get_followup_overdue_query(cr, uid, args, overdue_only=False, context=context) cr.execute(query, query_args) res = cr.fetchall() if not res: return [('id','=','0')] return [('id','in', [x[0] for x in res])] def _get_partners(self, cr, uid, ids, context=None): #this function search for the partners linked to all account.move.line 'ids' that have been changed partners = set() for aml in self.browse(cr, uid, ids, context=context): if aml.partner_id: partners.add(aml.partner_id.id) return list(partners) _inherit = "res.partner" _columns = { 'payment_responsible_id':fields.many2one('res.users', ondelete='set null', string='Follow-up Responsible', help="Optionally you can assign a user to this field, which will make him responsible for the action.", track_visibility="onchange", copy=False), 'payment_note':fields.text('Customer Payment Promise', help="Payment Note", track_visibility="onchange", copy=False), 'payment_next_action':fields.text('Next Action', copy=False, help="This is the next action to be taken. It will automatically be set when the partner gets a follow-up level that requires a manual action. ", track_visibility="onchange"), 'payment_next_action_date': fields.date('Next Action Date', copy=False, help="This is when the manual follow-up is needed. " "The date will be set to the current date when the partner " "gets a follow-up level that requires a manual action. " "Can be practical to set manually e.g. to see if he keeps " "his promises."), 'unreconciled_aml_ids':fields.one2many('account.move.line', 'partner_id', domain=['&', ('reconcile_id', '=', False), '&', ('account_id.active','=', True), '&', ('account_id.type', '=', 'receivable'), ('state', '!=', 'draft')]), 'latest_followup_date':fields.function(_get_latest, method=True, type='date', string="Latest Follow-up Date", help="Latest date that the follow-up level of the partner was changed", store=False, multi="latest"), 'latest_followup_level_id':fields.function(_get_latest, method=True, type='many2one', relation='account_followup.followup.line', string="Latest Follow-up Level", help="The maximum follow-up level", store={ 'res.partner': (lambda self, cr, uid, ids, c: ids,[],10), 'account.move.line': (_get_partners, ['followup_line_id'], 10), }, multi="latest"), 'latest_followup_level_id_without_lit':fields.function(_get_latest, method=True, type='many2one', relation='account_followup.followup.line', string="Latest Follow-up Level without litigation", help="The maximum follow-up level without taking into account the account move lines with litigation", store={ 'res.partner': (lambda self, cr, uid, ids, c: ids,[],10), 'account.move.line': (_get_partners, ['followup_line_id'], 10), }, multi="latest"), 'payment_amount_due':fields.function(_get_amounts_and_date, type='float', string="Amount Due", store = False, multi="followup", fnct_search=_payment_due_search), 'payment_amount_overdue':fields.function(_get_amounts_and_date, type='float', string="Amount Overdue", store = False, multi="followup", fnct_search = _payment_overdue_search), 'payment_earliest_due_date':fields.function(_get_amounts_and_date, type='date', string = "Worst Due Date", multi="followup", fnct_search=_payment_earliest_date_search), } class account_config_settings(osv.TransientModel): _name = 'account.config.settings' _inherit = 'account.config.settings' def open_followup_level_form(self, cr, uid, ids, context=None): res_ids = self.pool.get('account_followup.followup').search(cr, uid, [], context=context) return { 'type': 'ir.actions.act_window', 'name': 'Payment Follow-ups', 'res_model': 'account_followup.followup', 'res_id': res_ids and res_ids[0] or False, 'view_mode': 'form,tree', } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
brandond/ansible
test/units/module_utils/facts/test_collectors.py
78
16892
# unit tests for ansible fact collectors # -*- coding: utf-8 -*- # # Ansible 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. # # Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>. # # Make coding more python3-ish from __future__ import (absolute_import, division) __metaclass__ = type from units.compat.mock import Mock, patch from . base import BaseFactsTest from ansible.module_utils.facts import collector from ansible.module_utils.facts.system.apparmor import ApparmorFactCollector from ansible.module_utils.facts.system.caps import SystemCapabilitiesFactCollector from ansible.module_utils.facts.system.cmdline import CmdLineFactCollector from ansible.module_utils.facts.system.distribution import DistributionFactCollector from ansible.module_utils.facts.system.dns import DnsFactCollector from ansible.module_utils.facts.system.env import EnvFactCollector from ansible.module_utils.facts.system.fips import FipsFactCollector from ansible.module_utils.facts.system.pkg_mgr import PkgMgrFactCollector, OpenBSDPkgMgrFactCollector from ansible.module_utils.facts.system.platform import PlatformFactCollector from ansible.module_utils.facts.system.python import PythonFactCollector from ansible.module_utils.facts.system.selinux import SelinuxFactCollector from ansible.module_utils.facts.system.service_mgr import ServiceMgrFactCollector from ansible.module_utils.facts.system.ssh_pub_keys import SshPubKeyFactCollector from ansible.module_utils.facts.system.user import UserFactCollector from ansible.module_utils.facts.virtual.base import VirtualCollector from ansible.module_utils.facts.network.base import NetworkCollector from ansible.module_utils.facts.hardware.base import HardwareCollector class CollectorException(Exception): pass class ExceptionThrowingCollector(collector.BaseFactCollector): name = 'exc_throwing' def __init__(self, collectors=None, namespace=None, exception=None): super(ExceptionThrowingCollector, self).__init__(collectors, namespace) self._exception = exception or CollectorException('collection failed') def collect(self, module=None, collected_facts=None): raise self._exception class TestExceptionThrowingCollector(BaseFactsTest): __test__ = True gather_subset = ['exc_throwing'] valid_subsets = ['exc_throwing'] collector_class = ExceptionThrowingCollector def test_collect(self): module = self._mock_module() fact_collector = self.collector_class() self.assertRaises(CollectorException, fact_collector.collect, module=module, collected_facts=self.collected_facts) def test_collect_with_namespace(self): module = self._mock_module() fact_collector = self.collector_class() self.assertRaises(CollectorException, fact_collector.collect_with_namespace, module=module, collected_facts=self.collected_facts) class TestApparmorFacts(BaseFactsTest): __test__ = True gather_subset = ['!all', 'apparmor'] valid_subsets = ['apparmor'] fact_namespace = 'ansible_apparmor' collector_class = ApparmorFactCollector def test_collect(self): facts_dict = super(TestApparmorFacts, self).test_collect() self.assertIn('status', facts_dict['apparmor']) class TestCapsFacts(BaseFactsTest): __test__ = True gather_subset = ['!all', 'caps'] valid_subsets = ['caps'] fact_namespace = 'ansible_system_capabilities' collector_class = SystemCapabilitiesFactCollector def _mock_module(self): mock_module = Mock() mock_module.params = {'gather_subset': self.gather_subset, 'gather_timeout': 10, 'filter': '*'} mock_module.get_bin_path = Mock(return_value='/usr/sbin/capsh') mock_module.run_command = Mock(return_value=(0, 'Current: =ep', '')) return mock_module class TestCmdLineFacts(BaseFactsTest): __test__ = True gather_subset = ['!all', 'cmdline'] valid_subsets = ['cmdline'] fact_namespace = 'ansible_cmdline' collector_class = CmdLineFactCollector def test_parse_proc_cmdline_uefi(self): uefi_cmdline = r'initrd=\70ef65e1a04a47aea04f7b5145ea3537\4.10.0-19-generic\initrd root=UUID=50973b75-4a66-4bf0-9764-2b7614489e64 ro quiet' expected = {'initrd': r'\70ef65e1a04a47aea04f7b5145ea3537\4.10.0-19-generic\initrd', 'root': 'UUID=50973b75-4a66-4bf0-9764-2b7614489e64', 'quiet': True, 'ro': True} fact_collector = self.collector_class() facts_dict = fact_collector._parse_proc_cmdline(uefi_cmdline) self.assertDictEqual(facts_dict, expected) def test_parse_proc_cmdline_fedora(self): cmdline_fedora = r'BOOT_IMAGE=/vmlinuz-4.10.16-200.fc25.x86_64 root=/dev/mapper/fedora-root ro rd.lvm.lv=fedora/root rd.luks.uuid=luks-c80b7537-358b-4a07-b88c-c59ef187479b rd.lvm.lv=fedora/swap rhgb quiet LANG=en_US.UTF-8' # noqa expected = {'BOOT_IMAGE': '/vmlinuz-4.10.16-200.fc25.x86_64', 'LANG': 'en_US.UTF-8', 'quiet': True, 'rd.luks.uuid': 'luks-c80b7537-358b-4a07-b88c-c59ef187479b', 'rd.lvm.lv': 'fedora/swap', 'rhgb': True, 'ro': True, 'root': '/dev/mapper/fedora-root'} fact_collector = self.collector_class() facts_dict = fact_collector._parse_proc_cmdline(cmdline_fedora) self.assertDictEqual(facts_dict, expected) def test_parse_proc_cmdline_dup_console(self): example = r'BOOT_IMAGE=/boot/vmlinuz-4.4.0-72-generic root=UUID=e12e46d9-06c9-4a64-a7b3-60e24b062d90 ro console=tty1 console=ttyS0' # FIXME: Two 'console' keywords? Using a dict for the fact value here loses info. Currently the 'last' one wins expected = {'BOOT_IMAGE': '/boot/vmlinuz-4.4.0-72-generic', 'root': 'UUID=e12e46d9-06c9-4a64-a7b3-60e24b062d90', 'ro': True, 'console': 'ttyS0'} fact_collector = self.collector_class() facts_dict = fact_collector._parse_proc_cmdline(example) # TODO: fails because we lose a 'console' self.assertDictEqual(facts_dict, expected) class TestDistributionFacts(BaseFactsTest): __test__ = True gather_subset = ['!all', 'distribution'] valid_subsets = ['distribution'] fact_namespace = 'ansible_distribution' collector_class = DistributionFactCollector class TestDnsFacts(BaseFactsTest): __test__ = True gather_subset = ['!all', 'dns'] valid_subsets = ['dns'] fact_namespace = 'ansible_dns' collector_class = DnsFactCollector class TestEnvFacts(BaseFactsTest): __test__ = True gather_subset = ['!all', 'env'] valid_subsets = ['env'] fact_namespace = 'ansible_env' collector_class = EnvFactCollector def test_collect(self): facts_dict = super(TestEnvFacts, self).test_collect() self.assertIn('HOME', facts_dict['env']) class TestFipsFacts(BaseFactsTest): __test__ = True gather_subset = ['!all', 'fips'] valid_subsets = ['fips'] fact_namespace = 'ansible_fips' collector_class = FipsFactCollector class TestHardwareCollector(BaseFactsTest): __test__ = True gather_subset = ['!all', 'hardware'] valid_subsets = ['hardware'] fact_namespace = 'ansible_hardware' collector_class = HardwareCollector collected_facts = {'ansible_architecture': 'x86_64'} class TestNetworkCollector(BaseFactsTest): __test__ = True gather_subset = ['!all', 'network'] valid_subsets = ['network'] fact_namespace = 'ansible_network' collector_class = NetworkCollector class TestPkgMgrFacts(BaseFactsTest): __test__ = True gather_subset = ['!all', 'pkg_mgr'] valid_subsets = ['pkg_mgr'] fact_namespace = 'ansible_pkgmgr' collector_class = PkgMgrFactCollector collected_facts = { "ansible_distribution": "Fedora", "ansible_distribution_major_version": "28", "ansible_os_family": "RedHat" } def test_collect(self): module = self._mock_module() fact_collector = self.collector_class() facts_dict = fact_collector.collect(module=module, collected_facts=self.collected_facts) self.assertIsInstance(facts_dict, dict) self.assertIn('pkg_mgr', facts_dict) def _sanitize_os_path_apt_get(path): if path == '/usr/bin/apt-get': return True else: return False class TestPkgMgrFactsAptFedora(BaseFactsTest): __test__ = True gather_subset = ['!all', 'pkg_mgr'] valid_subsets = ['pkg_mgr'] fact_namespace = 'ansible_pkgmgr' collector_class = PkgMgrFactCollector collected_facts = { "ansible_distribution": "Fedora", "ansible_distribution_major_version": "28", "ansible_os_family": "RedHat", "ansible_pkg_mgr": "apt" } @patch('ansible.module_utils.facts.system.pkg_mgr.os.path.exists', side_effect=_sanitize_os_path_apt_get) def test_collect(self, mock_os_path_exists): module = self._mock_module() fact_collector = self.collector_class() facts_dict = fact_collector.collect(module=module, collected_facts=self.collected_facts) self.assertIsInstance(facts_dict, dict) self.assertIn('pkg_mgr', facts_dict) class TestOpenBSDPkgMgrFacts(BaseFactsTest): __test__ = True gather_subset = ['!all', 'pkg_mgr'] valid_subsets = ['pkg_mgr'] fact_namespace = 'ansible_pkgmgr' collector_class = OpenBSDPkgMgrFactCollector def test_collect(self): module = self._mock_module() fact_collector = self.collector_class() facts_dict = fact_collector.collect(module=module, collected_facts=self.collected_facts) self.assertIsInstance(facts_dict, dict) self.assertIn('pkg_mgr', facts_dict) self.assertEqual(facts_dict['pkg_mgr'], 'openbsd_pkg') class TestPlatformFactCollector(BaseFactsTest): __test__ = True gather_subset = ['!all', 'platform'] valid_subsets = ['platform'] fact_namespace = 'ansible_platform' collector_class = PlatformFactCollector class TestPythonFactCollector(BaseFactsTest): __test__ = True gather_subset = ['!all', 'python'] valid_subsets = ['python'] fact_namespace = 'ansible_python' collector_class = PythonFactCollector class TestSelinuxFacts(BaseFactsTest): __test__ = True gather_subset = ['!all', 'selinux'] valid_subsets = ['selinux'] fact_namespace = 'ansible_selinux' collector_class = SelinuxFactCollector def test_no_selinux(self): with patch('ansible.module_utils.facts.system.selinux.HAVE_SELINUX', False): module = self._mock_module() fact_collector = self.collector_class() facts_dict = fact_collector.collect(module=module) self.assertIsInstance(facts_dict, dict) self.assertEqual(facts_dict['selinux']['status'], 'Missing selinux Python library') return facts_dict class TestServiceMgrFacts(BaseFactsTest): __test__ = True gather_subset = ['!all', 'service_mgr'] valid_subsets = ['service_mgr'] fact_namespace = 'ansible_service_mgr' collector_class = ServiceMgrFactCollector # TODO: dedupe some of this test code @patch('ansible.module_utils.facts.system.service_mgr.get_file_content', return_value=None) def test_no_proc1(self, mock_gfc): # no /proc/1/comm, ps returns non-0 # should fallback to 'service' module = self._mock_module() module.run_command = Mock(return_value=(1, '', 'wat')) fact_collector = self.collector_class() facts_dict = fact_collector.collect(module=module) self.assertIsInstance(facts_dict, dict) self.assertEqual(facts_dict['service_mgr'], 'service') @patch('ansible.module_utils.facts.system.service_mgr.get_file_content', return_value=None) def test_no_proc1_ps_random_init(self, mock_gfc): # no /proc/1/comm, ps returns '/sbin/sys11' which we dont know # should end up return 'sys11' module = self._mock_module() module.run_command = Mock(return_value=(0, '/sbin/sys11', '')) fact_collector = self.collector_class() facts_dict = fact_collector.collect(module=module) self.assertIsInstance(facts_dict, dict) self.assertEqual(facts_dict['service_mgr'], 'sys11') @patch('ansible.module_utils.facts.system.service_mgr.get_file_content', return_value=None) def test_clowncar(self, mock_gfc): # no /proc/1/comm, ps fails, distro and system are clowncar # should end up return 'sys11' module = self._mock_module() module.run_command = Mock(return_value=(1, '', '')) collected_facts = {'distribution': 'clowncar', 'system': 'ClownCarOS'} fact_collector = self.collector_class() facts_dict = fact_collector.collect(module=module, collected_facts=collected_facts) self.assertIsInstance(facts_dict, dict) self.assertEqual(facts_dict['service_mgr'], 'service') # TODO: reenable these tests when we can mock more easily # @patch('ansible.module_utils.facts.system.service_mgr.get_file_content', return_value=None) # def test_sunos_fallback(self, mock_gfc): # # no /proc/1/comm, ps fails, 'system' is SunOS # # should end up return 'smf'? # module = self._mock_module() # # FIXME: the result here is a kluge to at least cover more of service_mgr.collect # # TODO: remove # # FIXME: have to force a pid for results here to get into any of the system/distro checks # module.run_command = Mock(return_value=(1, ' 37 ', '')) # collected_facts = {'system': 'SunOS'} # fact_collector = self.collector_class(module=module) # facts_dict = fact_collector.collect(collected_facts=collected_facts) # print('facts_dict: %s' % facts_dict) # self.assertIsInstance(facts_dict, dict) # self.assertEqual(facts_dict['service_mgr'], 'smf') # @patch('ansible.module_utils.facts.system.service_mgr.get_file_content', return_value=None) # def test_aix_fallback(self, mock_gfc): # # no /proc/1/comm, ps fails, 'system' is SunOS # # should end up return 'smf'? # module = self._mock_module() # module.run_command = Mock(return_value=(1, '', '')) # collected_facts = {'system': 'AIX'} # fact_collector = self.collector_class(module=module) # facts_dict = fact_collector.collect(collected_facts=collected_facts) # print('facts_dict: %s' % facts_dict) # self.assertIsInstance(facts_dict, dict) # self.assertEqual(facts_dict['service_mgr'], 'src') # @patch('ansible.module_utils.facts.system.service_mgr.get_file_content', return_value=None) # def test_linux_fallback(self, mock_gfc): # # no /proc/1/comm, ps fails, 'system' is SunOS # # should end up return 'smf'? # module = self._mock_module() # module.run_command = Mock(return_value=(1, ' 37 ', '')) # collected_facts = {'system': 'Linux'} # fact_collector = self.collector_class(module=module) # facts_dict = fact_collector.collect(collected_facts=collected_facts) # print('facts_dict: %s' % facts_dict) # self.assertIsInstance(facts_dict, dict) # self.assertEqual(facts_dict['service_mgr'], 'sdfadf') class TestSshPubKeyFactCollector(BaseFactsTest): __test__ = True gather_subset = ['!all', 'ssh_pub_keys'] valid_subsets = ['ssh_pub_keys'] fact_namespace = 'ansible_ssh_pub_leys' collector_class = SshPubKeyFactCollector class TestUserFactCollector(BaseFactsTest): __test__ = True gather_subset = ['!all', 'user'] valid_subsets = ['user'] fact_namespace = 'ansible_user' collector_class = UserFactCollector class TestVirtualFacts(BaseFactsTest): __test__ = True gather_subset = ['!all', 'virtual'] valid_subsets = ['virtual'] fact_namespace = 'ansible_virtual' collector_class = VirtualCollector
gpl-3.0
ilique/webpushkin
pushkin/pushkin.py
1
13033
import re import paramiko import telnetlib import time from django.core.exceptions import ObjectDoesNotExist from netmiko import ConnectHandler from .models import Service, CommandGroup class Switch(object): def __init__(self, value): self.value = value self.fall = False def __iter__(self): """Return the match method once, then stop""" yield self.match raise StopIteration def match(self, *args): """Indicate whether or not to enter a case suite""" if self.fall or not args: return True elif self.value in args: # changed for v1.5, see below self.fall = True return True else: return False class Device: def __init__(self, device_ip, device_type): self.ip = device_ip self.type = device_type self.model = 'Cisco' @staticmethod def get_next_linked_device(ip): for case in Switch(ip): if case('1.1.1.1'): return Device('2.2.2.2', 'sw') if case('2.2.2.2'): return Device('3.3.3.3', 'sw') if case('3.3.3.3'): return Device('4.4.4.4', 'sw') if case('4.4.4.4'): return Device('5.5.5.5', 'agw') if case(): return None @staticmethod def get_type_of_device(ip): for case in Switch(ip): if case('1.1.1.1'): return 'asw' if case('2.2.2.2'): return 'sw' if case('3.3.3.3'): return 'sw' if case('4.4.4.4'): return 'agw' if case('5.5.5.5'): return 'agw' if case(): return 'sw' @staticmethod def get_trunk_interfaces_of_device(ip): for case in Switch(ip): if case('1.1.1.1'): return {'up': '0/1', 'down': '0/2'} if case('2.2.2.2'): return {'up': '0/1', 'down': '0/2'} if case('3.3.3.3'): return {'up': '0/1', 'down': '0/2'} if case('4.4.4.4'): return {'up': '0/1', 'down': '0/2'} if case('5.5.5.5'): return {'up': '0/1', 'down': '0/2'} class BaseService: def __init__(self, service_id): self.service_id = service_id self.devices = [] self.device_types = [] self.parsed_instructions = {} self.evaluated_args = {} key = '' instructions = Service.objects.get(id=self.service_id).instructions.split("\n") for instruction in instructions: instruction = instruction.strip() if instruction: if self.instruction_is_device_spec(instruction): key = instruction self.parsed_instructions[key] = [] elif key in self.parsed_instructions: self.parsed_instructions[key].append(instruction) def prepare_commands(self): result = [] for device_spec, command_groups in self.parsed_instructions.items(): device_type = self.get_type_from_device_spec(device_spec) if device_type in self.device_types: if self.service_on_multiple_devices(device_spec): devices = self.find_devices_by_type(device_type) for device in devices: result.append( {'device_ip': device.ip, 'commands': self.evaluate_commands(device, command_groups)}) else: device = self.find_device_by_type(device_type) result.append({'device_ip': device.ip, 'commands': self.evaluate_commands(device, command_groups)}) return result def run(self): output = '' instructions = self.prepare_commands() for instruction in instructions: if instruction['device_ip'] and instruction['commands']: connection = PushkinNetmiko('ssh', 22, instruction['device_ip'], 'login', 'pass', 'cisco') output += connection.send_commands(instruction['commands']) return output def evaluate_commands(self, device, command_groups): commands = [] for group_name in command_groups: try: group = CommandGroup.objects.get(name=group_name, device_model__name=device.model) for command in group.commands.all(): for argument in command.arguments.all(): if argument.name in self.evaluated_args[device]: new_text = command.text.replace(argument.name, self.evaluated_args[device][argument.name]) commands.append(new_text) except ObjectDoesNotExist: pass return commands def evaluate_arguments(self, *args): pass def find_devices_by_type(self, device_type): result = [] for device in self.devices: if device_type == device.type: result.append(device) return result def find_device_by_type(self, device_type): for device in self.devices: if device_type == device.type: return device return None @staticmethod def instruction_is_device_spec(instruction): return re.match("on|на \[[\w\s]+\]", instruction) @staticmethod def get_type_from_device_spec(device_spec): found = re.findall('\w+$', device_spec) if len(found): return found[0] return None @staticmethod def service_on_multiple_devices(device_spec): return re.match("one or more|одном или более", device_spec) @staticmethod def get_vlan_id(): return '78' @staticmethod def get_vlan_name(client_name): return client_name class ServiceOnLinkedDevices(BaseService): def __init__(self, service_id, first_device): super(ServiceOnLinkedDevices, self).__init__(service_id) self.devices = self.find_all_linked_devices(first_device) self.device_types = self.find_all_linked_device_types(first_device) @staticmethod def find_all_linked_devices(first_device): devices = [first_device] ip = first_device.ip while True: next_device = Device.get_next_linked_device(ip) if next_device: devices.append(next_device) ip = next_device.ip else: break return devices @staticmethod def find_all_linked_device_types(first_device): types = [Device.get_type_of_device(first_device.ip)] ip = first_device.ip while True: next_device = Device.get_next_linked_device(ip) if next_device: types.append(Device.get_type_of_device(next_device.ip)) ip = next_device.ip else: break return types class SimpleVK(ServiceOnLinkedDevices): def __init__(self, service_id, client_device_ip, client_interface, client_name, client_speed): super(SimpleVK, self).__init__(service_id, Device(client_device_ip, 'asw')) for device in self.devices: trunk = Device.get_trunk_interfaces_of_device(device.ip) # TODO: sharing arguments between services self.evaluated_args[device] = { 'trunk_interface_up': trunk['up'], 'trunk_interface_down': trunk['down'], 'client_interface': client_interface, 'client_name': client_name, 'client_speed': client_speed, 'vlan_id': self.get_vlan_id(), 'vlan_name': self.get_vlan_name('test-sdn'), } class PushkinNetmiko: # TODO 0: merge with netmiko # TODO 1: handling of device models # TODO 2: do proper telnet support and organize protocol dispatch def __init__(self, protocol, port, ip, login, password, device_model, secret=''): self.protocol = protocol.lower().strip() self.port = port self.ip = ip self.login = login self.password = password self.device_model = device_model.split(' ')[0].lower().strip() self.ssh_device_models = { 'cisco': 'cisco_ios', 'eltex': 'eltex', 'huawei': 'huawei', 'extreme': 'extreme', 'juniper': 'juniper', 'linux': 'linux', } self.telnet_cli_tokens = { 'cisco': { 'login': 'Username:', 'pass': 'Password:', 'greet': '#', 'enabled_command': 'conf t', 'enabled': '(config)#', }, 'huawei': { 'login': 'Username:', 'pass': 'Password:', 'greet': '>', 'enabled_command': 'system-view', 'enabled': ']', }, 'raisecom': { 'login': 'Login:', 'pass': 'Password:', 'greet': 'Hello, Welcome to Raisecom', 'enabled_command': 'enable', 'enabled': '#', }, 'eltex': { 'login': 'User Name:', 'pass': 'Password:', 'greet': 'SW version', 'enabled_command': 'configure', 'enabled': '(config)#', } } self.telnet_enable_password = secret self.connection = self.connect() def connect(self): # TODO: no route to host exception handling if self.protocol == 'ssh': device = { 'ip': self.ip, 'port': self.port, 'username': self.login, 'password': self.password } pushkin_device_mapper = self.ssh_device_models device['device_type'] = pushkin_device_mapper[self.device_model] try: net_connect = ConnectHandler(**device) except paramiko.SSHException: return False return net_connect elif self.protocol == 'telnet': if self.device_model in self.telnet_cli_tokens: login_token = self.telnet_cli_tokens[self.device_model]['login'] password_token = self.telnet_cli_tokens[self.device_model]['pass'] greet_token = self.telnet_cli_tokens[self.device_model]['greet'] enable_command = self.telnet_cli_tokens[self.device_model]['enabled_command'] enabled_token = self.telnet_cli_tokens[self.device_model]['enabled'] try: tn = telnetlib.Telnet(self.ip) except IOError: return False tn.read_until(login_token.encode('ascii')) tn.write(self.login.encode('ascii') + b"\n") tn.read_until(password_token.encode('ascii')) tn.write(self.password.encode('ascii') + b"\n") tn.read_until(greet_token.encode('ascii')) tn.write(enable_command.encode('ascii') + b"\n") if self.telnet_enable_password: tn.read_until(password_token.encode('ascii')) tn.write(self.telnet_enable_password.encode('ascii') + b"\n") tn.read_until(enabled_token.encode('ascii')) return tn return False def send_commands(self, commands, timeout=.3): if self.connection: output = '' if 'ssh' in self.protocol.lower(): try: if (isinstance(commands, list)): output = self.connection.send_config_set(commands) elif (isinstance(commands, str)): output = self.connection.send_command(commands) except paramiko.SSHException: output = 'Connection timeout' elif 'telnet' in self.protocol.lower(): for command in commands: command = command.strip() # TODO: do it in a little more intelligent way if command == "newline": self.connection.write(b"\n") else: self.connection.write(command.encode('ascii') + b"\n") time.sleep(timeout) output += self.connection.read_very_eager().decode('ascii') return output else: return False class Pushkin: services = { 'Simple client tunnel': SimpleVK } def execute_service(self, service_name, *args): if service_name in self.services: service = self.services[service_name](*args) # initialize service.run()
mit
rsvip/Django
tests/model_formsets_regress/models.py
144
1146
from django.db import models from django.utils.encoding import python_2_unicode_compatible class User(models.Model): username = models.CharField(max_length=12, unique=True) serial = models.IntegerField() class UserSite(models.Model): user = models.ForeignKey(User, to_field="username") data = models.IntegerField() class UserProfile(models.Model): user = models.ForeignKey(User, unique=True, to_field="username") about = models.TextField() class ProfileNetwork(models.Model): profile = models.ForeignKey(UserProfile, to_field="user") network = models.IntegerField() identifier = models.IntegerField() class Place(models.Model): name = models.CharField(max_length=50) class Restaurant(Place): pass class Manager(models.Model): restaurant = models.ForeignKey(Restaurant) name = models.CharField(max_length=50) class Network(models.Model): name = models.CharField(max_length=15) @python_2_unicode_compatible class Host(models.Model): network = models.ForeignKey(Network) hostname = models.CharField(max_length=25) def __str__(self): return self.hostname
bsd-3-clause
ralphtheninja/compose
compose/config.py
9
16210
import logging import os import sys import yaml from collections import namedtuple import six from compose.cli.utils import find_candidates_in_parent_dirs DOCKER_CONFIG_KEYS = [ 'cap_add', 'cap_drop', 'cpu_shares', 'cpuset', 'command', 'detach', 'devices', 'dns', 'dns_search', 'domainname', 'entrypoint', 'env_file', 'environment', 'extra_hosts', 'hostname', 'image', 'labels', 'links', 'mac_address', 'mem_limit', 'memswap_limit', 'net', 'log_driver', 'log_opt', 'pid', 'ports', 'privileged', 'read_only', 'restart', 'security_opt', 'stdin_open', 'tty', 'user', 'volumes', 'volumes_from', 'working_dir', ] ALLOWED_KEYS = DOCKER_CONFIG_KEYS + [ 'build', 'dockerfile', 'expose', 'external_links', 'name', ] DOCKER_CONFIG_HINTS = { 'cpu_share': 'cpu_shares', 'add_host': 'extra_hosts', 'hosts': 'extra_hosts', 'extra_host': 'extra_hosts', 'device': 'devices', 'link': 'links', 'memory_swap': 'memswap_limit', 'port': 'ports', 'privilege': 'privileged', 'priviliged': 'privileged', 'privilige': 'privileged', 'volume': 'volumes', 'workdir': 'working_dir', } SUPPORTED_FILENAMES = [ 'docker-compose.yml', 'docker-compose.yaml', 'fig.yml', 'fig.yaml', ] log = logging.getLogger(__name__) ConfigDetails = namedtuple('ConfigDetails', 'config working_dir filename') def find(base_dir, filename): if filename == '-': return ConfigDetails(yaml.safe_load(sys.stdin), os.getcwd(), None) if filename: filename = os.path.join(base_dir, filename) else: filename = get_config_path(base_dir) return ConfigDetails(load_yaml(filename), os.path.dirname(filename), filename) def get_config_path(base_dir): (candidates, path) = find_candidates_in_parent_dirs(SUPPORTED_FILENAMES, base_dir) if len(candidates) == 0: raise ComposeFileNotFound(SUPPORTED_FILENAMES) winner = candidates[0] if len(candidates) > 1: log.warn("Found multiple config files with supported names: %s", ", ".join(candidates)) log.warn("Using %s\n", winner) if winner == 'docker-compose.yaml': log.warn("Please be aware that .yml is the expected extension " "in most cases, and using .yaml can cause compatibility " "issues in future.\n") if winner.startswith("fig."): log.warn("%s is deprecated and will not be supported in future. " "Please rename your config file to docker-compose.yml\n" % winner) return os.path.join(path, winner) def load(config_details): dictionary, working_dir, filename = config_details service_dicts = [] for service_name, service_dict in list(dictionary.items()): if not isinstance(service_dict, dict): raise ConfigurationError('Service "%s" doesn\'t have any configuration options. All top level keys in your docker-compose.yml must map to a dictionary of configuration options.' % service_name) loader = ServiceLoader(working_dir=working_dir, filename=filename) service_dict = loader.make_service_dict(service_name, service_dict) validate_paths(service_dict) service_dicts.append(service_dict) return service_dicts class ServiceLoader(object): def __init__(self, working_dir, filename=None, already_seen=None): self.working_dir = os.path.abspath(working_dir) if filename: self.filename = os.path.abspath(filename) else: self.filename = filename self.already_seen = already_seen or [] def detect_cycle(self, name): if self.signature(name) in self.already_seen: raise CircularReference(self.already_seen + [self.signature(name)]) def make_service_dict(self, name, service_dict): service_dict = service_dict.copy() service_dict['name'] = name service_dict = resolve_environment(service_dict, working_dir=self.working_dir) service_dict = self.resolve_extends(service_dict) return process_container_options(service_dict, working_dir=self.working_dir) def resolve_extends(self, service_dict): if 'extends' not in service_dict: return service_dict extends_options = self.validate_extends_options(service_dict['name'], service_dict['extends']) if self.working_dir is None: raise Exception("No working_dir passed to ServiceLoader()") if 'file' in extends_options: extends_from_filename = extends_options['file'] other_config_path = expand_path(self.working_dir, extends_from_filename) else: other_config_path = self.filename other_working_dir = os.path.dirname(other_config_path) other_already_seen = self.already_seen + [self.signature(service_dict['name'])] other_loader = ServiceLoader( working_dir=other_working_dir, filename=other_config_path, already_seen=other_already_seen, ) other_config = load_yaml(other_config_path) other_service_dict = other_config[extends_options['service']] other_loader.detect_cycle(extends_options['service']) other_service_dict = other_loader.make_service_dict( service_dict['name'], other_service_dict, ) validate_extended_service_dict( other_service_dict, filename=other_config_path, service=extends_options['service'], ) return merge_service_dicts(other_service_dict, service_dict) def signature(self, name): return (self.filename, name) def validate_extends_options(self, service_name, extends_options): error_prefix = "Invalid 'extends' configuration for %s:" % service_name if not isinstance(extends_options, dict): raise ConfigurationError("%s must be a dictionary" % error_prefix) if 'service' not in extends_options: raise ConfigurationError( "%s you need to specify a service, e.g. 'service: web'" % error_prefix ) if 'file' not in extends_options and self.filename is None: raise ConfigurationError( "%s you need to specify a 'file', e.g. 'file: something.yml'" % error_prefix ) for k, _ in extends_options.items(): if k not in ['file', 'service']: raise ConfigurationError( "%s unsupported configuration option '%s'" % (error_prefix, k) ) return extends_options def validate_extended_service_dict(service_dict, filename, service): error_prefix = "Cannot extend service '%s' in %s:" % (service, filename) if 'links' in service_dict: raise ConfigurationError("%s services with 'links' cannot be extended" % error_prefix) if 'volumes_from' in service_dict: raise ConfigurationError("%s services with 'volumes_from' cannot be extended" % error_prefix) if 'net' in service_dict: if get_service_name_from_net(service_dict['net']) is not None: raise ConfigurationError("%s services with 'net: container' cannot be extended" % error_prefix) def process_container_options(service_dict, working_dir=None): for k in service_dict: if k not in ALLOWED_KEYS: msg = "Unsupported config option for %s service: '%s'" % (service_dict['name'], k) if k in DOCKER_CONFIG_HINTS: msg += " (did you mean '%s'?)" % DOCKER_CONFIG_HINTS[k] raise ConfigurationError(msg) service_dict = service_dict.copy() if 'memswap_limit' in service_dict and 'mem_limit' not in service_dict: raise ConfigurationError("Invalid 'memswap_limit' configuration for %s service: when defining 'memswap_limit' you must set 'mem_limit' as well" % service_dict['name']) if 'volumes' in service_dict: service_dict['volumes'] = resolve_volume_paths(service_dict['volumes'], working_dir=working_dir) if 'build' in service_dict: service_dict['build'] = resolve_build_path(service_dict['build'], working_dir=working_dir) if 'labels' in service_dict: service_dict['labels'] = parse_labels(service_dict['labels']) return service_dict def merge_service_dicts(base, override): d = base.copy() if 'environment' in base or 'environment' in override: d['environment'] = merge_environment( base.get('environment'), override.get('environment'), ) path_mapping_keys = ['volumes', 'devices'] for key in path_mapping_keys: if key in base or key in override: d[key] = merge_path_mappings( base.get(key), override.get(key), ) if 'labels' in base or 'labels' in override: d['labels'] = merge_labels( base.get('labels'), override.get('labels'), ) if 'image' in override and 'build' in d: del d['build'] if 'build' in override and 'image' in d: del d['image'] list_keys = ['ports', 'expose', 'external_links'] for key in list_keys: if key in base or key in override: d[key] = base.get(key, []) + override.get(key, []) list_or_string_keys = ['dns', 'dns_search'] for key in list_or_string_keys: if key in base or key in override: d[key] = to_list(base.get(key)) + to_list(override.get(key)) already_merged_keys = ['environment', 'labels'] + path_mapping_keys + list_keys + list_or_string_keys for k in set(ALLOWED_KEYS) - set(already_merged_keys): if k in override: d[k] = override[k] return d def merge_environment(base, override): env = parse_environment(base) env.update(parse_environment(override)) return env def parse_links(links): return dict(parse_link(l) for l in links) def parse_link(link): if ':' in link: source, alias = link.split(':', 1) return (alias, source) else: return (link, link) def get_env_files(options, working_dir=None): if 'env_file' not in options: return {} if working_dir is None: raise Exception("No working_dir passed to get_env_files()") env_files = options.get('env_file', []) if not isinstance(env_files, list): env_files = [env_files] return [expand_path(working_dir, path) for path in env_files] def resolve_environment(service_dict, working_dir=None): service_dict = service_dict.copy() if 'environment' not in service_dict and 'env_file' not in service_dict: return service_dict env = {} if 'env_file' in service_dict: for f in get_env_files(service_dict, working_dir=working_dir): env.update(env_vars_from_file(f)) del service_dict['env_file'] env.update(parse_environment(service_dict.get('environment'))) env = dict(resolve_env_var(k, v) for k, v in six.iteritems(env)) service_dict['environment'] = env return service_dict def parse_environment(environment): if not environment: return {} if isinstance(environment, list): return dict(split_env(e) for e in environment) if isinstance(environment, dict): return environment raise ConfigurationError( "environment \"%s\" must be a list or mapping," % environment ) def split_env(env): if '=' in env: return env.split('=', 1) else: return env, None def resolve_env_var(key, val): if val is not None: return key, val elif key in os.environ: return key, os.environ[key] else: return key, '' def env_vars_from_file(filename): """ Read in a line delimited file of environment variables. """ if not os.path.exists(filename): raise ConfigurationError("Couldn't find env file: %s" % filename) env = {} for line in open(filename, 'r'): line = line.strip() if line and not line.startswith('#'): k, v = split_env(line) env[k] = v return env def resolve_volume_paths(volumes, working_dir=None): if working_dir is None: raise Exception("No working_dir passed to resolve_volume_paths()") return [resolve_volume_path(v, working_dir) for v in volumes] def resolve_volume_path(volume, working_dir): container_path, host_path = split_path_mapping(volume) container_path = os.path.expanduser(os.path.expandvars(container_path)) if host_path is not None: host_path = os.path.expanduser(os.path.expandvars(host_path)) return "%s:%s" % (expand_path(working_dir, host_path), container_path) else: return container_path def resolve_build_path(build_path, working_dir=None): if working_dir is None: raise Exception("No working_dir passed to resolve_build_path") return expand_path(working_dir, build_path) def validate_paths(service_dict): if 'build' in service_dict: build_path = service_dict['build'] if not os.path.exists(build_path) or not os.access(build_path, os.R_OK): raise ConfigurationError("build path %s either does not exist or is not accessible." % build_path) def merge_path_mappings(base, override): d = dict_from_path_mappings(base) d.update(dict_from_path_mappings(override)) return path_mappings_from_dict(d) def dict_from_path_mappings(path_mappings): if path_mappings: return dict(split_path_mapping(v) for v in path_mappings) else: return {} def path_mappings_from_dict(d): return [join_path_mapping(v) for v in d.items()] def split_path_mapping(string): if ':' in string: (host, container) = string.split(':', 1) return (container, host) else: return (string, None) def join_path_mapping(pair): (container, host) = pair if host is None: return container else: return ":".join((host, container)) def merge_labels(base, override): labels = parse_labels(base) labels.update(parse_labels(override)) return labels def parse_labels(labels): if not labels: return {} if isinstance(labels, list): return dict(split_label(e) for e in labels) if isinstance(labels, dict): return labels raise ConfigurationError( "labels \"%s\" must be a list or mapping" % labels ) def split_label(label): if '=' in label: return label.split('=', 1) else: return label, '' def expand_path(working_dir, path): return os.path.abspath(os.path.join(working_dir, path)) def to_list(value): if value is None: return [] elif isinstance(value, six.string_types): return [value] else: return value def get_service_name_from_net(net_config): if not net_config: return if not net_config.startswith('container:'): return _, net_name = net_config.split(':', 1) return net_name def load_yaml(filename): try: with open(filename, 'r') as fh: return yaml.safe_load(fh) except IOError as e: raise ConfigurationError(six.text_type(e)) class ConfigurationError(Exception): def __init__(self, msg): self.msg = msg def __str__(self): return self.msg class CircularReference(ConfigurationError): def __init__(self, trail): self.trail = trail @property def msg(self): lines = [ "{} in {}".format(service_name, filename) for (filename, service_name) in self.trail ] return "Circular reference:\n {}".format("\n extends ".join(lines)) class ComposeFileNotFound(ConfigurationError): def __init__(self, supported_filenames): super(ComposeFileNotFound, self).__init__(""" Can't find a suitable configuration file in this directory or any parent. Are you in the right directory? Supported filenames: %s """ % ", ".join(supported_filenames))
apache-2.0
OshynSong/scikit-learn
doc/tutorial/text_analytics/skeletons/exercise_01_language_train_model.py
254
2005
"""Build a language detector model The goal of this exercise is to train a linear classifier on text features that represent sequences of up to 3 consecutive characters so as to be recognize natural languages by using the frequencies of short character sequences as 'fingerprints'. """ # Author: Olivier Grisel <olivier.grisel@ensta.org> # License: Simplified BSD import sys from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.linear_model import Perceptron from sklearn.pipeline import Pipeline from sklearn.datasets import load_files from sklearn.cross_validation import train_test_split from sklearn import metrics # The training data folder must be passed as first argument languages_data_folder = sys.argv[1] dataset = load_files(languages_data_folder) # Split the dataset in training and test set: docs_train, docs_test, y_train, y_test = train_test_split( dataset.data, dataset.target, test_size=0.5) # TASK: Build a an vectorizer that splits strings into sequence of 1 to 3 # characters instead of word tokens # TASK: Build a vectorizer / classifier pipeline using the previous analyzer # the pipeline instance should stored in a variable named clf # TASK: Fit the pipeline on the training set # TASK: Predict the outcome on the testing set in a variable named y_predicted # Print the classification report print(metrics.classification_report(y_test, y_predicted, target_names=dataset.target_names)) # Plot the confusion matrix cm = metrics.confusion_matrix(y_test, y_predicted) print(cm) #import pylab as pl #pl.matshow(cm, cmap=pl.cm.jet) #pl.show() # Predict the result on some short new sentences: sentences = [ u'This is a language detection test.', u'Ceci est un test de d\xe9tection de la langue.', u'Dies ist ein Test, um die Sprache zu erkennen.', ] predicted = clf.predict(sentences) for s, p in zip(sentences, predicted): print(u'The language of "%s" is "%s"' % (s, dataset.target_names[p]))
bsd-3-clause
hradec/cortex
test/IECore/ops/mayaUserData/mayaUserData-1.py
12
2775
########################################################################## # # Copyright (c) 2010, Image Engine Design 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 Image Engine Design nor the names of any # other contributors to this software may be used to endorse or # promote products derived from this software without specific prior # written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS # IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ########################################################################## import IECore class mayaUserData( IECore.Op ) : def __init__( self ) : IECore.Op.__init__( self, "An Op to test the IECoreMaya::ParameterHandler support for userData.", IECore.IntParameter( name = "result", description = "d", defaultValue = 2, ) ) self.parameters().addParameters( [ IECore.IntParameter( "t", "", 100, userData = { "maya" : { "defaultConnection" : IECore.StringData( "time1.outTime" ), } } ), IECore.IntParameter( "e", "", 100, userData = { "maya" : { "defaultExpression" : IECore.StringData( " = time1.outTime * 10" ), } } ), IECore.StringParameter( "s", "", "", userData = { "maya" : { "valueProvider" : IECore.StringData( "connectedNodeName" ), } } ), ] ) def doOperation( self, args ) : return IECore.IntData( 2 ) IECore.registerRunTimeTyped( mayaUserData )
bsd-3-clause
computationalBiology/NPLB
NPLB/weblogoMod/test_corebio/test_transform.py
2
5194
#!/usr/bin/env python # Copyright (c) 2006 John Gilman # # This software is distributed under the MIT Open Source License. # <http://www.opensource.org/licenses/mit-license.html> # # 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. from corebio.transform import * from corebio.seq import * import unittest class test_mask_low_complexity(unittest.TestCase): def test_segging(self): before = "mgnrafkshhghflsaegeavkthhghhdhhthfhvenhggkvalkthcgkylsigdhkqvylshhlhgdhslfhlehhggkvsikghhhhyisadhhghvstkehhdhdttfeeiii".upper() after = "MGNRAFKSHHGHFLSAEGEAVxxxxxxxxxxxxxxxENHGGKVALKTHCGKYLSIGDHKQVYLSHHLHGDHSLFHLEHHGGKVSIKGHHHHYISADHHGHVSTKEHHDHDTTFEEIII".upper() bseq = Seq(before, protein_alphabet) aseq = Seq(after, protein_alphabet) xseq = Seq( 'X' * len(bseq), protein_alphabet) sseq = mask_low_complexity(bseq) self.assertEquals(aseq, sseq) # Nothing should be segged sseq = mask_low_complexity(bseq, 12, 0,0) self.assertEquals(bseq, sseq) # Everthing should be segged sseq = mask_low_complexity(bseq, 12, 4.3,4.3) self.assertEquals(sseq, xseq) def test_seg_invalid(self): seq = Seq("KTHCGKYLSIGDHKQVYLSHH", protein_alphabet) self.failUnlessRaises(ValueError, mask_low_complexity,seq, 12, -1, 0 ) self.failUnlessRaises(ValueError, mask_low_complexity, seq, 12, 1, 10 ) self.failUnlessRaises(ValueError, mask_low_complexity, seq, 6, 12, 13 ) self.failUnlessRaises(ValueError, mask_low_complexity, seq, 6, 2.0, 1.9 ) class test_transform(unittest.TestCase): def test_transform(self): trans = Transform( Seq("ACGTURYSWKMBDHVN",nucleic_alphabet), Seq("ACGTTNNNNNNNNNNN", dna_alphabet) ) s0 = Seq("AAAAAR",nucleic_alphabet) s1 = trans(s0) # Callable ob self.assertEquals(s1.alphabet, dna_alphabet) self.assertEquals(s1 ,Seq("AAAAAN", dna_alphabet)) # def test_translations(self) : # s = Seq("ACGTURYSWKMBDHVNACGTURYSWKMBDHVN", nucleic_alphabet ) # s2 = dna_ext_to_std(s) # s3 = Seq("ACGTTNNNNNNNNNNNACGTTNNNNNNNNNNN", dna_alphabet ) # self.assertEquals(s2, s3) def test_reduced_protein_alphabets(self): seq = Seq("ENHGGKVALKTHCGKYLSIGDHKQVYLSHHLHGDHSLFHLEHHGGKVSIKGHHHHYISADHHGHVSTKEHHDHDTTFEEIII", reduced_protein_alphabet) for t in reduced_protein_alphabets.values(): s = t(seq) class test_geneticcode(unittest.TestCase) : def test_repr(self) : for t in GeneticCode.std_list() : r = repr(t) gc = eval(r) self.assertEquals( r, repr(gc) ) self.assertEquals( str(gc), str(t) ) #print r #print t #print gc def test_translate_std(self) : dna = 'GCCATTGTAATGGGCCGCTGAAAGGGTGCCCGA' t = GeneticCode.std() s = t.translate(dna) self.assertEquals( str(s), 'AIVMGR*KGAR') for t in GeneticCode.std_list() : p = t.translate(dna) def test_translate(self) : # Ref: http://lists.open-bio.org/pipermail/biopython/2006-March/002960.html cft = ( ( "Vertebrate Mitochondrial", 'GCCATTGTAATGGGCCGCTGAAAGGGTGCCCGA', 'AIVMGRWKGAR'), ( 11, 'CAAGGCGTCGAAYAGCTTCAGGAACAGGAC', 'QGVE?LQEQD'), ( 1 , 'GCCATTGTAATGGGCCGCTGAAAGGGTGCCCGA', 'AIVMGR*KGAR'), ) for code, dna, protein in cft : c = GeneticCode.by_name(code) trans = c.translate(dna) self.assertEquals( str(trans), protein) def test_back_translate(self) : prot = 'ACDEFGHIKLMNPQRSTVWY*' t = GeneticCode.std() t.table['CGA'] s = t.back_translate(prot) self.assertEquals( prot, str( t.translate(s) ) ) if __name__ == '__main__': unittest.main()
gpl-3.0
seecr/meresco-oai
meresco/oai/oaiprovenance.py
1
3062
## begin license ## # # "Meresco Oai" are components to build Oai repositories, based on # "Meresco Core" and "Meresco Components". # # Copyright (C) 2007-2008 SURF Foundation. http://www.surf.nl # Copyright (C) 2007-2010 Seek You Too (CQ2) http://www.cq2.nl # Copyright (C) 2007-2009 Stichting Kennisnet Ict op school. http://www.kennisnetictopschool.nl # Copyright (C) 2009 Delft University of Technology http://www.tudelft.nl # Copyright (C) 2009 Tilburg University http://www.uvt.nl # Copyright (C) 2010, 2020-2021 Stichting Kennisnet https://www.kennisnet.nl # Copyright (C) 2012, 2014, 2020-2021 Seecr (Seek You Too B.V.) https://seecr.nl # Copyright (C) 2014 Netherlands Institute for Sound and Vision http://instituut.beeldengeluid.nl/ # Copyright (C) 2020-2021 Data Archiving and Network Services https://dans.knaw.nl # Copyright (C) 2020-2021 SURF https://www.surf.nl # Copyright (C) 2020-2021 The Netherlands Institute for Sound and Vision https://beeldengeluid.nl # # This file is part of "Meresco Oai" # # "Meresco Oai" 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. # # "Meresco Oai" 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 "Meresco Oai"; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # ## end license ## from meresco.components import XmlCompose from lxml.etree import parse from io import BytesIO PROVENANCE_TEMPLATE = """<provenance xmlns="http://www.openarchives.org/OAI/2.0/provenance" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.openarchives.org/OAI/2.0/provenance http://www.openarchives.org/OAI/2.0/provenance.xsd"> <originDescription harvestDate="%(harvestDate)s" altered="true"> <baseURL>%(baseURL)s</baseURL> <identifier>%(identifier)s</identifier> <datestamp>%(datestamp)s</datestamp> <metadataNamespace>%(metadataNamespace)s</metadataNamespace> </originDescription> </provenance> """ class OaiProvenance(XmlCompose): def __init__(self, nsMap, baseURL, harvestDate, metadataNamespace, identifier, datestamp): XmlCompose.__init__(self, PROVENANCE_TEMPLATE, nsMap, baseURL=baseURL, harvestDate=harvestDate, metadataNamespace=metadataNamespace, identifier=identifier, datestamp=datestamp) def provenance(self, identifier): yield self.getRecord(identifier=identifier) def _getPart(self, identifier, partname): data = self.call.getData(identifier=identifier, name=partname) return parse(BytesIO(data))
gpl-2.0
CAST-Extend/com.castsoftware.uc.checkanalysiscompleteness
xlsxwriter/styles.py
13
20948
############################################################################### # # Styles - A class for writing the Excel XLSX Worksheet file. # # Copyright 2013-2015, John McNamara, jmcnamara@cpan.org # # Package imports. from . import xmlwriter class Styles(xmlwriter.XMLwriter): """ A class for writing the Excel XLSX Styles file. """ ########################################################################### # # Public API. # ########################################################################### def __init__(self): """ Constructor. """ super(Styles, self).__init__() self.xf_formats = [] self.palette = [] self.font_count = 0 self.num_format_count = 0 self.border_count = 0 self.fill_count = 0 self.custom_colors = [] self.dxf_formats = [] ########################################################################### # # Private API. # ########################################################################### def _assemble_xml_file(self): # Assemble and write the XML file. # Write the XML declaration. self._xml_declaration() # Add the style sheet. self._write_style_sheet() # Write the number formats. self._write_num_fmts() # Write the fonts. self._write_fonts() # Write the fills. self._write_fills() # Write the borders element. self._write_borders() # Write the cellStyleXfs element. self._write_cell_style_xfs() # Write the cellXfs element. self._write_cell_xfs() # Write the cellStyles element. self._write_cell_styles() # Write the dxfs element. self._write_dxfs() # Write the tableStyles element. self._write_table_styles() # Write the colors element. self._write_colors() # Close the style sheet tag. self._xml_end_tag('styleSheet') # Close the file. self._xml_close() def _set_style_properties(self, properties): # Pass in the Format objects and other properties used in the styles. self.xf_formats = properties[0] self.palette = properties[1] self.font_count = properties[2] self.num_format_count = properties[3] self.border_count = properties[4] self.fill_count = properties[5] self.custom_colors = properties[6] self.dxf_formats = properties[7] def _get_palette_color(self, color): # Convert the RGB color. if color[0] == '#': color = color[1:] return "FF" + color.upper() ########################################################################### # # XML methods. # ########################################################################### def _write_style_sheet(self): # Write the <styleSheet> element. xmlns = 'http://schemas.openxmlformats.org/spreadsheetml/2006/main' attributes = [('xmlns', xmlns)] self._xml_start_tag('styleSheet', attributes) def _write_num_fmts(self): # Write the <numFmts> element. if not self.num_format_count: return attributes = [('count', self.num_format_count)] self._xml_start_tag('numFmts', attributes) # Write the numFmts elements. for xf_format in self.xf_formats: # Ignore built-in number formats, i.e., < 164. if xf_format.num_format_index >= 164: self._write_num_fmt(xf_format.num_format_index, xf_format.num_format) self._xml_end_tag('numFmts') def _write_num_fmt(self, num_fmt_id, format_code): # Write the <numFmt> element. format_codes = { 0: 'General', 1: '0', 2: '0.00', 3: '#,##0', 4: '#,##0.00', 5: '($#,##0_);($#,##0)', 6: '($#,##0_);[Red]($#,##0)', 7: '($#,##0.00_);($#,##0.00)', 8: '($#,##0.00_);[Red]($#,##0.00)', 9: '0%', 10: '0.00%', 11: '0.00E+00', 12: '# ?/?', 13: '# ??/??', 14: 'm/d/yy', 15: 'd-mmm-yy', 16: 'd-mmm', 17: 'mmm-yy', 18: 'h:mm AM/PM', 19: 'h:mm:ss AM/PM', 20: 'h:mm', 21: 'h:mm:ss', 22: 'm/d/yy h:mm', 37: '(#,##0_);(#,##0)', 38: '(#,##0_);[Red](#,##0)', 39: '(#,##0.00_);(#,##0.00)', 40: '(#,##0.00_);[Red](#,##0.00)', 41: '_(* #,##0_);_(* (#,##0);_(* "-"_);_(_)', 42: '_($* #,##0_);_($* (#,##0);_($* "-"_);_(_)', 43: '_(* #,##0.00_);_(* (#,##0.00);_(* "-"??_);_(_)', 44: '_($* #,##0.00_);_($* (#,##0.00);_($* "-"??_);_(_)', 45: 'mm:ss', 46: '[h]:mm:ss', 47: 'mm:ss.0', 48: '##0.0E+0', 49: '@'} # Set the format code for built-in number formats. if num_fmt_id < 164: if num_fmt_id in format_codes: format_code = format_codes[num_fmt_id] else: format_code = 'General' attributes = [ ('numFmtId', num_fmt_id), ('formatCode', format_code), ] self._xml_empty_tag('numFmt', attributes) def _write_fonts(self): # Write the <fonts> element. attributes = [('count', self.font_count)] self._xml_start_tag('fonts', attributes) # Write the font elements for xf_format objects that have them. for xf_format in self.xf_formats: if xf_format.has_font: self._write_font(xf_format) self._xml_end_tag('fonts') def _write_font(self, xf_format, is_dxf_format=False): # Write the <font> element. self._xml_start_tag('font') # The condense and extend elements are mainly used in dxf formats. if xf_format.font_condense: self._write_condense() if xf_format.font_extend: self._write_extend() if xf_format.bold: self._xml_empty_tag('b') if xf_format.italic: self._xml_empty_tag('i') if xf_format.font_strikeout: self._xml_empty_tag('strike') if xf_format.font_outline: self._xml_empty_tag('outline') if xf_format.font_shadow: self._xml_empty_tag('shadow') # Handle the underline variants. if xf_format.underline: self._write_underline(xf_format.underline) if xf_format.font_script == 1: self._write_vert_align('superscript') if xf_format.font_script == 2: self._write_vert_align('subscript') if not is_dxf_format: self._xml_empty_tag('sz', [('val', xf_format.font_size)]) if xf_format.theme == -1: # Ignore for excel2003_style. pass elif xf_format.theme: self._write_color('theme', xf_format.theme) elif xf_format.color_indexed: self._write_color('indexed', xf_format.color_indexed) elif xf_format.font_color: color = self._get_palette_color(xf_format.font_color) self._write_color('rgb', color) elif not is_dxf_format: self._write_color('theme', 1) if not is_dxf_format: self._xml_empty_tag('name', [('val', xf_format.font_name)]) if xf_format.font_family: self._xml_empty_tag('family', [('val', xf_format.font_family)]) if xf_format.font_name == 'Calibri' and not xf_format.hyperlink: self._xml_empty_tag( 'scheme', [('val', xf_format.font_scheme)]) self._xml_end_tag('font') def _write_underline(self, underline): # Write the underline font element. if underline == 2: attributes = [('val', 'double')] elif underline == 33: attributes = [('val', 'singleAccounting')] elif underline == 34: attributes = [('val', 'doubleAccounting')] else: # Default to single underline. attributes = [] self._xml_empty_tag('u', attributes) def _write_vert_align(self, val): # Write the <vertAlign> font sub-element. attributes = [('val', val)] self._xml_empty_tag('vertAlign', attributes) def _write_color(self, name, value): # Write the <color> element. attributes = [(name, value)] self._xml_empty_tag('color', attributes) def _write_fills(self): # Write the <fills> element. attributes = [('count', self.fill_count)] self._xml_start_tag('fills', attributes) # Write the default fill element. self._write_default_fill('none') self._write_default_fill('gray125') # Write the fill elements for xf_format objects that have them. for xf_format in self.xf_formats: if xf_format.has_fill: self._write_fill(xf_format) self._xml_end_tag('fills') def _write_default_fill(self, pattern_type): # Write the <fill> element for the default fills. self._xml_start_tag('fill') self._xml_empty_tag('patternFill', [('patternType', pattern_type)]) self._xml_end_tag('fill') def _write_fill(self, xf_format, is_dxf_format=False): # Write the <fill> element. pattern = xf_format.pattern bg_color = xf_format.bg_color fg_color = xf_format.fg_color # Colors for dxf formats are handled differently from normal formats # since the normal xf_format reverses the meaning of BG and FG for # solid fills. if is_dxf_format: bg_color = xf_format.dxf_bg_color fg_color = xf_format.dxf_fg_color patterns = ( 'none', 'solid', 'mediumGray', 'darkGray', 'lightGray', 'darkHorizontal', 'darkVertical', 'darkDown', 'darkUp', 'darkGrid', 'darkTrellis', 'lightHorizontal', 'lightVertical', 'lightDown', 'lightUp', 'lightGrid', 'lightTrellis', 'gray125', 'gray0625', ) self._xml_start_tag('fill') # The "none" pattern is handled differently for dxf formats. if is_dxf_format and pattern <= 1: self._xml_start_tag('patternFill') else: self._xml_start_tag( 'patternFill', [('patternType', patterns[pattern])]) if fg_color: fg_color = self._get_palette_color(fg_color) self._xml_empty_tag('fgColor', [('rgb', fg_color)]) if bg_color: bg_color = self._get_palette_color(bg_color) self._xml_empty_tag('bgColor', [('rgb', bg_color)]) else: if not is_dxf_format: self._xml_empty_tag('bgColor', [('indexed', 64)]) self._xml_end_tag('patternFill') self._xml_end_tag('fill') def _write_borders(self): # Write the <borders> element. attributes = [('count', self.border_count)] self._xml_start_tag('borders', attributes) # Write the border elements for xf_format objects that have them. for xf_format in self.xf_formats: if xf_format.has_border: self._write_border(xf_format) self._xml_end_tag('borders') def _write_border(self, xf_format, is_dxf_format=False): # Write the <border> element. attributes = [] # Diagonal borders add attributes to the <border> element. if xf_format.diag_type == 1: attributes.append(('diagonalUp', 1)) elif xf_format.diag_type == 2: attributes.append(('diagonalDown', 1)) elif xf_format.diag_type == 3: attributes.append(('diagonalUp', 1)) attributes.append(('diagonalDown', 1)) # Ensure that a default diag border is set if the diag type is set. if xf_format.diag_type and not xf_format.diag_border: xf_format.diag_border = 1 # Write the start border tag. self._xml_start_tag('border', attributes) # Write the <border> sub elements. self._write_sub_border( 'left', xf_format.left, xf_format.left_color) self._write_sub_border( 'right', xf_format.right, xf_format.right_color) self._write_sub_border( 'top', xf_format.top, xf_format.top_color) self._write_sub_border( 'bottom', xf_format.bottom, xf_format.bottom_color) # Condition DXF formats don't allow diagonal borders. if not is_dxf_format: self._write_sub_border( 'diagonal', xf_format.diag_border, xf_format.diag_color) if is_dxf_format: self._write_sub_border('vertical', None, None) self._write_sub_border('horizontal', None, None) self._xml_end_tag('border') def _write_sub_border(self, border_type, style, color): # Write the <border> sub elements such as <right>, <top>, etc. attributes = [] if not style: self._xml_empty_tag(border_type) return border_styles = ( 'none', 'thin', 'medium', 'dashed', 'dotted', 'thick', 'double', 'hair', 'mediumDashed', 'dashDot', 'mediumDashDot', 'dashDotDot', 'mediumDashDotDot', 'slantDashDot', ) attributes.append(('style', border_styles[style])) self._xml_start_tag(border_type, attributes) if color: color = self._get_palette_color(color) self._xml_empty_tag('color', [('rgb', color)]) else: self._xml_empty_tag('color', [('auto', 1)]) self._xml_end_tag(border_type) def _write_cell_style_xfs(self): # Write the <cellStyleXfs> element. attributes = [('count', 1)] self._xml_start_tag('cellStyleXfs', attributes) self._write_style_xf() self._xml_end_tag('cellStyleXfs') def _write_cell_xfs(self): # Write the <cellXfs> element. formats = self.xf_formats # Workaround for when the last xf_format is used for the comment font # and shouldn't be used for cellXfs. last_format = formats[-1] if last_format.font_only: formats.pop() attributes = [('count', len(formats))] self._xml_start_tag('cellXfs', attributes) # Write the xf elements. for xf_format in formats: self._write_xf(xf_format) self._xml_end_tag('cellXfs') def _write_style_xf(self): # Write the style <xf> element. num_fmt_id = 0 font_id = 0 fill_id = 0 border_id = 0 attributes = [ ('numFmtId', num_fmt_id), ('fontId', font_id), ('fillId', fill_id), ('borderId', border_id), ] self._xml_empty_tag('xf', attributes) def _write_xf(self, xf_format): # Write the <xf> element. num_fmt_id = xf_format.num_format_index font_id = xf_format.font_index fill_id = xf_format.fill_index border_id = xf_format.border_index xf_id = 0 has_align = 0 has_protect = 0 attributes = [ ('numFmtId', num_fmt_id), ('fontId', font_id), ('fillId', fill_id), ('borderId', border_id), ('xfId', xf_id), ] if xf_format.num_format_index > 0: attributes.append(('applyNumberFormat', 1)) # Add applyFont attribute if XF format uses a font element. if xf_format.font_index > 0: attributes.append(('applyFont', 1)) # Add applyFill attribute if XF format uses a fill element. if xf_format.fill_index > 0: attributes.append(('applyFill', 1)) # Add applyBorder attribute if XF format uses a border element. if xf_format.border_index > 0: attributes.append(('applyBorder', 1)) # Check if XF format has alignment properties set. (apply_align, align) = xf_format._get_align_properties() # Check if an alignment sub-element should be written. if apply_align and align: has_align = 1 # We can also have applyAlignment without a sub-element. if apply_align: attributes.append(('applyAlignment', 1)) # Check for cell protection properties. protection = xf_format._get_protection_properties() if protection: attributes.append(('applyProtection', 1)) has_protect = 1 # Write XF with sub-elements if required. if has_align or has_protect: self._xml_start_tag('xf', attributes) if has_align: self._xml_empty_tag('alignment', align) if has_protect: self._xml_empty_tag('protection', protection) self._xml_end_tag('xf') else: self._xml_empty_tag('xf', attributes) def _write_cell_styles(self): # Write the <cellStyles> element. attributes = [('count', 1)] self._xml_start_tag('cellStyles', attributes) self._write_cell_style() self._xml_end_tag('cellStyles') def _write_cell_style(self): # Write the <cellStyle> element. name = 'Normal' xf_id = 0 builtin_id = 0 attributes = [ ('name', name), ('xfId', xf_id), ('builtinId', builtin_id), ] self._xml_empty_tag('cellStyle', attributes) def _write_dxfs(self): # Write the <dxfs> element. formats = self.dxf_formats count = len(formats) attributes = [('count', len(formats))] if count: self._xml_start_tag('dxfs', attributes) # Write the font elements for xf_format objects that have them. for xf_format in self.dxf_formats: self._xml_start_tag('dxf') if xf_format.has_dxf_font: self._write_font(xf_format, True) if xf_format.num_format_index: self._write_num_fmt(xf_format.num_format_index, xf_format.num_format) if xf_format.has_dxf_fill: self._write_fill(xf_format, True) if xf_format.has_dxf_border: self._write_border(xf_format, True) self._xml_end_tag('dxf') self._xml_end_tag('dxfs') else: self._xml_empty_tag('dxfs', attributes) def _write_table_styles(self): # Write the <tableStyles> element. count = 0 default_table_style = 'TableStyleMedium9' default_pivot_style = 'PivotStyleLight16' attributes = [ ('count', count), ('defaultTableStyle', default_table_style), ('defaultPivotStyle', default_pivot_style), ] self._xml_empty_tag('tableStyles', attributes) def _write_colors(self): # Write the <colors> element. custom_colors = self.custom_colors if not custom_colors: return self._xml_start_tag('colors') self._write_mru_colors(custom_colors) self._xml_end_tag('colors') def _write_mru_colors(self, custom_colors): # Write the <mruColors> element for the most recently used colours. # Write the custom custom_colors in reverse order. custom_colors.reverse() # Limit the mruColors to the last 10. if len(custom_colors) > 10: custom_colors = custom_colors[0:10] self._xml_start_tag('mruColors') # Write the custom custom_colors in reverse order. for color in custom_colors: self._write_color('rgb', color) self._xml_end_tag('mruColors') def _write_condense(self): # Write the <condense> element. attributes = [('val', 0)] self._xml_empty_tag('condense', attributes) def _write_extend(self): # Write the <extend> element. attributes = [('val', 0)] self._xml_empty_tag('extend', attributes)
mit
wellpinho/coursera-dl
coursera/utils.py
15
3156
# -*- coding: utf-8 -*- """ This module provides utility functions that are used within the script. """ import errno import os import random import re import string import sys import six from .define import COURSERA_URL from six.moves import html_parser # six.moves doesn’t support urlparse if six.PY3: # pragma: no cover from urllib.parse import urlparse, urljoin else: from urlparse import urlparse, urljoin # Python3 (and six) don't provide string if six.PY3: from string import ascii_letters as string_ascii_letters from string import digits as string_digits else: from string import letters as string_ascii_letters from string import digits as string_digits if six.PY2: def decode_input(x): stdin_encoding = sys.stdin.encoding if stdin_encoding is None: stdin_encoding = "UTF-8" return x.decode(stdin_encoding) else: def decode_input(x): return x def random_string(length): """ Return a pseudo-random string of specified length. """ valid_chars = string_ascii_letters + string_digits return ''.join(random.choice(valid_chars) for i in range(length)) def clean_filename(s, minimal_change=False): """ Sanitize a string to be used as a filename. If minimal_change is set to true, then we only strip the bare minimum of characters that are problematic for filesystems (namely, ':', '/' and '\x00', '\n'). """ # First, deal with URL encoded strings h = html_parser.HTMLParser() s = h.unescape(s) # Strip forbidden characters s = ( s.replace(':', '-') .replace('/', '-') .replace('\x00', '-') .replace('\n', '') ) if minimal_change: return s s = s.replace('(', '').replace(')', '') s = s.rstrip('.') # Remove excess of trailing dots s = s.strip().replace(' ', '_') valid_chars = '-_.()%s%s' % (string.ascii_letters, string.digits) return ''.join(c for c in s if c in valid_chars) def get_anchor_format(a): """ Extract the resource file-type format from the anchor. """ # (. or format=) then (file_extension) then (? or $) # e.g. "...format=txt" or "...download.mp4?..." fmt = re.search(r"(?:\.|format=)(\w+)(?:\?.*)?$", a) return fmt.group(1) if fmt else None def mkdir_p(path, mode=0o777): """ Create subdirectory hierarchy given in the paths argument. """ try: os.makedirs(path, mode) except OSError as exc: if exc.errno == errno.EEXIST and os.path.isdir(path): pass else: raise def fix_url(url): """ Strip whitespace characters from the beginning and the end of the url and add a default scheme. """ if url is None: return None url = url.strip() if url and not urlparse(url).scheme: url = "http://" + url return url def make_coursera_absolute_url(url): """ If given url is relative adds coursera netloc, otherwise returns it without any changes. """ if not bool(urlparse(url).netloc): return urljoin(COURSERA_URL, url) return url
lgpl-3.0
pelikanchik/edx-platform
common/lib/xmodule/xmodule/tests/rendering/core.py
55
3311
""" This module is indended to provide a pluggable way to add assertions about the rendered content of XBlocks. For each view on the XBlock, this module defines a @singledispatch function that can be used to test the contents of the rendered html. The functions are of the form: @singledispatch def assert_student_view_valid_html(block, html): ''' block: The block that rendered the HTML html: An lxml.html parse of the HTML for this block ''' ... assert foo ... for child in children: assert_xblock_html(child, child_html) @singledispatch def assert_student_view_invalid_html(block, html): ''' block: The block that rendered the HTML html: A string of unparsable html ''' ... assert foo ... for child in children: assert_xblock_html(child, child_html) ... A further extension would be to provide a companion set of functions that resources that are provided to the Fragment """ import lxml.html import lxml.etree from singledispatch import singledispatch @singledispatch def assert_student_view_valid_html(block, html): """ Asserts that the html generated by the `student_view` view is correct for the supplied block :param block: The :class:`XBlock` that generated the html :param html: The generated html as parsed by lxml.html """ pass @singledispatch def assert_studio_view_valid_html(block, html): """ Asserts that the html generated by the `studio_view` view is correct for the supplied block :param block: The :class:`XBlock` that generated the html :param html: The generated html as parsed by lxml.html """ pass @singledispatch def assert_student_view_invalid_html(block, html): """ Asserts that the html generated by the `student_view` view is correct for the supplied block, given that html wasn't parsable :param block: The :class:`XBlock` that generated the html :param html: A string, not parseable as html """ assert False, "student_view should produce valid html" @singledispatch def assert_studio_view_invalid_html(block, html): """ Asserts that the html generated by the `studio_view` view is correct for the supplied block :param block: The :class:`XBlock` that generated the html :param html: A string, not parseable as html """ assert False, "studio_view should produce valid html" def assert_student_view(block, fragment): """ Helper function to assert that the `fragment` is valid output the specified `block`s `student_view` """ try: html = lxml.html.fragment_fromstring(fragment.content) except lxml.etree.ParserError: assert_student_view_invalid_html(block, fragment.content) else: assert_student_view_valid_html(block, html) def assert_studio_view(block, fragment): """ Helper function to assert that the `fragment` is valid output the specified `block`s `studio_view` """ try: html = lxml.html.fragment_fromstring(fragment.content) except lxml.etree.ParserError: assert_studio_view_invalid_html(block, fragment.content) else: assert_studio_view_valid_html(block, html)
agpl-3.0
talishte/ctigre
env/lib/python2.7/site-packages/Crypto/Cipher/CAST.py
116
4498
# -*- coding: utf-8 -*- # # Cipher/CAST.py : CAST # # =================================================================== # The contents of this file are dedicated to the public domain. To # the extent that dedication to the public domain is not available, # everyone is granted a worldwide, perpetual, royalty-free, # non-exclusive license to exercise all rights associated with the # contents of this file for any purpose whatsoever. # No rights are reserved. # # 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. # =================================================================== """CAST-128 symmetric cipher CAST-128_ (or CAST5) is a symmetric block cipher specified in RFC2144_. It has a fixed data block size of 8 bytes. Its key can vary in length from 40 to 128 bits. CAST is deemed to be cryptographically secure, but its usage is not widespread. Keys of sufficient length should be used to prevent brute force attacks (128 bits are recommended). As an example, encryption can be done as follows: >>> from Crypto.Cipher import CAST >>> from Crypto import Random >>> >>> key = b'Sixteen byte key' >>> iv = Random.new().read(CAST.block_size) >>> cipher = CAST.new(key, CAST.MODE_OPENPGP, iv) >>> plaintext = b'sona si latine loqueris ' >>> msg = cipher.encrypt(plaintext) >>> ... >>> eiv = msg[:CAST.block_size+2] >>> ciphertext = msg[CAST.block_size+2:] >>> cipher = CAST.new(key, CAST.MODE_OPENPGP, eiv) >>> print cipher.decrypt(ciphertext) .. _CAST-128: http://en.wikipedia.org/wiki/CAST-128 .. _RFC2144: http://tools.ietf.org/html/rfc2144 :undocumented: __revision__, __package__ """ __revision__ = "$Id$" from Crypto.Cipher import blockalgo from Crypto.Cipher import _CAST class CAST128Cipher(blockalgo.BlockAlgo): """CAST-128 cipher object""" def __init__(self, key, *args, **kwargs): """Initialize a CAST-128 cipher object See also `new()` at the module level.""" blockalgo.BlockAlgo.__init__(self, _CAST, key, *args, **kwargs) def new(key, *args, **kwargs): """Create a new CAST-128 cipher :Parameters: key : byte string The secret key to use in the symmetric cipher. Its length may vary from 5 to 16 bytes. :Keywords: mode : a *MODE_** constant The chaining mode to use for encryption or decryption. Default is `MODE_ECB`. IV : byte string The initialization vector to use for encryption or decryption. It is ignored for `MODE_ECB` and `MODE_CTR`. For `MODE_OPENPGP`, IV must be `block_size` bytes long for encryption and `block_size` +2 bytes for decryption (in the latter case, it is actually the *encrypted* IV which was prefixed to the ciphertext). It is mandatory. For all other modes, it must be `block_size` bytes longs. It is optional and when not present it will be given a default value of all zeroes. counter : callable (*Only* `MODE_CTR`). A stateful function that returns the next *counter block*, which is a byte string of `block_size` bytes. For better performance, use `Crypto.Util.Counter`. segment_size : integer (*Only* `MODE_CFB`).The number of bits the plaintext and ciphertext are segmented in. It must be a multiple of 8. If 0 or not specified, it will be assumed to be 8. :Return: an `CAST128Cipher` object """ return CAST128Cipher(key, *args, **kwargs) #: Electronic Code Book (ECB). See `blockalgo.MODE_ECB`. MODE_ECB = 1 #: Cipher-Block Chaining (CBC). See `blockalgo.MODE_CBC`. MODE_CBC = 2 #: Cipher FeedBack (CFB). See `blockalgo.MODE_CFB`. MODE_CFB = 3 #: This mode should not be used. MODE_PGP = 4 #: Output FeedBack (OFB). See `blockalgo.MODE_OFB`. MODE_OFB = 5 #: CounTer Mode (CTR). See `blockalgo.MODE_CTR`. MODE_CTR = 6 #: OpenPGP Mode. See `blockalgo.MODE_OPENPGP`. MODE_OPENPGP = 7 #: Size of a data block (in bytes) block_size = 8 #: Size of a key (in bytes) key_size = xrange(5,16+1)
bsd-2-clause
cheral/orange3
Orange/widgets/data/tests/test_oweditdomain.py
2
7136
# Test methods with long descriptive names can omit docstrings # pylint: disable=missing-docstring from unittest import TestCase import numpy as np from AnyQt.QtCore import QModelIndex, Qt from Orange.data import ContinuousVariable, DiscreteVariable, \ StringVariable, Table, Domain from Orange.widgets.data.oweditdomain import EditDomainReport, OWEditDomain, \ ContinuousVariableEditor, DiscreteVariableEditor, VariableEditor from Orange.widgets.data.owcolor import OWColor, ColorRole from Orange.widgets.tests.base import WidgetTest, GuiTest SECTION_NAME = "NAME" class TestEditDomainReport(TestCase): # This tests test private methods # pylint: disable=protected-access def setUp(self): self.report = EditDomainReport([], []) def test_section_yields_nothing_for_no_changes(self): result = self.report._section(SECTION_NAME, []) self.assertEmpty(result) def test_section_yields_header_for_changes(self): result = self.report._section(SECTION_NAME, ["a"]) self.assertTrue(any(SECTION_NAME in item for item in result)) def test_value_changes_yields_nothing_for_no_change(self): a = DiscreteVariable("a", values="abc") self.assertEmpty(self.report._value_changes(a, a)) def test_value_changes_yields_nothing_for_continuous_variables(self): v1, v2 = ContinuousVariable("a"), ContinuousVariable("b") self.assertEmpty(self.report._value_changes(v1, v2)) def test_value_changes_yields_changed_values(self): v1, v2 = DiscreteVariable("a", "ab"), DiscreteVariable("b", "ac") self.assertNotEmpty(self.report._value_changes(v1, v2)) def test_label_changes_yields_nothing_for_no_change(self): v1 = ContinuousVariable("a") v1.attributes["a"] = "b" self.assertEmpty(self.report._value_changes(v1, v1)) def test_label_changes_yields_added_labels(self): v1 = ContinuousVariable("a") v2 = v1.copy(None) v2.attributes["a"] = "b" self.assertNotEmpty(self.report._label_changes(v1, v2)) def test_label_changes_yields_removed_labels(self): v1 = ContinuousVariable("a") v1.attributes["a"] = "b" v2 = v1.copy(None) del v2.attributes["a"] self.assertNotEmpty(self.report._label_changes(v1, v2)) def test_label_changes_yields_modified_labels(self): v1 = ContinuousVariable("a") v1.attributes["a"] = "b" v2 = v1.copy(None) v2.attributes["a"] = "c" self.assertNotEmpty(self.report._label_changes(v1, v2)) def assertEmpty(self, iterable): self.assertRaises(StopIteration, lambda: next(iter(iterable))) def assertNotEmpty(self, iterable): try: next(iter(iterable)) except StopIteration: self.fail("Iterator did not produce any lines") class TestOWEditDomain(WidgetTest): def setUp(self): self.widget = self.create_widget(OWEditDomain) self.iris = Table("iris") def test_input_data(self): """Check widget's data with data on the input""" self.assertEqual(self.widget.data, None) self.send_signal("Data", self.iris) self.assertEqual(self.widget.data, self.iris) def test_input_data_disconnect(self): """Check widget's data after disconnecting data on the input""" self.send_signal("Data", self.iris) self.assertEqual(self.widget.data, self.iris) self.send_signal("Data", None) self.assertEqual(self.widget.data, None) def test_output_data(self): """Check data on the output after apply""" self.send_signal("Data", self.iris) output = self.get_output("Data") np.testing.assert_array_equal(output.X, self.iris.X) np.testing.assert_array_equal(output.Y, self.iris.Y) self.assertEqual(output.domain, self.iris.domain) def test_input_from_owcolor(self): """Check widget's data sent from OWColor widget""" owcolor = self.create_widget(OWColor) self.send_signal("Data", self.iris, widget=owcolor) owcolor.disc_model.setData(QModelIndex(), (250, 97, 70, 255), ColorRole) owcolor.cont_model.setData( QModelIndex(), ((255, 80, 114, 255), (255, 255, 0, 255), False), ColorRole) owcolor_output = self.get_output("Data", owcolor) self.send_signal("Data", owcolor_output) self.assertEqual(self.widget.data, owcolor_output) self.assertIsNotNone(self.widget.data.domain.class_vars[-1].colors) def test_list_attributes_remain_lists(self): a = ContinuousVariable("a") a.attributes["list"] = [1, 2, 3] d = Domain([a]) t = Table(d) self.send_signal("Data", t) assert isinstance(self.widget, OWEditDomain) # select first variable idx = self.widget.domain_view.model().index(0) self.widget.domain_view.setCurrentIndex(idx) # change first attribute value editor = self.widget.editor_stack.findChild(ContinuousVariableEditor) assert isinstance(editor, ContinuousVariableEditor) idx = editor.labels_model.index(0, 1) editor.labels_model.setData(idx, "[1, 2, 4]", Qt.EditRole) self.widget.unconditional_commit() t2 = self.get_output("Data") self.assertEqual(t2.domain["a"].attributes["list"], [1, 2, 4]) class TestEditors(GuiTest): def test_variable_editor(self): w = VariableEditor() self.assertIs(w.get_data(), None) v = StringVariable(name="S") v.attributes.update({"A": 1, "B": "b"},) w.set_data(v) self.assertEqual(w.name_edit.text(), v.name) self.assertEqual(w.labels_model.get_dict(), v.attributes) self.assertTrue(w.is_same()) w.set_data(None) self.assertEqual(w.name_edit.text(), "") self.assertEqual(w.labels_model.get_dict(), {}) self.assertIs(w.get_data(), None) def test_continuous_editor(self): w = ContinuousVariableEditor() self.assertIs(w.get_data(), None) v = ContinuousVariable("X", number_of_decimals=5) v.attributes.update({"A": 1, "B": "b"}) w.set_data(v) self.assertEqual(w.name_edit.text(), v.name) self.assertEqual(w.labels_model.get_dict(), v.attributes) self.assertTrue(w.is_same()) w.set_data(None) self.assertEqual(w.name_edit.text(), "") self.assertEqual(w.labels_model.get_dict(), {}) self.assertIs(w.get_data(), None) def test_discrete_editor(self): w = DiscreteVariableEditor() self.assertIs(w.get_data(), None) v = DiscreteVariable("C", values=["a", "b", "c"]) v.attributes.update({"A": 1, "B": "b"}) w.set_data(v) self.assertEqual(w.name_edit.text(), v.name) self.assertEqual(w.labels_model.get_dict(), v.attributes) self.assertTrue(w.is_same()) w.set_data(None) self.assertEqual(w.name_edit.text(), "") self.assertEqual(w.labels_model.get_dict(), {}) self.assertIs(w.get_data(), None)
bsd-2-clause
robintw/Py6S
Py6S/outputs.py
1
17043
# This file is part of Py6S. # # Copyright 2012 Robin Wilson and contributors listed in the CONTRIBUTORS file. # # Py6S is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Py6S is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Py6S. If not, see <http://www.gnu.org/licenses/>. import sys from .sixs_exceptions import OutputParsingError class Outputs(object): """Stores the output from a 6S run. Attributes: * ``fulltext`` -- The full output of the 6S executable. This can be written to a file with the write_output_file method. * ``values`` -- The main outputs from the 6S run, stored in a dictionary. Accessible either via standard dictionary notation (``s.outputs.values['pixel_radiance']``) or as attributes (``s.outputs.pixel_radiance``) Methods: * :meth:`.__init__` -- Constructor which takes the stdout and stderr from the model and processes it into the numerical outputs. * :meth:`.extract_results` -- Function called by the constructor to parse the output into individual variables * :meth:`.to_int` -- Convert a string to an int, so that it works even if passed a float. * :meth:`.write_output_file` -- Write the full textual output of the 6S model to a file. """ # Stores the full textual output from 6S fulltext = "" # Stores the numerical values extracted from the textual output as a dictionary def __init__(self, stdout, stderr): """Initialise the class with the stdout output from the model, and process it into the numerical outputs. Arguments: * ``stdout`` -- Standard output from the model run * ``stderr`` -- Standard error from the model run Will raise an :class:`.OutputParsingError` if the output cannot be parsed for any reason. """ self.values = {} self.trans = {} self.rat = {} if len(stderr) > 0: # Something on standard error - so there's been an error if sys.version_info[0] >= 3: stderr = stderr.decode("utf-8") import platform if platform.system() != "Darwin": print(stderr) raise OutputParsingError( "6S returned an error (shown above) - check for invalid parameter inputs" ) elif ( (platform.system() == "Darwin") and (not ("IEEE_INVALID_FLAG" in stderr)) and (not ("IEEE_DENORMAL" in stderr)) ): # Ignoring error on MacOS IEEE_INVALID_FLAG print(stderr) raise OutputParsingError( "6S returned an error (shown above) - check for invalid parameter inputs" ) self.fulltext = stdout # For Python 3 need to decode to string if sys.version_info[0] >= 3: self.fulltext = self.fulltext.decode() self.extract_results() def __getattr__(self, name): """Executed when an attribute is referenced and not found. This method is overridden to allow the user to access the outputs as ``outputs.variable`` rather than using the dictionary explicity""" if name == "__array_struct__": raise AttributeError() # If there is a key with this name in the standard variables field then use it if name in self.values: return self.values[name] else: # If not, then split it by .'s items = name.split("_") if items[0] == "transmittance": return self.trans["_".join(items[1:])] else: if name in self.rat: return self.rat[name] else: raise OutputParsingError("The specifed output variable does not exist.") def __dir__(self): # Returns list of the attributes that I want to tab-complete on that aren't actually attributes, for IPython trans_keys = ["transmittance_" + key for key in self.trans.keys()] rat_keys = self.rat.keys() all_keys = list(self.values.keys()) + list(trans_keys) + list(rat_keys) return sorted(all_keys) def extract_results(self): """Extract the results from the text output of the model and place them in the ``values`` dictionary.""" # Remove all of the *'s from the text as they just make it look pretty # and get in the way of analysing the output fulltext = self.fulltext.replace("*", "") # Split into lines lines = fulltext.splitlines() # There should be hundreds of lines for a full 6S run - so if there are # less than 10 then it suggests something has gone seriously wrong if len(lines) < 10: print(fulltext) raise OutputParsingError( "6S didn't return a full output. See raw 6S output above for " "more information and check for invalid parameter inputs" ) CURRENT = 0 WHOLE_LINE = (0, 30) # fmt: off # The dictionary below specifies how to extract each variable from the text output # of 6S. # The dictionary key is the text to search for. When this is found, the line corresponding # to the first value in the tuple is found. If this is CURRENT (ie. 0) then it is the line on which # the text was found, if it is 1 then it is the next line, 2 the one after that etc. # The next item in the tuple is the index of the split line to extract the value from, and the # third item is the key to store it in in the values dictionary. The final item is the type to convert # it to - the type conversion function must be specified. More specific functions such as math.floor can # be used here if desired. # Search Term Line Index DictKey Type extractors = {"6SV version": (CURRENT, 2, "version", str), "month": (CURRENT, 1, "month", self.to_int), "day": (CURRENT, 4, "day", self.to_int), "solar zenith angle": (CURRENT, 3, "solar_z", self.to_int), "solar azimuthal angle": (CURRENT, 8, "solar_a", self.to_int), "view zenith angle": (CURRENT, 3, "view_z", self.to_int), "view azimuthal angle": (CURRENT, 8, "view_a", self.to_int), "scattering angle": (CURRENT, 2, "scattering_angle", float), "azimuthal angle difference": (CURRENT, 7, "azimuthal_angle_difference", float), "optical condition identity": (1, WHOLE_LINE, "visibility", self.extract_vis), "optical condition": (1, WHOLE_LINE, "aot550", self.extract_aot), "ground pressure": (CURRENT, 3, "ground_pressure", float), "ground altitude": (CURRENT, 3, "ground_altitude", float), "appar. rad.(w/m2/sr/mic)": (CURRENT, 2, "apparent_reflectance", float), "appar. rad.": (CURRENT, 5, "apparent_radiance", float), "total gaseous transmittance": (CURRENT, 3, "total_gaseous_transmittance", float), "wv above aerosol": (CURRENT, 4, "wv_above_aerosol", float), "wv mixed with aerosol": (CURRENT, 10, "wv_mixed_with_aerosol", float), "wv under aerosol": (CURRENT, 4, "wv_under_aerosol", float), "% of irradiance": (2, 0, "percent_direct_solar_irradiance", float), "% of irradiance at": (2, 1, "percent_diffuse_solar_irradiance", float), "% of irradiance at ground level": (2, 2, "percent_environmental_irradiance", float), "reflectance at satellite level": (2, 0, "atmospheric_intrinsic_reflectance", float), "reflectance at satellite lev": (2, 1, "background_reflectance", float), "reflectance at satellite l": (2, 2, "pixel_reflectance", float), "irr. at ground level": (2, 0, "direct_solar_irradiance", float), "irr. at ground level (w/": (2, 1, "diffuse_solar_irradiance", float), "irr. at ground level (w/m2/mic)": (2, 2, "environmental_irradiance", float), "rad at satel. level": (2, 0, "atmospheric_intrinsic_radiance", float), "rad at satel. level (w/m2/": (2, 1, "background_radiance", float), "rad at satel. level (w/m2/sr/mic)": (2, 2, "pixel_radiance", float), "sol. spect (in w/m2/mic)": (1, 0, "solar_spectrum", float), "measured radiance [w/m2/sr/mic]": (CURRENT, 4, "measured_radiance", float), "atmospherically corrected reflectance": (1, 3, "atmos_corrected_reflectance_lambertian", float), "atmospherically corrected reflect": (2, 3, "atmos_corrected_reflectance_brdf", float), "coefficients xa": (CURRENT, 5, "coef_xa", float), "coefficients xa xb": (CURRENT, 6, "coef_xb", float), "coefficients xa xb xc": (CURRENT, 7, "coef_xc", float), "int. funct filter (in mic)": (1, 0, 'int_funct_filt', float), "int. sol. spect (in w/m2)": (1, 1, 'int_solar_spectrum', float), "Foam:": (CURRENT, 1, "water_component_foam", float), "Water:": (CURRENT, 3, "water_component_water", float), "Glint:": (CURRENT, 5, "water_component_glint", float), } # fmt: on # Process most variables in the output for index in range(len(lines)): current_line = lines[index] for label, details in extractors.items(): # If the label we're searching for is in the current line if label.lower() in current_line.lower(): # See if the data is in the current line (as specified above) if details[0] == CURRENT: extracting_line = current_line # Otherwise, work out which line to use and get it else: extracting_line = lines[index + details[0]] funct = details[3] items = extracting_line.split() try: a = details[1][0] b = details[1][1] except Exception: a = details[1] b = details[1] + 1 data_for_func = items[a:b] if len(data_for_func) == 1: data_for_func = data_for_func[0] try: self.values[details[2]] = funct(data_for_func) except Exception: self.values[details[2]] = float("nan") # Process big grid in the middle of the output for transmittances grid_extractors = { "global gas. trans. :": "global_gas", 'water " " :': "water", 'ozone " " :': "ozone", 'co2 " " :': "co2", 'oxyg " " :': "oxygen", 'no2 " " :': "no2", 'ch4 " " :': "ch4", 'co " " :': "co", "rayl. sca. trans. :": "rayleigh_scattering", 'aeros. sca. " :': "aerosol_scattering", 'total sca. " :': "total_scattering", } for index in range(len(lines)): current_line = lines[index] for search, name in grid_extractors.items(): # If the label we're searching for is in the current line if search in current_line: items = current_line.split() values = Transmittance() try: values.downward = float(items[4]) except ValueError: values.downward = float("nan") try: values.upward = float(items[5]) except ValueError: values.upward = float("nan") try: values.total = float(items[6]) except ValueError: values.total = float("nan") self.trans[name] = values # Process big grid in the middle of the output for transmittances bottom_grid_extractors = { "spherical albedo :": "spherical_albedo", "optical depth total:": "optical_depth_total", "optical depth plane:": "optical_depth_plane", "reflectance I :": "reflectance_I", "reflectance Q :": "reflectance_Q", "reflectance U :": "reflectance_U", "polarized reflect. :": "polarized_reflectance", # 'degree of polar. :' : "degree_of_polarization", "dir. plane polar. :": "direction_of_plane_polarization", "phase function I :": "phase_function_I", "phase function Q :": "phase_function_Q", "phase function U :": "phase_function_U", "primary deg. of pol:": "primary_degree_of_polarization", "sing. scat. albedo :": "single_scattering_albedo", } for index in range(len(lines)): current_line = lines[index] for search, name in bottom_grid_extractors.items(): # If the label we're searching for is in the current line if search in current_line: items = current_line.rsplit(None, 3) values = RayleighAerosolTotal() try: values.total = float(items[3]) except ValueError: values.total = float("nan") try: values.aerosol = float(items[2]) except ValueError: values.aerosol = float("nan") try: values.rayleigh = float(items[1]) except ValueError: values.rayleigh = float("nan") self.rat[name] = values def to_int(self, str): """Converts a string to an integer. Does this by converting to float and then converting that to int, meaning that converting "5.00" to an integer will actually work. Arguments: * ``str`` -- The string containing the number to convert to an integer """ return int(float(str)) def extract_vis(self, data): """Extracts the visibility from the visibility and AOT line in the output""" s = " ".join(data) spl = s.split(":") spl2 = spl[1].split() try: value = float(spl2[0]) except ValueError: value = float("Inf") return value def extract_aot(self, data): """Extracts the AOT from the visibility and AOT line in the output.""" s = " ".join(data) spl = s.split(":") return float(spl[2]) def write_output_file(self, filename): """Writes the full textual output of the 6S model run to the specified filename. Arguments: * ``filename`` -- The filename to write the output to """ with open(filename, "w") as f: f.write(self.fulltext) class Transmittance(object): """Stores transmittance values from the 6S output. Basically a simple class storing three attributes: * ``downward`` -- Transmittance downwards * ``upward`` -- Transmittance upwards * ``total`` -- Total transmittance """ downward = float("nan") upward = float("nan") total = float("nan") def __str__(self): return "Downward: %f, Upward: %f, Total: %f" % ( self.downward, self.upward, self.total, ) class RayleighAerosolTotal(object): rayleigh = float("nan") aerosol = float("nan") total = float("nan") def __str__(self): return "Rayleigh: %f, Aerosol: %f, Total: %f" % ( self.rayleigh, self.aerosol, self.total, )
lgpl-3.0
tchellomello/home-assistant
tests/components/mqtt_json/test_device_tracker.py
7
5830
"""The tests for the JSON MQTT device tracker platform.""" import json import logging import os import pytest from homeassistant.components.device_tracker.legacy import ( DOMAIN as DT_DOMAIN, YAML_DEVICES, ) from homeassistant.const import CONF_PLATFORM from homeassistant.setup import async_setup_component from tests.async_mock import patch from tests.common import async_fire_mqtt_message _LOGGER = logging.getLogger(__name__) LOCATION_MESSAGE = { "longitude": 1.0, "gps_accuracy": 60, "latitude": 2.0, "battery_level": 99.9, } LOCATION_MESSAGE_INCOMPLETE = {"longitude": 2.0} @pytest.fixture(autouse=True) def setup_comp(hass, mqtt_mock): """Initialize components.""" yaml_devices = hass.config.path(YAML_DEVICES) yield if os.path.isfile(yaml_devices): os.remove(yaml_devices) async def test_ensure_device_tracker_platform_validation(hass): """Test if platform validation was done.""" async def mock_setup_scanner(hass, config, see, discovery_info=None): """Check that Qos was added by validation.""" assert "qos" in config with patch( "homeassistant.components.mqtt_json.device_tracker.async_setup_scanner", autospec=True, side_effect=mock_setup_scanner, ) as mock_sp: dev_id = "paulus" topic = "location/paulus" assert await async_setup_component( hass, DT_DOMAIN, {DT_DOMAIN: {CONF_PLATFORM: "mqtt_json", "devices": {dev_id: topic}}}, ) assert mock_sp.call_count == 1 async def test_json_message(hass): """Test json location message.""" dev_id = "zanzito" topic = "location/zanzito" location = json.dumps(LOCATION_MESSAGE) assert await async_setup_component( hass, DT_DOMAIN, {DT_DOMAIN: {CONF_PLATFORM: "mqtt_json", "devices": {dev_id: topic}}}, ) async_fire_mqtt_message(hass, topic, location) await hass.async_block_till_done() state = hass.states.get("device_tracker.zanzito") assert state.attributes.get("latitude") == 2.0 assert state.attributes.get("longitude") == 1.0 async def test_non_json_message(hass, caplog): """Test receiving a non JSON message.""" dev_id = "zanzito" topic = "location/zanzito" location = "home" assert await async_setup_component( hass, DT_DOMAIN, {DT_DOMAIN: {CONF_PLATFORM: "mqtt_json", "devices": {dev_id: topic}}}, ) caplog.set_level(logging.ERROR) caplog.clear() async_fire_mqtt_message(hass, topic, location) await hass.async_block_till_done() assert "Error parsing JSON payload: home" in caplog.text async def test_incomplete_message(hass, caplog): """Test receiving an incomplete message.""" dev_id = "zanzito" topic = "location/zanzito" location = json.dumps(LOCATION_MESSAGE_INCOMPLETE) assert await async_setup_component( hass, DT_DOMAIN, {DT_DOMAIN: {CONF_PLATFORM: "mqtt_json", "devices": {dev_id: topic}}}, ) caplog.set_level(logging.ERROR) caplog.clear() async_fire_mqtt_message(hass, topic, location) await hass.async_block_till_done() assert ( "Skipping update for following data because of missing " 'or malformatted data: {"longitude": 2.0}' in caplog.text ) async def test_single_level_wildcard_topic(hass): """Test single level wildcard topic.""" dev_id = "zanzito" subscription = "location/+/zanzito" topic = "location/room/zanzito" location = json.dumps(LOCATION_MESSAGE) assert await async_setup_component( hass, DT_DOMAIN, {DT_DOMAIN: {CONF_PLATFORM: "mqtt_json", "devices": {dev_id: subscription}}}, ) async_fire_mqtt_message(hass, topic, location) await hass.async_block_till_done() state = hass.states.get("device_tracker.zanzito") assert state.attributes.get("latitude") == 2.0 assert state.attributes.get("longitude") == 1.0 async def test_multi_level_wildcard_topic(hass): """Test multi level wildcard topic.""" dev_id = "zanzito" subscription = "location/#" topic = "location/zanzito" location = json.dumps(LOCATION_MESSAGE) assert await async_setup_component( hass, DT_DOMAIN, {DT_DOMAIN: {CONF_PLATFORM: "mqtt_json", "devices": {dev_id: subscription}}}, ) async_fire_mqtt_message(hass, topic, location) await hass.async_block_till_done() state = hass.states.get("device_tracker.zanzito") assert state.attributes.get("latitude") == 2.0 assert state.attributes.get("longitude") == 1.0 async def test_single_level_wildcard_topic_not_matching(hass): """Test not matching single level wildcard topic.""" dev_id = "zanzito" entity_id = f"{DT_DOMAIN}.{dev_id}" subscription = "location/+/zanzito" topic = "location/zanzito" location = json.dumps(LOCATION_MESSAGE) assert await async_setup_component( hass, DT_DOMAIN, {DT_DOMAIN: {CONF_PLATFORM: "mqtt_json", "devices": {dev_id: subscription}}}, ) async_fire_mqtt_message(hass, topic, location) await hass.async_block_till_done() assert hass.states.get(entity_id) is None async def test_multi_level_wildcard_topic_not_matching(hass): """Test not matching multi level wildcard topic.""" dev_id = "zanzito" entity_id = f"{DT_DOMAIN}.{dev_id}" subscription = "location/#" topic = "somewhere/zanzito" location = json.dumps(LOCATION_MESSAGE) assert await async_setup_component( hass, DT_DOMAIN, {DT_DOMAIN: {CONF_PLATFORM: "mqtt_json", "devices": {dev_id: subscription}}}, ) async_fire_mqtt_message(hass, topic, location) await hass.async_block_till_done() assert hass.states.get(entity_id) is None
apache-2.0
sdcooke/django
tests/validation/test_unique.py
337
7108
from __future__ import unicode_literals import datetime import unittest from django.apps.registry import Apps from django.core.exceptions import ValidationError from django.db import models from django.test import TestCase from .models import ( CustomPKModel, FlexibleDatePost, ModelToValidate, Post, UniqueErrorsModel, UniqueFieldsModel, UniqueForDateModel, UniqueTogetherModel, ) class GetUniqueCheckTests(unittest.TestCase): def test_unique_fields_get_collected(self): m = UniqueFieldsModel() self.assertEqual( ([(UniqueFieldsModel, ('id',)), (UniqueFieldsModel, ('unique_charfield',)), (UniqueFieldsModel, ('unique_integerfield',))], []), m._get_unique_checks() ) def test_unique_together_gets_picked_up_and_converted_to_tuple(self): m = UniqueTogetherModel() self.assertEqual( ([(UniqueTogetherModel, ('ifield', 'cfield')), (UniqueTogetherModel, ('ifield', 'efield')), (UniqueTogetherModel, ('id',)), ], []), m._get_unique_checks() ) def test_unique_together_normalization(self): """ Test the Meta.unique_together normalization with different sorts of objects. """ data = { '2-tuple': (('foo', 'bar'), (('foo', 'bar'),)), 'list': (['foo', 'bar'], (('foo', 'bar'),)), 'already normalized': ((('foo', 'bar'), ('bar', 'baz')), (('foo', 'bar'), ('bar', 'baz'))), 'set': ({('foo', 'bar'), ('bar', 'baz')}, # Ref #21469 (('foo', 'bar'), ('bar', 'baz'))), } for test_name, (unique_together, normalized) in data.items(): class M(models.Model): foo = models.IntegerField() bar = models.IntegerField() baz = models.IntegerField() Meta = type(str('Meta'), (), { 'unique_together': unique_together, 'apps': Apps() }) checks, _ = M()._get_unique_checks() for t in normalized: check = (M, t) self.assertIn(check, checks) def test_primary_key_is_considered_unique(self): m = CustomPKModel() self.assertEqual(([(CustomPKModel, ('my_pk_field',))], []), m._get_unique_checks()) def test_unique_for_date_gets_picked_up(self): m = UniqueForDateModel() self.assertEqual(( [(UniqueForDateModel, ('id',))], [(UniqueForDateModel, 'date', 'count', 'start_date'), (UniqueForDateModel, 'year', 'count', 'end_date'), (UniqueForDateModel, 'month', 'order', 'end_date')] ), m._get_unique_checks() ) def test_unique_for_date_exclusion(self): m = UniqueForDateModel() self.assertEqual(( [(UniqueForDateModel, ('id',))], [(UniqueForDateModel, 'year', 'count', 'end_date'), (UniqueForDateModel, 'month', 'order', 'end_date')] ), m._get_unique_checks(exclude='start_date') ) class PerformUniqueChecksTest(TestCase): def test_primary_key_unique_check_not_performed_when_adding_and_pk_not_specified(self): # Regression test for #12560 with self.assertNumQueries(0): mtv = ModelToValidate(number=10, name='Some Name') setattr(mtv, '_adding', True) mtv.full_clean() def test_primary_key_unique_check_performed_when_adding_and_pk_specified(self): # Regression test for #12560 with self.assertNumQueries(1): mtv = ModelToValidate(number=10, name='Some Name', id=123) setattr(mtv, '_adding', True) mtv.full_clean() def test_primary_key_unique_check_not_performed_when_not_adding(self): # Regression test for #12132 with self.assertNumQueries(0): mtv = ModelToValidate(number=10, name='Some Name') mtv.full_clean() def test_unique_for_date(self): Post.objects.create(title="Django 1.0 is released", slug="Django 1.0", subtitle="Finally", posted=datetime.date(2008, 9, 3)) p = Post(title="Django 1.0 is released", posted=datetime.date(2008, 9, 3)) with self.assertRaises(ValidationError) as cm: p.full_clean() self.assertEqual(cm.exception.message_dict, {'title': ['Title must be unique for Posted date.']}) # Should work without errors p = Post(title="Work on Django 1.1 begins", posted=datetime.date(2008, 9, 3)) p.full_clean() # Should work without errors p = Post(title="Django 1.0 is released", posted=datetime.datetime(2008, 9, 4)) p.full_clean() p = Post(slug="Django 1.0", posted=datetime.datetime(2008, 1, 1)) with self.assertRaises(ValidationError) as cm: p.full_clean() self.assertEqual(cm.exception.message_dict, {'slug': ['Slug must be unique for Posted year.']}) p = Post(subtitle="Finally", posted=datetime.datetime(2008, 9, 30)) with self.assertRaises(ValidationError) as cm: p.full_clean() self.assertEqual(cm.exception.message_dict, {'subtitle': ['Subtitle must be unique for Posted month.']}) p = Post(title="Django 1.0 is released") with self.assertRaises(ValidationError) as cm: p.full_clean() self.assertEqual(cm.exception.message_dict, {'posted': ['This field cannot be null.']}) def test_unique_for_date_with_nullable_date(self): FlexibleDatePost.objects.create(title="Django 1.0 is released", slug="Django 1.0", subtitle="Finally", posted=datetime.date(2008, 9, 3)) p = FlexibleDatePost(title="Django 1.0 is released") try: p.full_clean() except ValidationError: self.fail("unique_for_date checks shouldn't trigger when the associated DateField is None.") p = FlexibleDatePost(slug="Django 1.0") try: p.full_clean() except ValidationError: self.fail("unique_for_year checks shouldn't trigger when the associated DateField is None.") p = FlexibleDatePost(subtitle="Finally") try: p.full_clean() except ValidationError: self.fail("unique_for_month checks shouldn't trigger when the associated DateField is None.") def test_unique_errors(self): UniqueErrorsModel.objects.create(name='Some Name', no=10) m = UniqueErrorsModel(name='Some Name', no=11) with self.assertRaises(ValidationError) as cm: m.full_clean() self.assertEqual(cm.exception.message_dict, {'name': ['Custom unique name message.']}) m = UniqueErrorsModel(name='Some Other Name', no=10) with self.assertRaises(ValidationError) as cm: m.full_clean() self.assertEqual(cm.exception.message_dict, {'no': ['Custom unique number message.']})
bsd-3-clause
s3nk4s/flaskTutorials
FlaskApp/FlaskApp/venv/local/lib/python2.7/encodings/gb2312.py
816
1027
# # gb2312.py: Python Unicode Codec for GB2312 # # Written by Hye-Shik Chang <perky@FreeBSD.org> # import _codecs_cn, codecs import _multibytecodec as mbc codec = _codecs_cn.getcodec('gb2312') class Codec(codecs.Codec): encode = codec.encode decode = codec.decode class IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder): codec = codec class IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder): codec = codec class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader): codec = codec class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter): codec = codec def getregentry(): return codecs.CodecInfo( name='gb2312', encode=Codec().encode, decode=Codec().decode, incrementalencoder=IncrementalEncoder, incrementaldecoder=IncrementalDecoder, streamreader=StreamReader, streamwriter=StreamWriter, )
mit
leppa/home-assistant
homeassistant/components/tado/__init__.py
2
5394
"""Support for the (unofficial) Tado API.""" from datetime import timedelta import logging import urllib from PyTado.interface import Tado import voluptuous as vol from homeassistant.const import CONF_PASSWORD, CONF_USERNAME from homeassistant.helpers import config_validation as cv from homeassistant.helpers.discovery import load_platform from homeassistant.helpers.dispatcher import dispatcher_send from homeassistant.util import Throttle from .const import CONF_FALLBACK _LOGGER = logging.getLogger(__name__) DOMAIN = "tado" SIGNAL_TADO_UPDATE_RECEIVED = "tado_update_received_{}_{}" TADO_COMPONENTS = ["sensor", "climate"] MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=10) SCAN_INTERVAL = timedelta(seconds=15) CONFIG_SCHEMA = vol.Schema( { DOMAIN: vol.Schema( { vol.Required(CONF_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Optional(CONF_FALLBACK, default=True): cv.boolean, } ) }, extra=vol.ALLOW_EXTRA, ) def setup(hass, config): """Set up of the Tado component.""" username = config[DOMAIN][CONF_USERNAME] password = config[DOMAIN][CONF_PASSWORD] tadoconnector = TadoConnector(hass, username, password) if not tadoconnector.setup(): return False hass.data[DOMAIN] = tadoconnector # Do first update tadoconnector.update() # Load components for component in TADO_COMPONENTS: load_platform( hass, component, DOMAIN, {CONF_FALLBACK: config[DOMAIN][CONF_FALLBACK]}, config, ) # Poll for updates in the background hass.helpers.event.track_time_interval( lambda now: tadoconnector.update(), SCAN_INTERVAL ) return True class TadoConnector: """An object to store the Tado data.""" def __init__(self, hass, username, password): """Initialize Tado Connector.""" self.hass = hass self._username = username self._password = password self.tado = None self.zones = None self.devices = None self.data = { "zone": {}, "device": {}, } def setup(self): """Connect to Tado and fetch the zones.""" try: self.tado = Tado(self._username, self._password) except (RuntimeError, urllib.error.HTTPError) as exc: _LOGGER.error("Unable to connect: %s", exc) return False self.tado.setDebugging(True) # Load zones and devices self.zones = self.tado.getZones() self.devices = self.tado.getMe()["homes"] return True @Throttle(MIN_TIME_BETWEEN_UPDATES) def update(self): """Update the registered zones.""" for zone in self.zones: self.update_sensor("zone", zone["id"]) for device in self.devices: self.update_sensor("device", device["id"]) def update_sensor(self, sensor_type, sensor): """Update the internal data from Tado.""" _LOGGER.debug("Updating %s %s", sensor_type, sensor) try: if sensor_type == "zone": data = self.tado.getState(sensor) elif sensor_type == "device": data = self.tado.getDevices()[0] else: _LOGGER.debug("Unknown sensor: %s", sensor_type) return except RuntimeError: _LOGGER.error( "Unable to connect to Tado while updating %s %s", sensor_type, sensor, ) return self.data[sensor_type][sensor] = data _LOGGER.debug("Dispatching update to %s %s: %s", sensor_type, sensor, data) dispatcher_send( self.hass, SIGNAL_TADO_UPDATE_RECEIVED.format(sensor_type, sensor) ) def get_capabilities(self, zone_id): """Return the capabilities of the devices.""" return self.tado.getCapabilities(zone_id) def reset_zone_overlay(self, zone_id): """Reset the zone back to the default operation.""" self.tado.resetZoneOverlay(zone_id) self.update_sensor("zone", zone_id) def set_zone_overlay( self, zone_id, overlay_mode, temperature=None, duration=None, device_type="HEATING", mode=None, ): """Set a zone overlay.""" _LOGGER.debug( "Set overlay for zone %s: mode=%s, temp=%s, duration=%s, type=%s, mode=%s", zone_id, overlay_mode, temperature, duration, device_type, mode, ) try: self.tado.setZoneOverlay( zone_id, overlay_mode, temperature, duration, device_type, "ON", mode ) except urllib.error.HTTPError as exc: _LOGGER.error("Could not set zone overlay: %s", exc.read()) self.update_sensor("zone", zone_id) def set_zone_off(self, zone_id, overlay_mode, device_type="HEATING"): """Set a zone to off.""" try: self.tado.setZoneOverlay( zone_id, overlay_mode, None, None, device_type, "OFF" ) except urllib.error.HTTPError as exc: _LOGGER.error("Could not set zone overlay: %s", exc.read()) self.update_sensor("zone", zone_id)
apache-2.0
foospidy/DbDat
plugins/mssql/check_privileges_clr_assembly_permissions.py
1
1261
class check_privileges_clr_assembly_permissions(): """ check_privileges_clr_assembly_permissions: Setting CLR Assembly Permission Sets to SAFE_ACCESS will prevent assemblies from accessing external system resources such as files, the network, environment variables, or the registry. """ # References: # https://benchmarks.cisecurity.org/downloads/show-single/index.cfm?file=sql2012DB.120 TITLE = 'CLR Assembly Permissions' CATEGORY = 'Configuration' TYPE = 'sql' SQL = "SELECT name, permission_set_desc FROM sys.assemblies WHERE is_user_defined=1" verbose = False skip = False result = {} def do_check(self, *results): self.result['level'] = 'GREEN' output = '' for rows in results: for row in rows: if 'SAFE_ACCESS' != row[1]: self.result['level'] = 'RED' output += row[0] + '\t' + row[1] + '\n' if 'GREEN' == self.result['level']: output = 'Assemblies without SAFE_ACCESS permission not found.' self.result['output'] = output return self.result def __init__(self, parent): print('Performing check: ' + self.TITLE)
gpl-2.0
wimnat/ansible-modules-core
network/nxos/nxos_hsrp.py
8
22854
#!/usr/bin/python # # This file is part of Ansible # # Ansible 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. # # Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>. # DOCUMENTATION = ''' --- module: nxos_hsrp version_added: "2.2" short_description: Manages HSRP configuration on NX-OS switches. description: - Manages HSRP configuration on NX-OS switches. extends_documentation_fragment: nxos author: - Jason Edelman (@jedelman8) - Gabriele Gerbino (@GGabriele) notes: - HSRP feature needs to be enabled first on the system. - SVIs must exist before using this module. - Interface must be a L3 port before using this module. - HSRP cannot be configured on loopback interfaces. - MD5 authentication is only possible with HSRPv2 while it is ignored if HSRPv1 is used instead, while it will not raise any error. Here we allow MD5 authentication only with HSRPv2 in order to enforce better practice. options: group: description: - HSRP group number. required: true interface: description: - Full name of interface that is being managed for HSRP. required: true version: description: - HSRP version. required: false default: 2 choices: ['1','2'] priority: description: - HSRP priority. required: false default: null vip: description: - HSRP virtual IP address. required: false default: null auth_string: description: - Authentication string. required: false default: null auth_type: description: - Authentication type. required: false default: null choices: ['text','md5'] state: description: - Specify desired state of the resource. required: false choices: ['present','absent'] default: 'present' ''' EXAMPLES = ''' - name: Ensure HSRP is configured with following params on a SVI nxos_hsrp: group: 10 vip: 10.1.1.1 priority: 150 interface: vlan10 preempt: enabled host: 68.170.147.165 - name: Ensure HSRP is configured with following params on a SVI nxos_hsrp: group: 10 vip: 10.1.1.1 priority: 150 interface: vlan10 preempt: enabled host: 68.170.147.165 auth_type: text auth_string: CISCO - name: Remove HSRP config for given interface, group, and VIP nxos_hsrp: group: 10 interface: vlan10 vip: 10.1.1.1 host: 68.170.147.165 state: absent ''' RETURN = ''' proposed: description: k/v pairs of parameters passed into module returned: always type: dict sample: {"group": "30", "version": "2", "vip": "10.30.1.1"} existing: description: k/v pairs of existing hsrp info on the interface type: dict sample: {} end_state: description: k/v pairs of hsrp after module execution returned: always type: dict sample: {"auth_string": "cisco", "auth_type": "text", "group": "30", "interface": "vlan10", "preempt": "disabled", "priority": "100", "version": "2", "vip": "10.30.1.1"} updates: description: commands sent to the device returned: always type: list sample: ["interface vlan10", "hsrp version 2", "hsrp 30", "ip 10.30.1.1"] changed: description: check to see if a change was made on the device returned: always type: boolean sample: true ''' import json # COMMON CODE FOR MIGRATION import ansible.module_utils.nxos from ansible.module_utils.basic import get_exception from ansible.module_utils.netcfg import NetworkConfig, ConfigLine from ansible.module_utils.shell import ShellError from ansible.module_utils.network import NetworkModule def to_list(val): if isinstance(val, (list, tuple)): return list(val) elif val is not None: return [val] else: return list() class CustomNetworkConfig(NetworkConfig): def expand_section(self, configobj, S=None): if S is None: S = list() S.append(configobj) for child in configobj.children: if child in S: continue self.expand_section(child, S) return S def get_object(self, path): for item in self.items: if item.text == path[-1]: parents = [p.text for p in item.parents] if parents == path[:-1]: return item def to_block(self, section): return '\n'.join([item.raw for item in section]) def get_section(self, path): try: section = self.get_section_objects(path) return self.to_block(section) except ValueError: return list() def get_section_objects(self, path): if not isinstance(path, list): path = [path] obj = self.get_object(path) if not obj: raise ValueError('path does not exist in config') return self.expand_section(obj) def add(self, lines, parents=None): """Adds one or lines of configuration """ ancestors = list() offset = 0 obj = None ## global config command if not parents: for line in to_list(lines): item = ConfigLine(line) item.raw = line if item not in self.items: self.items.append(item) else: for index, p in enumerate(parents): try: i = index + 1 obj = self.get_section_objects(parents[:i])[0] ancestors.append(obj) except ValueError: # add parent to config offset = index * self.indent obj = ConfigLine(p) obj.raw = p.rjust(len(p) + offset) if ancestors: obj.parents = list(ancestors) ancestors[-1].children.append(obj) self.items.append(obj) ancestors.append(obj) # add child objects for line in to_list(lines): # check if child already exists for child in ancestors[-1].children: if child.text == line: break else: offset = len(parents) * self.indent item = ConfigLine(line) item.raw = line.rjust(len(line) + offset) item.parents = ancestors ancestors[-1].children.append(item) self.items.append(item) def get_network_module(**kwargs): try: return get_module(**kwargs) except NameError: return NetworkModule(**kwargs) def get_config(module, include_defaults=False): config = module.params['config'] if not config: try: config = module.get_config() except AttributeError: defaults = module.params['include_defaults'] config = module.config.get_config(include_defaults=defaults) return CustomNetworkConfig(indent=2, contents=config) def load_config(module, candidate): config = get_config(module) commands = candidate.difference(config) commands = [str(c).strip() for c in commands] save_config = module.params['save'] result = dict(changed=False) if commands: if not module.check_mode: try: module.configure(commands) except AttributeError: module.config(commands) if save_config: try: module.config.save_config() except AttributeError: module.execute(['copy running-config startup-config']) result['changed'] = True result['updates'] = commands return result # END OF COMMON CODE def execute_config_command(commands, module): try: output = module.configure(commands) except ShellError: clie = get_exception() module.fail_json(msg='Error sending CLI commands', error=str(clie), commands=commands) except AttributeError: try: commands.insert(0, 'configure') module.cli.add_commands(commands, output='config') output = module.cli.run_commands() except ShellError: clie = get_exception() module.fail_json(msg='Error sending CLI commands', error=str(clie), commands=commands) return output def get_cli_body_ssh(command, response, module): """Get response for when transport=cli. This is kind of a hack and mainly needed because these modules were originally written for NX-API. And not every command supports "| json" when using cli/ssh. As such, we assume if | json returns an XML string, it is a valid command, but that the resource doesn't exist yet. Instead, the output will be a raw string when issuing commands containing 'show run'. """ if 'xml' in response[0]: body = [] elif 'show run' in command: body = response else: try: response = response[0].replace(command + '\n\n', '').strip() body = [json.loads(response)] except ValueError: module.fail_json(msg='Command does not support JSON output', command=command) return body def execute_show(cmds, module, command_type=None): command_type_map = { 'cli_show': 'json', 'cli_show_ascii': 'text' } try: if command_type: response = module.execute(cmds, command_type=command_type) else: response = module.execute(cmds) except ShellError: clie = get_exception() module.fail_json(msg='Error sending {0}'.format(cmds), error=str(clie)) except AttributeError: try: if command_type: command_type = command_type_map.get(command_type) module.cli.add_commands(cmds, output=command_type) response = module.cli.run_commands() else: module.cli.add_commands(cmds, raw=True) response = module.cli.run_commands() except ShellError: clie = get_exception() module.fail_json(msg='Error sending {0}'.format(cmds), error=str(clie)) return response def execute_show_command(command, module, command_type='cli_show'): if module.params['transport'] == 'cli': command += ' | json' cmds = [command] response = execute_show(cmds, module) body = get_cli_body_ssh(command, response, module) elif module.params['transport'] == 'nxapi': cmds = [command] body = execute_show(cmds, module, command_type=command_type) return body def apply_key_map(key_map, table): new_dict = {} for key, value in table.items(): new_key = key_map.get(key) if new_key: value = table.get(key) if value: new_dict[new_key] = str(value) else: new_dict[new_key] = value return new_dict def get_interface_type(interface): if interface.upper().startswith('ET'): return 'ethernet' elif interface.upper().startswith('VL'): return 'svi' elif interface.upper().startswith('LO'): return 'loopback' elif interface.upper().startswith('MG'): return 'management' elif interface.upper().startswith('MA'): return 'management' elif interface.upper().startswith('PO'): return 'portchannel' else: return 'unknown' def get_interface_mode(interface, intf_type, module): command = 'show interface {0}'.format(interface) interface = {} mode = 'unknown' if intf_type in ['ethernet', 'portchannel']: body = execute_show_command(command, module)[0] interface_table = body['TABLE_interface']['ROW_interface'] mode = str(interface_table.get('eth_mode', 'layer3')) if mode == 'access' or mode == 'trunk': mode = 'layer2' elif intf_type == 'svi': mode = 'layer3' return mode def get_hsrp_groups_on_interfaces(device, module): command = 'show hsrp all' body = execute_show_command(command, module) hsrp = {} try: get_data = body[0]['TABLE_grp_detail']['ROW_grp_detail'] except (KeyError, AttributeError): return {} for entry in get_data: interface = str(entry['sh_if_index'].lower()) value = hsrp.get(interface, 'new') if value == 'new': hsrp[interface] = [] group = str(entry['sh_group_num']) hsrp[interface].append(group) return hsrp def get_hsrp_group(group, interface, module): command = 'show hsrp group {0}'.format(group) body = execute_show_command(command, module) hsrp = {} hsrp_key = { 'sh_if_index': 'interface', 'sh_group_num': 'group', 'sh_group_version': 'version', 'sh_cfg_prio': 'priority', 'sh_preempt': 'preempt', 'sh_vip': 'vip', 'sh_authentication_type': 'auth_type', 'sh_authentication_data': 'auth_string' } try: hsrp_table = body[0]['TABLE_grp_detail']['ROW_grp_detail'] except (AttributeError, IndexError, TypeError): return {} if isinstance(hsrp_table, dict): hsrp_table = [hsrp_table] for hsrp_group in hsrp_table: parsed_hsrp = apply_key_map(hsrp_key, hsrp_group) parsed_hsrp['interface'] = parsed_hsrp['interface'].lower() if parsed_hsrp['version'] == 'v1': parsed_hsrp['version'] = '1' elif parsed_hsrp['version'] == 'v2': parsed_hsrp['version'] = '2' if parsed_hsrp['interface'] == interface: return parsed_hsrp return hsrp def get_commands_remove_hsrp(group, interface): commands = [] commands.append('interface {0}'.format(interface)) commands.append('no hsrp {0}'.format(group)) return commands def get_commands_config_hsrp(delta, interface, args): commands = [] config_args = { 'group': 'hsrp {group}', 'priority': 'priority {priority}', 'preempt': '{preempt}', 'vip': 'ip {vip}' } preempt = delta.get('preempt', None) group = delta.get('group', None) if preempt: if preempt == 'enabled': delta['preempt'] = 'preempt' elif preempt == 'disabled': delta['preempt'] = 'no preempt' for key, value in delta.iteritems(): command = config_args.get(key, 'DNE').format(**delta) if command and command != 'DNE': if key == 'group': commands.insert(0, command) else: commands.append(command) command = None auth_type = delta.get('auth_type', None) auth_string = delta.get('auth_string', None) if auth_type or auth_string: if not auth_type: auth_type = args['auth_type'] elif not auth_string: auth_string = args['auth_string'] if auth_type == 'md5': command = 'authentication md5 key-string {0}'.format(auth_string) commands.append(command) elif auth_type == 'text': command = 'authentication text {0}'.format(auth_string) commands.append(command) if commands and not group: commands.insert(0, 'hsrp {0}'.format(args['group'])) version = delta.get('version', None) if version: if version == '2': command = 'hsrp version 2' elif version == '1': command = 'hsrp version 1' commands.insert(0, command) commands.insert(0, 'interface {0}'.format(interface)) if commands: if not commands[0].startswith('interface'): commands.insert(0, 'interface {0}'.format(interface)) return commands def is_default(interface, module): command = 'show run interface {0}'.format(interface) try: body = execute_show_command(command, module)[0] if 'invalid' in body.lower(): return 'DNE' else: raw_list = body.split('\n') if raw_list[-1].startswith('interface'): return True else: return False except (KeyError): return 'DNE' def validate_config(body, vip, module): new_body = ''.join(body) if "invalid ip address" in new_body.lower(): module.fail_json(msg="Invalid VIP. Possible duplicate IP address.", vip=vip) def validate_params(param, module): value = module.params[param] version = module.params['version'] if param == 'group': try: if (int(value) < 0 or int(value) > 255) and version == '1': raise ValueError elif int(value) < 0 or int(value) > 4095: raise ValueError except ValueError: module.fail_json(msg="Warning! 'group' must be an integer between" " 0 and 255 when version 1 and up to 4095 " "when version 2.", group=value, version=version) elif param == 'priority': try: if (int(value) < 0 or int(value) > 255): raise ValueError except ValueError: module.fail_json(msg="Warning! 'priority' must be an integer " "between 0 and 255", priority=value) def main(): argument_spec = dict( group=dict(required=True, type='str'), interface=dict(required=True), version=dict(choices=['1', '2'], default='2', required=False), priority=dict(type='str', required=False), preempt=dict(type='str', choices=['disabled', 'enabled'], required=False), vip=dict(type='str', required=False), auth_type=dict(choices=['text', 'md5'], required=False), auth_string=dict(type='str', required=False), state=dict(choices=['absent', 'present'], required=False, default='present'), include_defaults=dict(default=True), config=dict(), save=dict(type='bool', default=False) ) module = get_network_module(argument_spec=argument_spec, supports_check_mode=True) interface = module.params['interface'].lower() group = module.params['group'] version = module.params['version'] state = module.params['state'] priority = module.params['priority'] preempt = module.params['preempt'] vip = module.params['vip'] auth_type = module.params['auth_type'] auth_string = module.params['auth_string'] transport = module.params['transport'] if state == 'present' and not vip: module.fail_json(msg='the "vip" param is required when state=present') for param in ['group', 'priority']: if module.params[param] is not None: validate_params(param, module) intf_type = get_interface_type(interface) if (intf_type != 'ethernet' and transport == 'cli'): if is_default(interface, module) == 'DNE': module.fail_json(msg='That interface does not exist yet. Create ' 'it first.', interface=interface) if intf_type == 'loopback': module.fail_json(msg="Loopback interfaces don't support HSRP.", interface=interface) mode = get_interface_mode(interface, intf_type, module) if mode == 'layer2': module.fail_json(msg='That interface is a layer2 port.\nMake it ' 'a layer 3 port first.', interface=interface) if auth_type or auth_string: if not (auth_type and auth_string): module.fail_json(msg='When using auth parameters, you need BOTH ' 'auth_type AND auth_string.') args = dict(group=group, version=version, priority=priority, preempt=preempt, vip=vip, auth_type=auth_type, auth_string=auth_string) proposed = dict((k, v) for k, v in args.iteritems() if v is not None) existing = get_hsrp_group(group, interface, module) # This will enforce better practice with md5 and hsrp version. if proposed.get('auth_type', None) == 'md5': if proposed['version'] == '1': module.fail_json(msg="It's recommended to use HSRP v2 " "when auth_type=md5") elif not proposed.get('auth_type', None) and existing: if (proposed['version'] == '1' and existing['auth_type'] == 'md5'): module.fail_json(msg="Existing auth_type is md5. It's recommended " "to use HSRP v2 when using md5") changed = False end_state = existing commands = [] if state == 'present': delta = dict( set(proposed.iteritems()).difference(existing.iteritems())) if delta: command = get_commands_config_hsrp(delta, interface, args) commands.extend(command) elif state == 'absent': if existing: command = get_commands_remove_hsrp(group, interface) commands.extend(command) if commands: if module.check_mode: module.exit_json(changed=True, commands=commands) else: body = execute_config_command(commands, module) if transport == 'cli': validate_config(body, vip, module) changed = True end_state = get_hsrp_group(group, interface, module) if 'configure' in commands: commands.pop(0) results = {} results['proposed'] = proposed results['existing'] = existing results['end_state'] = end_state results['updates'] = commands results['changed'] = changed module.exit_json(**results) if __name__ == '__main__': main()
gpl-3.0
40223114/0519
static/Brython3.1.1-20150328-091302/Lib/multiprocessing/dummy/__init__.py
693
4380
# # Support for the API of the multiprocessing package using threads # # multiprocessing/dummy/__init__.py # # Copyright (c) 2006-2008, R Oudkerk # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # 3. Neither the name of author nor the names of any contributors may be # used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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. # __all__ = [ 'Process', 'current_process', 'active_children', 'freeze_support', 'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Condition', 'Event', 'Barrier', 'Queue', 'Manager', 'Pipe', 'Pool', 'JoinableQueue' ] # # Imports # import threading import sys import weakref #brython fix me #import array from multiprocessing.dummy.connection import Pipe from threading import Lock, RLock, Semaphore, BoundedSemaphore from threading import Event, Condition, Barrier from queue import Queue # # # class DummyProcess(threading.Thread): def __init__(self, group=None, target=None, name=None, args=(), kwargs={}): threading.Thread.__init__(self, group, target, name, args, kwargs) self._pid = None self._children = weakref.WeakKeyDictionary() self._start_called = False self._parent = current_process() def start(self): assert self._parent is current_process() self._start_called = True if hasattr(self._parent, '_children'): self._parent._children[self] = None threading.Thread.start(self) @property def exitcode(self): if self._start_called and not self.is_alive(): return 0 else: return None # # # Process = DummyProcess current_process = threading.current_thread current_process()._children = weakref.WeakKeyDictionary() def active_children(): children = current_process()._children for p in list(children): if not p.is_alive(): children.pop(p, None) return list(children) def freeze_support(): pass # # # class Namespace(object): def __init__(self, **kwds): self.__dict__.update(kwds) def __repr__(self): items = list(self.__dict__.items()) temp = [] for name, value in items: if not name.startswith('_'): temp.append('%s=%r' % (name, value)) temp.sort() return 'Namespace(%s)' % str.join(', ', temp) dict = dict list = list #brython fix me #def Array(typecode, sequence, lock=True): # return array.array(typecode, sequence) class Value(object): def __init__(self, typecode, value, lock=True): self._typecode = typecode self._value = value def _get(self): return self._value def _set(self, value): self._value = value value = property(_get, _set) def __repr__(self): return '<%r(%r, %r)>'%(type(self).__name__,self._typecode,self._value) def Manager(): return sys.modules[__name__] def shutdown(): pass def Pool(processes=None, initializer=None, initargs=()): from multiprocessing.pool import ThreadPool return ThreadPool(processes, initializer, initargs) JoinableQueue = Queue
gpl-3.0
itead/ITEADSW_kernel
modules/wifi/ar6302/AR6K_SDK_ISC.build_3.1_RC.329/host/tools/athbtfilter/bluez/testscripts/bthmonoheadset.py
185
1768
#!/usr/bin/python import dbus import os import sys def printusage(): print 'bthmonoheadset.py <options>' print ' create - create a mono headset' print ' start - connect and play ' print ' stop - stop and disconnect' return headsetAddress = os.getenv("BTMONO_HEADSET") print 'BT Mono Headset Is : => %s' % headsetAddress bus = dbus.SystemBus() manager = dbus.Interface(bus.get_object('org.bluez', '/org/bluez'), 'org.bluez.Manager') bus_id = manager.ActivateService('audio') audio = dbus.Interface(bus.get_object(bus_id, '/org/bluez/audio'), 'org.bluez.audio.Manager') if len(sys.argv) == 1 : printusage() elif len(sys.argv) > 1 and sys.argv[1] == 'create' : path = audio.CreateHeadset(headsetAddress) audio.ChangeDefaultHeadset(path) headset = dbus.Interface (bus.get_object(bus_id, path), 'org.bluez.audio.Headset') headset.Connect() print 'Mono headset setup complete' elif len(sys.argv) > 1 and sys.argv[1] == 'start' : path = audio.DefaultDevice() headset = dbus.Interface (bus.get_object(bus_id, path), 'org.bluez.audio.Headset') if not headset.IsConnected() : headset.Connect() if len(sys.argv) > 2 and sys.argv[2] == 'pcm' : print "Turning on PCM ...." try : headset.Play() except dbus.exceptions.DBusException: print 'Play Failed' elif len(sys.argv) > 1 and sys.argv[1] == 'stop' : path = audio.DefaultDevice() headset = dbus.Interface (bus.get_object(bus_id, path), 'org.bluez.audio.Headset') try : headset.Stop() except dbus.exceptions.DBusException: print 'Stop Failed' headset.Disconnect() print 'Mono headset disconnect complete' elif len(sys.argv) > 1 and sys.argv[1] == 'delete' : path = audio.DefaultDevice() print 'Deleting: %s ' % path audio.RemoveDevice(path)
gpl-2.0
syjeon/new_edx
common/lib/supertrace.py
74
1646
""" A handy util to print a django-debug-screen-like stack trace with values of local variables. """ import sys import traceback from django.utils.encoding import smart_unicode def supertrace(max_len=160): """ Print the usual traceback information, followed by a listing of all the local variables in each frame. Should be called from an exception handler. if max_len is not None, will print up to max_len chars for each local variable. (cite: modified from somewhere on stackoverflow) """ tb = sys.exc_info()[2] while True: if not tb.tb_next: break tb = tb.tb_next stack = [] frame = tb.tb_frame while frame: stack.append(f) frame = frame.f_back stack.reverse() # First print the regular traceback traceback.print_exc() print "Locals by frame, innermost last" for frame in stack: print print "Frame %s in %s at line %s" % (frame.f_code.co_name, frame.f_code.co_filename, frame.f_lineno) for key, value in frame.f_locals.items(): print ("\t%20s = " % smart_unicode(key, errors='ignore')), # We have to be careful not to cause a new error in our error # printer! Calling str() on an unknown object could cause an # error. try: s = smart_unicode(value, errors='ignore') if max_len is not None: s = s[:max_len] print s except: print "<ERROR WHILE PRINTING VALUE>"
agpl-3.0
pacerom/external_skia
gm/rebaseline_server/results_test.py
89
2848
#!/usr/bin/python """ Copyright 2014 Google Inc. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. Test results.py """ # Imports from within Skia import base_unittest import results class ResultsTest(base_unittest.TestCase): def test_ignore_builder(self): """Test _ignore_builder().""" results_obj = results.BaseComparisons() self.assertEqual(results_obj._ignore_builder('SomethingTSAN'), True) self.assertEqual(results_obj._ignore_builder('Something-Trybot'), True) self.assertEqual(results_obj._ignore_builder( 'Test-Ubuntu12-ShuttleA-GTX660-x86-Release'), False) results_obj.set_skip_builders_pattern_list(['.*TSAN.*', '.*GTX660.*']) self.assertEqual(results_obj._ignore_builder('SomethingTSAN'), True) self.assertEqual(results_obj._ignore_builder('Something-Trybot'), False) self.assertEqual(results_obj._ignore_builder( 'Test-Ubuntu12-ShuttleA-GTX660-x86-Release'), True) results_obj.set_skip_builders_pattern_list(None) self.assertEqual(results_obj._ignore_builder('SomethingTSAN'), False) self.assertEqual(results_obj._ignore_builder('Something-Trybot'), False) self.assertEqual(results_obj._ignore_builder( 'Test-Ubuntu12-ShuttleA-GTX660-x86-Release'), False) results_obj.set_match_builders_pattern_list(['.*TSAN']) self.assertEqual(results_obj._ignore_builder('SomethingTSAN'), False) self.assertEqual(results_obj._ignore_builder('Something-Trybot'), True) self.assertEqual(results_obj._ignore_builder( 'Test-Ubuntu12-ShuttleA-GTX660-x86-Release'), True) def test_combine_subdicts_typical(self): """Test combine_subdicts() with no merge conflicts. """ input_dict = { "failed" : { "changed.png" : [ "bitmap-64bitMD5", 8891695120562235492 ], }, "no-comparison" : { "unchanged.png" : [ "bitmap-64bitMD5", 11092453015575919668 ], } } expected_output_dict = { "changed.png" : [ "bitmap-64bitMD5", 8891695120562235492 ], "unchanged.png" : [ "bitmap-64bitMD5", 11092453015575919668 ], } actual_output_dict = results.BaseComparisons.combine_subdicts( input_dict=input_dict) self.assertEqual(actual_output_dict, expected_output_dict) def test_combine_subdicts_with_merge_conflict(self): """Test combine_subdicts() with a merge conflict. """ input_dict = { "failed" : { "changed.png" : [ "bitmap-64bitMD5", 8891695120562235492 ], }, "no-comparison" : { "changed.png" : [ "bitmap-64bitMD5", 11092453015575919668 ], } } with self.assertRaises(Exception): actual_output_dict = results.BaseComparisons.combine_subdicts( input_dict=input_dict) def main(): base_unittest.main(ResultsTest) if __name__ == '__main__': main()
bsd-3-clause
rajul/Pydev
plugins/org.python.pydev/pysrc/pydevd_attach_to_process/winappdbg/process.py
100
183637
#!~/.wine/drive_c/Python25/python.exe # -*- coding: utf-8 -*- # Copyright (c) 2009-2014, Mario Vilas # 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 the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """ Process instrumentation. @group Instrumentation: Process """ from __future__ import with_statement # FIXME # I've been told the host process for the latest versions of VMWare # can't be instrumented, because they try to stop code injection into the VMs. # The solution appears to be to run the debugger from a user account that # belongs to the VMware group. I haven't confirmed this yet. __revision__ = "$Id$" __all__ = ['Process'] import sys from winappdbg import win32 from winappdbg import compat from winappdbg.textio import HexDump, HexInput from winappdbg.util import Regenerator, PathOperations, MemoryAddresses from winappdbg.module import Module, _ModuleContainer from winappdbg.thread import Thread, _ThreadContainer from winappdbg.window import Window from winappdbg.search import Search, \ Pattern, BytePattern, TextPattern, RegExpPattern, HexPattern from winappdbg.disasm import Disassembler import re import os import os.path import ctypes import struct import warnings import traceback # delayed import System = None #============================================================================== # TODO # * Remote GetLastError() # * The memory operation methods do not take into account that code breakpoints # change the memory. This object should talk to BreakpointContainer to # retrieve the original memory contents where code breakpoints are enabled. # * A memory cache could be implemented here. class Process (_ThreadContainer, _ModuleContainer): """ Interface to a process. Contains threads and modules snapshots. @group Properties: get_pid, is_alive, is_debugged, is_wow64, get_arch, get_bits, get_filename, get_exit_code, get_start_time, get_exit_time, get_running_time, get_services, get_dep_policy, get_peb, get_peb_address, get_entry_point, get_main_module, get_image_base, get_image_name, get_command_line, get_environment, get_command_line_block, get_environment_block, get_environment_variables, get_handle, open_handle, close_handle @group Instrumentation: kill, wait, suspend, resume, inject_code, inject_dll, clean_exit @group Disassembly: disassemble, disassemble_around, disassemble_around_pc, disassemble_string, disassemble_instruction, disassemble_current @group Debugging: flush_instruction_cache, debug_break, peek_pointers_in_data @group Memory mapping: take_memory_snapshot, generate_memory_snapshot, iter_memory_snapshot, restore_memory_snapshot, get_memory_map, get_mapped_filenames, generate_memory_map, iter_memory_map, is_pointer, is_address_valid, is_address_free, is_address_reserved, is_address_commited, is_address_guard, is_address_readable, is_address_writeable, is_address_copy_on_write, is_address_executable, is_address_executable_and_writeable, is_buffer, is_buffer_readable, is_buffer_writeable, is_buffer_executable, is_buffer_executable_and_writeable, is_buffer_copy_on_write @group Memory allocation: malloc, free, mprotect, mquery @group Memory read: read, read_char, read_int, read_uint, read_float, read_double, read_dword, read_qword, read_pointer, read_string, read_structure, peek, peek_char, peek_int, peek_uint, peek_float, peek_double, peek_dword, peek_qword, peek_pointer, peek_string @group Memory write: write, write_char, write_int, write_uint, write_float, write_double, write_dword, write_qword, write_pointer, poke, poke_char, poke_int, poke_uint, poke_float, poke_double, poke_dword, poke_qword, poke_pointer @group Memory search: search, search_bytes, search_hexa, search_text, search_regexp, strings @group Processes snapshot: scan, clear, __contains__, __iter__, __len__ @group Deprecated: get_environment_data, parse_environment_data @type dwProcessId: int @ivar dwProcessId: Global process ID. Use L{get_pid} instead. @type hProcess: L{ProcessHandle} @ivar hProcess: Handle to the process. Use L{get_handle} instead. @type fileName: str @ivar fileName: Filename of the main module. Use L{get_filename} instead. """ def __init__(self, dwProcessId, hProcess = None, fileName = None): """ @type dwProcessId: int @param dwProcessId: Global process ID. @type hProcess: L{ProcessHandle} @param hProcess: Handle to the process. @type fileName: str @param fileName: (Optional) Filename of the main module. """ _ThreadContainer.__init__(self) _ModuleContainer.__init__(self) self.dwProcessId = dwProcessId self.hProcess = hProcess self.fileName = fileName def get_pid(self): """ @rtype: int @return: Process global ID. """ return self.dwProcessId def get_filename(self): """ @rtype: str @return: Filename of the main module of the process. """ if not self.fileName: self.fileName = self.get_image_name() return self.fileName def open_handle(self, dwDesiredAccess = win32.PROCESS_ALL_ACCESS): """ Opens a new handle to the process. The new handle is stored in the L{hProcess} property. @warn: Normally you should call L{get_handle} instead, since it's much "smarter" and tries to reuse handles and merge access rights. @type dwDesiredAccess: int @param dwDesiredAccess: Desired access rights. Defaults to L{win32.PROCESS_ALL_ACCESS}. See: U{http://msdn.microsoft.com/en-us/library/windows/desktop/ms684880(v=vs.85).aspx} @raise WindowsError: It's not possible to open a handle to the process with the requested access rights. This tipically happens because the target process is a system process and the debugger is not runnning with administrative rights. """ hProcess = win32.OpenProcess(dwDesiredAccess, win32.FALSE, self.dwProcessId) try: self.close_handle() except Exception: warnings.warn( "Failed to close process handle: %s" % traceback.format_exc()) self.hProcess = hProcess def close_handle(self): """ Closes the handle to the process. @note: Normally you don't need to call this method. All handles created by I{WinAppDbg} are automatically closed when the garbage collector claims them. So unless you've been tinkering with it, setting L{hProcess} to C{None} should be enough. """ try: if hasattr(self.hProcess, 'close'): self.hProcess.close() elif self.hProcess not in (None, win32.INVALID_HANDLE_VALUE): win32.CloseHandle(self.hProcess) finally: self.hProcess = None def get_handle(self, dwDesiredAccess = win32.PROCESS_ALL_ACCESS): """ Returns a handle to the process with I{at least} the access rights requested. @note: If a handle was previously opened and has the required access rights, it's reused. If not, a new handle is opened with the combination of the old and new access rights. @type dwDesiredAccess: int @param dwDesiredAccess: Desired access rights. Defaults to L{win32.PROCESS_ALL_ACCESS}. See: U{http://msdn.microsoft.com/en-us/library/windows/desktop/ms684880(v=vs.85).aspx} @rtype: L{ProcessHandle} @return: Handle to the process. @raise WindowsError: It's not possible to open a handle to the process with the requested access rights. This tipically happens because the target process is a system process and the debugger is not runnning with administrative rights. """ if self.hProcess in (None, win32.INVALID_HANDLE_VALUE): self.open_handle(dwDesiredAccess) else: dwAccess = self.hProcess.dwAccess if (dwAccess | dwDesiredAccess) != dwAccess: self.open_handle(dwAccess | dwDesiredAccess) return self.hProcess #------------------------------------------------------------------------------ # Not really sure if it's a good idea... ## def __eq__(self, aProcess): ## """ ## Compare two Process objects. The comparison is made using the IDs. ## ## @warning: ## If you have two Process instances with different handles the ## equality operator still returns C{True}, so be careful! ## ## @type aProcess: L{Process} ## @param aProcess: Another Process object. ## ## @rtype: bool ## @return: C{True} if the two process IDs are equal, ## C{False} otherwise. ## """ ## return isinstance(aProcess, Process) and \ ## self.get_pid() == aProcess.get_pid() def __contains__(self, anObject): """ The same as: C{self.has_thread(anObject) or self.has_module(anObject)} @type anObject: L{Thread}, L{Module} or int @param anObject: Object to look for. Can be a Thread, Module, thread global ID or module base address. @rtype: bool @return: C{True} if the requested object was found in the snapshot. """ return _ThreadContainer.__contains__(self, anObject) or \ _ModuleContainer.__contains__(self, anObject) def __len__(self): """ @see: L{get_thread_count}, L{get_module_count} @rtype: int @return: Count of L{Thread} and L{Module} objects in this snapshot. """ return _ThreadContainer.__len__(self) + \ _ModuleContainer.__len__(self) class __ThreadsAndModulesIterator (object): """ Iterator object for L{Process} objects. Iterates through L{Thread} objects first, L{Module} objects next. """ def __init__(self, container): """ @type container: L{Process} @param container: L{Thread} and L{Module} container. """ self.__container = container self.__iterator = None self.__state = 0 def __iter__(self): 'x.__iter__() <==> iter(x)' return self def next(self): 'x.next() -> the next value, or raise StopIteration' if self.__state == 0: self.__iterator = self.__container.iter_threads() self.__state = 1 if self.__state == 1: try: return self.__iterator.next() except StopIteration: self.__iterator = self.__container.iter_modules() self.__state = 2 if self.__state == 2: try: return self.__iterator.next() except StopIteration: self.__iterator = None self.__state = 3 raise StopIteration def __iter__(self): """ @see: L{iter_threads}, L{iter_modules} @rtype: iterator @return: Iterator of L{Thread} and L{Module} objects in this snapshot. All threads are iterated first, then all modules. """ return self.__ThreadsAndModulesIterator(self) #------------------------------------------------------------------------------ def wait(self, dwTimeout = None): """ Waits for the process to finish executing. @raise WindowsError: On error an exception is raised. """ self.get_handle(win32.SYNCHRONIZE).wait(dwTimeout) def kill(self, dwExitCode = 0): """ Terminates the execution of the process. @raise WindowsError: On error an exception is raised. """ hProcess = self.get_handle(win32.PROCESS_TERMINATE) win32.TerminateProcess(hProcess, dwExitCode) def suspend(self): """ Suspends execution on all threads of the process. @raise WindowsError: On error an exception is raised. """ self.scan_threads() # force refresh the snapshot suspended = list() try: for aThread in self.iter_threads(): aThread.suspend() suspended.append(aThread) except Exception: for aThread in suspended: try: aThread.resume() except Exception: pass raise def resume(self): """ Resumes execution on all threads of the process. @raise WindowsError: On error an exception is raised. """ if self.get_thread_count() == 0: self.scan_threads() # only refresh the snapshot if empty resumed = list() try: for aThread in self.iter_threads(): aThread.resume() resumed.append(aThread) except Exception: for aThread in resumed: try: aThread.suspend() except Exception: pass raise def is_debugged(self): """ Tries to determine if the process is being debugged by another process. It may detect other debuggers besides WinAppDbg. @rtype: bool @return: C{True} if the process has a debugger attached. @warning: May return inaccurate results when some anti-debug techniques are used by the target process. @note: To know if a process currently being debugged by a L{Debug} object, call L{Debug.is_debugee} instead. """ # FIXME the MSDN docs don't say what access rights are needed here! hProcess = self.get_handle(win32.PROCESS_QUERY_INFORMATION) return win32.CheckRemoteDebuggerPresent(hProcess) def is_alive(self): """ @rtype: bool @return: C{True} if the process is currently running. """ try: self.wait(0) except WindowsError: e = sys.exc_info()[1] return e.winerror == win32.WAIT_TIMEOUT return False def get_exit_code(self): """ @rtype: int @return: Process exit code, or C{STILL_ACTIVE} if it's still alive. @warning: If a process returns C{STILL_ACTIVE} as it's exit code, you may not be able to determine if it's active or not with this method. Use L{is_alive} to check if the process is still active. Alternatively you can call L{get_handle} to get the handle object and then L{ProcessHandle.wait} on it to wait until the process finishes running. """ if win32.PROCESS_ALL_ACCESS == win32.PROCESS_ALL_ACCESS_VISTA: dwAccess = win32.PROCESS_QUERY_LIMITED_INFORMATION else: dwAccess = win32.PROCESS_QUERY_INFORMATION return win32.GetExitCodeProcess( self.get_handle(dwAccess) ) #------------------------------------------------------------------------------ def scan(self): """ Populates the snapshot of threads and modules. """ self.scan_threads() self.scan_modules() def clear(self): """ Clears the snapshot of threads and modules. """ try: try: self.clear_threads() finally: self.clear_modules() finally: self.close_handle() #------------------------------------------------------------------------------ # Regular expression to find hexadecimal values of any size. __hexa_parameter = re.compile('0x[0-9A-Fa-f]+') def __fixup_labels(self, disasm): """ Private method used when disassembling from process memory. It has no return value because the list is modified in place. On return all raw memory addresses are replaced by labels when possible. @type disasm: list of tuple(int, int, str, str) @param disasm: Output of one of the dissassembly functions. """ for index in compat.xrange(len(disasm)): (address, size, text, dump) = disasm[index] m = self.__hexa_parameter.search(text) while m: s, e = m.span() value = text[s:e] try: label = self.get_label_at_address( int(value, 0x10) ) except Exception: label = None if label: text = text[:s] + label + text[e:] e = s + len(value) m = self.__hexa_parameter.search(text, e) disasm[index] = (address, size, text, dump) def disassemble_string(self, lpAddress, code): """ Disassemble instructions from a block of binary code. @type lpAddress: int @param lpAddress: Memory address where the code was read from. @type code: str @param code: Binary code to disassemble. @rtype: list of tuple( long, int, str, str ) @return: List of tuples. Each tuple represents an assembly instruction and contains: - Memory address of instruction. - Size of instruction in bytes. - Disassembly line of instruction. - Hexadecimal dump of instruction. @raise NotImplementedError: No compatible disassembler was found for the current platform. """ try: disasm = self.__disasm except AttributeError: disasm = self.__disasm = Disassembler( self.get_arch() ) return disasm.decode(lpAddress, code) def disassemble(self, lpAddress, dwSize): """ Disassemble instructions from the address space of the process. @type lpAddress: int @param lpAddress: Memory address where to read the code from. @type dwSize: int @param dwSize: Size of binary code to disassemble. @rtype: list of tuple( long, int, str, str ) @return: List of tuples. Each tuple represents an assembly instruction and contains: - Memory address of instruction. - Size of instruction in bytes. - Disassembly line of instruction. - Hexadecimal dump of instruction. """ data = self.read(lpAddress, dwSize) disasm = self.disassemble_string(lpAddress, data) self.__fixup_labels(disasm) return disasm # FIXME # This algorithm really sucks, I've got to write a better one :P def disassemble_around(self, lpAddress, dwSize = 64): """ Disassemble around the given address. @type lpAddress: int @param lpAddress: Memory address where to read the code from. @type dwSize: int @param dwSize: Delta offset. Code will be read from lpAddress - dwSize to lpAddress + dwSize. @rtype: list of tuple( long, int, str, str ) @return: List of tuples. Each tuple represents an assembly instruction and contains: - Memory address of instruction. - Size of instruction in bytes. - Disassembly line of instruction. - Hexadecimal dump of instruction. """ dwDelta = int(float(dwSize) / 2.0) addr_1 = lpAddress - dwDelta addr_2 = lpAddress size_1 = dwDelta size_2 = dwSize - dwDelta data = self.read(addr_1, dwSize) data_1 = data[:size_1] data_2 = data[size_1:] disasm_1 = self.disassemble_string(addr_1, data_1) disasm_2 = self.disassemble_string(addr_2, data_2) disasm = disasm_1 + disasm_2 self.__fixup_labels(disasm) return disasm def disassemble_around_pc(self, dwThreadId, dwSize = 64): """ Disassemble around the program counter of the given thread. @type dwThreadId: int @param dwThreadId: Global thread ID. The program counter for this thread will be used as the disassembly address. @type dwSize: int @param dwSize: Delta offset. Code will be read from pc - dwSize to pc + dwSize. @rtype: list of tuple( long, int, str, str ) @return: List of tuples. Each tuple represents an assembly instruction and contains: - Memory address of instruction. - Size of instruction in bytes. - Disassembly line of instruction. - Hexadecimal dump of instruction. """ aThread = self.get_thread(dwThreadId) return self.disassemble_around(aThread.get_pc(), dwSize) def disassemble_instruction(self, lpAddress): """ Disassemble the instruction at the given memory address. @type lpAddress: int @param lpAddress: Memory address where to read the code from. @rtype: tuple( long, int, str, str ) @return: The tuple represents an assembly instruction and contains: - Memory address of instruction. - Size of instruction in bytes. - Disassembly line of instruction. - Hexadecimal dump of instruction. """ return self.disassemble(lpAddress, 15)[0] def disassemble_current(self, dwThreadId): """ Disassemble the instruction at the program counter of the given thread. @type dwThreadId: int @param dwThreadId: Global thread ID. The program counter for this thread will be used as the disassembly address. @rtype: tuple( long, int, str, str ) @return: The tuple represents an assembly instruction and contains: - Memory address of instruction. - Size of instruction in bytes. - Disassembly line of instruction. - Hexadecimal dump of instruction. """ aThread = self.get_thread(dwThreadId) return self.disassemble_instruction(aThread.get_pc()) #------------------------------------------------------------------------------ def flush_instruction_cache(self): """ Flush the instruction cache. This is required if the process memory is modified and one or more threads are executing nearby the modified memory region. @see: U{http://blogs.msdn.com/oldnewthing/archive/2003/12/08/55954.aspx#55958} @raise WindowsError: Raises exception on error. """ # FIXME # No idea what access rights are required here! # Maybe PROCESS_VM_OPERATION ??? # In any case we're only calling this from the debugger, # so it should be fine (we already have PROCESS_ALL_ACCESS). win32.FlushInstructionCache( self.get_handle() ) def debug_break(self): """ Triggers the system breakpoint in the process. @raise WindowsError: On error an exception is raised. """ # The exception is raised by a new thread. # When continuing the exception, the thread dies by itself. # This thread is hidden from the debugger. win32.DebugBreakProcess( self.get_handle() ) def is_wow64(self): """ Determines if the process is running under WOW64. @rtype: bool @return: C{True} if the process is running under WOW64. That is, a 32-bit application running in a 64-bit Windows. C{False} if the process is either a 32-bit application running in a 32-bit Windows, or a 64-bit application running in a 64-bit Windows. @raise WindowsError: On error an exception is raised. @see: U{http://msdn.microsoft.com/en-us/library/aa384249(VS.85).aspx} """ try: wow64 = self.__wow64 except AttributeError: if (win32.bits == 32 and not win32.wow64): wow64 = False else: if win32.PROCESS_ALL_ACCESS == win32.PROCESS_ALL_ACCESS_VISTA: dwAccess = win32.PROCESS_QUERY_LIMITED_INFORMATION else: dwAccess = win32.PROCESS_QUERY_INFORMATION hProcess = self.get_handle(dwAccess) try: wow64 = win32.IsWow64Process(hProcess) except AttributeError: wow64 = False self.__wow64 = wow64 return wow64 def get_arch(self): """ @rtype: str @return: The architecture in which this process believes to be running. For example, if running a 32 bit binary in a 64 bit machine, the architecture returned by this method will be L{win32.ARCH_I386}, but the value of L{System.arch} will be L{win32.ARCH_AMD64}. """ # Are we in a 32 bit machine? if win32.bits == 32 and not win32.wow64: return win32.arch # Is the process outside of WOW64? if not self.is_wow64(): return win32.arch # In WOW64, "amd64" becomes "i386". if win32.arch == win32.ARCH_AMD64: return win32.ARCH_I386 # We don't know the translation for other architectures. raise NotImplementedError() def get_bits(self): """ @rtype: str @return: The number of bits in which this process believes to be running. For example, if running a 32 bit binary in a 64 bit machine, the number of bits returned by this method will be C{32}, but the value of L{System.arch} will be C{64}. """ # Are we in a 32 bit machine? if win32.bits == 32 and not win32.wow64: # All processes are 32 bits. return 32 # Is the process inside WOW64? if self.is_wow64(): # The process is 32 bits. return 32 # The process is 64 bits. return 64 # TODO: get_os, to test compatibility run # See: http://msdn.microsoft.com/en-us/library/windows/desktop/ms683224(v=vs.85).aspx #------------------------------------------------------------------------------ def get_start_time(self): """ Determines when has this process started running. @rtype: win32.SYSTEMTIME @return: Process start time. """ if win32.PROCESS_ALL_ACCESS == win32.PROCESS_ALL_ACCESS_VISTA: dwAccess = win32.PROCESS_QUERY_LIMITED_INFORMATION else: dwAccess = win32.PROCESS_QUERY_INFORMATION hProcess = self.get_handle(dwAccess) CreationTime = win32.GetProcessTimes(hProcess)[0] return win32.FileTimeToSystemTime(CreationTime) def get_exit_time(self): """ Determines when has this process finished running. If the process is still alive, the current time is returned instead. @rtype: win32.SYSTEMTIME @return: Process exit time. """ if self.is_alive(): ExitTime = win32.GetSystemTimeAsFileTime() else: if win32.PROCESS_ALL_ACCESS == win32.PROCESS_ALL_ACCESS_VISTA: dwAccess = win32.PROCESS_QUERY_LIMITED_INFORMATION else: dwAccess = win32.PROCESS_QUERY_INFORMATION hProcess = self.get_handle(dwAccess) ExitTime = win32.GetProcessTimes(hProcess)[1] return win32.FileTimeToSystemTime(ExitTime) def get_running_time(self): """ Determines how long has this process been running. @rtype: long @return: Process running time in milliseconds. """ if win32.PROCESS_ALL_ACCESS == win32.PROCESS_ALL_ACCESS_VISTA: dwAccess = win32.PROCESS_QUERY_LIMITED_INFORMATION else: dwAccess = win32.PROCESS_QUERY_INFORMATION hProcess = self.get_handle(dwAccess) (CreationTime, ExitTime, _, _) = win32.GetProcessTimes(hProcess) if self.is_alive(): ExitTime = win32.GetSystemTimeAsFileTime() CreationTime = CreationTime.dwLowDateTime + (CreationTime.dwHighDateTime << 32) ExitTime = ExitTime.dwLowDateTime + ( ExitTime.dwHighDateTime << 32) RunningTime = ExitTime - CreationTime return RunningTime / 10000 # 100 nanoseconds steps => milliseconds #------------------------------------------------------------------------------ def __load_System_class(self): global System # delayed import if System is None: from system import System def get_services(self): """ Retrieves the list of system services that are currently running in this process. @see: L{System.get_services} @rtype: list( L{win32.ServiceStatusProcessEntry} ) @return: List of service status descriptors. """ self.__load_System_class() pid = self.get_pid() return [d for d in System.get_active_services() if d.ProcessId == pid] #------------------------------------------------------------------------------ def get_dep_policy(self): """ Retrieves the DEP (Data Execution Prevention) policy for this process. @note: This method is only available in Windows XP SP3 and above, and only for 32 bit processes. It will fail in any other circumstance. @see: U{http://msdn.microsoft.com/en-us/library/bb736297(v=vs.85).aspx} @rtype: tuple(int, int) @return: The first member of the tuple is the DEP flags. It can be a combination of the following values: - 0: DEP is disabled for this process. - 1: DEP is enabled for this process. (C{PROCESS_DEP_ENABLE}) - 2: DEP-ATL thunk emulation is disabled for this process. (C{PROCESS_DEP_DISABLE_ATL_THUNK_EMULATION}) The second member of the tuple is the permanent flag. If C{TRUE} the DEP settings cannot be changed in runtime for this process. @raise WindowsError: On error an exception is raised. """ hProcess = self.get_handle(win32.PROCESS_QUERY_INFORMATION) try: return win32.kernel32.GetProcessDEPPolicy(hProcess) except AttributeError: msg = "This method is only available in Windows XP SP3 and above." raise NotImplementedError(msg) #------------------------------------------------------------------------------ def get_peb(self): """ Returns a copy of the PEB. To dereference pointers in it call L{Process.read_structure}. @rtype: L{win32.PEB} @return: PEB structure. @raise WindowsError: An exception is raised on error. """ self.get_handle( win32.PROCESS_VM_READ | win32.PROCESS_QUERY_INFORMATION ) return self.read_structure(self.get_peb_address(), win32.PEB) def get_peb_address(self): """ Returns a remote pointer to the PEB. @rtype: int @return: Remote pointer to the L{win32.PEB} structure. Returns C{None} on error. """ try: return self._peb_ptr except AttributeError: hProcess = self.get_handle(win32.PROCESS_QUERY_INFORMATION) pbi = win32.NtQueryInformationProcess(hProcess, win32.ProcessBasicInformation) address = pbi.PebBaseAddress self._peb_ptr = address return address def get_entry_point(self): """ Alias to C{process.get_main_module().get_entry_point()}. @rtype: int @return: Address of the entry point of the main module. """ return self.get_main_module().get_entry_point() def get_main_module(self): """ @rtype: L{Module} @return: Module object for the process main module. """ return self.get_module(self.get_image_base()) def get_image_base(self): """ @rtype: int @return: Image base address for the process main module. """ return self.get_peb().ImageBaseAddress def get_image_name(self): """ @rtype: int @return: Filename of the process main module. This method does it's best to retrieve the filename. However sometimes this is not possible, so C{None} may be returned instead. """ # Method 1: Module.fileName # It's cached if the filename was already found by the other methods, # if it came with the corresponding debug event, or it was found by the # toolhelp API. mainModule = None try: mainModule = self.get_main_module() name = mainModule.fileName if not name: name = None except (KeyError, AttributeError, WindowsError): ## traceback.print_exc() # XXX DEBUG name = None # Method 2: QueryFullProcessImageName() # Not implemented until Windows Vista. if not name: try: hProcess = self.get_handle( win32.PROCESS_QUERY_LIMITED_INFORMATION) name = win32.QueryFullProcessImageName(hProcess) except (AttributeError, WindowsError): ## traceback.print_exc() # XXX DEBUG name = None # Method 3: GetProcessImageFileName() # # Not implemented until Windows XP. # For more info see: # https://voidnish.wordpress.com/2005/06/20/getprocessimagefilenamequerydosdevice-trivia/ if not name: try: hProcess = self.get_handle(win32.PROCESS_QUERY_INFORMATION) name = win32.GetProcessImageFileName(hProcess) if name: name = PathOperations.native_to_win32_pathname(name) else: name = None except (AttributeError, WindowsError): ## traceback.print_exc() # XXX DEBUG if not name: name = None # Method 4: GetModuleFileNameEx() # Not implemented until Windows 2000. # # May be spoofed by malware, since this information resides # in usermode space (see http://www.ragestorm.net/blogs/?p=163). if not name: try: hProcess = self.get_handle( win32.PROCESS_VM_READ | win32.PROCESS_QUERY_INFORMATION ) try: name = win32.GetModuleFileNameEx(hProcess) except WindowsError: ## traceback.print_exc() # XXX DEBUG name = win32.GetModuleFileNameEx( hProcess, self.get_image_base()) if name: name = PathOperations.native_to_win32_pathname(name) else: name = None except (AttributeError, WindowsError): ## traceback.print_exc() # XXX DEBUG if not name: name = None # Method 5: PEB.ProcessParameters->ImagePathName # # May fail since it's using an undocumented internal structure. # # May be spoofed by malware, since this information resides # in usermode space (see http://www.ragestorm.net/blogs/?p=163). if not name: try: peb = self.get_peb() pp = self.read_structure(peb.ProcessParameters, win32.RTL_USER_PROCESS_PARAMETERS) s = pp.ImagePathName name = self.peek_string(s.Buffer, dwMaxSize=s.MaximumLength, fUnicode=True) if name: name = PathOperations.native_to_win32_pathname(name) else: name = None except (AttributeError, WindowsError): ## traceback.print_exc() # XXX DEBUG name = None # Method 6: Module.get_filename() # It tries to get the filename from the file handle. # # There are currently some problems due to the strange way the API # works - it returns the pathname without the drive letter, and I # couldn't figure out a way to fix it. if not name and mainModule is not None: try: name = mainModule.get_filename() if not name: name = None except (AttributeError, WindowsError): ## traceback.print_exc() # XXX DEBUG name = None # Remember the filename. if name and mainModule is not None: mainModule.fileName = name # Return the image filename, or None on error. return name def get_command_line_block(self): """ Retrieves the command line block memory address and size. @rtype: tuple(int, int) @return: Tuple with the memory address of the command line block and it's maximum size in Unicode characters. @raise WindowsError: On error an exception is raised. """ peb = self.get_peb() pp = self.read_structure(peb.ProcessParameters, win32.RTL_USER_PROCESS_PARAMETERS) s = pp.CommandLine return (s.Buffer, s.MaximumLength) def get_environment_block(self): """ Retrieves the environment block memory address for the process. @note: The size is always enough to contain the environment data, but it may not be an exact size. It's best to read the memory and scan for two null wide chars to find the actual size. @rtype: tuple(int, int) @return: Tuple with the memory address of the environment block and it's size. @raise WindowsError: On error an exception is raised. """ peb = self.get_peb() pp = self.read_structure(peb.ProcessParameters, win32.RTL_USER_PROCESS_PARAMETERS) Environment = pp.Environment try: EnvironmentSize = pp.EnvironmentSize except AttributeError: mbi = self.mquery(Environment) EnvironmentSize = mbi.RegionSize + mbi.BaseAddress - Environment return (Environment, EnvironmentSize) def get_command_line(self): """ Retrieves the command line with wich the program was started. @rtype: str @return: Command line string. @raise WindowsError: On error an exception is raised. """ (Buffer, MaximumLength) = self.get_command_line_block() CommandLine = self.peek_string(Buffer, dwMaxSize=MaximumLength, fUnicode=True) gst = win32.GuessStringType if gst.t_default == gst.t_ansi: CommandLine = CommandLine.encode('cp1252') return CommandLine def get_environment_variables(self): """ Retrieves the environment variables with wich the program is running. @rtype: list of tuple(compat.unicode, compat.unicode) @return: Environment keys and values as found in the process memory. @raise WindowsError: On error an exception is raised. """ # Note: the first bytes are garbage and must be skipped. Then the first # two environment entries are the current drive and directory as key # and value pairs, followed by the ExitCode variable (it's what batch # files know as "errorlevel"). After that, the real environment vars # are there in alphabetical order. In theory that's where it stops, # but I've always seen one more "variable" tucked at the end which # may be another environment block but in ANSI. I haven't examined it # yet, I'm just skipping it because if it's parsed as Unicode it just # renders garbage. # Read the environment block contents. data = self.peek( *self.get_environment_block() ) # Put them into a Unicode buffer. tmp = ctypes.create_string_buffer(data) buffer = ctypes.create_unicode_buffer(len(data)) ctypes.memmove(buffer, tmp, len(data)) del tmp # Skip until the first Unicode null char is found. pos = 0 while buffer[pos] != u'\0': pos += 1 pos += 1 # Loop for each environment variable... environment = [] while buffer[pos] != u'\0': # Until we find a null char... env_name_pos = pos env_name = u'' found_name = False while buffer[pos] != u'\0': # Get the current char. char = buffer[pos] # Is it an equal sign? if char == u'=': # Skip leading equal signs. if env_name_pos == pos: env_name_pos += 1 pos += 1 continue # Otherwise we found the separator equal sign. pos += 1 found_name = True break # Add the char to the variable name. env_name += char # Next char. pos += 1 # If the name was not parsed properly, stop. if not found_name: break # Read the variable value until we find a null char. env_value = u'' while buffer[pos] != u'\0': env_value += buffer[pos] pos += 1 # Skip the null char. pos += 1 # Add to the list of environment variables found. environment.append( (env_name, env_value) ) # Remove the last entry, it's garbage. if environment: environment.pop() # Return the environment variables. return environment def get_environment_data(self, fUnicode = None): """ Retrieves the environment block data with wich the program is running. @warn: Deprecated since WinAppDbg 1.5. @see: L{win32.GuessStringType} @type fUnicode: bool or None @param fUnicode: C{True} to return a list of Unicode strings, C{False} to return a list of ANSI strings, or C{None} to return whatever the default is for string types. @rtype: list of str @return: Environment keys and values separated by a (C{=}) character, as found in the process memory. @raise WindowsError: On error an exception is raised. """ # Issue a deprecation warning. warnings.warn( "Process.get_environment_data() is deprecated" \ " since WinAppDbg 1.5.", DeprecationWarning) # Get the environment variables. block = [ key + u'=' + value for (key, value) \ in self.get_environment_variables() ] # Convert the data to ANSI if requested. if fUnicode is None: gst = win32.GuessStringType fUnicode = gst.t_default == gst.t_unicode if not fUnicode: block = [x.encode('cp1252') for x in block] # Return the environment data. return block @staticmethod def parse_environment_data(block): """ Parse the environment block into a Python dictionary. @warn: Deprecated since WinAppDbg 1.5. @note: Values of duplicated keys are joined using null characters. @type block: list of str @param block: List of strings as returned by L{get_environment_data}. @rtype: dict(str S{->} str) @return: Dictionary of environment keys and values. """ # Issue a deprecation warning. warnings.warn( "Process.parse_environment_data() is deprecated" \ " since WinAppDbg 1.5.", DeprecationWarning) # Create an empty environment dictionary. environment = dict() # End here if the environment block is empty. if not block: return environment # Prepare the tokens (ANSI or Unicode). gst = win32.GuessStringType if type(block[0]) == gst.t_ansi: equals = '=' terminator = '\0' else: equals = u'=' terminator = u'\0' # Split the blocks into key/value pairs. for chunk in block: sep = chunk.find(equals, 1) if sep < 0: ## raise Exception() continue # corrupted environment block? key, value = chunk[:sep], chunk[sep+1:] # For duplicated keys, append the value. # Values are separated using null terminators. if key not in environment: environment[key] = value else: environment[key] += terminator + value # Return the environment dictionary. return environment def get_environment(self, fUnicode = None): """ Retrieves the environment with wich the program is running. @note: Duplicated keys are joined using null characters. To avoid this behavior, call L{get_environment_variables} instead and convert the results to a dictionary directly, like this: C{dict(process.get_environment_variables())} @see: L{win32.GuessStringType} @type fUnicode: bool or None @param fUnicode: C{True} to return a list of Unicode strings, C{False} to return a list of ANSI strings, or C{None} to return whatever the default is for string types. @rtype: dict(str S{->} str) @return: Dictionary of environment keys and values. @raise WindowsError: On error an exception is raised. """ # Get the environment variables. variables = self.get_environment_variables() # Convert the strings to ANSI if requested. if fUnicode is None: gst = win32.GuessStringType fUnicode = gst.t_default == gst.t_unicode if not fUnicode: variables = [ ( key.encode('cp1252'), value.encode('cp1252') ) \ for (key, value) in variables ] # Add the variables to a dictionary, concatenating duplicates. environment = dict() for key, value in variables: if key in environment: environment[key] = environment[key] + u'\0' + value else: environment[key] = value # Return the dictionary. return environment #------------------------------------------------------------------------------ def search(self, pattern, minAddr = None, maxAddr = None): """ Search for the given pattern within the process memory. @type pattern: str, compat.unicode or L{Pattern} @param pattern: Pattern to search for. It may be a byte string, a Unicode string, or an instance of L{Pattern}. The following L{Pattern} subclasses are provided by WinAppDbg: - L{BytePattern} - L{TextPattern} - L{RegExpPattern} - L{HexPattern} You can also write your own subclass of L{Pattern} for customized searches. @type minAddr: int @param minAddr: (Optional) Start the search at this memory address. @type maxAddr: int @param maxAddr: (Optional) Stop the search at this memory address. @rtype: iterator of tuple( int, int, str ) @return: An iterator of tuples. Each tuple contains the following: - The memory address where the pattern was found. - The size of the data that matches the pattern. - The data that matches the pattern. @raise WindowsError: An error occurred when querying or reading the process memory. """ if isinstance(pattern, str): return self.search_bytes(pattern, minAddr, maxAddr) if isinstance(pattern, compat.unicode): return self.search_bytes(pattern.encode("utf-16le"), minAddr, maxAddr) if isinstance(pattern, Pattern): return Search.search_process(self, pattern, minAddr, maxAddr) raise TypeError("Unknown pattern type: %r" % type(pattern)) def search_bytes(self, bytes, minAddr = None, maxAddr = None): """ Search for the given byte pattern within the process memory. @type bytes: str @param bytes: Bytes to search for. @type minAddr: int @param minAddr: (Optional) Start the search at this memory address. @type maxAddr: int @param maxAddr: (Optional) Stop the search at this memory address. @rtype: iterator of int @return: An iterator of memory addresses where the pattern was found. @raise WindowsError: An error occurred when querying or reading the process memory. """ pattern = BytePattern(bytes) matches = Search.search_process(self, pattern, minAddr, maxAddr) for addr, size, data in matches: yield addr def search_text(self, text, encoding = "utf-16le", caseSensitive = False, minAddr = None, maxAddr = None): """ Search for the given text within the process memory. @type text: str or compat.unicode @param text: Text to search for. @type encoding: str @param encoding: (Optional) Encoding for the text parameter. Only used when the text to search for is a Unicode string. Don't change unless you know what you're doing! @type caseSensitive: bool @param caseSensitive: C{True} of the search is case sensitive, C{False} otherwise. @type minAddr: int @param minAddr: (Optional) Start the search at this memory address. @type maxAddr: int @param maxAddr: (Optional) Stop the search at this memory address. @rtype: iterator of tuple( int, str ) @return: An iterator of tuples. Each tuple contains the following: - The memory address where the pattern was found. - The text that matches the pattern. @raise WindowsError: An error occurred when querying or reading the process memory. """ pattern = TextPattern(text, encoding, caseSensitive) matches = Search.search_process(self, pattern, minAddr, maxAddr) for addr, size, data in matches: yield addr, data def search_regexp(self, regexp, flags = 0, minAddr = None, maxAddr = None, bufferPages = -1): """ Search for the given regular expression within the process memory. @type regexp: str @param regexp: Regular expression string. @type flags: int @param flags: Regular expression flags. @type minAddr: int @param minAddr: (Optional) Start the search at this memory address. @type maxAddr: int @param maxAddr: (Optional) Stop the search at this memory address. @type bufferPages: int @param bufferPages: (Optional) Number of memory pages to buffer when performing the search. Valid values are: - C{0} or C{None}: Automatically determine the required buffer size. May not give complete results for regular expressions that match variable sized strings. - C{> 0}: Set the buffer size, in memory pages. - C{< 0}: Disable buffering entirely. This may give you a little speed gain at the cost of an increased memory usage. If the target process has very large contiguous memory regions it may actually be slower or even fail. It's also the only way to guarantee complete results for regular expressions that match variable sized strings. @rtype: iterator of tuple( int, int, str ) @return: An iterator of tuples. Each tuple contains the following: - The memory address where the pattern was found. - The size of the data that matches the pattern. - The data that matches the pattern. @raise WindowsError: An error occurred when querying or reading the process memory. """ pattern = RegExpPattern(regexp, flags) return Search.search_process(self, pattern, minAddr, maxAddr, bufferPages) def search_hexa(self, hexa, minAddr = None, maxAddr = None): """ Search for the given hexadecimal pattern within the process memory. Hex patterns must be in this form:: "68 65 6c 6c 6f 20 77 6f 72 6c 64" # "hello world" Spaces are optional. Capitalization of hex digits doesn't matter. This is exactly equivalent to the previous example:: "68656C6C6F20776F726C64" # "hello world" Wildcards are allowed, in the form of a C{?} sign in any hex digit:: "5? 5? c3" # pop register / pop register / ret "b8 ?? ?? ?? ??" # mov eax, immediate value @type hexa: str @param hexa: Pattern to search for. @type minAddr: int @param minAddr: (Optional) Start the search at this memory address. @type maxAddr: int @param maxAddr: (Optional) Stop the search at this memory address. @rtype: iterator of tuple( int, str ) @return: An iterator of tuples. Each tuple contains the following: - The memory address where the pattern was found. - The bytes that match the pattern. @raise WindowsError: An error occurred when querying or reading the process memory. """ pattern = HexPattern(hexa) matches = Search.search_process(self, pattern, minAddr, maxAddr) for addr, size, data in matches: yield addr, data def strings(self, minSize = 4, maxSize = 1024): """ Extract ASCII strings from the process memory. @type minSize: int @param minSize: (Optional) Minimum size of the strings to search for. @type maxSize: int @param maxSize: (Optional) Maximum size of the strings to search for. @rtype: iterator of tuple(int, int, str) @return: Iterator of strings extracted from the process memory. Each tuple contains the following: - The memory address where the string was found. - The size of the string. - The string. """ return Search.extract_ascii_strings(self, minSize = minSize, maxSize = maxSize) #------------------------------------------------------------------------------ def __read_c_type(self, address, format, c_type): size = ctypes.sizeof(c_type) packed = self.read(address, size) if len(packed) != size: raise ctypes.WinError() return struct.unpack(format, packed)[0] def __write_c_type(self, address, format, unpacked): packed = struct.pack('@L', unpacked) self.write(address, packed) # XXX TODO # + Maybe change page permissions before trying to read? def read(self, lpBaseAddress, nSize): """ Reads from the memory of the process. @see: L{peek} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @type nSize: int @param nSize: Number of bytes to read. @rtype: str @return: Bytes read from the process memory. @raise WindowsError: On error an exception is raised. """ hProcess = self.get_handle( win32.PROCESS_VM_READ | win32.PROCESS_QUERY_INFORMATION ) if not self.is_buffer(lpBaseAddress, nSize): raise ctypes.WinError(win32.ERROR_INVALID_ADDRESS) data = win32.ReadProcessMemory(hProcess, lpBaseAddress, nSize) if len(data) != nSize: raise ctypes.WinError() return data def write(self, lpBaseAddress, lpBuffer): """ Writes to the memory of the process. @note: Page permissions may be changed temporarily while writing. @see: L{poke} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin writing. @type lpBuffer: str @param lpBuffer: Bytes to write. @raise WindowsError: On error an exception is raised. """ r = self.poke(lpBaseAddress, lpBuffer) if r != len(lpBuffer): raise ctypes.WinError() def read_char(self, lpBaseAddress): """ Reads a single character to the memory of the process. @see: L{peek_char} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin writing. @rtype: int @return: Character value read from the process memory. @raise WindowsError: On error an exception is raised. """ return ord( self.read(lpBaseAddress, 1) ) def write_char(self, lpBaseAddress, char): """ Writes a single character to the memory of the process. @note: Page permissions may be changed temporarily while writing. @see: L{poke_char} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin writing. @type char: int @param char: Character to write. @raise WindowsError: On error an exception is raised. """ self.write(lpBaseAddress, chr(char)) def read_int(self, lpBaseAddress): """ Reads a signed integer from the memory of the process. @see: L{peek_int} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @rtype: int @return: Integer value read from the process memory. @raise WindowsError: On error an exception is raised. """ return self.__read_c_type(lpBaseAddress, compat.b('@l'), ctypes.c_int) def write_int(self, lpBaseAddress, unpackedValue): """ Writes a signed integer to the memory of the process. @note: Page permissions may be changed temporarily while writing. @see: L{poke_int} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin writing. @type unpackedValue: int, long @param unpackedValue: Value to write. @raise WindowsError: On error an exception is raised. """ self.__write_c_type(lpBaseAddress, '@l', unpackedValue) def read_uint(self, lpBaseAddress): """ Reads an unsigned integer from the memory of the process. @see: L{peek_uint} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @rtype: int @return: Integer value read from the process memory. @raise WindowsError: On error an exception is raised. """ return self.__read_c_type(lpBaseAddress, '@L', ctypes.c_uint) def write_uint(self, lpBaseAddress, unpackedValue): """ Writes an unsigned integer to the memory of the process. @note: Page permissions may be changed temporarily while writing. @see: L{poke_uint} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin writing. @type unpackedValue: int, long @param unpackedValue: Value to write. @raise WindowsError: On error an exception is raised. """ self.__write_c_type(lpBaseAddress, '@L', unpackedValue) def read_float(self, lpBaseAddress): """ Reads a float from the memory of the process. @see: L{peek_float} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @rtype: int @return: Floating point value read from the process memory. @raise WindowsError: On error an exception is raised. """ return self.__read_c_type(lpBaseAddress, '@f', ctypes.c_float) def write_float(self, lpBaseAddress, unpackedValue): """ Writes a float to the memory of the process. @note: Page permissions may be changed temporarily while writing. @see: L{poke_float} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin writing. @type unpackedValue: int, long @param unpackedValue: Floating point value to write. @raise WindowsError: On error an exception is raised. """ self.__write_c_type(lpBaseAddress, '@f', unpackedValue) def read_double(self, lpBaseAddress): """ Reads a double from the memory of the process. @see: L{peek_double} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @rtype: int @return: Floating point value read from the process memory. @raise WindowsError: On error an exception is raised. """ return self.__read_c_type(lpBaseAddress, '@d', ctypes.c_double) def write_double(self, lpBaseAddress, unpackedValue): """ Writes a double to the memory of the process. @note: Page permissions may be changed temporarily while writing. @see: L{poke_double} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin writing. @type unpackedValue: int, long @param unpackedValue: Floating point value to write. @raise WindowsError: On error an exception is raised. """ self.__write_c_type(lpBaseAddress, '@d', unpackedValue) def read_pointer(self, lpBaseAddress): """ Reads a pointer value from the memory of the process. @see: L{peek_pointer} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @rtype: int @return: Pointer value read from the process memory. @raise WindowsError: On error an exception is raised. """ return self.__read_c_type(lpBaseAddress, '@P', ctypes.c_void_p) def write_pointer(self, lpBaseAddress, unpackedValue): """ Writes a pointer value to the memory of the process. @note: Page permissions may be changed temporarily while writing. @see: L{poke_pointer} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin writing. @type unpackedValue: int, long @param unpackedValue: Value to write. @raise WindowsError: On error an exception is raised. """ self.__write_c_type(lpBaseAddress, '@P', unpackedValue) def read_dword(self, lpBaseAddress): """ Reads a DWORD from the memory of the process. @see: L{peek_dword} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @rtype: int @return: Integer value read from the process memory. @raise WindowsError: On error an exception is raised. """ return self.__read_c_type(lpBaseAddress, '=L', win32.DWORD) def write_dword(self, lpBaseAddress, unpackedValue): """ Writes a DWORD to the memory of the process. @note: Page permissions may be changed temporarily while writing. @see: L{poke_dword} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin writing. @type unpackedValue: int, long @param unpackedValue: Value to write. @raise WindowsError: On error an exception is raised. """ self.__write_c_type(lpBaseAddress, '=L', unpackedValue) def read_qword(self, lpBaseAddress): """ Reads a QWORD from the memory of the process. @see: L{peek_qword} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @rtype: int @return: Integer value read from the process memory. @raise WindowsError: On error an exception is raised. """ return self.__read_c_type(lpBaseAddress, '=Q', win32.QWORD) def write_qword(self, lpBaseAddress, unpackedValue): """ Writes a QWORD to the memory of the process. @note: Page permissions may be changed temporarily while writing. @see: L{poke_qword} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin writing. @type unpackedValue: int, long @param unpackedValue: Value to write. @raise WindowsError: On error an exception is raised. """ self.__write_c_type(lpBaseAddress, '=Q', unpackedValue) def read_structure(self, lpBaseAddress, stype): """ Reads a ctypes structure from the memory of the process. @see: L{read} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @type stype: class ctypes.Structure or a subclass. @param stype: Structure definition. @rtype: int @return: Structure instance filled in with data read from the process memory. @raise WindowsError: On error an exception is raised. """ if type(lpBaseAddress) not in (type(0), type(long(0))): lpBaseAddress = ctypes.cast(lpBaseAddress, ctypes.c_void_p) data = self.read(lpBaseAddress, ctypes.sizeof(stype)) buff = ctypes.create_string_buffer(data) ptr = ctypes.cast(ctypes.pointer(buff), ctypes.POINTER(stype)) return ptr.contents # XXX TODO ## def write_structure(self, lpBaseAddress, sStructure): ## """ ## Writes a ctypes structure into the memory of the process. ## ## @note: Page permissions may be changed temporarily while writing. ## ## @see: L{write} ## ## @type lpBaseAddress: int ## @param lpBaseAddress: Memory address to begin writing. ## ## @type sStructure: ctypes.Structure or a subclass' instance. ## @param sStructure: Structure definition. ## ## @rtype: int ## @return: Structure instance filled in with data ## read from the process memory. ## ## @raise WindowsError: On error an exception is raised. ## """ ## size = ctypes.sizeof(sStructure) ## data = ctypes.create_string_buffer("", size = size) ## win32.CopyMemory(ctypes.byref(data), ctypes.byref(sStructure), size) ## self.write(lpBaseAddress, data.raw) def read_string(self, lpBaseAddress, nChars, fUnicode = False): """ Reads an ASCII or Unicode string from the address space of the process. @see: L{peek_string} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @type nChars: int @param nChars: String length to read, in characters. Remember that Unicode strings have two byte characters. @type fUnicode: bool @param fUnicode: C{True} is the string is expected to be Unicode, C{False} if it's expected to be ANSI. @rtype: str, compat.unicode @return: String read from the process memory space. @raise WindowsError: On error an exception is raised. """ if fUnicode: nChars = nChars * 2 szString = self.read(lpBaseAddress, nChars) if fUnicode: szString = compat.unicode(szString, 'U16', 'ignore') return szString #------------------------------------------------------------------------------ # FIXME this won't work properly with a different endianness! def __peek_c_type(self, address, format, c_type): size = ctypes.sizeof(c_type) packed = self.peek(address, size) if len(packed) < size: packed = '\0' * (size - len(packed)) + packed elif len(packed) > size: packed = packed[:size] return struct.unpack(format, packed)[0] def __poke_c_type(self, address, format, unpacked): packed = struct.pack('@L', unpacked) return self.poke(address, packed) def peek(self, lpBaseAddress, nSize): """ Reads the memory of the process. @see: L{read} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @type nSize: int @param nSize: Number of bytes to read. @rtype: str @return: Bytes read from the process memory. Returns an empty string on error. """ # XXX TODO # + Maybe change page permissions before trying to read? # + Maybe use mquery instead of get_memory_map? # (less syscalls if we break out of the loop earlier) data = '' if nSize > 0: try: hProcess = self.get_handle( win32.PROCESS_VM_READ | win32.PROCESS_QUERY_INFORMATION ) for mbi in self.get_memory_map(lpBaseAddress, lpBaseAddress + nSize): if not mbi.is_readable(): nSize = mbi.BaseAddress - lpBaseAddress break if nSize > 0: data = win32.ReadProcessMemory( hProcess, lpBaseAddress, nSize) except WindowsError: e = sys.exc_info()[1] msg = "Error reading process %d address %s: %s" msg %= (self.get_pid(), HexDump.address(lpBaseAddress), e.strerror) warnings.warn(msg) return data def poke(self, lpBaseAddress, lpBuffer): """ Writes to the memory of the process. @note: Page permissions may be changed temporarily while writing. @see: L{write} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin writing. @type lpBuffer: str @param lpBuffer: Bytes to write. @rtype: int @return: Number of bytes written. May be less than the number of bytes to write. """ assert isinstance(lpBuffer, compat.bytes) hProcess = self.get_handle( win32.PROCESS_VM_WRITE | win32.PROCESS_VM_OPERATION | win32.PROCESS_QUERY_INFORMATION ) mbi = self.mquery(lpBaseAddress) if not mbi.has_content(): raise ctypes.WinError(win32.ERROR_INVALID_ADDRESS) if mbi.is_image() or mbi.is_mapped(): prot = win32.PAGE_WRITECOPY elif mbi.is_writeable(): prot = None elif mbi.is_executable(): prot = win32.PAGE_EXECUTE_READWRITE else: prot = win32.PAGE_READWRITE if prot is not None: try: self.mprotect(lpBaseAddress, len(lpBuffer), prot) except Exception: prot = None msg = ("Failed to adjust page permissions" " for process %s at address %s: %s") msg = msg % (self.get_pid(), HexDump.address(lpBaseAddress, self.get_bits()), traceback.format_exc()) warnings.warn(msg, RuntimeWarning) try: r = win32.WriteProcessMemory(hProcess, lpBaseAddress, lpBuffer) finally: if prot is not None: self.mprotect(lpBaseAddress, len(lpBuffer), mbi.Protect) return r def peek_char(self, lpBaseAddress): """ Reads a single character from the memory of the process. @see: L{read_char} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @rtype: int @return: Character read from the process memory. Returns zero on error. """ char = self.peek(lpBaseAddress, 1) if char: return ord(char) return 0 def poke_char(self, lpBaseAddress, char): """ Writes a single character to the memory of the process. @note: Page permissions may be changed temporarily while writing. @see: L{write_char} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin writing. @type char: str @param char: Character to write. @rtype: int @return: Number of bytes written. May be less than the number of bytes to write. """ return self.poke(lpBaseAddress, chr(char)) def peek_int(self, lpBaseAddress): """ Reads a signed integer from the memory of the process. @see: L{read_int} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @rtype: int @return: Integer value read from the process memory. Returns zero on error. """ return self.__peek_c_type(lpBaseAddress, '@l', ctypes.c_int) def poke_int(self, lpBaseAddress, unpackedValue): """ Writes a signed integer to the memory of the process. @note: Page permissions may be changed temporarily while writing. @see: L{write_int} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin writing. @type unpackedValue: int, long @param unpackedValue: Value to write. @rtype: int @return: Number of bytes written. May be less than the number of bytes to write. """ return self.__poke_c_type(lpBaseAddress, '@l', unpackedValue) def peek_uint(self, lpBaseAddress): """ Reads an unsigned integer from the memory of the process. @see: L{read_uint} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @rtype: int @return: Integer value read from the process memory. Returns zero on error. """ return self.__peek_c_type(lpBaseAddress, '@L', ctypes.c_uint) def poke_uint(self, lpBaseAddress, unpackedValue): """ Writes an unsigned integer to the memory of the process. @note: Page permissions may be changed temporarily while writing. @see: L{write_uint} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin writing. @type unpackedValue: int, long @param unpackedValue: Value to write. @rtype: int @return: Number of bytes written. May be less than the number of bytes to write. """ return self.__poke_c_type(lpBaseAddress, '@L', unpackedValue) def peek_float(self, lpBaseAddress): """ Reads a float from the memory of the process. @see: L{read_float} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @rtype: int @return: Integer value read from the process memory. Returns zero on error. """ return self.__peek_c_type(lpBaseAddress, '@f', ctypes.c_float) def poke_float(self, lpBaseAddress, unpackedValue): """ Writes a float to the memory of the process. @note: Page permissions may be changed temporarily while writing. @see: L{write_float} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin writing. @type unpackedValue: int, long @param unpackedValue: Value to write. @rtype: int @return: Number of bytes written. May be less than the number of bytes to write. """ return self.__poke_c_type(lpBaseAddress, '@f', unpackedValue) def peek_double(self, lpBaseAddress): """ Reads a double from the memory of the process. @see: L{read_double} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @rtype: int @return: Integer value read from the process memory. Returns zero on error. """ return self.__peek_c_type(lpBaseAddress, '@d', ctypes.c_double) def poke_double(self, lpBaseAddress, unpackedValue): """ Writes a double to the memory of the process. @note: Page permissions may be changed temporarily while writing. @see: L{write_double} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin writing. @type unpackedValue: int, long @param unpackedValue: Value to write. @rtype: int @return: Number of bytes written. May be less than the number of bytes to write. """ return self.__poke_c_type(lpBaseAddress, '@d', unpackedValue) def peek_dword(self, lpBaseAddress): """ Reads a DWORD from the memory of the process. @see: L{read_dword} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @rtype: int @return: Integer value read from the process memory. Returns zero on error. """ return self.__peek_c_type(lpBaseAddress, '=L', win32.DWORD) def poke_dword(self, lpBaseAddress, unpackedValue): """ Writes a DWORD to the memory of the process. @note: Page permissions may be changed temporarily while writing. @see: L{write_dword} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin writing. @type unpackedValue: int, long @param unpackedValue: Value to write. @rtype: int @return: Number of bytes written. May be less than the number of bytes to write. """ return self.__poke_c_type(lpBaseAddress, '=L', unpackedValue) def peek_qword(self, lpBaseAddress): """ Reads a QWORD from the memory of the process. @see: L{read_qword} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @rtype: int @return: Integer value read from the process memory. Returns zero on error. """ return self.__peek_c_type(lpBaseAddress, '=Q', win32.QWORD) def poke_qword(self, lpBaseAddress, unpackedValue): """ Writes a QWORD to the memory of the process. @note: Page permissions may be changed temporarily while writing. @see: L{write_qword} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin writing. @type unpackedValue: int, long @param unpackedValue: Value to write. @rtype: int @return: Number of bytes written. May be less than the number of bytes to write. """ return self.__poke_c_type(lpBaseAddress, '=Q', unpackedValue) def peek_pointer(self, lpBaseAddress): """ Reads a pointer value from the memory of the process. @see: L{read_pointer} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @rtype: int @return: Pointer value read from the process memory. Returns zero on error. """ return self.__peek_c_type(lpBaseAddress, '@P', ctypes.c_void_p) def poke_pointer(self, lpBaseAddress, unpackedValue): """ Writes a pointer value to the memory of the process. @note: Page permissions may be changed temporarily while writing. @see: L{write_pointer} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin writing. @type unpackedValue: int, long @param unpackedValue: Value to write. @rtype: int @return: Number of bytes written. May be less than the number of bytes to write. """ return self.__poke_c_type(lpBaseAddress, '@P', unpackedValue) def peek_string(self, lpBaseAddress, fUnicode = False, dwMaxSize = 0x1000): """ Tries to read an ASCII or Unicode string from the address space of the process. @see: L{read_string} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @type fUnicode: bool @param fUnicode: C{True} is the string is expected to be Unicode, C{False} if it's expected to be ANSI. @type dwMaxSize: int @param dwMaxSize: Maximum allowed string length to read, in bytes. @rtype: str, compat.unicode @return: String read from the process memory space. It B{doesn't} include the terminating null character. Returns an empty string on failure. """ # Validate the parameters. if not lpBaseAddress or dwMaxSize == 0: if fUnicode: return u'' return '' if not dwMaxSize: dwMaxSize = 0x1000 # Read the string. szString = self.peek(lpBaseAddress, dwMaxSize) # If the string is Unicode... if fUnicode: # Decode the string. szString = compat.unicode(szString, 'U16', 'replace') ## try: ## szString = compat.unicode(szString, 'U16') ## except UnicodeDecodeError: ## szString = struct.unpack('H' * (len(szString) / 2), szString) ## szString = [ unichr(c) for c in szString ] ## szString = u''.join(szString) # Truncate the string when the first null char is found. szString = szString[ : szString.find(u'\0') ] # If the string is ANSI... else: # Truncate the string when the first null char is found. szString = szString[ : szString.find('\0') ] # Return the decoded string. return szString # TODO # try to avoid reading the same page twice by caching it def peek_pointers_in_data(self, data, peekSize = 16, peekStep = 1): """ Tries to guess which values in the given data are valid pointers, and reads some data from them. @see: L{peek} @type data: str @param data: Binary data to find pointers in. @type peekSize: int @param peekSize: Number of bytes to read from each pointer found. @type peekStep: int @param peekStep: Expected data alignment. Tipically you specify 1 when data alignment is unknown, or 4 when you expect data to be DWORD aligned. Any other value may be specified. @rtype: dict( str S{->} str ) @return: Dictionary mapping stack offsets to the data they point to. """ result = dict() ptrSize = win32.sizeof(win32.LPVOID) if ptrSize == 4: ptrFmt = '<L' else: ptrFmt = '<Q' if len(data) > 0: for i in compat.xrange(0, len(data), peekStep): packed = data[i:i+ptrSize] if len(packed) == ptrSize: address = struct.unpack(ptrFmt, packed)[0] ## if not address & (~0xFFFF): continue peek_data = self.peek(address, peekSize) if peek_data: result[i] = peek_data return result #------------------------------------------------------------------------------ def malloc(self, dwSize, lpAddress = None): """ Allocates memory into the address space of the process. @see: L{free} @type dwSize: int @param dwSize: Number of bytes to allocate. @type lpAddress: int @param lpAddress: (Optional) Desired address for the newly allocated memory. This is only a hint, the memory could still be allocated somewhere else. @rtype: int @return: Address of the newly allocated memory. @raise WindowsError: On error an exception is raised. """ hProcess = self.get_handle(win32.PROCESS_VM_OPERATION) return win32.VirtualAllocEx(hProcess, lpAddress, dwSize) def mprotect(self, lpAddress, dwSize, flNewProtect): """ Set memory protection in the address space of the process. @see: U{http://msdn.microsoft.com/en-us/library/aa366899.aspx} @type lpAddress: int @param lpAddress: Address of memory to protect. @type dwSize: int @param dwSize: Number of bytes to protect. @type flNewProtect: int @param flNewProtect: New protect flags. @rtype: int @return: Old protect flags. @raise WindowsError: On error an exception is raised. """ hProcess = self.get_handle(win32.PROCESS_VM_OPERATION) return win32.VirtualProtectEx(hProcess, lpAddress, dwSize, flNewProtect) def mquery(self, lpAddress): """ Query memory information from the address space of the process. Returns a L{win32.MemoryBasicInformation} object. @see: U{http://msdn.microsoft.com/en-us/library/aa366907(VS.85).aspx} @type lpAddress: int @param lpAddress: Address of memory to query. @rtype: L{win32.MemoryBasicInformation} @return: Memory region information. @raise WindowsError: On error an exception is raised. """ hProcess = self.get_handle(win32.PROCESS_QUERY_INFORMATION) return win32.VirtualQueryEx(hProcess, lpAddress) def free(self, lpAddress): """ Frees memory from the address space of the process. @see: U{http://msdn.microsoft.com/en-us/library/aa366894(v=vs.85).aspx} @type lpAddress: int @param lpAddress: Address of memory to free. Must be the base address returned by L{malloc}. @raise WindowsError: On error an exception is raised. """ hProcess = self.get_handle(win32.PROCESS_VM_OPERATION) win32.VirtualFreeEx(hProcess, lpAddress) #------------------------------------------------------------------------------ def is_pointer(self, address): """ Determines if an address is a valid code or data pointer. That is, the address must be valid and must point to code or data in the target process. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address is a valid code or data pointer. @raise WindowsError: An exception is raised on error. """ try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return mbi.has_content() def is_address_valid(self, address): """ Determines if an address is a valid user mode address. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address is a valid user mode address. @raise WindowsError: An exception is raised on error. """ try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return True def is_address_free(self, address): """ Determines if an address belongs to a free page. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address belongs to a free page. @raise WindowsError: An exception is raised on error. """ try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return mbi.is_free() def is_address_reserved(self, address): """ Determines if an address belongs to a reserved page. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address belongs to a reserved page. @raise WindowsError: An exception is raised on error. """ try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return mbi.is_reserved() def is_address_commited(self, address): """ Determines if an address belongs to a commited page. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address belongs to a commited page. @raise WindowsError: An exception is raised on error. """ try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return mbi.is_commited() def is_address_guard(self, address): """ Determines if an address belongs to a guard page. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address belongs to a guard page. @raise WindowsError: An exception is raised on error. """ try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return mbi.is_guard() def is_address_readable(self, address): """ Determines if an address belongs to a commited and readable page. The page may or may not have additional permissions. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address belongs to a commited and readable page. @raise WindowsError: An exception is raised on error. """ try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return mbi.is_readable() def is_address_writeable(self, address): """ Determines if an address belongs to a commited and writeable page. The page may or may not have additional permissions. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address belongs to a commited and writeable page. @raise WindowsError: An exception is raised on error. """ try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return mbi.is_writeable() def is_address_copy_on_write(self, address): """ Determines if an address belongs to a commited, copy-on-write page. The page may or may not have additional permissions. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address belongs to a commited, copy-on-write page. @raise WindowsError: An exception is raised on error. """ try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return mbi.is_copy_on_write() def is_address_executable(self, address): """ Determines if an address belongs to a commited and executable page. The page may or may not have additional permissions. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address belongs to a commited and executable page. @raise WindowsError: An exception is raised on error. """ try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return mbi.is_executable() def is_address_executable_and_writeable(self, address): """ Determines if an address belongs to a commited, writeable and executable page. The page may or may not have additional permissions. Looking for writeable and executable pages is important when exploiting a software vulnerability. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address belongs to a commited, writeable and executable page. @raise WindowsError: An exception is raised on error. """ try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return mbi.is_executable_and_writeable() def is_buffer(self, address, size): """ Determines if the given memory area is a valid code or data buffer. @note: Returns always C{False} for kernel mode addresses. @see: L{mquery} @type address: int @param address: Memory address. @type size: int @param size: Number of bytes. Must be greater than zero. @rtype: bool @return: C{True} if the memory area is a valid code or data buffer, C{False} otherwise. @raise ValueError: The size argument must be greater than zero. @raise WindowsError: On error an exception is raised. """ if size <= 0: raise ValueError("The size argument must be greater than zero") while size > 0: try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise if not mbi.has_content(): return False size = size - mbi.RegionSize return True def is_buffer_readable(self, address, size): """ Determines if the given memory area is readable. @note: Returns always C{False} for kernel mode addresses. @see: L{mquery} @type address: int @param address: Memory address. @type size: int @param size: Number of bytes. Must be greater than zero. @rtype: bool @return: C{True} if the memory area is readable, C{False} otherwise. @raise ValueError: The size argument must be greater than zero. @raise WindowsError: On error an exception is raised. """ if size <= 0: raise ValueError("The size argument must be greater than zero") while size > 0: try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise if not mbi.is_readable(): return False size = size - mbi.RegionSize return True def is_buffer_writeable(self, address, size): """ Determines if the given memory area is writeable. @note: Returns always C{False} for kernel mode addresses. @see: L{mquery} @type address: int @param address: Memory address. @type size: int @param size: Number of bytes. Must be greater than zero. @rtype: bool @return: C{True} if the memory area is writeable, C{False} otherwise. @raise ValueError: The size argument must be greater than zero. @raise WindowsError: On error an exception is raised. """ if size <= 0: raise ValueError("The size argument must be greater than zero") while size > 0: try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise if not mbi.is_writeable(): return False size = size - mbi.RegionSize return True def is_buffer_copy_on_write(self, address, size): """ Determines if the given memory area is marked as copy-on-write. @note: Returns always C{False} for kernel mode addresses. @see: L{mquery} @type address: int @param address: Memory address. @type size: int @param size: Number of bytes. Must be greater than zero. @rtype: bool @return: C{True} if the memory area is marked as copy-on-write, C{False} otherwise. @raise ValueError: The size argument must be greater than zero. @raise WindowsError: On error an exception is raised. """ if size <= 0: raise ValueError("The size argument must be greater than zero") while size > 0: try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise if not mbi.is_copy_on_write(): return False size = size - mbi.RegionSize return True def is_buffer_executable(self, address, size): """ Determines if the given memory area is executable. @note: Returns always C{False} for kernel mode addresses. @see: L{mquery} @type address: int @param address: Memory address. @type size: int @param size: Number of bytes. Must be greater than zero. @rtype: bool @return: C{True} if the memory area is executable, C{False} otherwise. @raise ValueError: The size argument must be greater than zero. @raise WindowsError: On error an exception is raised. """ if size <= 0: raise ValueError("The size argument must be greater than zero") while size > 0: try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise if not mbi.is_executable(): return False size = size - mbi.RegionSize return True def is_buffer_executable_and_writeable(self, address, size): """ Determines if the given memory area is writeable and executable. Looking for writeable and executable pages is important when exploiting a software vulnerability. @note: Returns always C{False} for kernel mode addresses. @see: L{mquery} @type address: int @param address: Memory address. @type size: int @param size: Number of bytes. Must be greater than zero. @rtype: bool @return: C{True} if the memory area is writeable and executable, C{False} otherwise. @raise ValueError: The size argument must be greater than zero. @raise WindowsError: On error an exception is raised. """ if size <= 0: raise ValueError("The size argument must be greater than zero") while size > 0: try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise if not mbi.is_executable(): return False size = size - mbi.RegionSize return True def get_memory_map(self, minAddr = None, maxAddr = None): """ Produces a memory map to the process address space. Optionally restrict the map to the given address range. @see: L{mquery} @type minAddr: int @param minAddr: (Optional) Starting address in address range to query. @type maxAddr: int @param maxAddr: (Optional) Ending address in address range to query. @rtype: list( L{win32.MemoryBasicInformation} ) @return: List of memory region information objects. """ return list(self.iter_memory_map(minAddr, maxAddr)) def generate_memory_map(self, minAddr = None, maxAddr = None): """ Returns a L{Regenerator} that can iterate indefinitely over the memory map to the process address space. Optionally restrict the map to the given address range. @see: L{mquery} @type minAddr: int @param minAddr: (Optional) Starting address in address range to query. @type maxAddr: int @param maxAddr: (Optional) Ending address in address range to query. @rtype: L{Regenerator} of L{win32.MemoryBasicInformation} @return: List of memory region information objects. """ return Regenerator(self.iter_memory_map, minAddr, maxAddr) def iter_memory_map(self, minAddr = None, maxAddr = None): """ Produces an iterator over the memory map to the process address space. Optionally restrict the map to the given address range. @see: L{mquery} @type minAddr: int @param minAddr: (Optional) Starting address in address range to query. @type maxAddr: int @param maxAddr: (Optional) Ending address in address range to query. @rtype: iterator of L{win32.MemoryBasicInformation} @return: List of memory region information objects. """ minAddr, maxAddr = MemoryAddresses.align_address_range(minAddr,maxAddr) prevAddr = minAddr - 1 currentAddr = minAddr while prevAddr < currentAddr < maxAddr: try: mbi = self.mquery(currentAddr) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: break raise yield mbi prevAddr = currentAddr currentAddr = mbi.BaseAddress + mbi.RegionSize def get_mapped_filenames(self, memoryMap = None): """ Retrieves the filenames for memory mapped files in the debugee. @type memoryMap: list( L{win32.MemoryBasicInformation} ) @param memoryMap: (Optional) Memory map returned by L{get_memory_map}. If not given, the current memory map is used. @rtype: dict( int S{->} str ) @return: Dictionary mapping memory addresses to file names. Native filenames are converted to Win32 filenames when possible. """ hProcess = self.get_handle( win32.PROCESS_VM_READ | win32.PROCESS_QUERY_INFORMATION ) if not memoryMap: memoryMap = self.get_memory_map() mappedFilenames = dict() for mbi in memoryMap: if mbi.Type not in (win32.MEM_IMAGE, win32.MEM_MAPPED): continue baseAddress = mbi.BaseAddress fileName = "" try: fileName = win32.GetMappedFileName(hProcess, baseAddress) fileName = PathOperations.native_to_win32_pathname(fileName) except WindowsError: #e = sys.exc_info()[1] #try: # msg = "Can't get mapped file name at address %s in process " \ # "%d, reason: %s" % (HexDump.address(baseAddress), # self.get_pid(), # e.strerror) # warnings.warn(msg, Warning) #except Exception: pass mappedFilenames[baseAddress] = fileName return mappedFilenames def generate_memory_snapshot(self, minAddr = None, maxAddr = None): """ Returns a L{Regenerator} that allows you to iterate through the memory contents of a process indefinitely. It's basically the same as the L{take_memory_snapshot} method, but it takes the snapshot of each memory region as it goes, as opposed to taking the whole snapshot at once. This allows you to work with very large snapshots without a significant performance penalty. Example:: # Print the memory contents of a process. process.suspend() try: snapshot = process.generate_memory_snapshot() for mbi in snapshot: print HexDump.hexblock(mbi.content, mbi.BaseAddress) finally: process.resume() The downside of this is the process must remain suspended while iterating the snapshot, otherwise strange things may happen. The snapshot can be iterated more than once. Each time it's iterated the memory contents of the process will be fetched again. You can also iterate the memory of a dead process, just as long as the last open handle to it hasn't been closed. @see: L{take_memory_snapshot} @type minAddr: int @param minAddr: (Optional) Starting address in address range to query. @type maxAddr: int @param maxAddr: (Optional) Ending address in address range to query. @rtype: L{Regenerator} of L{win32.MemoryBasicInformation} @return: Generator that when iterated returns memory region information objects. Two extra properties are added to these objects: - C{filename}: Mapped filename, or C{None}. - C{content}: Memory contents, or C{None}. """ return Regenerator(self.iter_memory_snapshot, minAddr, maxAddr) def iter_memory_snapshot(self, minAddr = None, maxAddr = None): """ Returns an iterator that allows you to go through the memory contents of a process. It's basically the same as the L{take_memory_snapshot} method, but it takes the snapshot of each memory region as it goes, as opposed to taking the whole snapshot at once. This allows you to work with very large snapshots without a significant performance penalty. Example:: # Print the memory contents of a process. process.suspend() try: snapshot = process.generate_memory_snapshot() for mbi in snapshot: print HexDump.hexblock(mbi.content, mbi.BaseAddress) finally: process.resume() The downside of this is the process must remain suspended while iterating the snapshot, otherwise strange things may happen. The snapshot can only iterated once. To be able to iterate indefinitely call the L{generate_memory_snapshot} method instead. You can also iterate the memory of a dead process, just as long as the last open handle to it hasn't been closed. @see: L{take_memory_snapshot} @type minAddr: int @param minAddr: (Optional) Starting address in address range to query. @type maxAddr: int @param maxAddr: (Optional) Ending address in address range to query. @rtype: iterator of L{win32.MemoryBasicInformation} @return: Iterator of memory region information objects. Two extra properties are added to these objects: - C{filename}: Mapped filename, or C{None}. - C{content}: Memory contents, or C{None}. """ # One may feel tempted to include calls to self.suspend() and # self.resume() here, but that wouldn't work on a dead process. # It also wouldn't be needed when debugging since the process is # already suspended when the debug event arrives. So it's up to # the user to suspend the process if needed. # Get the memory map. memory = self.get_memory_map(minAddr, maxAddr) # Abort if the map couldn't be retrieved. if not memory: return # Get the mapped filenames. # Don't fail on access denied errors. try: filenames = self.get_mapped_filenames(memory) except WindowsError: e = sys.exc_info()[1] if e.winerror != win32.ERROR_ACCESS_DENIED: raise filenames = dict() # Trim the first memory information block if needed. if minAddr is not None: minAddr = MemoryAddresses.align_address_to_page_start(minAddr) mbi = memory[0] if mbi.BaseAddress < minAddr: mbi.RegionSize = mbi.BaseAddress + mbi.RegionSize - minAddr mbi.BaseAddress = minAddr # Trim the last memory information block if needed. if maxAddr is not None: if maxAddr != MemoryAddresses.align_address_to_page_start(maxAddr): maxAddr = MemoryAddresses.align_address_to_page_end(maxAddr) mbi = memory[-1] if mbi.BaseAddress + mbi.RegionSize > maxAddr: mbi.RegionSize = maxAddr - mbi.BaseAddress # Read the contents of each block and yield it. while memory: mbi = memory.pop(0) # so the garbage collector can take it mbi.filename = filenames.get(mbi.BaseAddress, None) if mbi.has_content(): mbi.content = self.read(mbi.BaseAddress, mbi.RegionSize) else: mbi.content = None yield mbi def take_memory_snapshot(self, minAddr = None, maxAddr = None): """ Takes a snapshot of the memory contents of the process. It's best if the process is suspended (if alive) when taking the snapshot. Execution can be resumed afterwards. Example:: # Print the memory contents of a process. process.suspend() try: snapshot = process.take_memory_snapshot() for mbi in snapshot: print HexDump.hexblock(mbi.content, mbi.BaseAddress) finally: process.resume() You can also iterate the memory of a dead process, just as long as the last open handle to it hasn't been closed. @warning: If the target process has a very big memory footprint, the resulting snapshot will be equally big. This may result in a severe performance penalty. @see: L{generate_memory_snapshot} @type minAddr: int @param minAddr: (Optional) Starting address in address range to query. @type maxAddr: int @param maxAddr: (Optional) Ending address in address range to query. @rtype: list( L{win32.MemoryBasicInformation} ) @return: List of memory region information objects. Two extra properties are added to these objects: - C{filename}: Mapped filename, or C{None}. - C{content}: Memory contents, or C{None}. """ return list( self.iter_memory_snapshot(minAddr, maxAddr) ) def restore_memory_snapshot(self, snapshot, bSkipMappedFiles = True, bSkipOnError = False): """ Attempts to restore the memory state as it was when the given snapshot was taken. @warning: Currently only the memory contents, state and protect bits are restored. Under some circumstances this method may fail (for example if memory was freed and then reused by a mapped file). @type snapshot: list( L{win32.MemoryBasicInformation} ) @param snapshot: Memory snapshot returned by L{take_memory_snapshot}. Snapshots returned by L{generate_memory_snapshot} don't work here. @type bSkipMappedFiles: bool @param bSkipMappedFiles: C{True} to avoid restoring the contents of memory mapped files, C{False} otherwise. Use with care! Setting this to C{False} can cause undesired side effects - changes to memory mapped files may be written to disk by the OS. Also note that most mapped files are typically executables and don't change, so trying to restore their contents is usually a waste of time. @type bSkipOnError: bool @param bSkipOnError: C{True} to issue a warning when an error occurs during the restoration of the snapshot, C{False} to stop and raise an exception instead. Use with care! Setting this to C{True} will cause the debugger to falsely believe the memory snapshot has been correctly restored. @raise WindowsError: An error occured while restoring the snapshot. @raise RuntimeError: An error occured while restoring the snapshot. @raise TypeError: A snapshot of the wrong type was passed. """ if not snapshot or not isinstance(snapshot, list) \ or not isinstance(snapshot[0], win32.MemoryBasicInformation): raise TypeError( "Only snapshots returned by " \ "take_memory_snapshot() can be used here." ) # Get the process handle. hProcess = self.get_handle( win32.PROCESS_VM_WRITE | win32.PROCESS_VM_OPERATION | win32.PROCESS_SUSPEND_RESUME | win32.PROCESS_QUERY_INFORMATION ) # Freeze the process. self.suspend() try: # For each memory region in the snapshot... for old_mbi in snapshot: # If the region matches, restore it directly. new_mbi = self.mquery(old_mbi.BaseAddress) if new_mbi.BaseAddress == old_mbi.BaseAddress and \ new_mbi.RegionSize == old_mbi.RegionSize: self.__restore_mbi(hProcess, new_mbi, old_mbi, bSkipMappedFiles) # If the region doesn't match, restore it page by page. else: # We need a copy so we don't corrupt the snapshot. old_mbi = win32.MemoryBasicInformation(old_mbi) # Get the overlapping range of pages. old_start = old_mbi.BaseAddress old_end = old_start + old_mbi.RegionSize new_start = new_mbi.BaseAddress new_end = new_start + new_mbi.RegionSize if old_start > new_start: start = old_start else: start = new_start if old_end < new_end: end = old_end else: end = new_end # Restore each page in the overlapping range. step = MemoryAddresses.pageSize old_mbi.RegionSize = step new_mbi.RegionSize = step address = start while address < end: old_mbi.BaseAddress = address new_mbi.BaseAddress = address self.__restore_mbi(hProcess, new_mbi, old_mbi, bSkipMappedFiles, bSkipOnError) address = address + step # Resume execution. finally: self.resume() def __restore_mbi(self, hProcess, new_mbi, old_mbi, bSkipMappedFiles, bSkipOnError): """ Used internally by L{restore_memory_snapshot}. """ ## print "Restoring %s-%s" % ( ## HexDump.address(old_mbi.BaseAddress, self.get_bits()), ## HexDump.address(old_mbi.BaseAddress + old_mbi.RegionSize, ## self.get_bits())) try: # Restore the region state. if new_mbi.State != old_mbi.State: if new_mbi.is_free(): if old_mbi.is_reserved(): # Free -> Reserved address = win32.VirtualAllocEx(hProcess, old_mbi.BaseAddress, old_mbi.RegionSize, win32.MEM_RESERVE, old_mbi.Protect) if address != old_mbi.BaseAddress: self.free(address) msg = "Error restoring region at address %s" msg = msg % HexDump(old_mbi.BaseAddress, self.get_bits()) raise RuntimeError(msg) # permissions already restored new_mbi.Protect = old_mbi.Protect else: # elif old_mbi.is_commited(): # Free -> Commited address = win32.VirtualAllocEx(hProcess, old_mbi.BaseAddress, old_mbi.RegionSize, win32.MEM_RESERVE | \ win32.MEM_COMMIT, old_mbi.Protect) if address != old_mbi.BaseAddress: self.free(address) msg = "Error restoring region at address %s" msg = msg % HexDump(old_mbi.BaseAddress, self.get_bits()) raise RuntimeError(msg) # permissions already restored new_mbi.Protect = old_mbi.Protect elif new_mbi.is_reserved(): if old_mbi.is_commited(): # Reserved -> Commited address = win32.VirtualAllocEx(hProcess, old_mbi.BaseAddress, old_mbi.RegionSize, win32.MEM_COMMIT, old_mbi.Protect) if address != old_mbi.BaseAddress: self.free(address) msg = "Error restoring region at address %s" msg = msg % HexDump(old_mbi.BaseAddress, self.get_bits()) raise RuntimeError(msg) # permissions already restored new_mbi.Protect = old_mbi.Protect else: # elif old_mbi.is_free(): # Reserved -> Free win32.VirtualFreeEx(hProcess, old_mbi.BaseAddress, old_mbi.RegionSize, win32.MEM_RELEASE) else: # elif new_mbi.is_commited(): if old_mbi.is_reserved(): # Commited -> Reserved win32.VirtualFreeEx(hProcess, old_mbi.BaseAddress, old_mbi.RegionSize, win32.MEM_DECOMMIT) else: # elif old_mbi.is_free(): # Commited -> Free win32.VirtualFreeEx(hProcess, old_mbi.BaseAddress, old_mbi.RegionSize, win32.MEM_DECOMMIT | win32.MEM_RELEASE) new_mbi.State = old_mbi.State # Restore the region permissions. if old_mbi.is_commited() and old_mbi.Protect != new_mbi.Protect: win32.VirtualProtectEx(hProcess, old_mbi.BaseAddress, old_mbi.RegionSize, old_mbi.Protect) new_mbi.Protect = old_mbi.Protect # Restore the region data. # Ignore write errors when the region belongs to a mapped file. if old_mbi.has_content(): if old_mbi.Type != 0: if not bSkipMappedFiles: self.poke(old_mbi.BaseAddress, old_mbi.content) else: self.write(old_mbi.BaseAddress, old_mbi.content) new_mbi.content = old_mbi.content # On error, skip this region or raise an exception. except Exception: if not bSkipOnError: raise msg = "Error restoring region at address %s: %s" msg = msg % ( HexDump(old_mbi.BaseAddress, self.get_bits()), traceback.format_exc()) warnings.warn(msg, RuntimeWarning) #------------------------------------------------------------------------------ def inject_code(self, payload, lpParameter = 0): """ Injects relocatable code into the process memory and executes it. @warning: Don't forget to free the memory when you're done with it! Otherwise you'll be leaking memory in the target process. @see: L{inject_dll} @type payload: str @param payload: Relocatable code to run in a new thread. @type lpParameter: int @param lpParameter: (Optional) Parameter to be pushed in the stack. @rtype: tuple( L{Thread}, int ) @return: The injected Thread object and the memory address where the code was written. @raise WindowsError: An exception is raised on error. """ # Uncomment for debugging... ## payload = '\xCC' + payload # Allocate the memory for the shellcode. lpStartAddress = self.malloc(len(payload)) # Catch exceptions so we can free the memory on error. try: # Write the shellcode to our memory location. self.write(lpStartAddress, payload) # Start a new thread for the shellcode to run. aThread = self.start_thread(lpStartAddress, lpParameter, bSuspended = False) # Remember the shellcode address. # It will be freed ONLY by the Thread.kill() method # and the EventHandler class, otherwise you'll have to # free it in your code, or have your shellcode clean up # after itself (recommended). aThread.pInjectedMemory = lpStartAddress # Free the memory on error. except Exception: self.free(lpStartAddress) raise # Return the Thread object and the shellcode address. return aThread, lpStartAddress # TODO # The shellcode should check for errors, otherwise it just crashes # when the DLL can't be loaded or the procedure can't be found. # On error the shellcode should execute an int3 instruction. def inject_dll(self, dllname, procname = None, lpParameter = 0, bWait = True, dwTimeout = None): """ Injects a DLL into the process memory. @warning: Setting C{bWait} to C{True} when the process is frozen by a debug event will cause a deadlock in your debugger. @warning: This involves allocating memory in the target process. This is how the freeing of this memory is handled: - If the C{bWait} flag is set to C{True} the memory will be freed automatically before returning from this method. - If the C{bWait} flag is set to C{False}, the memory address is set as the L{Thread.pInjectedMemory} property of the returned thread object. - L{Debug} objects free L{Thread.pInjectedMemory} automatically both when it detaches from a process and when the injected thread finishes its execution. - The {Thread.kill} method also frees L{Thread.pInjectedMemory} automatically, even if you're not attached to the process. You could still be leaking memory if not careful. For example, if you inject a dll into a process you're not attached to, you don't wait for the thread's completion and you don't kill it either, the memory would be leaked. @see: L{inject_code} @type dllname: str @param dllname: Name of the DLL module to load. @type procname: str @param procname: (Optional) Procedure to call when the DLL is loaded. @type lpParameter: int @param lpParameter: (Optional) Parameter to the C{procname} procedure. @type bWait: bool @param bWait: C{True} to wait for the process to finish. C{False} to return immediately. @type dwTimeout: int @param dwTimeout: (Optional) Timeout value in milliseconds. Ignored if C{bWait} is C{False}. @rtype: L{Thread} @return: Newly created thread object. If C{bWait} is set to C{True} the thread will be dead, otherwise it will be alive. @raise NotImplementedError: The target platform is not supported. Currently calling a procedure in the library is only supported in the I{i386} architecture. @raise WindowsError: An exception is raised on error. """ # Resolve kernel32.dll aModule = self.get_module_by_name(compat.b('kernel32.dll')) if aModule is None: self.scan_modules() aModule = self.get_module_by_name(compat.b('kernel32.dll')) if aModule is None: raise RuntimeError( "Cannot resolve kernel32.dll in the remote process") # Old method, using shellcode. if procname: if self.get_arch() != win32.ARCH_I386: raise NotImplementedError() dllname = compat.b(dllname) # Resolve kernel32.dll!LoadLibraryA pllib = aModule.resolve(compat.b('LoadLibraryA')) if not pllib: raise RuntimeError( "Cannot resolve kernel32.dll!LoadLibraryA" " in the remote process") # Resolve kernel32.dll!GetProcAddress pgpad = aModule.resolve(compat.b('GetProcAddress')) if not pgpad: raise RuntimeError( "Cannot resolve kernel32.dll!GetProcAddress" " in the remote process") # Resolve kernel32.dll!VirtualFree pvf = aModule.resolve(compat.b('VirtualFree')) if not pvf: raise RuntimeError( "Cannot resolve kernel32.dll!VirtualFree" " in the remote process") # Shellcode follows... code = compat.b('') # push dllname code += compat.b('\xe8') + struct.pack('<L', len(dllname) + 1) + dllname + compat.b('\0') # mov eax, LoadLibraryA code += compat.b('\xb8') + struct.pack('<L', pllib) # call eax code += compat.b('\xff\xd0') if procname: # push procname code += compat.b('\xe8') + struct.pack('<L', len(procname) + 1) code += procname + compat.b('\0') # push eax code += compat.b('\x50') # mov eax, GetProcAddress code += compat.b('\xb8') + struct.pack('<L', pgpad) # call eax code += compat.b('\xff\xd0') # mov ebp, esp ; preserve stack pointer code += compat.b('\x8b\xec') # push lpParameter code += compat.b('\x68') + struct.pack('<L', lpParameter) # call eax code += compat.b('\xff\xd0') # mov esp, ebp ; restore stack pointer code += compat.b('\x8b\xe5') # pop edx ; our own return address code += compat.b('\x5a') # push MEM_RELEASE ; dwFreeType code += compat.b('\x68') + struct.pack('<L', win32.MEM_RELEASE) # push 0x1000 ; dwSize, shellcode max size 4096 bytes code += compat.b('\x68') + struct.pack('<L', 0x1000) # call $+5 code += compat.b('\xe8\x00\x00\x00\x00') # and dword ptr [esp], 0xFFFFF000 ; align to page boundary code += compat.b('\x81\x24\x24\x00\xf0\xff\xff') # mov eax, VirtualFree code += compat.b('\xb8') + struct.pack('<L', pvf) # push edx ; our own return address code += compat.b('\x52') # jmp eax ; VirtualFree will return to our own return address code += compat.b('\xff\xe0') # Inject the shellcode. # There's no need to free the memory, # because the shellcode will free it itself. aThread, lpStartAddress = self.inject_code(code, lpParameter) # New method, not using shellcode. else: # Resolve kernel32.dll!LoadLibrary (A/W) if type(dllname) == type(u''): pllibname = compat.b('LoadLibraryW') bufferlen = (len(dllname) + 1) * 2 dllname = win32.ctypes.create_unicode_buffer(dllname).raw[:bufferlen + 1] else: pllibname = compat.b('LoadLibraryA') dllname = compat.b(dllname) + compat.b('\x00') bufferlen = len(dllname) pllib = aModule.resolve(pllibname) if not pllib: msg = "Cannot resolve kernel32.dll!%s in the remote process" raise RuntimeError(msg % pllibname) # Copy the library name into the process memory space. pbuffer = self.malloc(bufferlen) try: self.write(pbuffer, dllname) # Create a new thread to load the library. try: aThread = self.start_thread(pllib, pbuffer) except WindowsError: e = sys.exc_info()[1] if e.winerror != win32.ERROR_NOT_ENOUGH_MEMORY: raise # This specific error is caused by trying to spawn a new # thread in a process belonging to a different Terminal # Services session (for example a service). raise NotImplementedError( "Target process belongs to a different" " Terminal Services session, cannot inject!" ) # Remember the buffer address. # It will be freed ONLY by the Thread.kill() method # and the EventHandler class, otherwise you'll have to # free it in your code. aThread.pInjectedMemory = pbuffer # Free the memory on error. except Exception: self.free(pbuffer) raise # Wait for the thread to finish. if bWait: aThread.wait(dwTimeout) self.free(aThread.pInjectedMemory) del aThread.pInjectedMemory # Return the thread object. return aThread def clean_exit(self, dwExitCode = 0, bWait = False, dwTimeout = None): """ Injects a new thread to call ExitProcess(). Optionally waits for the injected thread to finish. @warning: Setting C{bWait} to C{True} when the process is frozen by a debug event will cause a deadlock in your debugger. @type dwExitCode: int @param dwExitCode: Process exit code. @type bWait: bool @param bWait: C{True} to wait for the process to finish. C{False} to return immediately. @type dwTimeout: int @param dwTimeout: (Optional) Timeout value in milliseconds. Ignored if C{bWait} is C{False}. @raise WindowsError: An exception is raised on error. """ if not dwExitCode: dwExitCode = 0 pExitProcess = self.resolve_label('kernel32!ExitProcess') aThread = self.start_thread(pExitProcess, dwExitCode) if bWait: aThread.wait(dwTimeout) #------------------------------------------------------------------------------ def _notify_create_process(self, event): """ Notify the creation of a new process. This is done automatically by the L{Debug} class, you shouldn't need to call it yourself. @type event: L{CreateProcessEvent} @param event: Create process event. @rtype: bool @return: C{True} to call the user-defined handle, C{False} otherwise. """ # Do not use super() here. bCallHandler = _ThreadContainer._notify_create_process(self, event) bCallHandler = bCallHandler and \ _ModuleContainer._notify_create_process(self, event) return bCallHandler #============================================================================== class _ProcessContainer (object): """ Encapsulates the capability to contain Process objects. @group Instrumentation: start_process, argv_to_cmdline, cmdline_to_argv, get_explorer_pid @group Processes snapshot: scan, scan_processes, scan_processes_fast, get_process, get_process_count, get_process_ids, has_process, iter_processes, iter_process_ids, find_processes_by_filename, get_pid_from_tid, get_windows, scan_process_filenames, clear, clear_processes, clear_dead_processes, clear_unattached_processes, close_process_handles, close_process_and_thread_handles @group Threads snapshots: scan_processes_and_threads, get_thread, get_thread_count, get_thread_ids, has_thread @group Modules snapshots: scan_modules, find_modules_by_address, find_modules_by_base, find_modules_by_name, get_module_count """ def __init__(self): self.__processDict = dict() def __initialize_snapshot(self): """ Private method to automatically initialize the snapshot when you try to use it without calling any of the scan_* methods first. You don't need to call this yourself. """ if not self.__processDict: try: self.scan_processes() # remote desktop api (relative fn) except Exception: self.scan_processes_fast() # psapi (no filenames) self.scan_process_filenames() # get the pathnames when possible def __contains__(self, anObject): """ @type anObject: L{Process}, L{Thread}, int @param anObject: - C{int}: Global ID of the process to look for. - C{int}: Global ID of the thread to look for. - C{Process}: Process object to look for. - C{Thread}: Thread object to look for. @rtype: bool @return: C{True} if the snapshot contains a L{Process} or L{Thread} object with the same ID. """ if isinstance(anObject, Process): anObject = anObject.dwProcessId if self.has_process(anObject): return True for aProcess in self.iter_processes(): if anObject in aProcess: return True return False def __iter__(self): """ @see: L{iter_processes} @rtype: dictionary-valueiterator @return: Iterator of L{Process} objects in this snapshot. """ return self.iter_processes() def __len__(self): """ @see: L{get_process_count} @rtype: int @return: Count of L{Process} objects in this snapshot. """ return self.get_process_count() def has_process(self, dwProcessId): """ @type dwProcessId: int @param dwProcessId: Global ID of the process to look for. @rtype: bool @return: C{True} if the snapshot contains a L{Process} object with the given global ID. """ self.__initialize_snapshot() return dwProcessId in self.__processDict def get_process(self, dwProcessId): """ @type dwProcessId: int @param dwProcessId: Global ID of the process to look for. @rtype: L{Process} @return: Process object with the given global ID. """ self.__initialize_snapshot() if dwProcessId not in self.__processDict: msg = "Unknown process ID %d" % dwProcessId raise KeyError(msg) return self.__processDict[dwProcessId] def iter_process_ids(self): """ @see: L{iter_processes} @rtype: dictionary-keyiterator @return: Iterator of global process IDs in this snapshot. """ self.__initialize_snapshot() return compat.iterkeys(self.__processDict) def iter_processes(self): """ @see: L{iter_process_ids} @rtype: dictionary-valueiterator @return: Iterator of L{Process} objects in this snapshot. """ self.__initialize_snapshot() return compat.itervalues(self.__processDict) def get_process_ids(self): """ @see: L{iter_process_ids} @rtype: list( int ) @return: List of global process IDs in this snapshot. """ self.__initialize_snapshot() return compat.keys(self.__processDict) def get_process_count(self): """ @rtype: int @return: Count of L{Process} objects in this snapshot. """ self.__initialize_snapshot() return len(self.__processDict) #------------------------------------------------------------------------------ # XXX TODO # Support for string searches on the window captions. def get_windows(self): """ @rtype: list of L{Window} @return: Returns a list of windows handled by all processes in this snapshot. """ window_list = list() for process in self.iter_processes(): window_list.extend( process.get_windows() ) return window_list def get_pid_from_tid(self, dwThreadId): """ Retrieves the global ID of the process that owns the thread. @type dwThreadId: int @param dwThreadId: Thread global ID. @rtype: int @return: Process global ID. @raise KeyError: The thread does not exist. """ try: # No good, because in XP and below it tries to get the PID # through the toolhelp API, and that's slow. We don't want # to scan for threads over and over for each call. ## dwProcessId = Thread(dwThreadId).get_pid() # This API only exists in Windows 2003, Vista and above. try: hThread = win32.OpenThread( win32.THREAD_QUERY_LIMITED_INFORMATION, False, dwThreadId) except WindowsError: e = sys.exc_info()[1] if e.winerror != win32.ERROR_ACCESS_DENIED: raise hThread = win32.OpenThread( win32.THREAD_QUERY_INFORMATION, False, dwThreadId) try: return win32.GetProcessIdOfThread(hThread) finally: hThread.close() # If all else fails, go through all processes in the snapshot # looking for the one that owns the thread we're looking for. # If the snapshot was empty the iteration should trigger an # automatic scan. Otherwise, it'll look for the thread in what # could possibly be an outdated snapshot. except Exception: for aProcess in self.iter_processes(): if aProcess.has_thread(dwThreadId): return aProcess.get_pid() # The thread wasn't found, so let's refresh the snapshot and retry. # Normally this shouldn't happen since this function is only useful # for the debugger, so the thread should already exist in the snapshot. self.scan_processes_and_threads() for aProcess in self.iter_processes(): if aProcess.has_thread(dwThreadId): return aProcess.get_pid() # No luck! It appears to be the thread doesn't exist after all. msg = "Unknown thread ID %d" % dwThreadId raise KeyError(msg) #------------------------------------------------------------------------------ @staticmethod def argv_to_cmdline(argv): """ Convert a list of arguments to a single command line string. @type argv: list( str ) @param argv: List of argument strings. The first element is the program to execute. @rtype: str @return: Command line string. """ cmdline = list() for token in argv: if not token: token = '""' else: if '"' in token: token = token.replace('"', '\\"') if ' ' in token or \ '\t' in token or \ '\n' in token or \ '\r' in token: token = '"%s"' % token cmdline.append(token) return ' '.join(cmdline) @staticmethod def cmdline_to_argv(lpCmdLine): """ Convert a single command line string to a list of arguments. @type lpCmdLine: str @param lpCmdLine: Command line string. The first token is the program to execute. @rtype: list( str ) @return: List of argument strings. """ if not lpCmdLine: return [] return win32.CommandLineToArgv(lpCmdLine) def start_process(self, lpCmdLine, **kwargs): """ Starts a new process for instrumenting (or debugging). @type lpCmdLine: str @param lpCmdLine: Command line to execute. Can't be an empty string. @type bConsole: bool @keyword bConsole: True to inherit the console of the debugger. Defaults to C{False}. @type bDebug: bool @keyword bDebug: C{True} to attach to the new process. To debug a process it's best to use the L{Debug} class instead. Defaults to C{False}. @type bFollow: bool @keyword bFollow: C{True} to automatically attach to the child processes of the newly created process. Ignored unless C{bDebug} is C{True}. Defaults to C{False}. @type bInheritHandles: bool @keyword bInheritHandles: C{True} if the new process should inherit it's parent process' handles. Defaults to C{False}. @type bSuspended: bool @keyword bSuspended: C{True} to suspend the main thread before any code is executed in the debugee. Defaults to C{False}. @type dwParentProcessId: int or None @keyword dwParentProcessId: C{None} if the debugger process should be the parent process (default), or a process ID to forcefully set as the debugee's parent (only available for Windows Vista and above). @type iTrustLevel: int @keyword iTrustLevel: Trust level. Must be one of the following values: - 0: B{No trust}. May not access certain resources, such as cryptographic keys and credentials. Only available since Windows XP and 2003, desktop editions. - 1: B{Normal trust}. Run with the same privileges as a normal user, that is, one that doesn't have the I{Administrator} or I{Power User} user rights. Only available since Windows XP and 2003, desktop editions. - 2: B{Full trust}. Run with the exact same privileges as the current user. This is the default value. @type bAllowElevation: bool @keyword bAllowElevation: C{True} to allow the child process to keep UAC elevation, if the debugger itself is running elevated. C{False} to ensure the child process doesn't run with elevation. Defaults to C{True}. This flag is only meaningful on Windows Vista and above, and if the debugger itself is running with elevation. It can be used to make sure the child processes don't run elevated as well. This flag DOES NOT force an elevation prompt when the debugger is not running with elevation. Note that running the debugger with elevation (or the Python interpreter at all for that matter) is not normally required. You should only need to if the target program requires elevation to work properly (for example if you try to debug an installer). @rtype: L{Process} @return: Process object. """ # Get the flags. bConsole = kwargs.pop('bConsole', False) bDebug = kwargs.pop('bDebug', False) bFollow = kwargs.pop('bFollow', False) bSuspended = kwargs.pop('bSuspended', False) bInheritHandles = kwargs.pop('bInheritHandles', False) dwParentProcessId = kwargs.pop('dwParentProcessId', None) iTrustLevel = kwargs.pop('iTrustLevel', 2) bAllowElevation = kwargs.pop('bAllowElevation', True) if kwargs: raise TypeError("Unknown keyword arguments: %s" % compat.keys(kwargs)) if not lpCmdLine: raise ValueError("Missing command line to execute!") # Sanitize the trust level flag. if iTrustLevel is None: iTrustLevel = 2 # The UAC elevation flag is only meaningful if we're running elevated. try: bAllowElevation = bAllowElevation or not self.is_admin() except AttributeError: bAllowElevation = True warnings.warn( "UAC elevation is only available in Windows Vista and above", RuntimeWarning) # Calculate the process creation flags. dwCreationFlags = 0 dwCreationFlags |= win32.CREATE_DEFAULT_ERROR_MODE dwCreationFlags |= win32.CREATE_BREAKAWAY_FROM_JOB ##dwCreationFlags |= win32.CREATE_UNICODE_ENVIRONMENT if not bConsole: dwCreationFlags |= win32.DETACHED_PROCESS #dwCreationFlags |= win32.CREATE_NO_WINDOW # weird stuff happens if bSuspended: dwCreationFlags |= win32.CREATE_SUSPENDED if bDebug: dwCreationFlags |= win32.DEBUG_PROCESS if not bFollow: dwCreationFlags |= win32.DEBUG_ONLY_THIS_PROCESS # Change the parent process if requested. # May fail on old versions of Windows. lpStartupInfo = None if dwParentProcessId is not None: myPID = win32.GetCurrentProcessId() if dwParentProcessId != myPID: if self.has_process(dwParentProcessId): ParentProcess = self.get_process(dwParentProcessId) else: ParentProcess = Process(dwParentProcessId) ParentProcessHandle = ParentProcess.get_handle( win32.PROCESS_CREATE_PROCESS) AttributeListData = ( ( win32.PROC_THREAD_ATTRIBUTE_PARENT_PROCESS, ParentProcessHandle._as_parameter_ ), ) AttributeList = win32.ProcThreadAttributeList(AttributeListData) StartupInfoEx = win32.STARTUPINFOEX() StartupInfo = StartupInfoEx.StartupInfo StartupInfo.cb = win32.sizeof(win32.STARTUPINFOEX) StartupInfo.lpReserved = 0 StartupInfo.lpDesktop = 0 StartupInfo.lpTitle = 0 StartupInfo.dwFlags = 0 StartupInfo.cbReserved2 = 0 StartupInfo.lpReserved2 = 0 StartupInfoEx.lpAttributeList = AttributeList.value lpStartupInfo = StartupInfoEx dwCreationFlags |= win32.EXTENDED_STARTUPINFO_PRESENT pi = None try: # Create the process the easy way. if iTrustLevel >= 2 and bAllowElevation: pi = win32.CreateProcess(None, lpCmdLine, bInheritHandles = bInheritHandles, dwCreationFlags = dwCreationFlags, lpStartupInfo = lpStartupInfo) # Create the process the hard way... else: # If we allow elevation, use the current process token. # If not, get the token from the current shell process. hToken = None try: if not bAllowElevation: if bFollow: msg = ( "Child processes can't be autofollowed" " when dropping UAC elevation.") raise NotImplementedError(msg) if bConsole: msg = ( "Child processes can't inherit the debugger's" " console when dropping UAC elevation.") raise NotImplementedError(msg) if bInheritHandles: msg = ( "Child processes can't inherit the debugger's" " handles when dropping UAC elevation.") raise NotImplementedError(msg) try: hWnd = self.get_shell_window() except WindowsError: hWnd = self.get_desktop_window() shell = hWnd.get_process() try: hShell = shell.get_handle( win32.PROCESS_QUERY_INFORMATION) with win32.OpenProcessToken(hShell) as hShellToken: hToken = win32.DuplicateTokenEx(hShellToken) finally: shell.close_handle() # Lower trust level if requested. if iTrustLevel < 2: if iTrustLevel > 0: dwLevelId = win32.SAFER_LEVELID_NORMALUSER else: dwLevelId = win32.SAFER_LEVELID_UNTRUSTED with win32.SaferCreateLevel(dwLevelId = dwLevelId) as hSafer: hSaferToken = win32.SaferComputeTokenFromLevel( hSafer, hToken)[0] try: if hToken is not None: hToken.close() except: hSaferToken.close() raise hToken = hSaferToken # If we have a computed token, call CreateProcessAsUser(). if bAllowElevation: pi = win32.CreateProcessAsUser( hToken = hToken, lpCommandLine = lpCmdLine, bInheritHandles = bInheritHandles, dwCreationFlags = dwCreationFlags, lpStartupInfo = lpStartupInfo) # If we have a primary token call CreateProcessWithToken(). # The problem is, there are many flags CreateProcess() and # CreateProcessAsUser() accept but CreateProcessWithToken() # and CreateProcessWithLogonW() don't, so we need to work # around them. else: # Remove the debug flags. dwCreationFlags &= ~win32.DEBUG_PROCESS dwCreationFlags &= ~win32.DEBUG_ONLY_THIS_PROCESS # Remove the console flags. dwCreationFlags &= ~win32.DETACHED_PROCESS # The process will be created suspended. dwCreationFlags |= win32.CREATE_SUSPENDED # Create the process using the new primary token. pi = win32.CreateProcessWithToken( hToken = hToken, dwLogonFlags = win32.LOGON_WITH_PROFILE, lpCommandLine = lpCmdLine, dwCreationFlags = dwCreationFlags, lpStartupInfo = lpStartupInfo) # Attach as a debugger, if requested. if bDebug: win32.DebugActiveProcess(pi.dwProcessId) # Resume execution, if requested. if not bSuspended: win32.ResumeThread(pi.hThread) # Close the token when we're done with it. finally: if hToken is not None: hToken.close() # Wrap the new process and thread in Process and Thread objects, # and add them to the corresponding snapshots. aProcess = Process(pi.dwProcessId, pi.hProcess) aThread = Thread (pi.dwThreadId, pi.hThread) aProcess._add_thread(aThread) self._add_process(aProcess) # Clean up on error. except: if pi is not None: try: win32.TerminateProcess(pi.hProcess) except WindowsError: pass pi.hThread.close() pi.hProcess.close() raise # Return the new Process object. return aProcess def get_explorer_pid(self): """ Tries to find the process ID for "explorer.exe". @rtype: int or None @return: Returns the process ID, or C{None} on error. """ try: exp = win32.SHGetFolderPath(win32.CSIDL_WINDOWS) except Exception: exp = None if not exp: exp = os.getenv('SystemRoot') if exp: exp = os.path.join(exp, 'explorer.exe') exp_list = self.find_processes_by_filename(exp) if exp_list: return exp_list[0][0].get_pid() return None #------------------------------------------------------------------------------ # XXX this methods musn't end up calling __initialize_snapshot by accident! def scan(self): """ Populates the snapshot with running processes and threads, and loaded modules. Tipically this is the first method called after instantiating a L{System} object, as it makes a best effort approach to gathering information on running processes. @rtype: bool @return: C{True} if the snapshot is complete, C{False} if the debugger doesn't have permission to scan some processes. In either case, the snapshot is complete for all processes the debugger has access to. """ has_threads = True try: try: # Try using the Toolhelp API # to scan for processes and threads. self.scan_processes_and_threads() except Exception: # On error, try using the PSAPI to scan for process IDs only. self.scan_processes_fast() # Now try using the Toolhelp again to get the threads. for aProcess in self.__processDict.values(): if aProcess._get_thread_ids(): try: aProcess.scan_threads() except WindowsError: has_threads = False finally: # Try using the Remote Desktop API to scan for processes only. # This will update the filenames when it's not possible # to obtain them from the Toolhelp API. self.scan_processes() # When finished scanning for processes, try modules too. has_modules = self.scan_modules() # Try updating the process filenames when possible. has_full_names = self.scan_process_filenames() # Return the completion status. return has_threads and has_modules and has_full_names def scan_processes_and_threads(self): """ Populates the snapshot with running processes and threads. Tipically you don't need to call this method directly, if unsure use L{scan} instead. @note: This method uses the Toolhelp API. @see: L{scan_modules} @raise WindowsError: An error occured while updating the snapshot. The snapshot was not modified. """ # The main module filename may be spoofed by malware, # since this information resides in usermode space. # See: http://www.ragestorm.net/blogs/?p=163 our_pid = win32.GetCurrentProcessId() dead_pids = set( compat.iterkeys(self.__processDict) ) found_tids = set() # Ignore our own process if it's in the snapshot for some reason if our_pid in dead_pids: dead_pids.remove(our_pid) # Take a snapshot of all processes and threads dwFlags = win32.TH32CS_SNAPPROCESS | win32.TH32CS_SNAPTHREAD with win32.CreateToolhelp32Snapshot(dwFlags) as hSnapshot: # Add all the processes (excluding our own) pe = win32.Process32First(hSnapshot) while pe is not None: dwProcessId = pe.th32ProcessID if dwProcessId != our_pid: if dwProcessId in dead_pids: dead_pids.remove(dwProcessId) if dwProcessId not in self.__processDict: aProcess = Process(dwProcessId, fileName=pe.szExeFile) self._add_process(aProcess) elif pe.szExeFile: aProcess = self.get_process(dwProcessId) if not aProcess.fileName: aProcess.fileName = pe.szExeFile pe = win32.Process32Next(hSnapshot) # Add all the threads te = win32.Thread32First(hSnapshot) while te is not None: dwProcessId = te.th32OwnerProcessID if dwProcessId != our_pid: if dwProcessId in dead_pids: dead_pids.remove(dwProcessId) if dwProcessId in self.__processDict: aProcess = self.get_process(dwProcessId) else: aProcess = Process(dwProcessId) self._add_process(aProcess) dwThreadId = te.th32ThreadID found_tids.add(dwThreadId) if not aProcess._has_thread_id(dwThreadId): aThread = Thread(dwThreadId, process = aProcess) aProcess._add_thread(aThread) te = win32.Thread32Next(hSnapshot) # Remove dead processes for pid in dead_pids: self._del_process(pid) # Remove dead threads for aProcess in compat.itervalues(self.__processDict): dead_tids = set( aProcess._get_thread_ids() ) dead_tids.difference_update(found_tids) for tid in dead_tids: aProcess._del_thread(tid) def scan_modules(self): """ Populates the snapshot with loaded modules. Tipically you don't need to call this method directly, if unsure use L{scan} instead. @note: This method uses the Toolhelp API. @see: L{scan_processes_and_threads} @rtype: bool @return: C{True} if the snapshot is complete, C{False} if the debugger doesn't have permission to scan some processes. In either case, the snapshot is complete for all processes the debugger has access to. """ complete = True for aProcess in compat.itervalues(self.__processDict): try: aProcess.scan_modules() except WindowsError: complete = False return complete def scan_processes(self): """ Populates the snapshot with running processes. Tipically you don't need to call this method directly, if unsure use L{scan} instead. @note: This method uses the Remote Desktop API instead of the Toolhelp API. It might give slightly different results, especially if the current process does not have full privileges. @note: This method will only retrieve process filenames. To get the process pathnames instead, B{after} this method call L{scan_process_filenames}. @raise WindowsError: An error occured while updating the snapshot. The snapshot was not modified. """ # Get the previous list of PIDs. # We'll be removing live PIDs from it as we find them. our_pid = win32.GetCurrentProcessId() dead_pids = set( compat.iterkeys(self.__processDict) ) # Ignore our own PID. if our_pid in dead_pids: dead_pids.remove(our_pid) # Get the list of processes from the Remote Desktop API. pProcessInfo = None try: pProcessInfo, dwCount = win32.WTSEnumerateProcesses( win32.WTS_CURRENT_SERVER_HANDLE) # For each process found... for index in compat.xrange(dwCount): sProcessInfo = pProcessInfo[index] ## # Ignore processes belonging to other sessions. ## if sProcessInfo.SessionId != win32.WTS_CURRENT_SESSION: ## continue # Ignore our own PID. pid = sProcessInfo.ProcessId if pid == our_pid: continue # Remove the PID from the dead PIDs list. if pid in dead_pids: dead_pids.remove(pid) # Get the "process name". # Empirically, this seems to be the filename without the path. # (The MSDN docs aren't very clear about this API call). fileName = sProcessInfo.pProcessName # If the process is new, add a new Process object. if pid not in self.__processDict: aProcess = Process(pid, fileName = fileName) self._add_process(aProcess) # If the process was already in the snapshot, and the # filename is missing, update the Process object. elif fileName: aProcess = self.__processDict.get(pid) if not aProcess.fileName: aProcess.fileName = fileName # Free the memory allocated by the Remote Desktop API. finally: if pProcessInfo is not None: try: win32.WTSFreeMemory(pProcessInfo) except WindowsError: pass # At this point the only remaining PIDs from the old list are dead. # Remove them from the snapshot. for pid in dead_pids: self._del_process(pid) def scan_processes_fast(self): """ Populates the snapshot with running processes. Only the PID is retrieved for each process. Dead processes are removed. Threads and modules of living processes are ignored. Tipically you don't need to call this method directly, if unsure use L{scan} instead. @note: This method uses the PSAPI. It may be faster for scanning, but some information may be missing, outdated or slower to obtain. This could be a good tradeoff under some circumstances. """ # Get the new and old list of pids new_pids = set( win32.EnumProcesses() ) old_pids = set( compat.iterkeys(self.__processDict) ) # Ignore our own pid our_pid = win32.GetCurrentProcessId() if our_pid in new_pids: new_pids.remove(our_pid) if our_pid in old_pids: old_pids.remove(our_pid) # Add newly found pids for pid in new_pids.difference(old_pids): self._add_process( Process(pid) ) # Remove missing pids for pid in old_pids.difference(new_pids): self._del_process(pid) def scan_process_filenames(self): """ Update the filename for each process in the snapshot when possible. @note: Tipically you don't need to call this method. It's called automatically by L{scan} to get the full pathname for each process when possible, since some scan methods only get filenames without the path component. If unsure, use L{scan} instead. @see: L{scan}, L{Process.get_filename} @rtype: bool @return: C{True} if all the pathnames were retrieved, C{False} if the debugger doesn't have permission to scan some processes. In either case, all processes the debugger has access to have a full pathname instead of just a filename. """ complete = True for aProcess in self.__processDict.values(): try: new_name = None old_name = aProcess.fileName try: aProcess.fileName = None new_name = aProcess.get_filename() finally: if not new_name: aProcess.fileName = old_name complete = False except Exception: complete = False return complete #------------------------------------------------------------------------------ def clear_dead_processes(self): """ Removes Process objects from the snapshot referring to processes no longer running. """ for pid in self.get_process_ids(): aProcess = self.get_process(pid) if not aProcess.is_alive(): self._del_process(aProcess) def clear_unattached_processes(self): """ Removes Process objects from the snapshot referring to processes not being debugged. """ for pid in self.get_process_ids(): aProcess = self.get_process(pid) if not aProcess.is_being_debugged(): self._del_process(aProcess) def close_process_handles(self): """ Closes all open handles to processes in this snapshot. """ for pid in self.get_process_ids(): aProcess = self.get_process(pid) try: aProcess.close_handle() except Exception: e = sys.exc_info()[1] try: msg = "Cannot close process handle %s, reason: %s" msg %= (aProcess.hProcess.value, str(e)) warnings.warn(msg) except Exception: pass def close_process_and_thread_handles(self): """ Closes all open handles to processes and threads in this snapshot. """ for aProcess in self.iter_processes(): aProcess.close_thread_handles() try: aProcess.close_handle() except Exception: e = sys.exc_info()[1] try: msg = "Cannot close process handle %s, reason: %s" msg %= (aProcess.hProcess.value, str(e)) warnings.warn(msg) except Exception: pass def clear_processes(self): """ Removes all L{Process}, L{Thread} and L{Module} objects in this snapshot. """ #self.close_process_and_thread_handles() for aProcess in self.iter_processes(): aProcess.clear() self.__processDict = dict() def clear(self): """ Clears this snapshot. @see: L{clear_processes} """ self.clear_processes() #------------------------------------------------------------------------------ # Docs for these methods are taken from the _ThreadContainer class. def has_thread(self, dwThreadId): dwProcessId = self.get_pid_from_tid(dwThreadId) if dwProcessId is None: return False return self.has_process(dwProcessId) def get_thread(self, dwThreadId): dwProcessId = self.get_pid_from_tid(dwThreadId) if dwProcessId is None: msg = "Unknown thread ID %d" % dwThreadId raise KeyError(msg) return self.get_process(dwProcessId).get_thread(dwThreadId) def get_thread_ids(self): ids = list() for aProcess in self.iter_processes(): ids += aProcess.get_thread_ids() return ids def get_thread_count(self): count = 0 for aProcess in self.iter_processes(): count += aProcess.get_thread_count() return count has_thread.__doc__ = _ThreadContainer.has_thread.__doc__ get_thread.__doc__ = _ThreadContainer.get_thread.__doc__ get_thread_ids.__doc__ = _ThreadContainer.get_thread_ids.__doc__ get_thread_count.__doc__ = _ThreadContainer.get_thread_count.__doc__ #------------------------------------------------------------------------------ # Docs for these methods are taken from the _ModuleContainer class. def get_module_count(self): count = 0 for aProcess in self.iter_processes(): count += aProcess.get_module_count() return count get_module_count.__doc__ = _ModuleContainer.get_module_count.__doc__ #------------------------------------------------------------------------------ def find_modules_by_base(self, lpBaseOfDll): """ @rtype: list( L{Module}... ) @return: List of Module objects with the given base address. """ found = list() for aProcess in self.iter_processes(): if aProcess.has_module(lpBaseOfDll): aModule = aProcess.get_module(lpBaseOfDll) found.append( (aProcess, aModule) ) return found def find_modules_by_name(self, fileName): """ @rtype: list( L{Module}... ) @return: List of Module objects found. """ found = list() for aProcess in self.iter_processes(): aModule = aProcess.get_module_by_name(fileName) if aModule is not None: found.append( (aProcess, aModule) ) return found def find_modules_by_address(self, address): """ @rtype: list( L{Module}... ) @return: List of Module objects that best match the given address. """ found = list() for aProcess in self.iter_processes(): aModule = aProcess.get_module_at_address(address) if aModule is not None: found.append( (aProcess, aModule) ) return found def __find_processes_by_filename(self, filename): """ Internally used by L{find_processes_by_filename}. """ found = list() filename = filename.lower() if PathOperations.path_is_absolute(filename): for aProcess in self.iter_processes(): imagename = aProcess.get_filename() if imagename and imagename.lower() == filename: found.append( (aProcess, imagename) ) else: for aProcess in self.iter_processes(): imagename = aProcess.get_filename() if imagename: imagename = PathOperations.pathname_to_filename(imagename) if imagename.lower() == filename: found.append( (aProcess, imagename) ) return found def find_processes_by_filename(self, fileName): """ @type fileName: str @param fileName: Filename to search for. If it's a full pathname, the match must be exact. If it's a base filename only, the file part is matched, regardless of the directory where it's located. @note: If the process is not found and the file extension is not given, this method will search again assuming a default extension (.exe). @rtype: list of tuple( L{Process}, str ) @return: List of processes matching the given main module filename. Each tuple contains a Process object and it's filename. """ found = self.__find_processes_by_filename(fileName) if not found: fn, ext = PathOperations.split_extension(fileName) if not ext: fileName = '%s.exe' % fn found = self.__find_processes_by_filename(fileName) return found #------------------------------------------------------------------------------ # XXX _notify_* methods should not trigger a scan def _add_process(self, aProcess): """ Private method to add a process object to the snapshot. @type aProcess: L{Process} @param aProcess: Process object. """ ## if not isinstance(aProcess, Process): ## if hasattr(aProcess, '__class__'): ## typename = aProcess.__class__.__name__ ## else: ## typename = str(type(aProcess)) ## msg = "Expected Process, got %s instead" % typename ## raise TypeError(msg) dwProcessId = aProcess.dwProcessId ## if dwProcessId in self.__processDict: ## msg = "Process already exists: %d" % dwProcessId ## raise KeyError(msg) self.__processDict[dwProcessId] = aProcess def _del_process(self, dwProcessId): """ Private method to remove a process object from the snapshot. @type dwProcessId: int @param dwProcessId: Global process ID. """ try: aProcess = self.__processDict[dwProcessId] del self.__processDict[dwProcessId] except KeyError: aProcess = None msg = "Unknown process ID %d" % dwProcessId warnings.warn(msg, RuntimeWarning) if aProcess: aProcess.clear() # remove circular references # Notify the creation of a new process. def _notify_create_process(self, event): """ Notify the creation of a new process. This is done automatically by the L{Debug} class, you shouldn't need to call it yourself. @type event: L{CreateProcessEvent} @param event: Create process event. @rtype: bool @return: C{True} to call the user-defined handle, C{False} otherwise. """ dwProcessId = event.get_pid() dwThreadId = event.get_tid() hProcess = event.get_process_handle() ## if not self.has_process(dwProcessId): # XXX this would trigger a scan if dwProcessId not in self.__processDict: aProcess = Process(dwProcessId, hProcess) self._add_process(aProcess) aProcess.fileName = event.get_filename() else: aProcess = self.get_process(dwProcessId) #if hProcess != win32.INVALID_HANDLE_VALUE: # aProcess.hProcess = hProcess # may have more privileges if not aProcess.fileName: fileName = event.get_filename() if fileName: aProcess.fileName = fileName return aProcess._notify_create_process(event) # pass it to the process def _notify_exit_process(self, event): """ Notify the termination of a process. This is done automatically by the L{Debug} class, you shouldn't need to call it yourself. @type event: L{ExitProcessEvent} @param event: Exit process event. @rtype: bool @return: C{True} to call the user-defined handle, C{False} otherwise. """ dwProcessId = event.get_pid() ## if self.has_process(dwProcessId): # XXX this would trigger a scan if dwProcessId in self.__processDict: self._del_process(dwProcessId) return True
epl-1.0
fjammes/braise
libraries/ArduinoJson-master/third-party/gtest-1.7.0/test/gtest_uninitialized_test.py
2901
2480
#!/usr/bin/env python # # Copyright 2008, 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 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Verifies that Google Test warns the user when not initialized properly.""" __author__ = 'wan@google.com (Zhanyong Wan)' import gtest_test_utils COMMAND = gtest_test_utils.GetTestExecutablePath('gtest_uninitialized_test_') def Assert(condition): if not condition: raise AssertionError def AssertEq(expected, actual): if expected != actual: print 'Expected: %s' % (expected,) print ' Actual: %s' % (actual,) raise AssertionError def TestExitCodeAndOutput(command): """Runs the given command and verifies its exit code and output.""" # Verifies that 'command' exits with code 1. p = gtest_test_utils.Subprocess(command) Assert(p.exited) AssertEq(1, p.exit_code) Assert('InitGoogleTest' in p.output) class GTestUninitializedTest(gtest_test_utils.TestCase): def testExitCodeAndOutput(self): TestExitCodeAndOutput(COMMAND) if __name__ == '__main__': gtest_test_utils.Main()
gpl-3.0
redshodan/lazarus-ssh
tests/utils.py
1
5573
# # Copyright (C) 2009 Chris Newton <redshodan@gmail.com> # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # # # Author: Chris Newton <redshodan@gmail.com> # $Revision$ # import os, sys, unittest2, subprocess, signal, termios import log THE_TEST = None TESTUSER = None TESTPASS = None TESTPORT = "2227" ROOT = 1 TEST = 2 USER = 3 SCREEN_NONE = "No Sockets found in /var/run/screen/S-test." ## ## unittest behavior adjustment ## class LsshTestCase(unittest2.TestCase): def __init__(self, name, timeout=10): unittest2.TestCase.__init__(self, name) self.test_name = str(self) self.orgtest = getattr(self, name) setattr(self, name, self._run) if hasattr(self.orgtest, "timeout"): self.timeout = self.orgtest.timeout else: self.timeout = timeout self.error = "" def _sigalarm(self, sig, frame): log.info("_sigalarm: test failed to complete in time") self.error = "Test failed to complete in time: " self.cmd_timeout = True self.cmd.kill() def setUp(self): global THE_TEST unittest2.TestCase.setUp(self) log.info("---------Starting test: %s(timeout=%d)---------", self.test_name, self.timeout) THE_TEST = self self.cmd_timeout = False self.error = "" signal.signal(signal.SIGALRM, self._sigalarm) signal.alarm(self.timeout) def tearDown(self): signal.alarm(0) unittest2.TestCase.tearDown(self) log.info("---------Ending test: %s---------", self.test_name) def runCmd(self, who, cmd, **kwargs): if who == ROOT: args = ["sudo"] elif who == TEST: args = ["sudo", "-u", TESTUSER, "-i"] elif who == USER: args = ["bash", "-c", cmd] else: raise Exception("Invalid 'who' for runCmd") args.extend(["bash", "-c"]) args.append(cmd) expect_fail = True if "fail" in kwargs: expect_fail = kwargs["fail"] del kwargs["fail"] (ret, foo) = LsshTestCase._runCmd(args, kwargs, self) if expect_fail: if expect_fail is True: expect_fail = " ".join(args) self.assertIs( self.cmd.returncode, 0, expect_fail + (" : %sret=%d: %s" % (self.error, self.cmd.returncode, ret[1]))) return [self.cmd.returncode] + list(ret) @staticmethod def _runCmd(args, kwargs={}, obj=None): if "stdout" not in kwargs: kwargs["stdout"] = subprocess.PIPE if "stderr" not in kwargs: kwargs["stderr"] = subprocess.STDOUT log.info("Starting cmd: %s, %s" % (str(args), str(kwargs))) cmd = subprocess.Popen(args, **kwargs) if obj: obj.cmd = cmd try: ret = cmd.communicate() except IOError, e: if e.errno == 4: ret = ["", ""] self.cmd.returncode = -127 log.info("Finised cmd: ret=%d: %s", cmd.returncode, ret[0]) return (ret, cmd) def enableSshKey(self): self.runCmd(TEST, "cp -f ~/.ssh/authorized_keys_ ~/.ssh/authorized_keys") def disableSshKey(self): self.runCmd(TEST, "rm -f ~/.ssh/authorized_keys") def _run(self): try: self.orgtest() except KeyboardInterrupt: log.exception("Keyboard Interrupt") raise except: log.exception("Exception during test") raise finally: try: # Restore the tty in case ssh trashed it. termios.tcsetattr(sys.stdin, termios.TCSANOW, ORIG_TTY) except: pass def CriticalTest(func): def _failingTest(*args, **kwargs): try: return func(*args, **kwargs) except: THE_TEST._resultForDoCleanups.stop() raise return _failingTest def init(): global TESTUSER, TESTPASS, ORIG_TTY log.init("test") log.logger.setLevel(log.DEBUG) if "DISPLAY" in os.environ: del os.environ["DISPLAY"] if "TESTUSER" in os.environ: TESTUSER = os.environ["TESTUSER"] else: print ("The environment variable TESTUSER is not set. It must be set " + "to a test user") sys.exit(-1) ORIG_TTY = termios.tcgetattr(sys.stdin) # Make a test user password r = os.urandom(12) p = [] for c in r: c = ord(c) if c & 0x8: p.append(chr(0x41 + c % 26)) else: p.append(chr(0x61 + c % 26)) TESTPASS = "".join(p) print "Will set the '%s' user's password to: %s" % (TESTUSER, TESTPASS)
lgpl-2.1
kirillmakhonin/med
MED.Server/apps/human_resources/migrations/0004_auto_20160826_2140.py
1
1111
# -*- coding: utf-8 -*- # Generated by Django 1.10 on 2016-08-26 21:40 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('human_resources', '0003_auto_20160826_2113'), ] operations = [ migrations.CreateModel( name='Contact', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('first_name', models.CharField(max_length=30, verbose_name='first name')), ('last_name', models.CharField(max_length=30, verbose_name='last name')), ], ), migrations.RemoveField( model_name='employee', name='first_name', ), migrations.RemoveField( model_name='employee', name='last_name', ), migrations.AlterField( model_name='employee', name='title', field=models.CharField(max_length=200, verbose_name='employee title'), ), ]
mit
ehealthafrica-ci/formhub
restservice/models.py
2
1230
from django.db import models from django.utils.translation import ugettext_lazy from odk_logger.models.xform import XForm from restservice import SERVICE_CHOICES class RestService(models.Model): class Meta: app_label = 'restservice' unique_together = ('service_url', 'xform', 'name') service_url = models.URLField(ugettext_lazy("Service URL")) xform = models.ForeignKey(XForm) name = models.CharField(max_length=50, choices=SERVICE_CHOICES) def __unicode__(self): return u"%s:%s - %s" % (self.xform, self.long_name, self.service_url) def get_service_definition(self): m = __import__(''.join(['restservice.tasks']), globals(), \ locals(),[self.name]) a = getattr(m,self.name) return a @property def long_name(self): return [i for i in SERVICE_CHOICES if i[0]==self.name][0][1] class RestServiceAnswer(models.Model): service = models.ForeignKey(RestService) instance = models.ForeignKey("odk_viewer.ParsedInstance") returnCode = models.CharField(max_length=4) returnText = models.TextField() iteration = models.PositiveIntegerField(default=0) date = models.DateTimeField(auto_now=True)
bsd-2-clause
LeeRisk/ssbc
search/migrations/0002_filelist_hash_statusreport.py
35
2086
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('search', '0001_initial'), ] operations = [ migrations.CreateModel( name='FileList', fields=[ ('info_hash', models.CharField(max_length=40, serialize=False, primary_key=True)), ('file_list', models.TextField()), ], ), migrations.CreateModel( name='Hash', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('info_hash', models.CharField(unique=True, max_length=40)), ('category', models.CharField(max_length=20)), ('data_hash', models.CharField(max_length=32)), ('name', models.CharField(max_length=255)), ('extension', models.CharField(max_length=20)), ('classified', models.BooleanField(default=False)), ('source_ip', models.CharField(max_length=20, null=True)), ('tagged', models.BooleanField(default=False)), ('length', models.BigIntegerField()), ('create_time', models.DateTimeField()), ('last_seen', models.DateTimeField()), ('requests', models.PositiveIntegerField()), ('comment', models.CharField(max_length=255, null=True)), ('creator', models.CharField(max_length=20, null=True)), ], ), migrations.CreateModel( name='StatusReport', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('date', models.DateField(auto_now_add=True)), ('new_hashes', models.IntegerField()), ('total_requests', models.IntegerField()), ('valid_requests', models.IntegerField()), ], ), ]
gpl-2.0
Peddle/hue
desktop/core/ext-py/python-openid-2.2.5/openid/fetchers.py
138
13937
# -*- test-case-name: openid.test.test_fetchers -*- """ This module contains the HTTP fetcher interface and several implementations. """ __all__ = ['fetch', 'getDefaultFetcher', 'setDefaultFetcher', 'HTTPResponse', 'HTTPFetcher', 'createHTTPFetcher', 'HTTPFetchingError', 'HTTPError'] import urllib2 import time import cStringIO import sys import openid import openid.urinorm # Try to import httplib2 for caching support # http://bitworking.org/projects/httplib2/ try: import httplib2 except ImportError: # httplib2 not available httplib2 = None # try to import pycurl, which will let us use CurlHTTPFetcher try: import pycurl except ImportError: pycurl = None USER_AGENT = "python-openid/%s (%s)" % (openid.__version__, sys.platform) MAX_RESPONSE_KB = 1024 def fetch(url, body=None, headers=None): """Invoke the fetch method on the default fetcher. Most users should need only this method. @raises Exception: any exceptions that may be raised by the default fetcher """ fetcher = getDefaultFetcher() return fetcher.fetch(url, body, headers) def createHTTPFetcher(): """Create a default HTTP fetcher instance prefers Curl to urllib2.""" if pycurl is None: fetcher = Urllib2Fetcher() else: fetcher = CurlHTTPFetcher() return fetcher # Contains the currently set HTTP fetcher. If it is set to None, the # library will call createHTTPFetcher() to set it. Do not access this # variable outside of this module. _default_fetcher = None def getDefaultFetcher(): """Return the default fetcher instance if no fetcher has been set, it will create a default fetcher. @return: the default fetcher @rtype: HTTPFetcher """ global _default_fetcher if _default_fetcher is None: setDefaultFetcher(createHTTPFetcher()) return _default_fetcher def setDefaultFetcher(fetcher, wrap_exceptions=True): """Set the default fetcher @param fetcher: The fetcher to use as the default HTTP fetcher @type fetcher: HTTPFetcher @param wrap_exceptions: Whether to wrap exceptions thrown by the fetcher wil HTTPFetchingError so that they may be caught easier. By default, exceptions will be wrapped. In general, unwrapped fetchers are useful for debugging of fetching errors or if your fetcher raises well-known exceptions that you would like to catch. @type wrap_exceptions: bool """ global _default_fetcher if fetcher is None or not wrap_exceptions: _default_fetcher = fetcher else: _default_fetcher = ExceptionWrappingFetcher(fetcher) def usingCurl(): """Whether the currently set HTTP fetcher is a Curl HTTP fetcher.""" return isinstance(getDefaultFetcher(), CurlHTTPFetcher) class HTTPResponse(object): """XXX document attributes""" headers = None status = None body = None final_url = None def __init__(self, final_url=None, status=None, headers=None, body=None): self.final_url = final_url self.status = status self.headers = headers self.body = body def __repr__(self): return "<%s status %s for %s>" % (self.__class__.__name__, self.status, self.final_url) class HTTPFetcher(object): """ This class is the interface for openid HTTP fetchers. This interface is only important if you need to write a new fetcher for some reason. """ def fetch(self, url, body=None, headers=None): """ This performs an HTTP POST or GET, following redirects along the way. If a body is specified, then the request will be a POST. Otherwise, it will be a GET. @param headers: HTTP headers to include with the request @type headers: {str:str} @return: An object representing the server's HTTP response. If there are network or protocol errors, an exception will be raised. HTTP error responses, like 404 or 500, do not cause exceptions. @rtype: L{HTTPResponse} @raise Exception: Different implementations will raise different errors based on the underlying HTTP library. """ raise NotImplementedError def _allowedURL(url): return url.startswith('http://') or url.startswith('https://') class HTTPFetchingError(Exception): """Exception that is wrapped around all exceptions that are raised by the underlying fetcher when using the ExceptionWrappingFetcher @ivar why: The exception that caused this exception """ def __init__(self, why=None): Exception.__init__(self, why) self.why = why class ExceptionWrappingFetcher(HTTPFetcher): """Fetcher that wraps another fetcher, causing all exceptions @cvar uncaught_exceptions: Exceptions that should be exposed to the user if they are raised by the fetch call """ uncaught_exceptions = (SystemExit, KeyboardInterrupt, MemoryError) def __init__(self, fetcher): self.fetcher = fetcher def fetch(self, *args, **kwargs): try: return self.fetcher.fetch(*args, **kwargs) except self.uncaught_exceptions: raise except: exc_cls, exc_inst = sys.exc_info()[:2] if exc_inst is None: # string exceptions exc_inst = exc_cls raise HTTPFetchingError(why=exc_inst) class Urllib2Fetcher(HTTPFetcher): """An C{L{HTTPFetcher}} that uses urllib2. """ # Parameterized for the benefit of testing frameworks, see # http://trac.openidenabled.com/trac/ticket/85 urlopen = staticmethod(urllib2.urlopen) def fetch(self, url, body=None, headers=None): if not _allowedURL(url): raise ValueError('Bad URL scheme: %r' % (url,)) if headers is None: headers = {} headers.setdefault( 'User-Agent', "%s Python-urllib/%s" % (USER_AGENT, urllib2.__version__,)) req = urllib2.Request(url, data=body, headers=headers) try: f = self.urlopen(req) try: return self._makeResponse(f) finally: f.close() except urllib2.HTTPError, why: try: return self._makeResponse(why) finally: why.close() def _makeResponse(self, urllib2_response): resp = HTTPResponse() resp.body = urllib2_response.read(MAX_RESPONSE_KB * 1024) resp.final_url = urllib2_response.geturl() resp.headers = dict(urllib2_response.info().items()) if hasattr(urllib2_response, 'code'): resp.status = urllib2_response.code else: resp.status = 200 return resp class HTTPError(HTTPFetchingError): """ This exception is raised by the C{L{CurlHTTPFetcher}} when it encounters an exceptional situation fetching a URL. """ pass # XXX: define what we mean by paranoid, and make sure it is. class CurlHTTPFetcher(HTTPFetcher): """ An C{L{HTTPFetcher}} that uses pycurl for fetching. See U{http://pycurl.sourceforge.net/}. """ ALLOWED_TIME = 20 # seconds def __init__(self): HTTPFetcher.__init__(self) if pycurl is None: raise RuntimeError('Cannot find pycurl library') def _parseHeaders(self, header_file): header_file.seek(0) # Remove the status line from the beginning of the input unused_http_status_line = header_file.readline().lower () if unused_http_status_line.startswith('http/1.1 100 '): unused_http_status_line = header_file.readline() unused_http_status_line = header_file.readline() lines = [line.strip() for line in header_file] # and the blank line from the end empty_line = lines.pop() if empty_line: raise HTTPError("No blank line at end of headers: %r" % (line,)) headers = {} for line in lines: try: name, value = line.split(':', 1) except ValueError: raise HTTPError( "Malformed HTTP header line in response: %r" % (line,)) value = value.strip() # HTTP headers are case-insensitive name = name.lower() headers[name] = value return headers def _checkURL(self, url): # XXX: document that this can be overridden to match desired policy # XXX: make sure url is well-formed and routeable return _allowedURL(url) def fetch(self, url, body=None, headers=None): stop = int(time.time()) + self.ALLOWED_TIME off = self.ALLOWED_TIME if headers is None: headers = {} headers.setdefault('User-Agent', "%s %s" % (USER_AGENT, pycurl.version,)) header_list = [] if headers is not None: for header_name, header_value in headers.iteritems(): header_list.append('%s: %s' % (header_name, header_value)) c = pycurl.Curl() try: c.setopt(pycurl.NOSIGNAL, 1) if header_list: c.setopt(pycurl.HTTPHEADER, header_list) # Presence of a body indicates that we should do a POST if body is not None: c.setopt(pycurl.POST, 1) c.setopt(pycurl.POSTFIELDS, body) while off > 0: if not self._checkURL(url): raise HTTPError("Fetching URL not allowed: %r" % (url,)) data = cStringIO.StringIO() def write_data(chunk): if data.tell() > 1024*MAX_RESPONSE_KB: return 0 else: return data.write(chunk) response_header_data = cStringIO.StringIO() c.setopt(pycurl.WRITEFUNCTION, write_data) c.setopt(pycurl.HEADERFUNCTION, response_header_data.write) c.setopt(pycurl.TIMEOUT, off) c.setopt(pycurl.URL, openid.urinorm.urinorm(url)) c.perform() response_headers = self._parseHeaders(response_header_data) code = c.getinfo(pycurl.RESPONSE_CODE) if code in [301, 302, 303, 307]: url = response_headers.get('location') if url is None: raise HTTPError( 'Redirect (%s) returned without a location' % code) # Redirects are always GETs c.setopt(pycurl.POST, 0) # There is no way to reset POSTFIELDS to empty and # reuse the connection, but we only use it once. else: resp = HTTPResponse() resp.headers = response_headers resp.status = code resp.final_url = url resp.body = data.getvalue() return resp off = stop - int(time.time()) raise HTTPError("Timed out fetching: %r" % (url,)) finally: c.close() class HTTPLib2Fetcher(HTTPFetcher): """A fetcher that uses C{httplib2} for performing HTTP requests. This implementation supports HTTP caching. @see: http://bitworking.org/projects/httplib2/ """ def __init__(self, cache=None): """@param cache: An object suitable for use as an C{httplib2} cache. If a string is passed, it is assumed to be a directory name. """ if httplib2 is None: raise RuntimeError('Cannot find httplib2 library. ' 'See http://bitworking.org/projects/httplib2/') super(HTTPLib2Fetcher, self).__init__() # An instance of the httplib2 object that performs HTTP requests self.httplib2 = httplib2.Http(cache) # We want httplib2 to raise exceptions for errors, just like # the other fetchers. self.httplib2.force_exception_to_status_code = False def fetch(self, url, body=None, headers=None): """Perform an HTTP request @raises Exception: Any exception that can be raised by httplib2 @see: C{L{HTTPFetcher.fetch}} """ if body: method = 'POST' else: method = 'GET' if headers is None: headers = {} # httplib2 doesn't check to make sure that the URL's scheme is # 'http' so we do it here. if not (url.startswith('http://') or url.startswith('https://')): raise ValueError('URL is not a HTTP URL: %r' % (url,)) httplib2_response, content = self.httplib2.request( url, method, body=body, headers=headers) # Translate the httplib2 response to our HTTP response abstraction # When a 400 is returned, there is no "content-location" # header set. This seems like a bug to me. I can't think of a # case where we really care about the final URL when it is an # error response, but being careful about it can't hurt. try: final_url = httplib2_response['content-location'] except KeyError: # We're assuming that no redirects occurred assert not httplib2_response.previous # And this should never happen for a successful response assert httplib2_response.status != 200 final_url = url return HTTPResponse( body=content, final_url=final_url, headers=dict(httplib2_response.items()), status=httplib2_response.status, )
apache-2.0
Innovahn/odoo.old
addons/account_bank_statement_extensions/__init__.py
442
1153
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # # Copyright (c) 2011 Noviat nv/sa (www.noviat.be). All rights reserved. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import account_bank_statement import res_partner_bank import report import wizard # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
kirbyfan64/shedskin
tests/123.py
6
9445
# (c) Jack Ha # --- jack.ha@gmail.com def validMove(puzzle, x, y, number): # puzzle: [list(list(int))], x: [int], y: [int], number: [int] #see if the number is in any row, column or his own 3x3 square blnOK = True # [int] px = x / 3 # [int] py = y / 3 # [int] if puzzle[x][y] != 0: # [int] blnOK = False # [int] if blnOK: # [] for i in range(9): # [list(int)] if puzzle[i][y] == number: # [int] blnOK = False # [int] if blnOK: # [] for j in range(9): # [list(int)] if puzzle[x][j] == number: # [int] blnOK = False # [int] if blnOK: # [] for i in range(3): # [list(int)] for j in range(3): # [list(int)] if puzzle[px*3+i][py*3+j] == number: # [int] blnOK = False # [int] return blnOK # [int] def findallMoves(puzzle,x,y): # puzzle: [list(list(int))], x: [int], y: [int] returnList = [] # [list(int)] for n in range(1,10): # [list(int)] if validMove(puzzle, x, y, n): # [int] returnList.append(n) # [] return returnList # [list(int)] def solvePuzzleStep(puzzle): # puzzle: [list(list(int))] isChanged = False # [int] for y in range(9): # [list(int)] for x in range(9): # [list(int)] if puzzle[x][y] == 0: # [int] allMoves = findallMoves(puzzle, x, y) # [list(int)] if len(allMoves) == 1: # [int] puzzle[x][y] = allMoves[0] # [int] isChanged = True # [int] return isChanged # [int] #try to solve as much as possible without lookahead def solvePuzzleSimple(puzzle): # puzzle: [list(list(int))] iterationCount = 0 # [int] while solvePuzzleStep(puzzle) == True: # [int] iterationCount += 1 # [int] hashtable = {} # [dict(int, int)] def calc_hash(puzzle): # puzzle: [list(list(int))] hashcode = 0 # [int] for c in range(9): # [list(int)] hashcode = hashcode * 17 + hash(tuple(puzzle[c])) # [int] return hashcode # [int] def hash_add(puzzle): # puzzle: [list(list(int))] hashtable[calc_hash(puzzle)] = 1 # [int] def hash_lookup(puzzle): # puzzle: [list(list(int))] return hashtable.has_key(calc_hash(puzzle)) # [int] #solve with lookahead #unit is 3x3, (i,j) is coords of unit. l is the list of all todo's def perm(puzzle, i, j, l, u): # puzzle: [list(list(int))], i: [int], j: [int], l: [list(int)], u: [list(tuple(int))] global iterations iterations += 1 # [int] if (u == []) and (l == []): # [int] print "Solved!" # [str] #printpuzzle(puzzle) # [] print "iterations: ", iterations # [str], [int] return True # [int] else: if l == []: # [int] #here we have all permutations for one unit #some simple moves puzzlebackup = [] # [list(tuple(int))] for c in range(9): # [list(int)] puzzlebackup.append(tuple(puzzle[c])) # [] solvePuzzleSimple(puzzle) # [] #next unit to fill for c in range(len(u)): # [list(int)] if not hash_lookup(puzzle): # [int] inew, jnew = u.pop(c) # [tuple(int)] l = genMoveList(puzzle, inew, jnew) # [list(int)] #only print new situations #print "inew, jnew, l, u:", inew, jnew, l, u # [str], [int], [int], [list(int)], [list(tuple(int))] #printpuzzle(puzzle) # [] #print "iterations: ", iterations # [str], [int] if perm (puzzle, inew, jnew, l, u): # [int] return True # [int] else: hash_add(puzzle) # [] u.insert(c, (inew, jnew)) # [] #undo simple moves for y in range(9): # [list(int)] for x in range(9): # [list(int)] puzzle[x][y] = puzzlebackup[x][y] # [int] hash_add(puzzle) # [] return False # [int] else: #try all possibilities of one unit ii = i * 3 # [int] jj = j * 3 # [int] for m in range(len(l)): # [list(int)] #find first empty for y in range(3): # [list(int)] for x in range(3): # [list(int)] if validMove(puzzle, x+ii, y+jj, l[m]): # [int] puzzle[x+ii][y+jj] = l[m] # [int] backup = l.pop(m) # [int] if (perm(puzzle, i, j, l, u)): # [int] return True # [int] else: hash_add(puzzle) # [] l.insert(m, backup) # [] puzzle[x+ii][y+jj] = 0 # [int] return False # [int] #gen move list for unit (i,j) def genMoveList(puzzle, i, j): # puzzle: [list(list(int))], i: [int], j: [int] l = range(1,10) # [list(int)] for y in range(3): # [list(int)] for x in range(3): # [list(int)] p = puzzle[i*3+x][j*3+y] # [int] if p != 0: # [int] l.remove(p) # [] return l # [list(int)] def printpuzzle(puzzle): # puzzle: [list(list(int))] for x in range(9): # [list(int)] s = ' ' # [str] for y in range(9): # [list(int)] p = puzzle[x][y] # [int] if p == 0: # [int] s += '.' # [str] else: s += str(puzzle[x][y]) # [str] s += ' ' # [str] print s # [str] def main(): puzzle = [[0, 9, 3, 0, 8, 0, 4, 0, 0], # [list(list(int))] [0, 4, 0, 0, 3, 0, 0, 0, 0], # [list(int)] [6, 0, 0, 0, 0, 9, 2, 0, 5], # [list(int)] [3, 0, 0, 0, 0, 0, 0, 9, 0], # [list(int)] [0, 2, 7, 0, 0, 0, 5, 1, 0], # [list(int)] [0, 8, 0, 0, 0, 0, 0, 0, 4], # [list(int)] [7, 0, 1, 6, 0, 0, 0, 0, 2], # [list(int)] [0, 0, 0, 0, 7, 0, 0, 6, 0], # [list(int)] [0, 0, 4, 0, 1, 0, 8, 5, 0]] # [list(int)] #create todo unit(each 3x3) list (this is also the order that they will be tried!) u = [] # [list(tuple(int))] lcount = [] # [list(int)] for y in range(3): # [list(int)] for x in range(3): # [list(int)] u.append((x,y)) # [] lcount.append(len(genMoveList(puzzle, x, y))) # [] #sort for j in range(0,9): # [list(int)] for i in range(j,9): # [list(int)] if i != j: # [int] if lcount[i] < lcount[j]: # [int] u[i], u[j] = u[j], u[i] lcount[i], lcount[j] = lcount[j], lcount[i] l = genMoveList(puzzle, 0, 0) # [list(int)] perm (puzzle, 0, 0, l, u) # [int] iterations = 0 # [int] for x in range(30): main() # []
gpl-3.0
pniedzielski/fb-hackathon-2013-11-21
src/repl.it/jsrepl/extern/python/unclosured/lib/python2.7/encodings/cp424.py
593
12311
""" Python Character Mapping Codec cp424 generated from 'MAPPINGS/VENDORS/MISC/CP424.TXT' with gencodec.py. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_table) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_table) class IncrementalEncoder(codecs.IncrementalEncoder): def encode(self, input, final=False): return codecs.charmap_encode(input,self.errors,encoding_table)[0] class IncrementalDecoder(codecs.IncrementalDecoder): def decode(self, input, final=False): return codecs.charmap_decode(input,self.errors,decoding_table)[0] class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return codecs.CodecInfo( name='cp424', encode=Codec().encode, decode=Codec().decode, incrementalencoder=IncrementalEncoder, incrementaldecoder=IncrementalDecoder, streamreader=StreamReader, streamwriter=StreamWriter, ) ### Decoding Table decoding_table = ( u'\x00' # 0x00 -> NULL u'\x01' # 0x01 -> START OF HEADING u'\x02' # 0x02 -> START OF TEXT u'\x03' # 0x03 -> END OF TEXT u'\x9c' # 0x04 -> SELECT u'\t' # 0x05 -> HORIZONTAL TABULATION u'\x86' # 0x06 -> REQUIRED NEW LINE u'\x7f' # 0x07 -> DELETE u'\x97' # 0x08 -> GRAPHIC ESCAPE u'\x8d' # 0x09 -> SUPERSCRIPT u'\x8e' # 0x0A -> REPEAT u'\x0b' # 0x0B -> VERTICAL TABULATION u'\x0c' # 0x0C -> FORM FEED u'\r' # 0x0D -> CARRIAGE RETURN u'\x0e' # 0x0E -> SHIFT OUT u'\x0f' # 0x0F -> SHIFT IN u'\x10' # 0x10 -> DATA LINK ESCAPE u'\x11' # 0x11 -> DEVICE CONTROL ONE u'\x12' # 0x12 -> DEVICE CONTROL TWO u'\x13' # 0x13 -> DEVICE CONTROL THREE u'\x9d' # 0x14 -> RESTORE/ENABLE PRESENTATION u'\x85' # 0x15 -> NEW LINE u'\x08' # 0x16 -> BACKSPACE u'\x87' # 0x17 -> PROGRAM OPERATOR COMMUNICATION u'\x18' # 0x18 -> CANCEL u'\x19' # 0x19 -> END OF MEDIUM u'\x92' # 0x1A -> UNIT BACK SPACE u'\x8f' # 0x1B -> CUSTOMER USE ONE u'\x1c' # 0x1C -> FILE SEPARATOR u'\x1d' # 0x1D -> GROUP SEPARATOR u'\x1e' # 0x1E -> RECORD SEPARATOR u'\x1f' # 0x1F -> UNIT SEPARATOR u'\x80' # 0x20 -> DIGIT SELECT u'\x81' # 0x21 -> START OF SIGNIFICANCE u'\x82' # 0x22 -> FIELD SEPARATOR u'\x83' # 0x23 -> WORD UNDERSCORE u'\x84' # 0x24 -> BYPASS OR INHIBIT PRESENTATION u'\n' # 0x25 -> LINE FEED u'\x17' # 0x26 -> END OF TRANSMISSION BLOCK u'\x1b' # 0x27 -> ESCAPE u'\x88' # 0x28 -> SET ATTRIBUTE u'\x89' # 0x29 -> START FIELD EXTENDED u'\x8a' # 0x2A -> SET MODE OR SWITCH u'\x8b' # 0x2B -> CONTROL SEQUENCE PREFIX u'\x8c' # 0x2C -> MODIFY FIELD ATTRIBUTE u'\x05' # 0x2D -> ENQUIRY u'\x06' # 0x2E -> ACKNOWLEDGE u'\x07' # 0x2F -> BELL u'\x90' # 0x30 -> <reserved> u'\x91' # 0x31 -> <reserved> u'\x16' # 0x32 -> SYNCHRONOUS IDLE u'\x93' # 0x33 -> INDEX RETURN u'\x94' # 0x34 -> PRESENTATION POSITION u'\x95' # 0x35 -> TRANSPARENT u'\x96' # 0x36 -> NUMERIC BACKSPACE u'\x04' # 0x37 -> END OF TRANSMISSION u'\x98' # 0x38 -> SUBSCRIPT u'\x99' # 0x39 -> INDENT TABULATION u'\x9a' # 0x3A -> REVERSE FORM FEED u'\x9b' # 0x3B -> CUSTOMER USE THREE u'\x14' # 0x3C -> DEVICE CONTROL FOUR u'\x15' # 0x3D -> NEGATIVE ACKNOWLEDGE u'\x9e' # 0x3E -> <reserved> u'\x1a' # 0x3F -> SUBSTITUTE u' ' # 0x40 -> SPACE u'\u05d0' # 0x41 -> HEBREW LETTER ALEF u'\u05d1' # 0x42 -> HEBREW LETTER BET u'\u05d2' # 0x43 -> HEBREW LETTER GIMEL u'\u05d3' # 0x44 -> HEBREW LETTER DALET u'\u05d4' # 0x45 -> HEBREW LETTER HE u'\u05d5' # 0x46 -> HEBREW LETTER VAV u'\u05d6' # 0x47 -> HEBREW LETTER ZAYIN u'\u05d7' # 0x48 -> HEBREW LETTER HET u'\u05d8' # 0x49 -> HEBREW LETTER TET u'\xa2' # 0x4A -> CENT SIGN u'.' # 0x4B -> FULL STOP u'<' # 0x4C -> LESS-THAN SIGN u'(' # 0x4D -> LEFT PARENTHESIS u'+' # 0x4E -> PLUS SIGN u'|' # 0x4F -> VERTICAL LINE u'&' # 0x50 -> AMPERSAND u'\u05d9' # 0x51 -> HEBREW LETTER YOD u'\u05da' # 0x52 -> HEBREW LETTER FINAL KAF u'\u05db' # 0x53 -> HEBREW LETTER KAF u'\u05dc' # 0x54 -> HEBREW LETTER LAMED u'\u05dd' # 0x55 -> HEBREW LETTER FINAL MEM u'\u05de' # 0x56 -> HEBREW LETTER MEM u'\u05df' # 0x57 -> HEBREW LETTER FINAL NUN u'\u05e0' # 0x58 -> HEBREW LETTER NUN u'\u05e1' # 0x59 -> HEBREW LETTER SAMEKH u'!' # 0x5A -> EXCLAMATION MARK u'$' # 0x5B -> DOLLAR SIGN u'*' # 0x5C -> ASTERISK u')' # 0x5D -> RIGHT PARENTHESIS u';' # 0x5E -> SEMICOLON u'\xac' # 0x5F -> NOT SIGN u'-' # 0x60 -> HYPHEN-MINUS u'/' # 0x61 -> SOLIDUS u'\u05e2' # 0x62 -> HEBREW LETTER AYIN u'\u05e3' # 0x63 -> HEBREW LETTER FINAL PE u'\u05e4' # 0x64 -> HEBREW LETTER PE u'\u05e5' # 0x65 -> HEBREW LETTER FINAL TSADI u'\u05e6' # 0x66 -> HEBREW LETTER TSADI u'\u05e7' # 0x67 -> HEBREW LETTER QOF u'\u05e8' # 0x68 -> HEBREW LETTER RESH u'\u05e9' # 0x69 -> HEBREW LETTER SHIN u'\xa6' # 0x6A -> BROKEN BAR u',' # 0x6B -> COMMA u'%' # 0x6C -> PERCENT SIGN u'_' # 0x6D -> LOW LINE u'>' # 0x6E -> GREATER-THAN SIGN u'?' # 0x6F -> QUESTION MARK u'\ufffe' # 0x70 -> UNDEFINED u'\u05ea' # 0x71 -> HEBREW LETTER TAV u'\ufffe' # 0x72 -> UNDEFINED u'\ufffe' # 0x73 -> UNDEFINED u'\xa0' # 0x74 -> NO-BREAK SPACE u'\ufffe' # 0x75 -> UNDEFINED u'\ufffe' # 0x76 -> UNDEFINED u'\ufffe' # 0x77 -> UNDEFINED u'\u2017' # 0x78 -> DOUBLE LOW LINE u'`' # 0x79 -> GRAVE ACCENT u':' # 0x7A -> COLON u'#' # 0x7B -> NUMBER SIGN u'@' # 0x7C -> COMMERCIAL AT u"'" # 0x7D -> APOSTROPHE u'=' # 0x7E -> EQUALS SIGN u'"' # 0x7F -> QUOTATION MARK u'\ufffe' # 0x80 -> UNDEFINED u'a' # 0x81 -> LATIN SMALL LETTER A u'b' # 0x82 -> LATIN SMALL LETTER B u'c' # 0x83 -> LATIN SMALL LETTER C u'd' # 0x84 -> LATIN SMALL LETTER D u'e' # 0x85 -> LATIN SMALL LETTER E u'f' # 0x86 -> LATIN SMALL LETTER F u'g' # 0x87 -> LATIN SMALL LETTER G u'h' # 0x88 -> LATIN SMALL LETTER H u'i' # 0x89 -> LATIN SMALL LETTER I u'\xab' # 0x8A -> LEFT-POINTING DOUBLE ANGLE QUOTATION MARK u'\xbb' # 0x8B -> RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK u'\ufffe' # 0x8C -> UNDEFINED u'\ufffe' # 0x8D -> UNDEFINED u'\ufffe' # 0x8E -> UNDEFINED u'\xb1' # 0x8F -> PLUS-MINUS SIGN u'\xb0' # 0x90 -> DEGREE SIGN u'j' # 0x91 -> LATIN SMALL LETTER J u'k' # 0x92 -> LATIN SMALL LETTER K u'l' # 0x93 -> LATIN SMALL LETTER L u'm' # 0x94 -> LATIN SMALL LETTER M u'n' # 0x95 -> LATIN SMALL LETTER N u'o' # 0x96 -> LATIN SMALL LETTER O u'p' # 0x97 -> LATIN SMALL LETTER P u'q' # 0x98 -> LATIN SMALL LETTER Q u'r' # 0x99 -> LATIN SMALL LETTER R u'\ufffe' # 0x9A -> UNDEFINED u'\ufffe' # 0x9B -> UNDEFINED u'\ufffe' # 0x9C -> UNDEFINED u'\xb8' # 0x9D -> CEDILLA u'\ufffe' # 0x9E -> UNDEFINED u'\xa4' # 0x9F -> CURRENCY SIGN u'\xb5' # 0xA0 -> MICRO SIGN u'~' # 0xA1 -> TILDE u's' # 0xA2 -> LATIN SMALL LETTER S u't' # 0xA3 -> LATIN SMALL LETTER T u'u' # 0xA4 -> LATIN SMALL LETTER U u'v' # 0xA5 -> LATIN SMALL LETTER V u'w' # 0xA6 -> LATIN SMALL LETTER W u'x' # 0xA7 -> LATIN SMALL LETTER X u'y' # 0xA8 -> LATIN SMALL LETTER Y u'z' # 0xA9 -> LATIN SMALL LETTER Z u'\ufffe' # 0xAA -> UNDEFINED u'\ufffe' # 0xAB -> UNDEFINED u'\ufffe' # 0xAC -> UNDEFINED u'\ufffe' # 0xAD -> UNDEFINED u'\ufffe' # 0xAE -> UNDEFINED u'\xae' # 0xAF -> REGISTERED SIGN u'^' # 0xB0 -> CIRCUMFLEX ACCENT u'\xa3' # 0xB1 -> POUND SIGN u'\xa5' # 0xB2 -> YEN SIGN u'\xb7' # 0xB3 -> MIDDLE DOT u'\xa9' # 0xB4 -> COPYRIGHT SIGN u'\xa7' # 0xB5 -> SECTION SIGN u'\xb6' # 0xB6 -> PILCROW SIGN u'\xbc' # 0xB7 -> VULGAR FRACTION ONE QUARTER u'\xbd' # 0xB8 -> VULGAR FRACTION ONE HALF u'\xbe' # 0xB9 -> VULGAR FRACTION THREE QUARTERS u'[' # 0xBA -> LEFT SQUARE BRACKET u']' # 0xBB -> RIGHT SQUARE BRACKET u'\xaf' # 0xBC -> MACRON u'\xa8' # 0xBD -> DIAERESIS u'\xb4' # 0xBE -> ACUTE ACCENT u'\xd7' # 0xBF -> MULTIPLICATION SIGN u'{' # 0xC0 -> LEFT CURLY BRACKET u'A' # 0xC1 -> LATIN CAPITAL LETTER A u'B' # 0xC2 -> LATIN CAPITAL LETTER B u'C' # 0xC3 -> LATIN CAPITAL LETTER C u'D' # 0xC4 -> LATIN CAPITAL LETTER D u'E' # 0xC5 -> LATIN CAPITAL LETTER E u'F' # 0xC6 -> LATIN CAPITAL LETTER F u'G' # 0xC7 -> LATIN CAPITAL LETTER G u'H' # 0xC8 -> LATIN CAPITAL LETTER H u'I' # 0xC9 -> LATIN CAPITAL LETTER I u'\xad' # 0xCA -> SOFT HYPHEN u'\ufffe' # 0xCB -> UNDEFINED u'\ufffe' # 0xCC -> UNDEFINED u'\ufffe' # 0xCD -> UNDEFINED u'\ufffe' # 0xCE -> UNDEFINED u'\ufffe' # 0xCF -> UNDEFINED u'}' # 0xD0 -> RIGHT CURLY BRACKET u'J' # 0xD1 -> LATIN CAPITAL LETTER J u'K' # 0xD2 -> LATIN CAPITAL LETTER K u'L' # 0xD3 -> LATIN CAPITAL LETTER L u'M' # 0xD4 -> LATIN CAPITAL LETTER M u'N' # 0xD5 -> LATIN CAPITAL LETTER N u'O' # 0xD6 -> LATIN CAPITAL LETTER O u'P' # 0xD7 -> LATIN CAPITAL LETTER P u'Q' # 0xD8 -> LATIN CAPITAL LETTER Q u'R' # 0xD9 -> LATIN CAPITAL LETTER R u'\xb9' # 0xDA -> SUPERSCRIPT ONE u'\ufffe' # 0xDB -> UNDEFINED u'\ufffe' # 0xDC -> UNDEFINED u'\ufffe' # 0xDD -> UNDEFINED u'\ufffe' # 0xDE -> UNDEFINED u'\ufffe' # 0xDF -> UNDEFINED u'\\' # 0xE0 -> REVERSE SOLIDUS u'\xf7' # 0xE1 -> DIVISION SIGN u'S' # 0xE2 -> LATIN CAPITAL LETTER S u'T' # 0xE3 -> LATIN CAPITAL LETTER T u'U' # 0xE4 -> LATIN CAPITAL LETTER U u'V' # 0xE5 -> LATIN CAPITAL LETTER V u'W' # 0xE6 -> LATIN CAPITAL LETTER W u'X' # 0xE7 -> LATIN CAPITAL LETTER X u'Y' # 0xE8 -> LATIN CAPITAL LETTER Y u'Z' # 0xE9 -> LATIN CAPITAL LETTER Z u'\xb2' # 0xEA -> SUPERSCRIPT TWO u'\ufffe' # 0xEB -> UNDEFINED u'\ufffe' # 0xEC -> UNDEFINED u'\ufffe' # 0xED -> UNDEFINED u'\ufffe' # 0xEE -> UNDEFINED u'\ufffe' # 0xEF -> UNDEFINED u'0' # 0xF0 -> DIGIT ZERO u'1' # 0xF1 -> DIGIT ONE u'2' # 0xF2 -> DIGIT TWO u'3' # 0xF3 -> DIGIT THREE u'4' # 0xF4 -> DIGIT FOUR u'5' # 0xF5 -> DIGIT FIVE u'6' # 0xF6 -> DIGIT SIX u'7' # 0xF7 -> DIGIT SEVEN u'8' # 0xF8 -> DIGIT EIGHT u'9' # 0xF9 -> DIGIT NINE u'\xb3' # 0xFA -> SUPERSCRIPT THREE u'\ufffe' # 0xFB -> UNDEFINED u'\ufffe' # 0xFC -> UNDEFINED u'\ufffe' # 0xFD -> UNDEFINED u'\ufffe' # 0xFE -> UNDEFINED u'\x9f' # 0xFF -> EIGHT ONES ) ### Encoding table encoding_table=codecs.charmap_build(decoding_table)
agpl-3.0
Maximilian-Reuter/SickRage-1
lib/simplejson/encoder.py
343
16033
"""Implementation of JSONEncoder """ import re try: from simplejson._speedups import encode_basestring_ascii as c_encode_basestring_ascii except ImportError: c_encode_basestring_ascii = None try: from simplejson._speedups import make_encoder as c_make_encoder except ImportError: c_make_encoder = None ESCAPE = re.compile(r'[\x00-\x1f\\"\b\f\n\r\t]') ESCAPE_ASCII = re.compile(r'([\\"]|[^\ -~])') HAS_UTF8 = re.compile(r'[\x80-\xff]') ESCAPE_DCT = { '\\': '\\\\', '"': '\\"', '\b': '\\b', '\f': '\\f', '\n': '\\n', '\r': '\\r', '\t': '\\t', } for i in range(0x20): #ESCAPE_DCT.setdefault(chr(i), '\\u{0:04x}'.format(i)) ESCAPE_DCT.setdefault(chr(i), '\\u%04x' % (i,)) # Assume this produces an infinity on all machines (probably not guaranteed) INFINITY = float('1e66666') FLOAT_REPR = repr def encode_basestring(s): """Return a JSON representation of a Python string """ def replace(match): return ESCAPE_DCT[match.group(0)] return '"' + ESCAPE.sub(replace, s) + '"' def py_encode_basestring_ascii(s): """Return an ASCII-only JSON representation of a Python string """ if isinstance(s, str) and HAS_UTF8.search(s) is not None: s = s.decode('utf-8') def replace(match): s = match.group(0) try: return ESCAPE_DCT[s] except KeyError: n = ord(s) if n < 0x10000: #return '\\u{0:04x}'.format(n) return '\\u%04x' % (n,) else: # surrogate pair n -= 0x10000 s1 = 0xd800 | ((n >> 10) & 0x3ff) s2 = 0xdc00 | (n & 0x3ff) #return '\\u{0:04x}\\u{1:04x}'.format(s1, s2) return '\\u%04x\\u%04x' % (s1, s2) return '"' + str(ESCAPE_ASCII.sub(replace, s)) + '"' encode_basestring_ascii = c_encode_basestring_ascii or py_encode_basestring_ascii class JSONEncoder(object): """Extensible JSON <http://json.org> encoder for Python data structures. Supports the following objects and types by default: +-------------------+---------------+ | Python | JSON | +===================+===============+ | dict | object | +-------------------+---------------+ | list, tuple | array | +-------------------+---------------+ | str, unicode | string | +-------------------+---------------+ | int, long, float | number | +-------------------+---------------+ | True | true | +-------------------+---------------+ | False | false | +-------------------+---------------+ | None | null | +-------------------+---------------+ To extend this to recognize other objects, subclass and implement a ``.default()`` method with another method that returns a serializable object for ``o`` if possible, otherwise it should call the superclass implementation (to raise ``TypeError``). """ item_separator = ', ' key_separator = ': ' def __init__(self, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, encoding='utf-8', default=None): """Constructor for JSONEncoder, with sensible defaults. If skipkeys is false, then it is a TypeError to attempt encoding of keys that are not str, int, long, float or None. If skipkeys is True, such items are simply skipped. If ensure_ascii is true, the output is guaranteed to be str objects with all incoming unicode characters escaped. If ensure_ascii is false, the output will be unicode object. If check_circular is true, then lists, dicts, and custom encoded objects will be checked for circular references during encoding to prevent an infinite recursion (which would cause an OverflowError). Otherwise, no such check takes place. If allow_nan is true, then NaN, Infinity, and -Infinity will be encoded as such. This behavior is not JSON specification compliant, but is consistent with most JavaScript based encoders and decoders. Otherwise, it will be a ValueError to encode such floats. If sort_keys is true, then the output of dictionaries will be sorted by key; this is useful for regression tests to ensure that JSON serializations can be compared on a day-to-day basis. If indent is a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. None is the most compact representation. If specified, separators should be a (item_separator, key_separator) tuple. The default is (', ', ': '). To get the most compact JSON representation you should specify (',', ':') to eliminate whitespace. If specified, default is a function that gets called for objects that can't otherwise be serialized. It should return a JSON encodable version of the object or raise a ``TypeError``. If encoding is not None, then all input strings will be transformed into unicode using that encoding prior to JSON-encoding. The default is UTF-8. """ self.skipkeys = skipkeys self.ensure_ascii = ensure_ascii self.check_circular = check_circular self.allow_nan = allow_nan self.sort_keys = sort_keys self.indent = indent if separators is not None: self.item_separator, self.key_separator = separators if default is not None: self.default = default self.encoding = encoding def default(self, o): """Implement this method in a subclass such that it returns a serializable object for ``o``, or calls the base implementation (to raise a ``TypeError``). For example, to support arbitrary iterators, you could implement default like this:: def default(self, o): try: iterable = iter(o) except TypeError: pass else: return list(iterable) return JSONEncoder.default(self, o) """ raise TypeError(repr(o) + " is not JSON serializable") def encode(self, o): """Return a JSON string representation of a Python data structure. >>> JSONEncoder().encode({"foo": ["bar", "baz"]}) '{"foo": ["bar", "baz"]}' """ # This is for extremely simple cases and benchmarks. if isinstance(o, basestring): if isinstance(o, str): _encoding = self.encoding if (_encoding is not None and not (_encoding == 'utf-8')): o = o.decode(_encoding) if self.ensure_ascii: return encode_basestring_ascii(o) else: return encode_basestring(o) # This doesn't pass the iterator directly to ''.join() because the # exceptions aren't as detailed. The list call should be roughly # equivalent to the PySequence_Fast that ''.join() would do. chunks = self.iterencode(o, _one_shot=True) if not isinstance(chunks, (list, tuple)): chunks = list(chunks) return ''.join(chunks) def iterencode(self, o, _one_shot=False): """Encode the given object and yield each string representation as available. For example:: for chunk in JSONEncoder().iterencode(bigobject): mysocket.write(chunk) """ if self.check_circular: markers = {} else: markers = None if self.ensure_ascii: _encoder = encode_basestring_ascii else: _encoder = encode_basestring if self.encoding != 'utf-8': def _encoder(o, _orig_encoder=_encoder, _encoding=self.encoding): if isinstance(o, str): o = o.decode(_encoding) return _orig_encoder(o) def floatstr(o, allow_nan=self.allow_nan, _repr=FLOAT_REPR, _inf=INFINITY, _neginf=-INFINITY): # Check for specials. Note that this type of test is processor- and/or # platform-specific, so do tests which don't depend on the internals. if o != o: text = 'NaN' elif o == _inf: text = 'Infinity' elif o == _neginf: text = '-Infinity' else: return _repr(o) if not allow_nan: raise ValueError( "Out of range float values are not JSON compliant: " + repr(o)) return text if _one_shot and c_make_encoder is not None and not self.indent and not self.sort_keys: _iterencode = c_make_encoder( markers, self.default, _encoder, self.indent, self.key_separator, self.item_separator, self.sort_keys, self.skipkeys, self.allow_nan) else: _iterencode = _make_iterencode( markers, self.default, _encoder, self.indent, floatstr, self.key_separator, self.item_separator, self.sort_keys, self.skipkeys, _one_shot) return _iterencode(o, 0) def _make_iterencode(markers, _default, _encoder, _indent, _floatstr, _key_separator, _item_separator, _sort_keys, _skipkeys, _one_shot, ## HACK: hand-optimized bytecode; turn globals into locals False=False, True=True, ValueError=ValueError, basestring=basestring, dict=dict, float=float, id=id, int=int, isinstance=isinstance, list=list, long=long, str=str, tuple=tuple, ): def _iterencode_list(lst, _current_indent_level): if not lst: yield '[]' return if markers is not None: markerid = id(lst) if markerid in markers: raise ValueError("Circular reference detected") markers[markerid] = lst buf = '[' if _indent is not None: _current_indent_level += 1 newline_indent = '\n' + (' ' * (_indent * _current_indent_level)) separator = _item_separator + newline_indent buf += newline_indent else: newline_indent = None separator = _item_separator first = True for value in lst: if first: first = False else: buf = separator if isinstance(value, basestring): yield buf + _encoder(value) elif value is None: yield buf + 'null' elif value is True: yield buf + 'true' elif value is False: yield buf + 'false' elif isinstance(value, (int, long)): yield buf + str(value) elif isinstance(value, float): yield buf + _floatstr(value) else: yield buf if isinstance(value, (list, tuple)): chunks = _iterencode_list(value, _current_indent_level) elif isinstance(value, dict): chunks = _iterencode_dict(value, _current_indent_level) else: chunks = _iterencode(value, _current_indent_level) for chunk in chunks: yield chunk if newline_indent is not None: _current_indent_level -= 1 yield '\n' + (' ' * (_indent * _current_indent_level)) yield ']' if markers is not None: del markers[markerid] def _iterencode_dict(dct, _current_indent_level): if not dct: yield '{}' return if markers is not None: markerid = id(dct) if markerid in markers: raise ValueError("Circular reference detected") markers[markerid] = dct yield '{' if _indent is not None: _current_indent_level += 1 newline_indent = '\n' + (' ' * (_indent * _current_indent_level)) item_separator = _item_separator + newline_indent yield newline_indent else: newline_indent = None item_separator = _item_separator first = True if _sort_keys: items = dct.items() items.sort(key=lambda kv: kv[0]) else: items = dct.iteritems() for key, value in items: if isinstance(key, basestring): pass # JavaScript is weakly typed for these, so it makes sense to # also allow them. Many encoders seem to do something like this. elif isinstance(key, float): key = _floatstr(key) elif key is True: key = 'true' elif key is False: key = 'false' elif key is None: key = 'null' elif isinstance(key, (int, long)): key = str(key) elif _skipkeys: continue else: raise TypeError("key " + repr(key) + " is not a string") if first: first = False else: yield item_separator yield _encoder(key) yield _key_separator if isinstance(value, basestring): yield _encoder(value) elif value is None: yield 'null' elif value is True: yield 'true' elif value is False: yield 'false' elif isinstance(value, (int, long)): yield str(value) elif isinstance(value, float): yield _floatstr(value) else: if isinstance(value, (list, tuple)): chunks = _iterencode_list(value, _current_indent_level) elif isinstance(value, dict): chunks = _iterencode_dict(value, _current_indent_level) else: chunks = _iterencode(value, _current_indent_level) for chunk in chunks: yield chunk if newline_indent is not None: _current_indent_level -= 1 yield '\n' + (' ' * (_indent * _current_indent_level)) yield '}' if markers is not None: del markers[markerid] def _iterencode(o, _current_indent_level): if isinstance(o, basestring): yield _encoder(o) elif o is None: yield 'null' elif o is True: yield 'true' elif o is False: yield 'false' elif isinstance(o, (int, long)): yield str(o) elif isinstance(o, float): yield _floatstr(o) elif isinstance(o, (list, tuple)): for chunk in _iterencode_list(o, _current_indent_level): yield chunk elif isinstance(o, dict): for chunk in _iterencode_dict(o, _current_indent_level): yield chunk else: if markers is not None: markerid = id(o) if markerid in markers: raise ValueError("Circular reference detected") markers[markerid] = o o = _default(o) for chunk in _iterencode(o, _current_indent_level): yield chunk if markers is not None: del markers[markerid] return _iterencode
gpl-3.0
awkspace/ansible
test/units/plugins/strategy/test_strategy_linear.py
29
6509
# Copyright (c) 2018 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type from units.compat import unittest from units.compat.mock import patch, MagicMock from ansible.executor.play_iterator import PlayIterator from ansible.playbook import Playbook from ansible.playbook.play_context import PlayContext from ansible.plugins.strategy.linear import StrategyModule from ansible.executor.task_queue_manager import TaskQueueManager from units.mock.loader import DictDataLoader from units.mock.path import mock_unfrackpath_noop class TestStrategyLinear(unittest.TestCase): def setUp(self): pass def tearDown(self): pass @patch('ansible.playbook.role.definition.unfrackpath', mock_unfrackpath_noop) def test_noop(self): fake_loader = DictDataLoader({ "test_play.yml": """ - hosts: all gather_facts: no tasks: - block: - block: - name: task1 debug: msg='task1' failed_when: inventory_hostname == 'host01' - name: task2 debug: msg='task2' rescue: - name: rescue1 debug: msg='rescue1' - name: rescue2 debug: msg='rescue2' """, }) mock_var_manager = MagicMock() mock_var_manager._fact_cache = dict() mock_var_manager.get_vars.return_value = dict() p = Playbook.load('test_play.yml', loader=fake_loader, variable_manager=mock_var_manager) hosts = [] for i in range(0, 2): host = MagicMock() host.name = host.get_name.return_value = 'host%02d' % i hosts.append(host) mock_var_manager._fact_cache['host00'] = dict() inventory = MagicMock() inventory.get_hosts.return_value = hosts inventory.filter_hosts.return_value = hosts play_context = PlayContext(play=p._entries[0]) itr = PlayIterator( inventory=inventory, play=p._entries[0], play_context=play_context, variable_manager=mock_var_manager, all_vars=dict(), ) tqm = TaskQueueManager( inventory=inventory, variable_manager=mock_var_manager, loader=fake_loader, passwords=None, forks=5, ) tqm._initialize_processes(3) strategy = StrategyModule(tqm) # implicit meta: flush_handlers hosts_left = strategy.get_hosts_left(itr) hosts_tasks = strategy._get_next_task_lockstep(hosts_left, itr) host1_task = hosts_tasks[0][1] host2_task = hosts_tasks[1][1] self.assertIsNotNone(host1_task) self.assertIsNotNone(host2_task) self.assertEqual(host1_task.action, 'meta') self.assertEqual(host2_task.action, 'meta') # debug: task1, debug: task1 hosts_left = strategy.get_hosts_left(itr) hosts_tasks = strategy._get_next_task_lockstep(hosts_left, itr) host1_task = hosts_tasks[0][1] host2_task = hosts_tasks[1][1] self.assertIsNotNone(host1_task) self.assertIsNotNone(host2_task) self.assertEqual(host1_task.action, 'debug') self.assertEqual(host2_task.action, 'debug') self.assertEqual(host1_task.name, 'task1') self.assertEqual(host2_task.name, 'task1') # mark the second host failed itr.mark_host_failed(hosts[1]) # debug: task2, meta: noop hosts_left = strategy.get_hosts_left(itr) hosts_tasks = strategy._get_next_task_lockstep(hosts_left, itr) host1_task = hosts_tasks[0][1] host2_task = hosts_tasks[1][1] self.assertIsNotNone(host1_task) self.assertIsNotNone(host2_task) self.assertEqual(host1_task.action, 'debug') self.assertEqual(host2_task.action, 'meta') self.assertEqual(host1_task.name, 'task2') self.assertEqual(host2_task.name, '') # meta: noop, debug: rescue1 hosts_left = strategy.get_hosts_left(itr) hosts_tasks = strategy._get_next_task_lockstep(hosts_left, itr) host1_task = hosts_tasks[0][1] host2_task = hosts_tasks[1][1] self.assertIsNotNone(host1_task) self.assertIsNotNone(host2_task) self.assertEqual(host1_task.action, 'meta') self.assertEqual(host2_task.action, 'debug') self.assertEqual(host1_task.name, '') self.assertEqual(host2_task.name, 'rescue1') # meta: noop, debug: rescue2 hosts_left = strategy.get_hosts_left(itr) hosts_tasks = strategy._get_next_task_lockstep(hosts_left, itr) host1_task = hosts_tasks[0][1] host2_task = hosts_tasks[1][1] self.assertIsNotNone(host1_task) self.assertIsNotNone(host2_task) self.assertEqual(host1_task.action, 'meta') self.assertEqual(host2_task.action, 'debug') self.assertEqual(host1_task.name, '') self.assertEqual(host2_task.name, 'rescue2') # implicit meta: flush_handlers hosts_left = strategy.get_hosts_left(itr) hosts_tasks = strategy._get_next_task_lockstep(hosts_left, itr) host1_task = hosts_tasks[0][1] host2_task = hosts_tasks[1][1] self.assertIsNotNone(host1_task) self.assertIsNotNone(host2_task) self.assertEqual(host1_task.action, 'meta') self.assertEqual(host2_task.action, 'meta') # implicit meta: flush_handlers hosts_left = strategy.get_hosts_left(itr) hosts_tasks = strategy._get_next_task_lockstep(hosts_left, itr) host1_task = hosts_tasks[0][1] host2_task = hosts_tasks[1][1] self.assertIsNotNone(host1_task) self.assertIsNotNone(host2_task) self.assertEqual(host1_task.action, 'meta') self.assertEqual(host2_task.action, 'meta') # end of iteration hosts_left = strategy.get_hosts_left(itr) hosts_tasks = strategy._get_next_task_lockstep(hosts_left, itr) host1_task = hosts_tasks[0][1] host2_task = hosts_tasks[1][1] self.assertIsNone(host1_task) self.assertIsNone(host2_task)
gpl-3.0
helloworldC2/VirtualRobot
GuiHUD.py
1
22037
import scoring import pygame import gui import Game import selectBar from selectBar import * import Level from Level import * import Tile import EntityTreasure import Keyboard from pygame.locals import * from Image import * class GuiHUD(object): def __init__(self,screen): self.ebg = image(screen,(5,5),"menu/editbg.png") self.keys = None self.click = 0 self.tmp = 1 self.time = 1 self.tilesInBar = [Tile.grass,Tile.water,Tile.wall,Tile.sand,Tile.larva,Tile.cactus,Tile.quicksand] self.box = barItem(screen,(0,0),"tiles/select.png") self.trap = [barItem(screen,(90+120,500+50),"tiles/grass.png"), barItem(screen,(150+120,500+50),"tiles/water.png"), barItem(screen,(210+120,500+50),"tiles/wall.png"), barItem(screen,(270+120,500+50),"tiles/sand.png"), barItem(screen,(330+120,500+50),"tiles/larva.png"), barItem(screen,(390+120,500+50),"tiles/cactus.png"), barItem(screen,(450+120,500+50),"tiles/quicksand.png")] for i in self.trap: i.scale(48,48) self.healthbar = pygame.image.load('menu/Healthbar.png') self.bar = barItem(screen,(100,544),"menu/bar.png") self.t = [barItem(screen,(30+80,500+50),"tiles/brokenChest.png"), barItem(screen,(90+80,500+50),"tiles/burntChest.png"), barItem(screen,(150+80,500+50),"tiles/darkChest.png"), barItem(screen,(210+80,500+50),"tiles/glassChest.png"), barItem(screen,(270+80,500+50),"tiles/goldChest.png"), barItem(screen,(330+80,500+50),"tiles/normalChest.png"), barItem(screen,(390+80,500+50),"tiles/OverFlowChest.png"), barItem(screen,(450+80,500+50),"tiles/crystalChest.png"), barItem(screen,(510+80,500+50),"tiles/sandT.png"), barItem(screen,(570+80,500+50),"tiles/grownOverChest.png")] for i in range (10): self.t[i].scale(48,48) self.c = [barItem(screen,(30,500),"tiles/brokenChest.png"), barItem(screen,(80,500),"tiles/burntChest.png"), barItem(screen,(130,500),"tiles/darkChest.png"), barItem(screen,(180,500),"tiles/glassChest.png"), barItem(screen,(230,500),"tiles/goldChest.png"), barItem(screen,(280,500),"tiles/normalChest.png"), barItem(screen,(330,500),"tiles/OverFlowChest.png"), barItem(screen,(380,500),"tiles/crystalChest.png"), barItem(screen,(430,500),"tiles/sandT.png"), barItem(screen,(480,500),"tiles/grownOverChest.png")] for i in range (10): self.c[i].scale(32,32) self.font = pygame.font.SysFont("calibri",25) self.font.set_bold(1) self.txt = self.font.render("Treasure Description:",1,(250,250,250)) self.txt1 = self.font.render("Treasure Score:",1,(250,250,250)) self.txt2 = self.font.render("Put Treasure on the Wishlist:",1,(250,250,250)) return def render(self,screen,level,font,x,y): if gui.gameOver==True: font = pygame.font.SysFont(None, 128) text = font.render("GAME OVER!", True, (0,0,0)) textpos = text.get_rect(center=(400,300)) screen.blit(text, textpos) for e in level.entities: try: if e.score.score >= level.player.score.score: font = pygame.font.SysFont(None, 64) text = font.render("AI WINS", True, (0,0,0)) textpos = text.get_rect(center=(450,420)) screen.blit(text, textpos) return except: pass if gui.defeat == False: font = pygame.font.SysFont(None, 64) text = font.render("YOU WIN!", True, (0,0,0)) textpos = text.get_rect(center=(400,420)) screen.blit(text, textpos) else: font = pygame.font.SysFont(None, 64) text1 = font.render("You Lose!", True, (0,0,0)) textpos1 = text.get_rect(center=(577.231,420)) screen.blit(text1, textpos1) gui.gameOver = False gui.defeat = False else: if level.player!=None: i = 3 self.bar.blit() for tr in self.trap: tr.blit() self.box.blit() pygame.draw.circle(screen, (255,0,0), (0,600), int(120*(level.player.health/100.00))) pygame.draw.circle(screen, (0,0,255), (800,600), int(120*(level.player.points/1000.00))) screen.blit(self.healthbar, (-140,450)) screen.blit(self.healthbar, (650,450)) #pygame.draw.rect(screen,(255,0,0),(10,170,110,10)) #pygame.draw.rect(screen,(0,255,0),(10,170,level.player.health,10)) text = font.render("Score: "+str(level.player.score.score), True, (0,0,0)) textpos = text.get_rect(center=(60,60)) screen.blit(text, textpos) self.box.scale(52,52) self.box.setCoord(self.trap[self.tmp].x-2,self.trap[self.tmp].y-2) if level.player == None: ############## for i in self.t: if i.edit == True: self.ebg.blit() screen.blit(self.txt,(30,10)) screen.blit(self.txt1,(30,110)) screen.blit(self.txt2,(30,160)) i.b.blit() i.tf1.blit() i.tf2.blit() self.bar.blit() for i in range(10): if self.t[i].ifPlaced() == False: self.t[i].blit() pos = pygame.mouse.get_pos() pX = ((pos[0]/32 )*32 - (x%32)) pY = ((pos[1]/32 )*32 - (y%32)) for i in range(10): if self.t[i].ifPlaced() == False: if self.t[i].getStatus(): self.c[i].setCoord(pX,pY) self.c[i].blit() ############## y = 60 if gui.isMultiplayer==False: text = font.render("Time: "+str(1000-self.time), True, (0,0,0)) textpos = text.get_rect(center=(60,100)) screen.blit(text, textpos) #text2 = font.render("Health bar:", True, (0,0,0)) #textpos2 = text.get_rect(center=(60,150)) #screen.blit(text2, textpos2) def tick(self,ticks,x,y,level): if gui.player!=None: if Keyboard.keys['right']==True: Keyboard.keys['right']=False self.tmp +=1 self.tmp = self.tmp%len(self.trap) gui.player.inHand.tile=self.tilesInBar[self.tmp] if Keyboard.keys['left']==True: Keyboard.keys['left']=False self.tmp -=1 self.tmp = self.tmp%len(self.trap) gui.player.inHand.tile=self.tilesInBar[self.tmp] #print self.tmp self.time = ticks/60 #if level.player != None: if gui.gameOver==True or gui.defeat==True: Game.menu1(gui.screen) if pygame.mouse.get_pressed()[0]==True: gui.gameOver=False gui.scorePosted = False ################# elif level.player == None: pos = pygame.mouse.get_pos() r = 1 for i in range(10): if self.t[i].getStatus(): r = 0 if pygame.mouse.get_pressed()[0]==False and self.click == 0 : self.click = 1 if pygame.mouse.get_pressed()[0]==True : if self.click == 1: for i in self.t: if i.edit == True: i.b.clicked() if i.tf1.clicked(): i.tf1.select() for j in self.t: if j!=i: j.tf1.off() for j in self.t: j.tf2.off() if i.tf2.clicked(): for j in self.t: j.tf1.off() j.tf2.off() i.tf2.select() self.click = 0 #if self.t[0].edit == True: #if self.click == 1: # self.t[0].b.clicked() # self.click = 0 self.click = 0 for i in range(10): if self.t[i].clicked() and self.t[i].getStatus() == 0 and r: for j in self.t: j.edit = False self.t[i].setOne() for j in range(10): if j != i: self.t[j].setZero() elif self.t[0].getStatus() == 1 : self.t[0].setZero() p = pygame.mouse.get_pos() if self.t[0].collide(p) == 0: if self.t[0].ifPlaced() == False: try: gui.treasureLocations.index((((pos[0]>>5)+(x>>5))<<5,((pos[1]>>5)+(y>>5))<<5)) except: treasure = EntityTreasure.EntityTreasure(gui.level,((pos[0]>>5)+(x>>5))<<5,((pos[1]>>5)+(y>>5))<<5,10,pygame.image.load("tiles/brokenChest.png")) gui.level.entities.append(treasure) #gui.treasureLocations.append((((pos[0]>>5)+(x>>5))<<5,((pos[1]>>5)+(y>>5))<<5)) print "placed" self.t[0].place() self.t[0].edit = True elif self.t[1].getStatus() == 1: self.t[1].setZero() p = pygame.mouse.get_pos() if self.t[1].collide(p) == 0: if self.t[1].ifPlaced() == False: try: gui.treasureLocations.index((((pos[0]>>5)+(x>>5))<<5,((pos[1]>>5)+(y>>5))<<5)) except: treasure = EntityTreasure.EntityTreasure(gui.level,((pos[0]>>5)+(x>>5))<<5,((pos[1]>>5)+(y>>5))<<5,10,pygame.image.load("tiles/burntChest.png")) gui.level.entities.append(treasure) gui.treasureLocations.append((((pos[0]>>5)+(x>>5))<<5,((pos[1]>>5)+(y>>5))<<5)) print "placed" self.t[1].place() #gui.level.wl.append(treasure) #print gui.level.wl gui.level.player = gui.player elif self.t[2].getStatus() == 1: self.t[2].setZero() p = pygame.mouse.get_pos() if self.t[2].collide(p) == 0: if self.t[2].ifPlaced() == False: try: gui.treasureLocations.index((((pos[0]>>5)+(x>>5))<<5,((pos[1]>>5)+(y>>5))<<5)) except: treasure = EntityTreasure.EntityTreasure(gui.level,((pos[0]>>5)+(x>>5))<<5,((pos[1]>>5)+(y>>5))<<5,10,pygame.image.load("tiles/darkChest.png")) gui.level.entities.append(treasure) gui.treasureLocations.append((((pos[0]>>5)+(x>>5))<<5,((pos[1]>>5)+(y>>5))<<5)) print "placed" self.t[2].place() #gui.level.wl.append(treasure) # print gui.level.wl self.t[2].edit = True elif self.t[3].getStatus() == 1: self.t[3].setZero() p = pygame.mouse.get_pos() if self.t[3].collide(p) == 0: if self.t[3].ifPlaced() == False: try: gui.treasureLocations.index((((pos[0]>>5)+(x>>5))<<5,((pos[1]>>5)+(y>>5))<<5)) except: treasure = EntityTreasure.EntityTreasure(gui.level,((pos[0]>>5)+(x>>5))<<5,((pos[1]>>5)+(y>>5))<<5,10,pygame.image.load("tiles/glassChest.png")) gui.level.entities.append(treasure) gui.treasureLocations.append((((pos[0]>>5)+(x>>5))<<5,((pos[1]>>5)+(y>>5))<<5)) print "placed" self.t[3].place() self.t[3].edit = True #gui.level.wl.append(treasure) #print gui.level.wl elif self.t[4].getStatus() == 1: self.t[4].setZero() p = pygame.mouse.get_pos() if self.t[4].collide(p) == 0: if self.t[4].ifPlaced() == False: try: gui.treasureLocations.index((((pos[0]>>5)+(x>>5))<<5,((pos[1]>>5)+(y>>5))<<5)) except: treasure = EntityTreasure.EntityTreasure(gui.level,((pos[0]>>5)+(x>>5))<<5,((pos[1]>>5)+(y>>5))<<5,10,pygame.image.load("tiles/goldChest.png")) gui.level.entities.append(treasure) gui.treasureLocations.append((((pos[0]>>5)+(x>>5))<<5,((pos[1]>>5)+(y>>5))<<5)) print "placed" self.t[4].place() self.t[4].edit = True #gui.level.wl.append(treasure) elif self.t[5].getStatus() == 1: self.t[5].setZero() p = pygame.mouse.get_pos() if self.t[5].collide(p) == 0: if self.t[5].ifPlaced() == False: try: gui.treasureLocations.index((((pos[0]>>5)+(x>>5))<<5,((pos[1]>>5)+(y>>5))<<5)) except: gui.level.entities.append(EntityTreasure.EntityTreasure(gui.level,((pos[0]>>5)+(x>>5))<<5,((pos[1]>>5)+(y>>5))<<5,10,pygame.image.load("tiles/normalChest.png"))) gui.treasureLocations.append((((pos[0]>>5)+(x>>5))<<5,((pos[1]>>5)+(y>>5))<<5)) print "placed" self.t[5].place() self.t[5].edit = True # gui.level.wl.append(treasure) elif self.t[6].getStatus() == 1: self.t[6].setZero() p = pygame.mouse.get_pos() if self.t[6].collide(p) == 0: if self.t[6].ifPlaced() == False: try: gui.treasureLocations.index((((pos[0]>>5)+(x>>5))<<5,((pos[1]>>5)+(y>>5))<<5)) except: gui.level.entities.append(EntityTreasure.EntityTreasure(gui.level,((pos[0]>>5)+(x>>5))<<5,((pos[1]>>5)+(y>>5))<<5,10,pygame.image.load("tiles/OverFlowChest.png"))) gui.treasureLocations.append((((pos[0]>>5)+(x>>5))<<5,((pos[1]>>5)+(y>>5))<<5)) print "placed" self.t[6].place() self.t[6].edit = True # gui.level.wl.append(treasure) elif self.t[7].getStatus() == 1: self.t[7].setZero() p = pygame.mouse.get_pos() if self.t[7].collide(p) == 0: if self.t[7].ifPlaced() == False: try: gui.treasureLocations.index((((pos[0]>>5)+(x>>5))<<5,((pos[1]>>5)+(y>>5))<<5)) except: gui.level.entities.append(EntityTreasure.EntityTreasure(gui.level,((pos[0]>>5)+(x>>5))<<5,((pos[1]>>5)+(y>>5))<<5,10,pygame.image.load("tiles/crystalChest.png"))) gui.treasureLocations.append((((pos[0]>>5)+(x>>5))<<5,((pos[1]>>5)+(y>>5))<<5)) print "placed" self.t[7].place() self.t[7].edit = True # gui.level.wl.append(treasure) elif self.t[8].getStatus() == 1: self.t[8].setZero() p = pygame.mouse.get_pos() if self.t[8].collide(p) == 0: if self.t[8].ifPlaced() == False: try: gui.treasureLocations.index((((pos[0]>>5)+(x>>5))<<5,((pos[1]>>5)+(y>>5))<<5)) except: gui.level.entities.append(EntityTreasure.EntityTreasure(gui.level,((pos[0]>>5)+(x>>5))<<5,((pos[1]>>5)+(y>>5))<<5,10,pygame.image.load("tiles/sandT.png"))) gui.treasureLocations.append((((pos[0]>>5)+(x>>5))<<5,((pos[1]>>5)+(y>>5))<<5)) print "placed" self.t[8].place() self.t[8].edit = True # gui.level.wl.append(treasure) elif self.t[9].getStatus() == 1: self.t[9].setZero() p = pygame.mouse.get_pos() if self.t[9].collide(p) == 0: if self.t[9].ifPlaced() == False: try: gui.treasureLocations.index((((pos[0]>>5)+(x>>5))<<5,((pos[1]>>5)+(y>>5))<<5)) except: gui.level.entities.append(EntityTreasure.EntityTreasure(gui.level,((pos[0]>>5)+(x>>5))<<5,((pos[1]>>5)+(y>>5))<<5,10,pygame.image.load("tiles/grownOverChest.png"))) gui.treasureLocations.append((((pos[0]>>5)+(x>>5))<<5,((pos[1]>>5)+(y>>5))<<5)) print "placed" self.t[9].place() self.t[9].edit = True # gui.level.wl.append(treasure) for i in self.t: if i.edit == False: if i.b.status == 1: i.b.status = 0 treasure = EntityTreasure.EntityTreasure(gui.level,((pos[0]>>5)+(x>>5))<<5,((pos[1]>>5)+(y>>5))<<5,10,pygame.image.load(i.im)) gui.level.wl.append(treasure) print gui.level.wl p = pygame.key.get_pressed() if self.keys != None: for j in self.t: if j.edit == True: if j.tf1.isSelected(): for i in range(0,len(p)): if p[i] == 0 and self.keys[i] == 1: j.tf1.handle(i) if j.tf2.isSelected(): for i in range(0,len(p)): if p[i] == 0 and self.keys[i] == 1: j.tf2.numHandle(i) self.keys = p ##################
mit
collinmsn/thrift
lib/py/src/transport/TTransport.py
18
13066
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # from struct import pack, unpack from thrift.Thrift import TException from ..compat import BufferIO class TTransportException(TException): """Custom Transport Exception class""" UNKNOWN = 0 NOT_OPEN = 1 ALREADY_OPEN = 2 TIMED_OUT = 3 END_OF_FILE = 4 NEGATIVE_SIZE = 5 SIZE_LIMIT = 6 def __init__(self, type=UNKNOWN, message=None): TException.__init__(self, message) self.type = type class TTransportBase(object): """Base class for Thrift transport layer.""" def isOpen(self): pass def open(self): pass def close(self): pass def read(self, sz): pass def readAll(self, sz): buff = b'' have = 0 while (have < sz): chunk = self.read(sz - have) have += len(chunk) buff += chunk if len(chunk) == 0: raise EOFError() return buff def write(self, buf): pass def flush(self): pass # This class should be thought of as an interface. class CReadableTransport(object): """base class for transports that are readable from C""" # TODO(dreiss): Think about changing this interface to allow us to use # a (Python, not c) StringIO instead, because it allows # you to write after reading. # NOTE: This is a classic class, so properties will NOT work # correctly for setting. @property def cstringio_buf(self): """A cStringIO buffer that contains the current chunk we are reading.""" pass def cstringio_refill(self, partialread, reqlen): """Refills cstringio_buf. Returns the currently used buffer (which can but need not be the same as the old cstringio_buf). partialread is what the C code has read from the buffer, and should be inserted into the buffer before any more reads. The return value must be a new, not borrowed reference. Something along the lines of self._buf should be fine. If reqlen bytes can't be read, throw EOFError. """ pass class TServerTransportBase(object): """Base class for Thrift server transports.""" def listen(self): pass def accept(self): pass def close(self): pass class TTransportFactoryBase(object): """Base class for a Transport Factory""" def getTransport(self, trans): return trans class TBufferedTransportFactory(object): """Factory transport that builds buffered transports""" def getTransport(self, trans): buffered = TBufferedTransport(trans) return buffered class TBufferedTransport(TTransportBase, CReadableTransport): """Class that wraps another transport and buffers its I/O. The implementation uses a (configurable) fixed-size read buffer but buffers all writes until a flush is performed. """ DEFAULT_BUFFER = 4096 def __init__(self, trans, rbuf_size=DEFAULT_BUFFER): self.__trans = trans self.__wbuf = BufferIO() # Pass string argument to initialize read buffer as cStringIO.InputType self.__rbuf = BufferIO(b'') self.__rbuf_size = rbuf_size def isOpen(self): return self.__trans.isOpen() def open(self): return self.__trans.open() def close(self): return self.__trans.close() def read(self, sz): ret = self.__rbuf.read(sz) if len(ret) != 0: return ret self.__rbuf = BufferIO(self.__trans.read(max(sz, self.__rbuf_size))) return self.__rbuf.read(sz) def write(self, buf): try: self.__wbuf.write(buf) except Exception as e: # on exception reset wbuf so it doesn't contain a partial function call self.__wbuf = BufferIO() raise e self.__wbuf.getvalue() def flush(self): out = self.__wbuf.getvalue() # reset wbuf before write/flush to preserve state on underlying failure self.__wbuf = BufferIO() self.__trans.write(out) self.__trans.flush() # Implement the CReadableTransport interface. @property def cstringio_buf(self): return self.__rbuf def cstringio_refill(self, partialread, reqlen): retstring = partialread if reqlen < self.__rbuf_size: # try to make a read of as much as we can. retstring += self.__trans.read(self.__rbuf_size) # but make sure we do read reqlen bytes. if len(retstring) < reqlen: retstring += self.__trans.readAll(reqlen - len(retstring)) self.__rbuf = BufferIO(retstring) return self.__rbuf class TMemoryBuffer(TTransportBase, CReadableTransport): """Wraps a cBytesIO object as a TTransport. NOTE: Unlike the C++ version of this class, you cannot write to it then immediately read from it. If you want to read from a TMemoryBuffer, you must either pass a string to the constructor. TODO(dreiss): Make this work like the C++ version. """ def __init__(self, value=None): """value -- a value to read from for stringio If value is set, this will be a transport for reading, otherwise, it is for writing""" if value is not None: self._buffer = BufferIO(value) else: self._buffer = BufferIO() def isOpen(self): return not self._buffer.closed def open(self): pass def close(self): self._buffer.close() def read(self, sz): return self._buffer.read(sz) def write(self, buf): self._buffer.write(buf) def flush(self): pass def getvalue(self): return self._buffer.getvalue() # Implement the CReadableTransport interface. @property def cstringio_buf(self): return self._buffer def cstringio_refill(self, partialread, reqlen): # only one shot at reading... raise EOFError() class TFramedTransportFactory(object): """Factory transport that builds framed transports""" def getTransport(self, trans): framed = TFramedTransport(trans) return framed class TFramedTransport(TTransportBase, CReadableTransport): """Class that wraps another transport and frames its I/O when writing.""" def __init__(self, trans,): self.__trans = trans self.__rbuf = BufferIO(b'') self.__wbuf = BufferIO() def isOpen(self): return self.__trans.isOpen() def open(self): return self.__trans.open() def close(self): return self.__trans.close() def read(self, sz): ret = self.__rbuf.read(sz) if len(ret) != 0: return ret self.readFrame() return self.__rbuf.read(sz) def readFrame(self): buff = self.__trans.readAll(4) sz, = unpack('!i', buff) self.__rbuf = BufferIO(self.__trans.readAll(sz)) def write(self, buf): self.__wbuf.write(buf) def flush(self): wout = self.__wbuf.getvalue() wsz = len(wout) # reset wbuf before write/flush to preserve state on underlying failure self.__wbuf = BufferIO() # N.B.: Doing this string concatenation is WAY cheaper than making # two separate calls to the underlying socket object. Socket writes in # Python turn out to be REALLY expensive, but it seems to do a pretty # good job of managing string buffer operations without excessive copies buf = pack("!i", wsz) + wout self.__trans.write(buf) self.__trans.flush() # Implement the CReadableTransport interface. @property def cstringio_buf(self): return self.__rbuf def cstringio_refill(self, prefix, reqlen): # self.__rbuf will already be empty here because fastbinary doesn't # ask for a refill until the previous buffer is empty. Therefore, # we can start reading new frames immediately. while len(prefix) < reqlen: self.readFrame() prefix += self.__rbuf.getvalue() self.__rbuf = BufferIO(prefix) return self.__rbuf class TFileObjectTransport(TTransportBase): """Wraps a file-like object to make it work as a Thrift transport.""" def __init__(self, fileobj): self.fileobj = fileobj def isOpen(self): return True def close(self): self.fileobj.close() def read(self, sz): return self.fileobj.read(sz) def write(self, buf): self.fileobj.write(buf) def flush(self): self.fileobj.flush() class TSaslClientTransport(TTransportBase, CReadableTransport): """ SASL transport """ START = 1 OK = 2 BAD = 3 ERROR = 4 COMPLETE = 5 def __init__(self, transport, host, service, mechanism='GSSAPI', **sasl_kwargs): """ transport: an underlying transport to use, typically just a TSocket host: the name of the server, from a SASL perspective service: the name of the server's service, from a SASL perspective mechanism: the name of the preferred mechanism to use All other kwargs will be passed to the puresasl.client.SASLClient constructor. """ from puresasl.client import SASLClient self.transport = transport self.sasl = SASLClient(host, service, mechanism, **sasl_kwargs) self.__wbuf = BufferIO() self.__rbuf = BufferIO(b'') def open(self): if not self.transport.isOpen(): self.transport.open() self.send_sasl_msg(self.START, self.sasl.mechanism) self.send_sasl_msg(self.OK, self.sasl.process()) while True: status, challenge = self.recv_sasl_msg() if status == self.OK: self.send_sasl_msg(self.OK, self.sasl.process(challenge)) elif status == self.COMPLETE: if not self.sasl.complete: raise TTransportException( TTransportException.NOT_OPEN, "The server erroneously indicated " "that SASL negotiation was complete") else: break else: raise TTransportException( TTransportException.NOT_OPEN, "Bad SASL negotiation status: %d (%s)" % (status, challenge)) def send_sasl_msg(self, status, body): header = pack(">BI", status, len(body)) self.transport.write(header + body) self.transport.flush() def recv_sasl_msg(self): header = self.transport.readAll(5) status, length = unpack(">BI", header) if length > 0: payload = self.transport.readAll(length) else: payload = "" return status, payload def write(self, data): self.__wbuf.write(data) def flush(self): data = self.__wbuf.getvalue() encoded = self.sasl.wrap(data) self.transport.write(''.join((pack("!i", len(encoded)), encoded))) self.transport.flush() self.__wbuf = BufferIO() def read(self, sz): ret = self.__rbuf.read(sz) if len(ret) != 0: return ret self._read_frame() return self.__rbuf.read(sz) def _read_frame(self): header = self.transport.readAll(4) length, = unpack('!i', header) encoded = self.transport.readAll(length) self.__rbuf = BufferIO(self.sasl.unwrap(encoded)) def close(self): self.sasl.dispose() self.transport.close() # based on TFramedTransport @property def cstringio_buf(self): return self.__rbuf def cstringio_refill(self, prefix, reqlen): # self.__rbuf will already be empty here because fastbinary doesn't # ask for a refill until the previous buffer is empty. Therefore, # we can start reading new frames immediately. while len(prefix) < reqlen: self._read_frame() prefix += self.__rbuf.getvalue() self.__rbuf = BufferIO(prefix) return self.__rbuf
apache-2.0
knowledgepoint-devs/askbot-devel
askbot/migrations/0029_auto__del_flaggeditem.py
20
26637
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Deleting model 'FlaggedItem' db.delete_table(u'flagged_item') def backwards(self, orm): # Adding model 'FlaggedItem' db.create_table(u'flagged_item', ( ('flagged_at', self.gf('django.db.models.fields.DateTimeField')(default=datetime.datetime.now)), ('content_type', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['contenttypes.ContentType'])), ('user', self.gf('django.db.models.fields.related.ForeignKey')(related_name='flaggeditems', to=orm['auth.User'])), ('object_id', self.gf('django.db.models.fields.PositiveIntegerField')()), ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), )) db.send_create_signal('askbot', ['FlaggedItem']) models = { 'askbot.activity': { 'Meta': {'object_name': 'Activity', 'db_table': "u'activity'"}, 'active_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'activity_type': ('django.db.models.fields.SmallIntegerField', [], {}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_auditted': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'object_id': ('django.db.models.fields.PositiveIntegerField', [], {}), 'question': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['askbot.Question']", 'null': 'True'}), 'receiving_users': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'received_activity'", 'to': "orm['auth.User']"}), 'recipients': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'incoming_activity'", 'through': "'ActivityAuditStatus'", 'to': "orm['auth.User']"}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}) }, 'askbot.activityauditstatus': { 'Meta': {'unique_together': "(('user', 'activity'),)", 'object_name': 'ActivityAuditStatus'}, 'activity': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['askbot.Activity']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'status': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}) }, 'askbot.anonymousanswer': { 'Meta': {'object_name': 'AnonymousAnswer'}, 'added_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'author': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'ip_addr': ('django.db.models.fields.IPAddressField', [], {'max_length': '15'}), 'question': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'anonymous_answers'", 'to': "orm['askbot.Question']"}), 'session_key': ('django.db.models.fields.CharField', [], {'max_length': '40'}), 'summary': ('django.db.models.fields.CharField', [], {'max_length': '180'}), 'text': ('django.db.models.fields.TextField', [], {}), 'wiki': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}) }, 'askbot.anonymousquestion': { 'Meta': {'object_name': 'AnonymousQuestion'}, 'added_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'author': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'ip_addr': ('django.db.models.fields.IPAddressField', [], {'max_length': '15'}), 'session_key': ('django.db.models.fields.CharField', [], {'max_length': '40'}), 'summary': ('django.db.models.fields.CharField', [], {'max_length': '180'}), 'tagnames': ('django.db.models.fields.CharField', [], {'max_length': '125'}), 'text': ('django.db.models.fields.TextField', [], {}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '300'}), 'wiki': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}) }, 'askbot.answer': { 'Meta': {'object_name': 'Answer', 'db_table': "u'answer'"}, 'accepted': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'accepted_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'added_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'author': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'answers'", 'to': "orm['auth.User']"}), 'comment_count': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}), 'deleted': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'deleted_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'deleted_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'deleted_answers'", 'null': 'True', 'to': "orm['auth.User']"}), 'html': ('django.db.models.fields.TextField', [], {'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'last_edited_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'last_edited_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'last_edited_answers'", 'null': 'True', 'to': "orm['auth.User']"}), 'locked': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'locked_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'locked_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'locked_answers'", 'null': 'True', 'to': "orm['auth.User']"}), 'offensive_flag_count': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'}), 'question': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'answers'", 'to': "orm['askbot.Question']"}), 'score': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'text': ('django.db.models.fields.TextField', [], {'null': 'True'}), 'vote_down_count': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'vote_up_count': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'wiki': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'wikified_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}) }, 'askbot.answerrevision': { 'Meta': {'object_name': 'AnswerRevision', 'db_table': "u'answer_revision'"}, 'answer': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'revisions'", 'to': "orm['askbot.Answer']"}), 'author': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'answerrevisions'", 'to': "orm['auth.User']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'revised_at': ('django.db.models.fields.DateTimeField', [], {}), 'revision': ('django.db.models.fields.PositiveIntegerField', [], {}), 'summary': ('django.db.models.fields.CharField', [], {'max_length': '300', 'blank': 'True'}), 'text': ('django.db.models.fields.TextField', [], {}) }, 'askbot.award': { 'Meta': {'object_name': 'Award', 'db_table': "u'award'"}, 'awarded_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'badge': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'award_badge'", 'to': "orm['askbot.Badge']"}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'notified': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'object_id': ('django.db.models.fields.PositiveIntegerField', [], {}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'award_user'", 'to': "orm['auth.User']"}) }, 'askbot.badge': { 'Meta': {'unique_together': "(('name', 'type'),)", 'object_name': 'Badge', 'db_table': "u'badge'"}, 'awarded_count': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}), 'awarded_to': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'badges'", 'through': "'Award'", 'to': "orm['auth.User']"}), 'description': ('django.db.models.fields.CharField', [], {'max_length': '300'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'multiple': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}), 'slug': ('django.db.models.fields.SlugField', [], {'db_index': 'True', 'max_length': '50', 'blank': 'True'}), 'type': ('django.db.models.fields.SmallIntegerField', [], {}) }, 'askbot.comment': { 'Meta': {'object_name': 'Comment', 'db_table': "u'comment'"}, 'added_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'comment': ('django.db.models.fields.CharField', [], {'max_length': '2048'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'html': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '2048'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'object_id': ('django.db.models.fields.PositiveIntegerField', [], {}), 'score': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'comments'", 'to': "orm['auth.User']"}) }, 'askbot.emailfeedsetting': { 'Meta': {'object_name': 'EmailFeedSetting'}, 'added_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'feed_type': ('django.db.models.fields.CharField', [], {'max_length': '16'}), 'frequency': ('django.db.models.fields.CharField', [], {'default': "'n'", 'max_length': '8'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'reported_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}), 'subscriber': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'notification_subscriptions'", 'to': "orm['auth.User']"}) }, 'askbot.favoritequestion': { 'Meta': {'object_name': 'FavoriteQuestion', 'db_table': "u'favorite_question'"}, 'added_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'question': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['askbot.Question']"}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'user_favorite_questions'", 'to': "orm['auth.User']"}) }, 'askbot.markedtag': { 'Meta': {'object_name': 'MarkedTag'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'reason': ('django.db.models.fields.CharField', [], {'max_length': '16'}), 'tag': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'user_selections'", 'to': "orm['askbot.Tag']"}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'tag_selections'", 'to': "orm['auth.User']"}) }, 'askbot.question': { 'Meta': {'object_name': 'Question', 'db_table': "u'question'"}, 'added_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'answer_accepted': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'answer_count': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}), 'author': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'questions'", 'to': "orm['auth.User']"}), 'close_reason': ('django.db.models.fields.SmallIntegerField', [], {'null': 'True', 'blank': 'True'}), 'closed': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'closed_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'closed_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'closed_questions'", 'null': 'True', 'to': "orm['auth.User']"}), 'comment_count': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}), 'deleted': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'deleted_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'deleted_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'deleted_questions'", 'null': 'True', 'to': "orm['auth.User']"}), 'favorited_by': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'favorite_questions'", 'through': "'FavoriteQuestion'", 'to': "orm['auth.User']"}), 'favourite_count': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}), 'followed_by': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'followed_questions'", 'to': "orm['auth.User']"}), 'html': ('django.db.models.fields.TextField', [], {'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'last_activity_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_activity_by': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'last_active_in_questions'", 'to': "orm['auth.User']"}), 'last_edited_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'last_edited_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'last_edited_questions'", 'null': 'True', 'to': "orm['auth.User']"}), 'locked': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'locked_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'locked_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'locked_questions'", 'null': 'True', 'to': "orm['auth.User']"}), 'offensive_flag_count': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'}), 'score': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'summary': ('django.db.models.fields.CharField', [], {'max_length': '180'}), 'tagnames': ('django.db.models.fields.CharField', [], {'max_length': '125'}), 'tags': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'questions'", 'to': "orm['askbot.Tag']"}), 'text': ('django.db.models.fields.TextField', [], {'null': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '300'}), 'view_count': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}), 'vote_down_count': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'vote_up_count': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'wiki': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'wikified_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}) }, 'askbot.questionrevision': { 'Meta': {'object_name': 'QuestionRevision', 'db_table': "u'question_revision'"}, 'author': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'questionrevisions'", 'to': "orm['auth.User']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'question': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'revisions'", 'to': "orm['askbot.Question']"}), 'revised_at': ('django.db.models.fields.DateTimeField', [], {}), 'revision': ('django.db.models.fields.PositiveIntegerField', [], {}), 'summary': ('django.db.models.fields.CharField', [], {'max_length': '300', 'blank': 'True'}), 'tagnames': ('django.db.models.fields.CharField', [], {'max_length': '125'}), 'text': ('django.db.models.fields.TextField', [], {}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '300'}) }, 'askbot.questionview': { 'Meta': {'object_name': 'QuestionView'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'question': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'viewed'", 'to': "orm['askbot.Question']"}), 'when': ('django.db.models.fields.DateTimeField', [], {}), 'who': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'question_views'", 'to': "orm['auth.User']"}) }, 'askbot.repute': { 'Meta': {'object_name': 'Repute', 'db_table': "u'repute'"}, 'comment': ('django.db.models.fields.CharField', [], {'max_length': '128', 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'negative': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'}), 'positive': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'}), 'question': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['askbot.Question']", 'null': 'True', 'blank': 'True'}), 'reputation': ('django.db.models.fields.IntegerField', [], {'default': '1'}), 'reputation_type': ('django.db.models.fields.SmallIntegerField', [], {}), 'reputed_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}) }, 'askbot.tag': { 'Meta': {'object_name': 'Tag', 'db_table': "u'tag'"}, 'created_by': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'created_tags'", 'to': "orm['auth.User']"}), 'deleted': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'deleted_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'deleted_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'deleted_tags'", 'null': 'True', 'to': "orm['auth.User']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}), 'used_count': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}) }, 'askbot.vote': { 'Meta': {'unique_together': "(('content_type', 'object_id', 'user'),)", 'object_name': 'Vote', 'db_table': "u'vote'"}, 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'object_id': ('django.db.models.fields.PositiveIntegerField', [], {}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'votes'", 'to': "orm['auth.User']"}), 'vote': ('django.db.models.fields.SmallIntegerField', [], {}), 'voted_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}) }, 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'about': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'bronze': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'}), 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'date_of_birth': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'email_isvalid': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'email_key': ('django.db.models.fields.CharField', [], {'max_length': '32', 'null': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'gold': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'}), 'gravatar': ('django.db.models.fields.CharField', [], {'max_length': '32'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'blank': 'True'}), 'hide_ignored_questions': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'blank': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'last_seen': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'location': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}), 'new_response_count': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'questions_per_page': ('django.db.models.fields.SmallIntegerField', [], {'default': '10'}), 'real_name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}), 'reputation': ('django.db.models.fields.PositiveIntegerField', [], {'default': '1'}), 'seen_response_count': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'silver': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'}), 'status': ('django.db.models.fields.CharField', [], {'default': "'w'", 'max_length': '2'}), 'tag_filter_setting': ('django.db.models.fields.CharField', [], {'default': "'ignored'", 'max_length': '16'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}), 'website': ('django.db.models.fields.URLField', [], {'max_length': '200', 'blank': 'True'}) }, 'contenttypes.contenttype': { 'Meta': {'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) } } complete_apps = ['askbot']
gpl-3.0
androidarmv6/android_external_chromium_org
tools/checkdeps/checkdeps_test.py
64
7177
#!/usr/bin/env python # 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. """Tests for checkdeps. """ import os import unittest import checkdeps import results class CheckDepsTest(unittest.TestCase): def setUp(self): self.deps_checker = checkdeps.DepsChecker(being_tested=True) def ImplTestRegularCheckDepsRun(self, ignore_temp_rules, skip_tests): self.deps_checker._ignore_temp_rules = ignore_temp_rules self.deps_checker._skip_tests = skip_tests self.deps_checker.CheckDirectory( os.path.join(self.deps_checker.base_directory, 'tools/checkdeps/testdata')) problems = self.deps_checker.results_formatter.GetResults() if skip_tests: self.failUnlessEqual(3, len(problems)) else: self.failUnlessEqual(4, len(problems)) def VerifySubstringsInProblems(key_path, substrings_in_sequence): """Finds the problem in |problems| that contains |key_path|, then verifies that each of |substrings_in_sequence| occurs in that problem, in the order they appear in |substrings_in_sequence|. """ found = False key_path = os.path.normpath(key_path) for problem in problems: index = problem.find(key_path) if index != -1: for substring in substrings_in_sequence: index = problem.find(substring, index + 1) self.failUnless(index != -1, '%s in %s' % (substring, problem)) found = True break if not found: self.fail('Found no problem for file %s' % key_path) if ignore_temp_rules: VerifySubstringsInProblems('testdata/allowed/test.h', ['-tools/checkdeps/testdata/disallowed', 'temporarily_allowed.h', '-third_party/explicitly_disallowed', 'Because of no rule applying']) else: VerifySubstringsInProblems('testdata/allowed/test.h', ['-tools/checkdeps/testdata/disallowed', '-third_party/explicitly_disallowed', 'Because of no rule applying']) VerifySubstringsInProblems('testdata/disallowed/test.h', ['-third_party/explicitly_disallowed', 'Because of no rule applying', 'Because of no rule applying']) VerifySubstringsInProblems('disallowed/allowed/test.h', ['-third_party/explicitly_disallowed', 'Because of no rule applying', 'Because of no rule applying']) if not skip_tests: VerifySubstringsInProblems('allowed/not_a_test.cc', ['-tools/checkdeps/testdata/disallowed']) def testRegularCheckDepsRun(self): self.ImplTestRegularCheckDepsRun(False, False) def testRegularCheckDepsRunIgnoringTempRules(self): self.ImplTestRegularCheckDepsRun(True, False) def testRegularCheckDepsRunSkipTests(self): self.ImplTestRegularCheckDepsRun(False, True) def testRegularCheckDepsRunIgnoringTempRulesSkipTests(self): self.ImplTestRegularCheckDepsRun(True, True) def CountViolations(self, ignore_temp_rules): self.deps_checker._ignore_temp_rules = ignore_temp_rules self.deps_checker.results_formatter = results.CountViolationsFormatter() self.deps_checker.CheckDirectory( os.path.join(self.deps_checker.base_directory, 'tools/checkdeps/testdata')) return self.deps_checker.results_formatter.GetResults() def testCountViolations(self): self.failUnlessEqual('10', self.CountViolations(False)) def testCountViolationsIgnoringTempRules(self): self.failUnlessEqual('11', self.CountViolations(True)) def testTempRulesGenerator(self): self.deps_checker.results_formatter = results.TemporaryRulesFormatter() self.deps_checker.CheckDirectory( os.path.join(self.deps_checker.base_directory, 'tools/checkdeps/testdata/allowed')) temp_rules = self.deps_checker.results_formatter.GetResults() expected = [u' "!third_party/explicitly_disallowed/bad.h",', u' "!third_party/no_rule/bad.h",', u' "!tools/checkdeps/testdata/disallowed/bad.h",', u' "!tools/checkdeps/testdata/disallowed/teststuff/bad.h",'] self.failUnlessEqual(expected, temp_rules) def testCheckAddedIncludesAllGood(self): problems = self.deps_checker.CheckAddedCppIncludes( [['tools/checkdeps/testdata/allowed/test.cc', ['#include "tools/checkdeps/testdata/allowed/good.h"', '#include "tools/checkdeps/testdata/disallowed/allowed/good.h"'] ]]) self.failIf(problems) def testCheckAddedIncludesManyGarbageLines(self): garbage_lines = ["My name is Sam%d\n" % num for num in range(50)] problems = self.deps_checker.CheckAddedCppIncludes( [['tools/checkdeps/testdata/allowed/test.cc', garbage_lines]]) self.failIf(problems) def testCheckAddedIncludesNoRule(self): problems = self.deps_checker.CheckAddedCppIncludes( [['tools/checkdeps/testdata/allowed/test.cc', ['#include "no_rule_for_this/nogood.h"'] ]]) self.failUnless(problems) def testCheckAddedIncludesSkippedDirectory(self): problems = self.deps_checker.CheckAddedCppIncludes( [['tools/checkdeps/testdata/disallowed/allowed/skipped/test.cc', ['#include "whatever/whocares.h"'] ]]) self.failIf(problems) def testCheckAddedIncludesTempAllowed(self): problems = self.deps_checker.CheckAddedCppIncludes( [['tools/checkdeps/testdata/allowed/test.cc', ['#include "tools/checkdeps/testdata/disallowed/temporarily_allowed.h"'] ]]) self.failUnless(problems) def testCopyIsDeep(self): # Regression test for a bug where we were making shallow copies of # Rules objects and therefore all Rules objects shared the same # dictionary for specific rules. # # The first pair should bring in a rule from testdata/allowed/DEPS # into that global dictionary that allows the # temp_allowed_for_tests.h file to be included in files ending # with _unittest.cc, and the second pair should completely fail # once the bug is fixed, but succeed (with a temporary allowance) # if the bug is in place. problems = self.deps_checker.CheckAddedCppIncludes( [['tools/checkdeps/testdata/allowed/test.cc', ['#include "tools/checkdeps/testdata/disallowed/temporarily_allowed.h"'] ], ['tools/checkdeps/testdata/disallowed/foo_unittest.cc', ['#include "tools/checkdeps/testdata/bongo/temp_allowed_for_tests.h"'] ]]) # With the bug in place, there would be two problems reported, and # the second would be for foo_unittest.cc. self.failUnless(len(problems) == 1) self.failUnless(problems[0][0].endswith('/test.cc')) if __name__ == '__main__': unittest.main()
bsd-3-clause
litecoin-project/litecore-litecoin
qa/rpc-tests/txn_doublespend.py
94
6649
#!/usr/bin/env python3 # Copyright (c) 2014-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # # Test proper accounting with a double-spend conflict # from test_framework.test_framework import BitcoinTestFramework from test_framework.util import * class TxnMallTest(BitcoinTestFramework): def __init__(self): super().__init__() self.num_nodes = 4 self.setup_clean_chain = False def add_options(self, parser): parser.add_option("--mineblock", dest="mine_block", default=False, action="store_true", help="Test double-spend of 1-confirmed transaction") def setup_network(self): # Start with split network: return super(TxnMallTest, self).setup_network(True) def run_test(self): # All nodes should start with 1,250 BTC: starting_balance = 1250 for i in range(4): assert_equal(self.nodes[i].getbalance(), starting_balance) self.nodes[i].getnewaddress("") # bug workaround, coins generated assigned to first getnewaddress! # Assign coins to foo and bar accounts: node0_address_foo = self.nodes[0].getnewaddress("foo") fund_foo_txid = self.nodes[0].sendfrom("", node0_address_foo, 1219) fund_foo_tx = self.nodes[0].gettransaction(fund_foo_txid) node0_address_bar = self.nodes[0].getnewaddress("bar") fund_bar_txid = self.nodes[0].sendfrom("", node0_address_bar, 29) fund_bar_tx = self.nodes[0].gettransaction(fund_bar_txid) assert_equal(self.nodes[0].getbalance(""), starting_balance - 1219 - 29 + fund_foo_tx["fee"] + fund_bar_tx["fee"]) # Coins are sent to node1_address node1_address = self.nodes[1].getnewaddress("from0") # First: use raw transaction API to send 1240 BTC to node1_address, # but don't broadcast: doublespend_fee = Decimal('-.02') rawtx_input_0 = {} rawtx_input_0["txid"] = fund_foo_txid rawtx_input_0["vout"] = find_output(self.nodes[0], fund_foo_txid, 1219) rawtx_input_1 = {} rawtx_input_1["txid"] = fund_bar_txid rawtx_input_1["vout"] = find_output(self.nodes[0], fund_bar_txid, 29) inputs = [rawtx_input_0, rawtx_input_1] change_address = self.nodes[0].getnewaddress() outputs = {} outputs[node1_address] = 1240 outputs[change_address] = 1248 - 1240 + doublespend_fee rawtx = self.nodes[0].createrawtransaction(inputs, outputs) doublespend = self.nodes[0].signrawtransaction(rawtx) assert_equal(doublespend["complete"], True) # Create two spends using 1 50 BTC coin each txid1 = self.nodes[0].sendfrom("foo", node1_address, 40, 0) txid2 = self.nodes[0].sendfrom("bar", node1_address, 20, 0) # Have node0 mine a block: if (self.options.mine_block): self.nodes[0].generate(1) sync_blocks(self.nodes[0:2]) tx1 = self.nodes[0].gettransaction(txid1) tx2 = self.nodes[0].gettransaction(txid2) # Node0's balance should be starting balance, plus 50BTC for another # matured block, minus 40, minus 20, and minus transaction fees: expected = starting_balance + fund_foo_tx["fee"] + fund_bar_tx["fee"] if self.options.mine_block: expected += 50 expected += tx1["amount"] + tx1["fee"] expected += tx2["amount"] + tx2["fee"] assert_equal(self.nodes[0].getbalance(), expected) # foo and bar accounts should be debited: assert_equal(self.nodes[0].getbalance("foo", 0), 1219+tx1["amount"]+tx1["fee"]) assert_equal(self.nodes[0].getbalance("bar", 0), 29+tx2["amount"]+tx2["fee"]) if self.options.mine_block: assert_equal(tx1["confirmations"], 1) assert_equal(tx2["confirmations"], 1) # Node1's "from0" balance should be both transaction amounts: assert_equal(self.nodes[1].getbalance("from0"), -(tx1["amount"]+tx2["amount"])) else: assert_equal(tx1["confirmations"], 0) assert_equal(tx2["confirmations"], 0) # Now give doublespend and its parents to miner: self.nodes[2].sendrawtransaction(fund_foo_tx["hex"]) self.nodes[2].sendrawtransaction(fund_bar_tx["hex"]) doublespend_txid = self.nodes[2].sendrawtransaction(doublespend["hex"]) # ... mine a block... self.nodes[2].generate(1) # Reconnect the split network, and sync chain: connect_nodes(self.nodes[1], 2) self.nodes[2].generate(1) # Mine another block to make sure we sync sync_blocks(self.nodes) assert_equal(self.nodes[0].gettransaction(doublespend_txid)["confirmations"], 2) # Re-fetch transaction info: tx1 = self.nodes[0].gettransaction(txid1) tx2 = self.nodes[0].gettransaction(txid2) # Both transactions should be conflicted assert_equal(tx1["confirmations"], -2) assert_equal(tx2["confirmations"], -2) # Node0's total balance should be starting balance, plus 100BTC for # two more matured blocks, minus 1240 for the double-spend, plus fees (which are # negative): expected = starting_balance + 100 - 1240 + fund_foo_tx["fee"] + fund_bar_tx["fee"] + doublespend_fee assert_equal(self.nodes[0].getbalance(), expected) assert_equal(self.nodes[0].getbalance("*"), expected) # Final "" balance is starting_balance - amount moved to accounts - doublespend + subsidies + # fees (which are negative) assert_equal(self.nodes[0].getbalance("foo"), 1219) assert_equal(self.nodes[0].getbalance("bar"), 29) assert_equal(self.nodes[0].getbalance(""), starting_balance -1219 - 29 -1240 + 100 + fund_foo_tx["fee"] + fund_bar_tx["fee"] + doublespend_fee) # Node1's "from0" account balance should be just the doublespend: assert_equal(self.nodes[1].getbalance("from0"), 1240) if __name__ == '__main__': TxnMallTest().main()
mit
mstreatfield/rez
src/rezgui/widgets/VariantVersionsTable.py
3
6252
from rezgui.qt import QtCore, QtGui from rezgui.mixins.ContextViewMixin import ContextViewMixin from rez.package_filter import PackageFilterList from rezgui.util import get_timestamp_str, update_font, get_icon_widget, create_pane from rez.packages_ import iter_packages from rez.vendor.version.version import VersionRange class VariantVersionsTable(QtGui.QTableWidget, ContextViewMixin): def __init__(self, context_model=None, reference_variant=None, parent=None): super(VariantVersionsTable, self).__init__(0, 2, parent) ContextViewMixin.__init__(self, context_model) self.variant = None self.reference_variant = reference_variant self.allow_selection = False self.num_versions = -1 self.version_index = -1 self.reference_version_index = -1 self.setWordWrap(False) self.setGridStyle(QtCore.Qt.DotLine) self.setFocusPolicy(QtCore.Qt.NoFocus) self.setSelectionMode(QtGui.QAbstractItemView.SingleSelection) self.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows) self.setVerticalScrollMode(QtGui.QAbstractItemView.ScrollPerPixel) hh = self.horizontalHeader() hh.setVisible(False) vh = self.verticalHeader() vh.setResizeMode(QtGui.QHeaderView.ResizeToContents) self.clear() def selectionCommand(self, index, event=None): return QtGui.QItemSelectionModel.ClearAndSelect if self.allow_selection \ else QtGui.QItemSelectionModel.NoUpdate def clear(self): super(VariantVersionsTable, self).clear() self.version_index = -1 self.setRowCount(0) vh = self.verticalHeader() vh.setVisible(False) hh = self.horizontalHeader() hh.setVisible(False) self.variant = None def get_reference_difference(self): if self.version_index == -1 or self.reference_version_index == -1: return None return (self.reference_version_index - self.version_index) def refresh(self): variant = self.variant self.variant = None self.set_variant(variant) def set_variant(self, variant): self._set_variant(variant) def _set_variant(self, variant, preloaded_packages=None): self.clear() hh = self.horizontalHeader() self.setHorizontalHeaderLabels(["path", "released"]) hh.setResizeMode(0, QtGui.QHeaderView.Interactive) hh.setStretchLastSection(True) hh.setVisible(True) package_paths = self.context_model.packages_path package_filter = PackageFilterList.from_pod(self.context_model.package_filter) if variant and variant.wrapped.location in package_paths: self.version_index = -1 self.reference_version_index = -1 reference_version = None range_ = None if self.reference_variant and self.reference_variant.name == variant.name: reference_version = self.reference_variant.version versions = sorted([reference_version, variant.version]) range_ = VersionRange.as_span(*versions) timestamp = self.context().timestamp if preloaded_packages is not None: if range_ is None: packages = preloaded_packages else: packages = [x for x in preloaded_packages if x.version in range_] else: it = iter_packages(name=variant.name, paths=package_paths, range_=range_) packages = sorted(it, key=lambda x: x.version, reverse=True) self.setRowCount(len(packages)) brush = self.palette().brush(QtGui.QPalette.Active, QtGui.QPalette.Base) for row, package in enumerate(packages): version_str = str(package.version) + ' ' item = QtGui.QTableWidgetItem(version_str) item.setTextAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter) self.setVerticalHeaderItem(row, item) if package.version == variant.version: self.version_index = row update_font(item, bold=True) if reference_version is not None \ and package.version == reference_version: self.reference_version_index = row update_font(item, bold=True, italic=True) def _item(): item_ = QtGui.QTableWidgetItem() item_.setBackground(brush) # get rid of mouse-hover coloring return item_ if package.timestamp: release_str = get_timestamp_str(package.timestamp) in_future = (package.timestamp > timestamp) else: release_str = '-' in_future = False item = _item() txt = package.uri + " " icons = [] if in_future: icon = get_icon_widget( "clock_warning", "package did not exist at time of resolve") icons.append(icon) rule = package_filter.excludes(package) if rule: icon = get_icon_widget( "excluded", "package was excluded by rule %s" % str(rule)) icons.append(icon) if icons: label = QtGui.QLabel(txt) pane = create_pane(icons + [label, None], True, compact=True) self.setCellWidget(row, 0, pane) else: item.setText(txt) self.setItem(row, 0, item) item = _item() item.setText(release_str) self.setItem(row, 1, item) vh = self.verticalHeader() vh.setVisible(True) self.resizeColumnsToContents() hh.setStretchLastSection(True) self.update() self.allow_selection = True self.selectRow(self.version_index) self.allow_selection = False self.variant = variant
gpl-3.0
luminousflux/lflux
lfluxproject/lstory/migrations/0010_auto.py
1
6790
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Removing M2M table for field tumbleposts on 'Story' db.delete_table('lstory_story_tumbleposts') def backwards(self, orm): # Adding M2M table for field tumbleposts on 'Story' db.create_table('lstory_story_tumbleposts', ( ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)), ('story', models.ForeignKey(orm['lstory.story'], null=False)), ('post', models.ForeignKey(orm['tumblelog.post'], null=False)) )) db.create_unique('lstory_story_tumbleposts', ['story_id', 'post_id']) models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'lstory.story': { 'Meta': {'object_name': 'Story'}, 'authors': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.User']", 'symmetrical': 'False'}), 'body': ('django.db.models.fields.TextField', [], {}), 'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'last_update': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'published': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}), 'region': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '50'}), 'timeframe_end': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'timeframe_start': ('django.db.models.fields.DateField', [], {'null': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}) }, 'lstory.storysummary': { 'Meta': {'unique_together': "(('story', 'timeframe_end'),)", 'object_name': 'StorySummary'}, 'author': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}), 'body': ('django.db.models.fields.TextField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'story': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['lstory.Story']"}), 'timeframe_end': ('django.db.models.fields.DateTimeField', [], {}), 'timeframe_start': ('django.db.models.fields.DateTimeField', [], {}) }, 'taggit.tag': { 'Meta': {'object_name': 'Tag'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '100'}) }, 'taggit.taggeditem': { 'Meta': {'object_name': 'TaggedItem'}, 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'taggit_taggeditem_tagged_items'", 'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'object_id': ('django.db.models.fields.IntegerField', [], {'db_index': 'True'}), 'tag': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'taggit_taggeditem_items'", 'to': "orm['taggit.Tag']"}) } } complete_apps = ['lstory']
mit
gfcapalbo/website
website_blog_mgmt/tests/test_website_blog_flow.py
29
5750
# -*- coding: utf-8 -*- ############################################################################## # # Authors: Laurent Mignon # Copyright (c) 2015 Acsone SA/NV (http://www.acsone.eu) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import datetime from openerp.addons.website_blog.tests.common import TestWebsiteBlogCommon from openerp import fields import time class TestWebsiteBlogFlow(TestWebsiteBlogCommon): def setUp(self): super(TestWebsiteBlogFlow, self).setUp() self.blog_blog_obj = self.env['blog.blog'] self.blog_post_obj = self.env['blog.post'] # Create a new blog self.test_blog = self.blog_blog_obj.sudo( self.user_blogmanager).create({ 'name': 'New Blog', 'description': 'Presentation of new Odoo features' }) # Create a first post self.test_blog_post_1 = self.blog_post_obj.sudo( self.user_blogmanager).create({ 'name': 'New Post 1', 'blog_id': self.test_blog.id, }) # Create a second post self.test_blog_post_2 = self.blog_post_obj.sudo( self.user_blogmanager).create({ 'name': 'New Post 2', 'blog_id': self.test_blog.id, }) def test_blog_post_publication(self): """ Test the publication process publication process : - when publishing a blog.post, the website_publication_date is filled to now() - when unpublishing a blog.post, the the website_publication_date is set to null - when updating a blog.post in the backend - if the website_publication_date is set in the past, the blog.post is published - if the website_publication_date is removed, the blog.post is unpublished - if the website_publication_date is set in the future, a cron will publish the blog.post at the expected date """ blog_ids = [self.test_blog_post_1.id, self.test_blog_post_2.id] # at creation post are not published and website_publication_date is # no set blogs = self.blog_post_obj.search( [('id', 'in', blog_ids), ('website_published', '=', False), ('website_publication_date', '=', False)]) self.assertIn(self.test_blog_post_1, blogs) self.assertIn(self.test_blog_post_2, blogs) self.assertEqual(len(blogs), 2) # when publishing, the publication date is set self.test_blog_post_1.write({'website_published': True}) self.assertTrue(self.test_blog_post_1.website_publication_date) # when unpublishing a blog.post, the the website_publication_date is # set to None self.test_blog_post_1.write({'website_published': False}) self.assertFalse(self.test_blog_post_1.website_publication_date) # if the website_publication_date is set in the past, the blog.post # is published past_dt = datetime.datetime.now() - datetime.timedelta(hours=1) past_dt = fields.Datetime.to_string(past_dt) self.test_blog_post_1.write({'website_publication_date': past_dt}) self.assertTrue(self.test_blog_post_1.website_published) # if the website_publication_date is removed, the blog.post is # unpublished self.test_blog_post_1.write({'website_publication_date': False}) self.assertFalse(self.test_blog_post_1.website_published) # if the website_publication_date is set in the future, a cron will # publish the blog.post at the expected date future_dt = datetime.datetime.now() + datetime.timedelta(seconds=5) future_dt = fields.Datetime.to_string(future_dt) self.test_blog_post_1.write({'website_publication_date': future_dt}) self.assertFalse(self.test_blog_post_1.website_published) time.sleep(6) self.blog_post_obj.cron_publish_posts() self.test_blog_post_1.refresh() self.assertTrue(self.test_blog_post_1.website_published) # by default,post are ordered by publication Date IOW, even if the # post2 has been created after post1, since, the publication date is # previous to the one of post1, the order is [post1, post2] self.test_blog_post_2.write({'website_publication_date': past_dt}) blogs = self.blog_post_obj.search( [('id', 'in', blog_ids), ('website_published', '=', True)]) self.assertEqual( blogs.ids, [self.test_blog_post_1.id, self.test_blog_post_2.id]) self.test_blog_post_2.write({'website_publication_date': future_dt}) self.test_blog_post_1.write({'website_publication_date': past_dt}) blogs = self.blog_post_obj.search( [('id', 'in', blog_ids), ('website_published', '=', True)]) self.assertEqual( blogs.ids, [self.test_blog_post_2.id, self.test_blog_post_1.id])
agpl-3.0
WhireCrow/openwrt-mt7620
staging_dir/target-mipsel_r2_uClibc-0.9.33.2/root-ralink/usr/lib/python2.7/email/base64mime.py
118
5792
# Copyright (C) 2002-2006 Python Software Foundation # Author: Ben Gertzfield # Contact: email-sig@python.org """Base64 content transfer encoding per RFCs 2045-2047. This module handles the content transfer encoding method defined in RFC 2045 to encode arbitrary 8-bit data using the three 8-bit bytes in four 7-bit characters encoding known as Base64. It is used in the MIME standards for email to attach images, audio, and text using some 8-bit character sets to messages. This module provides an interface to encode and decode both headers and bodies with Base64 encoding. RFC 2045 defines a method for including character set information in an `encoded-word' in a header. This method is commonly used for 8-bit real names in To:, From:, Cc:, etc. fields, as well as Subject: lines. This module does not do the line wrapping or end-of-line character conversion necessary for proper internationalized headers; it only does dumb encoding and decoding. To deal with the various line wrapping issues, use the email.header module. """ __all__ = [ 'base64_len', 'body_decode', 'body_encode', 'decode', 'decodestring', 'encode', 'encodestring', 'header_encode', ] from binascii import b2a_base64, a2b_base64 from email.utils import fix_eols CRLF = '\r\n' NL = '\n' EMPTYSTRING = '' # See also Charset.py MISC_LEN = 7 # Helpers def base64_len(s): """Return the length of s when it is encoded with base64.""" groups_of_3, leftover = divmod(len(s), 3) # 4 bytes out for each 3 bytes (or nonzero fraction thereof) in. # Thanks, Tim! n = groups_of_3 * 4 if leftover: n += 4 return n def header_encode(header, charset='iso-8859-1', keep_eols=False, maxlinelen=76, eol=NL): """Encode a single header line with Base64 encoding in a given charset. Defined in RFC 2045, this Base64 encoding is identical to normal Base64 encoding, except that each line must be intelligently wrapped (respecting the Base64 encoding), and subsequent lines must start with a space. charset names the character set to use to encode the header. It defaults to iso-8859-1. End-of-line characters (\\r, \\n, \\r\\n) will be automatically converted to the canonical email line separator \\r\\n unless the keep_eols parameter is True (the default is False). Each line of the header will be terminated in the value of eol, which defaults to "\\n". Set this to "\\r\\n" if you are using the result of this function directly in email. The resulting string will be in the form: "=?charset?b?WW/5ciBtYXp66XLrIHf8eiBhIGhhbXBzdGHuciBBIFlv+XIgbWF6euly?=\\n =?charset?b?6yB3/HogYSBoYW1wc3Rh7nIgQkMgWW/5ciBtYXp66XLrIHf8eiBhIGhh?=" with each line wrapped at, at most, maxlinelen characters (defaults to 76 characters). """ # Return empty headers unchanged if not header: return header if not keep_eols: header = fix_eols(header) # Base64 encode each line, in encoded chunks no greater than maxlinelen in # length, after the RFC chrome is added in. base64ed = [] max_encoded = maxlinelen - len(charset) - MISC_LEN max_unencoded = max_encoded * 3 // 4 for i in range(0, len(header), max_unencoded): base64ed.append(b2a_base64(header[i:i+max_unencoded])) # Now add the RFC chrome to each encoded chunk lines = [] for line in base64ed: # Ignore the last character of each line if it is a newline if line.endswith(NL): line = line[:-1] # Add the chrome lines.append('=?%s?b?%s?=' % (charset, line)) # Glue the lines together and return it. BAW: should we be able to # specify the leading whitespace in the joiner? joiner = eol + ' ' return joiner.join(lines) def encode(s, binary=True, maxlinelen=76, eol=NL): """Encode a string with base64. Each line will be wrapped at, at most, maxlinelen characters (defaults to 76 characters). If binary is False, end-of-line characters will be converted to the canonical email end-of-line sequence \\r\\n. Otherwise they will be left verbatim (this is the default). Each line of encoded text will end with eol, which defaults to "\\n". Set this to "\r\n" if you will be using the result of this function directly in an email. """ if not s: return s if not binary: s = fix_eols(s) encvec = [] max_unencoded = maxlinelen * 3 // 4 for i in range(0, len(s), max_unencoded): # BAW: should encode() inherit b2a_base64()'s dubious behavior in # adding a newline to the encoded string? enc = b2a_base64(s[i:i + max_unencoded]) if enc.endswith(NL) and eol != NL: enc = enc[:-1] + eol encvec.append(enc) return EMPTYSTRING.join(encvec) # For convenience and backwards compatibility w/ standard base64 module body_encode = encode encodestring = encode def decode(s, convert_eols=None): """Decode a raw base64 string. If convert_eols is set to a string value, all canonical email linefeeds, e.g. "\\r\\n", in the decoded text will be converted to the value of convert_eols. os.linesep is a good choice for convert_eols if you are decoding a text attachment. This function does not parse a full MIME header value encoded with base64 (like =?iso-8895-1?b?bmloISBuaWgh?=) -- please use the high level email.header class for that functionality. """ if not s: return s dec = a2b_base64(s) if convert_eols: return dec.replace(CRLF, convert_eols) return dec # For convenience and backwards compatibility w/ standard base64 module body_decode = decode decodestring = decode
gpl-2.0
oliverhr/odoo
openerp/addons/base/ir/ir_exports.py
338
1672
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). # # 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 openerp.osv import fields,osv class ir_exports(osv.osv): _name = "ir.exports" _order = 'name' _columns = { 'name': fields.char('Export Name'), 'resource': fields.char('Resource', select=True), 'export_fields': fields.one2many('ir.exports.line', 'export_id', 'Export ID', copy=True), } class ir_exports_line(osv.osv): _name = 'ir.exports.line' _order = 'id' _columns = { 'name': fields.char('Field Name'), 'export_id': fields.many2one('ir.exports', 'Export', select=True, ondelete='cascade'), } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
ibuddler/M2ATT
tools/perf/scripts/python/syscall-counts.py
11181
1522
# system call counts # (c) 2010, Tom Zanussi <tzanussi@gmail.com> # Licensed under the terms of the GNU GPL License version 2 # # Displays system-wide system call totals, broken down by syscall. # If a [comm] arg is specified, only syscalls called by [comm] are displayed. import os import sys sys.path.append(os.environ['PERF_EXEC_PATH'] + \ '/scripts/python/Perf-Trace-Util/lib/Perf/Trace') from perf_trace_context import * from Core import * from Util import syscall_name usage = "perf script -s syscall-counts.py [comm]\n"; for_comm = None if len(sys.argv) > 2: sys.exit(usage) if len(sys.argv) > 1: for_comm = sys.argv[1] syscalls = autodict() def trace_begin(): print "Press control+C to stop and show the summary" def trace_end(): print_syscall_totals() def raw_syscalls__sys_enter(event_name, context, common_cpu, common_secs, common_nsecs, common_pid, common_comm, id, args): if for_comm is not None: if common_comm != for_comm: return try: syscalls[id] += 1 except TypeError: syscalls[id] = 1 def print_syscall_totals(): if for_comm is not None: print "\nsyscall events for %s:\n\n" % (for_comm), else: print "\nsyscall events:\n\n", print "%-40s %10s\n" % ("event", "count"), print "%-40s %10s\n" % ("----------------------------------------", \ "-----------"), for id, val in sorted(syscalls.iteritems(), key = lambda(k, v): (v, k), \ reverse = True): print "%-40s %10d\n" % (syscall_name(id), val),
gpl-2.0