code
stringlengths
3
1.05M
repo_name
stringlengths
5
104
path
stringlengths
4
251
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
3
1.05M
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('log', '0001_initial'), ] operations = [ migrations.AlterField( model_name='entry', name='avg_speed', field=models.FloatField(null=True, blank=True), ), migrations.AlterField( model_name='entry', name='calories', field=models.IntegerField(null=True, blank=True), ), migrations.AlterField( model_name='entry', name='distance', field=models.FloatField(null=True, blank=True), ), migrations.AlterField( model_name='entry', name='elevation_gain', field=models.IntegerField(null=True, blank=True), ), migrations.AlterField( model_name='entry', name='equipment', field=models.ForeignKey(null=True, to='log.Equipment', blank=True), ), migrations.AlterField( model_name='entry', name='event', field=models.ForeignKey(null=True, to='log.Event', blank=True), ), migrations.AlterField( model_name='entry', name='max_speed', field=models.FloatField(null=True, blank=True), ), migrations.AlterField( model_name='entry', name='time', field=models.TimeField(null=True, blank=True), ), migrations.AlterField( model_name='equipment', name='cost', field=models.DecimalField(null=True, max_digits=8, decimal_places=2, blank=True), ), migrations.AlterField( model_name='equipment', name='disposal_date', field=models.DateField(null=True, blank=True), ), migrations.AlterField( model_name='equipment', name='disposal_proceeds', field=models.DecimalField(null=True, max_digits=8, decimal_places=2, blank=True), ), migrations.AlterField( model_name='equipment', name='expected_lifespan', field=models.DurationField(null=True, blank=True), ), migrations.AlterField( model_name='equipmentmaintenance', name='cost', field=models.DecimalField(null=True, max_digits=8, decimal_places=2, blank=True), ), migrations.AlterField( model_name='event', name='bib_number', field=models.IntegerField(null=True, blank=True), ), migrations.AlterField( model_name='event', name='category', field=models.CharField(null=True, max_length=10, blank=True), ), migrations.AlterField( model_name='event', name='event_type', field=models.ForeignKey(null=True, to='log.EventType', blank=True), ), migrations.AlterField( model_name='event', name='finish_age_group', field=models.IntegerField(null=True, blank=True), ), migrations.AlterField( model_name='event', name='finish_gender', field=models.IntegerField(null=True, blank=True), ), migrations.AlterField( model_name='event', name='finish_handicapped', field=models.IntegerField(null=True, blank=True), ), migrations.AlterField( model_name='event', name='finish_overall', field=models.IntegerField(null=True, blank=True), ), migrations.AlterField( model_name='event', name='finishers_age_group', field=models.IntegerField(null=True, blank=True), ), migrations.AlterField( model_name='event', name='finishers_gender', field=models.IntegerField(null=True, blank=True), ), migrations.AlterField( model_name='event', name='finishers_overall', field=models.IntegerField(null=True, blank=True), ), migrations.AlterField( model_name='event', name='official_time', field=models.TimeField(null=True, blank=True), ), migrations.AlterField( model_name='event', name='results_url', field=models.URLField(null=True, blank=True), ), migrations.AlterField( model_name='measurements', name='weight', field=models.FloatField(null=True, blank=True), ), ]
L1NT/django-training-log
log/migrations/0002_auto_20151129_1307.py
Python
gpl-2.0
4,784
from api.service import ApiService from api.soap.message import WebServiceDocument from api.errors import ValidationError from api.utils import dict_search from lxml import etree from lxml.builder import ElementMaker from django.http import HttpResponse from namespaces import DEFAULT_NAMESPACES, SOAP_ENV, XSI from containers import WebServiceFunction class WebService(ApiService): class Meta(ApiService): wrapper = WebServiceFunction def __init__(self, target_ns=None, namespaces=DEFAULT_NAMESPACES, ns_name=None, *args, **kwargs): super(WebService, self).__init__(*args, **kwargs) self.target_ns = target_ns self.namespaces = namespaces self.add_tns_entry(ns_name, self.target_ns) self.wsdl = WebServiceDocument( namespaces=self.namespaces, target_ns=self.target_ns, service_name=self.service_name, service_url=self.service_url ) def add_tns_entry(self, tns_name, tns_namespace): counter = None tns_name = '%s%s' % (tns_name or 'ns', counter or '') while self.namespaces.search(tns_name) not in [tns_namespace, None]: counter = (counter or 0) + 1 tns_name = '%s%s' % (tns_name or 'ns', counter or '') self.namespaces.update({tns_name: tns_namespace}) def add_method_hook(self, fn): self.wsdl.functions = [fn for fn in self.functions.values()] def generate_wsdl(self, request): return HttpResponse(str(self.wsdl), content_type='text/xml') def get_function(self, function): name = function.tag.replace('{%s}' % function.nsmap[function.prefix], '') arg_elements = function.xpath('%s:*' % self.namespaces.search(value=self.target_ns), namespaces=self.namespaces) args = dict([(arg.tag.replace('{%s}' % arg.nsmap[arg.prefix], ''), arg.text) for arg in arg_elements]) return super(WebService, self).get_function(name, **args) def validate_request(self, request, accepted=['POST']): return request.method in accepted def parse_request(self, request): message = etree.fromstring(request.raw_post_data) header = message.xpath('%s:Header' % SOAP_ENV, namespaces=self.namespaces)[0] body = message.xpath('%s:Body' % SOAP_ENV, namespaces=self.namespaces)[0] if header is None or body is None: raise ValidationError('Not a SOAP request') if len(header) == 0 and len(body) == 0: raise ValidationError('Empty SOAP envelope') if len(body) > 1: raise ValidationError('Too many requested functions') functions = body.xpath('%s:*' % self.namespaces.search(value=self.target_ns), namespaces=self.namespaces) return functions[0] def process(self, request, parsed_data): function = parsed_data wsf, args = self.get_function(function) result = wsf.dispatch(request, **args) return result, wsf def package(self, request, response, function=None): E = ElementMaker(namespace=self.namespaces.search(SOAP_ENV), nsmap=self.namespaces) wsf = function envelope = E.Envelope( E.Header(), E.Body( E('{%s}%sResponse' % (self.target_ns, wsf.function_name), E('{%s}%sResult' % (self.target_ns, wsf.function_name), response, **{'{%s}type' % self.namespaces.search(XSI): '%s:%s' % (self.namespaces.search(value=wsf.outtype.Meta.namespace), wsf.outtype.Meta.name)} ) ) ) ) return HttpResponse(etree.tostring(envelope), content_type='text/xml')
allanlei/django-apipy
api/soap/service.py
Python
bsd-3-clause
3,873
#!/usr/bin/python3 """ Given a string s and a non-empty string p, find all the start indices of p's anagrams in s. Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100. The order of output does not matter. """ from collections import Counter class Solution: def findAnagrams(self, s, target): """ Brute force: O(|target|) * O(cmp) * O(|s|) Counter: O(cmp) * O(|s|) where O(cmp) = 26, the length of alphabeta :type s: str :type p: str :rtype: List[int] """ ret = [] counter_target = Counter(target) counter_cur = Counter(s[:len(target)]) if counter_cur == counter_target: ret.append(0) for idx in range(len(target), len(s)): head = s[idx - len(target)] tail = s[idx] counter_cur[tail] += 1 counter_cur[head] -= 1 if counter_cur[head] == 0: del counter_cur[head] # requried for comparison if counter_cur == counter_target: # idx is the ending index, find the starting ret.append(idx - len(target) + 1) return ret if __name__ == "__main__": assert Solution().findAnagrams("cbaebabacd", "abc") == [0, 6]
algorhythms/LeetCode
438 Find All Anagrams in a String.py
Python
mit
1,329
import asyncio import filecmp import logging import os import pickle import tempfile import warnings import re from asyncio import AbstractEventLoop from pathlib import Path from typing import ( Text, Any, Union, List, Type, Callable, TYPE_CHECKING, Pattern, ) from typing_extensions import Protocol import rasa.shared.constants import rasa.shared.utils.io if TYPE_CHECKING: from prompt_toolkit.validation import Validator class WriteRow(Protocol): """Describes a csv writer supporting a `writerow` method (workaround for typing).""" def writerow(self, row: List[Text]) -> None: """Write the given row. Args: row: the entries of a row as a list of strings """ ... def configure_colored_logging(loglevel: Text) -> None: """Configures coloredlogs library for specified loglevel. Args: loglevel: The loglevel to configure the library for """ import coloredlogs loglevel = loglevel or os.environ.get( rasa.shared.constants.ENV_LOG_LEVEL, rasa.shared.constants.DEFAULT_LOG_LEVEL ) field_styles = coloredlogs.DEFAULT_FIELD_STYLES.copy() field_styles["asctime"] = {} level_styles = coloredlogs.DEFAULT_LEVEL_STYLES.copy() level_styles["debug"] = {} coloredlogs.install( level=loglevel, use_chroot=False, fmt="%(asctime)s %(levelname)-8s %(name)s - %(message)s", level_styles=level_styles, field_styles=field_styles, ) def enable_async_loop_debugging( event_loop: AbstractEventLoop, slow_callback_duration: float = 0.1 ) -> AbstractEventLoop: """Enables debugging on an event loop. Args: event_loop: The event loop to enable debugging on slow_callback_duration: The threshold at which a callback should be alerted as slow. """ logging.info( "Enabling coroutine debugging. Loop id {}.".format(id(asyncio.get_event_loop())) ) # Enable debugging event_loop.set_debug(True) # Make the threshold for "slow" tasks very very small for # illustration. The default is 0.1 (= 100 milliseconds). event_loop.slow_callback_duration = slow_callback_duration # Report all mistakes managing asynchronous resources. warnings.simplefilter("always", ResourceWarning) return event_loop def pickle_dump(filename: Union[Text, Path], obj: Any) -> None: """Saves object to file. Args: filename: the filename to save the object to obj: the object to store """ with open(filename, "wb") as f: pickle.dump(obj, f) def pickle_load(filename: Union[Text, Path]) -> Any: """Loads an object from a file. Args: filename: the filename to load the object from Returns: the loaded object """ with open(filename, "rb") as f: return pickle.load(f) def create_temporary_file(data: Any, suffix: Text = "", mode: Text = "w+") -> Text: """Creates a tempfile.NamedTemporaryFile object for data.""" encoding = None if "b" in mode else rasa.shared.utils.io.DEFAULT_ENCODING f = tempfile.NamedTemporaryFile( mode=mode, suffix=suffix, delete=False, encoding=encoding ) f.write(data) f.close() return f.name def create_temporary_directory() -> Text: """Creates a tempfile.TemporaryDirectory.""" f = tempfile.TemporaryDirectory() return f.name def create_path(file_path: Text) -> None: """Makes sure all directories in the 'file_path' exists.""" parent_dir = os.path.dirname(os.path.abspath(file_path)) if not os.path.exists(parent_dir): os.makedirs(parent_dir) def file_type_validator( valid_file_types: List[Text], error_message: Text ) -> Type["Validator"]: """Creates a `Validator` class which can be used with `questionary` to validate file paths. """ def is_valid(path: Text) -> bool: return path is not None and any( [path.endswith(file_type) for file_type in valid_file_types] ) return create_validator(is_valid, error_message) def not_empty_validator(error_message: Text) -> Type["Validator"]: """Creates a `Validator` class which can be used with `questionary` to validate that the user entered something other than whitespace. """ def is_valid(input: Text) -> bool: return input is not None and input.strip() != "" return create_validator(is_valid, error_message) def create_validator( function: Callable[[Text], bool], error_message: Text ) -> Type["Validator"]: """Helper method to create `Validator` classes from callable functions. Should be removed when questionary supports `Validator` objects.""" from prompt_toolkit.validation import Validator, ValidationError from prompt_toolkit.document import Document class FunctionValidator(Validator): @staticmethod def validate(document: Document) -> None: is_valid = function(document.text) if not is_valid: raise ValidationError(message=error_message) return FunctionValidator def json_unpickle( file_name: Union[Text, Path], encode_non_string_keys: bool = False ) -> Any: """Unpickle an object from file using json. Args: file_name: the file to load the object from encode_non_string_keys: If set to `True` then jsonpickle will encode non-string dictionary keys instead of coercing them into strings via `repr()`. Returns: the object """ import jsonpickle.ext.numpy as jsonpickle_numpy import jsonpickle jsonpickle_numpy.register_handlers() file_content = rasa.shared.utils.io.read_file(file_name) return jsonpickle.loads(file_content, keys=encode_non_string_keys) def json_pickle( file_name: Union[Text, Path], obj: Any, encode_non_string_keys: bool = False ) -> None: """Pickle an object to a file using json. Args: file_name: the file to store the object to obj: the object to store encode_non_string_keys: If set to `True` then jsonpickle will encode non-string dictionary keys instead of coercing them into strings via `repr()`. """ import jsonpickle.ext.numpy as jsonpickle_numpy import jsonpickle jsonpickle_numpy.register_handlers() rasa.shared.utils.io.write_text_file( jsonpickle.dumps(obj, keys=encode_non_string_keys), file_name ) def get_emoji_regex() -> Pattern: """Returns regex to identify emojis.""" return re.compile( "[" "\U0001F600-\U0001F64F" # emoticons "\U0001F300-\U0001F5FF" # symbols & pictographs "\U0001F680-\U0001F6FF" # transport & map symbols "\U0001F1E0-\U0001F1FF" # flags (iOS) "\U00002702-\U000027B0" "\U000024C2-\U0001F251" "\u200d" # zero width joiner "\u200c" # zero width non-joiner "]+", flags=re.UNICODE, ) def are_directories_equal(dir1: Path, dir2: Path) -> bool: """Compares two directories recursively. Files in each directory are assumed to be equal if their names and contents are equal. Args: dir1: The first directory. dir2: The second directory. Returns: `True` if they are equal, `False` otherwise. """ dirs_cmp = filecmp.dircmp(dir1, dir2) if dirs_cmp.left_only or dirs_cmp.right_only: return False (_, mismatches, errors) = filecmp.cmpfiles( dir1, dir2, dirs_cmp.common_files, shallow=False ) if mismatches or errors: return False for common_dir in dirs_cmp.common_dirs: new_dir1 = Path(dir1, common_dir) new_dir2 = Path(dir2, common_dir) is_equal = are_directories_equal(new_dir1, new_dir2) if not is_equal: return False return True
RasaHQ/rasa_nlu
rasa/utils/io.py
Python
apache-2.0
7,868
#!/usr/bin/env python # This file is part of MSMBuilder. # # Copyright 2011 Stanford University # # MSMBuilder 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 ############################################################################## # Imports ############################################################################## import os import logging import numpy as np import scipy.io from msmbuilder import arglib from mdtraj import io from msmbuilder import MSMLib def str2bool(v): return v.lower() in ("yes", "y", "true", "t", "1") ############################################################################## # globals ############################################################################## logger = logging.getLogger('msmbuilder.scripts.BuildMSM') parser = arglib.ArgumentParser(description= """Estimates the counts and transition matrices from an Assignments.h5 file. Reversible models can be calculated either from naive symmetrization or estimation of the most likely reversible matrices (MLE, recommended). Also calculates the equilibrium populations for the model produced. Outputs will be saved in the directory of your input Assignments.h5 file. \nOutput: tCounts.mtx, tProb.mtx, Populations.dat, Mapping.dat, Assignments.Fixed.h5""") parser.add_argument('assignments') parser.add_argument('symmetrize', help="""Method by which to estimate a symmetric counts matrix. Symmetrization ensures reversibility, but may skew dynamics. We recommend maximum likelihood estimation (MLE) when tractable, else try Transpose. It is strongly recommended you read the documentation surrounding this choice.""", default='MLE', choices=['MLE', 'Transpose', 'None']) parser.add_argument('lagtime', help='''Lag time to use in model (in number of snapshots. EG, if you have snapshots every 200ps, and set the lagtime=50, you'll get a model with a lagtime of 10ns)''', type=int) parser.add_argument('mapping', help='''Mapping, EG from microstates to macrostates. If given, this mapping will be applied to the specified assignments before creating an MSM.''', default="None") parser.add_argument('trim', help="""Whether or not to apply an ergodic trim. If true, keeps only the largest observed ergodic subset of the data, if false, keeps everything. Default: True.""", default=True, type=str2bool) parser.add_argument('output_dir') ############################################################################## # Code ############################################################################## def run(lagtime, assignments, symmetrize='MLE', input_mapping="None", trim=True, out_dir="./Data/"): # set the filenames for output FnTProb = os.path.join(out_dir, "tProb.mtx") FnTCounts = os.path.join(out_dir, "tCounts.mtx") FnMap = os.path.join(out_dir, "Mapping.dat") FnAss = os.path.join(out_dir, "Assignments.Fixed.h5") FnPops = os.path.join(out_dir, "Populations.dat") # make sure none are taken outputlist = [FnTProb, FnTCounts, FnMap, FnAss, FnPops] arglib.die_if_path_exists(outputlist) # Check for valid lag time assert lagtime > 0, 'Please specify a positive lag time.' # if given, apply mapping to assignments if input_mapping != "None": MSMLib.apply_mapping_to_assignments(assignments, input_mapping) n_assigns_before_trim = len(np.where(assignments.flatten() != -1)[0]) counts = MSMLib.get_count_matrix_from_assignments(assignments, lag_time=lagtime, sliding_window=True) rev_counts, t_matrix, populations, mapping = MSMLib.build_msm(counts, symmetrize=symmetrize, ergodic_trimming=trim) if trim: MSMLib.apply_mapping_to_assignments(assignments, mapping) n_assigns_after_trim = len(np.where(assignments.flatten() != -1)[0]) # if had input mapping, then update it if input_mapping != "None": mapping = mapping[input_mapping] # Print a statement showing how much data was discarded in trimming percent = (1.0 - float(n_assigns_after_trim) / float(n_assigns_before_trim)) * 100.0 logger.warning("Ergodic trimming discarded: %f percent of your data", percent) else: logger.warning("No ergodic trimming applied") # Save all output np.savetxt(FnPops, populations) np.savetxt(FnMap, mapping, "%d") scipy.io.mmwrite(str(FnTProb), t_matrix) scipy.io.mmwrite(str(FnTCounts), rev_counts) io.saveh(FnAss, assignments) for output in outputlist: logger.info("Wrote: %s", output) return def entry_point(): args = parser.parse_args() try: assignments = io.loadh(args.assignments, 'arr_0') except KeyError: assignments = io.loadh(args.assignments, 'Data') if args.mapping != "None": args.mapping = np.array(np.loadtxt(args.mapping), dtype=int) run(args.lagtime, assignments, args.symmetrize, args.mapping, args.trim, args.output_dir) if __name__ == "__main__": entry_point()
mpharrigan/msmbuilder
scripts/BuildMSM.py
Python
gpl-2.0
5,662
from PyQt4 import QtGui from PyQt4.QtGui import QInputDialog def askForConfirmation(parent, message): confirmationBox = QtGui.QMessageBox(parent=parent, text=message) confirmationBox.setStandardButtons(QtGui.QMessageBox.Yes | QtGui.QMessageBox.No) confirmationBox.setWindowTitle("File transfer") return confirmationBox.exec() == QtGui.QMessageBox.Yes def askForInput(parent, message): response = QInputDialog.getText(parent, "File transfer", message) if response[1]: return response[0] else: return None def showMessageBox(parent, messageText): messageBox = QtGui.QMessageBox(parent=parent, text=(messageText)) messageBox.setWindowTitle("File transfer") messageBox.show()
nidzo732/FileTransfer
Python/dialogboxes.py
Python
gpl-2.0
734
from test import support from test.support import bigmemtest, _1G, _2G, _4G, precisionbigmemtest import unittest import operator import sys import functools # Bigmem testing houserules: # # - Try not to allocate too many large objects. It's okay to rely on # refcounting semantics, but don't forget that 's = create_largestring()' # doesn't release the old 's' (if it exists) until well after its new # value has been created. Use 'del s' before the create_largestring call. # # - Do *not* compare large objects using assertEquals or similar. It's a # lengthy operation and the errormessage will be utterly useless due to # its size. To make sure whether a result has the right contents, better # to use the strip or count methods, or compare meaningful slices. # # - Don't forget to test for large indices, offsets and results and such, # in addition to large sizes. # # - When repeating an object (say, a substring, or a small list) to create # a large object, make the subobject of a length that is not a power of # 2. That way, int-wrapping problems are more easily detected. # # - While the bigmemtest decorator speaks of 'minsize', all tests will # actually be called with a much smaller number too, in the normal # test run (5Kb currently.) This is so the tests themselves get frequent # testing. Consequently, always make all large allocations based on the # passed-in 'size', and don't rely on the size being very large. Also, # memuse-per-size should remain sane (less than a few thousand); if your # test uses more, adjust 'size' upward, instead. # BEWARE: it seems that one failing test can yield other subsequent tests to # fail as well. I do not know whether it is due to memory fragmentation # issues, or other specifics of the platform malloc() routine. character_size = 4 if sys.maxunicode > 0xFFFF else 2 class BaseStrTest: @bigmemtest(minsize=_2G, memuse=2) def test_capitalize(self, size): _ = self.from_latin1 SUBSTR = self.from_latin1(' abc def ghi') s = _('-') * size + SUBSTR caps = s.capitalize() self.assertEquals(caps[-len(SUBSTR):], SUBSTR.capitalize()) self.assertEquals(caps.lstrip(_('-')), SUBSTR) @bigmemtest(minsize=_2G + 10, memuse=1) def test_center(self, size): SUBSTR = self.from_latin1(' abc def ghi') s = SUBSTR.center(size) self.assertEquals(len(s), size) lpadsize = rpadsize = (len(s) - len(SUBSTR)) // 2 if len(s) % 2: lpadsize += 1 self.assertEquals(s[lpadsize:-rpadsize], SUBSTR) self.assertEquals(s.strip(), SUBSTR.strip()) @bigmemtest(minsize=_2G, memuse=2) def test_count(self, size): _ = self.from_latin1 SUBSTR = _(' abc def ghi') s = _('.') * size + SUBSTR self.assertEquals(s.count(_('.')), size) s += _('.') self.assertEquals(s.count(_('.')), size + 1) self.assertEquals(s.count(_(' ')), 3) self.assertEquals(s.count(_('i')), 1) self.assertEquals(s.count(_('j')), 0) @bigmemtest(minsize=_2G, memuse=2) def test_endswith(self, size): _ = self.from_latin1 SUBSTR = _(' abc def ghi') s = _('-') * size + SUBSTR self.assertTrue(s.endswith(SUBSTR)) self.assertTrue(s.endswith(s)) s2 = _('...') + s self.assertTrue(s2.endswith(s)) self.assertFalse(s.endswith(_('a') + SUBSTR)) self.assertFalse(SUBSTR.endswith(s)) @bigmemtest(minsize=_2G + 10, memuse=2) def test_expandtabs(self, size): _ = self.from_latin1 s = _('-') * size tabsize = 8 self.assertEquals(s.expandtabs(), s) del s slen, remainder = divmod(size, tabsize) s = _(' \t') * slen s = s.expandtabs(tabsize) self.assertEquals(len(s), size - remainder) self.assertEquals(len(s.strip(_(' '))), 0) @bigmemtest(minsize=_2G, memuse=2) def test_find(self, size): _ = self.from_latin1 SUBSTR = _(' abc def ghi') sublen = len(SUBSTR) s = _('').join([SUBSTR, _('-') * size, SUBSTR]) self.assertEquals(s.find(_(' ')), 0) self.assertEquals(s.find(SUBSTR), 0) self.assertEquals(s.find(_(' '), sublen), sublen + size) self.assertEquals(s.find(SUBSTR, len(SUBSTR)), sublen + size) self.assertEquals(s.find(_('i')), SUBSTR.find(_('i'))) self.assertEquals(s.find(_('i'), sublen), sublen + size + SUBSTR.find(_('i'))) self.assertEquals(s.find(_('i'), size), sublen + size + SUBSTR.find(_('i'))) self.assertEquals(s.find(_('j')), -1) @bigmemtest(minsize=_2G, memuse=2) def test_index(self, size): _ = self.from_latin1 SUBSTR = _(' abc def ghi') sublen = len(SUBSTR) s = _('').join([SUBSTR, _('-') * size, SUBSTR]) self.assertEquals(s.index(_(' ')), 0) self.assertEquals(s.index(SUBSTR), 0) self.assertEquals(s.index(_(' '), sublen), sublen + size) self.assertEquals(s.index(SUBSTR, sublen), sublen + size) self.assertEquals(s.index(_('i')), SUBSTR.index(_('i'))) self.assertEquals(s.index(_('i'), sublen), sublen + size + SUBSTR.index(_('i'))) self.assertEquals(s.index(_('i'), size), sublen + size + SUBSTR.index(_('i'))) self.assertRaises(ValueError, s.index, _('j')) @bigmemtest(minsize=_2G, memuse=2) def test_isalnum(self, size): _ = self.from_latin1 SUBSTR = _('123456') s = _('a') * size + SUBSTR self.assertTrue(s.isalnum()) s += _('.') self.assertFalse(s.isalnum()) @bigmemtest(minsize=_2G, memuse=2) def test_isalpha(self, size): _ = self.from_latin1 SUBSTR = _('zzzzzzz') s = _('a') * size + SUBSTR self.assertTrue(s.isalpha()) s += _('.') self.assertFalse(s.isalpha()) @bigmemtest(minsize=_2G, memuse=2) def test_isdigit(self, size): _ = self.from_latin1 SUBSTR = _('123456') s = _('9') * size + SUBSTR self.assertTrue(s.isdigit()) s += _('z') self.assertFalse(s.isdigit()) @bigmemtest(minsize=_2G, memuse=2) def test_islower(self, size): _ = self.from_latin1 chars = _(''.join( chr(c) for c in range(255) if not chr(c).isupper())) repeats = size // len(chars) + 2 s = chars * repeats self.assertTrue(s.islower()) s += _('A') self.assertFalse(s.islower()) @bigmemtest(minsize=_2G, memuse=2) def test_isspace(self, size): _ = self.from_latin1 whitespace = _(' \f\n\r\t\v') repeats = size // len(whitespace) + 2 s = whitespace * repeats self.assertTrue(s.isspace()) s += _('j') self.assertFalse(s.isspace()) @bigmemtest(minsize=_2G, memuse=2) def test_istitle(self, size): _ = self.from_latin1 SUBSTR = _('123456') s = _('').join([_('A'), _('a') * size, SUBSTR]) self.assertTrue(s.istitle()) s += _('A') self.assertTrue(s.istitle()) s += _('aA') self.assertFalse(s.istitle()) @bigmemtest(minsize=_2G, memuse=2) def test_isupper(self, size): _ = self.from_latin1 chars = _(''.join( chr(c) for c in range(255) if not chr(c).islower())) repeats = size // len(chars) + 2 s = chars * repeats self.assertTrue(s.isupper()) s += _('a') self.assertFalse(s.isupper()) @bigmemtest(minsize=_2G, memuse=2) def test_join(self, size): _ = self.from_latin1 s = _('A') * size x = s.join([_('aaaaa'), _('bbbbb')]) self.assertEquals(x.count(_('a')), 5) self.assertEquals(x.count(_('b')), 5) self.assertTrue(x.startswith(_('aaaaaA'))) self.assertTrue(x.endswith(_('Abbbbb'))) @bigmemtest(minsize=_2G + 10, memuse=1) def test_ljust(self, size): _ = self.from_latin1 SUBSTR = _(' abc def ghi') s = SUBSTR.ljust(size) self.assertTrue(s.startswith(SUBSTR + _(' '))) self.assertEquals(len(s), size) self.assertEquals(s.strip(), SUBSTR.strip()) @bigmemtest(minsize=_2G + 10, memuse=2) def test_lower(self, size): _ = self.from_latin1 s = _('A') * size s = s.lower() self.assertEquals(len(s), size) self.assertEquals(s.count(_('a')), size) @bigmemtest(minsize=_2G + 10, memuse=1) def test_lstrip(self, size): _ = self.from_latin1 SUBSTR = _('abc def ghi') s = SUBSTR.rjust(size) self.assertEquals(len(s), size) self.assertEquals(s.lstrip(), SUBSTR.lstrip()) del s s = SUBSTR.ljust(size) self.assertEquals(len(s), size) # Type-specific optimization if isinstance(s, (str, bytes)): stripped = s.lstrip() self.assertTrue(stripped is s) @bigmemtest(minsize=_2G + 10, memuse=2) def test_replace(self, size): _ = self.from_latin1 replacement = _('a') s = _(' ') * size s = s.replace(_(' '), replacement) self.assertEquals(len(s), size) self.assertEquals(s.count(replacement), size) s = s.replace(replacement, _(' '), size - 4) self.assertEquals(len(s), size) self.assertEquals(s.count(replacement), 4) self.assertEquals(s[-10:], _(' aaaa')) @bigmemtest(minsize=_2G, memuse=2) def test_rfind(self, size): _ = self.from_latin1 SUBSTR = _(' abc def ghi') sublen = len(SUBSTR) s = _('').join([SUBSTR, _('-') * size, SUBSTR]) self.assertEquals(s.rfind(_(' ')), sublen + size + SUBSTR.rfind(_(' '))) self.assertEquals(s.rfind(SUBSTR), sublen + size) self.assertEquals(s.rfind(_(' '), 0, size), SUBSTR.rfind(_(' '))) self.assertEquals(s.rfind(SUBSTR, 0, sublen + size), 0) self.assertEquals(s.rfind(_('i')), sublen + size + SUBSTR.rfind(_('i'))) self.assertEquals(s.rfind(_('i'), 0, sublen), SUBSTR.rfind(_('i'))) self.assertEquals(s.rfind(_('i'), 0, sublen + size), SUBSTR.rfind(_('i'))) self.assertEquals(s.rfind(_('j')), -1) @bigmemtest(minsize=_2G, memuse=2) def test_rindex(self, size): _ = self.from_latin1 SUBSTR = _(' abc def ghi') sublen = len(SUBSTR) s = _('').join([SUBSTR, _('-') * size, SUBSTR]) self.assertEquals(s.rindex(_(' ')), sublen + size + SUBSTR.rindex(_(' '))) self.assertEquals(s.rindex(SUBSTR), sublen + size) self.assertEquals(s.rindex(_(' '), 0, sublen + size - 1), SUBSTR.rindex(_(' '))) self.assertEquals(s.rindex(SUBSTR, 0, sublen + size), 0) self.assertEquals(s.rindex(_('i')), sublen + size + SUBSTR.rindex(_('i'))) self.assertEquals(s.rindex(_('i'), 0, sublen), SUBSTR.rindex(_('i'))) self.assertEquals(s.rindex(_('i'), 0, sublen + size), SUBSTR.rindex(_('i'))) self.assertRaises(ValueError, s.rindex, _('j')) @bigmemtest(minsize=_2G + 10, memuse=1) def test_rjust(self, size): _ = self.from_latin1 SUBSTR = _(' abc def ghi') s = SUBSTR.ljust(size) self.assertTrue(s.startswith(SUBSTR + _(' '))) self.assertEquals(len(s), size) self.assertEquals(s.strip(), SUBSTR.strip()) @bigmemtest(minsize=_2G + 10, memuse=1) def test_rstrip(self, size): _ = self.from_latin1 SUBSTR = _(' abc def ghi') s = SUBSTR.ljust(size) self.assertEquals(len(s), size) self.assertEquals(s.rstrip(), SUBSTR.rstrip()) del s s = SUBSTR.rjust(size) self.assertEquals(len(s), size) # Type-specific optimization if isinstance(s, (str, bytes)): stripped = s.rstrip() self.assertTrue(stripped is s) # The test takes about size bytes to build a string, and then about # sqrt(size) substrings of sqrt(size) in size and a list to # hold sqrt(size) items. It's close but just over 2x size. @bigmemtest(minsize=_2G, memuse=2.1) def test_split_small(self, size): _ = self.from_latin1 # Crudely calculate an estimate so that the result of s.split won't # take up an inordinate amount of memory chunksize = int(size ** 0.5 + 2) SUBSTR = _('a') + _(' ') * chunksize s = SUBSTR * chunksize l = s.split() self.assertEquals(len(l), chunksize) expected = _('a') for item in l: self.assertEquals(item, expected) del l l = s.split(_('a')) self.assertEquals(len(l), chunksize + 1) expected = _(' ') * chunksize for item in filter(None, l): self.assertEquals(item, expected) # Allocates a string of twice size (and briefly two) and a list of # size. Because of internal affairs, the s.split() call produces a # list of size times the same one-character string, so we only # suffer for the list size. (Otherwise, it'd cost another 48 times # size in bytes!) Nevertheless, a list of size takes # 8*size bytes. @bigmemtest(minsize=_2G + 5, memuse=10) def test_split_large(self, size): _ = self.from_latin1 s = _(' a') * size + _(' ') l = s.split() self.assertEquals(len(l), size) self.assertEquals(set(l), set([_('a')])) del l l = s.split(_('a')) self.assertEquals(len(l), size + 1) self.assertEquals(set(l), set([_(' ')])) @bigmemtest(minsize=_2G, memuse=2.1) def test_splitlines(self, size): _ = self.from_latin1 # Crudely calculate an estimate so that the result of s.split won't # take up an inordinate amount of memory chunksize = int(size ** 0.5 + 2) // 2 SUBSTR = _(' ') * chunksize + _('\n') + _(' ') * chunksize + _('\r\n') s = SUBSTR * chunksize l = s.splitlines() self.assertEquals(len(l), chunksize * 2) expected = _(' ') * chunksize for item in l: self.assertEquals(item, expected) @bigmemtest(minsize=_2G, memuse=2) def test_startswith(self, size): _ = self.from_latin1 SUBSTR = _(' abc def ghi') s = _('-') * size + SUBSTR self.assertTrue(s.startswith(s)) self.assertTrue(s.startswith(_('-') * size)) self.assertFalse(s.startswith(SUBSTR)) @bigmemtest(minsize=_2G, memuse=1) def test_strip(self, size): _ = self.from_latin1 SUBSTR = _(' abc def ghi ') s = SUBSTR.rjust(size) self.assertEquals(len(s), size) self.assertEquals(s.strip(), SUBSTR.strip()) del s s = SUBSTR.ljust(size) self.assertEquals(len(s), size) self.assertEquals(s.strip(), SUBSTR.strip()) @bigmemtest(minsize=_2G, memuse=2) def test_swapcase(self, size): _ = self.from_latin1 SUBSTR = _("aBcDeFG12.'\xa9\x00") sublen = len(SUBSTR) repeats = size // sublen + 2 s = SUBSTR * repeats s = s.swapcase() self.assertEquals(len(s), sublen * repeats) self.assertEquals(s[:sublen * 3], SUBSTR.swapcase() * 3) self.assertEquals(s[-sublen * 3:], SUBSTR.swapcase() * 3) @bigmemtest(minsize=_2G, memuse=2) def test_title(self, size): _ = self.from_latin1 SUBSTR = _('SpaaHAaaAaham') s = SUBSTR * (size // len(SUBSTR) + 2) s = s.title() self.assertTrue(s.startswith((SUBSTR * 3).title())) self.assertTrue(s.endswith(SUBSTR.lower() * 3)) @bigmemtest(minsize=_2G, memuse=2) def test_translate(self, size): _ = self.from_latin1 SUBSTR = _('aZz.z.Aaz.') if isinstance(SUBSTR, str): trans = { ord(_('.')): _('-'), ord(_('a')): _('!'), ord(_('Z')): _('$'), } else: trans = bytes.maketrans(b'.aZ', b'-!$') sublen = len(SUBSTR) repeats = size // sublen + 2 s = SUBSTR * repeats s = s.translate(trans) self.assertEquals(len(s), repeats * sublen) self.assertEquals(s[:sublen], SUBSTR.translate(trans)) self.assertEquals(s[-sublen:], SUBSTR.translate(trans)) self.assertEquals(s.count(_('.')), 0) self.assertEquals(s.count(_('!')), repeats * 2) self.assertEquals(s.count(_('z')), repeats * 3) @bigmemtest(minsize=_2G + 5, memuse=2) def test_upper(self, size): _ = self.from_latin1 s = _('a') * size s = s.upper() self.assertEquals(len(s), size) self.assertEquals(s.count(_('A')), size) @bigmemtest(minsize=_2G + 20, memuse=1) def test_zfill(self, size): _ = self.from_latin1 SUBSTR = _('-568324723598234') s = SUBSTR.zfill(size) self.assertTrue(s.endswith(_('0') + SUBSTR[1:])) self.assertTrue(s.startswith(_('-0'))) self.assertEquals(len(s), size) self.assertEquals(s.count(_('0')), size - len(SUBSTR)) # This test is meaningful even with size < 2G, as long as the # doubled string is > 2G (but it tests more if both are > 2G :) @bigmemtest(minsize=_1G + 2, memuse=3) def test_concat(self, size): _ = self.from_latin1 s = _('.') * size self.assertEquals(len(s), size) s = s + s self.assertEquals(len(s), size * 2) self.assertEquals(s.count(_('.')), size * 2) # This test is meaningful even with size < 2G, as long as the # repeated string is > 2G (but it tests more if both are > 2G :) @bigmemtest(minsize=_1G + 2, memuse=3) def test_repeat(self, size): _ = self.from_latin1 s = _('.') * size self.assertEquals(len(s), size) s = s * 2 self.assertEquals(len(s), size * 2) self.assertEquals(s.count(_('.')), size * 2) @bigmemtest(minsize=_2G + 20, memuse=2) def test_slice_and_getitem(self, size): _ = self.from_latin1 SUBSTR = _('0123456789') sublen = len(SUBSTR) s = SUBSTR * (size // sublen) stepsize = len(s) // 100 stepsize = stepsize - (stepsize % sublen) for i in range(0, len(s) - stepsize, stepsize): self.assertEquals(s[i], SUBSTR[0]) self.assertEquals(s[i:i + sublen], SUBSTR) self.assertEquals(s[i:i + sublen:2], SUBSTR[::2]) if i > 0: self.assertEquals(s[i + sublen - 1:i - 1:-3], SUBSTR[sublen::-3]) # Make sure we do some slicing and indexing near the end of the # string, too. self.assertEquals(s[len(s) - 1], SUBSTR[-1]) self.assertEquals(s[-1], SUBSTR[-1]) self.assertEquals(s[len(s) - 10], SUBSTR[0]) self.assertEquals(s[-sublen], SUBSTR[0]) self.assertEquals(s[len(s):], _('')) self.assertEquals(s[len(s) - 1:], SUBSTR[-1:]) self.assertEquals(s[-1:], SUBSTR[-1:]) self.assertEquals(s[len(s) - sublen:], SUBSTR) self.assertEquals(s[-sublen:], SUBSTR) self.assertEquals(len(s[:]), len(s)) self.assertEquals(len(s[:len(s) - 5]), len(s) - 5) self.assertEquals(len(s[5:-5]), len(s) - 10) self.assertRaises(IndexError, operator.getitem, s, len(s)) self.assertRaises(IndexError, operator.getitem, s, len(s) + 1) self.assertRaises(IndexError, operator.getitem, s, len(s) + 1<<31) @bigmemtest(minsize=_2G, memuse=2) def test_contains(self, size): _ = self.from_latin1 SUBSTR = _('0123456789') edge = _('-') * (size // 2) s = _('').join([edge, SUBSTR, edge]) del edge self.assertTrue(SUBSTR in s) self.assertFalse(SUBSTR * 2 in s) self.assertTrue(_('-') in s) self.assertFalse(_('a') in s) s += _('a') self.assertTrue(_('a') in s) @bigmemtest(minsize=_2G + 10, memuse=2) def test_compare(self, size): _ = self.from_latin1 s1 = _('-') * size s2 = _('-') * size self.assertEqual(s1, s2) del s2 s2 = s1 + _('a') self.assertFalse(s1 == s2) del s2 s2 = _('.') * size self.assertFalse(s1 == s2) @bigmemtest(minsize=_2G + 10, memuse=1) def test_hash(self, size): # Not sure if we can do any meaningful tests here... Even if we # start relying on the exact algorithm used, the result will be # different depending on the size of the C 'long int'. Even this # test is dodgy (there's no *guarantee* that the two things should # have a different hash, even if they, in the current # implementation, almost always do.) _ = self.from_latin1 s = _('\x00') * size h1 = hash(s) del s s = _('\x00') * (size + 1) self.assertFalse(h1 == hash(s)) class StrTest(unittest.TestCase, BaseStrTest): def from_latin1(self, s): return s def basic_encode_test(self, size, enc, c='.', expectedsize=None): if expectedsize is None: expectedsize = size s = c * size self.assertEquals(len(s.encode(enc)), expectedsize) def setUp(self): # HACK: adjust memory use of tests inherited from BaseStrTest # according to character size. self._adjusted = {} for name in dir(BaseStrTest): if not name.startswith('test_'): continue meth = getattr(type(self), name) try: memuse = meth.memuse except AttributeError: continue meth.memuse = character_size * memuse self._adjusted[name] = memuse def tearDown(self): for name, memuse in self._adjusted.items(): getattr(type(self), name).memuse = memuse @bigmemtest(minsize=_2G + 2, memuse=character_size + 1) def test_encode(self, size): return self.basic_encode_test(size, 'utf-8') @precisionbigmemtest(size=_4G // 6 + 2, memuse=character_size + 1) def test_encode_raw_unicode_escape(self, size): try: return self.basic_encode_test(size, 'raw_unicode_escape') except MemoryError: pass # acceptable on 32-bit @precisionbigmemtest(size=_4G // 5 + 70, memuse=character_size + 1) def test_encode_utf7(self, size): try: return self.basic_encode_test(size, 'utf7') except MemoryError: pass # acceptable on 32-bit @precisionbigmemtest(size=_4G // 4 + 5, memuse=character_size + 4) def test_encode_utf32(self, size): try: return self.basic_encode_test(size, 'utf32', expectedsize=4*size+4) except MemoryError: pass # acceptable on 32-bit @precisionbigmemtest(size=_2G - 1, memuse=character_size + 1) def test_encode_ascii(self, size): return self.basic_encode_test(size, 'ascii', c='A') @precisionbigmemtest(size=_4G // 5, memuse=character_size * (6 + 1)) def test_unicode_repr_overflow(self, size): try: s = "\uAAAA"*size r = repr(s) except MemoryError: pass # acceptable on 32-bit else: self.assertTrue(s == eval(r)) @bigmemtest(minsize=_2G + 10, memuse=character_size * 2) def test_format(self, size): s = '-' * size sf = '%s' % (s,) self.assertEqual(s, sf) del sf sf = '..%s..' % (s,) self.assertEquals(len(sf), len(s) + 4) self.assertTrue(sf.startswith('..-')) self.assertTrue(sf.endswith('-..')) del s, sf size //= 2 edge = '-' * size s = ''.join([edge, '%s', edge]) del edge s = s % '...' self.assertEquals(len(s), size * 2 + 3) self.assertEquals(s.count('.'), 3) self.assertEquals(s.count('-'), size * 2) @bigmemtest(minsize=_2G + 10, memuse=character_size * 2) def test_repr_small(self, size): s = '-' * size s = repr(s) self.assertEquals(len(s), size + 2) self.assertEquals(s[0], "'") self.assertEquals(s[-1], "'") self.assertEquals(s.count('-'), size) del s # repr() will create a string four times as large as this 'binary # string', but we don't want to allocate much more than twice # size in total. (We do extra testing in test_repr_large()) size = size // 5 * 2 s = '\x00' * size s = repr(s) self.assertEquals(len(s), size * 4 + 2) self.assertEquals(s[0], "'") self.assertEquals(s[-1], "'") self.assertEquals(s.count('\\'), size) self.assertEquals(s.count('0'), size * 2) @bigmemtest(minsize=_2G + 10, memuse=character_size * 5) def test_repr_large(self, size): s = '\x00' * size s = repr(s) self.assertEquals(len(s), size * 4 + 2) self.assertEquals(s[0], "'") self.assertEquals(s[-1], "'") self.assertEquals(s.count('\\'), size) self.assertEquals(s.count('0'), size * 2) @bigmemtest(minsize=2**32 / 5, memuse=character_size * 7) def test_unicode_repr(self, size): s = "\uAAAA" * size for f in (repr, ascii): r = f(s) self.assertTrue(len(r) > size) self.assertTrue(r.endswith(r"\uaaaa'"), r[-10:]) del r # The character takes 4 bytes even in UCS-2 builds because it will # be decomposed into surrogates. @bigmemtest(minsize=2**32 / 5, memuse=4 + character_size * 9) def test_unicode_repr_wide(self, size): s = "\U0001AAAA" * size for f in (repr, ascii): r = f(s) self.assertTrue(len(r) > size) self.assertTrue(r.endswith(r"\U0001aaaa'"), r[-12:]) del r class BytesTest(unittest.TestCase, BaseStrTest): def from_latin1(self, s): return s.encode("latin1") @bigmemtest(minsize=_2G + 2, memuse=1 + character_size) def test_decode(self, size): s = self.from_latin1('.') * size self.assertEquals(len(s.decode('utf-8')), size) class BytearrayTest(unittest.TestCase, BaseStrTest): def from_latin1(self, s): return bytearray(s.encode("latin1")) @bigmemtest(minsize=_2G + 2, memuse=1 + character_size) def test_decode(self, size): s = self.from_latin1('.') * size self.assertEquals(len(s.decode('utf-8')), size) test_hash = None test_split_large = None class TupleTest(unittest.TestCase): # Tuples have a small, fixed-sized head and an array of pointers to # data. Since we're testing 64-bit addressing, we can assume that the # pointers are 8 bytes, and that thus that the tuples take up 8 bytes # per size. # As a side-effect of testing long tuples, these tests happen to test # having more than 2<<31 references to any given object. Hence the # use of different types of objects as contents in different tests. @bigmemtest(minsize=_2G + 2, memuse=16) def test_compare(self, size): t1 = ('',) * size t2 = ('',) * size self.assertEqual(t1, t2) del t2 t2 = ('',) * (size + 1) self.assertFalse(t1 == t2) del t2 t2 = (1,) * size self.assertFalse(t1 == t2) # Test concatenating into a single tuple of more than 2G in length, # and concatenating a tuple of more than 2G in length separately, so # the smaller test still gets run even if there isn't memory for the # larger test (but we still let the tester know the larger test is # skipped, in verbose mode.) def basic_concat_test(self, size): t = ((),) * size self.assertEquals(len(t), size) t = t + t self.assertEquals(len(t), size * 2) @bigmemtest(minsize=_2G // 2 + 2, memuse=24) def test_concat_small(self, size): return self.basic_concat_test(size) @bigmemtest(minsize=_2G + 2, memuse=24) def test_concat_large(self, size): return self.basic_concat_test(size) @bigmemtest(minsize=_2G // 5 + 10, memuse=8 * 5) def test_contains(self, size): t = (1, 2, 3, 4, 5) * size self.assertEquals(len(t), size * 5) self.assertTrue(5 in t) self.assertFalse((1, 2, 3, 4, 5) in t) self.assertFalse(0 in t) @bigmemtest(minsize=_2G + 10, memuse=8) def test_hash(self, size): t1 = (0,) * size h1 = hash(t1) del t1 t2 = (0,) * (size + 1) self.assertFalse(h1 == hash(t2)) @bigmemtest(minsize=_2G + 10, memuse=8) def test_index_and_slice(self, size): t = (None,) * size self.assertEquals(len(t), size) self.assertEquals(t[-1], None) self.assertEquals(t[5], None) self.assertEquals(t[size - 1], None) self.assertRaises(IndexError, operator.getitem, t, size) self.assertEquals(t[:5], (None,) * 5) self.assertEquals(t[-5:], (None,) * 5) self.assertEquals(t[20:25], (None,) * 5) self.assertEquals(t[-25:-20], (None,) * 5) self.assertEquals(t[size - 5:], (None,) * 5) self.assertEquals(t[size - 5:size], (None,) * 5) self.assertEquals(t[size - 6:size - 2], (None,) * 4) self.assertEquals(t[size:size], ()) self.assertEquals(t[size:size+5], ()) # Like test_concat, split in two. def basic_test_repeat(self, size): t = ('',) * size self.assertEquals(len(t), size) t = t * 2 self.assertEquals(len(t), size * 2) @bigmemtest(minsize=_2G // 2 + 2, memuse=24) def test_repeat_small(self, size): return self.basic_test_repeat(size) @bigmemtest(minsize=_2G + 2, memuse=24) def test_repeat_large(self, size): return self.basic_test_repeat(size) @bigmemtest(minsize=_1G - 1, memuse=12) def test_repeat_large_2(self, size): return self.basic_test_repeat(size) @precisionbigmemtest(size=_1G - 1, memuse=9) def test_from_2G_generator(self, size): try: t = tuple(range(size)) except MemoryError: pass # acceptable on 32-bit else: count = 0 for item in t: self.assertEquals(item, count) count += 1 self.assertEquals(count, size) @precisionbigmemtest(size=_1G - 25, memuse=9) def test_from_almost_2G_generator(self, size): try: t = tuple(range(size)) count = 0 for item in t: self.assertEquals(item, count) count += 1 self.assertEquals(count, size) except MemoryError: pass # acceptable, expected on 32-bit # Like test_concat, split in two. def basic_test_repr(self, size): t = (0,) * size s = repr(t) # The repr of a tuple of 0's is exactly three times the tuple length. self.assertEquals(len(s), size * 3) self.assertEquals(s[:5], '(0, 0') self.assertEquals(s[-5:], '0, 0)') self.assertEquals(s.count('0'), size) @bigmemtest(minsize=_2G // 3 + 2, memuse=8 + 3) def test_repr_small(self, size): return self.basic_test_repr(size) @bigmemtest(minsize=_2G + 2, memuse=8 + 3) def test_repr_large(self, size): return self.basic_test_repr(size) class ListTest(unittest.TestCase): # Like tuples, lists have a small, fixed-sized head and an array of # pointers to data, so 8 bytes per size. Also like tuples, we make the # lists hold references to various objects to test their refcount # limits. @bigmemtest(minsize=_2G + 2, memuse=16) def test_compare(self, size): l1 = [''] * size l2 = [''] * size self.assertEqual(l1, l2) del l2 l2 = [''] * (size + 1) self.assertFalse(l1 == l2) del l2 l2 = [2] * size self.assertFalse(l1 == l2) # Test concatenating into a single list of more than 2G in length, # and concatenating a list of more than 2G in length separately, so # the smaller test still gets run even if there isn't memory for the # larger test (but we still let the tester know the larger test is # skipped, in verbose mode.) def basic_test_concat(self, size): l = [[]] * size self.assertEquals(len(l), size) l = l + l self.assertEquals(len(l), size * 2) @bigmemtest(minsize=_2G // 2 + 2, memuse=24) def test_concat_small(self, size): return self.basic_test_concat(size) @bigmemtest(minsize=_2G + 2, memuse=24) def test_concat_large(self, size): return self.basic_test_concat(size) def basic_test_inplace_concat(self, size): l = [sys.stdout] * size l += l self.assertEquals(len(l), size * 2) self.assertTrue(l[0] is l[-1]) self.assertTrue(l[size - 1] is l[size + 1]) @bigmemtest(minsize=_2G // 2 + 2, memuse=24) def test_inplace_concat_small(self, size): return self.basic_test_inplace_concat(size) @bigmemtest(minsize=_2G + 2, memuse=24) def test_inplace_concat_large(self, size): return self.basic_test_inplace_concat(size) @bigmemtest(minsize=_2G // 5 + 10, memuse=8 * 5) def test_contains(self, size): l = [1, 2, 3, 4, 5] * size self.assertEquals(len(l), size * 5) self.assertTrue(5 in l) self.assertFalse([1, 2, 3, 4, 5] in l) self.assertFalse(0 in l) @bigmemtest(minsize=_2G + 10, memuse=8) def test_hash(self, size): l = [0] * size self.assertRaises(TypeError, hash, l) @bigmemtest(minsize=_2G + 10, memuse=8) def test_index_and_slice(self, size): l = [None] * size self.assertEquals(len(l), size) self.assertEquals(l[-1], None) self.assertEquals(l[5], None) self.assertEquals(l[size - 1], None) self.assertRaises(IndexError, operator.getitem, l, size) self.assertEquals(l[:5], [None] * 5) self.assertEquals(l[-5:], [None] * 5) self.assertEquals(l[20:25], [None] * 5) self.assertEquals(l[-25:-20], [None] * 5) self.assertEquals(l[size - 5:], [None] * 5) self.assertEquals(l[size - 5:size], [None] * 5) self.assertEquals(l[size - 6:size - 2], [None] * 4) self.assertEquals(l[size:size], []) self.assertEquals(l[size:size+5], []) l[size - 2] = 5 self.assertEquals(len(l), size) self.assertEquals(l[-3:], [None, 5, None]) self.assertEquals(l.count(5), 1) self.assertRaises(IndexError, operator.setitem, l, size, 6) self.assertEquals(len(l), size) l[size - 7:] = [1, 2, 3, 4, 5] size -= 2 self.assertEquals(len(l), size) self.assertEquals(l[-7:], [None, None, 1, 2, 3, 4, 5]) l[:7] = [1, 2, 3, 4, 5] size -= 2 self.assertEquals(len(l), size) self.assertEquals(l[:7], [1, 2, 3, 4, 5, None, None]) del l[size - 1] size -= 1 self.assertEquals(len(l), size) self.assertEquals(l[-1], 4) del l[-2:] size -= 2 self.assertEquals(len(l), size) self.assertEquals(l[-1], 2) del l[0] size -= 1 self.assertEquals(len(l), size) self.assertEquals(l[0], 2) del l[:2] size -= 2 self.assertEquals(len(l), size) self.assertEquals(l[0], 4) # Like test_concat, split in two. def basic_test_repeat(self, size): l = [] * size self.assertFalse(l) l = [''] * size self.assertEquals(len(l), size) l = l * 2 self.assertEquals(len(l), size * 2) @bigmemtest(minsize=_2G // 2 + 2, memuse=24) def test_repeat_small(self, size): return self.basic_test_repeat(size) @bigmemtest(minsize=_2G + 2, memuse=24) def test_repeat_large(self, size): return self.basic_test_repeat(size) def basic_test_inplace_repeat(self, size): l = [''] l *= size self.assertEquals(len(l), size) self.assertTrue(l[0] is l[-1]) del l l = [''] * size l *= 2 self.assertEquals(len(l), size * 2) self.assertTrue(l[size - 1] is l[-1]) @bigmemtest(minsize=_2G // 2 + 2, memuse=16) def test_inplace_repeat_small(self, size): return self.basic_test_inplace_repeat(size) @bigmemtest(minsize=_2G + 2, memuse=16) def test_inplace_repeat_large(self, size): return self.basic_test_inplace_repeat(size) def basic_test_repr(self, size): l = [0] * size s = repr(l) # The repr of a list of 0's is exactly three times the list length. self.assertEquals(len(s), size * 3) self.assertEquals(s[:5], '[0, 0') self.assertEquals(s[-5:], '0, 0]') self.assertEquals(s.count('0'), size) @bigmemtest(minsize=_2G // 3 + 2, memuse=8 + 3) def test_repr_small(self, size): return self.basic_test_repr(size) @bigmemtest(minsize=_2G + 2, memuse=8 + 3) def test_repr_large(self, size): return self.basic_test_repr(size) # list overallocates ~1/8th of the total size (on first expansion) so # the single list.append call puts memuse at 9 bytes per size. @bigmemtest(minsize=_2G, memuse=9) def test_append(self, size): l = [object()] * size l.append(object()) self.assertEquals(len(l), size+1) self.assertTrue(l[-3] is l[-2]) self.assertFalse(l[-2] is l[-1]) @bigmemtest(minsize=_2G // 5 + 2, memuse=8 * 5) def test_count(self, size): l = [1, 2, 3, 4, 5] * size self.assertEquals(l.count(1), size) self.assertEquals(l.count("1"), 0) def basic_test_extend(self, size): l = [object] * size l.extend(l) self.assertEquals(len(l), size * 2) self.assertTrue(l[0] is l[-1]) self.assertTrue(l[size - 1] is l[size + 1]) @bigmemtest(minsize=_2G // 2 + 2, memuse=16) def test_extend_small(self, size): return self.basic_test_extend(size) @bigmemtest(minsize=_2G + 2, memuse=16) def test_extend_large(self, size): return self.basic_test_extend(size) @bigmemtest(minsize=_2G // 5 + 2, memuse=8 * 5) def test_index(self, size): l = [1, 2, 3, 4, 5] * size size *= 5 self.assertEquals(l.index(1), 0) self.assertEquals(l.index(5, size - 5), size - 1) self.assertEquals(l.index(5, size - 5, size), size - 1) self.assertRaises(ValueError, l.index, 1, size - 4, size) self.assertRaises(ValueError, l.index, 6) # This tests suffers from overallocation, just like test_append. @bigmemtest(minsize=_2G + 10, memuse=9) def test_insert(self, size): l = [1.0] * size l.insert(size - 1, "A") size += 1 self.assertEquals(len(l), size) self.assertEquals(l[-3:], [1.0, "A", 1.0]) l.insert(size + 1, "B") size += 1 self.assertEquals(len(l), size) self.assertEquals(l[-3:], ["A", 1.0, "B"]) l.insert(1, "C") size += 1 self.assertEquals(len(l), size) self.assertEquals(l[:3], [1.0, "C", 1.0]) self.assertEquals(l[size - 3:], ["A", 1.0, "B"]) @bigmemtest(minsize=_2G // 5 + 4, memuse=8 * 5) def test_pop(self, size): l = ["a", "b", "c", "d", "e"] * size size *= 5 self.assertEquals(len(l), size) item = l.pop() size -= 1 self.assertEquals(len(l), size) self.assertEquals(item, "e") self.assertEquals(l[-2:], ["c", "d"]) item = l.pop(0) size -= 1 self.assertEquals(len(l), size) self.assertEquals(item, "a") self.assertEquals(l[:2], ["b", "c"]) item = l.pop(size - 2) size -= 1 self.assertEquals(len(l), size) self.assertEquals(item, "c") self.assertEquals(l[-2:], ["b", "d"]) @bigmemtest(minsize=_2G + 10, memuse=8) def test_remove(self, size): l = [10] * size self.assertEquals(len(l), size) l.remove(10) size -= 1 self.assertEquals(len(l), size) # Because of the earlier l.remove(), this append doesn't trigger # a resize. l.append(5) size += 1 self.assertEquals(len(l), size) self.assertEquals(l[-2:], [10, 5]) l.remove(5) size -= 1 self.assertEquals(len(l), size) self.assertEquals(l[-2:], [10, 10]) @bigmemtest(minsize=_2G // 5 + 2, memuse=8 * 5) def test_reverse(self, size): l = [1, 2, 3, 4, 5] * size l.reverse() self.assertEquals(len(l), size * 5) self.assertEquals(l[-5:], [5, 4, 3, 2, 1]) self.assertEquals(l[:5], [5, 4, 3, 2, 1]) @bigmemtest(minsize=_2G // 5 + 2, memuse=8 * 5) def test_sort(self, size): l = [1, 2, 3, 4, 5] * size l.sort() self.assertEquals(len(l), size * 5) self.assertEquals(l.count(1), size) self.assertEquals(l[:10], [1] * 10) self.assertEquals(l[-10:], [5] * 10) def test_main(): support.run_unittest(StrTest, BytesTest, BytearrayTest, TupleTest, ListTest) if __name__ == '__main__': if len(sys.argv) > 1: support.set_memlimit(sys.argv[1]) test_main()
mancoast/CPythonPyc_test
fail/312_test_bigmem.py
Python
gpl-3.0
41,777
import pygame from . import * class TutorialScene(BaseScene): def __init__(self, context): # Create scene and make transparent box over the 'x' BaseScene.__init__(self, context) self.btn = pygame.Surface((50,50), pygame.SRCALPHA, 32) self.btn.convert_alpha() context.screen.blit(self.context.tutorial, (0,0)) self.b = context.screen.blit(self.btn, (1120,25)) def handle_inputs(self, events): for event in events: if event.type == pygame.QUIT: pygame.quit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: self.context.scene = TitleScene(self.context) elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1: pos = pygame.mouse.get_pos() if self.b.collidepoint(pos): self.context.scene = TitleScene(self.context) def render_scene(self): pygame.display.flip()
theheckle/rapid-pie-movement
game/scenes/tutorial_scene.py
Python
mit
1,005
#!/usr/bin/env python import sys, getopt, argparse from kazoo.client import KazooClient import json def loadZookeeperOptions(opts,zk): node = "/all_clients/"+opts['client']+"/offline/semvec" if zk.exists(node): data, stat = zk.get(node) jStr = data.decode("utf-8") print "Found zookeeper configuration:",jStr j = json.loads(jStr) for key in j: opts[key] = j[key] def activateModel(args,folder,zk): node = "/all_clients/"+args.client+"/svtext" print "Activating model in zookeper at node ",node," with data ",folder if zk.exists(node): zk.set(node,folder) else: zk.create(node,folder,makepath=True) if __name__ == '__main__': parser = argparse.ArgumentParser(prog='set-client-config') parser.add_argument('-z', '--zookeeper', help='zookeeper hosts', required=True) parser.add_argument('--clientVariable', help='client variable name', default="$CLIENT") args = parser.parse_args() opts = vars(args) zk = KazooClient(hosts=args.zookeeper) zk.start() for line in sys.stdin: line = line.rstrip() parts = line.split() if len(parts) == 3 and not line.startswith("#"): clients = parts[0].split(',') node = parts[1] value = parts[2] print "--------------------------" print parts[0],node,"->",value for client in clients: nodeClient = node.replace(args.clientVariable,client) valueClient = value.replace(args.clientVariable,client) print "----" print nodeClient print valueClient if zk.exists(nodeClient): zk.set(nodeClient,valueClient) else: zk.create(nodeClient,valueClient,makepath=True) zk.stop()
Snazz2001/seldon-server
scripts/zookeeper/set-client-config.py
Python
apache-2.0
1,898
#! /usr/bin/python from __future__ import division from pytronica import * #adj = 0.1 #def osc(p): #def osc1(p): #return Saw(p2f(p)) #os = [osc1(p+x) for x in [0, 12.03, 7-.03]] #return Layer(os) a = .5 saw = lambda p: Saw(p2f(p)) osc = lambda p: Pan(saw(p), -a) + Pan(saw(p+.1), a) def synth(p): return osc(p) * ExpDecay(1) s = .25 * synth(note('C4')) s.play()
chriswatrous/pytronica
songs/2.py
Python
gpl-2.0
390
# -*- coding: utf-8 -*- from setuptools import setup, find_packages import os import glob import sys #VERSION="2.1dev4" VERSION="2.6dev5" # Taken from kennethreitz/requests/setup.py package_directory = os.path.realpath(os.path.dirname(__file__)) def get_file_contents(file_path): """Get the context of the file using full path name.""" content = "" try: full_path = os.path.join(package_directory, file_path) content = open(full_path, 'r').read() except: print >> sys.stderr, "### could not open file %r" % file_path return content setup( name='privacyIDEA', version=VERSION, description='privacyIDEA: identity, multifactor authentication (OTP), ' 'authorization, audit', author='privacyidea.org', license='AGPLv3', author_email='[email protected]', url='http://www.privacyidea.org', keywords='OTP, two factor authentication, management, security', packages=find_packages(), scripts=['pi-manage.py', 'tools/privacyidea-convert-token', 'tools/privacyidea-create-pwidresolver-user', 'tools/privacyidea-create-sqlidresolver-user', 'tools/privacyidea-pip-update', 'tools/privacyidea-create-certificate', 'tools/privacyidea-fix-access-rights', 'tools/privacyidea-create-ad-users', 'tools/privacyidea-fetchssh.sh', 'tools/privacyidea-create-userdb.sh' ], extras_require={ 'dev': ["Sphinx>=1.3.1", "sphinxcontrib-httpdomain>=1.3.0"], 'test': ["coverage>=3.7.1", "mock>=1.0.1", "nose>=1.3.4", "responses>=0.4.0", "six>=1.8.0"], }, install_requires=["Flask>=0.10.1", "Flask-Cache>=0.13.1", "Flask-Migrate>=1.2.0", "Flask-SQLAlchemy>=2.0", "Flask-Script>=2.0.5", "Jinja2>=2.7.3", "Mako>=0.9.1", "MarkupSafe>=0.23", "MySQL-python>=1.2.5", "Pillow>=2.6.1", "PyJWT>=1.3.0", "PyYAML>=3.11", "Pygments>=2.0.2", "SQLAlchemy>=1.0.5", "Werkzeug>=0.10.4", "alembic>=0.6.7", "argparse>=1.2.1", "bcrypt>=1.1.0", "beautifulsoup4>=4.3.2", "cffi>=0.8.6", "configobj>=5.0.6", "docutils>=0.12", "funcparserlib>=0.3.6", "itsdangerous>=0.24", "ldap3>=0.9.8.4", "netaddr>=0.7.12", "passlib>=1.6.2", "pyasn1>=0.1.7", "pyOpenSSL>=0.15.1", "pycparser>=2.10", "pycrypto>=2.6.1", "pyrad>=2.0", "pyusb>=1.0.0b2", "qrcode>=5.1", "requests>=2.7.0", "sqlsoup>=0.9.0", "wsgiref>=0.1.2" ], include_package_data=True, data_files=[('etc/privacyidea/', ['deploy/apache/privacyideaapp.wsgi', 'deploy/privacyidea/dictionary', 'deploy/privacyidea/enckey', 'deploy/privacyidea/private.pem', 'deploy/privacyidea/public.pem']), ('share/man/man1', ["tools/privacyidea-convert-token.1", "tools/privacyidea-create-pwidresolver-user.1", "tools/privacyidea-create-sqlidresolver-user.1", "tools/privacyidea-pip-update.1", "tools/privacyidea-create-certificate.1", "tools/privacyidea-fix-access-rights.1" ]), ('lib/privacyidea/authmodules/FreeRADIUS', ["authmodules/FreeRADIUS/LICENSE", "authmodules/FreeRADIUS/privacyidea_radius.pm"]), ('lib/privacyidea/authmodules/OTRS', ["authmodules/OTRS/privacyIDEA.pm"]), ('lib/privacyidea/migrations', ["migrations/alembic.ini", "migrations/env.py", "migrations/README", "migrations/script.py.mako"]), ('lib/privacyidea/migrations/versions', ["migrations/versions/2551ee982544_.py", "migrations/versions/4f32a4e1bf33_.py", "migrations/versions/2181294eed0b_.py", "migrations/versions/e5cbeb7c177_.py", "migrations/versions/4d9178fa8336_.py", "migrations/versions/20969b4cbf06_.py"]) ], classifiers=["Framework :: Flask", "License :: OSI Approved :: " "GNU Affero General Public License v3", "Programming Language :: Python", "Development Status :: 5 - Production/Stable", "Topic :: Internet", "Topic :: Security", "Topic :: System ::" " Systems Administration :: Authentication/Directory" ], #message_extractors={'privacyidea': [ # ('**.py', 'python', None), # ('static/**.html', 'html', {'input_encoding': 'utf-8'})]}, zip_safe=False, long_description=get_file_contents('README.md') )
woddx/privacyidea
setup.py
Python
agpl-3.0
5,648
# -*- coding: iso-8859-15 -*- from xml.etree.ElementTree import * from descriptionparserxml import * from descriptionparserflatfile import * class DescriptionParserFactory: @classmethod def getParser(self, descParseInstruction): fp = open(descParseInstruction, 'r') tree = fromstring(fp.read()) fp.close() del fp grammarNode = tree.find('GameGrammar') del tree if(grammarNode == None): print "no valid parserConfig" return None attributes = grammarNode.attrib parserType = attributes.get('type') del attributes if(parserType == 'multiline'): return DescriptionParserFlatFile(grammarNode) elif(parserType == 'xml'): return DescriptionParserXml(grammarNode) else: print "Unknown parser: " +parserType return None
azumimuo/family-xbmc-addon
script.games.rom.collection.browser/resources/lib/pyscraper/descriptionparserfactory.py
Python
gpl-2.0
793
# The absolute import feature is required so that we get the root celery # module rather than `amo.celery`. from __future__ import absolute_import from collections import namedtuple from inspect import isclass from django.utils.translation import ugettext_lazy as _ __all__ = ('LOG', 'LOG_BY_ID', 'LOG_KEEP',) class _LOG(object): action_class = None class CREATE_ADDON(_LOG): id = 1 action_class = 'add' format = _(u'{addon} was created.') keep = True class EDIT_PROPERTIES(_LOG): """ Expects: addon """ id = 2 action_class = 'edit' format = _(u'{addon} properties edited.') class EDIT_DESCRIPTIONS(_LOG): id = 3 action_class = 'edit' format = _(u'{addon} description edited.') class EDIT_CATEGORIES(_LOG): id = 4 action_class = 'edit' format = _(u'Categories edited for {addon}.') class ADD_USER_WITH_ROLE(_LOG): id = 5 action_class = 'add' format = _(u'{0.name} ({1}) added to {addon}.') keep = True class REMOVE_USER_WITH_ROLE(_LOG): id = 6 action_class = 'delete' # L10n: {0} is the user being removed, {1} is their role. format = _(u'{0.name} ({1}) removed from {addon}.') keep = True class EDIT_CONTRIBUTIONS(_LOG): id = 7 action_class = 'edit' format = _(u'Contributions for {addon}.') class USER_DISABLE(_LOG): id = 8 format = _(u'{addon} disabled.') keep = True class USER_ENABLE(_LOG): id = 9 format = _(u'{addon} enabled.') keep = True class CHANGE_STATUS(_LOG): id = 12 # L10n: {status} is the status format = _(u'{addon} status changed to {status}.') keep = True class ADD_VERSION(_LOG): id = 16 action_class = 'add' format = _(u'{version} added to {addon}.') keep = True class EDIT_VERSION(_LOG): id = 17 action_class = 'edit' format = _(u'{version} edited for {addon}.') class DELETE_VERSION(_LOG): id = 18 action_class = 'delete' # Note, {0} is a string not a version since the version is deleted. # L10n: {0} is the version number format = _(u'Version {0} deleted from {addon}.') keep = True class ADD_FILE_TO_VERSION(_LOG): id = 19 action_class = 'add' format = _(u'File {0.name} added to {version} of {addon}.') class DELETE_FILE_FROM_VERSION(_LOG): """ Expecting: addon, filename, version Because the file is being deleted, filename and version should be strings and not the object. """ id = 20 action_class = 'delete' format = _(u'File {0} deleted from {version} of {addon}.') class APPROVE_VERSION(_LOG): id = 21 action_class = 'approve' format = _(u'{addon} {version} approved.') short = _(u'Approved') keep = True review_email_user = True review_queue = True reviewer_review_action = True class PRELIMINARY_VERSION(_LOG): id = 42 action_class = 'approve' format = _(u'{addon} {version} given preliminary review.') short = _(u'Preliminarily approved') keep = True review_email_user = True review_queue = True reviewer_review_action = True class REJECT_VERSION(_LOG): # takes add-on, version, reviewtype id = 43 action_class = 'reject' format = _(u'{addon} {version} rejected.') short = _(u'Rejected') keep = True review_email_user = True review_queue = True reviewer_review_action = True class RETAIN_VERSION(_LOG): # takes add-on, version, reviewtype id = 22 format = _(u'{addon} {version} retained.') short = _(u'Retained') keep = True review_email_user = True review_queue = True reviewer_review_action = True class ESCALATE_VERSION(_LOG): # takes add-on, version, reviewtype id = 23 format = _(u'{addon} {version} escalated.') short = _(u'Super review requested') keep = True review_email_user = True review_queue = True hide_developer = True class REQUEST_VERSION(_LOG): # takes add-on, version, reviewtype id = 24 format = _(u'{addon} {version} review requested.') short = _(u'Review requested') keep = True review_email_user = True review_queue = True class REQUEST_INFORMATION(_LOG): id = 44 format = _(u'{addon} {version} more information requested.') short = _(u'More information requested') keep = True review_email_user = True review_queue = True reviewer_review_action = True class REQUEST_SUPER_REVIEW(_LOG): id = 45 format = _(u'{addon} {version} super review requested.') short = _(u'Super review requested') keep = True review_queue = True sanitize = _(u'The addon has been flagged for Admin Review. It\'s still ' u'in our review queue, but it will need to be checked by one ' u'of our admin reviewers. The review might take longer than ' u'usual.') reviewer_review_action = True class COMMENT_VERSION(_LOG): id = 49 format = _(u'Comment on {addon} {version}.') short = _(u'Commented') keep = True review_queue = True hide_developer = True reviewer_review_action = True class ADD_TAG(_LOG): id = 25 action_class = 'tag' format = _(u'{tag} added to {addon}.') class REMOVE_TAG(_LOG): id = 26 action_class = 'tag' format = _(u'{tag} removed from {addon}.') class ADD_TO_COLLECTION(_LOG): id = 27 action_class = 'collection' format = _(u'{addon} added to {collection}.') class REMOVE_FROM_COLLECTION(_LOG): id = 28 action_class = 'collection' format = _(u'{addon} removed from {collection}.') class ADD_RATING(_LOG): id = 29 action_class = 'review' format = _(u'{rating} for {addon} written.') # TODO(davedash): Add these when we do the admin site class ADD_RECOMMENDED_CATEGORY(_LOG): id = 31 action_class = 'edit' # L10n: {0} is a category name. format = _(u'{addon} featured in {0}.') class REMOVE_RECOMMENDED_CATEGORY(_LOG): id = 32 action_class = 'edit' # L10n: {0} is a category name. format = _(u'{addon} no longer featured in {0}.') class ADD_RECOMMENDED(_LOG): id = 33 format = _(u'{addon} is now featured.') keep = True class REMOVE_RECOMMENDED(_LOG): id = 34 format = _(u'{addon} is no longer featured.') keep = True class ADD_APPVERSION(_LOG): id = 35 action_class = 'add' # L10n: {0} is the application, {1} is the version of the app format = _(u'{0} {1} added.') class CHANGE_USER_WITH_ROLE(_LOG): """ Expects: author.user, role, addon """ id = 36 # L10n: {0} is a user, {1} is their role format = _(u'{0.name} role changed to {1} for {addon}.') keep = True class CHANGE_LICENSE(_LOG): """ Expects: license, addon """ id = 37 action_class = 'edit' format = _(u'{addon} is now licensed under {0}.') class CHANGE_POLICY(_LOG): id = 38 action_class = 'edit' format = _(u'{addon} policy changed.') class CHANGE_ICON(_LOG): id = 39 action_class = 'edit' format = _(u'{addon} icon changed.') class APPROVE_RATING(_LOG): id = 40 action_class = 'approve' format = _(u'{rating} for {addon} approved.') reviewer_format = _(u'{user} approved {rating} for {addon}.') keep = True reviewer_event = True class DELETE_RATING(_LOG): """Requires rating.id and add-on objects.""" id = 41 action_class = 'review' format = _(u'Review {rating} for {addon} deleted.') reviewer_format = _(u'{user} deleted {rating} for {addon}.') keep = True reviewer_event = True class MAX_APPVERSION_UPDATED(_LOG): id = 46 format = _(u'Application max version for {version} updated.') class BULK_VALIDATION_EMAILED(_LOG): id = 47 format = _(u'Authors emailed about compatibility of {version}.') class BULK_VALIDATION_USER_EMAILED(_LOG): id = 130 format = _(u'Email sent to Author about add-on compatibility.') class CHANGE_PASSWORD(_LOG): id = 48 format = _(u'Password changed.') class APPROVE_VERSION_WAITING(_LOG): id = 53 action_class = 'approve' format = _(u'{addon} {version} approved but waiting to be made public.') short = _(u'Approved but waiting') keep = True review_email_user = True review_queue = True class USER_EDITED(_LOG): id = 60 format = _(u'Account updated.') class CUSTOM_TEXT(_LOG): id = 98 format = '{0}' class CUSTOM_HTML(_LOG): id = 99 format = '{0}' class OBJECT_ADDED(_LOG): id = 100 format = _(u'Created: {0}.') admin_event = True class OBJECT_EDITED(_LOG): id = 101 format = _(u'Edited field: {2} set to: {0}.') admin_event = True class OBJECT_DELETED(_LOG): id = 102 format = _(u'Deleted: {1}.') admin_event = True class ADMIN_USER_EDITED(_LOG): id = 103 format = _(u'User {user} edited, reason: {1}') admin_event = True class ADMIN_USER_ANONYMIZED(_LOG): id = 104 format = _(u'User {user} anonymized.') admin_event = True class ADMIN_USER_RESTRICTED(_LOG): id = 105 format = _(u'User {user} restricted.') admin_event = True class ADMIN_VIEWED_LOG(_LOG): id = 106 format = _(u'Admin {0} viewed activity log for {user}.') admin_event = True class EDIT_RATING(_LOG): id = 107 action_class = 'review' format = _(u'{rating} for {addon} updated.') class THEME_REVIEW(_LOG): id = 108 action_class = 'review' format = _(u'{addon} reviewed.') class ADMIN_USER_BANNED(_LOG): id = 109 format = _(u'User {user} banned.') admin_event = True class ADMIN_USER_PICTURE_DELETED(_LOG): id = 110 format = _(u'User {user} picture deleted.') admin_event = True class GROUP_USER_ADDED(_LOG): id = 120 action_class = 'access' format = _(u'User {0.name} added to {group}.') keep = True admin_event = True class GROUP_USER_REMOVED(_LOG): id = 121 action_class = 'access' format = _(u'User {0.name} removed from {group}.') keep = True admin_event = True class ADDON_UNLISTED(_LOG): id = 128 format = _(u'{addon} unlisted.') keep = True class BETA_SIGNED(_LOG): id = 131 format = _(u'{file} was signed.') keep = True # Obsolete, we don't care about validation results on beta files. class BETA_SIGNED_VALIDATION_FAILED(_LOG): id = 132 format = _(u'{file} was signed.') keep = True class DELETE_ADDON(_LOG): id = 133 action_class = 'delete' # L10n: {0} is the add-on GUID. format = _(u'Addon id {0} with GUID {1} has been deleted') keep = True class EXPERIMENT_SIGNED(_LOG): id = 134 format = _(u'{file} was signed.') keep = True class UNLISTED_SIGNED(_LOG): id = 135 format = _(u'{file} was signed.') keep = True # Obsolete, we don't care about validation results on unlisted files anymore. class UNLISTED_SIGNED_VALIDATION_FAILED(_LOG): id = 136 format = _(u'{file} was signed.') keep = True # Obsolete, we don't care about validation results on unlisted files anymore, # and the distinction for sideloading add-ons is gone as well. class UNLISTED_SIDELOAD_SIGNED_VALIDATION_PASSED(_LOG): id = 137 format = _(u'{file} was signed.') keep = True # Obsolete, we don't care about validation results on unlisted files anymore, # and the distinction for sideloading add-ons is gone as well. class UNLISTED_SIDELOAD_SIGNED_VALIDATION_FAILED(_LOG): id = 138 format = _(u'{file} was signed.') keep = True class PRELIMINARY_ADDON_MIGRATED(_LOG): id = 139 format = _(u'{addon} migrated from preliminary.') keep = True review_queue = True class DEVELOPER_REPLY_VERSION(_LOG): id = 140 format = _(u'Reply by developer on {addon} {version}.') short = _(u'Developer Reply') keep = True review_queue = True class REVIEWER_REPLY_VERSION(_LOG): id = 141 format = _(u'Reply by reviewer on {addon} {version}.') short = _(u'Reviewer Reply') keep = True review_queue = True class APPROVAL_NOTES_CHANGED(_LOG): id = 142 format = _(u'Approval notes changed for {addon} {version}.') short = _(u'Approval notes changed') keep = True review_queue = True class SOURCE_CODE_UPLOADED(_LOG): id = 143 format = _(u'Source code uploaded for {addon} {version}.') short = _(u'Source code uploaded') keep = True review_queue = True class CONFIRM_AUTO_APPROVED(_LOG): id = 144 format = _(u'Auto-Approval confirmed for {addon} {version}.') short = _(u'Auto-Approval confirmed') keep = True reviewer_review_action = True review_queue = True hide_developer = True class ENABLE_VERSION(_LOG): id = 145 format = _(u'{addon} {version} re-enabled.') class DISABLE_VERSION(_LOG): id = 146 format = _(u'{addon} {version} disabled.') class APPROVE_CONTENT(_LOG): id = 147 format = _(u'{addon} {version} content approved.') short = _(u'Content approved') keep = True reviewer_review_action = True review_queue = True hide_developer = True class REJECT_CONTENT(_LOG): id = 148 action_class = 'reject' format = _(u'{addon} {version} content rejected.') short = _(u'Content rejected') keep = True review_email_user = True review_queue = True reviewer_review_action = True class ADMIN_ALTER_INFO_REQUEST(_LOG): id = 149 format = _(u'{addon} information request altered or removed by admin.') short = _(u'Information request altered') keep = True reviewer_review_action = True review_queue = True class DEVELOPER_CLEAR_INFO_REQUEST(_LOG): id = 150 format = _(u'Information request cleared by developer on ' u'{addon} {version}.') short = _(u'Information request removed') keep = True review_queue = True class REQUEST_ADMIN_REVIEW_CODE(_LOG): id = 151 format = _(u'{addon} {version} admin add-on-review requested.') short = _(u'Admin add-on-review requested') keep = True review_queue = True reviewer_review_action = True class REQUEST_ADMIN_REVIEW_CONTENT(_LOG): id = 152 format = _(u'{addon} {version} admin content-review requested.') short = _(u'Admin content-review requested') keep = True review_queue = True reviewer_review_action = True class REQUEST_ADMIN_REVIEW_THEME(_LOG): id = 153 format = _(u'{addon} {version} admin theme-review requested.') short = _(u'Admin theme-review requested') keep = True review_queue = True reviewer_review_action = True class CREATE_STATICTHEME_FROM_PERSONA(_LOG): id = 154 action_class = 'add' format = _(u'{addon} was migrated from a lightweight theme.') keep = True class ADMIN_API_KEY_RESET(_LOG): id = 155 format = _(u'User {user} api key reset.') admin_event = True LOGS = [x for x in vars().values() if isclass(x) and issubclass(x, _LOG) and x != _LOG] # Make sure there's no duplicate IDs. assert len(LOGS) == len(set(log.id for log in LOGS)) LOG_BY_ID = dict((l.id, l) for l in LOGS) LOG = namedtuple('LogTuple', [l.__name__ for l in LOGS])(*[l for l in LOGS]) LOG_ADMINS = [l.id for l in LOGS if hasattr(l, 'admin_event')] LOG_KEEP = [l.id for l in LOGS if hasattr(l, 'keep')] LOG_RATING_MODERATION = [l.id for l in LOGS if hasattr(l, 'reviewer_event')] LOG_REVIEW_QUEUE = [l.id for l in LOGS if hasattr(l, 'review_queue')] LOG_REVIEWER_REVIEW_ACTION = [ l.id for l in LOGS if hasattr(l, 'reviewer_review_action')] # Is the user emailed the message? LOG_REVIEW_EMAIL_USER = [l.id for l in LOGS if hasattr(l, 'review_email_user')] # Logs *not* to show to the developer. LOG_HIDE_DEVELOPER = [l.id for l in LOGS if (getattr(l, 'hide_developer', False) or l.id in LOG_ADMINS)] # Review Queue logs to show to developer (i.e. hiding admin/private) LOG_REVIEW_QUEUE_DEVELOPER = list(set(LOG_REVIEW_QUEUE) - set(LOG_HIDE_DEVELOPER))
psiinon/addons-server
src/olympia/constants/activity.py
Python
bsd-3-clause
16,067
#!/usr/bin/env python # Unix SMB/CIFS implementation. # Copyright (C) Jelmer Vernooij <[email protected]> 2007-2008 # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # """Samba Python tests.""" import ldb import os import samba from samba.tests import TestCase, TestCaseInTempDir class SubstituteVarTestCase(TestCase): def test_empty(self): self.assertEquals("", samba.substitute_var("", {})) def test_nothing(self): self.assertEquals("foo bar", samba.substitute_var("foo bar", {"bar": "bla"})) def test_replace(self): self.assertEquals("foo bla", samba.substitute_var("foo ${bar}", {"bar": "bla"})) def test_broken(self): self.assertEquals("foo ${bdkjfhsdkfh sdkfh ", samba.substitute_var("foo ${bdkjfhsdkfh sdkfh ", {"bar": "bla"})) def test_unknown_var(self): self.assertEquals("foo ${bla} gsff", samba.substitute_var("foo ${bla} gsff", {"bar": "bla"})) def test_check_all_substituted(self): samba.check_all_substituted("nothing to see here") self.assertRaises(Exception, samba.check_all_substituted, "Not subsituted: ${FOOBAR}") class LdbExtensionTests(TestCaseInTempDir): def test_searchone(self): path = self.tempdir + "/searchone.ldb" l = samba.Ldb(path) try: l.add({"dn": "foo=dc", "bar": "bla"}) self.assertEquals("bla", l.searchone(basedn=ldb.Dn(l, "foo=dc"), attribute="bar")) finally: del l os.unlink(path)
wimberosa/samba
source4/scripting/python/samba/tests/core.py
Python
gpl-3.0
2,175
import array import struct import socket from odict import OrderedDict as OD class NLRI: def __init__(self, afi, safi, val): self.afi = afi self.safi = safi self.val = val def encode(self): return self.val class vpnv4(NLRI): def __init__(self, labels, rd, prefix): self.labels = labels self.rd = rd self.prefix = prefix def __repr__(self): if self.labels: l = ','.join([str(l) for l in self.labels]) else: l = 'none' return '<vpnv4 label %s rd %s prefix %s>' % (l, self.rd, self.prefix) def __str__(self): return '%s:%s' % (self.rd, self.prefix) def __cmp__(self, other): if isinstance(other, vpnv4): return cmp( (self.labels, self.rd, self.prefix), (other.labels, other.rd, other.prefix), ) return -1 def encode(self): plen = 0 v = '' labels = self.labels[:] if not labels: return '\0' labels = [l<<4 for l in labels] labels[-1] |= 1 for l in labels: lo = l & 0xff hi = (l & 0xffff00) >> 8 v += struct.pack('>HB', hi, lo) plen += 24 l, r = self.rd.split(':') if '.' in l: ip = socket.inet_aton(l) rd = struct.pack('!H4sH', 1, ip, int(r)) else: rd = struct.pack('!HHI', 0, int(l), int(r)) v += rd plen += 64 ip, masklen = self.prefix.split('/') ip = socket.inet_aton(ip) masklen = int(masklen) plen += masklen if masklen > 24: v += ip elif masklen > 16: v += ip[:3] elif masklen > 8: v += ip[:2] elif masklen > 0: v += ip[:1] else: pass return struct.pack('B', plen) + v @classmethod def from_bytes(cls, plen, val): if plen==0: # what the hell? return cls([], '0:0', '0.0.0.0/0') idx = 0 # plen is the length, in bits, of all the MPLS labels, plus the 8-byte RD, plus the IP prefix labels = [] while True: ls, = struct.unpack_from('3s', val, idx) idx += 3 plen -= 24 if ls=='\x80\x00\x00': # special null label for vpnv4 withdraws labels = None break label, = struct.unpack_from('!I', '\x00'+ls) bottom = label & 1 labels.append(label >> 4) if bottom: break rdtype, rd = struct.unpack_from('!H6s', val, idx) if rdtype==1: rdip, num = struct.unpack('!4sH', rd) rdip = socket.inet_ntoa(rdip) rd = '%s:%s' % (rdip, num) else: num1, num2 = struct.unpack('!HI', rd) rd = '%s:%s' % (num1, num2) idx += 8 plen -= 64 ipl = pb(plen) ip = val[idx:idx+ipl] idx += ipl prefix = pip(ip, plen) return cls(labels, rd, prefix) class ipv4(NLRI): def __init__(self, prefix): self.prefix = prefix def __cmp__(self, other): if isinstance(other, ipv4): aip, alen = self.prefix.split('/') alen = int(alen) aip = socket.inet_aton(aip) bip, blen = other.prefix.split('/') blen = int(blen) bip = socket.inet_aton(bip) return cmp((aip,alen),(bip,blen)) return -1 def encode(self): plen = 0 v = '' ip, masklen = self.prefix.split('/') ip = socket.inet_aton(ip) masklen = int(masklen) plen += masklen if masklen > 24: v += ip elif masklen > 16: v += ip[:3] elif masklen > 8: v += ip[:2] elif masklen > 0: v += ip[:1] else: pass return struct.pack('B', plen) + v def __repr__(self): return '<ipv4 %s>' % (self.prefix,) def __str__(self): return self.prefix @classmethod def from_bytes(cls, plen, val): return cls(pip(val, plen)) def pb(masklen): if masklen > 24: return 4 elif masklen > 16: return 3 elif masklen > 8: return 2 elif masklen > 0: return 1 return 0 def pip(pi, masklen): pi += '\x00\x00\x00\x00' return '%s/%s' % (socket.inet_ntoa(pi[:4]), masklen) def parse(bytes, afi=1, safi=0): rv = [] if afi==1 and safi==128: klass = vpnv4 else: klass = ipv4 idx = 0 while idx < len(bytes): plen, = struct.unpack_from('B', bytes, idx) idx += 1 nbytes, rest = divmod(plen, 8) if rest: nbytes += 1 val = bytes[idx:idx+nbytes] idx += nbytes rv.append(klass.from_bytes(plen, val)) return rv
plajjan/pybgp
pybgp/nlri.py
Python
mit
5,029
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import proto # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v9.enums", marshal="google.ads.googleads.v9", manifest={"DeviceEnum",}, ) class DeviceEnum(proto.Message): r"""Container for enumeration of Google Ads devices available for targeting. """ class Device(proto.Enum): r"""Enumerates Google Ads devices available for targeting.""" UNSPECIFIED = 0 UNKNOWN = 1 MOBILE = 2 TABLET = 3 DESKTOP = 4 CONNECTED_TV = 6 OTHER = 5 __all__ = tuple(sorted(__protobuf__.manifest))
googleads/google-ads-python
google/ads/googleads/v9/enums/types/device.py
Python
apache-2.0
1,200
# dialog.py -- Tkinter interface to the tk_dialog script. from tkinter import * from tkinter import _cnfmerge if TkVersion <= 3.6: DIALOG_ICON = 'warning' else: DIALOG_ICON = 'questhead' class Dialog(Widget): def __init__(self, master=None, cnf={}, **kw): cnf = _cnfmerge((cnf, kw)) self.widgetName = '__dialog__' Widget._setup(self, master, cnf) self.num = self.tk.getint( self.tk.call( 'tk_dialog', self._w, cnf['title'], cnf['text'], cnf['bitmap'], cnf['default'], *cnf['strings'])) try: Widget.destroy(self) except TclError: pass def destroy(self): pass def _test(): d = Dialog(None, {'title': 'File Modified', 'text': 'File "Python.h" has been modified' ' since the last time it was saved.' ' Do you want to save it before' ' exiting the application.', 'bitmap': DIALOG_ICON, 'default': 0, 'strings': ('Save File', 'Discard Changes', 'Return to Editor')}) print(d.num) if __name__ == '__main__': t = Button(None, {'text': 'Test', 'command': _test, Pack: {}}) q = Button(None, {'text': 'Quit', 'command': t.quit, Pack: {}}) t.mainloop()
Microvellum/Fluid-Designer
win64-vc/2.78/python/lib/tkinter/dialog.py
Python
gpl-3.0
1,568
from model.contact import Contact from model.group import Group from fixture.orm import ORMFixture import random def test_del_contact_from_group(app): orm = ORMFixture(host="127.0.0.1", name="addressbook", user="root", password="") # check for existing any group if len(orm.get_group_list()) == 0: app.group.create(Group(name="test")) group = random.choice(orm.get_group_list()) # choose random group from list if len(orm.get_contacts_in_group(Group(id=group.id))) == 0: if len(orm.get_contacts_not_in_group(Group(id=group.id))) == 0: app.contact.create(Contact(firstname="Ivan")) contact_not_in_group = random.choice(orm.get_contacts_not_in_group(Group(id=group.id))) app.contact.add_contact_to_group_by_id(contact_not_in_group.id, group.id) old_contacts_in_group = orm.get_contacts_in_group(Group(id=group.id)) contact_in_group = random.choice(old_contacts_in_group) # choose random contact from list app.contact.delete_contact_from_group_by_id(contact_in_group.id, group.id) new_contacts_in_group = orm.get_contacts_in_group(Group(id=group.id)) old_contacts_in_group.remove(contact_in_group) assert sorted(old_contacts_in_group, key=Contact.id_or_max) == sorted(new_contacts_in_group, key=Contact.id_or_max)
Lana-Pa/Python-training
test/test_delete_contact_from_group.py
Python
apache-2.0
1,311
README.md exists but content is empty.
Downloads last month
66