prompt
listlengths
1
1
compression_prompt
listlengths
1
1
target
stringlengths
1.03k
828k
[ { "content": "Return the code unaltered:\n```python\nimport unittest\nfrom feemodel.txmempool import MemBlock\nfrom feemodel.tests.pseudoproxy import proxy\nfrom feemodel.tests.config import test_memblock_dbfile as dbfile\n\nAVAILABLE_HEIGHTS = range(333931, 333954) + [334655, 334656]\n\n\nclass PseudoProxyTest...
[ { "content": "Return the code unaltered:\n<|memory_start|>```python\nimport unittest\nfrom feemodel.txmempool import MemBlock\nfrom feemodel.tests.pseudoproxy import proxy\nfrom feemodel.tests.config import test_memblock_dbfile as dbfile\n\nAVAILABLE_HEIGHTS = range(333931, 333954) + [334655, 334656]\n\n\nclass...
```python import unittest from feemodel.txmempool import MemBlock from feemodel.tests.pseudoproxy import proxy from feemodel.tests.config import test_memblock_dbfile as dbfile AVAILABLE_HEIGHTS = range(333931, 333954) + [334655, 334656] class PseudoProxyTests(unittest.TestCase): def test_A(self): # Just test that no KeyError is raised: we have the blocks # in AVAILABLE_HEIGHTS for height in AVAILABLE_HEIGHTS: blockhash = proxy.getblockhash(height) block = proxy.getblock(blockhash) self.assertTrue(block) def test_B(self): # Test the setting of rawmempool proxy.set_rawmempool(333931) rawmempool = proxy.getrawmempool() b = MemBlock.read(333931, dbfile=dbfile) self.assertEqual(set(b.entries), set(rawmempool)) for txid, rawentry in rawmempool.items(): for key, val in rawentry.items(): self.assertEqual(val, getattr(b.entries[txid], key)) if __name__ == "__main__": unittest.main() ```
[ { "content": "Repeat the code precisely as written (spacing intact):\n```python\n# Copyright (c) 2017, The MITRE Corporation. All rights reserved.\n# See LICENSE.txt for complete terms.\n\n# mixbox\nfrom mixbox import fields\n\n# cybox\nfrom cybox.core import Observables\n\n# internal\nimport stix\nfrom stix.co...
[ { "content": "Repeat the code precisely as written (spacing intact):\n<|memory_start|>```python\n# Copyright (c) 2017, The MITRE Corporation. All rights reserved.\n# See LICENSE.txt for complete terms.\n\n# mixbox\nfrom mixbox import fields\n\n# cybox\nfrom cybox.core import Observables\n\n# internal\nimport st...
```python # Copyright (c) 2017, The MITRE Corporation. All rights reserved. # See LICENSE.txt for complete terms. # mixbox from mixbox import fields # cybox from cybox.core import Observables # internal import stix from stix.common import StructuredTextList, VocabString from stix.common.vocabs import AttackerInfrastructureType import stix.bindings.ttp as ttp_binding from mixbox import fields, entities class Infrastructure(stix.Entity): _binding = ttp_binding _binding_class = _binding.InfrastructureType _namespace = "http://stix.mitre.org/TTP-1" id_ = fields.IdField("id") idref = fields.IdrefField("idref") title = fields.TypedField("Title") descriptions = fields.TypedField("Description", StructuredTextList) short_descriptions = fields.TypedField("Short_Description", StructuredTextList) types = fields.TypedField("Type", VocabString, multiple=True, key_name="types") observable_characterization = fields.TypedField("Observable_Characterization", Observables) def __init__(self, id_=None, idref=None, title=None, description=None, short_description=None): super(Infrastructure, self).__init__() self.id_ = id_ self.idref = idref self.title = title self.description = StructuredTextList(description) self.short_description = StructuredTextList(short_description) @property def description(self): """A single description about the contents or purpose of this object. Default Value: ``None`` Note: If this object has more than one description set, this will return the description with the lowest ordinality value. Returns: An instance of :class:`.StructuredText` """ if self.descriptions is None: self.descriptions = StructuredTextList() return next(iter(self.descriptions), None) @description.setter def description(self, value): self.descriptions = StructuredTextList(value) def add_description(self, description): """Adds a description to the ``descriptions`` collection. This is the same as calling "foo.descriptions.add(bar)". """ self.descriptions.add(description) @property def short_description(self): """A single short description about the contents or purpose of this object. Default Value: ``None`` Note: If this object has more than one short description set, this will return the description with the lowest ordinality value. Returns: An instance of :class:`.StructuredText` """ if self.short_descriptions is None: self.short_descriptions = StructuredTextList() return next(iter(self.short_descriptions), None) @short_description.setter def short_description(self, value): self.short_descriptions = value def add_short_description(self, description): """Adds a description to the ``short_descriptions`` collection. This is the same as calling "foo.short_descriptions.add(bar)". """ self.short_descriptions.add(description) def add_type(self, type_): self.types.append(type_) class InfraStructureTypes(stix.EntityList): _namespace = "http://stix.mitre.org/TTP-1" _contained_type = VocabString @classmethod def _dict_as_list(cls): return True def _fix_value(self, value): return AttackerInfrastructureType(value) ```
[ { "content": "```python\n#!/usr/bin/env python\n\"\"\"Determine single-source or multiple-source reachability in a digraph\"\"\"\n#pylint: disable=invalid-name\n\nimport sys\nfrom os.path import join\nfrom AlgsSedgewickWayne.Digraph import Digraph\nfrom AlgsSedgewickWayne.DirectedDFS import DirectedDFS\nfrom Al...
[ { "content": "<|memory_start|>```python\n#!/usr/bin/env python\n\"\"\"Determine single-source or multiple-source reachability in a digraph\"\"\"\n#pylint: disable=invalid-name\n\nimport sys\nfrom os.path import join\nfrom AlgsSedgewickWayne.Digraph import Digraph\nfrom AlgsSedgewickWayne.DirectedDFS import Dire...
```python #!/usr/bin/env python """Determine single-source or multiple-source reachability in a digraph""" #pylint: disable=invalid-name import sys from os.path import join from AlgsSedgewickWayne.Digraph import Digraph from AlgsSedgewickWayne.DirectedDFS import DirectedDFS from AlgsSedgewickWayne.testcode.InputArgs import cli_get_fin from tests.utils import DIR_TEST def test_main(digraph, *sources): """Determine single-source or multiple-source reachability in a digraph using depth first search. Runs in O(E + V) time. >>> test_main("tinyDG.txt", 1) [1] >>> test_main("tinyDG.txt", 2) [0, 1, 2, 3, 4, 5] >>> test_main("tinyDG.txt", 1, 2, 6) [0, 1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 12] """ if isinstance(digraph, str): digraph_fin = join(DIR_TEST, digraph) digraph_arr = cli_get_fin(digraph_fin) grph = Digraph(digraph_arr) dfs = DirectedDFS(grph, sources) # multiple-source reachability return [v for v in grph.keys if dfs.marked(v)] def cli(prt=sys.stdout): """Command-line interface""" if len(sys.argv) == 1: import doctest doctest.testmod() else: # read in digraph from command-line argument digraph_array = cli_get_fin(sys.argv[1]) # read in sources from command-line arguments sources = [int(s) for s in sys.argv[2:]] # print out vertices reachable from sources # reachable = test_main(digraph_array, *sources) reachable = test_main(digraph_array, *sources) prt.write("{}\n".format(' '.join(str(r) for r in reachable))) #**************************************************************************** if __name__ == "__main__": cli() # Copyright 2002-2016, Robert Sedgewick and Kevin Wayne. # Copyright 2015-2019, DV Klopfenstein, Python implementation. ```
[ { "content": "Replicate the code snippet exactly, without paraphrasing or reformatting:\n```python\nimport json\nfrom django.http import HttpResponse\n\n\nclass AjaxableResponseMixin(object):\n \"\"\"\n Mixin to add AJAX support to a form.\n Must be used with an object-based FormView (e.g. CreateView)\...
[ { "content": "Replicate the code snippet exactly, without paraphrasing or reformatting:\n<|memory_start|>```python\nimport json\nfrom django.http import HttpResponse\n\n\nclass AjaxableResponseMixin(object):\n \"\"\"\n Mixin to add AJAX support to a form.\n Must be used with an object-based FormView (e...
```python import json from django.http import HttpResponse class AjaxableResponseMixin(object): """ Mixin to add AJAX support to a form. Must be used with an object-based FormView (e.g. CreateView) """ def render_to_json_response(self, context, **response_kwargs): data = json.dumps(context) response_kwargs['content_type'] = 'application/json' return HttpResponse(data, **response_kwargs) def form_invalid(self, form): response = super(AjaxableResponseMixin, self).form_invalid(form) if self.request.is_ajax(): return self.render_to_json_response(form.errors, status=400) else: return response def form_valid(self, form): # We make sure to call the parent's form_valid() method because # it might do some processing (in the case of CreateView, it will # call form.save() for example). response = super(AjaxableResponseMixin, self).form_valid(form) if self.request.is_ajax(): data = { 'pk': self.object.pk, } return self.render_to_json_response(data) else: return response ```
[ { "content": "Output the full code verbatim (no extra comments):\n```python\nimport numpy as np\nimport pytest\nfrom rig.type_casts import (\n float_to_fix, fix_to_float,\n float_to_fp, fp_to_float,\n NumpyFloatToFixConverter, NumpyFixToFloatConverter\n)\nimport struct\n\nsz = {\n 8: 'b',\n 16: '...
[ { "content": "Output the full code verbatim (no extra comments):\n<|memory_start|>```python\nimport numpy as np\nimport pytest\nfrom rig.type_casts import (\n float_to_fix, fix_to_float,\n float_to_fp, fp_to_float,\n NumpyFloatToFixConverter, NumpyFixToFloatConverter\n)\nimport struct\n\nsz = {\n 8:...
```python import numpy as np import pytest from rig.type_casts import ( float_to_fix, fix_to_float, float_to_fp, fp_to_float, NumpyFloatToFixConverter, NumpyFixToFloatConverter ) import struct sz = { 8: 'b', 16: 'h', 32: 'i', } SZ = {k: v.upper() for k, v in sz.items()} class TestFloatToFix(object): """Test converting from a float to a fixed point. """ @pytest.mark.parametrize( "signed, n_bits, n_frac", [(True, 32, 32), # Too many frac bits (False, 32, 33), (False, -1, 3), (False, 32, -1), # Negative ]) def test_invalid_parameters(self, signed, n_bits, n_frac): with pytest.raises(ValueError): float_to_fix(signed, n_bits, n_frac) @pytest.mark.parametrize( "value, n_bits, n_frac, output", [(0.50, 8, 4, 0x08), (0.50, 8, 5, 0x10), (0.50, 8, 6, 0x20), (0.50, 8, 7, 0x40), (0.50, 8, 8, 0x80), (0.25, 8, 4, 0x04), (0.75, 8, 4, 0x0c), (1.75, 8, 4, 0x1c), (-1.75, 8, 4, 0x00), # Clipped ]) def test_no_saturate_unsigned(self, value, n_bits, n_frac, output): assert float_to_fix(False, n_bits, n_frac)(value) == output assert float_to_fp(False, n_bits, n_frac)(value) == output @pytest.mark.parametrize( "v, n_bits, n_frac, output", [(0.50, 8, 4, 0x08), (0.50, 8, 5, 0x10), (0.50, 8, 6, 0x20), (0.50, 8, 7, 0x40), (0.25, 8, 4, 0x04), (0.75, 8, 4, 0x0c), (-.50, 8, 4, 0xf8), (-.50, 8, 5, 0xf0), (-.50, 8, 6, 0xe0), (-.50, 8, 7, 0xc0), (-.25, 8, 4, 0xfc), (-.75, 8, 4, 0xf4), (-.25, 8, 1, 0x00), (1.75, 8, 4, 0x1c), (-1.75, 8, 4, 0xe4), (-2.75, 8, 4, 0xd4), (-1.0, 8, 4, 0xf0), (-7.9375, 8, 4, 0x81), (-8, 8, 4, 0x80), (-16, 8, 4, 0x80), (-1.0, 8, 3, 0xf8), (-1.0, 8, 2, 0xfc), (-1.0, 8, 1, 0xfe), (-1.0, 16, 1, 0xfffe), (-1.0, 16, 2, 0xfffc), ]) def test_no_saturate_signed(self, v, n_bits, n_frac, output): assert float_to_fix(True, n_bits, n_frac)(v) == output assert ( struct.pack(sz[n_bits], float_to_fp(True, n_bits, n_frac)(v)) == struct.pack(SZ[n_bits], output) ) @pytest.mark.parametrize( "value, n_bits, n_frac, output", [(2**4, 8, 4, 0xff), # Saturate (2**4 - 1 + sum(2**-n for n in range(1, 6)), 8, 4, 0xff), # Saturate ]) def test_saturate_unsigned(self, value, n_bits, n_frac, output): assert float_to_fix(False, n_bits, n_frac)(value) == output assert float_to_fp(False, n_bits, n_frac)(value) == output class TestFloatToFp(object): @pytest.mark.parametrize( "signed, n_bits, n_frac, value, output", ((True, 8, -2, 0.25, 0x0), (True, 8, -2, 4, 0x1), (True, 8, -2, -4, -0x1), (False, 8, -2, -4, 0x0), ) ) def test_negative_nfrac(self, signed, n_bits, n_frac, value, output): assert float_to_fp(signed, n_bits, n_frac)(value) == output @pytest.mark.parametrize( "signed, n_bits, n_frac, value, output", ((True, 8, 8, -0.5, -0x80), (False, 8, 8, 0.5, 0x80), (False, 8, 9, 0.5, 0xff), (False, 8, 9, 0.25, 0x80), ) ) def test_large_nfrac(self, signed, n_bits, n_frac, value, output): assert float_to_fp(signed, n_bits, n_frac)(value) == output class TestFixToFloat(object): @pytest.mark.parametrize( "signed, n_bits, n_frac", [(True, 32, 32), # Too many frac bits (False, 32, 33), (False, -1, 3), (False, 32, -1), # Negative ]) def test_invalid_parameters(self, signed, n_bits, n_frac): with pytest.raises(ValueError): fix_to_float(signed, n_bits, n_frac) @pytest.mark.parametrize( "bits, signed, n_bits, n_frac, value", [(0xff, False, 8, 0, 255.0), (0x81, True, 8, 0, -127.0), (0xff, False, 8, 1, 127.5), (0xf8, True, 8, 4, -0.5) ]) def test_fix_to_float(self, bits, signed, n_bits, n_frac, value): assert value == fix_to_float(signed, n_bits, n_frac)(bits) @pytest.mark.parametrize( "bits, n_frac, value", [(0xff, 0, 255.0), (-0x7f, 0, -127.0), (0xff, 1, 127.5), (-0x08, 4, -0.5) ]) def test_fp_to_float(bits, n_frac, value): assert value == fp_to_float(n_frac)(bits) class TestNumpyFloatToFixConverter(object): def test_init_fails(self): with pytest.raises(ValueError): NumpyFloatToFixConverter(False, 31, 0) @pytest.mark.parametrize( "signed, n_bits, dtype, n_bytes", [(False, 8, np.uint8, 1), (True, 8, np.int8, 1), (False, 16, np.uint16, 2), (True, 16, np.int16, 2), (False, 32, np.uint32, 4), (True, 32, np.int32, 4), (False, 64, np.uint64, 8), (True, 64, np.int64, 8), ]) def test_dtypes(self, signed, n_bits, dtype, n_bytes): """Check that the correcy dtype is returned.""" fpf = NumpyFloatToFixConverter(signed, n_bits, 0) assert fpf.dtype == dtype assert fpf.bytes_per_element == n_bytes @pytest.mark.parametrize( "n_bits, n_frac, values, dtype", [(8, 4, [0.5, 0.25, 0.125, 0.0625], np.uint8), (8, 3, [0.5, 0.25, 0.125, 0.0625], np.uint8), (8, 2, [0.5, 0.25, 0.125, 0.0625], np.uint8), (8, 1, [0.5, 0.25, 0.125, 0.0625], np.uint8), (8, 0, [0.5, 0.25, 0.125, 0.0625], np.uint8), (8, 8, [0.5, 0.25, 0.125, 0.0625], np.uint8), (8, 9, [0.5, 0.25, 0.125, 0.0625], np.uint8), (16, 12, [0.5, 0.25, 0.125, 0.0625], np.uint16), (32, 15, [0.5, 0.25, 0.125, 0.0625], np.uint32), ]) def test_unsigned_no_saturate(self, n_bits, n_frac, values, dtype): # Create the formatter then call it on the array fpf = NumpyFloatToFixConverter(False, n_bits, n_frac) vals = fpf(np.array(values)) # Check the values are correct ftf = float_to_fp(False, n_bits, n_frac) assert np.all(vals == np.array([ftf(v) for v in values])) assert vals.dtype == dtype @pytest.mark.parametrize( "n_bits, n_frac, values, dtype", [(8, 4, [0.5, 0.25, 0.125, 0.0625, -0.5], np.int8), (8, 3, [0.5, 0.25, 0.125, 0.0625, -0.25], np.int8), (8, 2, [0.5, 0.25, 0.125, 0.0625, -0.33], np.int8), (8, 1, [0.5, 0.25, 0.125, 0.0625, -0.25], np.int8), (8, 0, [0.5, 0.25, 0.125, 0.0625, -0.23], np.int8), (8, 9, [0.5, 0.25, 0.125, 0.0625, -0.23], np.int8), (16, 12, [0.5, 0.25, 0.125, 0.0625, -0.45], np.int16), (32, 15, [0.5, 0.25, 0.125, 0.0625, -0.77], np.int32), ]) def test_signed_no_saturate(self, n_bits, n_frac, values, dtype): # Create the formatter then call it on the array fpf = NumpyFloatToFixConverter(True, n_bits, n_frac) vals = fpf(np.array(values)) # Check the values are correct ftf = float_to_fp(True, n_bits, n_frac) assert np.all(vals == np.array([ftf(v) for v in values])) assert vals.dtype == dtype @pytest.mark.parametrize("signed", [True, False]) @pytest.mark.parametrize( "n_bits, n_frac", [(8, 0), (8, 4), (16, 5), (32, 27)]) def test_saturate(self, signed, n_bits, n_frac): # Build the values values = [2.0**(n_bits - n_frac - (1 if signed else 0)), 2.0**(n_bits - n_frac - (1 if signed else 0)) - 1] # Format fpf = NumpyFloatToFixConverter(signed, n_bits, n_frac) vals = fpf(np.array(values)) c = {8: 'B', 16: 'H', 32: 'I'}[n_bits] # Check the values are correct ftf = float_to_fix(signed, n_bits, n_frac) assert ( # pragma: no branch bytes(vals.data) == struct.pack("{}{}".format(len(values), c), *[ftf(v) for v in values]) ) class TestNumpyFixToFloat(object): @pytest.mark.parametrize( "values, dtype, n_frac, expected_values", [([0xff], np.uint8, 4, np.array([15.9375])), ([0xf8], np.int8, 4, np.array([-.5])), ] ) def test_standard(self, values, dtype, n_frac, expected_values): input_array = np.array(values, dtype=dtype) fpf = NumpyFixToFloatConverter(n_frac) output_array = fpf(input_array) assert np.all(output_array == expected_values) ```
[ { "content": "Replicate the source code:\n```python\nfrom pygments.lexer import RegexLexer, bygroups, include\nfrom pygments.token import *\n\nclass BlogLexer(RegexLexer):\n name = 'BLOG'\n aliases = ['blog']\n filenames = ['*.blog', '*.dblog']\n operators = ['\\\\-\\\\>', ':', '\\\\+', '\\\\-', '\\\\*', '/...
[ { "content": "Replicate the source code:\n<|memory_start|>```python\nfrom pygments.lexer import RegexLexer, bygroups, include\nfrom pygments.token import *\n\nclass BlogLexer(RegexLexer):\n name = 'BLOG'\n aliases = ['blog']\n filenames = ['*.blog', '*.dblog']\n operators = ['\\\\-\\\\>', ':', '\\\\+', '\\\...
```python from pygments.lexer import RegexLexer, bygroups, include from pygments.token import * class BlogLexer(RegexLexer): name = 'BLOG' aliases = ['blog'] filenames = ['*.blog', '*.dblog'] operators = ['\\-\\>', ':', '\\+', '\\-', '\\*', '/', '\\[', ']', '\\{', '}', '!', '\\<', '\\>', '\\<=', '\\>=', '==', '!=', '&', '\\|', '=\\>', '#', '\\^', '%', '@'] wordops = ['isEmptyString', 'succ', 'pred', 'prev', 'inv', 'det', 'min', 'max', 'round', 'transpose', 'sin', 'cos', 'tan', 'atan2', 'sum', 'vstack', 'eye', 'zeros', 'ones', 'toInt', 'toReal', 'diag', 'repmat', 'hstack', 'vstack', 'pi', 'trace'] deliminators = [',', ';', '\\(', '\\)', '=', '~'] keywords = ['extern','import','fixed','distinct','random','origin', 'param','type', 'forall', 'exists', 'obs', 'query', 'if', 'then', 'else', 'for', 'case', 'in'] types = ['Integer','Real','Boolean','NaturalNum','List','Map', 'Timestep','RealMatrix','IntegerMatrix'] distribs = ['TabularCPD', 'Distribution','Gaussian', 'UniformChoice', 'MultivarGaussian', 'Poisson', 'Bernoulli', 'BooleanDistrib', 'Binomial', 'Beta', 'BoundedGenometric', 'Categorical', 'Dirichlet', 'EqualsCPD', 'Gamma', 'Geometric', 'Iota', 'LinearGaussian', 'MixtureDistrib', 'Multinomial', 'NegativeBinamial', 'RoundedLogNormal', 'TabularInterp', 'UniformVector', 'UnivarGaussian', 'Exponential', 'UniformInt', 'UniformReal'] idname_reg = '[a-zA-Z_]\\w*' def gen_regex(ops): return "|".join(ops) tokens = { 'root' : [ (r'//.*?\n', Comment.Single), (r'(?s)/\*.*?\*/', Comment.Multiline), ('('+idname_reg+')(\\()', bygroups(Name.Function, Punctuation)), ('('+gen_regex(types)+')\\b', Keyword.Type), ('('+gen_regex(distribs)+')\\b', Name.Class), ('('+gen_regex(keywords)+')\\b', Keyword), (gen_regex(operators), Operator), ('(' + gen_regex(wordops) +')\\b', Operator.Word), ('(true|false|null)\\b', Keyword.Constant), ('('+idname_reg+')\\b', Name), (r'"(\\\\|\\"|[^"])*"', String), (gen_regex(deliminators), Punctuation), (r'\d*\.\d+', Number.Float), (r'\d+', Number.Integer), (r'\s+', Text), ] } def run_tests(): tests = [ "type Person;", "distinct Person Alice, Bob, P[100];", "random Real x1_x2x3 ~ Gaussian(0, 1);\nrandom Real y ~ Gaussian(x, 1);", "random type0 funcname(type1 x) =expression;\nrandom type0 funcname(type1 x) dependency-expression;", "random NaturalNum x ~ Poisson(a);", "param Real a: 0 < a & a < 10 ;" "random Real funcname(type1 x);", "1.0 + 2.0 * 3.0 - 4.0", "Twice( 10.0 ) * 5.5", "fixed NaturalNum[] c = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];", "fixed NaturalNum[][] table = [1, 2, 3; 4, 5, 6];", "fixed List<NaturalNum> a = List(1, 2, 3, 4, 5, 6);", "fixed Map<Boolean, Real> map1 = {true -> 0.3, false -> 0.7};", "Categorical<Boolean> cpd1 =Categorical({true -> 0.3, false -> 0.7});", "List", "/*abc */", """ /* Evidence for the Hidden Markov Model. */ """ ] lexer = BlogLexer() for test in tests: print(test) for token in (lexer.get_tokens(test)): print(token) if __name__ == '__main__': run_tests() ```
[ { "content": "Replicate the source code:\n```python\n# Copyright (c) 2007 The Hewlett-Packard Development Company\n# All rights reserved.\n#\n# The license below extends only to copyright in the software and shall\n# not be construed as granting a license to any other intellectual\n# property including but not ...
[ { "content": "Replicate the source code:\n<|memory_start|>```python\n# Copyright (c) 2007 The Hewlett-Packard Development Company\n# All rights reserved.\n#\n# The license below extends only to copyright in the software and shall\n# not be construed as granting a license to any other intellectual\n# property in...
```python # Copyright (c) 2007 The Hewlett-Packard Development Company # All rights reserved. # # The license below extends only to copyright in the software and shall # not be construed as granting a license to any other intellectual # property including but not limited to intellectual property relating # to a hardware implementation of the functionality of the software # licensed hereunder. You may use the software subject to the license # terms below provided that you ensure that this notice is replicated # unmodified and in its entirety in all distributions of the software, # modified or unmodified, in source code or in binary form. # # 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 holders 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. # # Authors: Gabe Black microcode = ''' def macroop FPREM { premfp st(0), st(1), st(0) }; def macroop FPREM1 { premfp st(0), st(1), st(0) }; ''' ```
[ { "content": "Replicate the source code:\n```python\n\"\"\"This module contains all functionality on the level of a single audio file.\n\"\"\"\n\nfrom __future__ import print_function\nfrom audiorename.meta import Meta, dict_diff\nfrom phrydy.utils import as_string\nfrom tmep import Functions\nfrom tmep import ...
[ { "content": "Replicate the source code:\n<|memory_start|>```python\n\"\"\"This module contains all functionality on the level of a single audio file.\n\"\"\"\n\nfrom __future__ import print_function\nfrom audiorename.meta import Meta, dict_diff\nfrom phrydy.utils import as_string\nfrom tmep import Functions\nf...
```python """This module contains all functionality on the level of a single audio file. """ from __future__ import print_function from audiorename.meta import Meta, dict_diff from phrydy.utils import as_string from tmep import Functions from tmep import Template import errno import os import phrydy import re import shutil class AudioFile(object): """ :param path: The path string of the audio file. :param string file_type: Either “source” or “target”. :param string prefix: The path prefix of the audio file, for example the base folder of your music collection. Used to shorten the path strings in the progress messaging. :param job: The `job` object. :type job: audiorename.job.Job """ def __init__(self, path=None, file_type='source', prefix=None, job=None): self.__path = path self.type = file_type self.job = job self.__prefix = prefix self.shorten_symbol = '[…]' if not self.job: shell_friendly = True else: shell_friendly = self.job.shell_friendly if self.exists: try: self.meta = Meta(self.abspath, shell_friendly) except phrydy.mediafile.UnreadableFileError: self.meta = False @property def abspath(self): return os.path.abspath(self.__path) @property def prefix(self): if self.__prefix and len(self.__prefix) > 1: if self.__prefix[-1] != os.path.sep: return self.__prefix + os.path.sep else: return self.__prefix @property def exists(self): return os.path.exists(self.abspath) @property def extension(self): return self.abspath.split('.')[-1].lower() @property def short(self): if self.prefix: short = self.abspath.replace(self.prefix, '') else: short = os.path.basename(self.abspath) return self.shorten_symbol + short @property def filename(self): return os.path.basename(self.abspath) @property def dir_and_file(self): path_segments = self.abspath.split(os.path.sep) return os.path.sep.join(path_segments[-2:]) class MBTrackListing(object): def __init__(self): self.counter = 0 def format_audiofile(self, album, title, length): self.counter += 1 m, s = divmod(length, 60) mmss = '{:d}:{:02d}'.format(int(m), int(s)) output = '{:d}. {:s}: {:s} ({:s})'.format(self.counter, album, title, mmss) output = output.replace('Op.', 'op.') return output.replace('- ', '') mb_track_listing = MBTrackListing() def get_target(target, extensions): """Get the path of a existing audio file target. Search for audio files with different extensions. """ target = os.path.splitext(target)[0] for extension in extensions: audio_file = target + '.' + extension if os.path.exists(audio_file): return audio_file def best_format(source, target, job): """ :param source: The metadata object of the source file. :type source: audiorename.meta.Meta :param target: The metadata object of the target file. :type target: audiorename.meta.Meta :return: Either the string `source` or the string `target` :param job: The `job` object. :type job: audiorename.job.Job :rtype: string """ def get_highest(dictionary): for key, value in sorted(dictionary.items()): out = value return out if source.format == target.format: bitrates = {} bitrates[source.bitrate] = 'source' bitrates[target.bitrate] = 'target' best = get_highest(bitrates) job.msg.best_format(best, 'bitrate', source, target) return best else: # All types: # # 'aac' # 'aiff' # 'alac': Apple Lossless Audio Codec (losless) # 'ape' # 'asf' # 'dsf' # 'flac' # 'mp3' # 'mpc' # 'ogg' # 'opus' # 'wv': WavPack (losless) ranking = { 'flac': 10, 'alac': 9, 'aac': 8, 'mp3': 5, 'ogg': 2, 'wma': 1, } types = {} types[ranking[source.type]] = 'source' types[ranking[target.type]] = 'target' best = get_highest(types) job.msg.best_format(best, 'type', source, target) return best def process_target_path(meta, format_string, shell_friendly=True): """ :param dict meta: The to a dictionary converted attributes of a meta object :class:`audiorename.meta.Meta`. :param string format_string: :param boolean shell_friendly: """ template = Template(as_string(format_string)) functions = Functions(meta) target = template.substitute(meta, functions.functions()) if isinstance(target, str): if shell_friendly: target = Functions.tmpl_asciify(target) target = Functions.tmpl_delchars(target, '().,!"\'’') target = Functions.tmpl_replchars(target, '-', ' ') # asciify generates new characters which must be sanitzed, e. g.: # ¿ -> ? target = Functions.tmpl_delchars(target, ':*?"<>|\\~&{}') target = Functions.tmpl_deldupchars(target) return re.sub(r'\.$', '', target) class Action(object): """ :param job: The `job` object. :type job: audiorename.job.Job """ def __init__(self, job): self.job = job self.dry_run = job.dry_run def count(self, counter_name): self.job.stats.counter.count(counter_name) def cleanup(self, audio_file): if self.job.rename.cleanup == 'backup': self.backup(audio_file) elif self.job.rename.cleanup == 'delete': self.delete(audio_file) def backup(self, audio_file): backup_file = AudioFile( os.path.join( self.job.rename.backup_folder, os.path.basename(audio_file.abspath) ), file_type='target' ) self.job.msg.action_two_path('Backup', audio_file, backup_file) self.count('backup') if not self.dry_run: self.create_dir(backup_file) shutil.move(audio_file.abspath, backup_file.abspath) def copy(self, source, target): self.job.msg.action_two_path('Copy', source, target) self.count('copy') if not self.dry_run: self.create_dir(target) shutil.copy2(source.abspath, target.abspath) def create_dir(self, audio_file): path = os.path.dirname(audio_file.abspath) try: os.makedirs(path) except OSError as exception: if exception.errno != errno.EEXIST: raise def delete(self, audio_file): self.job.msg.action_one_path('Delete', audio_file) self.count('delete') if not self.dry_run: os.remove(audio_file.abspath) def move(self, source, target): self.job.msg.action_two_path('Move', source, target) self.count('move') if not self.dry_run: self.create_dir(target) shutil.move(source.abspath, target.abspath) def metadata(self, audio_file, enrich=False, remap=False): pre = audio_file.meta.export_dict(sanitize=False) def single_action(audio_file, method_name, message): pre = audio_file.meta.export_dict(sanitize=False) method = getattr(audio_file.meta, method_name) method() post = audio_file.meta.export_dict(sanitize=False) diff = dict_diff(pre, post) if diff: self.count(method_name) self.job.msg.output(message) for change in diff: self.job.msg.diff(change[0], change[1], change[2]) if enrich: single_action(audio_file, 'enrich_metadata', 'Enrich metadata') if remap: single_action(audio_file, 'remap_classical', 'Remap classical') post = audio_file.meta.export_dict(sanitize=False) diff = dict_diff(pre, post) if not self.dry_run and diff: audio_file.meta.save() def do_job_on_audiofile(source, job=None): """ :param job: The `job` object. :type job: audiorename.job.Job """ def count(key): job.stats.counter.count(key) skip = False action = Action(job) source = AudioFile(source, prefix=os.getcwd(), file_type='source', job=job) if not job.output.mb_track_listing: job.msg.next_file(source) if not source.meta: skip = True ## # Skips ## if skip: job.msg.status(u'Broken file', status='error') count('broken_file') return ## # Output only ## if job.output.mb_track_listing: print(mb_track_listing.format_audiofile(source.meta.album, source.meta.title, source.meta.length)) return if job.output.debug: phrydy.doc.print_debug( source.abspath, Meta, Meta.fields, job.output.color, ) return if job.field_skip and (not hasattr(source.meta, job.field_skip) or not getattr(source.meta, job.field_skip)): job.msg.status(u'No field', status='error') count('no_field') return ## # Metadata actions ## if job.metadata_actions.remap_classical or \ job.metadata_actions.enrich_metadata: action.metadata( source, job.metadata_actions.enrich_metadata, job.metadata_actions.remap_classical ) ## # Rename action ## if job.rename.move != 'no_rename': if source.meta.ar_combined_soundtrack: format_string = job.format.soundtrack elif source.meta.comp: format_string = job.format.compilation else: format_string = job.format.default meta_dict = source.meta.export_dict() desired_target_path = process_target_path(meta_dict, format_string, job.shell_friendly) desired_target_path = os.path.join( job.target, desired_target_path + '.' + source.extension ) desired_target = AudioFile(desired_target_path, prefix=job.target, file_type='target', job=job) # Do nothing if source.abspath == desired_target.abspath: job.msg.status('Renamed', status='ok') count('renamed') return # Search existing target target = False target_path = get_target(desired_target.abspath, job.filter.extension) if target_path: target = AudioFile(target_path, prefix=job.target, file_type='target', job=job) # Both file exist if target: best = best_format(source.meta, target.meta, job) if job.rename.cleanup: # delete source if not job.rename.best_format or \ (job.rename.best_format and best == 'target'): action.cleanup(source) # delete target if job.rename.best_format and best == 'source': action.cleanup(target) # Unset target object to trigger copy or move actions. target = None if target: job.msg.status('Exists', status='error') # copy elif job.rename.move == 'copy': action.copy(source, desired_target) # move elif job.rename.move == 'move': action.move(source, desired_target) ```
[ { "content": "Repeat the code precisely as written (spacing intact):\n```python\nimport sqlite3\nimport urllib\nimport re\nfrom urllib.request import urlopen\nfrom bs4 import BeautifulSoup\n\n\ndef main():\n # The collection URL below.\n collURL = 'http://www.thelatinlibrary.com/germanicus.html'\n coll...
[ { "content": "Repeat the code precisely as written (spacing intact):\n<|memory_start|>```python\nimport sqlite3\nimport urllib\nimport re\nfrom urllib.request import urlopen\nfrom bs4 import BeautifulSoup\n\n\ndef main():\n # The collection URL below.\n collURL = 'http://www.thelatinlibrary.com/germanicus...
```python import sqlite3 import urllib import re from urllib.request import urlopen from bs4 import BeautifulSoup def main(): # The collection URL below. collURL = 'http://www.thelatinlibrary.com/germanicus.html' collOpen = urllib.request.urlopen(collURL) collSOUP = BeautifulSoup(collOpen, 'html5lib') author = collSOUP.title.string.split(":")[0].strip() colltitle = collSOUP.p.string.split(":")[0].strip() date = "no date found" textsURL = [collURL] with sqlite3.connect('texts.db') as db: c = db.cursor() c.execute( 'CREATE TABLE IF NOT EXISTS texts (id INTEGER PRIMARY KEY, title TEXT, book TEXT,' ' language TEXT, author TEXT, date TEXT, chapter TEXT, verse TEXT, passage TEXT,' ' link TEXT, documentType TEXT)') c.execute("DELETE FROM texts WHERE author = 'Germanicus'") for url in textsURL: chapter = "-1" verse = 0 title = collSOUP.title.string.split(":")[1].strip() openurl = urllib.request.urlopen(url) textsoup = BeautifulSoup(openurl, 'html5lib') getp = textsoup.find_all('p') for p in getp: # make sure it's not a paragraph without the main text try: if p['class'][0].lower() in ['border', 'pagehead', 'shortborder', 'smallboarder', 'margin', 'internal_navigation']: # these are not part of the main t continue except: pass txtstr = p.get_text().strip() if txtstr.startswith("The"): continue brtags = p.findAll('br') verses = [] try: firstline = brtags[0].previous_sibling.previous_sibling.strip() except: firstline = brtags[0].previous_sibling.strip() verses.append(firstline) for br in brtags: try: text = br.next_sibling.next_sibling.strip() except: text = br.next_sibling.strip() if text is None or text == '' or text.isspace(): continue # remove in-text line numbers if text.endswith(r'[0-9]+'): try: text = text.split(r'[0-9]')[0].strip() except: pass verses.append(text) for v in verses: # verse number assignment. verse += 1 c.execute("INSERT INTO texts VALUES (?,?,?,?,?,?,?, ?, ?, ?, ?)", (None, colltitle, title, 'Latin', author, date, chapter, verse, v, url, 'poetry')) if __name__ == '__main__': main() ```
[ { "content": "```python\n\"\"\"Test code for binary neural network operators.\"\"\"\nimport numpy as np\nimport tvm\nimport topi\nfrom topi.util import get_const_tuple\nfrom tvm.contrib.pickle_memoize import memoize\n\n\ndef verify_binary_dense(batch, in_dim, out_dim):\n A = tvm.placeholder((batch, in_dim), ...
[ { "content": "<|memory_start|>```python\n\"\"\"Test code for binary neural network operators.\"\"\"\nimport numpy as np\nimport tvm\nimport topi\nfrom topi.util import get_const_tuple\nfrom tvm.contrib.pickle_memoize import memoize\n\n\ndef verify_binary_dense(batch, in_dim, out_dim):\n A = tvm.placeholder((...
```python """Test code for binary neural network operators.""" import numpy as np import tvm import topi from topi.util import get_const_tuple from tvm.contrib.pickle_memoize import memoize def verify_binary_dense(batch, in_dim, out_dim): A = tvm.placeholder((batch, in_dim), name='A') B = tvm.placeholder((out_dim, in_dim), name='B') bnn_A = topi.nn.binarize_pack(A) bnn_B = topi.nn.binarize_pack(B) # binary dense bnn_A1 = tvm.placeholder(bnn_A.shape, dtype=bnn_A.dtype) bnn_B1 = tvm.placeholder(bnn_B.shape, dtype=bnn_B.dtype) bnn_C = topi.nn.binary_dense(bnn_A1, bnn_B1) # schedule with tvm.target.create('llvm'): s1 = topi.generic.schedule_binarize_pack(bnn_A) s2 = topi.generic.schedule_binarize_pack(bnn_B) s3 = topi.generic.schedule_binary_dense(bnn_C) dtype = A.dtype @memoize("topi.tests.test_topi_binary_dense") def get_ref_data(): # generate random matrix of +1 or -1 value a_np = (np.random.randint(2, size=(batch, in_dim)) * 2 - 1).astype(dtype) b_np = (np.random.randint(2, size=(out_dim, in_dim)) * 2 - 1).astype(dtype) c_np = np.dot(a_np, b_np.T) return a_np, b_np, c_np a_np, b_np, c_np = get_ref_data() ctx = tvm.cpu(0) a = tvm.nd.array(a_np, ctx) b = tvm.nd.array(b_np, ctx) bnn_a = tvm.nd.array(np.zeros(get_const_tuple(bnn_A.shape), dtype=bnn_A.dtype), ctx) bnn_b = tvm.nd.array(np.zeros(get_const_tuple(bnn_B.shape), dtype=bnn_B.dtype), ctx) bnn_c = tvm.nd.array(np.zeros(get_const_tuple(bnn_C.shape), dtype=bnn_C.dtype), ctx) f1 = tvm.build(s1, [A, bnn_A], 'llvm') f2 = tvm.build(s2, [B, bnn_B], 'llvm') f3 = tvm.build(s3, [bnn_A1, bnn_B1, bnn_C], 'llvm') f1(a, bnn_a) f2(b, bnn_b) f3(bnn_a, bnn_b, bnn_c) np.testing.assert_allclose(bnn_c.asnumpy(), c_np, rtol=1e-5) def test_binary_dense(): verify_binary_dense(1, 4096, 1024) verify_binary_dense(1, 1024, 1000) if __name__ == "__main__": test_binary_dense() ```
[ { "content": "Here is the snippet:\n```python\n#!/usr/bin/python\nimport pyman\nfrom os import getcwd, path\n\n\nclass VM( pyman.Page ):\n def __init__( self, pkg ):\n super( VM, self ).__init__( \"VM\" )\n self.host = None\n self.pkg = pkg\n self.dir = path.split( getcwd() )[1]\...
[ { "content": "Here is the snippet:\n<|memory_start|>```python\n#!/usr/bin/python\nimport pyman\nfrom os import getcwd, path\n\n\nclass VM( pyman.Page ):\n def __init__( self, pkg ):\n super( VM, self ).__init__( \"VM\" )\n self.host = None\n self.pkg = pkg\n self.dir = path.split...
```python #!/usr/bin/python import pyman from os import getcwd, path class VM( pyman.Page ): def __init__( self, pkg ): super( VM, self ).__init__( "VM" ) self.host = None self.pkg = pkg self.dir = path.split( getcwd() )[1] def choices( self ): if not self.actions: try: self.host = raw_input( "Host [user@]ip: " ) except NameError: self.host = input( "Host [user@]ip: " ) self.init_actions() return super( VM, self ).choices() def init_actions( self ): self.add([ pyman.Actions.Cmd( "Push Code", "rsync -aP --delete . %s:~/%s" % ( self.host, self.dir ) ), pyman.Actions.Cmd( "Pull Code", "rsync -aP %s:~/%s/ ." % ( self.host, self.dir ) ), pyman.Actions.Cmd( "Test", 'ssh -t %s "cd ~/%s; time nosetests -v --cover-branches --with-coverage --cover-erase --cover-package=%s --cover-html"' % ( self.host, self.dir, self.pkg ) ), pyman.Actions.Cmd( "Test With Stdout", 'ssh -t %s "cd ~/%s; time nosetests -vs --cover-branches --with-coverage --cover-erase --cover-package=%s --cover-html"' % ( self.host, self.dir, self.pkg) ), pyman.Actions.Cmd( "Pull Coverage", "rsync -aP %s:~/%s/cover/ cover/ &> /dev/null; google-chrome cover/index.html" % ( self.host, self.dir ) ), pyman.Actions.Cmd( "Open Coverage", "google-chrome cover/index.html" ), pyman.Actions.Cmd( "PyTerm", 'ssh -t %s "cd ~/%s; python"' % ( self.host, self.dir ) ), pyman.Actions.Cmd( "Install Package", 'ssh -t %s "cd ~/%s; sudo python setup.py develop"' % ( self.host, self.dir ) ), pyman.Actions.Back() ]) menu = pyman.Main( "DStore - Manager", [ VM( "dstore" ), pyman.Doc(), pyman.PyPi(), pyman.NoseTest(), pyman.Git(), pyman.Actions.Cmd("Install Package", "sudo python setup.py develop"), pyman.Actions.Exit() ]) menu.cli() ```
[ { "content": "Repeat the code exactly:\n```python\nimport cv2\nimport numpy\nfrom alpha_fill import alpha_fill\n\nclass BoundingBox(object):\n\n def __init__(self, pil_img, show_plot=False):\n self.mask_img = alpha_fill(pil_img)\n self.set_bounding_box()\n self.set_side_lengths()\n\n ...
[ { "content": "Repeat the code exactly:\n<|memory_start|>```python\nimport cv2\nimport numpy\nfrom alpha_fill import alpha_fill\n\nclass BoundingBox(object):\n\n def __init__(self, pil_img, show_plot=False):\n self.mask_img = alpha_fill(pil_img)\n self.set_bounding_box()\n self.set_side_l...
```python import cv2 import numpy from alpha_fill import alpha_fill class BoundingBox(object): def __init__(self, pil_img, show_plot=False): self.mask_img = alpha_fill(pil_img) self.set_bounding_box() self.set_side_lengths() self.set_areas() if show_plot: self.show_plot() def set_bounding_box(self): _,contours,_ = cv2.findContours(self.mask_img,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) self.contour = contours[0] rect = cv2.minAreaRect(self.contour) self.box = cv2.boxPoints(rect) #self.box = numpy.int0(box) def set_side_lengths(self): point1 = self.box[0] point2 = self.box[1] point3 = self.box[2] diffx = numpy.abs(point1[0]-point2[0]) diffy = numpy.abs(point1[1]-point2[1]) side1 = numpy.hypot(diffx,diffy) diffx = numpy.abs(point2[0]-point3[0]) diffy = numpy.abs(point2[1]-point3[1]) side2 = numpy.hypot(diffx,diffy) self.bounding_box_side_lengths = (side1,side2) """ def set_areas(self): self.hull = cv2.convexHull(self.contour) self.unpacked_hull = [] for i in range(len(self.hull)): self.unpacked_hull.append((self.hull[i][0][0],self.hull[i][0][1])) self.hull_area = self.polygon_area(self.unpacked_hull) self.bounding_box_area = self.bounding_box_side_lengths[0]*self.bounding_box_side_lengths[1] """ def set_areas(self): epsilon = 0.001*cv2.arcLength(self.contour,True) self.contour_approx = cv2.approxPolyDP(self.contour,epsilon,True) self.unpacked_contour_approx = [] for i in range(len(self.contour_approx)): self.unpacked_contour_approx.append((self.contour_approx[i][0][0],self.contour_approx[i][0][1])) self.contour_approx_area = self.polygon_area(self.unpacked_contour_approx) self.bounding_box_area = self.bounding_box_side_lengths[0]*self.bounding_box_side_lengths[1] def show_plot(self): color_img = cv2.cvtColor(self.mask_img, cv2.COLOR_GRAY2RGB) #cv2.drawContours(color_img,self.hull,0,(0,0,255),4) cv2.drawContours(color_img,[self.contour_approx],0,(0,0,255),1) cv2.drawContours(color_img,[numpy.int0(self.box)],0,(0,255,0),1) cv2.imshow('image',color_img) cv2.waitKey(0) cv2.destroyAllWindows() def get_box(self): return self.box def get_side_lengths(self): return self.bounding_box_side_lengths def get_side_length_difference(self): return numpy.abs(side_lengths[0]-side_lengths[1]) def get_area_difference(self): return numpy.abs(self.contour_approx_area-self.bounding_box_area) def polygon_area(self, corners): n = len(corners) cx = float(sum(x for x, y in corners)) / n cy = float(sum(y for x, y in corners)) / n cornersWithAngles = [] for x, y in corners: an = (numpy.arctan2(y - cy, x - cx) + 2.0 * numpy.pi) % (2.0 * numpy.pi) cornersWithAngles.append((x, y, an)) cornersWithAngles.sort(key = lambda tup: tup[2]) corners = map(lambda (x, y, an): (x, y), cornersWithAngles) area = 0.0 for i in range(n): j = (i + 1) % n area += corners[i][0] * corners[j][1] area -= corners[j][0] * corners[i][1] area = abs(area) / 2.0 return area ```
[ { "content": "Repeat the following code:\n```python\n# -*- coding: utf-8 -*-\n\nfrom copy import deepcopy\n\nimport pytest\n\nfrom pydash._compat import iteritems\n\n\n# pytest.mark is a generator so create alias for convenience\nparametrize = pytest.mark.parametrize\n\n\nclass Object(object):\n def __init__...
[ { "content": "Repeat the following code:\n<|memory_start|>```python\n# -*- coding: utf-8 -*-\n\nfrom copy import deepcopy\n\nimport pytest\n\nfrom pydash._compat import iteritems\n\n\n# pytest.mark is a generator so create alias for convenience\nparametrize = pytest.mark.parametrize\n\n\nclass Object(object):\n...
```python # -*- coding: utf-8 -*- from copy import deepcopy import pytest from pydash._compat import iteritems # pytest.mark is a generator so create alias for convenience parametrize = pytest.mark.parametrize class Object(object): def __init__(self, **attrs): for key, value in iteritems(attrs): setattr(self, key, value) class ItemsObject(object): def __init__(self, items): self._items = items def items(self): if isinstance(self._items, dict): return list(iteritems(self._items)) else: return enumerate(self._items) class IteritemsObject(object): def __init__(self, items): self._items = items def iteritems(self): if isinstance(self._items, dict): for key, value in iteritems(self._items): yield key, value else: for i, item in enumerate(self._items): yield i, item def reduce_callback0(total, num): return total + num def reduce_callback1(result, num, key): result[key] = num * 3 return result def reduce_right_callback0(a, b): return a + b def noop(*args, **kargs): pass def transform_callback0(result, num): num *= num if num % 2: result.append(num) return len(result) < 3 def is_equal_callback0(a, b): a_greet = a.startswith('h') if hasattr(a, 'startswith') else False b_greet = b.startswith('h') if hasattr(b, 'startswith') else False return a_greet == b_greet if a_greet or b_greet else None def for_in_callback0(value, key, obj): obj[key] += value def for_in_callback1(value, key, obj): obj[key] += value return False def for_in_callback2(value, index, obj): if index == 2: obj[index] = 'index:2' return True elif index == 0: obj[index] = False return True else: obj[index] = True return False ```
[ { "content": "```python\nimport os\n\nfrom flask import Flask, render_template\nfrom alexandria.extensions import db, migrate, bcrypt, login_manager\n\nfrom alexandria.models import users, documentlinks\n\ndef create_app(config_setting='dev'):\n \"\"\"An application factory, as explained here:\n http:...
[ { "content": "<|memory_start|>```python\nimport os\n\nfrom flask import Flask, render_template\nfrom alexandria.extensions import db, migrate, bcrypt, login_manager\n\nfrom alexandria.models import users, documentlinks\n\ndef create_app(config_setting='dev'):\n \"\"\"An application factory, as explained here...
```python import os from flask import Flask, render_template from alexandria.extensions import db, migrate, bcrypt, login_manager from alexandria.models import users, documentlinks def create_app(config_setting='dev'): """An application factory, as explained here: http://flask.pocoo.org/docs/patterns/appfactories/ :param config_object: The configuration object to use. """ app = Flask(__name__) if config_setting == 'prod': # only trigger SSLify if the app is running on Heroku #sslify = SSLify(app) from alexandria.settings import ProductionConfig #app.config.from_object('config.ProductionConfig') app.config.from_object(ProductionConfig) elif config_setting == 'test': from alexandria.settings import TestConfig #app.config.from_object('config.ProductionConfig') app.config.from_object(TestConfig) else: from alexandria.settings import DevelopmentConfig app.config.from_object(DevelopmentConfig) register_extensions(app) register_blueprints(app) register_errorhandlers(app) return app def register_extensions(app): #assets.init_app(app) bcrypt.init_app(app) #cache.init_app(app) db.init_app(app) login_manager.init_app(app) #debug_toolbar.init_app(app) migrate.init_app(app, db) #mail.init_app(app) return None def register_blueprints(app): # Prevents circular imports #from linksApp.views import links from alexandria.views import users app.register_blueprint(users.blueprint) from alexandria.views import public app.register_blueprint(public.blueprint) from alexandria.views import documents app.register_blueprint(documents.blueprint) return None def register_errorhandlers(app): def render_error(error): # If a HTTPException, pull the `code` attribute; default to 500 error_code = getattr(error, 'code', 500) return render_template("{0}.html".format(error_code)), error_code for errcode in [401, 404, 500]: app.errorhandler(errcode)(render_error) return None ```
[ { "content": "Here is the script:\n```python\n#!/usr/bin/python2\n\"\"\"\nRuns a validation command on the provided file, and generates an Event from\nthe results.\n\nIf a format has no defined validation commands, no command is run.\n\"\"\"\nfrom __future__ import print_function\nimport ast\nimport sys\n\n# ar...
[ { "content": "Here is the script:\n<|memory_start|>```python\n#!/usr/bin/python2\n\"\"\"\nRuns a validation command on the provided file, and generates an Event from\nthe results.\n\nIf a format has no defined validation commands, no command is run.\n\"\"\"\nfrom __future__ import print_function\nimport ast\nim...
```python #!/usr/bin/python2 """ Runs a validation command on the provided file, and generates an Event from the results. If a format has no defined validation commands, no command is run. """ from __future__ import print_function import ast import sys # archivematicaCommon from custom_handlers import get_script_logger from executeOrRunSubProcess import executeOrRun import databaseFunctions from dicts import replace_string_values # dashboard from fpr.models import FPRule, FormatVersion def main(file_path, file_uuid, sip_uuid): failed = False # Get file format try: fmt = FormatVersion.active.get(fileformatversion__file_uuid=file_uuid) except FormatVersion.DoesNotExist: rules = fmt = None if fmt: rules = FPRule.active.filter(format=fmt.uuid, purpose='validation') # Check for a default rule exists if not rules: rules = FPRule.active.filter(purpose='default_validation') for rule in rules: if rule.command.script_type in ('bashScript', 'command'): command_to_execute = replace_string_values(rule.command.command, file_=file_uuid, sip=sip_uuid, type_='file') args = [] else: command_to_execute = rule.command.command args = [file_path] print('Running', rule.command.description) exitstatus, stdout, stderr = executeOrRun(rule.command.script_type, command_to_execute, arguments=args) if exitstatus != 0: print('Command {} failed with exit status {}; stderr:'.format(rule.command.description, exitstatus), stderr, file=sys.stderr) failed = True continue print('Command {} completed with output {}'.format(rule.command.description, stdout)) # Parse output and generate an Event # Output is JSON in format: # { "eventOutcomeInformation": "pass", # "eventOutcomeDetailNote": "format=\"JPEG\"; version=\"1.01\"; result=\"Well-Formed and valid\"" } # Or # { "eventOutcomeInformation": "fail", # "eventOutcomeDetailNote": "format=\"Not detected\"; result=\"Not well-formed\"" } output = ast.literal_eval(stdout) event_detail = 'program="{tool.description}"; version="{tool.version}"'.format(tool=rule.command.tool) print('Creating validation event for {} ({})'.format(file_path, file_uuid)) databaseFunctions.insertIntoEvents( fileUUID=file_uuid, eventType='validation', eventDetail=event_detail, eventOutcome=output.get('eventOutcomeInformation'), eventOutcomeDetailNote=output.get('eventOutcomeDetailNote'), ) if failed: return -1 else: return 0 if __name__ == '__main__': logger = get_script_logger("archivematica.mcp.client.validateFile") file_path = sys.argv[1] file_uuid = sys.argv[2] sip_uuid = sys.argv[3] sys.exit(main(file_path, file_uuid, sip_uuid)) ```
[ { "content": "Write the code verbatim:\n```python\n#!usr/bin/python\n# -*- coding: utf-8-*-\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by the\n# Free Software Foundation; either version 3, or (at your option) any l...
[ { "content": "Write the code verbatim:\n<|memory_start|>```python\n#!usr/bin/python\n# -*- coding: utf-8-*-\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by the\n# Free Software Foundation; either version 3, or (at yo...
```python #!usr/bin/python # -*- coding: utf-8-*- # 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, 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 MERCHANTIBILITY # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License # for more details. "Aplicativo AdHoc Para generación de Facturas Electrónicas" __author__ = "Mariano Reingart (reingart@gmail.com)" __copyright__ = "Copyright (C) 2009-2015 Mariano Reingart" __license__ = "GPL 3.0" __version__ = "1.27b" from datetime import datetime from decimal import Decimal, getcontext, ROUND_DOWN import os import sys import wx import gui import traceback from ConfigParser import SafeConfigParser import wsaa, wsfe, wsfev1, wsfexv1 from php import SimpleXMLElement, SoapClient, SoapFault, date from email.mime.text import MIMEText from email.mime.application import MIMEApplication from email.mime.multipart import MIMEMultipart from smtplib import SMTP #from PyFPDF.ejemplos.form import Form from pyfepdf import FEPDF # Formatos de archivos: from formatos import formato_xml, formato_csv, formato_dbf, formato_txt, formato_json HOMO = False DEBUG = '--debug' in sys.argv CONFIG_FILE = "rece.ini" ACERCA_DE = u""" PyRece: Aplicativo AdHoc para generar Facturas Electrónicas Copyright (C) 2008-2015 Mariano Reingart reingart@gmail.com Este progarma es software libre, se entrega ABSOLUTAMENTE SIN GARANTIA y es bienvenido a redistribuirlo bajo la licencia GPLv3. Para información adicional y descargas ver: http://www.sistemasagiles.com.ar/ """ INSTRUCTIVO = U""" Forma de uso: * Examinar: para buscar el archivo a procesar (opcional) * Cargar: para leer los datos del archivo de facturas a procesar * Autenticar: para iniciar la sesión en los servidores de AFIP (obligatorio antes de autorizar) * Marcar Todo: para seleccionar todas las facturas * Autorizar: para autorizar las facturas seleccionadas, completando el CAE y demás datos * Autorizar Lote: para autorizar en un solo lote las facturas seleccionadas * Grabar: para almacenar los datos procesados en el archivo de facturas * Previsualizar: para ver por pantalla la factura seleccionadas * Enviar: para envia por correo electrónico las facturas seleccionadas Para solicitar soporte comercial, escriba a pyrece@sistemasagiles.com.ar """ class PyRece(gui.Controller): def on_load(self, event): self.cols = [] self.items = [] self.paths = [entrada] self.token = self.sign = "" self.smtp = None self.webservice = None if entrada and os.path.exists(entrada): self.cargar() self.components.cboWebservice.value = DEFAULT_WEBSERVICE self.on_cboWebservice_click(event) self.tipos = { 1:u"Factura A", 2:u"Notas de Débito A", 3:u"Notas de Crédito A", 4:u"Recibos A", 5:u"Notas de Venta al contado A", 6:u"Facturas B", 7:u"Notas de Débito B", 8:u"Notas de Crédito B", 9:u"Recibos B", 10:u"Notas de Venta al contado B", 19:u"Facturas de Exportación", 20:u"Nota de Débito por Operaciones con el Exterior", 21:u"Nota de Crédito por Operaciones con el Exterior", 39:u"Otros comprobantes A que cumplan con la R.G. N° 3419", 40:u"Otros comprobantes B que cumplan con la R.G. N° 3419", 60:u"Cuenta de Venta y Líquido producto A", 61:u"Cuenta de Venta y Líquido producto B", 63:u"Liquidación A", 64:u"Liquidación B", 11:u"Factura C", 12:u"Nota de Débito C", 13:u"Nota de Crédito C", 15:u"Recibo C", } self.component.bgcolor = "light gray" # deshabilito ordenar ##self.components.lvwListado.GetColumnSorter = lambda: lambda x,y: 0 def set_cols(self, cols): self.__cols = cols lv = self.components.lvwListado # remove old columns: lv.clear_all() # insert new columns for col in cols: ch = gui.ListColumn(lv, name=col, text=col.replace("_"," ").title(), align="left") def get_cols(self): return self.__cols cols = property(get_cols, set_cols) def set_items(self, items): cols = self.cols self.__items = items def convert_str(value): if value is None: return '' elif isinstance(value, str): return unicode(value,'latin1') elif isinstance(value, unicode): return value else: return str(value) self.components.lvwListado.items = [[convert_str(item[col]) for col in cols] for item in items] wx.SafeYield() def get_items(self): return self.__items items = property(get_items, set_items) def get_selected_items(self): for it in self.components.lvwListado.get_selected_items(): yield it.index, it def set_selected_items(self, selected): for it in selected: it.selected = True def set_paths(self, paths): self.__paths = paths self.components.txtArchivo.value = ', '.join([fn for fn in paths]) def get_paths(self): return self.__paths paths = property(get_paths, set_paths) def log(self, msg): if not isinstance(msg, unicode): msg = unicode(msg, "latin1","ignore") print "LOG", msg self.components.txtEstado.value = msg + u"\n" + self.components.txtEstado.value wx.SafeYield() f = None try: f = open("pyrece.log","a") f.write("%s: " % (datetime.now(), )) f.write(msg.encode("ascii", "ignore")) f.write("\n\r") except Exception, e: print e finally: if f: f.close() def progreso(self, value): if self.items: per = (value+1)/float(len(self.items))*100 self.components.pbProgreso.value = per wx.SafeYield() def error(self, code, text): ex = traceback.format_exception( sys.exc_type, sys.exc_value, sys.exc_traceback) self.log(''.join(ex)) gui.alert(text, 'Error %s' % code) def verifica_ws(self): if not self.ws: gui.alert("Debe seleccionar el webservice a utilizar!", 'Advertencia') raise RuntimeError() if not self.token or not self.sign: gui.alert("Debe autenticarse con AFIP!", 'Advertencia') raise RuntimeError() def on_btnMarcarTodo_click(self, event): for it in self.components.lvwListado.items: it.selected = True def on_menu_consultas_dummy_click(self, event): ##self.verifica_ws() try: if self.webservice=="wsfe": results = self.client.FEDummy() msg = "AppServ %s\nDbServer %s\nAuthServer %s" % ( results.appserver, results.dbserver, results.authserver) location = self.ws.client.location elif self.webservice in ("wsfev1", "wsfexv1"): self.ws.Dummy() msg = "AppServ %s\nDbServer %s\nAuthServer %s" % ( self.ws.AppServerStatus, self.ws.DbServerStatus, self.ws.AuthServerStatus) location = self.ws.client.location else: msg = "%s no soportado" % self.webservice location = "" gui.alert(msg, location) except Exception, e: self.error(u'Excepción',unicode(str(e),"latin1","ignore")) def on_menu_consultas_lastCBTE_click(self, event): ##self.verifica_ws() options = [v for k,v in sorted([(k,v) for k,v in self.tipos.items()])] result = gui.single_choice(options, "Tipo de comprobante", u"Consulta Último Nro. Comprobante", ) if not result: return tipocbte = [k for k,v in self.tipos.items() if v==result][0] result = gui.prompt(u"Punto de venta", u"Consulta Último Nro. Comprobante", '2') if not result: return ptovta = result try: if self.webservice=="wsfe": ultcmp = wsfe.recuperar_last_cmp(self.client, self.token, self.sign, cuit, ptovta, tipocbte) elif self.webservice=="wsfev1": ultcmp = "%s (wsfev1)" % self.ws.CompUltimoAutorizado(tipocbte, ptovta) elif self.webservice=="wsfexv1": ultcmp = "%s (wsfexv1)" % self.ws.GetLastCMP(tipocbte, ptovta) gui.alert(u"Último comprobante: %s\n" u"Tipo: %s (%s)\nPunto de Venta: %s" % (ultcmp, self.tipos[tipocbte], tipocbte, ptovta), u'Consulta Último Nro. Comprobante') except SoapFault,e: self.log(self.client.xml_request) self.log(self.client.xml_response) self.error(e.faultcode, e.faultstring.encode("ascii","ignore")) except wsfe.WSFEError,e: self.error(e.code, e.msg.encode("ascii","ignore")) except Exception, e: self.error(u'Excepción',unicode(str(e),"latin1","ignore")) def on_menu_consultas_getCAE_click(self, event): self.verifica_ws() options = [v for k,v in sorted([(k,v) for k,v in self.tipos.items()])] result = gui.single_choice(options, "Tipo de comprobante", u"Consulta Comprobante", ) if not result: return tipocbte = [k for k,v in self.tipos.items() if v==result][0] result = gui.prompt(u"Punto de venta", u"Consulta Comprobante", '2') if not result: return ptovta = result result = gui.prompt(u"Nº de comprobante", u"Consulta Comprobante", '2') if not result: return nrocbte = result try: if self.webservice=="wsfe": cae = 'no soportado' elif self.webservice=="wsfev1": cae = "%s (wsfev1)" % self.ws.CompConsultar(tipocbte, ptovta, nrocbte) self.log('CAE: %s' % self.ws.CAE) self.log('FechaCbte: %s' % self.ws.FechaCbte) self.log('PuntoVenta: %s' % self.ws.PuntoVenta) self.log('CbteNro: %s' % self.ws.CbteNro) self.log('ImpTotal: %s' % self.ws.ImpTotal) self.log('ImpNeto: %s' % self.ws.ImpNeto) self.log('ImptoLiq: %s' % self.ws.ImptoLiq) self.log('EmisionTipo: %s' % self.ws.EmisionTipo) elif self.webservice=="wsfexv1": cae = "%s (wsfexv1)" % self.ws.GetCMP(tipocbte, ptovta, nrocbte) self.log('CAE: %s' % self.ws.CAE) self.log('FechaCbte: %s' % self.ws.FechaCbte) self.log('PuntoVenta: %s' % self.ws.PuntoVenta) self.log('CbteNro: %s' % self.ws.CbteNro) self.log('ImpTotal: %s' % self.ws.ImpTotal) gui.alert(u"CAE: %s\n" u"Tipo: %s (%s)\nPunto de Venta: %s\nNumero: %s\nFecha: %s" % ( cae, self.tipos[tipocbte], tipocbte, ptovta, nrocbte, self.ws.FechaCbte), u'Consulta Comprobante') except SoapFault,e: self.log(self.client.xml_request) self.log(self.client.xml_response) self.error(e.faultcode, e.faultstring.encode("ascii","ignore")) except wsfe.WSFEError,e: self.error(e.code, e.msg.encode("ascii","ignore")) except Exception, e: self.error(u'Excepción',unicode(str(e),"latin1","ignore")) def on_menu_consultas_lastID_click(self, event): ##self.verifica_ws() try: if self.webservice=="wsfe": ultnro = wsfe.ultnro(self.client, self.token, self.sign, cuit) print "ultnro", ultnro print self.client.xml_response elif self.webservice=="wsfexv1": ultnro = self.ws.GetLastID() else: ultnro = None gui.alert(u"Último ID (máximo): %s" % (ultnro), u'Consulta Último ID') except SoapFault,e: self.log(self.client.xml_request) self.log(self.client.xml_response) self.error(e.faultcode, e.faultstring.encode("ascii","ignore")) except wsfe.WSFEError,e: self.error(e.code, e.msg.encode("ascii","ignore")) except Exception, e: self.error(u'Excepción',unicode(e)) def on_menu_ayuda_acercade_click(self, event): text = ACERCA_DE gui.alert(text, u'Acerca de PyRece Versión %s' % __version__) def on_menu_ayuda_instructivo_click(self, event): text = INSTRUCTIVO gui.alert(text, u'Instructivo de PyRece') def on_menu_ayuda_limpiar_click(self, event): self.components.txtEstado.value = "" def on_menu_ayuda_mensajesXML_click(self, event): self.verifica_ws() self.components.txtEstado.value = u"XmlRequest:\n%s\n\nXmlResponse:\n%s" % ( self.ws.xml_request, self.ws.xml_response) self.component.size = (592, 517) def on_menu_ayuda_estado_click(self, event): if self.component.size[1]<517: self.component.size = (592, 517) else: self.component.size = (592, 265) def on_menu_ayuda_configuracion_click(self, event): self.components.txtEstado.value = open(CONFIG_FILE).read() self.component.size = (592, 517) def on_cboWebservice_click(self, event): self.webservice = self.components.cboWebservice.value self.ws = None self.token = None self.sign = None if self.webservice == "wsfe": self.client = SoapClient(wsfe_url, action=wsfe.SOAP_ACTION, namespace=wsfe.SOAP_NS, trace=False, exceptions=True) elif self.webservice == "wsfev1": self.ws = wsfev1.WSFEv1() elif self.webservice == "wsfexv1": self.ws = wsfexv1.WSFEXv1() def on_btnAutenticar_click(self, event): try: if self.webservice in ('wsfe', ): service = "wsfe" elif self.webservice in ('wsfev1', ): self.log("Conectando WSFEv1... " + wsfev1_url) self.ws.Conectar("",wsfev1_url, proxy_dict) self.ws.Cuit = cuit service = "wsfe" elif self.webservice in ('wsfex', 'wsfexv1'): self.log("Conectando WSFEXv1... " + wsfexv1_url) self.ws.Conectar("",wsfexv1_url, proxy_dict) self.ws.Cuit = cuit service = "wsfex" else: gui.alert('Debe seleccionar servicio web!', 'Advertencia') return self.log("Creando TRA %s ..." % service) ws = wsaa.WSAA() tra = ws.CreateTRA(service) self.log("Frimando TRA (CMS) con %s %s..." % (str(cert),str(privatekey))) cms = ws.SignTRA(str(tra),str(cert),str(privatekey)) self.log("Llamando a WSAA... " + wsaa_url) ws.Conectar("", wsdl=wsaa_url, proxy=proxy_dict) self.log("Proxy: %s" % proxy_dict) xml = ws.LoginCMS(str(cms)) self.log("Procesando respuesta...") if xml: self.token = ws.Token self.sign = ws.Sign if DEBUG: self.log("Token: %s" % self.token) self.log("Sign: %s" % self.sign) elif self.token and self.sign: self.log("Token: %s... OK" % self.token[:10]) self.log("Sign: %s... OK" % self.sign[:10]) if self.webservice in ("wsfev1", "wsfexv1"): self.ws.Token = self.token self.ws.Sign = self.sign if xml: gui.alert('Autenticado OK!', 'Advertencia') else: gui.alert(u'Respuesta: %s' % ws.XmlResponse, u'No se pudo autenticar: %s' % ws.Excepcion) except SoapFault,e: self.error(e.faultcode, e.faultstring.encode("ascii","ignore")) except Exception, e: self.error(u'Excepción',unicode(e)) def examinar(self): filename = entrada wildcard = ["Planillas Excel (*.xlsx)|*.xlsx", "Archivos CSV (*.csv)|*.csv", "Archivos XML (*.xml)|*.xml", "Archivos TXT (*.txt)|*.txt", "Archivos DBF (*.dbf)|*.dbf", "Archivos JSON (*.json)|*.json", ] if entrada.endswith("xml"): wildcard.sort(reverse=True) result = gui.open_file('Abrir', 'datos', filename, '|'.join(wildcard)) if not result: return self.paths = [result] def on_menu_archivo_abrir_click(self, event): self.examinar() self.cargar() def on_menu_archivo_cargar_click(self, event): self.cargar() def cargar(self): try: items = [] for fn in self.paths: if fn.lower().endswith(".csv") or fn.lower().endswith(".xlsx"): filas = formato_csv.leer(fn) items.extend(filas) elif fn.lower().endswith(".xml"): regs = formato_xml.leer(fn) items.extend(formato_csv.aplanar(regs)) elif fn.lower().endswith(".txt"): regs = formato_txt.leer(fn) items.extend(formato_csv.aplanar(regs)) elif fn.lower().endswith(".dbf"): reg = formato_dbf.leer({}, carpeta=os.path.dirname(fn)) items.extend(formato_csv.aplanar(reg.values())) elif fn.lower().endswith(".json"): regs = formato_json.leer(fn) items.extend(formato_csv.aplanar(regs)) else: self.error(u'Formato de archivo desconocido: %s', unicode(fn)) if len(items) < 2: gui.alert(u'El archivo no tiene datos válidos', 'Advertencia') # extraer los nombres de columnas (ignorar vacios de XLSX) cols = items and [str(it).strip() for it in items[0] if it] or [] if DEBUG: print "Cols",cols # armar diccionario por cada linea items = [dict([(col,item[i]) for i, col in enumerate(cols)]) for item in items[1:]] self.cols = cols self.items = items except Exception,e: self.error(u'Excepción',unicode(e)) ##raise def on_menu_archivo_guardar_click(self, event): filename = entrada wildcard = ["Archivos CSV (*.csv)|*.csv", "Archivos XML (*.xml)|*.xml", "Archivos TXT (*.txt)|*.txt", "Archivos DBF (*.dbf)|*.dbf", "Archivos JSON (*.json)|*.json", "Planillas Excel (*.xlsx)|*.xlsx", ] if entrada.endswith("xml"): wildcard.sort(reverse=True) if self.paths: path = self.paths[0] else: path = salida result = gui.save_file(title='Guardar', filename=path, wildcard='|'.join(wildcard)) if not result: return fn = result[0] self.grabar(fn) def grabar(self, fn=None): try: if fn is None and salida: if salida.startswith("-") and self.paths: fn = os.path.splitext(self.paths[0])[0] + salida else: fn = salida elif not fn: raise RuntimeError("Debe indicar un nombre de archivo para grabar") if fn.lower().endswith(".csv") or fn.lower().endswith(".xlsx"): formato_csv.escribir([self.cols] + [[item[k] for k in self.cols] for item in self.items], fn) else: regs = formato_csv.desaplanar([self.cols] + [[item[k] for k in self.cols] for item in self.items]) if fn.endswith(".xml"): formato_xml.escribir(regs, fn) elif fn.endswith(".txt"): formato_txt.escribir(regs, fn) elif fn.endswith(".dbf"): formato_dbf.escribir(regs, {}, carpeta=os.path.dirname(fn)) elif fn.endswith(".json"): formato_json.escribir(regs, fn) else: self.error(u'Formato de archivo desconocido', unicode(fn)) gui.alert(u'Se guardó con éxito el archivo:\n%s' % (unicode(fn),), 'Guardar') except Exception, e: self.error(u'Excepción',unicode(e)) def on_btnAutorizar_click(self, event): self.verifica_ws() try: ok = procesadas = rechazadas = 0 cols = self.cols items = [] self.progreso(0) selected = [] for i, item in self.get_selected_items(): kargs = item.copy() selected.append(item) kargs['cbt_desde'] = kargs['cbt_hasta'] = kargs ['cbt_numero'] for key in kargs: if isinstance(kargs[key], basestring): kargs[key] = kargs[key].replace(",",".") if self.webservice == 'wsfe': if 'id' not in kargs or kargs['id'] == "": id = long(kargs['cbt_desde']) id += (int(kargs['tipo_cbte'])*10**4 + int(kargs['punto_vta']))*10**8 kargs['id'] = id if DEBUG: self.log('\n'.join(["%s='%s'" % (k,v) for k,v in kargs.items()])) if not cuit in kargs: kargs['cuit'] = cuit ret = wsfe.aut(self.client, self.token, self.sign, **kargs) kargs.update(ret) del kargs['cbt_desde'] del kargs['cbt_hasta'] elif self.webservice == 'wsfev1': encabezado = {} for k in ('concepto', 'tipo_doc', 'nro_doc', 'tipo_cbte', 'punto_vta', 'cbt_desde', 'cbt_hasta', 'imp_total', 'imp_tot_conc', 'imp_neto', 'imp_iva', 'imp_trib', 'imp_op_ex', 'fecha_cbte', 'moneda_id', 'moneda_ctz'): encabezado[k] = kargs[k] for k in ('fecha_venc_pago', 'fecha_serv_desde', 'fecha_serv_hasta'): if k in kargs: encabezado[k] = kargs.get(k) self.ws.CrearFactura(**encabezado) for l in range(1,1000): k = 'tributo_%%s_%s' % l if (k % 'id') in kargs: id = kargs[k % 'id'] desc = kargs[k % 'desc'] base_imp = kargs[k % 'base_imp'] alic = kargs[k % 'alic'] importe = kargs[k % 'importe'] if id: self.ws.AgregarTributo(id, desc, base_imp, alic, importe) else: break for l in range(1,1000): k = 'iva_%%s_%s' % l if (k % 'id') in kargs: id = kargs[k % 'id'] base_imp = kargs[k % 'base_imp'] importe = kargs[k % 'importe'] if id: self.ws.AgregarIva(id, base_imp, importe) else: break for l in range(1,1000): k = 'cbte_asoc_%%s_%s' % l if (k % 'tipo') in kargs: tipo = kargs[k % 'tipo'] pto_vta = kargs[k % 'pto_vta'] nro = kargs[k % 'nro'] if id: self.ws.AgregarCmpAsoc(tipo, pto_vta, nro) else: break if DEBUG: self.log('\n'.join(["%s='%s'" % (k,v) for k,v in self.ws.factura.items()])) cae = self.ws.CAESolicitar() kargs.update({ 'cae': self.ws.CAE, 'fecha_vto': self.ws.Vencimiento, 'resultado': self.ws.Resultado, 'motivo': self.ws.Obs, 'reproceso': self.ws.Reproceso, 'err_code': self.ws.ErrCode.encode("latin1"), 'err_msg': self.ws.ErrMsg.encode("latin1"), }) if self.ws.ErrMsg: gui.alert(self.ws.ErrMsg, "Error AFIP") if self.ws.Obs and self.ws.Obs!='00': gui.alert(self.ws.Obs, u"Observación AFIP") elif self.webservice == 'wsfexv1': kargs['cbte_nro'] = kargs ['cbt_numero'] kargs['permiso_existente'] = kargs['permiso_existente'] or "" encabezado = {} for k in ('tipo_cbte', 'punto_vta', 'cbte_nro', 'fecha_cbte', 'imp_total', 'tipo_expo', 'permiso_existente', 'pais_dst_cmp', 'nombre_cliente', 'cuit_pais_cliente', 'domicilio_cliente', 'id_impositivo', 'moneda_id', 'moneda_ctz', 'obs_comerciales', 'obs_generales', 'forma_pago', 'incoterms', 'idioma_cbte', 'incoterms_ds'): encabezado[k] = kargs.get(k) self.ws.CrearFactura(**encabezado) for l in range(1,1000): k = 'codigo%s' % l if k in kargs: codigo = kargs['codigo%s' % l] ds = kargs['descripcion%s' % l] qty = kargs['cantidad%s' % l] umed = kargs['umed%s' % l] precio = kargs['precio%s' % l] importe = kargs['importe%s' % l] bonif = kargs.get('bonif%s' % l) self.ws.AgregarItem(codigo, ds, qty, umed, precio, importe, bonif) else: break for l in range(1,1000): k = 'cbte_asoc_%%s_%s' % l if (k % 'tipo') in kargs: tipo = kargs[k % 'tipo'] pto_vta = kargs[k % 'pto_vta'] nro = kargs[k % 'nro'] if id: self.ws.AgregarCmpAsoc(tipo, pto_vta, nro) else: break if DEBUG: self.log('\n'.join(["%s='%s'" % (k,v) for k,v in self.ws.factura.items()])) cae = self.ws.Authorize(kargs['id']) kargs.update({ 'cae': self.ws.CAE, 'fecha_vto': self.ws.Vencimiento, 'resultado': self.ws.Resultado, 'motivo': self.ws.Obs, 'reproceso': self.ws.Reproceso, 'err_code': self.ws.ErrCode.encode("latin1"), 'err_msg': self.ws.ErrMsg.encode("latin1"), }) if self.ws.ErrMsg: gui.alert(self.ws.ErrMsg, "Error AFIP") if self.ws.Obs and self.ws.Obs!='00': gui.alert(self.ws.Obs, u"Observación AFIP") # actuaizo la factura for k in ('cae', 'fecha_vto', 'resultado', 'motivo', 'reproceso', 'err_code', 'err_msg'): if kargs.get(k): item[k] = kargs[k] self.items[i] = item self.log(u"ID: %s CAE: %s Motivo: %s Reproceso: %s" % (kargs['id'], kargs['cae'], kargs['motivo'],kargs['reproceso'])) procesadas += 1 if kargs['resultado'] == "R": rechazadas += 1 elif kargs['resultado'] == "A": ok += 1 self.progreso(i) self.items = self.items self.set_selected_items(selected) self.progreso(len(self.items) - 1) gui.alert(u'Proceso finalizado, procesadas %d\n\n' 'Aceptadas: %d\n' 'Rechazadas: %d' % (procesadas, ok, rechazadas), u'Autorización') self.grabar() except SoapFault, e: self.error(e.faultcode, e.faultstring.encode("ascii","ignore")) except wsfe.WSFEError,e: self.error(e.code, e.msg.encode("ascii","ignore")) except KeyError, e: self.error("Error",u'Campo obligatorio no encontrado: %s' % e) except Exception, e: self.error(u'Excepción',unicode(e)) finally: if DEBUG: if self.webservice == 'wsfev1' and DEBUG: print self.ws.XmlRequest print self.ws.XmlResponse def on_btnAutorizarLote_click(self, event): self.verifica_ws() if not self.items: return try: #getcontext().prec = 2 ok = 0 rechazadas = 0 cols = self.cols items = [] self.progreso(0) cbt_desde = cbt_hasta = None datos = { 'tipo_cbte': None, 'punto_vta': None, 'fecha_cbte': None, 'fecha_venc_pago': None, 'fecha_cbte': None, 'fecha_venc_pago': None, 'fecha_serv_desde': None, 'fecha_serv_hasta': None, 'moneda_id': None, 'moneda_ctz': None, 'id': None, } importes = { 'imp_total': Decimal(0), 'imp_tot_conc': Decimal(0), 'imp_neto': Decimal(0), 'imp_iva':Decimal(0), 'imp_op_ex': Decimal(0), 'imp_trib': Decimal(0), } for l in range(1,5): k = 'iva_%%s_%s' % l datos[k % 'id'] = None importes[k % 'base_imp'] = Decimal(0) importes[k % 'importe'] = Decimal(0) for l in range(1,10): k = 'tributo_%%s_%s' % l datos[k % 'id'] = None datos[k % 'desc'] = None importes[k % 'base_imp'] = Decimal(0) datos[k % 'alic'] = None importes[k % 'importe'] = Decimal(0) for i, item in self.get_selected_items(): if cbt_desde is None or int(item['cbt_numero']) < cbt_desde: cbt_desde = int(item['cbt_numero']) if cbt_hasta is None or int(item['cbt_numero']) > cbt_hasta: cbt_hasta = int(item['cbt_numero']) for key in item: if key in datos: if datos[key] is None: datos[key] = item[key] elif datos[key] != item[key]: raise RuntimeError(u"%s tiene valores distintos en el lote!" % key) if key in importes and item[key]: importes[key] = importes[key] + Decimal("%.2f" % float(str(item[key].replace(",",".")))) kargs = {'cbt_desde': cbt_desde, 'cbt_hasta': cbt_hasta} kargs.update({'tipo_doc': 99, 'nro_doc': '0'}) kargs.update(datos) kargs.update(importes) if kargs['fecha_serv_desde'] and kargs['fecha_serv_hasta']: kargs['presta_serv'] = 1 kargs['concepto'] = 2 else: kargs['presta_serv'] = 0 kargs['concepto'] = 1 del kargs['fecha_serv_desde'] del kargs['fecha_serv_hasta'] for key, val in importes.items(): importes[key] = val.quantize(Decimal('.01'), rounding=ROUND_DOWN) if 'id' not in kargs or kargs['id'] == "": id = long(kargs['cbt_desde']) id += (int(kargs['tipo_cbte'])*10**4 + int(kargs['punto_vta']))*10**8 kargs['id'] = id if DEBUG: self.log('\n'.join(["%s='%s'" % (k,v) for k,v in kargs.items()])) if '--test' in sys.argv: kargs['cbt_desde'] = 777 kargs['fecha_cbte'] = '20110802' kargs['fecha_venc_pago'] = '20110831' if gui.confirm("Confirma Lote:\n" "Tipo: %(tipo_cbte)s Desde: %(cbt_desde)s Hasta %(cbt_hasta)s\n" "Neto: %(imp_neto)s IVA: %(imp_iva)s Trib.: %(imp_trib)s Total: %(imp_total)s" % kargs, "Autorizar lote:"): if self.webservice == 'wsfev1': encabezado = {} for k in ('concepto', 'tipo_doc', 'nro_doc', 'tipo_cbte', 'punto_vta', 'cbt_desde', 'cbt_hasta', 'imp_total', 'imp_tot_conc', 'imp_neto', 'imp_iva', 'imp_trib', 'imp_op_ex', 'fecha_cbte', 'moneda_id', 'moneda_ctz'): encabezado[k] = kargs[k] for k in ('fecha_venc_pago', 'fecha_serv_desde', 'fecha_serv_hasta'): if k in kargs: encabezado[k] = kargs.get(k) self.ws.CrearFactura(**encabezado) for l in range(1,1000): k = 'iva_%%s_%s' % l if (k % 'id') in kargs: id = kargs[k % 'id'] base_imp = kargs[k % 'base_imp'] importe = kargs[k % 'importe'] if id: self.ws.AgregarIva(id, base_imp, importe) else: break for l in range(1,1000): k = 'tributo_%%s_%s' % l if (k % 'id') in kargs: id = kargs[k % 'id'] desc = kargs[k % 'desc'] base_imp = kargs[k % 'base_imp'] alic = kargs[k % 'alic'] importe = kargs[k % 'importe'] if id: self.ws.AgregarTributo(id, desc, base_imp, alic, importe) else: break if DEBUG: self.log('\n'.join(["%s='%s'" % (k,v) for k,v in self.ws.factura.items()])) cae = self.ws.CAESolicitar() kargs.update({ 'cae': self.ws.CAE, 'fecha_vto': self.ws.Vencimiento, 'resultado': self.ws.Resultado, 'motivo': self.ws.Obs, 'reproceso': self.ws.Reproceso, 'err_code': self.ws.ErrCode.encode("latin1"), 'err_msg': self.ws.ErrMsg.encode("latin1"), }) if self.ws.ErrMsg: gui.alert(self.ws.ErrMsg, "Error AFIP") if self.ws.Obs and self.ws.Obs!='00': gui.alert(self.ws.Obs, u"Observación AFIP") for i, item in self.get_selected_items(): for key in ('id', 'cae', 'fecha_vto', 'resultado', 'motivo', 'reproceso', 'err_code', 'err_msg'): item[key] = kargs[key] self.log("ID: %s CAE: %s Motivo: %s Reproceso: %s" % (kargs['id'], kargs['cae'], kargs['motivo'],kargs['reproceso'])) if kargs['resultado'] == "R": rechazadas += 1 elif kargs['resultado'] == "A": ok += 1 self.items = self.items # refrescar, ver de corregir self.progreso(len(self.items)) gui.alert('Proceso finalizado OK!\n\nAceptadas: %d\nRechazadas: %d' % (ok, rechazadas), 'Autorización') self.grabar() except SoapFault,e: self.log(self.client.xml_request) self.log(self.client.xml_response) self.error(e.faultcode, e.faultstring.encode("ascii","ignore")) except wsfe.WSFEError,e: self.error(e.code, e.msg.encode("ascii","ignore")) except Exception, e: self.error(u'Excepción',unicode(e)) def on_btnPrevisualizar_click(self, event): try: j = 0 for i, item in self.get_selected_items(): j += 1 archivo = self.generar_factura(item, mostrar=(j==1)) except Exception, e: print e self.error(u'Excepción', unicode(str(e), 'latin1', 'ignore')) def on_btnEnviar_click(self, event): try: ok = no = 0 self.progreso(0) for i, item in self.get_selected_items(): if not item['cae'] in ("", "NULL"): archivo = self.generar_factura(item) if item.get('email'): self.enviar_mail(item,archivo) ok += 1 else: no += 1 self.log("No se envia factura %s por no tener EMAIL" % item['cbt_numero']) else: self.log("No se envia factura %s por no tener CAE" % item['cbt_numero']) no += 1 self.progreso(i) self.progreso(len(self.items)) gui.alert('Proceso finalizado OK!\n\nEnviados: %d\nNo enviados: %d' % (ok, no), 'Envio de Email') except Exception, e: self.error(u'Excepción',unicode(e)) def generar_factura(self, fila, mostrar=False): fepdf = FEPDF() fact = formato_csv.desaplanar([self.cols] + [[item[k] for k in self.cols] for item in [fila]])[0] fact['cbte_nro'] = fact['cbt_numero'] fact['items'] = fact['detalles'] for d in fact['datos']: fepdf.AgregarDato(d['campo'], d['valor'], d['pagina']) # por compatiblidad, completo campos anteriores if d['campo'] not in fact and d['valor']: fact[d['campo']] = d['valor'] fepdf.factura = fact # cargo el formato CSV por defecto (factura.csv) fepdf.CargarFormato(conf_fact.get("formato", "factura.csv")) # datos fijos: fepdf.CUIT = cuit # CUIT del emisor para código de barras for k, v in conf_pdf.items(): fepdf.AgregarDato(k, v) fepdf.CrearPlantilla(papel=conf_fact.get("papel", "legal"), orientacion=conf_fact.get("orientacion", "portrait")) fepdf.ProcesarPlantilla(num_copias=int(conf_fact.get("copias", 1)), lineas_max=int(conf_fact.get("lineas_max", 24)), qty_pos=conf_fact.get("cant_pos") or 'izq') salida = conf_fact.get("salida", "") fact = fepdf.factura if salida: pass elif 'pdf' in fact and fact['pdf']: salida = fact['pdf'] else: # genero el nombre de archivo según datos de factura d = conf_fact.get('directorio', ".") clave_subdir = conf_fact.get('subdirectorio','fecha_cbte') if clave_subdir: d = os.path.join(d, item[clave_subdir]) if not os.path.isdir(d): os.mkdir(d) fs = conf_fact.get('archivo','numero').split(",") it = item.copy() tipo_fact, letra_fact, numero_fact = fact['_fmt_fact'] it['tipo'] = tipo_fact.replace(" ", "_") it['letra'] = letra_fact it['numero'] = numero_fact it['mes'] = item['fecha_cbte'][4:6] it['año'] = item['fecha_cbte'][0:4] fn = ''.join([str(it.get(ff,ff)) for ff in fs]) fn = fn.decode('latin1').encode('ascii', 'replace').replace('?','_') salida = os.path.join(d, "%s.pdf" % fn) fepdf.GenerarPDF(archivo=salida) if mostrar: fepdf.MostrarPDF(archivo=salida,imprimir='--imprimir' in sys.argv) return salida def enviar_mail(self, item, archivo): archivo = self.generar_factura(item) if item['email']: msg = MIMEMultipart() msg['Subject'] = conf_mail['motivo'].replace("NUMERO",str(item['cbt_numero'])) msg['From'] = conf_mail['remitente'] msg['Reply-to'] = msg['From'] msg['To'] = item['email'] msg.preamble = 'Mensaje de multiples partes.\n' if not 'html' in conf_mail: part = MIMEText(conf_mail['cuerpo']) msg.attach(part) else: alt = MIMEMultipart('alternative') msg.attach(alt) text = MIMEText(conf_mail['cuerpo']) alt.attach(text) # We reference the image in the IMG SRC attribute by the ID we give it below html = MIMEText(conf_mail['html'], 'html') alt.attach(html) part = MIMEApplication(open(archivo,"rb").read()) part.add_header('Content-Disposition', 'attachment', filename=os.path.basename(archivo)) msg.attach(part) try: self.log("Enviando email: %s a %s" % (msg['Subject'], msg['To'])) if not self.smtp: self.smtp = SMTP(conf_mail['servidor'], conf_mail.get('puerto', 25)) if conf_mail['usuario'] and conf_mail['clave']: self.smtp.ehlo() self.smtp.login(conf_mail['usuario'], conf_mail['clave']) self.smtp.sendmail(msg['From'], msg['To'], msg.as_string()) except Exception,e: self.error(u'Excepción',unicode(e)) if __name__ == '__main__': if len(sys.argv)>1 and not sys.argv[1].startswith("-"): CONFIG_FILE = sys.argv[1] config = SafeConfigParser() config.read(CONFIG_FILE) if not len(config.sections()): if os.path.exists(CONFIG_FILE): gui.alert(u"Error al cargar archivo de configuración: %s" % CONFIG_FILE, "PyRece: Imposible Continuar") else: gui.alert(u"No se encuentra archivo de configuración: %s" % CONFIG_FILE, "PyRece: Imposible Continuar") sys.exit(1) cert = config.get('WSAA','CERT') privatekey = config.get('WSAA','PRIVATEKEY') cuit = config.get('WSFEv1','CUIT') if config.has_option('WSFEv1','ENTRADA'): entrada = config.get('WSFEv1','ENTRADA') else: entrada = "" if not os.path.exists(entrada): entrada = "facturas.csv" if config.has_option('WSFEv1','SALIDA'): salida = config.get('WSFEv1','SALIDA') else: salida = "resultado.csv" if config.has_section('FACTURA'): conf_fact = dict(config.items('FACTURA')) else: conf_fact = {} conf_pdf = dict(config.items('PDF')) conf_mail = dict(config.items('MAIL')) if config.has_option('WSAA','URL') and not HOMO: wsaa_url = config.get('WSAA','URL') else: wsaa_url = wsaa.WSAAURL if config.has_option('WSFE','URL') and not HOMO: wsfe_url = config.get('WSFE','URL') else: wsfe_url = wsfe.WSFEURL if config.has_option('WSFEv1','URL') and not HOMO: wsfev1_url = config.get('WSFEv1','URL') else: wsfev1_url = wsfev1.WSDL if config.has_option('WSFEXv1','URL') and not HOMO: wsfexv1_url = config.get('WSFEXv1','URL') else: wsfexv1_url = wsfexv1.WSDL DEFAULT_WEBSERVICE = "wsfev1" if config.has_section('PYRECE'): DEFAULT_WEBSERVICE = config.get('PYRECE','WEBSERVICE') if config.has_section('PROXY'): proxy_dict = dict(("proxy_%s" % k,v) for k,v in config.items('PROXY')) proxy_dict['proxy_port'] = int(proxy_dict['proxy_port']) else: proxy_dict = {} c = PyRece() gui.main_loop() ```
[ { "content": "```python\nfrom django.conf.urls import url, include, patterns\nfrom django.contrib import admin\nfrom django.conf import settings\n\nhandler403 = 'core.views.forbidden'\nhandler404 = 'core.views.page_not_found'\nhandler500 = 'core.views.server_error'\n\nurlpatterns = patterns(\n 'core.views',\...
[ { "content": "<|memory_start|>```python\nfrom django.conf.urls import url, include, patterns\nfrom django.contrib import admin\nfrom django.conf import settings\n\nhandler403 = 'core.views.forbidden'\nhandler404 = 'core.views.page_not_found'\nhandler500 = 'core.views.server_error'\n\nurlpatterns = patterns(\n ...
```python from django.conf.urls import url, include, patterns from django.contrib import admin from django.conf import settings handler403 = 'core.views.forbidden' handler404 = 'core.views.page_not_found' handler500 = 'core.views.server_error' urlpatterns = patterns( 'core.views', # api urls - WARNING: Do NOT change this URL url(r'^api/', include('api.urls')), # gui urls url(r'^', include('gui.urls')), # sio urls url(r'^socket\.io/', include('sio.urls')), ) if settings.THIRD_PARTY_APPS_ENABLED: # Allow to overload ESDC CE URLs with third party app custom functionality. for app in settings.THIRD_PARTY_APPS: urlpatterns = patterns('', url(r'', include(app + '.urls')),) + urlpatterns if settings.DEBUG: urlpatterns = patterns( '', url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}), url(r'', include('django.contrib.staticfiles.urls')), # Django Admin URLs url(r'^' + settings.ADMIN_URL, include(admin.site.urls)), ) + urlpatterns ```
[ { "content": "```python\n# -*- coding: utf-8 -*-\n\nfrom unittest import mock\n\nimport jinja2\nimport pytest\n\nfrom wt import jinja\n\n\ndef describe_Registry():\n\n def must_properly_register_filter(jinja_registry):\n\n assert len(list(jinja_registry)) == 0\n\n def fltr(d):\n retu...
[ { "content": "<|memory_start|>```python\n# -*- coding: utf-8 -*-\n\nfrom unittest import mock\n\nimport jinja2\nimport pytest\n\nfrom wt import jinja\n\n\ndef describe_Registry():\n\n def must_properly_register_filter(jinja_registry):\n\n assert len(list(jinja_registry)) == 0\n\n def fltr(d):\n...
```python # -*- coding: utf-8 -*- from unittest import mock import jinja2 import pytest from wt import jinja def describe_Registry(): def must_properly_register_filter(jinja_registry): assert len(list(jinja_registry)) == 0 def fltr(d): return d res = jinja_registry.add(fltr) assert res is fltr assert fltr in jinja_registry def must_raise_value_error_if_filter_has_no_name(tmpdir): with mock.patch('wt.jinja.filters', jinja.Registry()): class Fltr(object): def __call__(self, text): return text jinja.filters.add(Fltr()) with pytest.raises(ValueError): jinja.get_env(str(tmpdir)) def must_raise_value_error_if_function_has_no_name(tmpdir): with mock.patch('wt.jinja.functions', jinja.Registry()): class Function(object): def __call__(self, text): return text jinja.functions.add(Function()) with pytest.raises(ValueError): jinja.get_env(str(tmpdir)) def must_properly_register_class_based_filter(jinja_registry): class Fltr(object): filter_name = 'class_based_filter' def __call__(self, text): return text fltr = Fltr() res = jinja_registry.add(fltr) assert isinstance(res, Fltr) assert fltr in jinja_registry def describe_Baseurl(): def must_return_concatenated_baseurl_and_url(): baseurl, url = '/foo', '/baz' u = jinja.Baseurl(baseurl) assert u(url) == '/foo/baz' def must_return_url_if_baseurl_is_None(): url = '/baz' u = jinja.Baseurl(None) assert u(url) == url def must_return_url_if_baseurl_is_empty(): url = '/baz' u = jinja.Baseurl('') assert u(url) == url def describe_get_env(): def must_return_jinja2_environment(jinja_env): assert isinstance(jinja_env, jinja2.Environment) def must_properly_register_helpers(jinja_env_with_helpers): assert 'demo_filter' in jinja_env_with_helpers.filters assert 'my_demo_fn' in jinja_env_with_helpers.globals CONTENT = """\ # H1 Hello, [world](http://example.com)! """ def must_use_markdown_function(template_with_markdown): content = template_with_markdown.render(content=CONTENT) assert 'Hello' in content and 'world' in content ```
[ { "content": "Output the full code verbatim (no extra comments):\n```python\n#!/usr/bin/env python\n# -------------------------------------------------------------------\n# File Name : create_dataset_events.py\n# Creation Date : 05-12-2016\n# Last Modified : Fri Jan 6 15:04:54 2017\n# Author: Thibaut Perol <tp...
[ { "content": "Output the full code verbatim (no extra comments):\n<|memory_start|>```python\n#!/usr/bin/env python\n# -------------------------------------------------------------------\n# File Name : create_dataset_events.py\n# Creation Date : 05-12-2016\n# Last Modified : Fri Jan 6 15:04:54 2017\n# Author: T...
```python #!/usr/bin/env python # ------------------------------------------------------------------- # File Name : create_dataset_events.py # Creation Date : 05-12-2016 # Last Modified : Fri Jan 6 15:04:54 2017 # Author: Thibaut Perol <tperol@g.harvard.edu> # ------------------------------------------------------------------- """Creates tfrecords dataset of events trace and their cluster_ids. This is done by loading a dir of .mseed and one catalog with the time stamps of the events and their cluster_id e.g., ./bin/preprocess/create_dataset_events.py \ --stream_dir data/streams \ --catalog data/50_clusters/catalog_with_cluster_ids.csv\ --output_dir data/50_clusters/tfrecords """ import os import numpy as np from quakenet.data_pipeline import DataWriter import tensorflow as tf from obspy.core import read from quakenet.data_io import load_catalog from obspy.core.utcdatetime import UTCDateTime from openquake.hazardlib.geo.geodetic import distance import fnmatch import json flags = tf.flags flags.DEFINE_string('stream_dir', None, 'path to the directory of streams to preprocess.') flags.DEFINE_string( 'catalog', None, 'path to the events catalog to use as labels.') flags.DEFINE_string('output_dir', None, 'path to the directory in which the tfrecords are saved') flags.DEFINE_bool("plot", False, "If we want the event traces to be plotted") flags.DEFINE_float( 'window_size', 10, 'size of the window samples (in seconds)') flags.DEFINE_float('v_mean', 5.0, 'mean velocity') flags.DEFINE_boolean("save_mseed",False, "save the windows in mseed format") FLAGS = flags.FLAGS def distance_to_station(lat, long, depth): # station GPS coordinates lat0 = 35.796570 long0 = -97.454860 depth0 = -0.333 # return distance of the event to the station return distance(long, lat, depth, long0, lat0, depth0) def preprocess_stream(stream): stream = stream.detrend('constant') return stream.normalize() def filter_catalog(cat): # Filter around Guthrie sequence cat = cat[(cat.latitude > 35.7) & (cat.latitude < 36) & (cat.longitude > -97.6) & (cat.longitude < -97.2)] return cat def get_travel_time(catalog): """Find the time between origin and propagation""" v_mean = FLAGS.v_mean coordinates = [(lat, lon, depth) for (lat, lon, depth) in zip(catalog.latitude, catalog.longitude, catalog.depth)] distances_to_station = [distance_to_station(lat, lon, depth) for (lat, lon, depth) in coordinates] travel_time = [distance/v_mean for distance in distances_to_station] return travel_time def write_json(metadata,output_metadata): with open(output_metadata, 'w') as outfile: json.dump(metadata, outfile) def main(_): stream_files = [file for file in os.listdir(FLAGS.stream_dir) if fnmatch.fnmatch(file, '*.mseed')] print "List of streams to anlayze", stream_files # Create dir to store tfrecords if not os.path.exists(FLAGS.output_dir): os.makedirs(FLAGS.output_dir) # Dictionary of nb of events per tfrecords metadata = {} output_metadata = os.path.join(FLAGS.output_dir,"metadata.json") # Load Catalog print "+ Loading Catalog" cat = load_catalog(FLAGS.catalog) cat = filter_catalog(cat) for stream_file in stream_files: # Load stream stream_path = os.path.join(FLAGS.stream_dir, stream_file) print "+ Loading Stream {}".format(stream_file) stream = read(stream_path) print '+ Preprocessing stream' stream = preprocess_stream(stream) # Filter catalog according to the loaded stream start_date = stream[0].stats.starttime end_date = stream[-1].stats.endtime print("-- Start Date={}, End Date={}".format(start_date, end_date)) filtered_catalog = cat[ ((cat.utc_timestamp >= start_date) & (cat.utc_timestamp < end_date))] # Propagation time from source to station travel_time = get_travel_time(filtered_catalog) # Write event waveforms and cluster_id in .tfrecords output_name = stream_file.split(".mseed")[0] + ".tfrecords" output_path = os.path.join(FLAGS.output_dir, output_name) writer = DataWriter(output_path) print("+ Creating tfrecords for {} events".format(filtered_catalog.shape[0])) # Loop over all events in the considered stream for event_n in range(filtered_catalog.shape[0]): event_time = filtered_catalog.utc_timestamp.values[event_n] event_time += travel_time[event_n] st_event = stream.slice(UTCDateTime(event_time), UTCDateTime(event_time) + FLAGS.window_size).copy() cluster_id = filtered_catalog.cluster_id.values[event_n] n_traces = len(st_event) # If there is not trace skip this waveform if n_traces == 0: continue n_samples = len(st_event[0].data) n_pts = st_event[0].stats.sampling_rate * FLAGS.window_size + 1 if (len(st_event) == 3) and (n_pts == n_samples): # Write tfrecords writer.write(st_event, cluster_id) # Save window and cluster_id if FLAGS.save_mseed: output_label = "label_{}_lat_{:.3f}_lon_{:.3f}.mseed".format( cluster_id, filtered_catalog.latitude.values[event_n], filtered_catalog.longitude.values[event_n]) output_mseed_dir = os.path.join(FLAGS.output_dir,"mseed") if not os.path.exists(output_mseed_dir): os.makedirs(output_mseed_dir) output_mseed = os.path.join(output_mseed_dir,output_label) st_event.write(output_mseed,format="MSEED") # Plot events if FLAGS.plot: trace = st_event[0] viz_dir = os.path.join( FLAGS.output_dir, "viz", stream_file.split(".mseed")[0]) if not os.path.exists(viz_dir): os.makedirs(viz_dir) trace.plot(outfile=os.path.join(viz_dir, "event_{}.png".format(event_n))) else: print "Missing waveform for event:", UTCDateTime(event_time) # Cleanup writer print("Number of events written={}".format(writer._written)) writer.close() # Write metadata metadata[stream_file.split(".mseed")[0]] = writer._written write_json(metadata, output_metadata) if __name__ == "__main__": tf.app.run() ```
[ { "content": "Repeat the code exactly:\n```python\n#!/usr/bin/env python\n\n\n\n\n##################################################\n## DEPENDENCIES\nimport sys\nimport os\nimport os.path\ntry:\n import builtins as builtin\nexcept ImportError:\n import __builtin__ as builtin\nfrom os.path import getmtime...
[ { "content": "Repeat the code exactly:\n<|memory_start|>```python\n#!/usr/bin/env python\n\n\n\n\n##################################################\n## DEPENDENCIES\nimport sys\nimport os\nimport os.path\ntry:\n import builtins as builtin\nexcept ImportError:\n import __builtin__ as builtin\nfrom os.path...
```python #!/usr/bin/env python ################################################## ## DEPENDENCIES import sys import os import os.path try: import builtins as builtin except ImportError: import __builtin__ as builtin from os.path import getmtime, exists import time import types from Cheetah.Version import MinCompatibleVersion as RequiredCheetahVersion from Cheetah.Version import MinCompatibleVersionTuple as RequiredCheetahVersionTuple from Cheetah.Template import Template from Cheetah.DummyTransaction import * from Cheetah.NameMapper import NotFound, valueForName, valueFromSearchList, valueFromFrameOrSearchList from Cheetah.CacheRegion import CacheRegion import Cheetah.Filters as Filters import Cheetah.ErrorCatchers as ErrorCatchers from urllib import quote ################################################## ## MODULE CONSTANTS VFFSL=valueFromFrameOrSearchList VFSL=valueFromSearchList VFN=valueForName currentTime=time.time __CHEETAH_version__ = '2.4.4' __CHEETAH_versionTuple__ = (2, 4, 4, 'development', 0) __CHEETAH_genTime__ = 1406885498.551486 __CHEETAH_genTimestamp__ = 'Fri Aug 1 18:31:38 2014' __CHEETAH_src__ = '/home/wslee2/models/5-wo/force1plus/openpli3.0/build-force1plus/tmp/work/mips32el-oe-linux/enigma2-plugin-extensions-openwebif-1+git5+3c0c4fbdb28d7153bf2140459b553b3d5cdd4149-r0/git/plugin/controllers/views/web/movielistm3u.tmpl' __CHEETAH_srcLastModified__ = 'Fri Aug 1 18:30:05 2014' __CHEETAH_docstring__ = 'Autogenerated by Cheetah: The Python-Powered Template Engine' if __CHEETAH_versionTuple__ < RequiredCheetahVersionTuple: raise AssertionError( 'This template was compiled with Cheetah version' ' %s. Templates compiled before version %s must be recompiled.'%( __CHEETAH_version__, RequiredCheetahVersion)) ################################################## ## CLASSES class movielistm3u(Template): ################################################## ## CHEETAH GENERATED METHODS def __init__(self, *args, **KWs): super(movielistm3u, self).__init__(*args, **KWs) if not self._CHEETAH__instanceInitialized: cheetahKWArgs = {} allowedKWs = 'searchList namespaces filter filtersLib errorCatcher'.split() for k,v in KWs.items(): if k in allowedKWs: cheetahKWArgs[k] = v self._initCheetahInstance(**cheetahKWArgs) def respond(self, trans=None): ## CHEETAH: main method generated for this template if (not trans and not self._CHEETAH__isBuffering and not callable(self.transaction)): trans = self.transaction # is None unless self.awake() was called if not trans: trans = DummyTransaction() _dummyTrans = True else: _dummyTrans = False write = trans.response().write SL = self._CHEETAH__searchList _filter = self._CHEETAH__currentFilter ######################################## ## START - generated method body write(u'''#EXTM3U #EXTVLCOPT--http-reconnect=true ''') for movie in VFFSL(SL,"movies",True): # generated from line 4, col 1 write(u'''#EXTINF:-1,: ''') _v = VFFSL(SL,"movie.filename_stripped",True) # u'$movie.filename_stripped' on line 5, col 14 if _v is not None: write(_filter(_v, rawExpr=u'$movie.filename_stripped')) # from line 5, col 14. write(u''' http://''') _v = VFFSL(SL,"host",True) # u'$host' on line 6, col 8 if _v is not None: write(_filter(_v, rawExpr=u'$host')) # from line 6, col 8. write(u'''/file?file=''') _v = VFFSL(SL,"quote",False)(VFFSL(SL,"movie.filename",True)) # u'$quote($movie.filename)' on line 6, col 24 if _v is not None: write(_filter(_v, rawExpr=u'$quote($movie.filename)')) # from line 6, col 24. write(u''' ''') ######################################## ## END - generated method body return _dummyTrans and trans.response().getvalue() or "" ################################################## ## CHEETAH GENERATED ATTRIBUTES _CHEETAH__instanceInitialized = False _CHEETAH_version = __CHEETAH_version__ _CHEETAH_versionTuple = __CHEETAH_versionTuple__ _CHEETAH_genTime = __CHEETAH_genTime__ _CHEETAH_genTimestamp = __CHEETAH_genTimestamp__ _CHEETAH_src = __CHEETAH_src__ _CHEETAH_srcLastModified = __CHEETAH_srcLastModified__ _mainCheetahMethod_for_movielistm3u= 'respond' ## END CLASS DEFINITION if not hasattr(movielistm3u, '_initCheetahAttributes'): templateAPIClass = getattr(movielistm3u, '_CHEETAH_templateClass', Template) templateAPIClass._addCheetahPlumbingCodeToClass(movielistm3u) # CHEETAH was developed by Tavis Rudd and Mike Orr # with code, advice and input from many other volunteers. # For more information visit http://www.CheetahTemplate.org/ ################################################## ## if run from command line: if __name__ == '__main__': from Cheetah.TemplateCmdLineIface import CmdLineIface CmdLineIface(templateObj=movielistm3u()).run() ```
[ { "content": "```python\n#----------------------------------------------------------------------\n# Purpose: This test compares k-means centers between H2O and MLlib.\n#----------------------------------------------------------------------\n\nimport sys\nsys.path.insert(1, \"../../\")\nimport h2o\nimport numpy...
[ { "content": "<|memory_start|>```python\n#----------------------------------------------------------------------\n# Purpose: This test compares k-means centers between H2O and MLlib.\n#----------------------------------------------------------------------\n\nimport sys\nsys.path.insert(1, \"../../\")\nimport h...
```python #---------------------------------------------------------------------- # Purpose: This test compares k-means centers between H2O and MLlib. #---------------------------------------------------------------------- import sys sys.path.insert(1, "../../") import h2o import numpy as np def kmeans_mllib(ip, port): h2o.init(ip, port) # Check if we are running inside the H2O network by seeing if we can touch # the namenode. running_inside_h2o = h2o.is_running_internal_to_h2o() if running_inside_h2o: hdfs_name_node = h2o.get_h2o_internal_hdfs_name_node() hdfs_cross_file = "/datasets/runit/BigCross.data" print "Import BigCross.data from HDFS" url = "hdfs://{0}{1}".format(hdfs_name_node, hdfs_cross_file) cross_h2o = h2o.import_frame(url) n = cross_h2o.nrow() err_mllib = np.genfromtxt(h2o.locate("smalldata/mllib_bench/bigcross_wcsse.csv"), delimiter=",", skip_header=1) ncent = [int(err_mllib[r][0]) for r in range(len(err_mllib))] for k in ncent: print "Run k-means++ with k = {0} and max_iterations = 10".format(k) cross_km = h2o.kmeans(training_frame = cross_h2o, x = cross_h2o, k = k, init = "PlusPlus", max_iterations = 10, standardize = False) clust_mllib = np.genfromtxt(h2o.locate("smalldata/mllib_bench/bigcross_centers_" + str(k) + ".csv"), delimiter=",").tolist() clust_h2o = cross_km.centers() # Sort in ascending order by first dimension for comparison purposes clust_mllib.sort(key=lambda x: x[0]) clust_h2o.sort(key=lambda x: x[0]) print "\nMLlib Cluster Centers:\n" print clust_mllib print "\nH2O Cluster Centers:\n" print clust_h2o wcsse_mllib = err_mllib[err_mllib[0:4,0].tolist().index(k)][1] wcsse_h2o = cross_km.tot_withinss() / n print "\nMLlib Average Within-Cluster SSE: \n".format(wcsse_mllib) print "H2O Average Within-Cluster SSE: \n".format(wcsse_h2o) assert wcsse_h2o == wcsse_mllib, "Expected mllib and h2o to get the same wcsse. Mllib got {0}, and H2O " \ "got {1}".format(wcsse_mllib, wcsse_h2o) if __name__ == "__main__": h2o.run_test(sys.argv, kmeans_mllib) ```
[ { "content": "Reconstruct the code exactly:\n```python\n__author__ = \"Christian Kongsgaard\"\n__license__ = 'MIT'\n\n# -------------------------------------------------------------------------------------------------------------------- #\n# IMPORTS\n\n# Modules\nimport pytest\nimport numpy as np\n\n# RiBuild M...
[ { "content": "Reconstruct the code exactly:\n<|memory_start|>```python\n__author__ = \"Christian Kongsgaard\"\n__license__ = 'MIT'\n\n# -------------------------------------------------------------------------------------------------------------------- #\n# IMPORTS\n\n# Modules\nimport pytest\nimport numpy as n...
```python __author__ = "Christian Kongsgaard" __license__ = 'MIT' # -------------------------------------------------------------------------------------------------------------------- # # IMPORTS # Modules import pytest import numpy as np # RiBuild Modules from delphin_6_automation.delphin_setup import weather_modeling from delphin_6_automation.file_parsing import weather_parser # -------------------------------------------------------------------------------------------------------------------- # # TEST WEATHER MODELS @pytest.mark.skip('Catch ration model is not implemented correctly') def test_rain_model_1(test_folder): rain = weather_parser.ccd_to_list(test_folder + '/weather/vertical_rain.ccd') wind_speed = weather_parser.ccd_to_list(test_folder + '/weather/wind_speed.ccd') wind_direction = weather_parser.ccd_to_list(test_folder + '/weather/wind_direction.ccd') wall_location = {'height': 5.0, 'width': 5.0} wdr = weather_modeling.driving_rain(rain, wind_direction, wind_speed, wall_location, 90, 0) assert rain == wdr def test_rain_model_2(test_folder): rain = weather_parser.ccd_to_list(test_folder + '/weather/vertical_rain.ccd') wind_speed = weather_parser.ccd_to_list(test_folder + '/weather/wind_speed.ccd') wind_direction = weather_parser.ccd_to_list(test_folder + '/weather/wind_direction.ccd') wall_location = {'height': 5.0, 'width': 5.0} wdr = weather_modeling.driving_rain(rain, wind_direction, wind_speed, wall_location, 90, 0, 1) assert rain == wdr def test_solar_radiation(test_folder): # TODO - Create some assertments diff_rad = np.array(weather_parser.ccd_to_list(test_folder + '/weather/diffuse_radiation.ccd')) dir_rad = np.array(weather_parser.ccd_to_list(test_folder + '/weather/direct_radiation.ccd')) radiation = diff_rad + dir_rad short_wave = weather_modeling.short_wave_radiation(radiation, -2.083, 57.167, 0, 230) ```
[ { "content": "Recreate the entire code block with identical formatting:\n```python\n# -*- coding: utf-8 -*-\n# Copyright (C) 2008-2010, 2013-2015 Rocky Bernstein <rocky@gnu.org>\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public Licen...
[ { "content": "Recreate the entire code block with identical formatting:\n<|memory_start|>```python\n# -*- coding: utf-8 -*-\n# Copyright (C) 2008-2010, 2013-2015 Rocky Bernstein <rocky@gnu.org>\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Gene...
```python # -*- coding: utf-8 -*- # Copyright (C) 2008-2010, 2013-2015 Rocky Bernstein <rocky@gnu.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 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/>. import inspect, linecache, sys, traceback, types import pyficache from repr import Repr from trepan import vprocessor as Mprocessor from trepan import exception as Mexcept, misc as Mmisc from trepan.lib import bytecode as Mbytecode, display as Mdisplay from trepan.lib import thred as Mthread from trepan.bwprocessor import location as Mlocation, msg as Mmsg def get_stack(f, t, botframe, proc_obj=None): """Return a stack of frames which the debugger will use for in showing backtraces and in frame switching. As such various frame that are really around may be excluded unless we are debugging the sebugger. Also we will add traceback frame on top if that exists.""" exclude_frame = lambda f: False if proc_obj: settings = proc_obj.debugger.settings if not settings['dbg_trepan']: exclude_frame = lambda f: \ proc_obj.core.ignore_filter.is_included(f) pass pass stack = [] if t and t.tb_frame is f: t = t.tb_next while f is not None: if exclude_frame(f): break # See commented alternative below stack.append((f, f.f_lineno)) # bdb has: # if f is botframe: break f = f.f_back pass stack.reverse() i = max(0, len(stack) - 1) while t is not None: stack.append((t.tb_frame, t.tb_lineno)) t = t.tb_next pass return stack, i def run_hooks(obj, hooks, *args): """Run each function in `hooks' with args""" for hook in hooks: if hook(obj, *args): return True pass return False def resolve_name(obj, command_name): if command_name not in obj.commands: return None return command_name # Default settings for command processor method call DEFAULT_PROC_OPTS = { # A list of debugger initialization files to read on first command # loop entry. Often this something like [~/.trepanrc] which the # front-end sets. 'initfile_list' : [] } class BWProcessor(Mprocessor.Processor): def __init__(self, core_obj, opts=None): Mprocessor.Processor.__init__(self, core_obj) self.response = {'errs': [], 'msg': []} self.continue_running = False # True if we should leave command loop self.cmd_instances = self._populate_commands() self.cmd_name = '' # command name before alias or # macro resolution self.current_command = '' # Current command getting run self.debug_nest = 1 self.display_mgr = Mdisplay.DisplayMgr() self.intf = core_obj.debugger.intf self.last_command = None # Initially a no-op self.precmd_hooks = [] # If not: # self.location = lambda : print_location(self) self.preloop_hooks = [] self.postcmd_hooks = [] self._populate_cmd_lists() # Stop only if line/file is different from last time self.different_line = None # These values updated on entry. Set initial values. self.curframe = None self.event = None self.event_arg = None self.frame = None self.list_lineno = 0 # Create a custom safe Repr instance and increase its maxstring. # The default of 30 truncates error messages too easily. self._repr = Repr() self._repr.maxstring = 100 self._repr.maxother = 60 self._repr.maxset = 10 self._repr.maxfrozen = 10 self._repr.array = 10 self._saferepr = self._repr.repr self.stack = [] self.thread_name = None self.frame_thread_name = None return def add_preloop_hook(self, hook, position=-1, nodups = True): if hook in self.preloop_hooks: return False self.preloop_hooks.insert(position, hook) return True def adjust_frame(self, pos, absolute_pos): """Adjust stack frame by pos positions. If absolute_pos then pos is an absolute number. Otherwise it is a relative number. A negative number indexes from the other end.""" if not self.curframe: Mmsg.errmsg(self, "No stack.") return # Below we remove any negativity. At the end, pos will be # the new value of self.curindex. if absolute_pos: if pos >= 0: pos = len(self.stack)-pos-1 else: pos = -pos-1 else: pos += self.curindex if pos < 0: Mmsg.errmsg(self, "Adjusting would put us beyond the oldest frame.") return elif pos >= len(self.stack): Mmsg.errmsg(self, "Adjusting would put us beyond the newest frame.") return self.curindex = pos self.curframe = self.stack[self.curindex][0] self.print_location() self.list_lineno = None return # To be overridden in derived debuggers def defaultFile(self): """Produce a reasonable default.""" filename = self.curframe.f_code.co_filename # Consider using is_exec_stmt(). I just don't understand # the conditions under which the below test is true. if filename == '<string>' and self.debugger.mainpyfile: filename = self.debugger.mainpyfile pass return filename def event_processor(self, frame, event, event_arg, prompt='Trepan'): 'command event processor: reading a commands do something with them.' self.frame = frame self.event = event self.event_arg = event_arg filename = frame.f_code.co_filename lineno = frame.f_lineno line = linecache.getline(filename, lineno, frame.f_globals) if not line: opts = {'output': 'plain', 'reload_on_change': self.settings('reload'), 'strip_nl': False} line = pyficache.getline(filename, lineno, opts) self.current_source_text = line if self.settings('skip') is not None: if Mbytecode.is_def_stmt(line, frame): return True if Mbytecode.is_class_def(line, frame): return True pass self.thread_name = Mthread.current_thread_name() self.frame_thread_name = self.thread_name self.process_commands() return True def forget(self): """ Remove memory of state variables set in the command processor """ self.stack = [] self.curindex = 0 self.curframe = None self.thread_name = None self.frame_thread_name = None return def eval(self, arg): """Eval string arg in the current frame context.""" try: return eval(arg, self.curframe.f_globals, self.curframe.f_locals) except: t, v = sys.exc_info()[:2] if isinstance(t, str): exc_type_name = t pass else: exc_type_name = t.__name__ Mmsg.errmsg(self, str("%s: %s" % (exc_type_name, arg))) raise return None # Not reached def exec_line(self, line): if self.curframe: local_vars = self.curframe.f_locals global_vars = self.curframe.f_globals else: local_vars = None # FIXME: should probably have place where the # user can store variables inside the debug session. # The setup for this should be elsewhere. Possibly # in interaction. global_vars = None try: code = compile(line + '\n', '"%s"' % line, 'single') exec code in global_vars, local_vars except: t, v = sys.exc_info()[:2] if isinstance(t, types.StringType): exc_type_name = t else: exc_type_name = t.__name__ Mmsg.errmsg(self, '%s: %s' % (str(exc_type_name), str(v))) pass return def ok_for_running(self, cmd_obj, name, cmd_hash): '''We separate some of the common debugger command checks here: whether it makes sense to run the command in this execution state, if the command has the right number of arguments and so on. ''' if hasattr(cmd_obj, 'execution_set'): if not (self.core.execution_status in cmd_obj.execution_set): part1 = ("Command '%s' is not available for execution " "status:" % name) Mmsg.errmsg(self, Mmisc. wrapped_lines(part1, self.core.execution_status, self.debugger.settings['width'])) return False pass if self.frame is None and cmd_obj.need_stack: self.intf[-1].errmsg("Command '%s' needs an execution stack." % name) return False return True def process_commands(self): """Handle debugger commands.""" if self.core.execution_status != 'No program': self.setup() Mlocation.print_location(self, self.event) pass leave_loop = run_hooks(self, self.preloop_hooks) self.continue_running = False while not leave_loop: try: run_hooks(self, self.precmd_hooks) # bdb had a True return to leave loop. # A more straight-forward way is to set # instance variable self.continue_running. leave_loop = self.process_command() if leave_loop or self.continue_running: break except EOFError: # If we have stacked interfaces, pop to the next # one. If this is the last one however, we'll # just stick with that. FIXME: Possibly we should # check to see if we are interactive. and not # leave if that's the case. Is this the right # thing? investigate and fix. if len(self.debugger.intf) > 1: del self.debugger.intf[-1] self.last_command = '' else: if self.debugger.intf[-1].output: self.debugger.intf[-1].output.writeline('Leaving') raise Mexcept.DebuggerQuit pass break pass pass return run_hooks(self, self.postcmd_hooks) def process_command(self): # process command self.response = {'errs': [], 'msg': []} cmd_hash = self.intf[-1].read_command() # FIXME: put this into a routine if isinstance(cmd_hash, types.DictType): Mmsg.errmsg(self, "invalid input, expecting a hash: %s" % cmd_hash, {'set_name': True}) self.intf[-1].msg(self.response) return False if 'command' not in cmd_hash: Mmsg.errmsg(self, "invalid input, expecting a 'command' key: %s" % cmd_hash, {'set_name': True}) self.intf[-1].msg(self.response) return False self.cmd_name = cmd_hash['command'] cmd_name = resolve_name(self, self.cmd_name) if cmd_name: cmd_obj = self.commands[cmd_name] if self.ok_for_running(cmd_obj, cmd_name, cmd_hash): try: self.response['name'] = cmd_name result = cmd_obj.run(cmd_hash) self.intf[-1].msg(self.response) if result: return result except (Mexcept.DebuggerQuit, Mexcept.DebuggerRestart, SystemExit): # Let these exceptions propagate through raise except: Mmsg.errmsg(self, "INTERNAL ERROR: " + traceback.format_exc()) pass pass else: self.undefined_cmd(cmd_name) pass pass return False def remove_preloop_hook(self, hook): try: position = self.preloop_hooks.index(hook) except ValueError: return False del self.preloop_hooks[position] return True def setup(self): """Initialization done before entering the debugger-command loop. In particular we set up the call stack used for local variable lookup and frame/up/down commands. We return True if we should NOT enter the debugger-command loop.""" self.forget() if self.settings('dbg_trepan'): self.frame = inspect.currentframe() pass if self.event in ['exception', 'c_exception']: exc_type, exc_value, exc_traceback = self.event_arg else: _, _, exc_traceback = (None, None, None,) # NOQA pass if self.frame or exc_traceback: self.stack, self.curindex = \ get_stack(self.frame, exc_traceback, None, self) self.curframe = self.stack[self.curindex][0] self.thread_name = Mthread.current_thread_name() else: self.stack = self.curframe = \ self.botframe = None pass if self.curframe: self.list_lineno = \ max(1, inspect.getlineno(self.curframe)) else: self.list_lineno = None pass # if self.execRcLines()==1: return True return False def undefined_cmd(self, cmd): """Error message when a command doesn't exist""" Mmsg.errmsg(self, 'Undefined command: "%s". Try "help".' % cmd) return def _populate_commands(self): """ Create an instance of each of the debugger commands. Commands are found by importing files in the directory 'command'. Some files are excluded via an array set in __init__. For each of the remaining files, we import them and scan for class names inside those files and for each class name, we will create an instance of that class. The set of DebuggerCommand class instances form set of possible debugger commands.""" cmd_instances = [] from trepan.bwprocessor import command as Mcommand eval_cmd_template = 'command_mod.%s(self)' for mod_name in Mcommand.__modules__: import_name = "command." + mod_name try: command_mod = getattr(__import__(import_name), mod_name) except: print('Error importing %s: %s' % (mod_name, sys.exc_info()[0])) continue classnames = [ tup[0] for tup in inspect.getmembers(command_mod, inspect.isclass) if ('DebuggerCommand' != tup[0] and tup[0].endswith('Command')) ] for classname in classnames: eval_cmd = eval_cmd_template % classname try: instance = eval(eval_cmd) cmd_instances.append(instance) except: print ('Error loading %s from %s: %s' % (classname, mod_name, sys.exc_info()[0])) pass pass pass return cmd_instances def _populate_cmd_lists(self): """ Populate self.commands""" self.commands = {} for cmd_instance in self.cmd_instances: cmd_name = cmd_instance.name self.commands[cmd_name] = cmd_instance pass return pass # Demo it if __name__=='__main__': from trepan.interfaces import bullwinkle as Mbullwinkle class Debugger: def __init__(self): self.intf = [Mbullwinkle.BWInterface()] self.settings = {'dbg_trepan': True, 'reload': False} pass class MockCore: def filename(self, fn): return fn def canonic_filename(self, frame): return frame.f_code.co_filename def __init__(self): self.debugger = Debugger() return pass core = MockCore() bwproc = BWProcessor(core) print 'commands:' commands = bwproc.commands.keys() commands.sort() print commands print resolve_name(bwproc, 'quit') # print '-' * 10 # print_source_line(sys.stdout.write, 100, 'source_line_test.py') # print '-' * 10 bwproc.frame = sys._getframe() bwproc.setup() # print # print '-' * 10 Mlocation.print_location(bwproc) # print 'Removing non-existing quit hook: ', bwproc.remove_preloop_hook(fn) # bwproc.add_preloop_hook(fn) # print bwproc.preloop_hooks # print 'Removed existing quit hook: ', bwproc.remove_preloop_hook(fn) pass ```
[ { "content": "```python\n# This file is part of the myhdl library, a Python package for using\n# Python as a Hardware Description Language.\n#\n# Copyright (C) 2003-2008 Jan Decaluwe\n#\n# The myhdl library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Lesser Gene...
[ { "content": "<|memory_start|>```python\n# This file is part of the myhdl library, a Python package for using\n# Python as a Hardware Description Language.\n#\n# Copyright (C) 2003-2008 Jan Decaluwe\n#\n# The myhdl library is free software; you can redistribute it and/or\n# modify it under the terms of the...
```python # This file is part of the myhdl library, a Python package for using # Python as a Hardware Description Language. # # Copyright (C) 2003-2008 Jan Decaluwe # # The myhdl 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ myhdl _extractHierarchy module. """ from __future__ import absolute_import import inspect import re import string import sys import ast from ._errors import ExtractHierarchyError, ToVerilogError, ToVHDLError from ._enum import EnumItemType from ._Signal import _Signal, _isListOfSigs from ._compat import integer_types from ._getcellvars import _getCellVars from ._misc import _isGenSeq from ._resolverefs import _resolveRefs from ._util import _flatten, _genfunc, _isTupleOfInts, _isTupleOfFloats _profileFunc = None class _error: pass _error.NoInstances = "No instances found" _error.InconsistentHierarchy = "Inconsistent hierarchy - are all" \ " instances returned ?" _error.InconsistentToplevel = "Inconsistent top level %s for %s - should be 1" class _Constant(object): def __init__(self, orig_name, value): self.name = None self.orig_name = orig_name self.instance = None self.value = value self.used = False class _Instance(object): __slots__ = ['level', 'obj', 'subs', 'constdict', 'sigdict', 'memdict', 'romdict', 'name', 'func', 'frame', ] def __init__(self, level, obj, subs, constdict, sigdict, memdict, romdict, func, frame): self.level = level self.obj = obj self.subs = subs self.constdict = constdict self.sigdict = sigdict self.memdict = memdict self.romdict = romdict self.func = func self.frame = frame self.name = None _memInfoMap = {} class _MemInfo(object): __slots__ = ['mem', 'name', 'elObj', 'depth', 'type', '_used', '_driven', '_read'] def __init__(self, mem): self.mem = mem self.name = None self.depth = len(mem) self.elObj = mem[0] self.type = None self._used = False self._driven = None self._read = False @property def used(self): return self._used @used.setter def used(self, val): self._used = bool(val) for s in self.mem: s._used = bool(val) def _clear(self): self._driven = None self._read = False for el in self.mem: el._clear() def _getMemInfo(mem): return _memInfoMap[id(mem)] def _makeMemInfo(mem): key = id(mem) if key not in _memInfoMap: _memInfoMap[key] = _MemInfo(mem) return _memInfoMap[key] def _isMem(mem): return id(mem) in _memInfoMap _romInfoMap = {} class _RomInfo(object): __slots__ = ['mem', 'orig_name', 'name', 'elObj', 'depth', 'type', '_used'] def __init__(self, orig_name, mem): self.mem = mem self.orig_name = orig_name self.name = None self.depth = len(mem) if (self.depth > 0): if isinstance(mem[0], integer_types): for elObj in mem: if elObj < 0: break else: elObj = mem[0] self.elObj = elObj else: self.elObj = None self.type = None self._used = False @property def used(self): return self._used @used.setter def used(self, val): self._used = bool(val) def _getRomInfo(mem): return _romInfoMap[id(mem)] def _makeRomInfo(n, mem): key = id(mem) if key not in _romInfoMap: _romInfoMap[key] = _RomInfo(n, mem) return _romInfoMap[key] def _isRom(mem): return id(mem) in _romInfoMap _userCodeMap = {'verilog': {}, 'vhdl': {} } class _UserCode(object): __slots__ = ['code', 'namespace', 'funcname', 'func', 'sourcefile', 'sourceline'] def __init__(self, code, namespace, funcname, func, sourcefile, sourceline): self.code = code self.namespace = namespace self.sourcefile = sourcefile self.func = func self.funcname = funcname self.sourceline = sourceline def __str__(self): try: code = self._interpolate() except: tipe, value, _ = sys.exc_info() info = "in file %s, function %s starting on line %s:\n " % \ (self.sourcefile, self.funcname, self.sourceline) msg = "%s: %s" % (tipe, value) self.raiseError(msg, info) code = "\n%s\n" % code return code def _interpolate(self): return string.Template(self.code).substitute(self.namespace) class _UserCodeDepr(_UserCode): def _interpolate(self): return self.code % self.namespace class _UserVerilogCode(_UserCode): def raiseError(self, msg, info): raise ToVerilogError("Error in user defined Verilog code", msg, info) class _UserVhdlCode(_UserCode): def raiseError(self, msg, info): raise ToVHDLError("Error in user defined VHDL code", msg, info) class _UserVerilogCodeDepr(_UserVerilogCode, _UserCodeDepr): pass class _UserVhdlCodeDepr(_UserVhdlCode, _UserCodeDepr): pass class _UserVerilogInstance(_UserVerilogCode): def __str__(self): args = inspect.getargspec(self.func)[0] s = "%s %s(" % (self.funcname, self.code) sep = '' for arg in args: if arg in self.namespace and isinstance(self.namespace[arg], _Signal): signame = self.namespace[arg]._name s += sep sep = ',' s += "\n .%s(%s)" % (arg, signame) s += "\n);\n\n" return s class _UserVhdlInstance(_UserVhdlCode): def __str__(self): args = inspect.getargspec(self.func)[0] s = "%s: entity work.%s(MyHDL)\n" % (self.code, self.funcname) s += " port map (" sep = '' for arg in args: if arg in self.namespace and isinstance(self.namespace[arg], _Signal): signame = self.namespace[arg]._name s += sep sep = ',' s += "\n %s=>%s" % (arg, signame) s += "\n );\n\n" return s def _addUserCode(specs, arg, funcname, func, frame): classMap = { '__verilog__': _UserVerilogCodeDepr, '__vhdl__': _UserVhdlCodeDepr, 'verilog_code': _UserVerilogCode, 'vhdl_code': _UserVhdlCode, 'verilog_instance': _UserVerilogInstance, 'vhdl_instance': _UserVhdlInstance, } namespace = frame.f_globals.copy() namespace.update(frame.f_locals) sourcefile = inspect.getsourcefile(frame) sourceline = inspect.getsourcelines(frame)[1] for hdl in _userCodeMap: oldspec = "__%s__" % hdl codespec = "%s_code" % hdl instancespec = "%s_instance" % hdl spec = None # XXX add warning logic if instancespec in specs: spec = instancespec elif codespec in specs: spec = codespec elif oldspec in specs: spec = oldspec if spec: assert id(arg) not in _userCodeMap[hdl] code = specs[spec] _userCodeMap[hdl][id(arg)] = classMap[spec](code, namespace, funcname, func, sourcefile, sourceline) class _CallFuncVisitor(object): def __init__(self): self.linemap = {} def visitAssign(self, node): if isinstance(node.expr, ast.Call): self.lineno = None self.visit(node.expr) self.linemap[self.lineno] = node.lineno def visitName(self, node): self.lineno = node.lineno class _HierExtr(object): def __init__(self, name, dut, *args, **kwargs): global _profileFunc _memInfoMap.clear() for hdl in _userCodeMap: _userCodeMap[hdl].clear() self.skipNames = ('always_comb', 'instance', 'always_seq', '_always_seq_decorator', 'always', '_always_decorator', 'instances', 'processes', 'posedge', 'negedge') self.skip = 0 self.hierarchy = hierarchy = [] self.absnames = absnames = {} self.level = 0 _profileFunc = self.extractor sys.setprofile(_profileFunc) _top = dut(*args, **kwargs) sys.setprofile(None) if not hierarchy: raise ExtractHierarchyError(_error.NoInstances) self.top = _top # streamline hierarchy hierarchy.reverse() # walk the hierarchy to define relative and absolute names names = {} top_inst = hierarchy[0] obj, subs = top_inst.obj, top_inst.subs names[id(obj)] = name absnames[id(obj)] = name if not top_inst.level == 1: raise ExtractHierarchyError(_error.InconsistentToplevel % (top_inst.level, name)) for inst in hierarchy: obj, subs = inst.obj, inst.subs if id(obj) not in names: raise ExtractHierarchyError(_error.InconsistentHierarchy) inst.name = names[id(obj)] tn = absnames[id(obj)] for sn, so in subs: names[id(so)] = sn absnames[id(so)] = "%s_%s" % (tn, sn) if isinstance(so, (tuple, list)): for i, soi in enumerate(so): sni = "%s_%s" % (sn, i) names[id(soi)] = sni absnames[id(soi)] = "%s_%s_%s" % (tn, sn, i) def extractor(self, frame, event, arg): if event == "call": funcname = frame.f_code.co_name # skip certain functions if funcname in self.skipNames: self.skip += 1 if not self.skip: self.level += 1 elif event == "return": funcname = frame.f_code.co_name func = frame.f_globals.get(funcname) if func is None: # Didn't find a func in the global space, try the local "self" # argument and see if it has a method called *funcname* obj = frame.f_locals.get('self') if hasattr(obj, funcname): func = getattr(obj, funcname) if not self.skip: isGenSeq = _isGenSeq(arg) if isGenSeq: specs = {} for hdl in _userCodeMap: spec = "__%s__" % hdl if spec in frame.f_locals and frame.f_locals[spec]: specs[spec] = frame.f_locals[spec] spec = "%s_code" % hdl if func and hasattr(func, spec) and \ getattr(func, spec): specs[spec] = getattr(func, spec) spec = "%s_instance" % hdl if func and hasattr(func, spec) and \ getattr(func, spec): specs[spec] = getattr(func, spec) if specs: _addUserCode(specs, arg, funcname, func, frame) # building hierarchy only makes sense if there are generators if isGenSeq and arg: constdict = {} sigdict = {} memdict = {} romdict = {} symdict = frame.f_globals.copy() symdict.update(frame.f_locals) cellvars = [] # All nested functions will be in co_consts if func: local_gens = [] consts = func.__code__.co_consts for item in _flatten(arg): genfunc = _genfunc(item) if genfunc.__code__ in consts: local_gens.append(item) if local_gens: cellvarlist = _getCellVars(symdict, local_gens) cellvars.extend(cellvarlist) objlist = _resolveRefs(symdict, local_gens) cellvars.extend(objlist) for n, v in symdict.items(): # extract signals and memories # also keep track of whether they are used in # generators only include objects that are used in # generators if isinstance(v, _Signal): sigdict[n] = v if n in cellvars: v._markUsed() elif isinstance(v, (integer_types, float, EnumItemType)): constdict[n] = _Constant(n, v) elif _isListOfSigs(v): m = _makeMemInfo(v) memdict[n] = m if n in cellvars: m._used = True elif _isTupleOfInts(v): m = _makeRomInfo(n, v) romdict[n] = m if n in cellvars: m._used = True elif _isTupleOfFloats(v): m = _makeRomInfo(n, v) romdict[n] = m if n in cellvars: m._used = True subs = [] for n, sub in frame.f_locals.items(): for elt in _inferArgs(arg): if elt is sub: subs.append((n, sub)) inst = _Instance(self.level, arg, subs, constdict, sigdict, memdict, romdict, func, frame) self.hierarchy.append(inst) self.level -= 1 if funcname in self.skipNames: self.skip -= 1 def _inferArgs(arg): c = [arg] if isinstance(arg, (tuple, list)): c += list(arg) return c ```
[ { "content": "Repeat the full code snippet:\n```python\nimport sys\nimport pylab as plt\nsys.path.append(\"/mnt/brand01-00/mbrand_analysis/lib/matplotlib_venn/\")\nfrom venn3 import venn3, venn3_circles\nfrom venn_util import venn3_unweighted, venn2_unweighted\nimport itertools\nfrom subsetClass import subsetW...
[ { "content": "Repeat the full code snippet:\n<|memory_start|>```python\nimport sys\nimport pylab as plt\nsys.path.append(\"/mnt/brand01-00/mbrand_analysis/lib/matplotlib_venn/\")\nfrom venn3 import venn3, venn3_circles\nfrom venn_util import venn3_unweighted, venn2_unweighted\nimport itertools\nfrom subsetClas...
```python import sys import pylab as plt sys.path.append("/mnt/brand01-00/mbrand_analysis/lib/matplotlib_venn/") from venn3 import venn3, venn3_circles from venn_util import venn3_unweighted, venn2_unweighted import itertools from subsetClass import subsetWraper class buildVennDiagram(): def __init__(self,data): self.data=data def __call__(self,title,seqs,labels): if len(seqs)>3: return 0 x=[] for i in range(len(seqs)): x.extend([i for i in itertools.combinations(seqs,i+1)]) combs=[] for i in x: A=list(i) A.append("intersection") A=A[::-1] B=self.nots(i,seqs) if B: B.append("union") B=B[::-1] B=["not",B] A.append(B) temp=subsetWraper(self.data,A,i).count() combs.append([temp,str(i)]) self.venn_build(title,[i[0]for i in combs],labels) def vennBuild(self,title,bis,labels): if len(bis)>3: v = venn3_unweighted(subsets=([bis[i] for i in [0,1,3,2,4,5,6]]),set_labels=(labels[0],labels[1],labels[2])) v.get_label_by_id('100').set_text(str(bis[2])) v.get_label_by_id('010').set_text(str(bis[1])) v.get_label_by_id('001').set_text(str(bis[0])) elif len(bis)==3: v = venn2_unweighted(subsets=(bis),set_labels=(labels[0],labels[1])) v.get_label_by_id('10').set_text(str(bis[0])) v.get_label_by_id('01').set_text(str(bis[1])) plt.title(title) plt.savefig(title+'venn.png') plt.close() def nots(self,val,seqs): return [i for i in seqs if not i in val] ```
[ { "content": "Here is the snippet:\n```python\nfrom __future__ import print_function\n\nimport os\n\nfrom IPython.display import display, HTML, Javascript\n\nleaflet_css = '//cdn.leafletjs.com/leaflet-0.7.2/leaflet.css'\n# leaftlet_js = \"//cdn.leafletjs.com/leaflet-0.7.2/leaflet\"\n\n# leaflet_draw_js = ['//cd...
[ { "content": "Here is the snippet:\n<|memory_start|>```python\nfrom __future__ import print_function\n\nimport os\n\nfrom IPython.display import display, HTML, Javascript\n\nleaflet_css = '//cdn.leafletjs.com/leaflet-0.7.2/leaflet.css'\n# leaftlet_js = \"//cdn.leafletjs.com/leaflet-0.7.2/leaflet\"\n\n# leaflet_...
```python from __future__ import print_function import os from IPython.display import display, HTML, Javascript leaflet_css = '//cdn.leafletjs.com/leaflet-0.7.2/leaflet.css' # leaftlet_js = "//cdn.leafletjs.com/leaflet-0.7.2/leaflet" # leaflet_draw_js = ['//cdnjs.cloudflare.com/ajax/libs/leaflet.draw/0.2.3/leaflet.draw-src.js', # '//cdnjs.cloudflare.com/ajax/libs/leaflet.draw/0.2.3/leaflet.draw.js'] # leaflet_draw_png = ['//cdnjs.cloudflare.com/ajax/libs/leaflet.draw/0.2.3/images/spritesheet-2x.png', # '//cdnjs.cloudflare.com/ajax/libs/leaflet.draw/0.2.3/images/spritesheet.png'] leaflet_draw_css = '//cdnjs.cloudflare.com/ajax/libs/leaflet.draw/0.2.3/leaflet.draw.css' def get_static_path(): return os.path.join(os.path.split(__file__)[0], 'static') css_template = '<link rel="stylesheet" href="{}" />' def display_css(url): display(HTML(css_template.format(url))) def initialize_notebook(leaflet_css=leaflet_css, leaflet_js=leaflet_css): display_css(leaflet_css) display_css(leaflet_draw_css) for filename in ['leaflet.js']: with open(os.path.join(get_static_path(), filename)) as f: display(Javascript(f.read())) ```
[ { "content": "```python\n# Copyright 2020 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required ...
[ { "content": "<|memory_start|>```python\n# Copyright 2020 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# ...
```python # 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. """Graph processing script.""" import os from absl import app from absl import flags from absl import logging import networkx as nx import pandas as pd from utils import graph_filter_with_degree from utils import load_graph_from_edgelist_csv FLAGS = flags.FLAGS flags.DEFINE_string( 'g_file', '../proj_Data/cat_data/test3/sr_timespan_post_graph-00000-of-00001.csv', 'raw graph edgelist csv file') flags.DEFINE_integer('low', 40, 'low degree threshold') flags.DEFINE_integer('high', 80, 'high degree threshold') flags.DEFINE_string('data_file', '', 'raw data path') flags.DEFINE_string('filename', '', 'graph filename') flags.DEFINE_string('save_path', '', 'graph save path') def main(_): df = pd.read_csv(FLAGS.data_file) author_set = set(df['author'].unique()) graph = load_graph_from_edgelist_csv(FLAGS.g_file) logging.info('Original Graph size: %d nodes, %d edges', graph.number_of_nodes(), graph.number_of_edges()) graph = graph_filter_with_degree(graph, FLAGS.low, FLAGS.high, author_set) logging.info('Filtered Graph size: %d nodes, %d edges', graph.number_of_nodes(), graph.number_of_edges()) nx.write_gpickle(graph, os.path.join( FLAGS.save_path, FLAGS.filename + '%s_%s.gpickle' % (FLAGS.low, FLAGS.high))) logging.info('Saved graph.') if __name__ == '__main__': app.run(main) ```
[ { "content": "Provide a verbatim copy of the code:\n```python\n# Copyright 2020 Google LLC. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http:/...
[ { "content": "Provide a verbatim copy of the code:\n<|memory_start|>```python\n# Copyright 2020 Google LLC. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\...
```python # Copyright 2020 Google LLC. 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 tfx.orchestration.portable.cache_utils.""" import os import tensorflow as tf from tfx.dsl.io import fileio from tfx.orchestration import metadata from tfx.orchestration.portable import cache_utils from tfx.orchestration.portable import execution_publish_utils from tfx.orchestration.portable.mlmd import context_lib from tfx.proto.orchestration import executable_spec_pb2 from tfx.proto.orchestration import pipeline_pb2 from tfx.types import standard_artifacts from tfx.utils import test_case_utils from google.protobuf import text_format from ml_metadata.proto import metadata_store_pb2 class CacheUtilsTest(test_case_utils.TfxTest): def setUp(self): super().setUp() self._connection_config = metadata_store_pb2.ConnectionConfig() self._connection_config.sqlite.SetInParent() self._module_file_path = os.path.join(self.tmp_dir, 'module_file') self._input_artifacts = {'input_examples': [standard_artifacts.Examples()]} self._output_artifacts = {'output_models': [standard_artifacts.Model()]} self._parameters = {'module_file': self._module_file_path} self._module_file_content = 'module content' self._pipeline_node = text_format.Parse( """ node_info { id: "my_id" } """, pipeline_pb2.PipelineNode()) self._pipeline_info = pipeline_pb2.PipelineInfo(id='pipeline_id') self._executor_spec = text_format.Parse( """ class_path: "my.class.path" """, executable_spec_pb2.PythonClassExecutableSpec()) def _get_cache_context(self, metadata_handler, custom_pipeline_node=None, custom_pipeline_info=None, executor_spec=None, custom_input_artifacts=None, custom_output_artifacts=None, custom_parameters=None, custom_module_content=None): with fileio.open(self._module_file_path, 'w+') as f: f.write(custom_module_content or self._module_file_content) return cache_utils.get_cache_context( metadata_handler, custom_pipeline_node or self._pipeline_node, custom_pipeline_info or self._pipeline_info, executor_spec=(executor_spec or self._executor_spec), input_artifacts=(custom_input_artifacts or self._input_artifacts), output_artifacts=(custom_output_artifacts or self._output_artifacts), parameters=(custom_parameters or self._parameters)) def testGetCacheContext(self): with metadata.Metadata(connection_config=self._connection_config) as m: cache_context = self._get_cache_context(m) [context_from_mlmd] = m.store.get_contexts() self.assertProtoPartiallyEquals( cache_context, context_from_mlmd, ignored_fields=[ 'create_time_since_epoch', 'last_update_time_since_epoch' ]) def testGetCacheContextTwiceSameArgs(self): with metadata.Metadata(connection_config=self._connection_config) as m: self._get_cache_context(m) self._get_cache_context(m) # Same args should not create a new cache context. self.assertLen(m.store.get_contexts(), 1) def testGetCacheContextTwiceDifferentOutputUri(self): with metadata.Metadata(connection_config=self._connection_config) as m: self._get_cache_context(m) output_model_different_uri = standard_artifacts.Model() output_model_different_uri.uri = 'diff_uri' self._get_cache_context( m, custom_output_artifacts={ 'output_models': [output_model_different_uri] }) # Only different output uri should not create a new cache context. self.assertLen(m.store.get_contexts(), 1) def testGetCacheContextTwiceDifferentOutputs(self): with metadata.Metadata(connection_config=self._connection_config) as m: self._get_cache_context(m) self._get_cache_context( m, custom_output_artifacts={'k': [standard_artifacts.Model()]}) # Different output skeleton will result in a new cache context. self.assertLen(m.store.get_contexts(), 2) def testGetCacheContextTwiceDifferentInputs(self): with metadata.Metadata(connection_config=self._connection_config) as m: self._get_cache_context(m) self._get_cache_context( m, custom_input_artifacts={'k': [standard_artifacts.Examples(),]}) # Different input artifacts will result in new cache context. self.assertLen(m.store.get_contexts(), 2) def testGetCacheContextTwiceDifferentParameters(self): with metadata.Metadata(connection_config=self._connection_config) as m: self._get_cache_context(m) self._get_cache_context(m, custom_parameters={'new_prop': 'value'}) # Different parameters will result in new cache context. self.assertLen(m.store.get_contexts(), 2) def testGetCacheContextTwiceDifferentModuleContent(self): with metadata.Metadata(connection_config=self._connection_config) as m: self._get_cache_context(m) self._get_cache_context(m, custom_module_content='new module content') # Different module file content will result in new cache context. self.assertLen(m.store.get_contexts(), 2) def testGetCacheContextTwiceDifferentPipelineInfo(self): with metadata.Metadata(connection_config=self._connection_config) as m: self._get_cache_context(m) self._get_cache_context( m, custom_pipeline_info=pipeline_pb2.PipelineInfo(id='new_id')) # Different pipeline info will result in new cache context. self.assertLen(m.store.get_contexts(), 2) def testGetCacheContextTwiceDifferentNodeInfo(self): with metadata.Metadata(connection_config=self._connection_config) as m: self._get_cache_context(m) self._get_cache_context( m, custom_pipeline_node=text_format.Parse( """ node_info { id: "new_node_id" } """, pipeline_pb2.PipelineNode())) # Different executor spec will result in new cache context. self.assertLen(m.store.get_contexts(), 2) def testGetCacheContextTwiceDifferentExecutorSpec(self): with metadata.Metadata(connection_config=self._connection_config) as m: self._get_cache_context(m) self._get_cache_context( m, executor_spec=text_format.Parse( """ class_path: "new.class.path" """, executable_spec_pb2.PythonClassExecutableSpec())) # Different executor spec will result in new cache context. self.assertLen(m.store.get_contexts(), 2) def testGetCachedOutputArtifacts(self): # Output artifacts that will be used by the first execution with the same # cache key. output_model_one = standard_artifacts.Model() output_model_one.uri = 'model_one' output_model_two = standard_artifacts.Model() output_model_two.uri = 'model_two' output_example_one = standard_artifacts.Examples() output_example_one.uri = 'example_one' # Output artifacts that will be used by the second execution with the same # cache key. output_model_three = standard_artifacts.Model() output_model_three.uri = 'model_three' output_model_four = standard_artifacts.Model() output_model_four.uri = 'model_four' output_example_two = standard_artifacts.Examples() output_example_two.uri = 'example_two' output_models_key = 'output_models' output_examples_key = 'output_examples' with metadata.Metadata(connection_config=self._connection_config) as m: cache_context = context_lib.register_context_if_not_exists( m, context_lib.CONTEXT_TYPE_EXECUTION_CACHE, 'cache_key') cached_output = cache_utils.get_cached_outputs(m, cache_context) # No succeed execution is associate with this context yet, so the cached # output is None self.assertIsNone(cached_output) execution_one = execution_publish_utils.register_execution( m, metadata_store_pb2.ExecutionType(name='my_type'), [cache_context]) execution_publish_utils.publish_succeeded_execution( m, execution_one.id, [cache_context], output_artifacts={ output_models_key: [output_model_one, output_model_two], output_examples_key: [output_example_one] }) execution_two = execution_publish_utils.register_execution( m, metadata_store_pb2.ExecutionType(name='my_type'), [cache_context]) output_artifacts = execution_publish_utils.publish_succeeded_execution( m, execution_two.id, [cache_context], output_artifacts={ output_models_key: [output_model_three, output_model_four], output_examples_key: [output_example_two] }) # The cached output got should be the artifacts produced by the most # recent execution under the given cache context. cached_output = cache_utils.get_cached_outputs(m, cache_context) self.assertLen(cached_output, 2) self.assertLen(cached_output[output_models_key], 2) self.assertLen(cached_output[output_examples_key], 1) self.assertProtoPartiallyEquals( cached_output[output_models_key][0].mlmd_artifact, output_artifacts[output_models_key][0].mlmd_artifact, ignored_fields=[ 'create_time_since_epoch', 'last_update_time_since_epoch' ]) self.assertProtoPartiallyEquals( cached_output[output_models_key][1].mlmd_artifact, output_artifacts[output_models_key][1].mlmd_artifact, ignored_fields=[ 'create_time_since_epoch', 'last_update_time_since_epoch' ]) self.assertProtoPartiallyEquals( cached_output[output_examples_key][0].mlmd_artifact, output_artifacts[output_examples_key][0].mlmd_artifact, ignored_fields=[ 'create_time_since_epoch', 'last_update_time_since_epoch' ]) def testGetCachedOutputArtifactsForNodesWithNoOuput(self): with metadata.Metadata(connection_config=self._connection_config) as m: cache_context = context_lib.register_context_if_not_exists( m, context_lib.CONTEXT_TYPE_EXECUTION_CACHE, 'cache_key') cached_output = cache_utils.get_cached_outputs(m, cache_context) # No succeed execution is associate with this context yet, so the cached # output is None. self.assertIsNone(cached_output) execution_one = execution_publish_utils.register_execution( m, metadata_store_pb2.ExecutionType(name='my_type'), [cache_context]) execution_publish_utils.publish_succeeded_execution( m, execution_one.id, [cache_context]) cached_output = cache_utils.get_cached_outputs(m, cache_context) # A succeed execution is associate with this context, so the cached # output is not None but an empty dict. self.assertIsNotNone(cached_output) self.assertEmpty(cached_output) if __name__ == '__main__': tf.test.main() ```
[ { "content": "Replicate the code snippet exactly, without paraphrasing or reformatting:\n```python\n# This Source Code Form is subject to the terms of the Mozilla Public\n# License, v. 2.0. If a copy of the MPL was not distributed with this\n# file, You can obtain one at http://mozilla.org/MPL/2.0/.\n\nimport o...
[ { "content": "Replicate the code snippet exactly, without paraphrasing or reformatting:\n<|memory_start|>```python\n# This Source Code Form is subject to the terms of the Mozilla Public\n# License, v. 2.0. If a copy of the MPL was not distributed with this\n# file, You can obtain one at http://mozilla.org/MPL/2...
```python # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import os import sys from metadata import MetadataUpdateRunner from sync import SyncFromUpstreamRunner from tree import GitTree, HgTree, NoVCSTree from .. import environment as env from base import Step, StepRunner, exit_clean, exit_unclean from state import State def setup_paths(sync_path): sys.path.insert(0, sync_path) from tools import localpaths class LoadConfig(Step): """Step for loading configuration from the ini file and kwargs.""" provides = ["sync", "paths", "metadata_path", "tests_path"] def create(self, state): state.sync = {"remote_url": state.kwargs["remote_url"], "branch": state.kwargs["branch"], "path": state.kwargs["sync_path"]} state.paths = state.kwargs["test_paths"] state.tests_path = state.paths["/"]["tests_path"] state.metadata_path = state.paths["/"]["metadata_path"] assert state.tests_path.startswith("/") class LoadTrees(Step): """Step for creating a Tree for the local copy and a GitTree for the upstream sync.""" provides = ["local_tree", "sync_tree"] def create(self, state): if os.path.exists(state.sync["path"]): sync_tree = GitTree(root=state.sync["path"]) else: sync_tree = None if GitTree.is_type(): local_tree = GitTree() elif HgTree.is_type(): local_tree = HgTree() else: local_tree = NoVCSTree() state.update({"local_tree": local_tree, "sync_tree": sync_tree}) class SyncFromUpstream(Step): """Step that synchronises a local copy of the code with upstream.""" def create(self, state): if not state.kwargs["sync"]: return if not state.sync_tree: os.mkdir(state.sync["path"]) state.sync_tree = GitTree(root=state.sync["path"]) kwargs = state.kwargs with state.push(["sync", "paths", "metadata_path", "tests_path", "local_tree", "sync_tree"]): state.target_rev = kwargs["rev"] state.no_patch = kwargs["no_patch"] state.suite_name = kwargs["suite_name"] runner = SyncFromUpstreamRunner(self.logger, state) runner.run() class UpdateMetadata(Step): """Update the expectation metadata from a set of run logs""" def create(self, state): if not state.kwargs["run_log"]: return kwargs = state.kwargs with state.push(["local_tree", "sync_tree", "paths", "serve_root"]): state.run_log = kwargs["run_log"] state.ignore_existing = kwargs["ignore_existing"] state.no_patch = kwargs["no_patch"] state.suite_name = kwargs["suite_name"] runner = MetadataUpdateRunner(self.logger, state) runner.run() class UpdateRunner(StepRunner): """Runner for doing an overall update.""" steps = [LoadConfig, LoadTrees, SyncFromUpstream, UpdateMetadata] class WPTUpdate(object): def __init__(self, logger, runner_cls=UpdateRunner, **kwargs): """Object that controls the running of a whole wptupdate. :param runner_cls: Runner subclass holding the overall list of steps to run. :param kwargs: Command line arguments """ self.runner_cls = runner_cls self.serve_root = kwargs["test_paths"]["/"]["tests_path"] if not kwargs["sync"]: setup_paths(self.serve_root) else: setup_paths(kwargs["sync_path"]) self.state = State(logger) self.kwargs = kwargs self.logger = logger def run(self, **kwargs): if self.kwargs["abort"]: self.abort() return exit_clean if not self.kwargs["continue"] and not self.state.is_empty(): self.logger.error("Found existing state. Run with --continue to resume or --abort to clear state") return exit_unclean if self.kwargs["continue"]: if self.state.is_empty(): self.logger.error("No sync in progress?") return exit_clean self.kwargs = self.state.kwargs else: self.state.kwargs = self.kwargs self.state.serve_root = self.serve_root update_runner = self.runner_cls(self.logger, self.state) rv = update_runner.run() if rv in (exit_clean, None): self.state.clear() return rv def abort(self): self.state.clear() ```
[ { "content": "Provide an exact copy of the source code:\n```python\n# -*- coding: utf-8 -*-\nfrom django.core.files.base import ContentFile\nimport os\nfrom photologue.models import Photo, PhotoSizeCache\nfrom photologue.tests.helpers import PhotologueBaseTest, SQUARE_IMAGE_PATH, PORTRAIT_IMAGE_PATH\n\nclass Im...
[ { "content": "Provide an exact copy of the source code:\n<|memory_start|>```python\n# -*- coding: utf-8 -*-\nfrom django.core.files.base import ContentFile\nimport os\nfrom photologue.models import Photo, PhotoSizeCache\nfrom photologue.tests.helpers import PhotologueBaseTest, SQUARE_IMAGE_PATH, PORTRAIT_IMAGE_...
```python # -*- coding: utf-8 -*- from django.core.files.base import ContentFile import os from photologue.models import Photo, PhotoSizeCache from photologue.tests.helpers import PhotologueBaseTest, SQUARE_IMAGE_PATH, PORTRAIT_IMAGE_PATH class ImageResizeTest(PhotologueBaseTest): def setUp(self): super(ImageResizeTest, self).setUp() self.pp = Photo(title='portrait', title_slug='portrait' ) self.pp.image.save(os.path.basename(PORTRAIT_IMAGE_PATH), ContentFile(open(PORTRAIT_IMAGE_PATH, 'rb').read())) self.pp.save() self.ps = Photo(title='square', title_slug='square', ) self.ps.image.save(os.path.basename(SQUARE_IMAGE_PATH), ContentFile(open(SQUARE_IMAGE_PATH, 'rb').read())) self.ps.save() def tearDown(self): super(ImageResizeTest, self).tearDown() self.pp.delete() self.ps.delete() def test_resize_to_fit(self): self.assertEquals(self.pl.get_test_size(), (100, 75)) self.assertEquals(self.pp.get_test_size(), (75, 100)) self.assertEquals(self.ps.get_test_size(), (100, 100)) def test_resize_to_fit_width(self): self.s.size = (100, 0) self.s.save() self.assertEquals(self.pl.get_test_size(), (100, 75)) self.assertEquals(self.pp.get_test_size(), (100, 133)) self.assertEquals(self.ps.get_test_size(), (100, 100)) def test_resize_to_fit_width_enlarge(self): self.s.size = (400, 0) self.s.upscale = True self.s.save() self.assertEquals(self.pl.get_test_size(), (400, 300)) self.assertEquals(self.pp.get_test_size(), (400, 533)) self.assertEquals(self.ps.get_test_size(), (400, 400)) def test_resize_to_fit_height(self): self.s.size = (0, 100) self.s.save() self.assertEquals(self.pl.get_test_size(), (133, 100)) self.assertEquals(self.pp.get_test_size(), (75, 100)) self.assertEquals(self.ps.get_test_size(), (100, 100)) def test_resize_to_fit_height_enlarge(self): self.s.size = (0, 400) self.s.upscale = True self.s.save() self.assertEquals(self.pl.get_test_size(), (533, 400)) self.assertEquals(self.pp.get_test_size(), (300, 400)) self.assertEquals(self.ps.get_test_size(), (400, 400)) def test_resize_and_crop(self): self.s.crop = True self.s.save() self.assertEquals(self.pl.get_test_size(), self.s.size) self.assertEquals(self.pp.get_test_size(), self.s.size) self.assertEquals(self.ps.get_test_size(), self.s.size) def test_resize_rounding_to_fit(self): self.s.size = (113, 113) self.s.save() self.assertEquals(self.pl.get_test_size(), (113, 85)) self.assertEquals(self.pp.get_test_size(), (85, 113)) self.assertEquals(self.ps.get_test_size(), (113, 113)) def test_resize_rounding_cropped(self): self.s.size = (113, 113) self.s.crop = True self.s.save() self.assertEquals(self.pl.get_test_size(), self.s.size) self.assertEquals(self.pp.get_test_size(), self.s.size) self.assertEquals(self.ps.get_test_size(), self.s.size) def test_resize_one_dimension_width(self): self.s.size = (100, 150) self.s.save() self.assertEquals(self.pl.get_test_size(), (100, 75)) def test_resize_one_dimension_height(self): self.s.size = (200, 75) self.s.save() self.assertEquals(self.pl.get_test_size(), (100, 75)) def test_resize_no_upscale(self): self.s.size = (1000, 1000) self.s.save() self.assertEquals(self.pl.get_test_size(), (200, 150)) def test_resize_no_upscale_mixed_height(self): self.s.size = (400, 75) self.s.save() self.assertEquals(self.pl.get_test_size(), (100, 75)) def test_resize_no_upscale_mixed_width(self): self.s.size = (100, 300) self.s.save() self.assertEquals(self.pl.get_test_size(), (100, 75)) def test_resize_no_upscale_crop(self): self.s.size = (1000, 1000) self.s.crop = True self.s.save() self.assertEquals(self.pl.get_test_size(), (1000, 1000)) def test_resize_upscale(self): self.s.size = (1000, 1000) self.s.upscale = True self.s.save() self.assertEquals(self.pl.get_test_size(), (1000, 750)) self.assertEquals(self.pp.get_test_size(), (750, 1000)) self.assertEquals(self.ps.get_test_size(), (1000, 1000)) class PhotoSizeCacheTest(PhotologueBaseTest): def test(self): cache = PhotoSizeCache() self.assertEqual(cache.sizes['test'], self.s) ```
[ { "content": "Recreate the original code text:\n```python\n# -*- coding: utf-8 -*-\n# <Lettuce - Behaviour Driven Development for python>\n# Copyright (C) <2010-2012> Gabriel Falcão <gabriel@nacaolivre.org>\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the ...
[ { "content": "Recreate the original code text:\n<|memory_start|>```python\n# -*- coding: utf-8 -*-\n# <Lettuce - Behaviour Driven Development for python>\n# Copyright (C) <2010-2012> Gabriel Falcão <gabriel@nacaolivre.org>\n#\n# This program is free software: you can redistribute it and/or modify\n# it under t...
```python # -*- coding: utf-8 -*- # <Lettuce - Behaviour Driven Development for python> # Copyright (C) <2010-2012> Gabriel Falcão <gabriel@nacaolivre.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 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/>. import os import random import lettuce from mock import Mock, patch from sure import expect from StringIO import StringIO from os.path import dirname, join, abspath from nose.tools import assert_equals, with_setup, assert_raises from lettuce.fs import FeatureLoader from lettuce.core import Feature, fs, StepDefinition from lettuce.terrain import world from lettuce import Runner from tests.asserts import assert_lines from tests.asserts import prepare_stderr from tests.asserts import prepare_stdout from tests.asserts import assert_stderr_lines from tests.asserts import assert_stdout_lines from tests.asserts import assert_stderr_lines_with_traceback from tests.asserts import assert_stdout_lines_with_traceback current_dir = abspath(dirname(__file__)) lettuce_dir = abspath(dirname(lettuce.__file__)) ojoin = lambda *x: join(current_dir, 'output_features', *x) sjoin = lambda *x: join(current_dir, 'syntax_features', *x) tjoin = lambda *x: join(current_dir, 'tag_features', *x) bjoin = lambda *x: join(current_dir, 'bg_features', *x) lettuce_path = lambda *x: fs.relpath(join(lettuce_dir, *x)) call_line = StepDefinition.__call__.im_func.func_code.co_firstlineno + 5 def joiner(callback, name): return callback(name, "%s.feature" % name) feature_name = lambda name: joiner(ojoin, name) syntax_feature_name = lambda name: joiner(sjoin, name) tag_feature_name = lambda name: joiner(tjoin, name) bg_feature_name = lambda name: joiner(bjoin, name) @with_setup(prepare_stderr) def test_try_to_import_terrain(): "Runner tries to import terrain, but has a nice output when it fail" sandbox_path = ojoin('..', 'sandbox') original_path = abspath(".") os.chdir(sandbox_path) try: import lettuce reload(lettuce) raise AssertionError('The runner should raise ImportError !') except SystemExit: assert_stderr_lines_with_traceback( 'Lettuce has tried to load the conventional environment module ' '"terrain"\nbut it has errors, check its contents and ' 'try to run lettuce again.\n\nOriginal traceback below:\n\n' "Traceback (most recent call last):\n" ' File "%(lettuce_core_file)s", line 44, in <module>\n' ' terrain = fs.FileSystem._import("terrain")\n' ' File "%(lettuce_fs_file)s", line 63, in _import\n' ' module = imp.load_module(name, fp, pathname, description)\n' ' File "%(terrain_file)s", line 18\n' ' it is here just to cause a syntax error\n' " ^\n" 'SyntaxError: invalid syntax\n' % { 'lettuce_core_file': abspath(join(lettuce_dir, '__init__.py')), 'lettuce_fs_file': abspath(join(lettuce_dir, 'fs.py')), 'terrain_file': abspath(lettuce_path('..', 'tests', 'functional', 'sandbox', 'terrain.py')), } ) finally: os.chdir(original_path) def test_feature_representation_without_colors(): "Feature represented without colors" feature_file = ojoin('..', 'simple_features', '1st_feature_dir', 'some.feature') feature = Feature.from_file(feature_file) assert_lines( feature.represented(), "Feature: Addition # tests/functional/simple_features/1st_feature_dir/some.feature:5\n" " In order to avoid silly mistakes # tests/functional/simple_features/1st_feature_dir/some.feature:6\n" " As a math idiot # tests/functional/simple_features/1st_feature_dir/some.feature:7\n" " I want to be told the sum of two numbers # tests/functional/simple_features/1st_feature_dir/some.feature:8\n" ) def test_scenario_outline_representation_without_colors(): "Scenario Outline represented without colors" feature_file = ojoin('..', 'simple_features', '1st_feature_dir', 'some.feature') feature = Feature.from_file(feature_file) assert_equals( feature.scenarios[0].represented(), " Scenario Outline: Add two numbers # tests/functional/simple_features/1st_feature_dir/some.feature:10\n" ) def test_scenario_representation_without_colors(): "Scenario represented without colors" feature_file = ojoin('runner_features', 'first.feature') feature = Feature.from_file(feature_file) assert_equals( feature.scenarios[0].represented(), " Scenario: Do nothing # tests/functional/output_features/runner_features/first.feature:6\n" ) def test_undefined_step_represent_string(): "Undefined step represented without colors" feature_file = ojoin('runner_features', 'first.feature') feature = Feature.from_file(feature_file) step = feature.scenarios[0].steps[0] assert_equals( step.represent_string(step.sentence), " Given I do nothing # tests/functional/output_features/runner_features/first.feature:7\n" ) assert_equals( step.represent_string("foo bar"), " foo bar # tests/functional/output_features/runner_features/first.feature:7\n" ) def test_defined_step_represent_string(): "Defined step represented without colors" feature_file = ojoin('runner_features', 'first.feature') feature_dir = ojoin('runner_features') loader = FeatureLoader(feature_dir) world._output = StringIO() world._is_colored = False loader.find_and_load_step_definitions() feature = Feature.from_file(feature_file) step = feature.scenarios[0].steps[0] step.run(True) assert_equals( step.represent_string(step.sentence), " Given I do nothing # tests/functional/output_features/runner_features/dumb_steps.py:6\n" ) @with_setup(prepare_stdout) def test_output_with_success_colorless2(): "Testing the colorless output of a successful feature" runner = Runner(join(abspath(dirname(__file__)), 'output_features', 'runner_features'), verbosity=3) runner.run() assert_stdout_lines( "\n" "Feature: Dumb feature # tests/functional/output_features/runner_features/first.feature:1\n" " In order to test success # tests/functional/output_features/runner_features/first.feature:2\n" " As a programmer # tests/functional/output_features/runner_features/first.feature:3\n" " I want to see that the output is green # tests/functional/output_features/runner_features/first.feature:4\n" "\n" " Scenario: Do nothing # tests/functional/output_features/runner_features/first.feature:6\n" " Given I do nothing # tests/functional/output_features/runner_features/dumb_steps.py:6\n" "\n" "1 feature (1 passed)\n" "1 scenario (1 passed)\n" "1 step (1 passed)\n" ) @with_setup(prepare_stdout) def test_output_with_success_colorless(): "A feature with two scenarios should separate the two scenarios with a new line (in colorless mode)." runner = Runner(join(abspath(dirname(__file__)), 'output_features', 'many_successful_scenarios'), verbosity=3) runner.run() assert_stdout_lines( "\n" "Feature: Dumb feature # tests/functional/output_features/many_successful_scenarios/first.feature:1\n" " In order to test success # tests/functional/output_features/many_successful_scenarios/first.feature:2\n" " As a programmer # tests/functional/output_features/many_successful_scenarios/first.feature:3\n" " I want to see that the output is green # tests/functional/output_features/many_successful_scenarios/first.feature:4\n" "\n" " Scenario: Do nothing # tests/functional/output_features/many_successful_scenarios/first.feature:6\n" " Given I do nothing # tests/functional/output_features/many_successful_scenarios/dumb_steps.py:6\n" "\n" " Scenario: Do nothing (again) # tests/functional/output_features/many_successful_scenarios/first.feature:9\n" " Given I do nothing (again) # tests/functional/output_features/many_successful_scenarios/dumb_steps.py:6\n" "\n" "1 feature (1 passed)\n" "2 scenarios (2 passed)\n" "2 steps (2 passed)\n" ) @with_setup(prepare_stdout) def test_output_with_success_colorful(): "Testing the output of a successful feature" runner = Runner(join(abspath(dirname(__file__)), 'output_features', 'runner_features'), verbosity=4) runner.run() assert_stdout_lines( "\n" "\033[1;37mFeature: Dumb feature \033[1;30m# tests/functional/output_features/runner_features/first.feature:1\033[0m\n" "\033[1;37m In order to test success \033[1;30m# tests/functional/output_features/runner_features/first.feature:2\033[0m\n" "\033[1;37m As a programmer \033[1;30m# tests/functional/output_features/runner_features/first.feature:3\033[0m\n" "\033[1;37m I want to see that the output is green \033[1;30m# tests/functional/output_features/runner_features/first.feature:4\033[0m\n" "\n" "\033[1;37m Scenario: Do nothing \033[1;30m# tests/functional/output_features/runner_features/first.feature:6\033[0m\n" "\033[1;30m Given I do nothing \033[1;30m# tests/functional/output_features/runner_features/dumb_steps.py:6\033[0m\n" "\033[A\033[1;32m Given I do nothing \033[1;30m# tests/functional/output_features/runner_features/dumb_steps.py:6\033[0m\n" "\n" "\033[1;37m1 feature (\033[1;32m1 passed\033[1;37m)\033[0m\n" "\033[1;37m1 scenario (\033[1;32m1 passed\033[1;37m)\033[0m\n" "\033[1;37m1 step (\033[1;32m1 passed\033[1;37m)\033[0m\n" ) @with_setup(prepare_stdout) def test_output_with_success_colorful_newline(): "A feature with two scenarios should separate the two scenarios with a new line (in color mode)." runner = Runner(join(abspath(dirname(__file__)), 'output_features', 'many_successful_scenarios'), verbosity=4) runner.run() assert_stdout_lines( "\n" "\033[1;37mFeature: Dumb feature \033[1;30m# tests/functional/output_features/many_successful_scenarios/first.feature:1\033[0m\n" "\033[1;37m In order to test success \033[1;30m# tests/functional/output_features/many_successful_scenarios/first.feature:2\033[0m\n" "\033[1;37m As a programmer \033[1;30m# tests/functional/output_features/many_successful_scenarios/first.feature:3\033[0m\n" "\033[1;37m I want to see that the output is green \033[1;30m# tests/functional/output_features/many_successful_scenarios/first.feature:4\033[0m\n" "\n" "\033[1;37m Scenario: Do nothing \033[1;30m# tests/functional/output_features/many_successful_scenarios/first.feature:6\033[0m\n" "\033[1;30m Given I do nothing \033[1;30m# tests/functional/output_features/many_successful_scenarios/dumb_steps.py:6\033[0m\n" "\033[A\033[1;32m Given I do nothing \033[1;30m# tests/functional/output_features/many_successful_scenarios/dumb_steps.py:6\033[0m\n" "\n" "\033[1;37m Scenario: Do nothing (again) \033[1;30m# tests/functional/output_features/many_successful_scenarios/first.feature:9\033[0m\n" "\033[1;30m Given I do nothing (again) \033[1;30m# tests/functional/output_features/many_successful_scenarios/dumb_steps.py:6\033[0m\n" "\033[A\033[1;32m Given I do nothing (again) \033[1;30m# tests/functional/output_features/many_successful_scenarios/dumb_steps.py:6\033[0m\n" "\n" "\033[1;37m1 feature (\033[1;32m1 passed\033[1;37m)\033[0m\n" "\033[1;37m2 scenarios (\033[1;32m2 passed\033[1;37m)\033[0m\n" "\033[1;37m2 steps (\033[1;32m2 passed\033[1;37m)\033[0m\n" ) @with_setup(prepare_stdout) def test_output_with_success_colorless_many_features(): "Testing the output of many successful features" runner = Runner(join(abspath(dirname(__file__)), 'output_features', 'many_successful_features'), verbosity=3) runner.run() assert_stdout_lines( "\n" "Feature: First feature, of many # tests/functional/output_features/many_successful_features/one.feature:1\n" " In order to make lettuce more robust # tests/functional/output_features/many_successful_features/one.feature:2\n" " As a programmer # tests/functional/output_features/many_successful_features/one.feature:3\n" " I want to test its output on many features # tests/functional/output_features/many_successful_features/one.feature:4\n" "\n" " Scenario: Do nothing # tests/functional/output_features/many_successful_features/one.feature:6\n" " Given I do nothing # tests/functional/output_features/many_successful_features/dumb_steps.py:6\n" " Then I see that the test passes # tests/functional/output_features/many_successful_features/dumb_steps.py:8\n" "\n" "Feature: Second feature, of many # tests/functional/output_features/many_successful_features/two.feature:1\n" " I just want to see it green :) # tests/functional/output_features/many_successful_features/two.feature:2\n" "\n" " Scenario: Do nothing # tests/functional/output_features/many_successful_features/two.feature:4\n" " Given I do nothing # tests/functional/output_features/many_successful_features/dumb_steps.py:6\n" " Then I see that the test passes # tests/functional/output_features/many_successful_features/dumb_steps.py:8\n" "\n" "2 features (2 passed)\n" "2 scenarios (2 passed)\n" "4 steps (4 passed)\n" ) @with_setup(prepare_stdout) def test_output_with_success_colorful_many_features(): "Testing the colorful output of many successful features" runner = Runner(join(abspath(dirname(__file__)), 'output_features', 'many_successful_features'), verbosity=4) runner.run() assert_stdout_lines( "\n" "\033[1;37mFeature: First feature, of many \033[1;30m# tests/functional/output_features/many_successful_features/one.feature:1\033[0m\n" "\033[1;37m In order to make lettuce more robust \033[1;30m# tests/functional/output_features/many_successful_features/one.feature:2\033[0m\n" "\033[1;37m As a programmer \033[1;30m# tests/functional/output_features/many_successful_features/one.feature:3\033[0m\n" "\033[1;37m I want to test its output on many features \033[1;30m# tests/functional/output_features/many_successful_features/one.feature:4\033[0m\n" "\n" "\033[1;37m Scenario: Do nothing \033[1;30m# tests/functional/output_features/many_successful_features/one.feature:6\033[0m\n" "\033[1;30m Given I do nothing \033[1;30m# tests/functional/output_features/many_successful_features/dumb_steps.py:6\033[0m\n" "\033[A\033[1;32m Given I do nothing \033[1;30m# tests/functional/output_features/many_successful_features/dumb_steps.py:6\033[0m\n" "\033[1;30m Then I see that the test passes \033[1;30m# tests/functional/output_features/many_successful_features/dumb_steps.py:8\033[0m\n" "\033[A\033[1;32m Then I see that the test passes \033[1;30m# tests/functional/output_features/many_successful_features/dumb_steps.py:8\033[0m\n" "\n" "\033[1;37mFeature: Second feature, of many \033[1;30m# tests/functional/output_features/many_successful_features/two.feature:1\033[0m\n" "\033[1;37m I just want to see it green :) \033[1;30m# tests/functional/output_features/many_successful_features/two.feature:2\033[0m\n" "\n" "\033[1;37m Scenario: Do nothing \033[1;30m# tests/functional/output_features/many_successful_features/two.feature:4\033[0m\n" "\033[1;30m Given I do nothing \033[1;30m# tests/functional/output_features/many_successful_features/dumb_steps.py:6\033[0m\n" "\033[A\033[1;32m Given I do nothing \033[1;30m# tests/functional/output_features/many_successful_features/dumb_steps.py:6\033[0m\n" "\033[1;30m Then I see that the test passes \033[1;30m# tests/functional/output_features/many_successful_features/dumb_steps.py:8\033[0m\n" "\033[A\033[1;32m Then I see that the test passes \033[1;30m# tests/functional/output_features/many_successful_features/dumb_steps.py:8\033[0m\n" "\n" "\033[1;37m2 features (\033[1;32m2 passed\033[1;37m)\033[0m\n" "\033[1;37m2 scenarios (\033[1;32m2 passed\033[1;37m)\033[0m\n" "\033[1;37m4 steps (\033[1;32m4 passed\033[1;37m)\033[0m\n" ) @with_setup(prepare_stdout) def test_output_when_could_not_find_features(): "Testing the colorful output of many successful features" path = fs.relpath(join(abspath(dirname(__file__)), 'no_features', 'unexistent-folder')) runner = Runner(path, verbosity=4) runner.run() assert_stdout_lines( '\033[1;31mOops!\033[0m\n' '\033[1;37mcould not find features at \033[1;33m./%s\033[0m\n' % path ) @with_setup(prepare_stdout) def test_output_when_could_not_find_features_colorless(): "Testing the colorful output of many successful features colorless" path = fs.relpath(join(abspath(dirname(__file__)), 'no_features', 'unexistent-folder')) runner = Runner(path, verbosity=3) runner.run() assert_stdout_lines( 'Oops!\n' 'could not find features at ./%s\n' % path ) @with_setup(prepare_stdout) def test_output_when_could_not_find_features_verbosity_level_2(): "Testing the colorful output of many successful features colorless" path = fs.relpath(join(abspath(dirname(__file__)), 'no_features', 'unexistent-folder')) runner = Runner(path, verbosity=2) runner.run() assert_stdout_lines( 'Oops!\n' 'could not find features at ./%s\n' % path ) @with_setup(prepare_stdout) def test_output_with_success_colorless_with_table(): "Testing the colorless output of success with table" runner = Runner(feature_name('success_table'), verbosity=3) runner.run() assert_stdout_lines( '\n' 'Feature: Table Success # tests/functional/output_features/success_table/success_table.feature:1\n' '\n' ' Scenario: Add two numbers ♥ # tests/functional/output_features/success_table/success_table.feature:2\n' ' Given I have 0 bucks # tests/functional/output_features/success_table/success_table_steps.py:28\n' ' And that I have these items: # tests/functional/output_features/success_table/success_table_steps.py:32\n' ' | name | price |\n' ' | Porsche | 200000 |\n' ' | Ferrari | 400000 |\n' ' When I sell the "Ferrari" # tests/functional/output_features/success_table/success_table_steps.py:42\n' ' Then I have 400000 bucks # tests/functional/output_features/success_table/success_table_steps.py:28\n' ' And my garage contains: # tests/functional/output_features/success_table/success_table_steps.py:47\n' ' | name | price |\n' ' | Porsche | 200000 |\n' '\n' '1 feature (1 passed)\n' '1 scenario (1 passed)\n' '5 steps (5 passed)\n' ) @with_setup(prepare_stdout) def test_output_with_success_colorful_with_table(): "Testing the colorful output of success with table" runner = Runner(feature_name('success_table'), verbosity=4) runner.run() assert_stdout_lines( '\n' '\033[1;37mFeature: Table Success \033[1;30m# tests/functional/output_features/success_table/success_table.feature:1\033[0m\n' '\n' '\033[1;37m Scenario: Add two numbers ♥ \033[1;30m# tests/functional/output_features/success_table/success_table.feature:2\033[0m\n' '\033[1;30m Given I have 0 bucks \033[1;30m# tests/functional/output_features/success_table/success_table_steps.py:28\033[0m\n' '\033[A\033[1;32m Given I have 0 bucks \033[1;30m# tests/functional/output_features/success_table/success_table_steps.py:28\033[0m\n' '\033[1;30m And that I have these items: \033[1;30m# tests/functional/output_features/success_table/success_table_steps.py:32\033[0m\n' '\033[1;30m \033[1;37m |\033[1;30m name \033[1;37m |\033[1;30m price \033[1;37m |\033[1;30m\033[0m\n' '\033[1;30m \033[1;37m |\033[1;30m Porsche\033[1;37m |\033[1;30m 200000\033[1;37m |\033[1;30m\033[0m\n' '\033[1;30m \033[1;37m |\033[1;30m Ferrari\033[1;37m |\033[1;30m 400000\033[1;37m |\033[1;30m\033[0m\n' '\033[A\033[A\033[A\033[A\033[1;32m And that I have these items: \033[1;30m# tests/functional/output_features/success_table/success_table_steps.py:32\033[0m\n' '\033[1;32m \033[1;37m |\033[1;32m name \033[1;37m |\033[1;32m price \033[1;37m |\033[1;32m\033[0m\n' '\033[1;32m \033[1;37m |\033[1;32m Porsche\033[1;37m |\033[1;32m 200000\033[1;37m |\033[1;32m\033[0m\n' '\033[1;32m \033[1;37m |\033[1;32m Ferrari\033[1;37m |\033[1;32m 400000\033[1;37m |\033[1;32m\033[0m\n' '\033[1;30m When I sell the "Ferrari" \033[1;30m# tests/functional/output_features/success_table/success_table_steps.py:42\033[0m\n' '\033[A\033[1;32m When I sell the "Ferrari" \033[1;30m# tests/functional/output_features/success_table/success_table_steps.py:42\033[0m\n' '\033[1;30m Then I have 400000 bucks \033[1;30m# tests/functional/output_features/success_table/success_table_steps.py:28\033[0m\n' '\033[A\033[1;32m Then I have 400000 bucks \033[1;30m# tests/functional/output_features/success_table/success_table_steps.py:28\033[0m\n' '\033[1;30m And my garage contains: \033[1;30m# tests/functional/output_features/success_table/success_table_steps.py:47\033[0m\n' '\033[1;30m \033[1;37m |\033[1;30m name \033[1;37m |\033[1;30m price \033[1;37m |\033[1;30m\033[0m\n' '\033[1;30m \033[1;37m |\033[1;30m Porsche\033[1;37m |\033[1;30m 200000\033[1;37m |\033[1;30m\033[0m\n' '\033[A\033[A\033[A\033[1;32m And my garage contains: \033[1;30m# tests/functional/output_features/success_table/success_table_steps.py:47\033[0m\n' '\033[1;32m \033[1;37m |\033[1;32m name \033[1;37m |\033[1;32m price \033[1;37m |\033[1;32m\033[0m\n' '\033[1;32m \033[1;37m |\033[1;32m Porsche\033[1;37m |\033[1;32m 200000\033[1;37m |\033[1;32m\033[0m\n' '\n' "\033[1;37m1 feature (\033[1;32m1 passed\033[1;37m)\033[0m\n" "\033[1;37m1 scenario (\033[1;32m1 passed\033[1;37m)\033[0m\n" "\033[1;37m5 steps (\033[1;32m5 passed\033[1;37m)\033[0m\n" ) @with_setup(prepare_stdout) def test_output_with_failed_colorless_with_table(): "Testing the colorless output of failed with table" runner = Runner(feature_name('failed_table'), verbosity=3) runner.run() assert_stdout_lines_with_traceback( ("\n" "Feature: Table Fail # tests/functional/output_features/failed_table/failed_table.feature:1\n" "\n" " Scenario: See it fail # tests/functional/output_features/failed_table/failed_table.feature:2\n" u" Given I have a dumb step that passes ♥ # tests/functional/output_features/failed_table/failed_table_steps.py:20\n" " And this one fails # tests/functional/output_features/failed_table/failed_table_steps.py:24\n" " Traceback (most recent call last):\n" ' File "%(lettuce_core_file)s", line %(call_line)d, in __call__\n' " ret = self.function(self.step, *args, **kw)\n" ' File "%(step_file)s", line 25, in tof\n' " assert False\n" " AssertionError\n" " Then this one will be skipped # tests/functional/output_features/failed_table/failed_table_steps.py:28\n" " And this one will be skipped # tests/functional/output_features/failed_table/failed_table_steps.py:28\n" " And this one does not even has definition # tests/functional/output_features/failed_table/failed_table.feature:12 (undefined)\n" "\n" "1 feature (0 passed)\n" "1 scenario (0 passed)\n" "5 steps (1 failed, 2 skipped, 1 undefined, 1 passed)\n" "\n" "You can implement step definitions for undefined steps with these snippets:\n" "\n" "# -*- coding: utf-8 -*-\n" "from lettuce import step\n" "\n" "@step(u'And this one does not even has definition')\n" "def and_this_one_does_not_even_has_definition(step):\n" " assert False, 'This step must be implemented'\n" "\n" "List of failed scenarios:\n" " Scenario: See it fail # tests/functional/output_features/failed_table/failed_table.feature:2\n" "\n") % { 'lettuce_core_file': lettuce_path('core.py'), 'step_file': abspath(lettuce_path('..', 'tests', 'functional', 'output_features', 'failed_table', 'failed_table_steps.py')), 'call_line': call_line, } ) @with_setup(prepare_stdout) def test_output_with_failed_colorful_with_table(): "Testing the colorful output of failed with table" runner = Runner(feature_name('failed_table'), verbosity=4) runner.run() assert_stdout_lines_with_traceback( "\n" "\033[1;37mFeature: Table Fail \033[1;30m# tests/functional/output_features/failed_table/failed_table.feature:1\033[0m\n" "\n" "\033[1;37m Scenario: See it fail \033[1;30m# tests/functional/output_features/failed_table/failed_table.feature:2\033[0m\n" u"\033[1;30m Given I have a dumb step that passes ♥ \033[1;30m# tests/functional/output_features/failed_table/failed_table_steps.py:20\033[0m\n" u"\033[A\033[1;32m Given I have a dumb step that passes ♥ \033[1;30m# tests/functional/output_features/failed_table/failed_table_steps.py:20\033[0m\n" "\033[1;30m And this one fails \033[1;30m# tests/functional/output_features/failed_table/failed_table_steps.py:24\033[0m\n" "\033[A\033[0;31m And this one fails \033[1;41;33m# tests/functional/output_features/failed_table/failed_table_steps.py:24\033[0m\n" "\033[1;31m Traceback (most recent call last):\n" ' File "%(lettuce_core_file)s", line %(call_line)d, in __call__\n' " ret = self.function(self.step, *args, **kw)\n" ' File "%(step_file)s", line 25, in tof\n' " assert False\n" " AssertionError\033[0m\n" "\033[1;30m Then this one will be skipped \033[1;30m# tests/functional/output_features/failed_table/failed_table_steps.py:28\033[0m\n" "\033[A\033[0;36m Then this one will be skipped \033[1;30m# tests/functional/output_features/failed_table/failed_table_steps.py:28\033[0m\n" "\033[1;30m And this one will be skipped \033[1;30m# tests/functional/output_features/failed_table/failed_table_steps.py:28\033[0m\n" "\033[A\033[0;36m And this one will be skipped \033[1;30m# tests/functional/output_features/failed_table/failed_table_steps.py:28\033[0m\n" "\033[0;33m And this one does not even has definition \033[1;30m# tests/functional/output_features/failed_table/failed_table.feature:12\033[0m\n" "\n" "\033[1;37m1 feature (\033[0;31m0 passed\033[1;37m)\033[0m\n" "\033[1;37m1 scenario (\033[0;31m0 passed\033[1;37m)\033[0m\n" "\033[1;37m5 steps (\033[0;31m1 failed\033[1;37m, \033[0;36m2 skipped\033[1;37m, \033[0;33m1 undefined\033[1;37m, \033[1;32m1 passed\033[1;37m)\033[0m\n" "\n" "\033[0;33mYou can implement step definitions for undefined steps with these snippets:\n" "\n" "# -*- coding: utf-8 -*-\n" "from lettuce import step\n" "\n" "@step(u'And this one does not even has definition')\n" "def and_this_one_does_not_even_has_definition(step):\n" " assert False, 'This step must be implemented'\033[0m" "\n" "\n" "\033[1;31mList of failed scenarios:\n" "\033[0;31m Scenario: See it fail # tests/functional/output_features/failed_table/failed_table.feature:2\n" "\033[0m\n" % { 'lettuce_core_file': lettuce_path('core.py'), 'step_file': abspath(lettuce_path('..', 'tests', 'functional', 'output_features', 'failed_table', 'failed_table_steps.py')), 'call_line': call_line, } ) @with_setup(prepare_stdout) def test_output_with_successful_outline_colorless(): "With colorless output, a successful outline scenario should print beautifully." runner = Runner(feature_name('success_outline'), verbosity=3) runner.run() assert_stdout_lines( '\n' 'Feature: Successful Scenario Outline # tests/functional/output_features/success_outline/success_outline.feature:1\n' ' As lettuce author # tests/functional/output_features/success_outline/success_outline.feature:2\n' ' In order to finish the first release # tests/functional/output_features/success_outline/success_outline.feature:3\n' u' I want to make scenario outlines work ♥ # tests/functional/output_features/success_outline/success_outline.feature:4\n' '\n' ' Scenario Outline: fill a web form # tests/functional/output_features/success_outline/success_outline.feature:6\n' ' Given I open browser at "http://www.my-website.com/" # tests/functional/output_features/success_outline/success_outline_steps.py:21\n' ' And click on "sign-up" # tests/functional/output_features/success_outline/success_outline_steps.py:25\n' ' When I fill the field "username" with "<username>" # tests/functional/output_features/success_outline/success_outline_steps.py:29\n' ' And I fill the field "password" with "<password>" # tests/functional/output_features/success_outline/success_outline_steps.py:29\n' ' And I fill the field "password-confirm" with "<password>" # tests/functional/output_features/success_outline/success_outline_steps.py:29\n' ' And I fill the field "email" with "<email>" # tests/functional/output_features/success_outline/success_outline_steps.py:29\n' ' And I click "done" # tests/functional/output_features/success_outline/success_outline_steps.py:33\n' ' Then I see the title of the page is "<title>" # tests/functional/output_features/success_outline/success_outline_steps.py:37\n' '\n' ' Examples:\n' ' | username | password | email | title |\n' ' | john | doe-1234 | john@gmail.org | John \| My Website |\n' ' | mary | wee-9876 | mary@email.com | Mary \| My Website |\n' ' | foo | foo-bar | foo@bar.com | Foo \| My Website |\n' '\n' '1 feature (1 passed)\n' '3 scenarios (3 passed)\n' '24 steps (24 passed)\n' ) @with_setup(prepare_stdout) def test_output_with_successful_outline_colorful(): "With colored output, a successful outline scenario should print beautifully." runner = Runner(feature_name('success_outline'), verbosity=4) runner.run() assert_stdout_lines_with_traceback( '\n' '\033[1;37mFeature: Successful Scenario Outline \033[1;30m# tests/functional/output_features/success_outline/success_outline.feature:1\033[0m\n' '\033[1;37m As lettuce author \033[1;30m# tests/functional/output_features/success_outline/success_outline.feature:2\033[0m\n' '\033[1;37m In order to finish the first release \033[1;30m# tests/functional/output_features/success_outline/success_outline.feature:3\033[0m\n' u'\033[1;37m I want to make scenario outlines work ♥ \033[1;30m# tests/functional/output_features/success_outline/success_outline.feature:4\033[0m\n' '\n' '\033[1;37m Scenario Outline: fill a web form \033[1;30m# tests/functional/output_features/success_outline/success_outline.feature:6\033[0m\n' '\033[0;36m Given I open browser at "http://www.my-website.com/" \033[1;30m# tests/functional/output_features/success_outline/success_outline_steps.py:21\033[0m\n' '\033[0;36m And click on "sign-up" \033[1;30m# tests/functional/output_features/success_outline/success_outline_steps.py:25\033[0m\n' '\033[0;36m When I fill the field "username" with "<username>" \033[1;30m# tests/functional/output_features/success_outline/success_outline_steps.py:29\033[0m\n' '\033[0;36m And I fill the field "password" with "<password>" \033[1;30m# tests/functional/output_features/success_outline/success_outline_steps.py:29\033[0m\n' '\033[0;36m And I fill the field "password-confirm" with "<password>" \033[1;30m# tests/functional/output_features/success_outline/success_outline_steps.py:29\033[0m\n' '\033[0;36m And I fill the field "email" with "<email>" \033[1;30m# tests/functional/output_features/success_outline/success_outline_steps.py:29\033[0m\n' '\033[0;36m And I click "done" \033[1;30m# tests/functional/output_features/success_outline/success_outline_steps.py:33\033[0m\n' '\033[0;36m Then I see the title of the page is "<title>" \033[1;30m# tests/functional/output_features/success_outline/success_outline_steps.py:37\033[0m\n' '\n' '\033[1;37m Examples:\033[0m\n' '\033[0;36m \033[1;37m |\033[0;36m username\033[1;37m |\033[0;36m password\033[1;37m |\033[0;36m email \033[1;37m |\033[0;36m title \033[1;37m |\033[0;36m\033[0m\n' '\033[1;32m \033[1;37m |\033[1;32m john \033[1;37m |\033[1;32m doe-1234\033[1;37m |\033[1;32m john@gmail.org\033[1;37m |\033[1;32m John \| My Website\033[1;37m |\033[1;32m\033[0m\n' '\033[1;32m \033[1;37m |\033[1;32m mary \033[1;37m |\033[1;32m wee-9876\033[1;37m |\033[1;32m mary@email.com\033[1;37m |\033[1;32m Mary \| My Website\033[1;37m |\033[1;32m\033[0m\n' '\033[1;32m \033[1;37m |\033[1;32m foo \033[1;37m |\033[1;32m foo-bar \033[1;37m |\033[1;32m foo@bar.com \033[1;37m |\033[1;32m Foo \| My Website \033[1;37m |\033[1;32m\033[0m\n' '\n' "\033[1;37m1 feature (\033[1;32m1 passed\033[1;37m)\033[0m\n" "\033[1;37m3 scenarios (\033[1;32m3 passed\033[1;37m)\033[0m\n" "\033[1;37m24 steps (\033[1;32m24 passed\033[1;37m)\033[0m\n" ) @with_setup(prepare_stdout) def test_output_with_failful_outline_colorless(): "With colorless output, an unsuccessful outline scenario should print beautifully." runner = Runner(feature_name('fail_outline'), verbosity=3) runner.run() assert_stdout_lines_with_traceback( '\n' 'Feature: Failful Scenario Outline # tests/functional/output_features/fail_outline/fail_outline.feature:1\n' ' As lettuce author # tests/functional/output_features/fail_outline/fail_outline.feature:2\n' ' In order to finish the first release # tests/functional/output_features/fail_outline/fail_outline.feature:3\n' u' I want to make scenario outlines work ♥ # tests/functional/output_features/fail_outline/fail_outline.feature:4\n' '\n' ' Scenario Outline: fill a web form # tests/functional/output_features/fail_outline/fail_outline.feature:6\n' ' Given I open browser at "http://www.my-website.com/" # tests/functional/output_features/fail_outline/fail_outline_steps.py:21\n' ' And click on "sign-up" # tests/functional/output_features/fail_outline/fail_outline_steps.py:25\n' ' When I fill the field "username" with "<username>" # tests/functional/output_features/fail_outline/fail_outline_steps.py:29\n' ' And I fill the field "password" with "<password>" # tests/functional/output_features/fail_outline/fail_outline_steps.py:29\n' ' And I fill the field "password-confirm" with "<password>" # tests/functional/output_features/fail_outline/fail_outline_steps.py:29\n' ' And I fill the field "email" with "<email>" # tests/functional/output_features/fail_outline/fail_outline_steps.py:29\n' ' And I click "done" # tests/functional/output_features/fail_outline/fail_outline_steps.py:33\n' ' Then I see the message "<message>" # tests/functional/output_features/fail_outline/fail_outline_steps.py:37\n' '\n' ' Examples:\n' ' | username | password | email | message |\n' ' | john | doe-1234 | john@gmail.org | Welcome, John |\n' ' | mary | wee-9876 | mary@email.com | Welcome, Mary |\n' " Traceback (most recent call last):\n" ' File "%(lettuce_core_file)s", line %(call_line)d, in __call__\n' " ret = self.function(self.step, *args, **kw)\n" ' File "%(step_file)s", line 30, in when_i_fill_the_field_x_with_y\n' " if field == 'password' and value == 'wee-9876': assert False\n" " AssertionError\n" ' | foo | foo-bar | foo@bar.com | Welcome, Foo |\n' '\n' '1 feature (0 passed)\n' '3 scenarios (2 passed)\n' '24 steps (1 failed, 4 skipped, 19 passed)\n' '\n' 'List of failed scenarios:\n' ' Scenario Outline: fill a web form # tests/functional/output_features/fail_outline/fail_outline.feature:6\n' '\n' % { 'lettuce_core_file': lettuce_path('core.py'), 'step_file': abspath(lettuce_path('..', 'tests', 'functional', 'output_features', 'fail_outline', 'fail_outline_steps.py')), 'call_line': call_line, } ) @with_setup(prepare_stdout) def test_output_with_failful_outline_colorful(): "With colored output, an unsuccessful outline scenario should print beautifully." runner = Runner(feature_name('fail_outline'), verbosity=4) runner.run() assert_stdout_lines_with_traceback( '\n' '\033[1;37mFeature: Failful Scenario Outline \033[1;30m# tests/functional/output_features/fail_outline/fail_outline.feature:1\033[0m\n' '\033[1;37m As lettuce author \033[1;30m# tests/functional/output_features/fail_outline/fail_outline.feature:2\033[0m\n' '\033[1;37m In order to finish the first release \033[1;30m# tests/functional/output_features/fail_outline/fail_outline.feature:3\033[0m\n' u'\033[1;37m I want to make scenario outlines work ♥ \033[1;30m# tests/functional/output_features/fail_outline/fail_outline.feature:4\033[0m\n' '\n' '\033[1;37m Scenario Outline: fill a web form \033[1;30m# tests/functional/output_features/fail_outline/fail_outline.feature:6\033[0m\n' '\033[0;36m Given I open browser at "http://www.my-website.com/" \033[1;30m# tests/functional/output_features/fail_outline/fail_outline_steps.py:21\033[0m\n' '\033[0;36m And click on "sign-up" \033[1;30m# tests/functional/output_features/fail_outline/fail_outline_steps.py:25\033[0m\n' '\033[0;36m When I fill the field "username" with "<username>" \033[1;30m# tests/functional/output_features/fail_outline/fail_outline_steps.py:29\033[0m\n' '\033[0;36m And I fill the field "password" with "<password>" \033[1;30m# tests/functional/output_features/fail_outline/fail_outline_steps.py:29\033[0m\n' '\033[0;36m And I fill the field "password-confirm" with "<password>" \033[1;30m# tests/functional/output_features/fail_outline/fail_outline_steps.py:29\033[0m\n' '\033[0;36m And I fill the field "email" with "<email>" \033[1;30m# tests/functional/output_features/fail_outline/fail_outline_steps.py:29\033[0m\n' '\033[0;36m And I click "done" \033[1;30m# tests/functional/output_features/fail_outline/fail_outline_steps.py:33\033[0m\n' '\033[0;36m Then I see the message "<message>" \033[1;30m# tests/functional/output_features/fail_outline/fail_outline_steps.py:37\033[0m\n' '\n' '\033[1;37m Examples:\033[0m\n' '\033[0;36m \033[1;37m |\033[0;36m username\033[1;37m |\033[0;36m password\033[1;37m |\033[0;36m email \033[1;37m |\033[0;36m message \033[1;37m |\033[0;36m\033[0m\n' '\033[1;32m \033[1;37m |\033[1;32m john \033[1;37m |\033[1;32m doe-1234\033[1;37m |\033[1;32m john@gmail.org\033[1;37m |\033[1;32m Welcome, John\033[1;37m |\033[1;32m\033[0m\n' '\033[1;32m \033[1;37m |\033[1;32m mary \033[1;37m |\033[1;32m wee-9876\033[1;37m |\033[1;32m mary@email.com\033[1;37m |\033[1;32m Welcome, Mary\033[1;37m |\033[1;32m\033[0m\n' "\033[1;31m Traceback (most recent call last):\n" ' File "%(lettuce_core_file)s", line %(call_line)d, in __call__\n' " ret = self.function(self.step, *args, **kw)\n" ' File "%(step_file)s", line 30, in when_i_fill_the_field_x_with_y\n' " if field == 'password' and value == 'wee-9876': assert False\n" " AssertionError\033[0m\n" '\033[1;32m \033[1;37m |\033[1;32m foo \033[1;37m |\033[1;32m foo-bar \033[1;37m |\033[1;32m foo@bar.com \033[1;37m |\033[1;32m Welcome, Foo \033[1;37m |\033[1;32m\033[0m\n' '\n' "\033[1;37m1 feature (\033[0;31m0 passed\033[1;37m)\033[0m\n" "\033[1;37m3 scenarios (\033[1;32m2 passed\033[1;37m)\033[0m\n" "\033[1;37m24 steps (\033[0;31m1 failed\033[1;37m, \033[0;36m4 skipped\033[1;37m, \033[1;32m19 passed\033[1;37m)\033[0m\n" "\n" "\033[1;31mList of failed scenarios:\n" "\033[0;31m Scenario Outline: fill a web form # tests/functional/output_features/fail_outline/fail_outline.feature:6\n" "\033[0m\n" % { 'lettuce_core_file': lettuce_path('core.py'), 'step_file': abspath(lettuce_path('..', 'tests', 'functional', 'output_features', 'fail_outline', 'fail_outline_steps.py')), 'call_line': call_line, } ) @with_setup(prepare_stdout) def test_output_snippets_with_groups_within_double_quotes_colorless(): "Testing that the proposed snippet is clever enough to identify groups within double quotes. colorless" runner = Runner(feature_name('double-quoted-snippet'), verbosity=3) runner.run() assert_stdout_lines( u'\n' u'Feature: double-quoted snippet proposal # tests/functional/output_features/double-quoted-snippet/double-quoted-snippet.feature:1\n' u'\n' u' Scenario: Propose matched groups # tests/functional/output_features/double-quoted-snippet/double-quoted-snippet.feature:2\n' u' Given I have "stuff here" and "more @#$%ˆ& bizar sutff h3r3" # tests/functional/output_features/double-quoted-snippet/double-quoted-snippet.feature:3 (undefined)\n' u'\n' u'1 feature (0 passed)\n' u'1 scenario (0 passed)\n' u'1 step (1 undefined, 0 passed)\n' u'\n' u'You can implement step definitions for undefined steps with these snippets:\n' u'\n' u"# -*- coding: utf-8 -*-\n" u'from lettuce import step\n' u'\n' u'@step(u\'Given I have "([^\"]*)" and "([^\"]*)"\')\n' u'def given_i_have_group1_and_group2(step, group1, group2):\n' u' assert False, \'This step must be implemented\'\n' ) @with_setup(prepare_stdout) def test_output_snippets_with_groups_within_double_quotes_colorful(): "Testing that the proposed snippet is clever enough to identify groups within double quotes. colorful" runner = Runner(feature_name('double-quoted-snippet'), verbosity=4) runner.run() assert_stdout_lines( u'\n' u'\033[1;37mFeature: double-quoted snippet proposal \033[1;30m# tests/functional/output_features/double-quoted-snippet/double-quoted-snippet.feature:1\033[0m\n' u'\n' u'\033[1;37m Scenario: Propose matched groups \033[1;30m# tests/functional/output_features/double-quoted-snippet/double-quoted-snippet.feature:2\033[0m\n' u'\033[0;33m Given I have "stuff here" and "more @#$%ˆ& bizar sutff h3r3" \033[1;30m# tests/functional/output_features/double-quoted-snippet/double-quoted-snippet.feature:3\033[0m\n' u'\n' "\033[1;37m1 feature (\033[0;31m0 passed\033[1;37m)\033[0m\n" "\033[1;37m1 scenario (\033[0;31m0 passed\033[1;37m)\033[0m\n" "\033[1;37m1 step (\033[0;33m1 undefined\033[1;37m, \033[1;32m0 passed\033[1;37m)\033[0m\n" u'\n' u'\033[0;33mYou can implement step definitions for undefined steps with these snippets:\n' u'\n' u"# -*- coding: utf-8 -*-\n" u'from lettuce import step\n' u'\n' u'@step(u\'Given I have "([^"]*)" and "([^"]*)"\')\n' u'def given_i_have_group1_and_group2(step, group1, group2):\n' u' assert False, \'This step must be implemented\'\033[0m\n' ) @with_setup(prepare_stdout) def test_output_snippets_with_groups_within_single_quotes_colorless(): "Testing that the proposed snippet is clever enough to identify groups within single quotes. colorless" runner = Runner(feature_name('single-quoted-snippet'), verbosity=3) runner.run() assert_stdout_lines( u'\n' u'Feature: single-quoted snippet proposal # tests/functional/output_features/single-quoted-snippet/single-quoted-snippet.feature:1\n' u'\n' u' Scenario: Propose matched groups # tests/functional/output_features/single-quoted-snippet/single-quoted-snippet.feature:2\n' u' Given I have \'stuff here\' and \'more @#$%ˆ& bizar sutff h3r3\' # tests/functional/output_features/single-quoted-snippet/single-quoted-snippet.feature:3 (undefined)\n' u'\n' u'1 feature (0 passed)\n' u'1 scenario (0 passed)\n' u'1 step (1 undefined, 0 passed)\n' u'\n' u'You can implement step definitions for undefined steps with these snippets:\n' u'\n' u"# -*- coding: utf-8 -*-\n" u'from lettuce import step\n' u'\n' u'@step(u\'Given I have \\\'([^\\\']*)\\\' and \\\'([^\\\']*)\\\'\')\n' u'def given_i_have_group1_and_group2(step, group1, group2):\n' u' assert False, \'This step must be implemented\'\n' ) @with_setup(prepare_stdout) def test_output_snippets_with_groups_within_single_quotes_colorful(): "Testing that the proposed snippet is clever enough to identify groups within single quotes. colorful" runner = Runner(feature_name('single-quoted-snippet'), verbosity=4) runner.run() assert_stdout_lines( u'\n' u'\033[1;37mFeature: single-quoted snippet proposal \033[1;30m# tests/functional/output_features/single-quoted-snippet/single-quoted-snippet.feature:1\033[0m\n' u'\n' u'\033[1;37m Scenario: Propose matched groups \033[1;30m# tests/functional/output_features/single-quoted-snippet/single-quoted-snippet.feature:2\033[0m\n' u'\033[0;33m Given I have \'stuff here\' and \'more @#$%ˆ& bizar sutff h3r3\' \033[1;30m# tests/functional/output_features/single-quoted-snippet/single-quoted-snippet.feature:3\033[0m\n' u'\n' "\033[1;37m1 feature (\033[0;31m0 passed\033[1;37m)\033[0m\n" "\033[1;37m1 scenario (\033[0;31m0 passed\033[1;37m)\033[0m\n" "\033[1;37m1 step (\033[0;33m1 undefined\033[1;37m, \033[1;32m0 passed\033[1;37m)\033[0m\n" u'\n' u'\033[0;33mYou can implement step definitions for undefined steps with these snippets:\n' u'\n' u"# -*- coding: utf-8 -*-\n" u'from lettuce import step\n' u'\n' u'@step(u\'Given I have \\\'([^\\\']*)\\\' and \\\'([^\\\']*)\\\'\')\n' u'def given_i_have_group1_and_group2(step, group1, group2):\n' u' assert False, \'This step must be implemented\'\033[0m\n' ) @with_setup(prepare_stdout) def test_output_snippets_with_groups_within_redundant_quotes(): "Testing that the proposed snippet is clever enough to avoid duplicating the same snippet" runner = Runner(feature_name('redundant-steps-quotes'), verbosity=3) runner.run() assert_stdout_lines( u'\n' u'Feature: avoid duplicating same snippet # tests/functional/output_features/redundant-steps-quotes/redundant-steps-quotes.feature:1\n' u'\n' u' Scenario: Propose matched groups # tests/functional/output_features/redundant-steps-quotes/redundant-steps-quotes.feature:2\n' u' Given I have "stuff here" and "more @#$%ˆ& bizar sutff h3r3" # tests/functional/output_features/redundant-steps-quotes/redundant-steps-quotes.feature:3 (undefined)\n' u' Given I have "blablabla" and "12345" # tests/functional/output_features/redundant-steps-quotes/redundant-steps-quotes.feature:4 (undefined)\n' u'\n' u'1 feature (0 passed)\n' u'1 scenario (0 passed)\n' u'2 steps (2 undefined, 0 passed)\n' u'\n' u'You can implement step definitions for undefined steps with these snippets:\n' u'\n' u"# -*- coding: utf-8 -*-\n" u'from lettuce import step\n' u'\n' u'@step(u\'Given I have "([^"]*)" and "([^"]*)"\')\n' u'def given_i_have_group1_and_group2(step, group1, group2):\n' u' assert False, \'This step must be implemented\'\n' ) @with_setup(prepare_stdout) def test_output_snippets_with_normalized_unicode_names(): "Testing that the proposed snippet is clever enough normalize method names even with latin accents" runner = Runner(feature_name('latin-accents'), verbosity=3) runner.run() assert_stdout_lines( u"\n" u"Funcionalidade: melhorar o output de snippets do lettuce # tests/functional/output_features/latin-accents/latin-accents.feature:2\n" u" Como autor do lettuce # tests/functional/output_features/latin-accents/latin-accents.feature:3\n" u" Eu quero ter um output refinado de snippets # tests/functional/output_features/latin-accents/latin-accents.feature:4\n" u" Para melhorar, de uma forma geral, a vida do programador # tests/functional/output_features/latin-accents/latin-accents.feature:5\n" u"\n" u" Cenário: normalizar snippets com unicode # tests/functional/output_features/latin-accents/latin-accents.feature:7\n" u" Dado que eu tenho palavrões e outras situações # tests/functional/output_features/latin-accents/latin-accents.feature:8 (undefined)\n" u" E várias palavras acentuadas são úteis, tais como: \"(é,não,léo,chororó,chácara,epígrafo)\" # tests/functional/output_features/latin-accents/latin-accents.feature:9 (undefined)\n" u" Então eu fico felizão # tests/functional/output_features/latin-accents/latin-accents.feature:10 (undefined)\n" u"\n" u"1 feature (0 passed)\n" u"1 scenario (0 passed)\n" u"3 steps (3 undefined, 0 passed)\n" u"\n" u"You can implement step definitions for undefined steps with these snippets:\n" u"\n" u"# -*- coding: utf-8 -*-\n" u"from lettuce import step\n" u"\n" u"@step(u'Dado que eu tenho palavrões e outras situações')\n" u"def dado_que_eu_tenho_palavroes_e_outras_situacoes(step):\n" u" assert False, 'This step must be implemented'\n" u"@step(u'E várias palavras acentuadas são úteis, tais como: \"([^\"]*)\"')\n" u"def e_varias_palavras_acentuadas_sao_uteis_tais_como_group1(step, group1):\n" u" assert False, 'This step must be implemented'\n" u"@step(u'Então eu fico felizão')\n" u"def entao_eu_fico_felizao(step):\n" u" assert False, 'This step must be implemented'\n" ) @with_setup(prepare_stdout) def test_output_level_2_success(): 'Output with verbosity 2 must show only the scenario names, followed by "... OK" in case of success' runner = Runner(join(abspath(dirname(__file__)), 'output_features', 'many_successful_scenarios'), verbosity=2) runner.run() assert_stdout_lines( "Do nothing ... OK\n" "Do nothing (again) ... OK\n" "\n" "1 feature (1 passed)\n" "2 scenarios (2 passed)\n" "2 steps (2 passed)\n" ) @with_setup(prepare_stdout) def test_output_level_2_fail(): 'Output with verbosity 2 must show only the scenario names, followed by "... FAILED" in case of fail' runner = Runner(feature_name('failed_table'), verbosity=2) runner.run() assert_stdout_lines_with_traceback( "See it fail ... FAILED\n" "\n" "\n" "<Step: \"And this one fails\">\n" "Traceback (most recent call last):\n" ' File "%(lettuce_core_file)s", line %(call_line)d, in __call__\n' " ret = self.function(self.step, *args, **kw)\n" ' File "%(step_file)s", line 25, in tof\n' " assert False\n" "AssertionError\n" "\n" "1 feature (0 passed)\n" "1 scenario (0 passed)\n" "5 steps (1 failed, 2 skipped, 1 undefined, 1 passed)\n" % { 'lettuce_core_file': lettuce_path('core.py'), 'step_file': abspath(lettuce_path('..', 'tests', 'functional', 'output_features', 'failed_table', 'failed_table_steps.py')), 'call_line': call_line, } ) @with_setup(prepare_stdout) def test_output_level_2_error(): 'Output with verbosity 2 must show only the scenario names, followed by "... ERROR" in case of fail' runner = Runner(feature_name('error_traceback'), verbosity=2) runner.run() assert_stdout_lines_with_traceback( "It should pass ... OK\n" "It should raise an exception different of AssertionError ... ERROR\n" "\n" "\n" "<Step: \"Given my step that blows a exception\">\n" "Traceback (most recent call last):\n" ' File "%(lettuce_core_file)s", line %(call_line)d, in __call__\n' " ret = self.function(self.step, *args, **kw)\n" ' File "%(step_file)s", line 10, in given_my_step_that_blows_a_exception\n' " raise RuntimeError\n" "RuntimeError\n" "\n" "1 feature (0 passed)\n" "2 scenarios (1 passed)\n" "2 steps (1 failed, 1 passed)\n" % { 'lettuce_core_file': lettuce_path('core.py'), 'step_file': abspath(lettuce_path('..', 'tests', 'functional', 'output_features', 'error_traceback', 'error_traceback_steps.py')), 'call_line': call_line, } ) @with_setup(prepare_stdout) def test_output_level_1_success(): 'Output with verbosity 2 must show only the scenario names, followed by "... OK" in case of success' runner = Runner(join(abspath(dirname(__file__)), 'output_features', 'many_successful_scenarios'), verbosity=1) runner.run() assert_stdout_lines( ".." "\n" "1 feature (1 passed)\n" "2 scenarios (2 passed)\n" "2 steps (2 passed)\n" ) @with_setup(prepare_stdout) def test_output_level_1_fail(): 'Output with verbosity 2 must show only the scenario names, followed by "... FAILED" in case of fail' runner = Runner(feature_name('failed_table'), verbosity=1) runner.run() assert_stdout_lines_with_traceback( "F\n" "\n" "<Step: \"And this one fails\">\n" "Traceback (most recent call last):\n" ' File "%(lettuce_core_file)s", line %(call_line)d, in __call__\n' " ret = self.function(self.step, *args, **kw)\n" ' File "%(step_file)s", line 25, in tof\n' " assert False\n" "AssertionError\n" "\n" "1 feature (0 passed)\n" "1 scenario (0 passed)\n" "5 steps (1 failed, 2 skipped, 1 undefined, 1 passed)\n" % { 'lettuce_core_file': lettuce_path('core.py'), 'step_file': abspath(lettuce_path('..', 'tests', 'functional', 'output_features', 'failed_table', 'failed_table_steps.py')), 'call_line': call_line, } ) @with_setup(prepare_stdout) def test_output_level_1_error(): 'Output with verbosity 2 must show only the scenario names, followed by "... ERROR" in case of fail' runner = Runner(feature_name('error_traceback'), verbosity=1) runner.run() assert_stdout_lines_with_traceback( ".E\n" "\n" "<Step: \"Given my step that blows a exception\">\n" "Traceback (most recent call last):\n" ' File "%(lettuce_core_file)s", line %(call_line)d, in __call__\n' " ret = self.function(self.step, *args, **kw)\n" ' File "%(step_file)s", line 10, in given_my_step_that_blows_a_exception\n' " raise RuntimeError\n" "RuntimeError\n" "\n" "1 feature (0 passed)\n" "2 scenarios (1 passed)\n" "2 steps (1 failed, 1 passed)\n" % { 'lettuce_core_file': lettuce_path('core.py'), 'step_file': abspath(lettuce_path('..', 'tests', 'functional', 'output_features', 'error_traceback', 'error_traceback_steps.py')), 'call_line': call_line, } ) @with_setup(prepare_stdout) def test_commented_scenario(): 'Test one commented scenario' runner = Runner(feature_name('commented_feature'), verbosity=1) runner.run() assert_stdout_lines( "." "\n" "1 feature (1 passed)\n" "1 scenario (1 passed)\n" "1 step (1 passed)\n" ) @with_setup(prepare_stdout) def test_blank_step_hash_value(): "syntax checking: Blank in step hash column = empty string" from lettuce import step @step('ignore step') def ignore_step(step): pass @step('string length calc') def string_lenth_calc(step): for hash in step.hashes: if len(hash["string"]) + len(hash["string2"]) != int(hash["length"]): raise AssertionError("fail") filename = syntax_feature_name('blank_values_in_hash') runner = Runner(filename, verbosity=1) runner.run() assert_stdout_lines( "." "\n" "1 feature (1 passed)\n" "1 scenario (1 passed)\n" "4 steps (4 passed)\n" ) @with_setup(prepare_stdout) def test_run_only_fast_tests(): "Runner can filter by tags" from lettuce import step good_one = Mock() bad_one = Mock() @step('I wait for 0 seconds') def wait_for_0_seconds(step): good_one(step.sentence) @step('the time passed is 0 seconds') def time_passed_0_sec(step): good_one(step.sentence) @step('I wait for 60 seconds') def wait_for_60_seconds(step): bad_one(step.sentence) @step('the time passed is 1 minute') def time_passed_1_min(step): bad_one(step.sentence) filename = tag_feature_name('timebound') runner = Runner(filename, verbosity=1, tags=['fast-ish']) runner.run() assert_stdout_lines( "." "\n" "1 feature (1 passed)\n" "1 scenario (1 passed)\n" "2 steps (2 passed)\n" ) def test_run_random(): "Randomise the feature order" path = fs.relpath(join(abspath(dirname(__file__)), 'no_features', 'unexistent-folder')) runner = Runner(path, random=True) assert_equals(True, runner.random) with patch.object(random, 'shuffle') as pshuffle: runner.run() pshuffle.assert_called_once_with([]) @with_setup(prepare_stdout) def test_background_with_header(): "Running background with header" from lettuce import step, world @step(ur'the variable "(\w+)" holds (\d+)') def set_variable(step, name, value): setattr(world, name, int(value)) @step(ur'the variable "(\w+)" is equal to (\d+)') def check_variable(step, name, expected): expected = int(expected) expect(world).to.have.property(name).being.equal(expected) @step(ur'the variable "(\w+)" times (\d+) is equal to (\d+)') def multiply_and_verify(step, name, times, expected): times = int(times) expected = int(expected) (getattr(world, name) * times).should.equal(expected) filename = bg_feature_name('header') runner = Runner(filename, verbosity=1) runner.run() assert_stdout_lines( ".." "\n" "1 feature (1 passed)\n" "2 scenarios (2 passed)\n" "7 steps (7 passed)\n" ) @with_setup(prepare_stdout) def test_background_without_header(): "Running background without header" from lettuce import step, world, before, after actions = {} @before.each_background def register_background_before(background): actions['before'] = unicode(background) @after.each_background def register_background_after(background, results): actions['after'] = { 'background': unicode(background), 'results': results, } @step(ur'the variable "(\w+)" holds (\d+)') def set_variable(step, name, value): setattr(world, name, int(value)) @step(ur'the variable "(\w+)" is equal to (\d+)') def check_variable(step, name, expected): expected = int(expected) expect(world).to.have.property(name).being.equal(expected) @step(ur'the variable "(\w+)" times (\d+) is equal to (\d+)') def multiply_and_verify(step, name, times, expected): times = int(times) expected = int(expected) (getattr(world, name) * times).should.equal(expected) filename = bg_feature_name('naked') runner = Runner(filename, verbosity=1) runner.run() assert_stdout_lines( ".." "\n" "1 feature (1 passed)\n" "2 scenarios (2 passed)\n" "7 steps (7 passed)\n" ) expect(actions).to.equal({ 'after': { 'results': [True], 'background': u'<Background for feature: Without Header>' }, 'before': u'<Background for feature: Without Header>' }) @with_setup(prepare_stdout) def test_output_background_with_success_colorless(): "A feature with background should print it accordingly under verbosity 3" from lettuce import step @step(ur'the variable "(\w+)" holds (\d+)') @step(ur'the variable "(\w+)" is equal to (\d+)') def just_pass(step, *args): pass filename = bg_feature_name('simple') runner = Runner(filename, verbosity=3) runner.run() assert_stdout_lines( '\n' 'Feature: Simple and successful # tests/functional/bg_features/simple/simple.feature:1\n' ' As the Lettuce maintainer # tests/functional/bg_features/simple/simple.feature:2\n' ' In order to make sure the output is pretty # tests/functional/bg_features/simple/simple.feature:3\n' ' I want to automate its test # tests/functional/bg_features/simple/simple.feature:4\n' '\n' ' Background:\n' ' Given the variable "X" holds 2 # tests/functional/test_runner.py:1239\n' '\n' ' Scenario: multiplication changing the value # tests/functional/bg_features/simple/simple.feature:9\n' ' Given the variable "X" is equal to 2 # tests/functional/test_runner.py:1239\n' '\n' '1 feature (1 passed)\n' '1 scenario (1 passed)\n' '1 step (1 passed)\n' ) @with_setup(prepare_stdout) def test_output_background_with_success_colorful(): "A feature with background should print it accordingly under verbosity 4" from lettuce import step @step(ur'the variable "(\w+)" holds (\d+)') @step(ur'the variable "(\w+)" is equal to (\d+)') def just_pass(step, *args): pass filename = bg_feature_name('simple') runner = Runner(filename, verbosity=4) runner.run() assert_stdout_lines( '\n' '\033[1;37mFeature: Simple and successful \033[1;30m# tests/functional/bg_features/simple/simple.feature:1\033[0m\n' '\033[1;37m As the Lettuce maintainer \033[1;30m# tests/functional/bg_features/simple/simple.feature:2\033[0m\n' '\033[1;37m In order to make sure the output is pretty \033[1;30m# tests/functional/bg_features/simple/simple.feature:3\033[0m\n' '\033[1;37m I want to automate its test \033[1;30m# tests/functional/bg_features/simple/simple.feature:4\033[0m\n' '\n' '\033[1;37m Background:\033[0m\n' '\033[1;30m Given the variable "X" holds 2 \033[1;30m# tests/functional/test_runner.py:1274\033[0m\n' '\033[A\033[1;32m Given the variable "X" holds 2 \033[1;30m# tests/functional/test_runner.py:1274\033[0m\n' '\n' '\033[1;37m Scenario: multiplication changing the value \033[1;30m# tests/functional/bg_features/simple/simple.feature:9\033[0m\n' '\033[1;30m Given the variable "X" is equal to 2 \033[1;30m# tests/functional/test_runner.py:1274\033[0m\n' '\033[A\033[1;32m Given the variable "X" is equal to 2 \033[1;30m# tests/functional/test_runner.py:1274\033[0m\n' '\n' '\033[1;37m1 feature (\033[1;32m1 passed\033[1;37m)\033[0m\n' '\033[1;37m1 scenario (\033[1;32m1 passed\033[1;37m)\033[0m\n' '\033[1;37m1 step (\033[1;32m1 passed\033[1;37m)\033[0m\n' ) @with_setup(prepare_stdout) def test_background_with_scenario_before_hook(): "Running background with before_scenario hook" from lettuce import step, world, before @before.each_scenario def reset_variable(scenario): world.X = None @step(ur'the variable "(\w+)" holds (\d+)') def set_variable(step, name, value): setattr(world, name, int(value)) @step(ur'the variable "(\w+)" is equal to (\d+)') def check_variable(step, name, expected): expected = int(expected) expect(world).to.have.property(name).being.equal(expected) @step(ur'the variable "(\w+)" times (\d+) is equal to (\d+)') def multiply_and_verify(step, name, times, expected): times = int(times) expected = int(expected) (getattr(world, name) * times).should.equal(expected) filename = bg_feature_name('header') runner = Runner(filename, verbosity=1) runner.run() assert_stdout_lines( ".." "\n" "1 feature (1 passed)\n" "2 scenarios (2 passed)\n" "7 steps (7 passed)\n" ) @with_setup(prepare_stderr) def test_many_features_a_file(): "syntax checking: Fail if a file has more than one feature" filename = syntax_feature_name('many_features_a_file') runner = Runner(filename) assert_raises(SystemExit, runner.run) assert_stderr_lines( 'Syntax error at: %s\n' 'A feature file must contain ONLY ONE feature!\n' % filename ) @with_setup(prepare_stderr) def test_feature_without_name(): "syntax checking: Fail on features without name" filename = syntax_feature_name('feature_without_name') runner = Runner(filename) assert_raises(SystemExit, runner.run) assert_stderr_lines( 'Syntax error at: %s\n' 'Features must have a name. e.g: "Feature: This is my name"\n' % filename ) @with_setup(prepare_stderr) def test_feature_missing_scenarios(): "syntax checking: Fail on features missing scenarios" filename = syntax_feature_name("feature_missing_scenarios") runner = Runner(filename) assert_raises(SystemExit, runner.run) assert_stderr_lines( u"Syntax error at: %s\n" "Features must have scenarios.\nPlease refer to the documentation " "available at http://lettuce.it for more information.\n" % filename ) @with_setup(prepare_stdout) def test_output_with_undefined_steps_colorful(): "With colored output, an undefined step should be printed in sequence." runner = Runner(feature_name('undefined_steps'), verbosity=4) runner.run() assert_stdout_lines_with_traceback( '\n' '\x1b[1;37mFeature: Test undefined steps are displayed on console \x1b[1;30m# tests/functional/output_features/undefined_steps/undefined_steps.feature:1\x1b[0m\n' '\n' '\x1b[1;37m Scenario: Scenario with undefined step \x1b[1;30m# tests/functional/output_features/undefined_steps/undefined_steps.feature:3\x1b[0m\n' '\x1b[1;30m Given this test step passes \x1b[1;30m# tests/functional/output_features/undefined_steps/undefined_steps.py:4\x1b[0m\n' '\x1b[A\x1b[1;32m Given this test step passes \x1b[1;30m# tests/functional/output_features/undefined_steps/undefined_steps.py:4\x1b[0m\n' '\x1b[0;33m When this test step is undefined \x1b[1;30m# tests/functional/output_features/undefined_steps/undefined_steps.feature:5\x1b[0m\n' '\n' '\x1b[1;37m Scenario Outline: Outline scenario with general undefined step \x1b[1;30m# tests/functional/output_features/undefined_steps/undefined_steps.feature:7\x1b[0m\n' '\x1b[0;36m Given this test step passes \x1b[1;30m# tests/functional/output_features/undefined_steps/undefined_steps.py:4\x1b[0m\n' '\x1b[0;33m When this test step is undefined \x1b[1;30m# tests/functional/output_features/undefined_steps/undefined_steps.feature:5\x1b[0m\n' '\x1b[0;36m Then <in> squared is <out> \x1b[1;30m# tests/functional/output_features/undefined_steps/undefined_steps.py:8\x1b[0m\n' '\n' '\x1b[1;37m Examples:\x1b[0m\n' '\x1b[0;36m \x1b[1;37m |\x1b[0;36m in\x1b[1;37m |\x1b[0;36m out\x1b[1;37m |\x1b[0;36m\x1b[0m\n' '\x1b[1;32m \x1b[1;37m |\x1b[1;32m 1 \x1b[1;37m |\x1b[1;32m 1 \x1b[1;37m |\x1b[1;32m\x1b[0m\n' '\x1b[1;32m \x1b[1;37m |\x1b[1;32m 2 \x1b[1;37m |\x1b[1;32m 4 \x1b[1;37m |\x1b[1;32m\x1b[0m\n' '\n' '\x1b[1;37m1 feature (\x1b[0;31m0 passed\x1b[1;37m)\x1b[0m\n' '\x1b[1;37m3 scenarios (\x1b[0;31m0 passed\x1b[1;37m)\x1b[0m\n' '\x1b[1;37m8 steps (\x1b[0;36m2 skipped\x1b[1;37m, \x1b[0;33m3 undefined\x1b[1;37m, \x1b[1;32m3 passed\x1b[1;37m)\x1b[0m\n' '\n' '\x1b[0;33mYou can implement step definitions for undefined steps with these snippets:\n' '\n' '# -*- coding: utf-8 -*-\n' 'from lettuce import step\n' '\n' "@step(u'When this test step is undefined')\n" 'def when_this_test_step_is_undefined(step):\n' " assert False, 'This step must be implemented'\x1b[0m\n" ) ```
[ { "content": "Here is a code snippet:\n```python\n# coding=utf-8\n# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n#\n# Cod...
[ { "content": "Here is a code snippet:\n<|memory_start|>```python\n# coding=utf-8\n# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license inform...
```python # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from msrest.serialization import Model class X12ValidationOverride(Model): """X12ValidationOverride. :param message_id: The message id on which the validation settings has to be applied. :type message_id: str :param validate_edi_types: The value indicating whether to validate EDI types. :type validate_edi_types: bool :param validate_xsd_types: The value indicating whether to validate XSD types. :type validate_xsd_types: bool :param allow_leading_and_trailing_spaces_and_zeroes: The value indicating whether to allow leading and trailing spaces and zeroes. :type allow_leading_and_trailing_spaces_and_zeroes: bool :param validate_character_set: The value indicating whether to validate character Set. :type validate_character_set: bool :param trim_leading_and_trailing_spaces_and_zeroes: The value indicating whether to trim leading and trailing spaces and zeroes. :type trim_leading_and_trailing_spaces_and_zeroes: bool :param trailing_separator_policy: The trailing separator policy. Possible values include: 'NotSpecified', 'NotAllowed', 'Optional', 'Mandatory' :type trailing_separator_policy: str or :class:`TrailingSeparatorPolicy <azure.mgmt.logic.models.TrailingSeparatorPolicy>` """ _attribute_map = { 'message_id': {'key': 'messageId', 'type': 'str'}, 'validate_edi_types': {'key': 'validateEDITypes', 'type': 'bool'}, 'validate_xsd_types': {'key': 'validateXSDTypes', 'type': 'bool'}, 'allow_leading_and_trailing_spaces_and_zeroes': {'key': 'allowLeadingAndTrailingSpacesAndZeroes', 'type': 'bool'}, 'validate_character_set': {'key': 'validateCharacterSet', 'type': 'bool'}, 'trim_leading_and_trailing_spaces_and_zeroes': {'key': 'trimLeadingAndTrailingSpacesAndZeroes', 'type': 'bool'}, 'trailing_separator_policy': {'key': 'trailingSeparatorPolicy', 'type': 'TrailingSeparatorPolicy'}, } def __init__(self, message_id=None, validate_edi_types=None, validate_xsd_types=None, allow_leading_and_trailing_spaces_and_zeroes=None, validate_character_set=None, trim_leading_and_trailing_spaces_and_zeroes=None, trailing_separator_policy=None): self.message_id = message_id self.validate_edi_types = validate_edi_types self.validate_xsd_types = validate_xsd_types self.allow_leading_and_trailing_spaces_and_zeroes = allow_leading_and_trailing_spaces_and_zeroes self.validate_character_set = validate_character_set self.trim_leading_and_trailing_spaces_and_zeroes = trim_leading_and_trailing_spaces_and_zeroes self.trailing_separator_policy = trailing_separator_policy ```
[ { "content": "```python\n# The following parse_* methods are from bitcoin-abe\n\nimport base58\n\ndef parse_TxIn(vds):\n d = {}\n d['prevout_hash'] = vds.read_bytes(32)\n d['prevout_n'] = vds.read_uint32()\n d['scriptSig'] = vds.read_bytes(vds.read_compact_size())\n d['sequence'] = vds.read_uint32()\n ret...
[ { "content": "<|memory_start|>```python\n# The following parse_* methods are from bitcoin-abe\n\nimport base58\n\ndef parse_TxIn(vds):\n d = {}\n d['prevout_hash'] = vds.read_bytes(32)\n d['prevout_n'] = vds.read_uint32()\n d['scriptSig'] = vds.read_bytes(vds.read_compact_size())\n d['sequence'] = vds.read...
```python # The following parse_* methods are from bitcoin-abe import base58 def parse_TxIn(vds): d = {} d['prevout_hash'] = vds.read_bytes(32) d['prevout_n'] = vds.read_uint32() d['scriptSig'] = vds.read_bytes(vds.read_compact_size()) d['sequence'] = vds.read_uint32() return d def parse_TxOut(vds): d = {} d['value'] = vds.read_int64() raw = vds.read_bytes(vds.read_compact_size()) d['scriptPubKey'] = raw if len(raw) == 25 and raw[0] == '\x76' and raw[1] == '\xa9' and raw[2] == '\x14': d['address'] = base58.hash_160_to_bc_address(raw[3:-2]) return d def parse_Transaction(vds): d = {} start = vds.read_cursor d['version'] = vds.read_int32() n_vin = vds.read_compact_size() d['txIn'] = [] for i in xrange(n_vin): d['txIn'].append(parse_TxIn(vds)) n_vout = vds.read_compact_size() d['txOut'] = [] for i in xrange(n_vout): d['txOut'].append(parse_TxOut(vds)) d['lockTime'] = vds.read_uint32() d['tx'] = vds.input[start:vds.read_cursor] return d def parse_BlockHeader(vds): d = {} blk_magic = vds.read_bytes(4) #if blk_magic != '\xf9\xbe\xb4\xd9': # if blk_magic != '\xbf\xfa\xda\xb5': # raise Exception('Bad magic' + str(blk_magic)) # return d blk_length = vds.read_int32() header_start = vds.read_cursor d['version'] = vds.read_int32() d['hashPrev'] = vds.read_bytes(32) d['hashMerkleRoot'] = vds.read_bytes(32) d['nTime'] = vds.read_uint32() d['nBits'] = vds.read_uint32() d['nNonce'] = vds.read_uint32() header_end = vds.read_cursor d['__header__'] = vds.input[header_start:header_end] return d def parse_Block(vds): d = parse_BlockHeader(vds) d['transactions'] = [] nTransactions = vds.read_compact_size() for i in xrange(nTransactions): d['transactions'].append(parse_Transaction(vds)) return d ```
[ { "content": "Repeat the full code snippet:\n```python\n\"\"\"\n * Copyright (c) 2008 Zivios, LLC.\n *\n * This file is part of Zivios.\n *\n * Zivios is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation...
[ { "content": "Repeat the full code snippet:\n<|memory_start|>```python\n\"\"\"\n * Copyright (c) 2008 Zivios, LLC.\n *\n * This file is part of Zivios.\n *\n * Zivios is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Sof...
```python """ * Copyright (c) 2008 Zivios, LLC. * * This file is part of Zivios. * * Zivios 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. * * Zivios 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 Zivios. If not, see <http://www.gnu.org/licenses/>. * * @package ZiviosAgent * @copyright Copyright (c) 2008 Zivios, LLC. (http://www.zivios.org) * @license http://www.zivios.org/legal/license * @version $Id: Exception.php 908 2008-08-25 11:03:00Z fkhan $ * @subpackage Core """ from twisted.web import xmlrpc import logging import os import popen2 import re import string import time import datetime from twisted.python import log import ZiviosAgent class ntp(ZiviosAgent.ZiviosAgent): def xmlrpc_addService(self): print 'ntp addService function called' def xmlrpc_serviceStatus(self): response,regexcode,exitcode = self.command("statusntpcommand") return (exitcode==0) def xmlrpc_stopService(self): response,regexcode,exitcode = self.command("stopntpcommand") return (exitcode==0) def xmlrpc_startService(self): response,regexcode,exitcode = self.command("startntpcommand") return (exitcode==0) def xmlrpc_currentTime(self): now = datetime.datetime.now() return now.ctime() def xmlrpc_getTimezone(self): tz,tzm = time.tzname return tzm; def xmlrpc_getsyncstatus(self): #sanitizing output! response,regexcode,exitcode = self.command("ntpq"); resp = response.split('\n') if (len(resp) <= 2): return -1 del resp[0:2] length = len(resp) del resp[length-1] retarray = [] for a in resp: a = a.lstrip() a = a.rstrip() joinarray = re.split('\s+',a) retarray.append(joinarray) return retarray def xmlrpc_getGmtOffset(self): return time.timezone/3600; ```
[ { "content": "```python\nfrom decimal import Decimal\nfrom django.db import models\nfrom django.core.validators import MinValueValidator\nfrom ..notifications.models import NotificationMessage\nfrom ..users.models import User\n\nclass Answer(models.Model):\n question = models.ForeignKey('contests.contest', r...
[ { "content": "<|memory_start|>```python\nfrom decimal import Decimal\nfrom django.db import models\nfrom django.core.validators import MinValueValidator\nfrom ..notifications.models import NotificationMessage\nfrom ..users.models import User\n\nclass Answer(models.Model):\n question = models.ForeignKey('cont...
```python from decimal import Decimal from django.db import models from django.core.validators import MinValueValidator from ..notifications.models import NotificationMessage from ..users.models import User class Answer(models.Model): question = models.ForeignKey('contests.contest', related_name='answer', on_delete=models.CASCADE) answer_text = models.CharField(max_length=200) correct_answer = models.BooleanField(default=False) is_active = models.BooleanField(default=True) def __str__(self): return self.answer_text class Meta: db_table = 'cms_answer' class Account(models.Model): billingpostalcode = models.CharField(max_length=20, null=True, blank=True) isdeleted = models.BooleanField(default=False) id = models.IntegerField(primary_key=True, unique=True) billinglatitude = models.DecimalField( max_digits=11, decimal_places=8, null=True, blank=True) _hc_lastop = models.CharField(max_length=32, null=True, blank=True) createddate = models.DateTimeField(null=True, blank=True) billingcountry = models.CharField(max_length=80, null=True, blank=True) geolocation_longitude_s = models.DecimalField( max_digits=11, decimal_places=8, db_column='geolocation__longitude__s', null=True, blank=True) geolocation_latitude_s = models.DecimalField( max_digits=11, decimal_places=8, db_column='geolocation__latitude__s', null=True, blank=True) billingstate = models.CharField(max_length=80, null=True, blank=True) billingstreet = models.CharField(max_length=255, null=True, blank=True) billinglongitude = models.DecimalField( max_digits=11, decimal_places=8, null=True, blank=True) billingcity = models.CharField(max_length=40, null=True, blank=True) systemmodstamp = models.DateTimeField(null=True, blank=True) name = models.CharField(max_length=255, null=True, blank=True) _hc_err = models.TextField(null=True, blank=True, max_length=1024) sfid = models.CharField(max_length=18, null=True, blank=True) # these three should be on a separate model # schedule = models.CharField(max_length=200,null=True,blank=True) # timestamp = models.DateTimeField(auto_now_add=True) # is_featured = models.BooleanField(default=False) def __str__(self): return self.name class Meta: # managed = False db_table = 'salesforce\".\"account' verbose_name = 'Salesforce Account' verbose_name_plural = 'Salesforce Accounts' class AccountAddon(models.Model): account = models.OneToOneField(Account, related_name='accountaddons', on_delete=models.CASCADE) schedule = models.CharField(max_length=200, null=True, blank=True) timestamp = models.DateTimeField(auto_now_add=True) is_featured = models.BooleanField(default=False) avg_consumer_spending = models.DecimalField(null=True, blank=True, max_digits=7, decimal_places=2, validators=[MinValueValidator(Decimal('0.00'))]) menu_best_sellers = models.TextField(null=True, blank=True) promotions = models.TextField(null=True, blank=True) author = models.ForeignKey(User, null=True, blank=True) last_update_datetime = models.DateTimeField(null=True, blank=True) category = models.CharField(max_length=50, null=True, blank=True) is_type = models.CharField(default='Account', max_length=50) def __str__(self): return str(self.account) @property def has_notif(self): try: notif_obj = NotificationMessage.objects.get(linkback = 'new_account_' + str(self.account.id)) return True except NotificationMessage.DoesNotExist: return False class Meta: verbose_name_plural = 'Account Addons' db_table = 'cms_account_addon' ```
[ { "content": "```python\n#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n\n\n# Plese delete 'system.db' before running this module\n# This is a temporary solution, i will add suport to the android app later on\n# But it is still very useful if you keen to add device though this method\n\nimport utils.device as Devi...
[ { "content": "<|memory_start|>```python\n#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n\n\n# Plese delete 'system.db' before running this module\n# This is a temporary solution, i will add suport to the android app later on\n# But it is still very useful if you keen to add device though this method\n\nimport util...
```python #!/usr/bin/python # -*- coding: UTF-8 -*- # Plese delete 'system.db' before running this module # This is a temporary solution, i will add suport to the android app later on # But it is still very useful if you keen to add device though this method import utils.device as Device # Example format: Device.addDevice(id, className, title, port, category) # Highly recommond that the id start from 1000 or a larger integer # port could be None for some types, check it out in the modules in devices folder # category could be None if you do not use 'Device' as the className Device.addDevice(1000, 'Switch', 'Fake Switch at Port 23', 23, None) Device.addDevice(1001, 'RandomValue', 'Random Value', None, None) Device.addDevice(1002, 'CPUTemp', 'CPU Temperature', None, None) Device.addDevice(1003, 'Button', 'Green LED', 18, None) Device.addDevice(1004, 'PWMSignal', 'Blue PWM LED', 15, None) Device.addDevice(1005, 'DHT11Temp', 'Temperature', 4, None) Device.addDevice(1006, 'DHT11Humidity', 'Humidity', 4, None) Device.addDevice(1007, 'BH1750FVI', 'Brightness', 0x23, None) devices = Device.getDevices() print devices for device in devices: print device.description() # Device.removeDeviceSQL(1008) ```
[ { "content": "Output the full code verbatim (no extra comments):\n```python\n#\n# bluetooth_config.py\n#\n# Copyright (C) 2016 - 2018 Kano Computing Ltd.\n# License: http://www.gnu.org/licenses/gpl-2.0.txt GNU GPLv2\n#\n# Bluetooth setup screen\n#\n\nimport os\nimport threading\n\nfrom gi import require_version...
[ { "content": "Output the full code verbatim (no extra comments):\n<|memory_start|>```python\n#\n# bluetooth_config.py\n#\n# Copyright (C) 2016 - 2018 Kano Computing Ltd.\n# License: http://www.gnu.org/licenses/gpl-2.0.txt GNU GPLv2\n#\n# Bluetooth setup screen\n#\n\nimport os\nimport threading\n\nfrom gi import...
```python # # bluetooth_config.py # # Copyright (C) 2016 - 2018 Kano Computing Ltd. # License: http://www.gnu.org/licenses/gpl-2.0.txt GNU GPLv2 # # Bluetooth setup screen # import os import threading from gi import require_version require_version('Gtk', '3.0') from gi.repository import Gtk, GObject from kano.gtk3.scrolled_window import ScrolledWindow from kano.gtk3.buttons import KanoButton from kano.gtk3.kano_dialog import KanoDialog from kano.gtk3.blur_overlay import BlurOverlay from kano.logging import logger from kano.decorators import queue_cb from kano_settings.common import IMAGES_DIR from kano_settings.templates import Template from kano_settings.system.bt.interface import is_bluetooth_available, \ device_scan class BluetoothDeviceItem(Gtk.Box): __gsignals__ = { 'pairing': (GObject.SIGNAL_RUN_FIRST, GObject.TYPE_NONE, ()), 'done-pairing': (GObject.SIGNAL_RUN_FIRST, GObject.TYPE_NONE, ()), } def __init__(self, device): Gtk.Box.__init__(self, hexpand=True) self.device = device device_name = device.name dev_label = Gtk.Label(device_name, hexpand=True) dev_label.get_style_context().add_class('normal_label') self.pack_start(dev_label, False, False, 0) self._pair_button = KanoButton() self._set_paired_button_state() self._pair_button.set_margin_top(10) self._pair_button.set_margin_bottom(10) self._pair_button.set_margin_left(10) self._pair_button.set_margin_right(10) self._pair_button.connect('clicked', self.pair) self.pack_start(self._pair_button, False, False, 0) def _set_paired_button_state(self, *dummy_args, **dummy_kwargs): if not self.device.connected: label = _("PAIR") colour = 'green' else: label = _("UNPAIR") colour = 'red' self._pair_button.set_label(label) self._pair_button.set_color(colour) def error(self, err_msg): KanoDialog(err_msg).run() def pair(self, *dummy_args, **dummy_kwargs): def done_pairing(): self._set_paired_button_state() self.emit('done-pairing') @queue_cb(callback=done_pairing, gtk=True) def do_pair(): if not self.device.fuse(): GObject.idle_add(self.error, _("Pairing failed")) @queue_cb(callback=done_pairing, gtk=True) def do_unpair(): if not self.device.unfuse(): GObject.idle_add(self.error, _("Unpairing failed")) self.emit('pairing') if self.device.connected: pair_fn = do_unpair logger.info("Unpairing {}".format(self.device)) else: pair_fn = do_pair logger.info("Pairing {}".format(self.device)) pair_thr = threading.Thread(target=pair_fn) pair_thr.start() class BluetoothDevicesList(ScrolledWindow): __gsignals__ = { 'loading': (GObject.SIGNAL_RUN_FIRST, GObject.TYPE_NONE, ()), 'done-loading': (GObject.SIGNAL_RUN_FIRST, GObject.TYPE_NONE, ()), } def __init__(self): ScrolledWindow.__init__(self, hexpand=True, vexpand=True) self.set_size_request(500, 300) self.contents = Gtk.Box(orientation=Gtk.Orientation.VERTICAL) self.add_with_viewport(self.contents) self.devices = [] self.dev_view = Gtk.Box(orientation=Gtk.Orientation.VERTICAL) self.contents.pack_start(self.dev_view, False, False, 0) def add_device(self, device, idx=0): dev_item = BluetoothDeviceItem(device) dev_item.connect('pairing', self.set_loading) dev_item.connect('done-pairing', self.unset_loading) css_class = 'white-bg' if idx % 2 else 'grey-bg' dev_item.get_style_context().add_class(css_class) self.dev_view.pack_start(dev_item, False, False, 0) self.dev_view.show_all() def empty(self): for device in self.dev_view.get_children(): self.dev_view.remove(device) def set_no_adapter_available(self): no_adapter = Gtk.Label(_("No bluetooth dongle detected")) no_adapter.get_style_context().add_class('normal_label') self.dev_view.pack_start(no_adapter, False, False, 0) self.dev_view.show_all() def set_no_devices_nearby(self): no_dev = Gtk.Label(_("No devices found nearby")) no_dev.get_style_context().add_class('normal_label') self.dev_view.pack_start(no_dev, False, False, 0) self.dev_view.show_all() def set_loading(self, *dummy_args, **dummy_kwargs): logger.debug("loading...") self.emit('loading') def unset_loading(self, *dummy_args, **dummy_kwargs): logger.debug("done loading") self.emit('done-loading') def populate(self): def _end_populate(): self.unset_loading() @queue_cb(callback=_end_populate, gtk=True) def _do_populate(devices): if not devices: logger.info("No devices") GObject.idle_add(self.set_no_devices_nearby) for idx, device in enumerate(devices): logger.info("Adding device {}".format(device)) GObject.idle_add(self.add_device, device, idx) if not is_bluetooth_available(): logger.info("No adapter") self.set_no_adapter_available() return self.set_loading() device_scan(_do_populate) def refresh(self, *dummy_args, **dummy_kwargs): self.empty() self.populate() class BluetoothConfig(Template): def __init__(self, win): Template.__init__( self, _("Bluetooth"), _("Connect to bluetooth devices"), _("APPLY CHANGES"), win.is_plug(), back_btn=True ) self.win = win self.win.set_main_widget(self) self.win.top_bar.enable_prev() self.win.change_prev_callback(self.win.go_to_home) self._overlay = BlurOverlay() self.box.pack_start(self._overlay, False, False, 0) self._contents = Gtk.Box(orientation=Gtk.Orientation.VERTICAL) self.fill_contents() self._overlay.add(self._contents) self._refresh_btn = None self._done_btn = None self._arrange_buttons() self.show_all() self.dev_list.refresh() def _arrange_buttons(self): self.remove(self.kano_button.align) btn_box = Gtk.Box() btn_box.set_valign(Gtk.Align.CENTER) btn_box.set_halign(Gtk.Align.CENTER) btn_box.set_margin_top(30) btn_box.set_margin_bottom(30) self._refresh_btn = refresh_button = KanoButton(color='orange') refresh_icon_filepath = os.path.join(IMAGES_DIR, 'refresh.png') refresh_icon = Gtk.Image.new_from_file(refresh_icon_filepath) refresh_button.set_image(refresh_icon) refresh_button.set_margin_right(10) refresh_button.connect('clicked', self.dev_list.refresh) btn_box.pack_start(refresh_button, False, False, 0) self._done_button = done_btn = KanoButton(_("DONE")) done_btn.connect('clicked', self.win.go_to_home) btn_box.pack_start(done_btn, False, False, 0) self.pack_end(btn_box, False, False, 0) def fill_contents(self): self.dev_list = BluetoothDevicesList() self.dev_list.connect('loading', self.blur) self.dev_list.connect('done-loading', self.unblur) self._contents.pack_start(self.dev_list, False, False, 0) def blur(self, *dummy_args, **dummy_kwargs): self._overlay.blur() self._refresh_btn.set_sensitive(False) self._done_button.set_sensitive(False) self.win.top_bar.disable_prev() def unblur(self, *dummy_args, **dummy_kwargs): self._overlay.unblur() self._refresh_btn.set_sensitive(True) self._done_button.set_sensitive(True) self.win.top_bar.enable_prev() ```
[ { "content": "Here is a code file:\n```python\n# #\n# Copyright 2013-2016 Ghent University\n#\n# This file is part of EasyBuild,\n# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),\n# with support of Ghent University (http://ugent.be/hpc),\n# the Flemish Supercomputer Centre (VSC...
[ { "content": "Here is a code file:\n<|memory_start|>```python\n# #\n# Copyright 2013-2016 Ghent University\n#\n# This file is part of EasyBuild,\n# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),\n# with support of Ghent University (http://ugent.be/hpc),\n# the Flemish Supercomp...
```python # # # Copyright 2013-2016 Ghent University # # This file is part of EasyBuild, # originally created by the HPC team of Ghent University (http://ugent.be/hpc/en), # with support of Ghent University (http://ugent.be/hpc), # the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be), # Flemish Research Foundation (FWO) (http://www.fwo.be/en) # and the Department of Economy, Science and Innovation (EWI) (http://www.ewi-vlaanderen.be/en). # # http://github.com/hpcugent/easybuild # # EasyBuild 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 v2. # # EasyBuild 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 EasyBuild. If not, see <http://www.gnu.org/licenses/>. # # """ This describes the easyconfig format versions 2.x This is a mix between version 1.0 and configparser-style configuration @author: Stijn De Weirdt (Ghent University) @author: Kenneth Hoste (Ghent University) """ import copy import re from easybuild.framework.easyconfig.format.pyheaderconfigobj import EasyConfigFormatConfigObj from easybuild.framework.easyconfig.format.format import EBConfigObj from easybuild.framework.easyconfig.format.version import EasyVersion, ToolchainVersionOperator, VersionOperator from easybuild.tools.build_log import EasyBuildError class FormatTwoZero(EasyConfigFormatConfigObj): """ Support for easyconfig format 2.0 Simple extension of FormatOneZero with configparser blocks Doesn't set version and toolchain/toolchain version like in FormatOneZero; referencing 'version' directly in pyheader doesn't work => use templating '%(version)s' NOT in 2.0 - order preservation: need more recent ConfigObj (more recent Python as minimal version) - nested sections (need other ConfigParser/ConfigObj, eg INITools) - type validation - command line generation (--try-X command line options) """ VERSION = EasyVersion('2.0') USABLE = True PYHEADER_ALLOWED_BUILTINS = ['len', 'False', 'True'] PYHEADER_MANDATORY = ['name', 'homepage', 'description', 'software_license', 'software_license_urls', 'docurls'] PYHEADER_BLACKLIST = ['version', 'toolchain'] NAME_DOCSTRING_REGEX_TEMPLATE = r'^\s*@%s\s*:\s*(?P<name>\S.*?)\s*$' # non-greedy match in named pattern AUTHOR_DOCSTRING_REGEX = re.compile(NAME_DOCSTRING_REGEX_TEMPLATE % 'author', re.M) MAINTAINER_DOCSTRING_REGEX = re.compile(NAME_DOCSTRING_REGEX_TEMPLATE % 'maintainer', re.M) AUTHOR_REQUIRED = True MAINTAINER_REQUIRED = False def validate(self): """Format validation""" self._check_docstring() self._validate_pyheader() def _check_docstring(self): """ Verify docstring. field @author: people who contributed to the easyconfig field @maintainer: people who can be contacted in case of problems """ authors = [] maintainers = [] for auth_reg in self.AUTHOR_DOCSTRING_REGEX.finditer(self.docstring): res = auth_reg.groupdict() authors.append(res['name']) for maint_reg in self.MAINTAINER_DOCSTRING_REGEX.finditer(self.docstring): res = maint_reg.groupdict() maintainers.append(res['name']) if self.AUTHOR_REQUIRED and not authors: raise EasyBuildError("No author in docstring (regex: '%s')", self.AUTHOR_DOCSTRING_REGEX.pattern) if self.MAINTAINER_REQUIRED and not maintainers: raise EasyBuildError("No maintainer in docstring (regex: '%s')", self.MAINTAINER_DOCSTRING_REGEX.pattern) def get_config_dict(self): """Return the best matching easyconfig dict""" self.log.experimental(self.__class__.__name__) # the toolchain name/version should not be specified in the pyheader, # but other toolchain options are allowed cfg = copy.deepcopy(self.pyheader_localvars) self.log.debug("Config dict based on Python header: %s" % cfg) co = EBConfigObj(self.configobj) version = self.specs.get('version', None) tc_spec = self.specs.get('toolchain', {}) toolchain_name = tc_spec.get('name', None) toolchain_version = tc_spec.get('version', None) # parse and interpret, dealing with defaults etc version, tcname, tcversion = co.get_version_toolchain(version, toolchain_name, toolchain_version) # format 2.0 will squash self.log.debug('Squashing with version %s and toolchain %s' % (version, (tcname, tcversion))) res = co.squash(version, tcname, tcversion) cfg.update(res) self.log.debug("Config dict after processing applicable easyconfig sections: %s" % cfg) # FIXME what about updating dict values/appending to list values? # FIXME how do we allow both redefining and updating? = and +=? # update config with correct version/toolchain (to avoid using values specified in default section) cfg.update({ 'version': version, 'toolchain': {'name': tcname, 'version': tcversion}, }) self.log.debug("Final config dict (including correct version/toolchain): %s" % cfg) return cfg def extract_comments(self, rawtxt): """Extract comments from raw content.""" # this is fine-ish, it only implies that comments will be lost for format v2 easyconfig files that are dumped self.log.warning("Extraction of comments not supported yet for easyconfig format v2") ```
[ { "content": "Write out the code verbatim, preserving indentation and whitespace:\n```python\nimport json\nimport requests\nfrom bs4 import BeautifulSoup\nfrom .payload import Payload, Author, Affiliation\nfrom metadata import nmd\nfrom metadata import bioaging\nimport re\n\n\ndef map(url):\n meta = Payload(...
[ { "content": "Write out the code verbatim, preserving indentation and whitespace:\n<|memory_start|>```python\nimport json\nimport requests\nfrom bs4 import BeautifulSoup\nfrom .payload import Payload, Author, Affiliation\nfrom metadata import nmd\nfrom metadata import bioaging\nimport re\n\n\ndef map(url):\n ...
```python import json import requests from bs4 import BeautifulSoup from .payload import Payload, Author, Affiliation from metadata import nmd from metadata import bioaging import re def map(url): meta = Payload() headers = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36', 'From': 'youremail@domain.com' } try: r = requests.get(url, headers=headers) except: return {} html = BeautifulSoup(r.content, 'html.parser') r.close() if 'nmd-journal' in r.url: return nmd.map(url) elif 'neurobiologyofaging' in r.url: return bioaging.map(url) td = html.find('script', {'type': 'application/json'}) if td is None: return map2(html) data = td.contents[0].replace('\\\\', '\\') data = data.replace(r'\"', '"') obj = json.loads(data[1:-1]) meta.publication_date = obj['article']['dates']['Publication date'] if 'Received' in obj['article']['dates']: meta.received = obj['article']['dates']['Received'] meta.online_date = obj['article']['dates']['Available online'] for name in obj['authors']['authors']: member = obj['authors']['authors'][name] location = [] if not member['refs']: for loc in obj['authors']['affiliations']: location.append(obj['authors']['affiliations'][loc]) for loc in member['refs']: if 'af' in loc.lower(): location.append(obj['authors']['affiliations'][loc]) else: continue if not location: for af in obj['authors']['affiliations']: location.append(obj['authors']['affiliations'][af]) meta.authors.append(Author(member['surname'], member['givenName'], location)) meta.keywords = [] meta.references = '' meta.language = '' meta.journal_title = obj['article']['srctitle'] meta.issn = obj['article']['issn'] meta.doi = obj['article']['doi'] meta.title = obj['article']['titlePlain'] meta.pages.first = obj['article']['pages'][0]['first-page'] meta.pages.last = obj['article']['pages'][0]['last-page'] if 'last-page' in obj['article']['pages'][0] else '' meta.issues.first = obj['article']['iss-first'] if 'iss-first' in obj['article'] else '' meta.issues.last = obj['article']['iss-last'] if 'iss-last' in obj['article'] else '' meta.volumes.first = obj['article']['vol-first'] meta.volumes.last = obj['article']['vol-last'] if 'vol-last' in obj['article'] else '' meta.publisher = obj['article']['imprintPublisher']['displayName'] return meta def map2(html): meta = Payload() td = html.find('title') if td: data = td.contents[0] meta.title = str(data).strip() td = html.find('ul', {'class': 'authorGroup'}) authors = {} affiliation = {} if td: for li in td.children: reference = [] name = str(li.find_all('a')[0].contents[0]) if li.find('sup'): for sup in li.find_all('sup'): if sup.contents[0].isalpha(): reference.append(str(sup.contents[0])) else: reference.append('a') authors[name] = reference td = html.find('ul', {'class': 'affiliation'}) if td: for li in td.children: if li.find('sup'): reference = str(li.find('sup').contents[0]) else: reference = 'a' institute = str(li.find('span').contents[0]) affiliation[reference] = institute for author in authors: writer = Author(author) for ref in authors[author]: writer.affiliations.append(Affiliation(affiliation[ref])) meta.authors.append(writer) td = html.find('p', {'class': 'volIssue'}) for token in td.text.split(','): if 'volume' in token.lower(): m = re.search('([0-9]+).([0-9]+)', token) if not m: m = re.search('([0-9]+)', token) meta.volumes.first = str(m.group(1)) continue meta.volumes.first = m.group(0) meta.volumes.last = m.group(1) elif 'issue' in token.lower(): m = re.search('([0-9]+).([0-9]+)', token) if not m: m = re.search('([0-9]+)', token) meta.issues.first = m.group(1) continue meta.issues.first = m.group(1) meta.issues.last = m.group(2) elif 'page' in token.lower(): m = re.search('([0-9]+).([0-9]+)', token) if not m: m = re.search('([0-9]+)', token) meta.pages.first = m.group(1) continue meta.pages.first = m.group(1) meta.pages.last = m.group(2) td = html.find('div', {'class': 'title'}) meta.journal_title = str(td.find('span').contents[0]) meta.publisher = 'Elsevier' td = html.find('dl', {'class': 'articleDates'}) data = td.find('dd').contents[0].split(',') accepted = '' online = '' received = '' for dates in data: if 'accepted' in dates.lower(): m = re.search('([0-9]+.*[0-9]+)', dates) accepted = str(m.group(0)) elif 'available' in dates.lower(): m = re.search('([0-9]+.*[0-9]+)', dates) online = str(m.group(0)) elif 'received' in dates.lower(): m = re.search('([0-9]+.*[0-9]+)', dates) received = str(m.group(0)) meta.online_date = online meta.publication_date = accepted meta.received = received td = html.find_all('script') doi = False for script in td: for element in script.contents: if 'doi' in element: for item in element.split(';'): if 'SDM.doi' in item: m = re.search("'(.*)'", item) data = m.groups() meta.doi = str(data[0]) doi = True break if doi: break if doi: break td = html.find('ul', {'class': 'keyword'}) if td: for keyword in td.text.split(';'): meta.keywords.append(keyword.strip()) return meta ```
[ { "content": "Here is the snippet:\n```python\nimport os\nimport io\nimport itertools\nimport types\nfrom ochre.Sequence import Seq\n\n\nclass SeqList(object):\n \"\"\"\n A Python object that represents a collection of sequences.\n The underlying storage can be in a file (through the\n subclass File...
[ { "content": "Here is the snippet:\n<|memory_start|>```python\nimport os\nimport io\nimport itertools\nimport types\nfrom ochre.Sequence import Seq\n\n\nclass SeqList(object):\n \"\"\"\n A Python object that represents a collection of sequences.\n The underlying storage can be in a file (through the\n ...
```python import os import io import itertools import types from ochre.Sequence import Seq class SeqList(object): """ A Python object that represents a collection of sequences. The underlying storage can be in a file (through the subclass FileSeqList) or in a list of Seq objects. """ def __new__(cls, sqlst, *args, **kwargs): from ochre.FileSeqList import FileSeqList if isinstance(sqlst, str): if os.path.extsep in sqlst or os.path.sep in sqlst: # probably a file #TODO: check if URL _file = open(sqlst, 'r') return super(SeqList, cls).__new__(FileSeqList, _file, *args, **kwargs) elif isinstance(sqlst, io.IOBase): return super(SeqList, cls).__new__(FileSeqList, sqlst, *args, **kwargs) # for python 2, we need to do the following check try: if isinstance(sqlst, file): return super(SeqList, cls).__new__(FileSeqList, sqlst, *args, **kwargs) except NameError: pass # end python 2 code return super(SeqList, cls).__new__(SeqList, sqlst, *args, **kwargs) def __init__(self, sqlst, loose_indexing=False, other=None): """ Create a list of sequences. Parameters: sqlst (file, str, list): data to create the list of sequences from. If *sqlst* is a file or string containing a path delimiter (typically / or .) read that file and return the sequences within. If *sqlst* is a string, separate it by comma and return each sequence. If *sqlst* is a list, make each item into a sequence. loose_indexing (bool): if true, match sequences that start with a given string and not the entire string, i.e. seqlist['te'] will match a sequence with the key, 'test'. other_csv (file, str): a csv file containing a list of data associated with each sequence, e.g. coverages, OTUs, etc. in the format: "SeqName, Data1, Data2, ..." Data1, Data2, etc can then be obtained from the sequence through the info parameter. """ if isinstance(sqlst, str): self._seqs = [Seq(s) for s in sqlst.split(',')] elif isinstance(sqlst, list): if isinstance(sqlst[0], str): self._seqs = [Seq(s) for s in sqlst] elif isinstance(sqlst[0], Seq): self._seqs = sqlst elif isinstance(sqlst, itertools.islice) or \ isinstance(sqlst, types.GeneratorType): self._seqs = list(sqlst) elif sqlst is not None: # sqlst should be none if this is getting called # from FileSeqList, because that's already handling # the same things with _file raise TypeError('sqlst is not a file, str, or list.') if other is not None: if isinstance(sqlst, str): other = open(other, 'r') keys = other.readline().split(',')[1:] self._other = {} for ln in other: sep = ln.split(',')[1:] self._other[1:] = dict(zip(keys, sep[1:])) if self._seqs is not None: for s in self._seqs: s.info = self._other.get(s.name, {}) else: self._other = None self.loose_indexing = loose_indexing def __len__(self): return len(self._seqs) def __iter__(self): for s in self._seqs: yield s def __getitem__(self, key): if isinstance(key, str): for itm in self: if itm.name == key: return itm elif itm.name.startswith(key) and self.loose_indexing: return itm raise KeyError(str(key)) elif isinstance(key, slice): return SeqList(itertools.islice(iter(self), \ key.start, key.stop, key.step)) else: try: return next(itertools.islice(iter(self), key, key + 1)) except StopIteration: raise IndexError("List index out of range.") def get_file(self, frmt='fa', fdir=None): """ Write my sequences to disk in a file *seqs-######* in the directory *fdir* making sure they're in a format specified by the list "frmt" and return a FileSeqList. Useful for quickly getting a file in the correct format to pass onto an external program. Parameters: frmt (str): a file type (e.g. FASTA, FASTQ, etc) (default: FASTA) fdir (str): a directory to save the file in (default: the temp directory) Returns: the file name of the saved sequences """ from ochre.External.External import temp if isinstance(frmt, str): frmt = (frmt,) fname = 'seqs-' + str(id(self)) + '.' + frmt[0] if fdir is None: file_name = temp(fname) else: file_name = os.path.join(fdir, fname) self.write(file_name, frmt[0]) return file_name def write(self, filename, file_type=None): """ Write out my sequences to a file. Parameters: filename (str): the name of the file to write to file_type (str): a file type (e.g. FASTA, FASTQ, etc) (default: determine from the file name, otherwise FASTA) """ from ochre.FileSeqList import FileSeqList from ochre.FileFormats.FileFormats import guess_filetype, file_writer if hasattr(filename, 'write'): fh = filename filename = fh.name else: fh = open(filename, 'w') if file_type is None: ftype = guess_filetype(filename.split(os.path.extsep)[-1]) if ftype == '': ftype = 'fa' # return a FASTA file if nothing else else: ftype = guess_filetype(file_type) file_writer(ftype, fh, self) if filename != '<stdout>': fh.close() return FileSeqList(filename) def n(self, interval=0.5): """ Calculate N-values (i.e. N50) from a group of sequences Parameters: interval (float): a percentage Returns: *interval* percentage of the bases in this file are in a sequence of this length or longer """ seq_len = [len(seq) for seq in self] seq_len.sort(reverse=True) s = sum(seq_len) limit = s * (1 - interval) for l in seq_len: s -= l if s <= limit: return l def filter(self, min_len=None, max_len=None, min_gc=None, \ max_gc=None, min_cov=None, max_cov=None): pass def sample(self, n, replace=False): """ Randomly sample sequences from this seqlist. Parameters: n (int): number of sequences to sample replace (bool): sample with replacement? (default: False) Returns: SeqList with *n* sampled sequences. """ import random if replace: return SeqList(random.choice(list(self)) for _ in range(n)) else: return SeqList(random.sample(list(self), n)) def stats(self): """'Quick' statistics on sequences.""" seqs, bps = len(self), sum(len(s) for s in self) o = 'Sequences: ' + str(seqs) + '\n' o += 'Basepairs: ' + str(bps) + '\n\n' o += 'Shortest: ' + str(min(len(s) for s in self)) + ' bp\n' o += 'N90: ' + str(self.n(0.9)) + ' bp\n' o += 'Average: ' + str(bps / seqs) + ' bp\n' o += 'N50: ' + str(self.n(0.5)) + ' bp\n' o += 'N10: ' + str(self.n(0.1)) + ' bp\n' o += 'Longest: ' + str(max(len(s) for s in self)) + ' bp' return o ```
[ { "content": "Repeat the code exactly as the original, including blank lines:\n```python\n# -*- coding: utf-8 -*-\n# Copyright 2012 Loris Corazza, Sakis Christakidis\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\...
[ { "content": "Repeat the code exactly as the original, including blank lines:\n<|memory_start|>```python\n# -*- coding: utf-8 -*-\n# Copyright 2012 Loris Corazza, Sakis Christakidis\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance wi...
```python # -*- coding: utf-8 -*- # Copyright 2012 Loris Corazza, Sakis Christakidis # # 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 p2ner.base.ControlMessage import ControlMessage, trap_sent,probe_all,BaseControlMessage from p2ner.base.Consts import MessageCodes as MSG from construct import Container class AskInitNeighs(BaseControlMessage): type = "subsidmessage" code = MSG.ASK_INIT_NEIGHS_SUB ack = True @classmethod def send(cls, sid, superOverlay,interOverlay, peer, out): d=out.send(cls, Container(streamid = sid, superOverlay=superOverlay, interOverlay=interOverlay), peer) d.addErrback(trap_sent) return d class PeerListMessage(ControlMessage): type = "subpeerlistmessage" code = MSG.SEND_IP_LIST_SUB ack = True def trigger(self, message): if self.stream.id != message.streamid or not self.subOverlay.checkTriggerInitiatorsMessage(message.superOverlay,message.interOverlay): return False return True def action(self, message, peer): self.log.debug('received peerList message from %s for %s',peer,str(message.peer)) if message.peer: for p in message.peer: self.subOverlay.checkSendAddNeighbour(p,peer) else: self.subOverlay.checkSendAddNeighbour(None,peer) @classmethod def send(cls, sid, peerlist, peer, out): return out.send(cls, Container(streamid=sid, peer=peerlist), peer).addErrback(trap_sent) class AddNeighbourMessage(ControlMessage): type = "suboverlaymessage" code = MSG.ADD_NEIGH_SUB ack = True def trigger(self, message): if self.stream.id != message.streamid or not self.subOverlay.checkTriggerMessage(message.superOverlay,message.interOverlay): return False return True def action(self, message, peer): peer.dataPort=message.port peer.reportedBW=message.bw if message.peer: peer.lip=message.peer.ip peer.lport=message.peer.port peer.ldataPort=message.peer.dataPort peer.hpunch=message.peer.hpunch self.log.debug('received add neigh message from %s',peer) print 'received neigh message from ',peer self.subOverlay.checkAcceptNeighbour(peer) @classmethod def send(cls, id,sOver,iOver,port,bw, inpeer, peer, out): msg = Container(streamid=id,superOverlay=sOver,interOverlay=iOver,port=int(port), bw=bw,peer=inpeer) d=out.send(cls, msg, peer) d.addErrback(trap_sent) return d class ConfirmNeighbourMessage(ControlMessage): type = "subsidmessage" code = MSG.CONFIRM_NEIGH_SUB ack = True def trigger(self, message): if self.stream.id != message.streamid or not self.subOverlay.checkTriggerMessage(message.superOverlay,message.interOverlay): return False return True def action(self, message, peer): self.subOverlay.addNeighbour(peer) @classmethod def send(cls, sid, sOver,iOver,peer, out): d=out.send(cls, Container(streamid = sid, superOverlay=sOver, interOverlay=iOver), peer) d.addErrback(trap_sent) return d class SuggestNewPeerMessage(ControlMessage): type = "subpeerlistmessage" code = MSG.SUGGEST_NEW_PEER_SUB ack = True def trigger(self, message): if self.stream.id != message.streamid or not self.subOverlay.checkTriggerMessage(message.superOverlay,message.interOverlay): return False return True def action(self, message, peer): self.log.debug('received suggest new peer message from %s',peer) self.subOverlay.suggestNewPeer(peer,message.peer) @classmethod def send(cls, sid,sover,iover, peerlist, peer, out, suc_func=None,err_func=None): return out.send(cls, Container(streamid=sid, superOverlay=sover, interOverlay=iover, peer=peerlist), peer).addErrback(probe_all,err_func=err_func,suc_func=suc_func) class SuggestMessage(ControlMessage): type = "subpeerlistmessage" code = MSG.SUGGEST_SUB ack = True def trigger(self, message): if self.stream.id != message.streamid or not self.subOverlay.checkTriggerMessage(message.superOverlay,message.interOverlay): return False return True def action(self, message, peer): self.log.debug('received suggest message from %s',peer) self.subOverlay.availableNewPeers(peer,message.peer) @classmethod def send(cls, sid,sover,iover, peerlist, peer, out): return out.send(cls, Container(streamid=sid, superOverlay=sover,interOverlay=iover, peer=peerlist), peer).addErrback(trap_sent) class PingMessage(ControlMessage): type='basemessage' code=MSG.ADDNEIGH_RTT ack=True def trigger(self,message): return True def action(self,message,peer): return @classmethod def send(cls, peer, out): out.send(cls,Container(message=None),peer).addErrback(trap_sent) ```
[ { "content": "Here is the snippet:\n```python\n# -*- coding: utf-8 -*-\n\"\"\"\n werkzeug.testsuite.cache\n ~~~~~~~~~~~~~~~~~~~~~~~~\n\n Tests the cache system\n\n :copyright: (c) 2014 by Armin Ronacher.\n :license: BSD, see LICENSE for more details.\n\"\"\"\nimport os\nimport time\nimport unitte...
[ { "content": "Here is the snippet:\n<|memory_start|>```python\n# -*- coding: utf-8 -*-\n\"\"\"\n werkzeug.testsuite.cache\n ~~~~~~~~~~~~~~~~~~~~~~~~\n\n Tests the cache system\n\n :copyright: (c) 2014 by Armin Ronacher.\n :license: BSD, see LICENSE for more details.\n\"\"\"\nimport os\nimport tim...
```python # -*- coding: utf-8 -*- """ werkzeug.testsuite.cache ~~~~~~~~~~~~~~~~~~~~~~~~ Tests the cache system :copyright: (c) 2014 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ import os import time import unittest import tempfile import shutil from werkzeug.testsuite import WerkzeugTestCase from werkzeug.contrib import cache try: import redis try: from redis.exceptions import ConnectionError as RedisConnectionError cache.RedisCache(key_prefix='werkzeug-test-case:')._client.set('test','connection') except RedisConnectionError: redis = None except ImportError: redis = None try: import pylibmc as memcache except ImportError: try: from google.appengine.api import memcache except ImportError: try: import memcache except ImportError: memcache = None class CacheTestCase(WerkzeugTestCase): make_cache = None def test_generic_get_dict(self): c = self.make_cache() assert c.set('a', 'a') assert c.set('b', 'b') d = c.get_dict('a', 'b') assert 'a' in d assert 'a' == d['a'] assert 'b' in d assert 'b' == d['b'] def test_generic_set_many(self): c = self.make_cache() assert c.set_many({0: 0, 1: 1, 2: 4}) assert c.get(2) == 4 assert c.set_many((i, i*i) for i in range(3)) assert c.get(2) == 4 def test_generic_set_get(self): c = self.make_cache() for i in range(3): assert c.set(str(i), i * i) for i in range(3): result = c.get(str(i)) assert result == i * i, result def test_generic_get_set(self): c = self.make_cache() assert c.set('foo', ['bar']) assert c.get('foo') == ['bar'] def test_generic_get_many(self): c = self.make_cache() assert c.set('foo', ['bar']) assert c.set('spam', 'eggs') self.assert_equal(list(c.get_many('foo', 'spam')), [['bar'], 'eggs']) def test_generic_set_many(self): c = self.make_cache() assert c.set_many({'foo': 'bar', 'spam': ['eggs']}) assert c.get('foo') == 'bar' assert c.get('spam') == ['eggs'] def test_generic_expire(self): c = self.make_cache() assert c.set('foo', 'bar', 1) time.sleep(2) assert c.get('foo') is None def test_generic_add(self): c = self.make_cache() # sanity check that add() works like set() assert c.add('foo', 'bar') assert c.get('foo') == 'bar' assert not c.add('foo', 'qux') assert c.get('foo') == 'bar' def test_generic_delete(self): c = self.make_cache() assert c.add('foo', 'bar') assert c.get('foo') == 'bar' assert c.delete('foo') assert c.get('foo') is None def test_generic_delete_many(self): c = self.make_cache() assert c.add('foo', 'bar') assert c.add('spam', 'eggs') assert c.delete_many('foo', 'spam') assert c.get('foo') is None assert c.get('spam') is None def test_generic_inc_dec(self): c = self.make_cache() assert c.set('foo', 1) assert c.inc('foo') == c.get('foo') == 2 assert c.dec('foo') == c.get('foo') == 1 assert c.delete('foo') def test_generic_true_false(self): c = self.make_cache() assert c.set('foo', True) assert c.get('foo') == True assert c.set('bar', False) assert c.get('bar') == False class SimpleCacheTestCase(CacheTestCase): make_cache = cache.SimpleCache class FileSystemCacheTestCase(CacheTestCase): tmp_dir = None def make_cache(self, **kwargs): if self.tmp_dir is None: self.tmp_dir = tempfile.mkdtemp() return cache.FileSystemCache(cache_dir=self.tmp_dir, **kwargs) def teardown(self): if self.tmp_dir is not None: shutil.rmtree(self.tmp_dir) def test_filesystemcache_prune(self): THRESHOLD = 13 c = self.make_cache(threshold=THRESHOLD) for i in range(2 * THRESHOLD): assert c.set(str(i), i) cache_files = os.listdir(self.tmp_dir) assert len(cache_files) <= THRESHOLD def test_filesystemcache_clear(self): c = self.make_cache() assert c.set('foo', 'bar') cache_files = os.listdir(self.tmp_dir) assert len(cache_files) == 1 assert c.clear() cache_files = os.listdir(self.tmp_dir) assert len(cache_files) == 0 class RedisCacheTestCase(CacheTestCase): def make_cache(self): return cache.RedisCache(key_prefix='werkzeug-test-case:') def teardown(self): self.make_cache().clear() def test_compat(self): c = self.make_cache() assert c._client.set(c.key_prefix + 'foo', 'Awesome') self.assert_equal(c.get('foo'), b'Awesome') assert c._client.set(c.key_prefix + 'foo', '42') self.assert_equal(c.get('foo'), 42) class MemcachedCacheTestCase(CacheTestCase): def make_cache(self): return cache.MemcachedCache(key_prefix='werkzeug-test-case:') def teardown(self): self.make_cache().clear() def test_compat(self): c = self.make_cache() assert c._client.set(c.key_prefix + b'foo', 'bar') self.assert_equal(c.get('foo'), 'bar') def suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(SimpleCacheTestCase)) suite.addTest(unittest.makeSuite(FileSystemCacheTestCase)) if redis is not None: suite.addTest(unittest.makeSuite(RedisCacheTestCase)) if memcache is not None: suite.addTest(unittest.makeSuite(MemcachedCacheTestCase)) return suite ```
[ { "content": "```python\n# Generated by Django 2.1.2 on 2018-10-26 17:19\n\nfrom django.db import migrations, models\nimport django.utils.timezone\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('core', '0013_user_terms_accepted'),\n ]\n\n operations = [\n migrations.A...
[ { "content": "<|memory_start|>```python\n# Generated by Django 2.1.2 on 2018-10-26 17:19\n\nfrom django.db import migrations, models\nimport django.utils.timezone\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('core', '0013_user_terms_accepted'),\n ]\n\n operations = [\n ...
```python # Generated by Django 2.1.2 on 2018-10-26 17:19 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('core', '0013_user_terms_accepted'), ] operations = [ migrations.AddField( model_name='organization', name='created_at', field=models.DateTimeField(auto_now_add=True, default=django.utils.timezone.now), preserve_default=False, ), migrations.AddField( model_name='organization', name='updated_at', field=models.DateTimeField(auto_now=True), ), migrations.AddField( model_name='user', name='created_at', field=models.DateTimeField(auto_now_add=True, default=django.utils.timezone.now), preserve_default=False, ), migrations.AddField( model_name='user', name='updated_at', field=models.DateTimeField(auto_now=True), ), migrations.AlterField( model_name='user', name='terms_accepted', field=models.BooleanField(default=False), ), ] ```
[ { "content": "Repeat the following code:\n```python\n#Program using word problems to demonstrate math and number operators\n\nprint(\"If a 2000 pound pregnant hippo gives birth to a 100 pound calf,\")\nprint(\"but then eats 50 pounds of food, how much does she weigh?\")\ninput(\"Press the enter key to find out....
[ { "content": "Repeat the following code:\n<|memory_start|>```python\n#Program using word problems to demonstrate math and number operators\n\nprint(\"If a 2000 pound pregnant hippo gives birth to a 100 pound calf,\")\nprint(\"but then eats 50 pounds of food, how much does she weigh?\")\ninput(\"Press the enter ...
```python #Program using word problems to demonstrate math and number operators print("If a 2000 pound pregnant hippo gives birth to a 100 pound calf,") print("but then eats 50 pounds of food, how much does she weigh?") input("Press the enter key to find out.") print("2000 - 100 + 50 = ", 2000 - 100 + 50) print("\nIf an adventurer returns from a successful quest and buys each of") print("6 companions 3 bottles of ale, how many bottles are purchased?") input("Press the enter key to find out") print("6 * 3 = ",6 * 3) print("\nIf a restaurant check comes to 19 dollars with tip, and you and") print("your friends split it evenly 4 ways, how much do each of you throw in?") input("Press the enter key to find out.") print("19 / 4 = ", 19 / 4) print("\nIf a group of 4 pirates finds a chest full of 107 gold coins, and") print("they divide the botty evenly, how many whole coins does each get?") input("Press the enter key to find out.") print("107 // 4 = ", 107 // 4) print("\nIf the same group of 4 pirates evenly divides the chest full") print("of 107 gold coins, how many coins are left over?") input("Press the enter key to find out.") print("107 % 4 = ", 107 % 4) input("\n\nPress the enter key to exit") ```
[ { "content": "```python\n# -*- coding: utf-8 -*-\nimport sys\nimport os\nimport urllib\nimport urlparse\nimport xbmc\nimport xbmcgui\nimport xbmcplugin\nimport xbmcaddon\n\nif sys.version_info < (2, 7):\n import simplejson\nelse:\n import json as simplejson\n\n# Import the common settings\nfrom resources....
[ { "content": "<|memory_start|>```python\n# -*- coding: utf-8 -*-\nimport sys\nimport os\nimport urllib\nimport urlparse\nimport xbmc\nimport xbmcgui\nimport xbmcplugin\nimport xbmcaddon\n\nif sys.version_info < (2, 7):\n import simplejson\nelse:\n import json as simplejson\n\n# Import the common settings\...
```python # -*- coding: utf-8 -*- import sys import os import urllib import urlparse import xbmc import xbmcgui import xbmcplugin import xbmcaddon if sys.version_info < (2, 7): import simplejson else: import json as simplejson # Import the common settings from resources.lib.settings import Settings from resources.lib.settings import log from resources.lib.settings import os_path_join from resources.lib.database import PinSentryDB ADDON = xbmcaddon.Addon(id='script.pinsentry') ICON = ADDON.getAddonInfo('icon') FANART = ADDON.getAddonInfo('fanart') CWD = ADDON.getAddonInfo('path').decode("utf-8") ICON_DIR = xbmc.translatePath(os.path.join(CWD, 'resources', 'media', 'classifications').encode("utf-8")).decode("utf-8") ################################################################### # Class to handle the navigation information for the plugin ################################################################### class MenuNavigator(): MOVIES = 'movies' TVSHOWS = 'tvshows' MOVIESETS = 'sets' PLUGINS = 'plugins' MUSICVIDEOS = 'musicvideos' FILESOURCE = 'filesource' REPOSITORIES = 'repositories' TVCHANNELS = 'tvchannels' CLASSIFICATIONS = 'classifications' CLASSIFICATIONS_MOVIES = 'classifications-movies' CLASSIFICATIONS_TV = 'classifications-tv' def __init__(self, base_url, addon_handle): self.base_url = base_url self.addon_handle = addon_handle # Creates a URL for a directory def _build_url(self, query): return self.base_url + '?' + urllib.urlencode(query) # Display the default list of items in the root menu def showRootMenu(self): # Movies url = self._build_url({'mode': 'folder', 'foldername': MenuNavigator.MOVIES}) li = xbmcgui.ListItem(ADDON.getLocalizedString(32201), iconImage=ICON) li.setProperty("Fanart_Image", FANART) li.addContextMenuItems(self._getContextMenu(MenuNavigator.MOVIES), replaceItems=True) xbmcplugin.addDirectoryItem(handle=self.addon_handle, url=url, listitem=li, isFolder=True) # TV Shows url = self._build_url({'mode': 'folder', 'foldername': MenuNavigator.TVSHOWS}) li = xbmcgui.ListItem(ADDON.getLocalizedString(32202), iconImage=ICON) li.setProperty("Fanart_Image", FANART) li.addContextMenuItems(self._getContextMenu(MenuNavigator.TVSHOWS), replaceItems=True) xbmcplugin.addDirectoryItem(handle=self.addon_handle, url=url, listitem=li, isFolder=True) # Movie Sets url = self._build_url({'mode': 'folder', 'foldername': MenuNavigator.MOVIESETS}) li = xbmcgui.ListItem(ADDON.getLocalizedString(32203), iconImage=ICON) li.setProperty("Fanart_Image", FANART) li.addContextMenuItems(self._getContextMenu(MenuNavigator.MOVIESETS), replaceItems=True) xbmcplugin.addDirectoryItem(handle=self.addon_handle, url=url, listitem=li, isFolder=True) # Music Videos url = self._build_url({'mode': 'folder', 'foldername': MenuNavigator.MUSICVIDEOS}) li = xbmcgui.ListItem(ADDON.getLocalizedString(32205), iconImage=ICON) li.setProperty("Fanart_Image", FANART) li.addContextMenuItems(self._getContextMenu(MenuNavigator.MUSICVIDEOS), replaceItems=True) xbmcplugin.addDirectoryItem(handle=self.addon_handle, url=url, listitem=li, isFolder=True) # Plugins if Settings.isActivePlugins(): url = self._build_url({'mode': 'folder', 'foldername': MenuNavigator.PLUGINS}) li = xbmcgui.ListItem(ADDON.getLocalizedString(32128), iconImage=ICON) li.setProperty("Fanart_Image", FANART) li.addContextMenuItems([], replaceItems=True) xbmcplugin.addDirectoryItem(handle=self.addon_handle, url=url, listitem=li, isFolder=True) # Files if Settings.isActiveFileSource(): url = self._build_url({'mode': 'folder', 'foldername': MenuNavigator.FILESOURCE}) li = xbmcgui.ListItem(ADDON.getLocalizedString(32204), iconImage=ICON) li.setProperty("Fanart_Image", FANART) li.addContextMenuItems([], replaceItems=True) xbmcplugin.addDirectoryItem(handle=self.addon_handle, url=url, listitem=li, isFolder=True) # Classifications url = self._build_url({'mode': 'folder', 'foldername': MenuNavigator.CLASSIFICATIONS}) li = xbmcgui.ListItem(ADDON.getLocalizedString(32206), iconImage=ICON) li.setProperty("Fanart_Image", FANART) li.addContextMenuItems([], replaceItems=True) xbmcplugin.addDirectoryItem(handle=self.addon_handle, url=url, listitem=li, isFolder=True) # Repositories if Settings.isActiveRepositories(): url = self._build_url({'mode': 'folder', 'foldername': MenuNavigator.REPOSITORIES}) li = xbmcgui.ListItem(ADDON.getLocalizedString(32214), iconImage=ICON) li.setProperty("Fanart_Image", FANART) li.addContextMenuItems([], replaceItems=True) xbmcplugin.addDirectoryItem(handle=self.addon_handle, url=url, listitem=li, isFolder=True) # Live TV Channels if Settings.isActiveTvChannels(): url = self._build_url({'mode': 'folder', 'foldername': MenuNavigator.TVCHANNELS}) li = xbmcgui.ListItem(ADDON.getLocalizedString(32215), iconImage=ICON) li.setProperty("Fanart_Image", FANART) li.addContextMenuItems([], replaceItems=True) xbmcplugin.addDirectoryItem(handle=self.addon_handle, url=url, listitem=li, isFolder=True) # Add a blank line before the Operations li = xbmcgui.ListItem("", iconImage=ICON) li.setProperty("Fanart_Image", FANART) li.addContextMenuItems([], replaceItems=True) xbmcplugin.addDirectoryItem(handle=self.addon_handle, url="", listitem=li, isFolder=False) # Force Pin Entry url = self._build_url({'mode': 'forcepin', 'foldername': 'none'}) menuItemName = ADDON.getLocalizedString(32213) try: menuItemName = "[%s]" % menuItemName except: pass li = xbmcgui.ListItem(menuItemName, iconImage=ICON) li.setProperty("Fanart_Image", FANART) li.addContextMenuItems([], replaceItems=True) xbmcplugin.addDirectoryItem(handle=self.addon_handle, url=url, listitem=li, isFolder=False) xbmcplugin.endOfDirectory(self.addon_handle) # Show the list of videos in a given set def showFolder(self, foldername, type="", subType=""): # Check for the special case of manually defined folders if foldername == MenuNavigator.TVSHOWS: self._setList(MenuNavigator.TVSHOWS) elif foldername == MenuNavigator.MOVIES: self._setList(MenuNavigator.MOVIES) elif foldername == MenuNavigator.MOVIESETS: self._setList(MenuNavigator.MOVIESETS) elif foldername == MenuNavigator.MUSICVIDEOS: self._setList(MenuNavigator.MUSICVIDEOS) elif foldername == MenuNavigator.PLUGINS: self._setList(MenuNavigator.PLUGINS) elif foldername == MenuNavigator.FILESOURCE: self._setList(MenuNavigator.FILESOURCE) elif foldername == MenuNavigator.CLASSIFICATIONS: self._setClassificationList(type, subType) elif foldername == MenuNavigator.REPOSITORIES: self._setList(MenuNavigator.REPOSITORIES) elif foldername == MenuNavigator.TVCHANNELS: # Check the subType to work out which list we are showing if type in [None, ""]: self._setTvChannelGroupList() elif type == 'group': self._setTvChannelList(subType) # Produce the list of videos and flag which ones with security details def _setList(self, target): items = [] if target == MenuNavigator.PLUGINS: items = self._setPluginList() elif target == MenuNavigator.FILESOURCE: items = self._setFileSourceList() elif target == MenuNavigator.REPOSITORIES: items = self._setRepositoryList() else: # Everything other plugins are forms of video items = self._getVideos(target) # Now add the security details to the list items = self._addSecurityFlags(target, items) # Update the classifications items = self._cleanClassification(target, items) for item in items: # Create the list-item for this video li = xbmcgui.ListItem(item['title'], iconImage=item['thumbnail']) # Remove the default context menu li.addContextMenuItems([], replaceItems=True) # Get the title of the video title = item['title'] try: title = item['title'].encode("utf-8") except: pass # Make sure the dbid is coded correctly dbid = item['dbid'] try: dbid = item['dbid'].encode("utf-8") except: pass # Check if the classification is restricting this item isBlockedByClassification = False if 'mpaa' in item: if item['mpaa'] not in [None, ""]: isBlockedByClassification = True # Add a tick if security is set if item['securityLevel'] != 0: li.setInfo('video', {'PlayCount': 1}) # Not the best display format - but the only way that I can get a number to display # In the list, the problem is it will display 01:00 - but at least it's something if Settings.showSecurityLevelInPlugin(): li.setInfo('video', {'Duration': item['securityLevel']}) elif Settings.isHighlightClassificationUnprotectedVideos(): # If the user wishes to see which files are not protected by one of the rules # currently applied, we put the play signal next to them if not isBlockedByClassification: li.setProperty("TotalTime", "") li.setProperty("ResumeTime", "1") # Handle the case where we want to turn off security for a video if isBlockedByClassification and (item['securityLevel'] == -1): # This is the case where the user has forced access to be allowed, this # is useful if you have classification enabled and you want to allow a # given video for a classification to be unprotected li.setProperty("TotalTime", "") li.setProperty("ResumeTime", "1") li.setProperty("Fanart_Image", item['fanart']) url = self._build_url({'mode': 'setsecurity', 'level': item['securityLevel'], 'type': target, 'title': title, 'id': dbid, 'classificationBlocked': str(isBlockedByClassification)}) xbmcplugin.addDirectoryItem(handle=self.addon_handle, url=url, listitem=li, isFolder=False) xbmcplugin.endOfDirectory(self.addon_handle) # Do a lookup in the database for the given type of videos def _getVideos(self, target): jsonGet = 'GetMovies' dbid = 'movieid' extraDetails = ', "mpaa"' if target == MenuNavigator.TVSHOWS: jsonGet = 'GetTVShows' dbid = 'tvshowid' elif target == MenuNavigator.MOVIESETS: jsonGet = 'GetMovieSets' dbid = 'setid' extraDetails = "" elif target == MenuNavigator.MUSICVIDEOS: jsonGet = 'GetMusicVideos' dbid = 'musicvideoid' extraDetails = "" json_query = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "VideoLibrary.%s", "params": {"properties": ["title", "thumbnail", "fanart"%s], "sort": { "method": "title" } }, "id": 1}' % (jsonGet, extraDetails)) json_query = unicode(json_query, 'utf-8', errors='ignore') json_response = simplejson.loads(json_query) log(json_response) videolist = [] if ("result" in json_response) and (target in json_response['result']): for item in json_response['result'][target]: videoItem = {} try: videoItem['title'] = item['title'].encode("utf-8") except: log("setVideoList: Failed to encode title %s" % item['title']) videoItem['title'] = item['title'] if item['thumbnail'] in [None, ""]: videoItem['thumbnail'] = 'DefaultFolder.png' else: videoItem['thumbnail'] = item['thumbnail'] if item['fanart'] in [None, ""]: videoItem['fanart'] = FANART else: videoItem['fanart'] = item['fanart'] videoItem['dbid'] = item[dbid] if 'mpaa' in item: videoItem['mpaa'] = item['mpaa'] videolist.append(videoItem) return videolist # Adds the current security details to the items def _addSecurityFlags(self, type, items): # Make sure we have some items to append the details to if len(items) < 1: return items # Make the call to the DB to get all the specific security settings pinDB = PinSentryDB() securityDetails = {} if type == MenuNavigator.TVSHOWS: securityDetails = pinDB.getAllTvShowsSecurity() elif type == MenuNavigator.MOVIES: securityDetails = pinDB.getAllMoviesSecurity() elif type == MenuNavigator.MOVIESETS: securityDetails = pinDB.getAllMovieSetsSecurity() elif type == MenuNavigator.MUSICVIDEOS: securityDetails = pinDB.getAllMusicVideosSecurity() elif type == MenuNavigator.PLUGINS: securityDetails = pinDB.getAllPluginsSecurity() elif type == MenuNavigator.FILESOURCE: securityDetails = pinDB.getAllFileSourcesSecurity() elif type == MenuNavigator.REPOSITORIES: securityDetails = pinDB.getAllRepositoriesSecurity() for item in items: # Default security to 0 (Not Set) securityLevel = 0 if item['title'] in securityDetails: title = item['title'] securityLevel = securityDetails[title] log("PinSentryPlugin: %s has security level %d" % (title, securityLevel)) item['securityLevel'] = securityLevel del pinDB return items # Update the classifications def _cleanClassification(self, target, items): securityDetails = {} # Make the call to the DB to get all the specific security settings if target == MenuNavigator.MOVIES: pinDB = PinSentryDB() securityDetails = pinDB.getAllMovieClassificationSecurity(True) del pinDB elif target == MenuNavigator.TVSHOWS: pinDB = PinSentryDB() securityDetails = pinDB.getAllTvClassificationSecurity(True) del pinDB else: # No Classifications to deal with return items # Generate a list of certificates to check against certValues = securityDetails.keys() log("PinSentryPlugin: Allowing certificates for %s" % str(certValues)) # Check each of the items and add a flag if they are protected by a classification rule for item in items: if 'mpaa' in item: if item['mpaa'] not in [None, ""]: cert = item['mpaa'].strip().split(':')[-1] cert = cert.strip().split()[-1] try: cert = cert.encode("utf-8") except: log("PinSentryPlugin: Failed to encode certificate") # Need to decode the title as it doesn't link it for the logging that follows # if we don't title = item['title'] try: title = item['title'].decode("utf-8") except: log("PinSentryPlugin: Failed to decode title") if cert in certValues: item['mpaa'] = cert log("PinSentryPlugin: Setting mpaa for %s to %s" % (title, cert)) else: log("PinSentryPlugin: Clearing mpaa for %s (was %s)" % (title, item['mpaa'])) item['mpaa'] = "" return items # get the list of plugins installed on the system def _setPluginList(self): # Make the call to find out all the addons that are installed json_query = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "Addons.GetAddons", "params": { "type": "xbmc.python.pluginsource", "enabled": true, "properties": ["name", "thumbnail", "fanart"] }, "id": 1}') json_query = unicode(json_query, 'utf-8', errors='ignore') json_response = simplejson.loads(json_query) log(json_response) plugins = [] if ("result" in json_response) and ('addons' in json_response['result']): # Check each of the plugins that are installed on the system for addonItem in json_response['result']['addons']: addonId = addonItem['addonid'] # Need to skip ourselves if addonId in ['script.pinsentry']: log("setPluginList: Skipping PinSentry Plugin") continue pluginDetails = {} pluginDetails['title'] = addonItem['name'] pluginDetails['dbid'] = addonId if addonItem['thumbnail'] in [None, ""]: pluginDetails['thumbnail'] = 'DefaultAddon.png' else: pluginDetails['thumbnail'] = addonItem['thumbnail'] if addonItem['fanart'] in [None, ""]: pluginDetails['fanart'] = FANART else: pluginDetails['fanart'] = addonItem['fanart'] plugins.append(pluginDetails) return plugins # Get the list of repos installed on the system def _setRepositoryList(self): # Make the call to find out all the addons that are installed json_query = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "Addons.GetAddons", "params": { "type": "xbmc.addon.repository", "properties": ["name", "thumbnail", "fanart"] }, "id": 1}') json_query = unicode(json_query, 'utf-8', errors='ignore') json_response = simplejson.loads(json_query) log(json_response) repos = [] if ("result" in json_response) and ('addons' in json_response['result']): # Check each of the repos that are installed on the system for addonItem in json_response['result']['addons']: addonId = addonItem['addonid'] pluginDetails = {} pluginDetails['title'] = addonItem['name'] pluginDetails['dbid'] = addonId if addonItem['thumbnail'] in [None, ""]: pluginDetails['thumbnail'] = 'DefaultAddon.png' else: pluginDetails['thumbnail'] = addonItem['thumbnail'] if addonItem['fanart'] in [None, ""]: pluginDetails['fanart'] = FANART else: pluginDetails['fanart'] = addonItem['fanart'] repos.append(pluginDetails) return repos # Get the list of live TV Group Channels on the system def _setTvChannelGroupList(self): # Make the call to find out all the addons that are installed json_query = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "PVR.GetChannelGroups", "params": { "channeltype": "tv" }, "id": 1}') json_query = unicode(json_query, 'utf-8', errors='ignore') json_response = simplejson.loads(json_query) log(json_response) if ("result" in json_response) and ('channelgroups' in json_response['result']): # Check each of the channel groups that are installed on the system for pvrItem in json_response['result']['channelgroups']: # Create the list-item for this channel group li = xbmcgui.ListItem(pvrItem['label'], iconImage='DefaultAddonPVRClient.png') # Remove the default context menu li.addContextMenuItems([], replaceItems=True) li.setProperty("Fanart_Image", FANART) url = self._build_url({'mode': 'folder', 'foldername': MenuNavigator.TVCHANNELS, 'type': 'group', 'subtype': pvrItem['channelgroupid']}) xbmcplugin.addDirectoryItem(handle=self.addon_handle, url=url, listitem=li, isFolder=True) xbmcplugin.endOfDirectory(self.addon_handle) # Get the list of live TV Channels on the system def _setTvChannelList(self, groupId): # Make the call to find out all the addons that are installed json_query = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "PVR.GetChannels", "params": { "channelgroupid": %s, "properties": ["hidden", "thumbnail"] }, "id": 1}' % groupId) json_query = unicode(json_query, 'utf-8', errors='ignore') json_response = simplejson.loads(json_query) log(json_response) channels = [] if ("result" in json_response) and ('channels' in json_response['result']): # Load the existing security levels for the TV Channels pinDB = PinSentryDB() securityDetails = pinDB.getAllTvChannelsSecurity() del pinDB # Check each of the channel groups that are installed on the system for pvrItem in json_response['result']['channels']: # Skip hidden channels if pvrItem['hidden']: continue channelId = pvrItem['channelid'] # Get the name of the channel channelName = pvrItem['label'] try: channelName = pvrItem['label'].encode("utf-8") except: pass iconImage = 'DefaultAddonPVRClient.png' if pvrItem['thumbnail'] not in [None, ""]: iconImage = pvrItem['thumbnail'] securityLevel = 0 # Check the existing security level if channelName in securityDetails: securityLevel = securityDetails[channelName] li = xbmcgui.ListItem(pvrItem['label'], iconImage=iconImage) # Add a tick if security is set if securityLevel > 0: li.setInfo('video', {'PlayCount': 1}) # Remove the default context menu li.addContextMenuItems([], replaceItems=True) li.setProperty("Fanart_Image", FANART) url = self._build_url({'mode': 'setsecurity', 'type': MenuNavigator.TVCHANNELS, 'id': channelId, 'title': channelName, 'level': securityLevel}) xbmcplugin.addDirectoryItem(handle=self.addon_handle, url=url, listitem=li, isFolder=False) xbmcplugin.endOfDirectory(self.addon_handle) return channels # get the list of plugins installed on the system def _setFileSourceList(self): # Make the call to find out all the addons that are installed json_query = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "Files.GetSources", "params": { "media": "video" }, "id": 1}') json_query = unicode(json_query, 'utf-8', errors='ignore') json_response = simplejson.loads(json_query) log(json_response) fileSources = [] if ("result" in json_response) and ('sources' in json_response['result']): # Check each of the plugins that are installed on the system for fileSource in json_response['result']['sources']: fileDetails = {} fileDetails['title'] = fileSource['label'] fileDetails['dbid'] = fileSource['file'] fileDetails['thumbnail'] = 'DefaultFolder.png' fileDetails['fanart'] = FANART fileSources.append(fileDetails) return fileSources # Display the classification details def _setClassificationList(self, type="", subtype=""): classifications = () securityDetails = {} # Make the call to the DB to get all the specific security settings pinDB = PinSentryDB() if type == MenuNavigator.CLASSIFICATIONS_MOVIES: classifications = Settings.movieCassificationsNames securityDetails = pinDB.getAllMovieClassificationSecurity() elif type == MenuNavigator.CLASSIFICATIONS_TV: classifications = Settings.tvCassificationsNames securityDetails = pinDB.getAllTvClassificationSecurity() del pinDB # Check if we are showing the root classification listing if type in [None, ""]: url = self._build_url({'mode': 'folder', 'foldername': MenuNavigator.CLASSIFICATIONS, 'type': MenuNavigator.CLASSIFICATIONS_MOVIES}) li = xbmcgui.ListItem(ADDON.getLocalizedString(32207), iconImage=ICON) li.setProperty("Fanart_Image", FANART) li.addContextMenuItems([], replaceItems=True) xbmcplugin.addDirectoryItem(handle=self.addon_handle, url=url, listitem=li, isFolder=True) url = self._build_url({'mode': 'folder', 'foldername': MenuNavigator.CLASSIFICATIONS, 'type': MenuNavigator.CLASSIFICATIONS_TV}) li = xbmcgui.ListItem(ADDON.getLocalizedString(32208), iconImage=ICON) li.setProperty("Fanart_Image", FANART) li.addContextMenuItems([], replaceItems=True) xbmcplugin.addDirectoryItem(handle=self.addon_handle, url=url, listitem=li, isFolder=True) elif subtype in [None, ""]: # Get all the different language that are supported languages = [] for classification in classifications: if classification['lang'] not in languages: languages.append(classification['lang']) # Check to see if we can sort all the entries alphabetically for the given language try: languages = sorted(languages, key=ADDON.getLocalizedString) except: # If it fails to sort, then we just list them unsorted log("PinSentryPlugin: Failed to sort language list") # Now print out the item for each language for lang in languages: url = self._build_url({'mode': 'folder', 'foldername': MenuNavigator.CLASSIFICATIONS, 'type': type, 'subtype': str(lang)}) iconImage = ICON for flag in Settings.flags: if flag['lang'] == lang: iconImage = os_path_join(ICON_DIR, flag['icon']) li = xbmcgui.ListItem(ADDON.getLocalizedString(lang), iconImage=iconImage) li.setProperty("Fanart_Image", FANART) li.addContextMenuItems([], replaceItems=True) xbmcplugin.addDirectoryItem(handle=self.addon_handle, url=url, listitem=li, isFolder=True) else: for classification in classifications: # Check if we are looking for a specific country if subtype != str(classification['lang']): continue fullName = classification['name'] % ADDON.getLocalizedString(classification['lang']) idStr = str(classification['id']) securityLevel = 0 if idStr in securityDetails: securityLevel = securityDetails[idStr] log("PinSentryPlugin: Classification %s has security level %d" % (fullName, securityLevel)) # Set the icon to the certificate one if available iconImage = ICON if classification['icon'] not in [None, ""]: iconImage = os_path_join(ICON_DIR, classification['icon']) li = xbmcgui.ListItem(fullName, iconImage=iconImage) # Add a tick if security is set if securityLevel > 0: li.setInfo('video', {'PlayCount': 1}) li.setProperty("Fanart_Image", FANART) li.addContextMenuItems([], replaceItems=True) url = self._build_url({'mode': 'setsecurity', 'type': type, 'id': classification['id'], 'title': classification['match'], 'level': securityLevel}) xbmcplugin.addDirectoryItem(handle=self.addon_handle, url=url, listitem=li, isFolder=False) xbmcplugin.endOfDirectory(self.addon_handle) # Set the security value for a given video def setSecurity(self, type, title, id, oldLevel, classBlocked=False, forceLevel=None): log("Setting security for (id:%s) %s" % (id, title)) level = 1 # Check if we need to prompt the user or the new security level has been supplied if forceLevel is None: # Set the new security level to be used if oldLevel > 0: # Default is to disable it if it was enabled level = 0 numLevels = Settings.getNumberOfLevels() if numLevels > 1 or classBlocked: # Need to prompt the user to see which pin they are trying to set displayNameList = [] # Add the option to turn it off displayNameList.append("%s %s" % (ADDON.getLocalizedString(32211), ADDON.getLocalizedString(32013))) for i in range(1, numLevels + 1): secLevStr = str(i) if numLevels < 2: # If there is only one security level, use "On" rather than the number secLevStr = ADDON.getLocalizedString(32014) displayString = "%s %s" % (ADDON.getLocalizedString(32211), secLevStr) displayNameList.append(displayString) # Check if we need the option to disable a classification restriction if classBlocked: displayNameList.append(ADDON.getLocalizedString(32212)) select = xbmcgui.Dialog().select(ADDON.getLocalizedString(32001), displayNameList) if select != -1: level = select if classBlocked and (select >= (len(displayNameList) - 1)): level = -1 log("Setting security level to %d" % level) else: log("Exiting set security as no level selected") return else: level = forceLevel # This could take a little time to set the value so show the busy dialog xbmc.executebuiltin("ActivateWindow(busydialog)") if title not in [None, ""]: pinDB = PinSentryDB() if type == MenuNavigator.TVSHOWS: # Set the security level for this title, setting it to zero # will result in the entry being removed from the database # as the default for an item is unset pinDB.setTvShowSecurityLevel(title, int(id), level) elif type == MenuNavigator.MOVIES: pinDB.setMovieSecurityLevel(title, int(id), level) elif type == MenuNavigator.MOVIESETS: pinDB.setMovieSetSecurityLevel(title, int(id), level) # As well as setting the security on the Movie set, we need # to also set it on each movie in the Movie Set self._setSecurityOnMoviesInMovieSets(int(id), level) elif type == MenuNavigator.MUSICVIDEOS: pinDB.setMusicVideoSecurityLevel(title, int(id), level) elif type == MenuNavigator.PLUGINS: pinDB.setPluginSecurityLevel(title, id, level) elif type == MenuNavigator.REPOSITORIES: pinDB.setRepositorySecurityLevel(title, id, level) elif type == MenuNavigator.FILESOURCE: pinDB.setFileSourceSecurityLevel(title, id, level) elif type == MenuNavigator.CLASSIFICATIONS_MOVIES: pinDB.setMovieClassificationSecurityLevel(id, title, level) elif type == MenuNavigator.CLASSIFICATIONS_TV: pinDB.setTvClassificationSecurityLevel(id, title, level) elif type == MenuNavigator.TVCHANNELS: pinDB.setTvChannelSecurityLevel(title, id, level) del pinDB else: # Handle the bulk operations like set All security for the movies self._setBulkSecurity(type, level) xbmc.executebuiltin("Dialog.Close(busydialog)") xbmc.executebuiltin("Container.Refresh") # Sets the security details on all the Movies in a given Movie Set def _setSecurityOnMoviesInMovieSets(self, setid, level): log("Setting security for movies in movie set %d" % setid) # Get all the movies in the movie set json_query = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "VideoLibrary.GetMovieSetDetails", "params": { "setid": %d, "properties": ["title"] }, "id": 1}' % setid) json_query = unicode(json_query, 'utf-8', errors='ignore') json_response = simplejson.loads(json_query) log(json_response) if ("result" in json_response) and ('setdetails' in json_response['result']): if 'movies' in json_response['result']['setdetails']: for item in json_response['result']['setdetails']['movies']: # Now set the security on the movies in the set self.setSecurity(MenuNavigator.MOVIES, item['label'], item['movieid'], level, forceLevel=level) return # Performs an operation on all the elements of a given type def _setBulkSecurity(self, type, level): items = self._getVideos(type) for item in items: # Get the title of the video title = item['title'] try: title = item['title'].encode("utf-8") except: log("PinSentryPlugin: setBulkSecurity Failed to encode title %s" % title) self.setSecurity(type, title, item['dbid'], level, forceLevel=level) # Construct the context menu def _getContextMenu(self, type): ctxtMenu = [] if type in [MenuNavigator.TVSHOWS, MenuNavigator.MOVIES, MenuNavigator.MOVIESETS, MenuNavigator.MUSICVIDEOS]: # Clear All Security cmd = self._build_url({'mode': 'setsecurity', 'level': 0, 'type': type, 'forceLevel': 0}) ctxtMenu.append((ADDON.getLocalizedString(32209), 'RunPlugin(%s)' % cmd)) # Apply Security To All cmd = self._build_url({'mode': 'setsecurity', 'level': 1, 'type': type}) ctxtMenu.append((ADDON.getLocalizedString(32210), 'RunPlugin(%s)' % cmd)) return ctxtMenu ################################ # Main of the PinSentry Plugin ################################ if __name__ == '__main__': # If we have been called from the settings screen make sure that all the # dialogs (like the Addon Information Dialog) are closed if xbmc.getCondVisibility("Window.IsActive(10146)"): xbmc.executebuiltin("Dialog.Close(all, true)", True) # Get all the arguments base_url = sys.argv[0] addon_handle = int(sys.argv[1]) args = urlparse.parse_qs(sys.argv[2][1:]) # Record what the plugin deals with, files in our case xbmcplugin.setContent(addon_handle, 'files') # Get the current mode from the arguments, if none set, then use None mode = args.get('mode', None) log("PinSentryPlugin: Called with addon_handle = %d" % addon_handle) # If None, then at the root if mode is None: log("PinSentryPlugin: Mode is NONE - showing root menu") menuNav = MenuNavigator(base_url, addon_handle) menuNav.showRootMenu() del menuNav elif mode[0] == 'folder': log("PinSentryPlugin: Mode is FOLDER") # Get the actual folder that was navigated to foldername = args.get('foldername', None) type = args.get('type', None) subtype = args.get('subtype', None) if (foldername is not None) and (len(foldername) > 0): type1 = "" if (type is not None) and (len(type) > 0): type1 = type[0] subtype1 = "" if (subtype is not None) and (len(subtype) > 0): subtype1 = subtype[0] menuNav = MenuNavigator(base_url, addon_handle) menuNav.showFolder(foldername[0], type1, subtype1) del menuNav elif mode[0] == 'setsecurity': log("PinSentryPlugin: Mode is SET SECURITY") # Get the actual details of the selection type = args.get('type', None) title = args.get('title', None) level = args.get('level', None) id = args.get('id', None) classificationBlocked = args.get('classificationBlocked', None) forceLevel = args.get('forceLevel', None) if (type is not None) and (len(type) > 0): log("PinSentryPlugin: Type to set security for %s" % type[0]) secTitle = "" if (title is not None) and (len(title) > 0): secTitle = title[0] secLevel = 0 if (level is not None) and (len(level) > 0): secLevel = int(level[0]) dbid = "" if (id is not None) and (len(id) > 0): dbid = id[0] classBlocked = False if (classificationBlocked is not None) and (len(classificationBlocked) > 0): if classificationBlocked[0] == str(True): classBlocked = True forceLevelVal = None if (forceLevel is not None) and (len(forceLevel) > 0): forceLevelVal = int(forceLevel[0]) menuNav = MenuNavigator(base_url, addon_handle) menuNav.setSecurity(type[0], secTitle, dbid, secLevel, classBlocked, forceLevelVal) del menuNav elif mode[0] == 'forcepin': log("PinSentryPlugin: Mode is FORCE PIN") xbmcgui.Window(10000).setProperty("PinSentryPrompt", "true") elif mode[0] == 'setclassification': log("PinSentryPlugin: Mode is SET CLASSIFICATION") ```
[ { "content": "Here is a code snippet:\n```python\n#!/opt/local/bin/python\nimport os\nimport sys\nimport re\nimport fnmatch\nPROJECT_NAME = \"KExperiment\"\n\nsource_reg = re.compile(\".*\\.(cpp|h)$\")\ntask_reg = re.compile(\"^\\s*/+\\s*(TODO|FIXME|BUG|NOTE|HACK):?\\s*(.*)$\", re.I)\n\nsource_match = source_re...
[ { "content": "Here is a code snippet:\n<|memory_start|>```python\n#!/opt/local/bin/python\nimport os\nimport sys\nimport re\nimport fnmatch\nPROJECT_NAME = \"KExperiment\"\n\nsource_reg = re.compile(\".*\\.(cpp|h)$\")\ntask_reg = re.compile(\"^\\s*/+\\s*(TODO|FIXME|BUG|NOTE|HACK):?\\s*(.*)$\", re.I)\n\nsource_m...
```python #!/opt/local/bin/python import os import sys import re import fnmatch PROJECT_NAME = "KExperiment" source_reg = re.compile(".*\.(cpp|h)$") task_reg = re.compile("^\s*/+\s*(TODO|FIXME|BUG|NOTE|HACK):?\s*(.*)$", re.I) source_match = source_reg.match task_match = task_reg.match def main(): output = os.path.join(os.getcwd(), "{0}.tasks".format(PROJECT_NAME)) if len(sys.argv) < 2: sys.stderr.write("You must provide a project root path\n") exit(1) if len(sys.argv) > 2: output = os.path.abspath(sys.argv[2]) root = os.path.abspath(sys.argv[1]) matches = [] types = { "todo": "err", "fixme": "err", "bug": "err", "note": "info", # currently undefined "hack": "warn" } for root, dirs, files in os.walk(root): paths = [os.path.join(root, f) for f in filter(source_match, files)] matches.extend(paths) tasks = [] for source in matches: with open(source, 'r') as f: lines = f.readlines() for line in lines: m = task_match(line) if m: base = os.path.relpath(source) line_number = lines.index(line) + 1 t = types.get(m.group(1).lower(), "info") desc = "{0}: {1}".format(m.group(1), m.group(2)) task = "{base}\t{line}\t{type}\t{desc}" tasks.append(task.format(base=base, line=line_number, type=t, desc=desc)) with open(output, 'w') as f: f.write("\n".join(tasks)) if __name__ == "__main__": main() ```
[ { "content": "Here is a code file:\n```python\n# -*- coding: utf-8 -*-\n\n\"\"\" Provides new permission policies for django-rest-framework\n\"\"\"\n\nfrom rest_framework.permissions import DjangoModelPermissions, BasePermission\nfrom django.contrib.contenttypes.models import ContentType\nfrom rest_framework_fi...
[ { "content": "Here is a code file:\n<|memory_start|>```python\n# -*- coding: utf-8 -*-\n\n\"\"\" Provides new permission policies for django-rest-framework\n\"\"\"\n\nfrom rest_framework.permissions import DjangoModelPermissions, BasePermission\nfrom django.contrib.contenttypes.models import ContentType\nfrom r...
```python # -*- coding: utf-8 -*- """ Provides new permission policies for django-rest-framework """ from rest_framework.permissions import DjangoModelPermissions, BasePermission from django.contrib.contenttypes.models import ContentType from rest_framework_fine_permissions.models import FilterPermissionModel from django.core.exceptions import ObjectDoesNotExist from rest_framework_fine_permissions.serializers import QSerializer class FullDjangoModelPermissions(DjangoModelPermissions): """ The request is authenticated using `django.contrib.auth` permissions. See: https://docs.djangoproject.com/en/dev/topics/auth/#permissions It ensures that the user is authenticated, and has the appropriate `view`/`add`/`change`/`delete` permissions on the model. This permission can only be applied against view classes that provide a `.model` or `.queryset` attribute. """ perms_map = { 'GET': ['%(app_label)s.view_%(model_name)s'], 'OPTIONS': [], 'HEAD': ['%(app_label)s.view_%(model_name)s'], 'POST': ['%(app_label)s.add_%(model_name)s'], 'PUT': ['%(app_label)s.change_%(model_name)s'], 'PATCH': ['%(app_label)s.change_%(model_name)s'], 'DELETE': ['%(app_label)s.delete_%(model_name)s'], } class FilterPermission(BasePermission): """ filter permission """ def has_object_permission(self, request, view, obj): """ check filter permissions """ user = request.user if not user.is_superuser and not user.is_anonymous: valid = False try: ct = ContentType.objects.get_for_model(obj) fpm = FilterPermissionModel.objects.get(user=user, content_type=ct) myq = QSerializer(base64=True).loads(fpm.filter) try: myobj = obj.__class__.objects.filter(myq).distinct().get(pk=obj.pk) if myobj: valid = True except ObjectDoesNotExist: valid = False except ObjectDoesNotExist: valid = True finally: return valid else: return True ```
[ { "content": "Replicate the source code:\n```python\n# grammar.py, part of Yapps 2 - yet another python parser system\n# Copyright 1999-2003 by Amit J. Patel <amitp@cs.stanford.edu>\n# Enhancements copyright 2003-2004 by Matthias Urlichs <smurf@debian.org>\n#\n# This version of the Yapps 2 grammar can be distri...
[ { "content": "Replicate the source code:\n<|memory_start|>```python\n# grammar.py, part of Yapps 2 - yet another python parser system\n# Copyright 1999-2003 by Amit J. Patel <amitp@cs.stanford.edu>\n# Enhancements copyright 2003-2004 by Matthias Urlichs <smurf@debian.org>\n#\n# This version of the Yapps 2 gramm...
```python # grammar.py, part of Yapps 2 - yet another python parser system # Copyright 1999-2003 by Amit J. Patel <amitp@cs.stanford.edu> # Enhancements copyright 2003-2004 by Matthias Urlichs <smurf@debian.org> # # This version of the Yapps 2 grammar can be distributed under the # terms of the MIT open source license, either found in the LICENSE # file included with the Yapps distribution # <http://theory.stanford.edu/~amitp/yapps/> or at # <http://www.opensource.org/licenses/mit-license.php> # """Parser for Yapps grammars. This file defines the grammar of Yapps grammars. Naturally, it is implemented in Yapps. The grammar.py module needed by Yapps is built by running Yapps on yapps_grammar.g. (Holy circularity, Batman!) """ import sys, re from yapps import parsetree ###################################################################### def cleanup_choice(rule, lst): if len(lst) == 0: return Sequence(rule, []) if len(lst) == 1: return lst[0] return parsetree.Choice(rule, *tuple(lst)) def cleanup_sequence(rule, lst): if len(lst) == 1: return lst[0] return parsetree.Sequence(rule, *tuple(lst)) def resolve_name(rule, tokens, id, args): if id in [x[0] for x in tokens]: # It's a token if args: print 'Warning: ignoring parameters on TOKEN %s<<%s>>' % (id, args) return parsetree.Terminal(rule, id) else: # It's a name, so assume it's a nonterminal return parsetree.NonTerminal(rule, id, args) # Begin -- grammar generated by Yapps import sys, re from yapps import runtime class ParserDescriptionScanner(runtime.Scanner): patterns = [ ('"rule"', re.compile('rule')), ('"ignore"', re.compile('ignore')), ('"token"', re.compile('token')), ('"option"', re.compile('option')), ('":"', re.compile(':')), ('"parser"', re.compile('parser')), ('[ \t\r\n]+', re.compile('[ \t\r\n]+')), ('#.*?\r?\n', re.compile('#.*?\r?\n')), ('EOF', re.compile('$')), ('ATTR', re.compile('<<.+?>>')), ('STMT', re.compile('{{.+?}}')), ('ID', re.compile('[a-zA-Z_][a-zA-Z_0-9]*')), ('STR', re.compile('[rR]?\'([^\\n\'\\\\]|\\\\.)*\'|[rR]?"([^\\n"\\\\]|\\\\.)*"')), ('LP', re.compile('\\(')), ('RP', re.compile('\\)')), ('LB', re.compile('\\[')), ('RB', re.compile('\\]')), ('OR', re.compile('[|]')), ('STAR', re.compile('[*]')), ('PLUS', re.compile('[+]')), ('QUEST', re.compile('[?]')), ('COLON', re.compile(':')), ] def __init__(self, str,*args,**kw): runtime.Scanner.__init__(self,None,{'[ \t\r\n]+':None,'#.*?\r?\n':None,},str,*args,**kw) class ParserDescription(runtime.Parser): Context = runtime.Context def Parser(self, _parent=None): _context = self.Context(_parent, self._scanner, 'Parser', []) self._scan('"parser"', context=_context) ID = self._scan('ID', context=_context) self._scan('":"', context=_context) Options = self.Options(_context) Tokens = self.Tokens(_context) Rules = self.Rules(Tokens, _context) EOF = self._scan('EOF', context=_context) return parsetree.Generator(ID,Options,Tokens,Rules) def Options(self, _parent=None): _context = self.Context(_parent, self._scanner, 'Options', []) opt = {} while self._peek('"option"', '"token"', '"ignore"', 'EOF', '"rule"', context=_context) == '"option"': self._scan('"option"', context=_context) self._scan('":"', context=_context) Str = self.Str(_context) opt[Str] = 1 return opt def Tokens(self, _parent=None): _context = self.Context(_parent, self._scanner, 'Tokens', []) tok = [] while self._peek('"token"', '"ignore"', 'EOF', '"rule"', context=_context) in ['"token"', '"ignore"']: _token = self._peek('"token"', '"ignore"', context=_context) if _token == '"token"': self._scan('"token"', context=_context) ID = self._scan('ID', context=_context) self._scan('":"', context=_context) Str = self.Str(_context) tok.append( (ID,Str) ) else: # == '"ignore"' self._scan('"ignore"', context=_context) self._scan('":"', context=_context) Str = self.Str(_context) ign = ('#ignore',Str) if self._peek('STMT', '"token"', '"ignore"', 'EOF', '"rule"', context=_context) == 'STMT': STMT = self._scan('STMT', context=_context) ign = ign + (STMT[2:-2],) tok.append( ign ) return tok def Rules(self, tokens, _parent=None): _context = self.Context(_parent, self._scanner, 'Rules', [tokens]) rul = [] while self._peek('"rule"', 'EOF', context=_context) == '"rule"': self._scan('"rule"', context=_context) ID = self._scan('ID', context=_context) OptParam = self.OptParam(_context) self._scan('":"', context=_context) ClauseA = self.ClauseA(ID, tokens, _context) rul.append( (ID, OptParam, ClauseA) ) return rul def ClauseA(self, rule, tokens, _parent=None): _context = self.Context(_parent, self._scanner, 'ClauseA', [rule, tokens]) ClauseB = self.ClauseB(rule,tokens, _context) v = [ClauseB] while self._peek('OR', 'RP', 'RB', '"rule"', 'EOF', context=_context) == 'OR': OR = self._scan('OR', context=_context) ClauseB = self.ClauseB(rule,tokens, _context) v.append(ClauseB) return cleanup_choice(rule,v) def ClauseB(self, rule,tokens, _parent=None): _context = self.Context(_parent, self._scanner, 'ClauseB', [rule,tokens]) v = [] while self._peek('STR', 'ID', 'LP', 'LB', 'STMT', 'OR', 'RP', 'RB', '"rule"', 'EOF', context=_context) in ['STR', 'ID', 'LP', 'LB', 'STMT']: ClauseC = self.ClauseC(rule,tokens, _context) v.append(ClauseC) return cleanup_sequence(rule, v) def ClauseC(self, rule,tokens, _parent=None): _context = self.Context(_parent, self._scanner, 'ClauseC', [rule,tokens]) ClauseD = self.ClauseD(rule,tokens, _context) _token = self._peek('PLUS', 'STAR', 'QUEST', 'STR', 'ID', 'LP', 'LB', 'STMT', 'OR', 'RP', 'RB', '"rule"', 'EOF', context=_context) if _token == 'PLUS': PLUS = self._scan('PLUS', context=_context) return parsetree.Plus(rule, ClauseD) elif _token == 'STAR': STAR = self._scan('STAR', context=_context) return parsetree.Star(rule, ClauseD) elif _token == 'QUEST': QUEST = self._scan('QUEST', context=_context) return parsetree.Option(rule, ClauseD) else: return ClauseD def ClauseD(self, rule,tokens, _parent=None): _context = self.Context(_parent, self._scanner, 'ClauseD', [rule,tokens]) _token = self._peek('STR', 'ID', 'LP', 'LB', 'STMT', context=_context) if _token == 'STR': STR = self._scan('STR', context=_context) t = (STR, eval(STR,{},{})) if t not in tokens: tokens.insert( 0, t ) return parsetree.Terminal(rule, STR) elif _token == 'ID': ID = self._scan('ID', context=_context) OptParam = self.OptParam(_context) return resolve_name(rule,tokens, ID, OptParam) elif _token == 'LP': LP = self._scan('LP', context=_context) ClauseA = self.ClauseA(rule,tokens, _context) RP = self._scan('RP', context=_context) return ClauseA elif _token == 'LB': LB = self._scan('LB', context=_context) ClauseA = self.ClauseA(rule,tokens, _context) RB = self._scan('RB', context=_context) return parsetree.Option(rule, ClauseA) else: # == 'STMT' STMT = self._scan('STMT', context=_context) return parsetree.Eval(rule, STMT[2:-2]) def OptParam(self, _parent=None): _context = self.Context(_parent, self._scanner, 'OptParam', []) if self._peek('ATTR', '":"', 'PLUS', 'STAR', 'QUEST', 'STR', 'ID', 'LP', 'LB', 'STMT', 'OR', 'RP', 'RB', '"rule"', 'EOF', context=_context) == 'ATTR': ATTR = self._scan('ATTR', context=_context) return ATTR[2:-2] return '' def Str(self, _parent=None): _context = self.Context(_parent, self._scanner, 'Str', []) STR = self._scan('STR', context=_context) return eval(STR,{},{}) def parse(rule, text): P = ParserDescription(ParserDescriptionScanner(text)) return runtime.wrap_error_reporter(P, rule) # End -- grammar generated by Yapps ```
[ { "content": "Provide an exact copy of the source code:\n```python\nimport sys\nimport os\nimport re\nimport textwrap\nimport pytest\nfrom doctest import OutputChecker, ELLIPSIS\n\nfrom tests.lib import _create_test_package, _create_test_package_with_srcdir\n\n\ndistribute_re = re.compile('^distribute==[0-9.]+\...
[ { "content": "Provide an exact copy of the source code:\n<|memory_start|>```python\nimport sys\nimport os\nimport re\nimport textwrap\nimport pytest\nfrom doctest import OutputChecker, ELLIPSIS\n\nfrom tests.lib import _create_test_package, _create_test_package_with_srcdir\n\n\ndistribute_re = re.compile('^dist...
```python import sys import os import re import textwrap import pytest from doctest import OutputChecker, ELLIPSIS from tests.lib import _create_test_package, _create_test_package_with_srcdir distribute_re = re.compile('^distribute==[0-9.]+\n', re.MULTILINE) def _check_output(result, expected): checker = OutputChecker() actual = str(result) # FIXME! The following is a TOTAL hack. For some reason the # __str__ result for pkg_resources.Requirement gets downcased on # Windows. Since INITools is the only package we're installing # in this file with funky case requirements, I'm forcibly # upcasing it. You can also normalize everything to lowercase, # but then you have to remember to upcase <BLANKLINE>. The right # thing to do in the end is probably to find out how to report # the proper fully-cased package name in our error message. if sys.platform == 'win32': actual = actual.replace('initools', 'INITools') # This allows our existing tests to work when run in a context # with distribute installed. actual = distribute_re.sub('', actual) def banner(msg): return '\n========== %s ==========\n' % msg assert checker.check_output(expected, actual, ELLIPSIS), ( banner('EXPECTED') + expected + banner('ACTUAL') + actual + banner(6 * '=') ) def test_freeze_basic(script): """ Some tests of freeze, first we have to install some stuff. Note that the test is a little crude at the end because Python 2.5+ adds egg info to the standard library, so stuff like wsgiref will show up in the freezing. (Probably that should be accounted for in pip, but currently it is not). """ script.scratch_path.join("initools-req.txt").write(textwrap.dedent("""\ simple==2.0 # and something else to test out: simple2<=3.0 """)) script.pip_install_local( '-r', script.scratch_path / 'initools-req.txt', ) result = script.pip('freeze', expect_stderr=True) expected = textwrap.dedent("""\ ...simple==2.0 simple2==3.0... <BLANKLINE>""") _check_output(result.stdout, expected) def test_freeze_with_pip(script): """Test pip shows itself""" result = script.pip('freeze', '--all') assert 'pip==' in result.stdout def test_freeze_with_invalid_names(script): """ Test that invalid names produce warnings and are passed over gracefully. """ def fake_install(pkgname, dest): egg_info_path = os.path.join( dest, '{0}-1.0-py{1}.{2}.egg-info'.format( pkgname.replace('-', '_'), sys.version_info[0], sys.version_info[1] ) ) with open(egg_info_path, 'w') as egg_info_file: egg_info_file.write(textwrap.dedent("""\ Metadata-Version: 1.0 Name: {0} Version: 1.0 """.format(pkgname) )) valid_pkgnames = ('middle-dash', 'middle_underscore', 'middle.dot') invalid_pkgnames = ( '-leadingdash', '_leadingunderscore', '.leadingdot', 'trailingdash-', 'trailingunderscore_', 'trailingdot.' ) for pkgname in valid_pkgnames + invalid_pkgnames: fake_install(pkgname, script.site_packages_path) result = script.pip('freeze', expect_stderr=True) for pkgname in valid_pkgnames: _check_output( result.stdout, '...{0}==1.0...'.format(pkgname.replace('_', '-')) ) for pkgname in invalid_pkgnames: _check_output( result.stderr, '...Could not parse requirement: {0}\n...'.format( pkgname.replace('_', '-') ) ) @pytest.mark.svn def test_freeze_svn(script, tmpdir): """Test freezing a svn checkout""" checkout_path = _create_test_package(script, vcs='svn') # Install with develop script.run( 'python', 'setup.py', 'develop', cwd=checkout_path, expect_stderr=True ) result = script.pip('freeze', expect_stderr=True) expected = textwrap.dedent("""\ ...-e svn+...#egg=version_pkg ...""") _check_output(result.stdout, expected) @pytest.mark.git @pytest.mark.xfail def test_freeze_exclude_editable(script, tmpdir): """ Test excluding editable from freezing list. """ # Returns path to a generated package called "version_pkg" pkg_version = _create_test_package(script) result = script.run( 'git', 'clone', pkg_version, 'pip-test-package', expect_stderr=True, ) repo_dir = script.scratch_path / 'pip-test-package' result = script.run( 'python', 'setup.py', 'develop', cwd=repo_dir, expect_stderr=True, ) result = script.pip('freeze', '--exclude-editable', expect_stderr=True) expected = textwrap.dedent( """ ...-e git+...#egg=version_pkg ... """ ).strip() _check_output(result.stdout, expected) @pytest.mark.git def test_freeze_git_clone(script, tmpdir): """ Test freezing a Git clone. """ # Returns path to a generated package called "version_pkg" pkg_version = _create_test_package(script) result = script.run( 'git', 'clone', pkg_version, 'pip-test-package', expect_stderr=True, ) repo_dir = script.scratch_path / 'pip-test-package' result = script.run( 'python', 'setup.py', 'develop', cwd=repo_dir, expect_stderr=True, ) result = script.pip('freeze', expect_stderr=True) expected = textwrap.dedent( """ ...-e git+...#egg=version_pkg ... """ ).strip() _check_output(result.stdout, expected) result = script.pip( 'freeze', '-f', '%s#egg=pip_test_package' % repo_dir, expect_stderr=True, ) expected = textwrap.dedent( """ -f %(repo)s#egg=pip_test_package... -e git+...#egg=version_pkg ... """ % {'repo': repo_dir}, ).strip() _check_output(result.stdout, expected) # Check that slashes in branch or tag names are translated. # See also issue #1083: https://github.com/pypa/pip/issues/1083 script.run( 'git', 'checkout', '-b', 'branch/name/with/slash', cwd=repo_dir, expect_stderr=True, ) # Create a new commit to ensure that the commit has only one branch # or tag name associated to it (to avoid the non-determinism reported # in issue #1867). script.run('touch', 'newfile', cwd=repo_dir) script.run('git', 'add', 'newfile', cwd=repo_dir) script.run('git', 'commit', '-m', '...', cwd=repo_dir) result = script.pip('freeze', expect_stderr=True) expected = textwrap.dedent( """ ...-e ...@...#egg=version_pkg ... """ ).strip() _check_output(result.stdout, expected) @pytest.mark.git def test_freeze_git_clone_srcdir(script, tmpdir): """ Test freezing a Git clone where setup.py is in a subdirectory relative the repo root and the source code is in a subdirectory relative to setup.py. """ # Returns path to a generated package called "version_pkg" pkg_version = _create_test_package_with_srcdir(script) result = script.run( 'git', 'clone', pkg_version, 'pip-test-package', expect_stderr=True, ) repo_dir = script.scratch_path / 'pip-test-package' result = script.run( 'python', 'setup.py', 'develop', cwd=repo_dir / 'subdir', expect_stderr=True, ) result = script.pip('freeze', expect_stderr=True) expected = textwrap.dedent( """ ...-e git+...#egg=version_pkg&subdirectory=subdir ... """ ).strip() _check_output(result.stdout, expected) result = script.pip( 'freeze', '-f', '%s#egg=pip_test_package' % repo_dir, expect_stderr=True, ) expected = textwrap.dedent( """ -f %(repo)s#egg=pip_test_package... -e git+...#egg=version_pkg&subdirectory=subdir ... """ % {'repo': repo_dir}, ).strip() _check_output(result.stdout, expected) @pytest.mark.git def test_freeze_git_remote(script, tmpdir): """ Test freezing a Git clone. """ # Returns path to a generated package called "version_pkg" pkg_version = _create_test_package(script) result = script.run( 'git', 'clone', pkg_version, 'pip-test-package', expect_stderr=True, ) repo_dir = script.scratch_path / 'pip-test-package' result = script.run( 'python', 'setup.py', 'develop', cwd=repo_dir, expect_stderr=True, ) origin_remote = pkg_version other_remote = pkg_version + '-other' # check frozen remote after clone result = script.pip('freeze', expect_stderr=True) expected = textwrap.dedent( """ ...-e git+{remote}@...#egg=version_pkg ... """ ).format(remote=origin_remote).strip() _check_output(result.stdout, expected) # check frozen remote when there is no remote named origin script.run('git', 'remote', 'remove', 'origin', cwd=repo_dir) script.run('git', 'remote', 'add', 'other', other_remote, cwd=repo_dir) result = script.pip('freeze', expect_stderr=True) expected = textwrap.dedent( """ ...-e git+{remote}@...#egg=version_pkg ... """ ).format(remote=other_remote).strip() _check_output(result.stdout, expected) # when there are more than one origin, priority is given to the # remote named origin script.run('git', 'remote', 'add', 'origin', origin_remote, cwd=repo_dir) result = script.pip('freeze', expect_stderr=True) expected = textwrap.dedent( """ ...-e git+{remote}@...#egg=version_pkg ... """ ).format(remote=origin_remote).strip() _check_output(result.stdout, expected) @pytest.mark.mercurial def test_freeze_mercurial_clone(script, tmpdir): """ Test freezing a Mercurial clone. """ # Returns path to a generated package called "version_pkg" pkg_version = _create_test_package(script, vcs='hg') result = script.run( 'hg', 'clone', pkg_version, 'pip-test-package', expect_stderr=True, ) repo_dir = script.scratch_path / 'pip-test-package' result = script.run( 'python', 'setup.py', 'develop', cwd=repo_dir, expect_stderr=True, ) result = script.pip('freeze', expect_stderr=True) expected = textwrap.dedent( """ ...-e hg+...#egg=version_pkg ... """ ).strip() _check_output(result.stdout, expected) result = script.pip( 'freeze', '-f', '%s#egg=pip_test_package' % repo_dir, expect_stderr=True, ) expected = textwrap.dedent( """ -f %(repo)s#egg=pip_test_package... ...-e hg+...#egg=version_pkg ... """ % {'repo': repo_dir}, ).strip() _check_output(result.stdout, expected) @pytest.mark.bzr def test_freeze_bazaar_clone(script, tmpdir): """ Test freezing a Bazaar clone. """ try: checkout_path = _create_test_package(script, vcs='bazaar') except OSError as e: pytest.fail('Invoking `bzr` failed: %s' % e) result = script.run( 'bzr', 'checkout', checkout_path, 'bzr-package' ) result = script.run( 'python', 'setup.py', 'develop', cwd=script.scratch_path / 'bzr-package', expect_stderr=True, ) result = script.pip('freeze', expect_stderr=True) expected = textwrap.dedent("""\ ...-e bzr+file://...@1#egg=version_pkg ...""") _check_output(result.stdout, expected) result = script.pip( 'freeze', '-f', '%s/#egg=django-wikiapp' % checkout_path, expect_stderr=True, ) expected = textwrap.dedent("""\ -f %(repo)s/#egg=django-wikiapp ...-e bzr+file://...@...#egg=version_pkg ...""" % {'repo': checkout_path}) _check_output(result.stdout, expected) def test_freeze_with_local_option(script): """ Test that wsgiref (from global site-packages) is reported normally, but not with --local. """ result = script.pip_install_local('initools==0.2') result = script.pip('freeze', expect_stderr=True) expected = textwrap.dedent("""\ INITools==0.2 wsgiref==... <BLANKLINE>""") # The following check is broken (see # http://bitbucket.org/ianb/pip/issue/110). For now we are simply # neutering this test, but if we can't find a way to fix it, # this whole function should be removed. # _check_output(result, expected) result = script.pip('freeze', '--local', expect_stderr=True) expected = textwrap.dedent("""\ INITools==0.2 <BLANKLINE>""") _check_output(result.stdout, expected) # used by the test_freeze_with_requirement_* tests below _freeze_req_opts = textwrap.dedent("""\ # Unchanged requirements below this line -r ignore.txt --requirement ignore.txt -Z ignore --always-unzip ignore -f http://ignore -i http://ignore --pre --trusted-host url --process-dependency-links --extra-index-url http://ignore --find-links http://ignore --index-url http://ignore """) def test_freeze_with_requirement_option(script): """ Test that new requirements are created correctly with --requirement hints """ script.scratch_path.join("hint.txt").write(textwrap.dedent("""\ INITools==0.1 NoExist==4.2 # A comment that ensures end of line comments work. simple==3.0; python_version > '1.0' """) + _freeze_req_opts) result = script.pip_install_local('initools==0.2') result = script.pip_install_local('simple') result = script.pip( 'freeze', '--requirement', 'hint.txt', expect_stderr=True, ) expected = textwrap.dedent("""\ INITools==0.2 simple==3.0 """) expected += _freeze_req_opts expected += "## The following requirements were added by pip freeze:..." _check_output(result.stdout, expected) assert ( "Requirement file [hint.txt] contains NoExist==4.2, but that package " "is not installed" ) in result.stderr def test_freeze_with_requirement_option_multiple(script): """ Test that new requirements are created correctly with multiple --requirement hints """ script.scratch_path.join('hint1.txt').write(textwrap.dedent("""\ INITools==0.1 NoExist==4.2 simple==3.0; python_version > '1.0' """) + _freeze_req_opts) script.scratch_path.join('hint2.txt').write(textwrap.dedent("""\ NoExist2==2.0 simple2==1.0 """) + _freeze_req_opts) result = script.pip_install_local('initools==0.2') result = script.pip_install_local('simple') result = script.pip_install_local('simple2==1.0') result = script.pip_install_local('meta') result = script.pip( 'freeze', '--requirement', 'hint1.txt', '--requirement', 'hint2.txt', expect_stderr=True, ) expected = textwrap.dedent("""\ INITools==0.2 simple==1.0 """) expected += _freeze_req_opts expected += textwrap.dedent("""\ simple2==1.0 """) expected += "## The following requirements were added by pip freeze:" expected += os.linesep + textwrap.dedent("""\ ...meta==1.0... """) _check_output(result.stdout, expected) assert ( "Requirement file [hint1.txt] contains NoExist==4.2, but that " "package is not installed" ) in result.stderr assert ( "Requirement file [hint2.txt] contains NoExist2==2.0, but that " "package is not installed" ) in result.stderr # any options like '--index-url http://ignore' should only be emitted once # even if they are listed in multiple requirements files assert result.stdout.count("--index-url http://ignore") == 1 def test_freeze_user(script, virtualenv): """ Testing freeze with --user, first we have to install some stuff. """ virtualenv.system_site_packages = True script.pip_install_local('--user', 'simple==2.0') script.pip_install_local('simple2==3.0') result = script.pip('freeze', '--user', expect_stderr=True) expected = textwrap.dedent("""\ simple==2.0 <BLANKLINE>""") _check_output(result.stdout, expected) assert 'simple2' not in result.stdout ```
[ { "content": "Here is the script:\n```python\n\"\"\"\nPyroman uses some standard chains, set in it's config.\nThese chains are used by the \"allow()\", \"reject()\" and \"drop()\" commandos\nfor nicer rule writing, and probably should do exactly that.\n\nIf you want maximal performance, you'll want to change th...
[ { "content": "Here is the script:\n<|memory_start|>```python\n\"\"\"\nPyroman uses some standard chains, set in it's config.\nThese chains are used by the \"allow()\", \"reject()\" and \"drop()\" commandos\nfor nicer rule writing, and probably should do exactly that.\n\nIf you want maximal performance, you'll w...
```python """ Pyroman uses some standard chains, set in it's config. These chains are used by the "allow()", "reject()" and "drop()" commandos for nicer rule writing, and probably should do exactly that. If you want maximal performance, you'll want to change these to ACCEPT and DROP directly by calling 'Firewall.accept = "ACCEPT"' and removing the lines below. The (small) benefits of using this approach is that you can easily disable the rules (by modifying 'drop' and 'reject') without reloading your firewall and that you get complete traffic counters in these chains. The variables "Firewall.accept", "Firewall.drop" and "Firewall.reject" are used here, so you can change them in one place only. """ Firewall.accept="accept" add_chain(Firewall.accept) # Kernel and iptables can do new string matches? if Firewall.iptables_version(min="1.3.4") and \ Firewall.kernel_version(min="2.6.12"): # Drop bittorrent traffic iptables(Firewall.accept, '-m string --string "BitTorrent protocol" ' + \ '--algo bm --from 0 --to 100 -j DROP') # add accept default rule to the chain iptables(Firewall.accept, "-j ACCEPT") # this is a silent drop Firewall.drop="drop" add_chain(Firewall.drop) iptables(Firewall.drop, "-j DROP") # .. these are clean "reject" rules (i.e. send 'connection refused' back) Firewall.reject="reject" add_chain(Firewall.reject) iptables(Firewall.reject, "-p tcp -j REJECT --reject-with tcp-reset") iptables(Firewall.reject, "-j REJECT") ```
[ { "content": "```python\n#some import\r\nimport numpy\r\nimport itertools\r\nimport random\r\nimport math\r\nimport os.path\r\nimport urllib2\r\nimport sys\r\n\r\n#global variables\r\nn = None\r\nN = None\r\nDk = None\r\nDu = None\r\nDc = None\r\ne = None\r\nr = None\r\nx = None\r\nxa = None\r\nASW = None\r\nEX...
[ { "content": "<|memory_start|>```python\n#some import\r\nimport numpy\r\nimport itertools\r\nimport random\r\nimport math\r\nimport os.path\r\nimport urllib2\r\nimport sys\r\n\r\n#global variables\r\nn = None\r\nN = None\r\nDk = None\r\nDu = None\r\nDc = None\r\ne = None\r\nr = None\r\nx = None\r\nxa = None\r\n...
```python #some import import numpy import itertools import random import math import os.path import urllib2 import sys #global variables n = None N = None Dk = None Du = None Dc = None e = None r = None x = None xa = None ASW = None EXC = None INS = None pASW = None pEXC = None pINS = None #help function def help(): print(""" VARIABLES --------- n permutation size N total number of permutations Dk diameter with Kendall's tau distance Du diameter with Ulam distance Dc diameter with Cayley distance e identity permutation r identity reversed permutation x a random permutation xa antipodal permutation of x with respect to exchanges ASW set of adjacent swap generators (in tuple normal form) EXC set of exchange generators (in tuple normal form) INS set of insertion generators (in tuple normal form) pASW ASW in permutation form pEXC EXC in permutation form pINS INS in permutation form FUNCTIONS --------- reset(n) re-initialize environment with a new permutation size fact(n) factorial of n inv(x) inverse of x rev(x) reverse of x compl(x) complement of x dot(x,y) composition x*y prand() a random permutation isPerm(x) check if the list x is a permutation asw(i) adjacent swap (i,i+1) [callable also with a tuple arg] exc(i,j) exchange (i,j) [callable also with a tuple arg] ins(i,j) insertion (i,j) [callable also with a tuple arg] asw_nf(i) tuple normal form for adjacent swap (i,j) with j=i+1 exc_nf(t) tuple normal form for exchange (t[0],t[1]) with t[1]>t[0] ins_nf(t) tuple normal form for insertion (t[0],t[1]) with t[1]>t[0] only for case t[1]=t[0]+1 aswToTuple(x) convert an adjacent swap from permutation form to tuple form excToTuple(x) convert an exchange from permutation form to tuple form insToTuple(x) convert an insertion from permutation form to tuple form swap(x,i,j) swap items at position i and j in x (inplace) insert(x,i,j) shift item at position i to position j in x (inplace) dk(x,y) Kendall's tau distance between x and y du(x,y) Ulam distance between x and y dc(x,y) Cayley distance between x and y ninver(x) number of inversion in x inver(x) set of inversions in x ainver(x) list of adjacent inversions in x lis(x) standard lis of x llis(x) length of a lis of x alis(x) all the lis of x urlis(x) unfirom random lis of x ind(l,x) indexes of x where values in list l appear cycles(x) cycle decomposition of x ncycles(x) number of cycles of the decomposition of x cycleToPerm(c) build a permutation corresponding to cycle c prandUnredLis() random permutation whose lis is "unreducible" hasUnredLis(x) check if the lis of x can be reduced or not lisldsRedCases(x) print and return lis/lds reduction cases after applying all insertion generators (if additional False is passed it doesnt print) printLisLdsRedCases(d)print the result of "lisldsRedCases" bothLisLdsIncrease() get a random permutation x + ins generator g such that x*g increases both lis and lds lengths prand1c() random permutation whith only one cycle stirling1u(n,k) [n,k] unsigned stirling number of the 1st kind npermWithCycles(k) number of permutations with k cycles lds(x) standard lds of x llds(x) length of a lds of x alds(x) all the lds of x urlds(x) uniform random lds of x mahonian(n,k) [n,k] mahonian number npermWithInvers(k) number of permutations with k inversions seqA047874(n,k) [n,k] number of the sequence A047874 (it works only till n=60 and requires the file at https://oeis.org/A047874/b047874.txt or internet) npermWithLisLength(k) number of permutations with a lis of length k (it works only tille n=60 the file at https://oeis.org/A047874/b047874.txt or internet) applySeq(x,s) return x*s[0]*s[1]*... composeSeq(s) return s[0]*s[1]*... mapAswSeq(s) from a sequence of ASW tuples return a sequence of permutations mapExcSeq(s) from a sequence of EXC tuples return a sequence of permutations mapInsSeq(s) from a sequence of INS tuples return a sequence of permutations randbs(x) return a sequence of ASW tuples that sorts x randDecAsw(x) return a ASW decomposition of x randss(x) return a sequence of EXC tuples that sorts x randmergess(x) return a sequence of EXC tuples that UNsorts x randDecExc(x) return a EXC decomposition of x randis(x,randlis) return a sequence of INS tuples that sorts x (UNIFORM STEP NOT IMPLEMENTED) (the randlis function as parameter is optional) randDecIns(x,randlis) return a INS decomposition of x (see randis) checkAllInsDiamRev() return true if for all permutations x the Ulam distance between x and rev(x) equals the Ulam diameter ssort(x) return the sequence of EXC using classical selection sort expInertia(nexp,q) write how many inertia anomalies with q adj.swaps are over nexp random experiments all_asw_decomp(x) return all the decompositions (using ASW) of x checkAverage(x,y) check if the a*x+(1-a)*y has equiprobability perm2str(x) return string representation of the permutation x """) #test function #def test(): # pass #default permutation size DEFAULT_n = 10 #reset/init functions (with global variables declaration) def reset(size=DEFAULT_n): #global variables global n,N,Dk,Du,Dc,e,r,ASW,EXC,INS,pASW,pEXC,pINS #permutation size n = size #total number of permutations N = fact(n) #diameters Dk = n*(n-1)/2 Du = n-1 Dc = n-1 #useful permutations e = range(n) r = e[::-1] x = prand() xa = applySeq(x,mapExcSeq(randmergess(x))) #generators sets ASW = set() for i in range(n-1): ASW.add((i,i+1)) pASW = sorted(map(lambda p : asw(p), ASW)) EXC = set() for i in range(n): for j in range(i+1,n): EXC.add((i,j)) pEXC = sorted(map(lambda p : exc(p), EXC)) INS = set() for i in range(n): for j in filter(lambda j : j!=i and j!=i-1,range(n)): INS.add((i,j)) pINS = sorted(map(lambda p : ins(p), INS)) #copy variables to the main module scope import __main__ __main__.n = n __main__.N = N __main__.Dk = Dk __main__.Du = Du __main__.Dc = Dc __main__.e = e __main__.r = r __main__.x = x __main__.xa = xa __main__.ASW = ASW __main__.pASW = pASW __main__.EXC = EXC __main__.pEXC = pEXC __main__.INS = INS __main__.pINS = pINS init = reset #some basic functions def fact(n): return math.factorial(n) def inv(x): z = [None]*n for i in range(n): z[x[i]] = i return z def rev(x): return x[::-1] def dot(x,y): return [x[v] for v in y] def prand(): return numpy.random.permutation(n).tolist() def isPerm(x): return sorted(x)==e def compl(x): return [n-1-v for v in x] #generators to permutation functions def asw(g1,g2=-1): if type(g1) is tuple: return exc(g1[0],g1[0]+1) else: return exc(g1,g1+1) def exc(g1,g2=-1): if type(g1) is tuple: i,j = g1 else: i,j = g1,g2 z = e[:] z[i],z[j] = z[j],z[i] return z def ins(g1,g2=-1): if type(g1) is tuple: i,j = g1 else: i,j = g1,g2 if i<j: return range(i) + range(i+1,j+1) + [i] + range(j+1,n) else: return range(j) + [i] + range(j,i) + range(i+1,n) def asw_nf(t): if type(t) is not tuple: return (t,t+1) return exc_nf(t) def exc_nf(t): return tuple(sorted(t)) def ins_nf(t): return tuple(sorted(t)) if t[0]==t[1]+1 else t def aswToTuple(x): t = excToTuple(x) if t[1]!=t[0]+1: print("It is not an adjacent swap!!!") return (t[0],t[0]+1) def excToTuple(x): diff = [i==x[i] for i in range(n)] if diff.count(False)!=2: print("It is not an exchange!!!") return tuple([i for i,v in enumerate(diff) if not v]) def insToTuple(x): diff = [i==x[i] for i in range(n)] if diff.count(False)<2: print("It is not an insertion!!!") first,last = diff.index(False),n-1-diff[::-1].index(False) if any(diff[first:last]): print("It is not an insertion!!!") if x[first]==first+1: #i<j if x[first:last-1]!=range(first+1,last): print("It is not an insertion!!!") return (first,last) else: #i>j if x[first+1:last]!=range(first,last-1) or x[first]!=last: print("It is not an insertion!!!") return (last,first) #swap and insert inplace def swap(x,i,j=-1): if j==-1: j = i+1 x[i],x[j] = x[j],x[i] def insert(x,i,j): t = x[i] del x[i] x.insert(j,t) #distances def dk(x,y): return ninver(dot(inv(y),x)) def du(x,y): return n-llis(dot(inv(y),x)) def dc(x,y): return n-ncycles(dot(inv(y),x)) #inversion function def ninver(x): return len(inver(x)) def inver(x): return set([(i,j) for i,j in itertools.combinations(range(n),2) if x[i]>x[j]]) def ainver(x): return [(i,i+1) for i in range(n-1) if x[i]>x[i+1]] #lis functions def lis(x): #see http://rosettacode.org/wiki/Longest_increasing_subsequence#Python X = x[:] N = len(X) P = [0 for i in range(N)] M = [0 for i in range(N+1)] L = 0 for i in range(N): lo = 1 hi = L while lo <= hi: mid = (lo+hi)//2 if (X[M[mid]] < X[i]): lo = mid+1 else: hi = mid-1 newL = lo P[i] = M[newL-1] M[newL] = i if (newL > L): L = newL S = [] k = M[L] for i in range(L-1, -1, -1): S.append(X[k]) k = P[k] return S[::-1] def llis(x): return len(lis(x)) def alis(x): #see http://stackoverflow.com/questions/9554266/finding-all-possible-longest-increasing-subsequence?rq=1 count = [1]*n def longestIncreaseSubsequence(seq): n = len(seq) for i in range(1,n): maxi = 0 for j in range(i-1,-1,-1): if seq[j]<seq[i]: maxi = max(maxi,count[j]) count[i] = maxi + 1 maxi = 0 for i in range(len(count)): if count[i]>maxi: maxi = count[i] return maxi def allLIS(a,k,count,arr,maxi,result): if k==maxi: lista = [] for i in range(maxi,0,-1): lista.append(arr[a[i]]) result.append(lista) else: k = k+1 candidates = [None]*len(arr) ncandidate = 0 for i in range(a[k-1],-1,-1): if count[i]==maxi-k+1 and (arr[i]<arr[a[k-1]] or count[i]==maxi): candidates[ncandidate] = i ncandidate = ncandidate + 1 for i in range(0,ncandidate): a[k] = candidates[i] allLIS(a,k,count,arr,maxi,result) maxi = longestIncreaseSubsequence(x) a = [None]*(maxi+1) a[0] = len(x)-1 result = [] allLIS(a,0,count,x,maxi,result) return result def urlis(x): return random.choice(alis(x)) def ind(l,x): return [x.index(v) for v in l] #cycles functions def cycles(perm): #see https://gist.github.com/begriffs/2211881 remain = set(perm) result = [] while len(remain) > 0: n = remain.pop() cycle = [n] while True: n = perm[n] if n not in remain: break remain.remove(n) cycle.append(n) result.append(cycle) return result def ncycles(x): return len(cycles(x)) def cycleToPerm(c): z = range(n) for k in range(len(c)-1): i = c[k] j = c[k+1] z[i] = j z[c[-1]] = c[0] return z #lis reduction functions def prandUnredLis(): while True: x = prand() lx = llis(x) flag = True for pins in pINS: y = dot(x,pins) ly = llis(y) if ly<lx: flag = False if flag: return x def hasUnredLis(x): lx = llis(x) for pins in pINS: y = dot(x,pins) if llis(y)<lx: return False return True def lisldsRedCases(x,verbose=True): r = { "<<":0, "<=":0, "<>":0, "=<":0, "==":0, "=>":0, "><":0, ">=":0, ">>":0, "other":0 } l1x,l2x = llis(x),llds(x) for g in pINS: y = dot(x,g) l1y,l2y = llis(y),llds(y) if l1y==l1x-1 and l2y==l2x-1: r["<<"] += 1 elif l1y==l1x-1 and l2y==l2x: r["<="] += 1 elif l1y==l1x-1 and l2y==l2x+1: r["<>"] += 1 elif l1y==l1x and l2y==l2x-1: r["=<"] += 1 elif l1y==l1x and l2y==l2x: r["=="] += 1 elif l1y==l1x and l2y==l2x+1: r["=>"] += 1 elif l1y==l1x+1 and l2y==l2x-1: r["><"] += 1 elif l1y==l1x+1 and l2y==l2x: r[">="] += 1 elif l1y==l1x+1 and l2y==l2x+1: r[">>"] += 1 else: r["other"] += 1 if verbose: printLisLdsRedCases(r) return r def printLisLdsRedCases(d): print("ID") print("<< : "+(str(d["<<"] if "<<" in d else 0))) print("<= : "+(str(d["<="] if "<=" in d else 0))) print("<> : "+(str(d["<>"] if "<>" in d else 0))) print("=< : "+(str(d["=<"] if "=<" in d else 0))) print("== : "+(str(d["=="] if "==" in d else 0))) print("=> : "+(str(d["=>"] if "=>" in d else 0))) print(">< : "+(str(d["><"] if "><" in d else 0))) print(">= : "+(str(d[">="] if ">=" in d else 0))) print(">> : "+(str(d[">>"] if ">>" in d else 0))) print("other : "+(str(d["other"] if "other" in d else 0))) def bothLisLdsIncrease(): while True: x = prand() l1x,l2x = llis(x),llds(x) for g in pINS: y = dot(x,g) l1y,l2y = llis(y),llds(y) if l1y>l1x and l2y>l2x: return [x,g] #random permutation with only 1 cycle def prand1c(): x = [None]*n c = range(1,n) i = 0 while c: j = random.choice(c) c.remove(j) x[i] = j i = j x[i] = 0 return x #cycle distribution functions def stirling1u(n,k): #stirling number of the 1st kind unsigned if n==0 and k==0: return 1 if n==0 or k==0: return 0 return (n-1)*stirling1u(n-1,k) + stirling1u(n-1,k-1) def npermWithCycles(k): return stirling1u(n,k) #lds functions def lds(x): return compl(lis(compl(x))) def llds(x): return len(lds(x)) def alds(x): return [compl(l) for l in alis(compl(x))] def urlds(x): return compl(urlis(compl(x))) #inversion distribution functions def mahonian(n,k): #see http://stackoverflow.com/questions/19372991/number-of-n-element-permutations-with-exactly-k-inversions def mahonian_row(n): i = 1 result = [1] while i < n: prev = result[:] result = [0] * int(1 + ((i + 1) * 0.5) * (i)) m = [1] * (i + 1) for j in range(len(m)): for k in range(len(prev)): result[k+j] += m[j] * prev[k] i = i + 1 return result return mahonian_row(n)[k] def npermWithInvers(k): return mahonian(n,k) #lis length distribution function def seqA047874(n,k): #see https://oeis.org/A047874 and https://oeis.org/A047874/b047874.txt if n>60: print("Impossible to compute this value for n greater than 60") lineno = n*(n-1)/2 + k fn = "b047874.txt" if os.path.exists(fn): with open(fn,"r") as f: for line in f: if int(line.split()[0])==lineno: return int(line.split()[1]) else: print "Trying to read the file from web https://oeis.org/A047874/b047874.txt" un = "https://oeis.org/A047874/b047874.txt" txt = urllib2.urlopen(un).read().split("\n") for line in txt: if int(line.split()[0])==lineno: return int(line.split()[1]) return -1 def npermWithLisLength(k): return seqA047874(n,k) #randomized sorting algorithms def applySeq(x,s): z = x[:] for y in s: z = dot(z,y) return z def composeSeq(s): return applySeq(e,s) def mapAswSeq(s): return map(lambda p : asw(p), s) def mapExcSeq(s): return map(lambda p : exc(p), s) def mapInsSeq(s): return map(lambda p : ins(p), s) def randbs(x): y = x[:] s = [] ai = ainver(y) while len(ai)>0: sw = random.choice(ai) swap(y,sw[0],sw[1]) ai = ainver(y) s.append(sw) return s def randDecAsw(x): return randbs(inv(x)) def randss(x): y = x[:] s = [] cyc = cycles(y) while len(cyc)<n: cyc = filter(lambda c : len(c)>1,cyc) q = list(numpy.cumsum([len(c)*(len(c)-1)/2 for c in cyc])) tot = q[-1] r = random.randint(0,tot-1) for i in range(len(cyc)): if r<q[i]: c = i c = cyc[c] i = random.choice(c) c.remove(i) j = random.choice(c) s.append(exc_nf((i,j))) swap(y,i,j) cyc = cycles(y) return s def randmergess(x): y = x[:] s = [] cyc = cycles(y) while len(cyc)>1: w = list(numpy.cumsum([len(cyc[k])*(n-len(cyc[k])) for k in range(len(cyc))])) r = random.randint(0,w[-1]-1) for c1 in range(len(cyc)): if r<w[c1]: break i = random.choice(cyc[c1]) del cyc[c1] w = list(numpy.cumsum(map(lambda c : len(c),cyc))) r = random.randint(0,w[-1]-1) for c2 in range(len(cyc)): if r<w[c2]: break j = random.choice(cyc[c2]) s.append(exc_nf((i,j))) swap(y,i,j) cyc = cycles(y) return s def randDecExc(x): return randss(inv(x)) def randis(x,randlis=urlis): y = x[:] s = [] lis = randlis(y) while len(lis)<n: u = [i for i in range(n) if i not in lis] i = random.choice(ind(u,y)) ival = y[i] for b in range(len(lis)): if lis[b]>ival: break else: b = len(lis) if b==0: a,b = 0,y.index(lis[0]) elif b==len(lis): a,b = y.index(lis[-1]),n-1 else: a,b = y.index(lis[b-1]),y.index(lis[b]) if a==b: j = a elif i<a: j = random.randint(a,b-1) elif i>b: j = random.randint(a+1,b) else: j = None print("Problem with randis") s.append(ins_nf((i,j))) lis.append(ival) lis = sorted(lis) insert(y,i,j) if lis not in alis(y): print("BIG PROBLEM") return s def decInsSeq(x,randlis=urlis): return randis(inv(x),randlis) def checkAllInsDiamRev(): #return true if for all permutations x the Ulam distance between x and rev(x) equals the Ulam diameter #return false otherwise for p in itertools.permutations(e): x = list(p) r = rev(x) if du(x,r)!=Du: return False return True def ssort(x): y = x[:] s = [] for j in range(0,n-1): imin = j for i in range(j+1,n): if y[i]<y[imin]: imin = i if imin!=j: t = y[j] y[j] = y[imin] y[imin] = t s.append(exc_nf((j,imin))) return s def expInertia(nexp=1000,q=1): anomalies = 0 for i in xrange(nexp): x = prand() dx = randDecAsw(x) #y = dot(x,asw(dx[0])) y = [x[k] for k in xrange(n)] # for j in xrange(q): # if j>=len(dx): # break # y = dot(y,asw(dx[j])) # wx = ninver(x) wy = ninver(y) #if wy!=wx+1: if wy!=wx+q: # anomalies += 1 print "Anomalies: " + str(anomalies) + " / " + str(nexp) def all_asw_decomp_aux(a,L,sc,ld): n=len(a) if L==[]: ld.append(sc) else: for i in L: L1=[j for j in L if j!=i] sc1=[i]+sc swap(a,i,i+1) #scambia(a,i,i+1) if i<n-2 and i+1 not in L1 and a[i+1]>a[i+2]: L1.append(i+1) if i>0 and i-1 not in L1 and a[i-1]>a[i]: L1.append(i-1) all_asw_decomp_aux(a,L1,sc1,ld) swap(a,i,i+1) #scambia(a,i,i+1) def all_asw_decomp(a): ld=[] n=len(a) L=[i for i in range(n-1) if a[i]>a[i+1]] all_asw_decomp_aux(a,L,[],ld) return ld def perm2str(x): s = "" for i in range(len(x)): s += str(x[i]) if i<len(x)-1: s += "," return s def checkAverage(q): for j in range(q): x = prand() y = prand() if dk(x,y)<=1: continue #x+a*(y-x) and y+(1-a)*(x-y) #z=y-x=x^-1*y and w=x-y=y^-1*x=inv(y-x) z = dot(inv(x),y) w = inv(z) adz = all_asw_decomp(z) l = len(adz[0]) k = random.randint(1,l-1) #in [1,l-1] #k generators from (y-x) and l-k generators from (x-y) dict1 = {} dict2 = {} for d in adz: zz = x for i in range(k): zz = dot(zz,asw(d[i])) sz = perm2str(zz) if sz in dict1: dict1[sz] += 1 else: dict1[sz] = 1 ww = y drev = rev(d) for i in range(l-k): ww = dot(ww,asw(drev[i])) sw = perm2str(ww) if sw in dict2: dict2[sw] += 1 else: dict2[sw] = 1 if dict1!=dict2: return False; return True #init the environment and print usage init() #test() help() ```
[ { "content": "Repeat the code precisely as written (spacing intact):\n```python\n# (C) British Crown Copyright 2014, Met Office\n#\n# This file is part of Iris.\n#\n# Iris is free software: you can redistribute it and/or modify it under\n# the terms of the GNU Lesser General Public License as published by the\n...
[ { "content": "Repeat the code precisely as written (spacing intact):\n<|memory_start|>```python\n# (C) British Crown Copyright 2014, Met Office\n#\n# This file is part of Iris.\n#\n# Iris is free software: you can redistribute it and/or modify it under\n# the terms of the GNU Lesser General Public License as pu...
```python # (C) British Crown Copyright 2014, Met Office # # This file is part of Iris. # # Iris 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. # # Iris 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 Iris. If not, see <http://www.gnu.org/licenses/>. """ Tests for function :func:`iris.fileformats.grib._load_convert.translate_phenomenon`. """ from __future__ import (absolute_import, division, print_function) # import iris tests first so that some things can be initialised # before importing anything else. import iris.tests as tests from copy import deepcopy from iris.coords import DimCoord from iris.unit import Unit from iris.fileformats.grib._load_convert import Probability from iris.fileformats.grib.grib_phenom_translation import _GribToCfDataClass from iris.fileformats.grib._load_convert import translate_phenomenon class Test_probability(tests.IrisTest): def setUp(self): # Patch inner call to return a given phenomenon type. target_module = 'iris.fileformats.grib._load_convert' self.phenom_lookup_patch = self.patch( target_module + '.itranslation.grib2_phenom_to_cf_info', return_value=_GribToCfDataClass('air_temperature', '', 'K', None)) # Construct dummy call arguments self.probability = Probability('<prob_type>', 22.0) self.metadata = {'aux_coords_and_dims': []} def test_basic(self): result = translate_phenomenon(self.metadata, None, None, None, probability=self.probability) # Check metadata. thresh_coord = DimCoord([22.0], standard_name='air_temperature', long_name='', units='K') self.assertEqual(self.metadata, { 'standard_name': None, 'long_name': 'probability_of_air_temperature_<prob_type>', 'units': Unit(1), 'aux_coords_and_dims': [(thresh_coord, None)]}) def test_no_phenomenon(self): original_metadata = deepcopy(self.metadata) self.phenom_lookup_patch.return_value = None result = translate_phenomenon(self.metadata, None, None, None, probability=self.probability) self.assertEqual(self.metadata, original_metadata) if __name__ == '__main__': tests.main() ```
[ { "content": "Here is some code:\n```python\n#!/usr/bin/env python\n# -*- coding: latin-1 -*-\nimport sys, os\n\nfrom optparse import OptionParser, OptionGroup\nimport xml.etree.ElementTree as ET\n\n## Importing Utils from parent path\nfile_path = os.path.dirname(__file__)\njoin_path = os.path.join(file_path, '...
[ { "content": "Here is some code:\n<|memory_start|>```python\n#!/usr/bin/env python\n# -*- coding: latin-1 -*-\nimport sys, os\n\nfrom optparse import OptionParser, OptionGroup\nimport xml.etree.ElementTree as ET\n\n## Importing Utils from parent path\nfile_path = os.path.dirname(__file__)\njoin_path = os.path.j...
```python #!/usr/bin/env python # -*- coding: latin-1 -*- import sys, os from optparse import OptionParser, OptionGroup import xml.etree.ElementTree as ET ## Importing Utils from parent path file_path = os.path.dirname(__file__) join_path = os.path.join(file_path, '../Utils') abs_path = os.path.abspath(join_path) sys.path.append(abs_path) from Utils import Utilities from Utils.XMLParser import ParseXml2Dict class AutoCodeError(Exception): def __init__(self, message, reason): self.message = message self.reason = reason class AutoCode(object): ''' Service instance is the type of created service as defined in task service parameters as 'instance' in the configuration file ''' ServiceType = 'TestServiceType' ''' Task file name is for defining specific operations from task class. It will be imported from created directory and used to instance a task class. ''' TaskFile = 'TestTaskFile' ''' Name of the autogenerated task class. It should have the logic for producing a service. It is called by the service and imported by file name. ''' TaskClass = 'TestTaskClass' ''' Required for logging and identifying task operations. ''' TaskDescription = 'TestTaskDescription' ''' Logging context name. It is used in 'TaskLogName' in the configuration file. ''' ContextName = 'TestContextName' ''' Defines a service name for the identifying service process messages. It is called in process configuration configuration file. ''' ServiceName = 'TestServiceName' ''' IP address of server endpoint. It is used in 'FrontEndEndpoint' and 'BackendEndpoint' in the configuration file. ''' ServerIP = 'TestServerIP' ''' Front end port for subscriber and back end binding ports. It is used in 'FrontEndEndpoint' and 'BackendBind' in the configuration file. ''' SubPort = 'TestSubPort' ''' Back end port for subscriber and front end binding ports. It is used in 'BackendEndpoint' and 'FrontBind' in the configuration file. ''' PubPort = 'TestPubPort' ''' Task service ID identifier. It is used as parameter 'id' in 'TaskService' label in the configuration file. ''' TaskID = 'TestTaskID' ''' Task device action used for message identification. It is used as 'device_action' of the content configuration of the task service in the configuration file. ''' DeviceAction = 'TestDeviceAction' ''' Defines entry action to be executed upon entry to a state associated with other states. It is not to transitions and it is called regardless of how a state is resulted. This fixture is related to UML statechart. ''' EntryAction = 'TestEntryAction' ''' If it exists, defines the type of task template to use: "Single" or "Looped". The "Single" process is executed from start to finish. The "Looped" is a process that continously executes itself. ''' TaskType = 'TestTaskType' ''' User-defined identifier for context. It should be a unique alpha-numeric identifier. ''' ContextID = 'TestContextID' ''' Used to refer the absolute path location of non-system services. ''' ModuleLocation = 'TestModuleLocation' def __init__(self, options): ''' Class constructor''' try: self.ServicePath = None self.HomePath = None self.ServiceType = None self.TaskFile = None self.TaskClass = None self.TaskDescription = None self.ServiceName = None self.ServerIP = None self.SubPort = None self.PubPort = None self.ContextName = None self.TaskID = None self.DeviceAction = None self.EntryAction = None self.TaskType = 'Looped' self.ModuleLocation = None self.ContextID = None self.StateConf = [] self.log = True ## Service configuration location self.ServicePath = options['service_path'] self.HomePath = options['home_path'] ## Service generation stub variables self.ServiceType = options['task_service'] self.TaskFile = options['task_service'] self.TaskClass = options['task_service'] self.TaskDescription= options['task_desc'] ## Service XML configuration options self.ServiceName = options['service_name'] self.ServerIP = options['server_ip'] self.SubPort = options['sub_port'] self.PubPort = options['pub_port'] self.ContextName = options['context_name'] self.TaskID = options['task_id'] self.DeviceAction = options['device_action'] self.EntryAction = options['entry_action'] self.StateConf = options['state'] self.ContextID = options['context_id'] self.ModuleLocation= options['location'] ## Setting logger if 'log_on' in options.keys(): self.log = options['log_on'] # Validating state values whether they would be incomplete if 'task_type' in options.keys(): self.TaskType = options['task_type'] if len(self.StateConf) != 4: raise AutoCodeError('Failure in constructor', 'State transitions are not complete') reason = "Analysing... ["+self.ServicePath+"]" self.PrintLog("- "+reason) servicesPath = self.ServicePath+'/Services' if not os.path.exists(servicesPath): self.PrintLog("- Context service root path not found, creating [Services] directory") os.makedirs(servicesPath) else: self.PrintLog(" Nothing to do") except Exception as inst: Utilities.ParseException(inst) def PrintLog(self, msg): ''' Internal logger method''' if self.log: print msg def CreateInit(self): '''Create init file for service''' try: servicePath = self.ServicePath+'/Services/'+self.ServiceType if not os.path.exists(servicePath): message = "Warning:" reason = "Root path is not valid" print message+" : "+reason return servicePath ## Open init template #$TaskFile import $TaskClass self.PrintLog("+ Generating init template file") initName = '__init__.' initPath = self.HomePath+'/Tools/Templates/'+initName+'tmpl' with open(initPath, 'r') as openedFile: data=openedFile.read() data = data.replace('$TaskFile', self.TaskFile) data = data.replace('$TaskClass', self.TaskClass) initOutput = servicePath+'/'+initName+'py' #print "==>", initOutput with open(initOutput, "w") as init_file: init_file.write(data) except Exception as inst: Utilities.ParseException(inst) finally: return servicePath def CreateDirectory(self): '''Create directoy with service name ''' try: servicePath = self.ServicePath+'/Services/'+self.ServiceType if os.path.exists(servicePath): message = "Warning: Couldn't create service path" reason = "Path already exists ["+servicePath+"]" self.PrintLog(message+" "+reason) return servicePath ## If directory does not exists, create it self.PrintLog("+ Creating service directory [%s]"%servicePath) os.makedirs(servicePath) except Exception as inst: Utilities.ParseException(inst) finally: return servicePath def CreateServiceStub(self): '''Create service task stub file''' try: servicePath = self.ServicePath+'/Services/'+self.ServiceType if not os.path.exists(servicePath): message = "Warning:" reason = "Root path is not valid" print message+" : "+reason return servicePath ## Open service task template #$TaskFile import $TaskClass self.PrintLog("+ Loading task service stub template file") fileName = 'Service'+self.ServiceType+'.py' filePath = self.HomePath+'/Tools/Templates/ServiceTask.tmpl' with open(filePath, 'r') as openedFile: data=openedFile.read() data = data.replace('$ServiceType', self.ServiceType) data = data.replace('$TaskFile', self.TaskFile) data = data.replace('$TaskDescription', self.TaskDescription) data = data.replace('$ServiceName', self.ServiceName) data = data.replace('$TaskClass', self.TaskClass) fileOutput = servicePath+'/'+fileName with open(fileOutput, "w") as init_file: init_file.write(data) except Exception as inst: Utilities.ParseException(inst) def CreateTaskStub(self): '''Create strategy task stub file''' try: servicePath = self.ServicePath+'/Services/'+self.ServiceType if not os.path.exists(servicePath): message = "Warning:" reason = "Root path is not valid" print message+" : "+reason ##TODO: Should create an exception sys.exit(0) ## Open service task template self.PrintLog("+ Loading task template file") fileName = self.TaskFile+'.py' ## Defining the type of task if self.TaskType == 'Looped': filePath = self.HomePath+'/Tools/Templates/Task.tmpl' elif self.TaskType == 'Single': filePath = self.HomePath+'/Tools/Templates/TaskSingle.tmpl' else: message = "Warning:" reason = "Invalid type of task template" print message+" : "+reason ##TODO: Should create an exception sys.exit(0) self.PrintLog("+ Loading a task for [%s]"%self.TaskType) with open(filePath, 'r') as openedFile: data=openedFile.read() data = data.replace('$TaskClass', self.TaskClass) fileOutput = servicePath+'/'+fileName with open(fileOutput, "w") as init_file: init_file.write(data) except Exception as inst: Utilities.ParseException(inst) def AdaptConfFile(self): '''Create strategy task stub file''' try: servicePath = self.ServicePath+'/Services/'+self.ServiceType if not os.path.exists(servicePath): message = "Warning:" reason = "Root path is not valid" print message+" : "+reason return servicePath ## Open configuration template file self.PrintLog("+ Adapting configuration file") fileName = 'Context-'+self.ContextName+'.xml' filePath = self.HomePath+'/Tools/Templates/Context.tmpl' ## Creating conf path confFilePath = self.HomePath+'/Conf/' if not os.path.exists(confFilePath): self.PrintLog("- Creating configuration directory") os.makedirs(confFilePath) confFileName = confFilePath+fileName if os.path.isfile(confFileName): ''' ''' ## File already exists, self.PrintLog("+ Updating configuration file [%s]"%fileName) with open(confFileName, 'r') as openedFile: '''''' ## Loading file content as XML data=openedFile.read() root = ET.fromstring(data) ## Checking for already defined configuration processes nodes = root.findall("./TaskService") for child in nodes: #print "==>1 ", child.tag, child.attrib attribs = child.attrib ## Checking if process is already defined if attribs['instance']==self.ServiceType or attribs['id']==self.TaskID: self.PrintLog("+ Process is already defined") return ## Merging both XML's self.PrintLog("+ Verifying for exisiting content") ## Opening template file to get task service model with open(filePath, 'r') as openedFile: templateData = openedFile.read() templateData = self.SetValues(templateData) templateRoot = ET.fromstring(templateData) ## Removing non required items for merging templateRoot.remove(templateRoot.find('FrontEndEndpoint')) templateRoot.remove(templateRoot.find('BackendEndpoint')) templateRoot.remove(templateRoot.find('FrontBind')) templateRoot.remove(templateRoot.find('BackendBind')) templateRoot.remove(templateRoot.find('TaskLogName')) templateRoot.remove(templateRoot.find('ContextID')) ## Merging XML trees and obtaining merged XML file self.PrintLog("+ Merging XML processes") root.append(templateRoot[0]) mergedXML = ET.tostring(root, encoding='utf8', method='xml') ## Writing new appended file self.PrintLog("+ Writing on merged file: [%s]"%confFilePath) with open(confFileName, "w") as init_file: init_file.write(mergedXML) else: ## Generating a new file self.PrintLog("+ Opening task template file") with open(filePath, 'r') as openedFile: data = openedFile.read() data = self.SetValues(data) self.PrintLog("+ Creating a new [%s] configuration file"%fileName) with open(confFileName, "w") as init_file: init_file.write(data) ## TODO: Add extended configuration if it exists except Exception as inst: Utilities.ParseException(inst) def SetValues(self, data): '''Setting values to template ''' data = data.replace('$ServerIP', self.ServerIP) data = data.replace('$SubPort', self.SubPort) data = data.replace('$PubPort', self.PubPort) data = data.replace('$ContextName', self.ContextName) data = data.replace('$ContextID', self.ContextID) data = data.replace('$TaskID', self.TaskID) data = data.replace('$DeviceAction',self.DeviceAction) data = data.replace('$TaskDescription',self.TaskDescription) data = data.replace('$ServiceName', self.ServiceName) data = data.replace('$ServiceType', self.ServiceType) data = data.replace('$EntryAction', self.EntryAction) data = data.replace('$ModuleLocation',self.ModuleLocation) ## Replacing state information confSize = len(self.StateConf) for i in range(confSize): confData = self.StateConf[i] indexDoc = str(i+1) self.PrintLog("+ [%s] Setting up data for triggering [%s]"%(indexDoc, confData['trigger'])) ## Replacing state information: trigger, action and state ID data = data.replace('$Trigger'+indexDoc, confData['trigger']) data = data.replace('$Action'+indexDoc , confData['action']) data = data.replace('$State'+indexDoc , confData['state_id']) return data def CreateFiles(self): ''' Generate code for: 1) Create service directory 2) __init__.py 3) Service<NAME>.py stub file 4) Strategy file stub ''' try: ## 1) Create service directory ## TODO: Change to a dynamic path in context services servicesPath = self.CreateDirectory() ## 2) Creating __init__.py self.CreateInit() ## 3) Service<NAME>.py stub file self.CreateServiceStub() ## 4) Strategy file stub self.CreateTaskStub() ## 5) Create or update configuration file self.AdaptConfFile() except AutoCodeError as e: print e.message+" : "+e.reason except Exception as inst: Utilities.ParseException(inst) sUsage = "usage:\n"\ " For sending a message to an annotator service\n"\ "\t python Tools/create_service.py \n"\ "\t\t--service_path='/abs/path/unix/style' \n"\ "\t\t--home_path='/abs/path/unix/style' \n"\ "\t\t--task_service='instance_type' \n"\ "\t\t--service_name='service_name' \n"\ "\t\t--task_desc='task_description' \n"\ "\t\t--server_ip='127.0.0.1' \n"\ "\t\t--sub_port='XXXX' \n"\ "\t\t--pub_port='YYYY' \n"\ "\t\t--context_name='context_test_name' \n"\ "\t\t--task_id='task_ID' \n"\ "\t\t--device_action='device_action_id' \n" if __name__ == '__main__': try: available_entry_actions = ['on_exit', 'on_fail', 'on_start', 'on_update'] usage = sUsage parser = OptionParser(usage=usage) systemOpts = OptionGroup(parser, "Service configuration location") systemOpts.add_option('--service_path', metavar="PATH", default=None, help="Absolute root path where context services are located") systemOpts.add_option('--xml_file', metavar="PATH XML FILE", default=None, help="Absolute root path where xml configuration file is located") contextOpts= OptionGroup(parser, "Service generation stub variables") contextOpts.add_option('--task_service', metavar="SERVICE", default=None, help="Service instance is the type of created service as defined " "in task service parameters in the configuration file") contextOpts.add_option('--task_desc', metavar="TASK_DESCRIPTION", default=None, help="Required for logging and identifying task operations.") xmltOpts= OptionGroup(parser, "Service XML configuration options") xmltOpts.add_option('--context_name', metavar="CONTEXTNAME", default=None, help="Logging context name. It is used in 'TaskLogName' in the " "configuration file.") xmltOpts.add_option('--service_name', metavar="SERVICE_NAME", default=None, help="Defines a service name for the identifying service process " "messages. It is called in process configuration configuration file") xmltOpts.add_option('--server_ip', metavar="SERVERIP", default=None, help="IP address of server endpoint. It is used in " "'FrontEndEndpoint' and 'BackendEndpoint' in the " "configuration file.") xmltOpts.add_option('--sub_port', metavar="SUBPORT", default=None, help="Front end port for subscriber and back end binding ports. " "It is used in 'FrontEndEndpoint' and 'BackendBind' in the " "configuration file.") xmltOpts.add_option('--pub_port', metavar="PUBPORT", default=None, help="Back end port for subscriber and front end binding ports. " "It is used in 'BackendEndpoint' and 'FrontBind' in the " "configuration file.") xmltOpts.add_option('--task_id', metavar="TASKID", default=None, help="Task service ID identifier. It is used as parameter" "'id' in 'TaskService' label in the configuration file") xmltOpts.add_option('--device_action', metavar="DEVICEACTION", default=None, help="Task device action used for message identification. messages." "It is called in process configuration configuration file It is " "used as 'device_action of the content configuration of the task " "service in the configuration file.") xmltOpts.add_option('--entry_action', type='choice', action='store', dest='entry_action', choices=available_entry_actions, default=None, help="Defines entry action to be executed upon entry to a state associated with " "other states. It is not to transitions and it is called regardless of how a " "state is resulted. This fixture is related to UML statechart from the following " "choices: "+str(available_entry_actions)) parser.add_option_group(systemOpts) parser.add_option_group(contextOpts) parser.add_option_group(xmltOpts) (options, args) = parser.parse_args() if options.xml_file is None and options.service_path is None: parser.error("Missing required option: service_path or xml_file") parser.print_help() if options.xml_file is None and options.home_path is None: parser.error("Missing required option: home_path or xml_file") parser.print_help() if options.xml_file is not None: ''' ''' ## Use if many services are generated at the same time services = ParseXml2Dict(options.xml_file, 'MetaServiceConf') if type(services['Service']) is not type([]): services['Service'] = [services['Service']] for service in services['Service']: service.update({'context_name': services['context_name']}) service.update({'server_ip': services['server_ip']}) service.update({'sub_port': services['sub_port']}) service.update({'pub_port': services['pub_port']}) service.update({'service_path': services['service_path']}) if 'home_path' not in services.keys(): service.update({'home_path': '/opt/zmicroservices/'}) else: service.update({'home_path': services['home_path']}) service.update({'context_id': services['context_id']}) if 'log_on' in services.keys(): service.update({'log_on': bool(int(services['log_on']))}) if 'location' not in services.keys(): service.update({'location': services['service_path']+'/Services'}) else: service.update({'location': services['location']}) service.update({'context_id': services['context_id']}) #pprint.pprint(service) ## Checking if there is a type of task taskType = 'Looped' if 'task_type' in service.keys(): taskType = service['task_type'] service.update({'taskType': taskType}) ## Calling code autogenerator autogenerator = AutoCode(service) autogenerator.CreateFiles() else: ''' Checking argument values ''' if options.task_service is None: parser.error("Missing required option: task_service") parser.print_help() if options.task_desc is None: parser.error("Missing required option: task_desc") parser.print_help() if options.context_name is None: parser.error("Missing required option: context_name") parser.print_help() if options.service_name is None: parser.error("Missing required option: service_name") parser.print_help() if options.server_ip is None: parser.error("Missing required option: server_ip") parser.print_help() if options.sub_port is None: parser.error("Missing required option: sub_port") parser.print_help() if options.pub_port is None: parser.error("Missing required option: pub_port") parser.print_help() if options.task_id is None: parser.error("Missing required option: task_id") parser.print_help() if options.device_action is None: parser.error("Missing required option: device_action") parser.print_help() if options.entry_action is None: parser.error("Missing required option: entry_action") parser.print_help() ## Calling code autogenerator options_dict = vars(options) autogenerator = AutoCode(options_dict) autogenerator.CreateFiles() except AutoCodeError as e: print('Error: %s, %s'%(e.message, e.reason)) ```
[ { "content": "Output the full code verbatim (no extra comments):\n```python\n# -*- coding: utf-8 -*-\n# Copyright 2009-2017 Noviat\n# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).\n\nimport calendar\nfrom datetime import datetime\nfrom dateutil.relativedelta import relativedelta\nimport logging\...
[ { "content": "Output the full code verbatim (no extra comments):\n<|memory_start|>```python\n# -*- coding: utf-8 -*-\n# Copyright 2009-2017 Noviat\n# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).\n\nimport calendar\nfrom datetime import datetime\nfrom dateutil.relativedelta import relativedelta\...
```python # -*- coding: utf-8 -*- # Copyright 2009-2017 Noviat # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). import calendar from datetime import datetime from dateutil.relativedelta import relativedelta import logging from sys import exc_info from traceback import format_exception from openerp import api, fields, models, _ from openerp.addons.decimal_precision import decimal_precision as dp from openerp.exceptions import Warning as UserError _logger = logging.getLogger(__name__) class DummyFy(object): def __init__(self, *args, **argv): for key, arg in argv.items(): setattr(self, key, arg) class AccountAsset(models.Model): _name = 'account.asset' _description = 'Asset' _order = 'date_start desc, name' _parent_store = True account_move_line_ids = fields.One2many( comodel_name='account.move.line', inverse_name='asset_id', string='Entries', readonly=True, copy=False) move_line_check = fields.Boolean( compute='_compute_move_line_check', type='boolean', string='Has accounting entries') name = fields.Char( string='Asset Name', size=64, required=True, readonly=True, states={'draft': [('readonly', False)]}) code = fields.Char( string='Reference', size=32, readonly=True, states={'draft': [('readonly', False)]}) purchase_value = fields.Float( string='Purchase Value', required=True, readonly=True, states={'draft': [('readonly', False)]}, help="This amount represent the initial value of the asset." "\nThe Depreciation Base is calculated as follows:" "\nPurchase Value - Salvage Value.") salvage_value = fields.Float( string='Salvage Value', digits=dp.get_precision('Account'), readonly=True, states={'draft': [('readonly', False)]}, help="The estimated value that an asset will realize upon " "its sale at the end of its useful life.\n" "This value is used to determine the depreciation amounts.") depreciation_base = fields.Float( compute='_compute_depreciation_base', digits=dp.get_precision('Account'), string='Depreciation Base', store=True, help="This amount represent the depreciation base " "of the asset (Purchase Value - Salvage Value.") value_residual = fields.Float( compute='_compute_depreciation', digits=dp.get_precision('Account'), string='Residual Value', store=True) value_depreciated = fields.Float( compute='_compute_depreciation', digits=dp.get_precision('Account'), string='Depreciated Value', store=True) taxadmin_depreciation_base = fields.Float( compute='_compute_taxadmin_depreciation_base', digits=dp.get_precision('Account'), string='Taxadmin Depreciation Base', store=True, help="This amount represent the taxadmin depreciation base " "of the asset (if resitual valie is same depreciation base it take 0.") taxadmin_value_residual = fields.Float( compute='_compute_taxadmin_depreciation', digits=dp.get_precision('Account'), string='Taxadmin Residual Value', store=True) taxadmin_value_depreciated = fields.Float( compute='_compute_taxadmin_depreciation', digits=dp.get_precision('Account'), string='Taxadmin Depreciated Value', store=True) note = fields.Text('Note') profile_id = fields.Many2one( comodel_name='account.asset.profile', string='Asset Profile', change_default=True, readonly=True, domain=[('type', '=', 'normal')], states={'draft': [('readonly', False)]}) taxadmin_profile_id = fields.Many2one( comodel_name='account.asset.profile', string='Taxadmin Asset Profile', change_default=True, readonly=True, domain=[('type', '=', 'taxadmin')], states={'draft': [('readonly', False)]}) parent_id = fields.Many2one( comodel_name='account.asset', string='Parent Asset', readonly=True, states={'draft': [('readonly', False)]}, domain=[('type', '=', 'view')], ondelete='restrict') parent_left = fields.Integer(index=True) parent_right = fields.Integer(index=True) child_ids = fields.One2many( comodel_name='account.asset', inverse_name='parent_id', string='Child Assets') date_start = fields.Date( string='Asset Start Date', readonly=True, states={'draft': [('readonly', False)]}, default=fields.Datetime.now, help="You should manually add depreciation lines " "with the depreciations of previous fiscal years " "if the Depreciation Start Date is different from the date " "for which accounting entries need to be generated.") date_remove = fields.Date(string='Asset Removal Date', readonly=True) state = fields.Selection( selection=[ ('draft', 'Draft'), ('open', 'Running'), ('close', 'Close'), ('removed', 'Removed'), ], string='Status', required=True, default='draft', copy='draft', help="When an asset is created, the status is 'Draft'.\n" "If the asset is confirmed, the status goes in 'Running' " "and the depreciation lines can be posted " "to the accounting.\n" "If the last depreciation line is posted, " "the asset goes into the 'Close' status.\n" "When the removal entries are generated, " "the asset goes into the 'Removed' status.") active = fields.Boolean(default=True) partner_id = fields.Many2one( comodel_name='res.partner', string='Partner', readonly=True, states={'draft': [('readonly', False)]}) method = fields.Selection( selection=lambda self: self.env['account.asset.profile']. _selection_method(), string='Computation Method', required=True, readonly=True, states={'draft': [('readonly', False)]}, default='linear', help="Choose the method to use to compute " "the amount of depreciation lines.\n" " * Linear: Calculated on basis of: " "Gross Value / Number of Depreciations\n" " * Degressive: Calculated on basis of: " "Residual Value * Degressive Factor" " * Degressive-Linear (only for Time Method = Year): " "Degressive becomes linear when the annual linear " "depreciation exceeds the annual degressive depreciation") method_number = fields.Integer( string='Number of Years', readonly=True, states={'draft': [('readonly', False)]}, default=5, help="The number of years needed to depreciate your asset") method_period = fields.Selection( selection=[('month', 'Month'), ('quarter', 'Quarter'), ('year', 'Year')], string='Period Length', required=True, readonly=True, states={'draft': [('readonly', False)]}, default='year', help="Period length for the depreciation accounting entries") method_end = fields.Date( string='Ending Date', readonly=True, states={'draft': [('readonly', False)]}) method_percentage = fields.Float( string='Depreciation percentage', readonly=True, digits=(3, 2), states={'draft': [('readonly', False)]}, default=100.0, help="The percent for liniar method of depreciate your asset") taxadmin_method_percentage = fields.Float( string='Taxadmin Depreciation percentage', related='taxadmin_profile_id.method_percentage', help="The percent for liniar method of depreciate your asset") method_progress_factor = fields.Float( string='Degressive Factor', readonly=True, states={'draft': [('readonly', False)]}, default=0.3) method_time = fields.Selection( selection=lambda self: self.env['account.asset.profile']. _selection_method_time(), string='Time Method', required=True, readonly=True, states={'draft': [('readonly', False)]}, default='year', help="Choose the method to use to compute the dates and " "number of depreciation lines.\n" " * Number of Years: Specify the number of years " "for the depreciation.\n" # " * Number of Depreciations: Fix the number of " # "depreciation lines and the time between 2 depreciations.\n" # " * Ending Date: Choose the time between 2 depreciations " # "and the date the depreciations won't go beyond." ) prorata = fields.Boolean( string='Prorata Temporis', readonly=True, states={'draft': [('readonly', False)]}, help="Indicates that the first depreciation entry for this asset " "have to be done from the depreciation start date instead " "of the first day of the fiscal year.") history_ids = fields.One2many( comodel_name='account.asset.history', inverse_name='asset_id', string='History', copy=False, readonly=True) depreciation_line_ids = fields.One2many( comodel_name='account.asset.line', inverse_name='asset_id', string='Depreciation Lines', copy=False, readonly=True, domain=[('type', 'in', ['create', 'depreciate', 'remove'])], states={'draft': [('readonly', False)]}) taxadmin_depreciation_line_ids = fields.One2many( comodel_name='account.asset.line', inverse_name='asset_id', string='Depreciation Lines', copy=False, domain=[('type', 'in', ['create', 'taxadmin', 'remove'])], readonly=True, states={'draft': [('readonly', False)]}) type = fields.Selection( selection=[('view', 'View'), ('normal', 'Normal')], string='Type', required=True, readonly=True, default='normal', states={'draft': [('readonly', False)]}) company_id = fields.Many2one( comodel_name='res.company', string='Company', required=True, readonly=True, default=lambda self: self._default_company_id()) company_currency_id = fields.Many2one( comodel_name='res.currency', related='company_id.currency_id', string='Company Currency', store=True, readonly=True) account_analytic_id = fields.Many2one( comodel_name='account.analytic.account', string='Analytic account', domain=[('type', '!=', 'view'), ('state', 'not in', ('close', 'cancelled'))]) @api.model def _default_company_id(self): return self.env[ 'res.company']._company_default_get('account.asset') @api.multi def _compute_move_line_check(self): for asset in self: for line in asset.depreciation_line_ids: if line.move_id: asset.move_line_check = True continue @api.depends('purchase_value', 'salvage_value', 'type', 'method') @api.multi def _compute_depreciation_base(self): for asset in self: if asset.type == 'view': asset.depreciation_base = 0.0 elif asset.method in ['linear-limit', 'degr-limit']: asset.depreciation_base = asset.purchase_value else: asset.depreciation_base = \ asset.purchase_value - asset.salvage_value @api.multi @api.depends('depreciation_base', 'depreciation_line_ids.amount', 'depreciation_line_ids.previous_id', 'depreciation_line_ids.init_entry', 'depreciation_line_ids.move_id') def _compute_depreciation(self): for asset in self: if asset.type == 'normal': lines = asset.depreciation_line_ids.filtered( lambda l: l.type in ('depreciate', 'remove') and (l.init_entry or l.move_check)) value_depreciated = sum([l.amount for l in lines]) asset.value_residual = \ asset.depreciation_base - value_depreciated asset.value_depreciated = value_depreciated else: asset.value_residual = 0.0 asset.value_depreciated = 0.0 @api.multi @api.depends('depreciation_base', 'taxadmin_value_depreciated', 'taxadmin_value_residual') def _compute_taxadmin_depreciation_base(self): for asset in self: if self.taxadmin_value_residual <= 0.0: self.taxadmin_depreciation_base = 0.0 self.taxadmin_value_depreciated = 0.0 else: self.taxadmin_depreciation_base = self.depreciation_base @api.multi @api.depends('depreciation_base', 'depreciation_line_ids.amount', 'depreciation_line_ids.previous_id', 'depreciation_line_ids.init_entry', 'depreciation_line_ids.move_id') def _compute_taxadmin_depreciation(self): for asset in self: if asset.type == 'normal': lines = asset.depreciation_line_ids.filtered( lambda l: l.type in ('taxadmin', 'remove') and (l.init_entry or l.move_check)) value_depreciated = sum([l.amount for l in lines]) asset.taxadmin_value_residual = \ asset.depreciation_base - value_depreciated asset.taxadmin_value_depreciated = value_depreciated else: asset.taxadmin_value_residual = 0.0 asset.taxadmin_value_depreciated = 0.0 @api.multi @api.constrains('parent_id') def _check_recursion(self, parent=None): res = super(AccountAsset, self)._check_recursion(parent=parent) if not res: raise UserError( _("Error ! You can not create recursive assets.")) return res @api.multi @api.constrains('method') def _check_method(self): for asset in self: if asset.method == 'degr-linear' and asset.method_time != 'year': raise UserError( _("Degressive-Linear is only supported for Time Method = " "Year.")) @api.multi @api.constrains('date_start', 'method_end') def _check_dates(self): for asset in self: if asset.method_time == 'end': if asset.method_end <= asset.date_start: raise UserError( _("The Start Date must precede the Ending Date.")) @api.onchange('purchase_value', 'salvage_value', 'date_start', 'method') def _onchange_purchase_salvage_value(self): if self.method in ['linear-limit', 'degr-limit']: self.depreciation_base = self.purchase_value or 0.0 else: purchase_value = self.purchase_value or 0.0 salvage_value = self.salvage_value or 0.0 self.depreciation_base = purchase_value - salvage_value dl_create_line = self.depreciation_line_ids.filtered( lambda r: r.type == 'create') dl_create_line.write({ 'amount': self.depreciation_base, 'line_date': self.date_start}) @api.onchange('profile_id') def _onchange_profile_id(self): for line in self.depreciation_line_ids: if line.move_id: raise UserError( _("You cannot change the profile of an asset " "with accounting entries.")) if self.profile_id: profile = self.profile_id self.parent_id = profile.parent_id self.method = profile.method self.method_number = profile.method_number self.method_percentage = profile.method_percentage self.method_time = profile.method_time self.method_period = profile.method_period self.method_progress_factor = profile.method_progress_factor self.prorata = profile.prorata self.account_analytic_id = profile.account_analytic_id self.taxadmin_profile_id = profile.taxadmin_profile_id @api.onchange('method_time') @api.depends('method_percentage') def _onchange_method_time(self): if self.method_time != 'year': self.prorata = True if self.method_time == 'percentage': self.method_period = 'month' self.method_number = int((100.0/self.method_percentage)*12) @api.onchange('method_percentage') def _onchange_method_percentage(self): self.method_period = 'month' self.method_number = int((100.0/self.method_percentage)*12) @api.onchange('type') def _onchange_type(self): if self.type == 'view': self.date_start = False self.profile_id = False self.purchase_value = False self.salvage_value = False if self.depreciation_line_ids: self.depreciation_line_ids.unlink() @api.model def create(self, vals): if vals.get('method_time') != 'year' and not vals.get('prorata'): vals['prorata'] = True if vals.get('method_time') == 'percentage': vals['method_period'] = 'month' vals['method_number'] = int((100.0/vals['method_percentage'])*12) asset = super(AccountAsset, self).create(vals) if self._context.get('create_asset_from_move_line'): # Trigger compute of depreciation_base asset.salvage_value = 0.0 if asset.type == 'normal': # create first asset line asset_line_obj = self.env['account.asset.line'] line_name = asset._get_depreciation_entry_name(0) asset_line_vals = { 'amount': asset.depreciation_base, 'taxadmin_amount': asset.depreciation_base, 'asset_id': asset.id, 'name': line_name, 'line_date': asset.date_start, 'init_entry': True, 'type': 'create', } asset_line = asset_line_obj.create(asset_line_vals) if self._context.get('create_asset_from_move_line'): asset_line.move_id = self._context['move_id'] # Add as taxadmin #ctx = dict(self._context, mode='taxadmin') #asset_line = asset_line_obj.with_context(ctx).create(asset_line_vals) #if self._context.get('create_asset_from_move_line'): # asset_line.move_id = self._context['move_id'] return asset @api.multi def write(self, vals): if vals.get('method_time'): if vals['method_time'] != 'year' and not vals.get('prorata'): vals['prorata'] = True if vals.get('method_percentage') and vals['method_time'] == 'percentage': vals['method_period'] = 'month' vals['method_number'] = int((100.0/vals['method_percentage'])*12) for asset in self: asset_type = vals.get('type') or asset.type super(AccountAsset, self).write(vals) if asset_type == 'view' or \ self._context.get('asset_validate_from_write'): continue if asset.profile_id.open_asset and \ self._context.get('create_asset_from_move_line'): asset.compute_depreciation_board() # extra context to avoid recursion ctx = dict(self._context, asset_validate_from_write=True) asset.with_context(ctx).validate() return True @api.multi def unlink(self): for asset in self: if asset.state != 'draft': raise UserError( _("You can only delete assets in draft state.")) if asset.depreciation_line_ids.filtered( lambda r: (r.type == 'depreciate' or r.type == 'taxadmin') and r.move_check): raise UserError( _("You cannot delete an asset that contains " "posted depreciation lines.")) # update accounting entries linked to lines of type 'create' ctx = dict(self._context, allow_asset_removal=True, from_parent_object=True) amls = self.with_context(ctx).mapped('account_move_line_ids') amls.write({'asset_id': False}) return super(AccountAsset, self).unlink() @api.multi def validate(self): for asset in self: if asset.type == 'normal' and asset.company_currency_id.is_zero( asset.value_residual): asset.state = 'close' else: asset.state = 'open' return True @api.multi def remove(self): self.ensure_one() ctx = dict(self._context, active_ids=self.ids, active_id=self.id) early_removal = False if self.method in ['linear-limit', 'degr-limit']: if self.value_residual != self.salvage_value: early_removal = True elif self.value_residual: early_removal = True if early_removal: ctx.update({'early_removal': True}) return { 'name': _("Generate Asset Removal entries"), 'view_type': 'form', 'view_mode': 'form', 'res_model': 'account.asset.remove', 'target': 'new', 'type': 'ir.actions.act_window', 'context': ctx, 'nodestroy': True, } @api.multi def set_to_draft(self): return self.write({'state': 'draft'}) @api.multi def open_entries(self): self.ensure_one() amls = self.env['account.move.line'].search( [('asset_id', '=', self.id)], order='date ASC') am_ids = [l.move_id.id for l in amls] return { 'name': _("Journal Entries"), 'view_type': 'form', 'view_mode': 'tree,form', 'res_model': 'account.move', 'view_id': False, 'type': 'ir.actions.act_window', 'context': self._context, 'nodestroy': True, 'domain': [('id', 'in', am_ids)], } @api.multi def compute_depreciation_board(self): line_obj = self.env['account.asset.line'] digits = self.env['decimal.precision'].precision_get('Account') mode = self._context.get('mode', 'depreciate') #_logger.info("Mode of board %s" % mode) for asset in self: if asset.value_residual == 0.0: continue domain = [ ('asset_id', '=', asset.id), ('type', '=', mode), '|', ('move_check', '=', True), ('init_entry', '=', True)] posted_lines = line_obj.search( domain, order='line_date desc') if (len(posted_lines) > 0): last_line = posted_lines[0] else: last_line = line_obj domain = [ ('asset_id', '=', asset.id), ('type', '=', mode), ('move_id', '=', False), ('init_entry', '=', False)] old_lines = line_obj.search(domain) if old_lines: old_lines.unlink() table = asset._compute_depreciation_table(mode) if not table: continue # group lines prior to depreciation start period depreciation_start_date = datetime.strptime( asset.date_start, '%Y-%m-%d') lines = table[0]['lines'] lines1 = [] lines2 = [] flag = lines[0]['date'] < depreciation_start_date for line in lines: if flag: lines1.append(line) if line['date'] >= depreciation_start_date: flag = False else: lines2.append(line) if lines1: def group_lines(x, y): y.update({'amount': x['amount'] + y['amount']}) return y lines1 = [reduce(group_lines, lines1)] lines1[0]['depreciated_value'] = 0.0 table[0]['lines'] = lines1 + lines2 # check table with posted entries and # recompute in case of deviation depreciated_value_posted = depreciated_value = 0.0 if (len(posted_lines) > 0): last_depreciation_date = datetime.strptime( last_line.line_date, '%Y-%m-%d') last_date_in_table = table[-1]['lines'][-1]['date'] if last_date_in_table <= last_depreciation_date: raise UserError( _("The duration of the asset conflicts with the " "posted depreciation table entry dates.")) for table_i, entry in enumerate(table): residual_amount_table = \ entry['lines'][-1]['remaining_value'] if entry['date_start'] <= last_depreciation_date \ <= entry['date_stop']: break if entry['date_stop'] == last_depreciation_date: table_i += 1 line_i = 0 else: entry = table[table_i] date_min = entry['date_start'] for line_i, line in enumerate(entry['lines']): residual_amount_table = line['remaining_value'] if date_min <= last_depreciation_date <= line['date']: break date_min = line['date'] if line['date'] == last_depreciation_date: line_i += 1 table_i_start = table_i line_i_start = line_i # check if residual value corresponds with table # and adjust table when needed depreciated_value_posted = depreciated_value = \ sum([l.amount for l in posted_lines]) residual_amount = asset.depreciation_base - depreciated_value amount_diff = round( residual_amount_table - residual_amount, digits) if amount_diff: # compensate in first depreciation entry # after last posting line = table[table_i_start]['lines'][line_i_start] line['amount'] -= amount_diff else: # no posted lines table_i_start = 0 line_i_start = 0 seq = len(posted_lines) depr_line = last_line last_date = table[-1]['lines'][-1]['date'] depreciated_value = depreciated_value_posted _logger.info("Table %s" % table) for entry in table[table_i_start:]: for line in entry['lines'][line_i_start:]: seq += 1 name = asset._get_depreciation_entry_name(seq) if line['date'] == last_date: # ensure that the last entry of the table always # depreciates the remaining value if asset.method in ['linear-limit', 'degr-limit']: depr_max = asset.depreciation_base \ - asset.salvage_value else: depr_max = asset.depreciation_base amount = depr_max - depreciated_value else: amount = line['amount'] if amount: vals = { 'previous_id': depr_line.id, 'amount': mode == 'depreciate' and amount or 0.0, 'taxadmin_amount': mode == 'taxadmin' and amount or 0.0, 'asset_id': asset.id, 'name': name, 'line_date': line['date'].strftime('%Y-%m-%d'), 'init_entry': entry['init'], } depreciated_value += amount depr_line = line_obj.create(vals) else: seq -= 1 line_i_start = 0 return True def _get_fy_duration(self, fy_id, option='days'): """ Returns fiscal year duration. @param option: - days: duration in days - months: duration in months, a started month is counted as a full month - years: duration in calendar years, considering also leap years """ fy = self.env['account.fiscalyear'].browse(fy_id) fy_date_start = datetime.strptime(fy.date_start, '%Y-%m-%d') fy_date_stop = datetime.strptime(fy.date_stop, '%Y-%m-%d') days = (fy_date_stop - fy_date_start).days + 1 months = (fy_date_stop.year - fy_date_start.year) * 12 \ + (fy_date_stop.month - fy_date_start.month) + 1 if option == 'days': return days elif option == 'months': return months elif option == 'years': year = fy_date_start.year cnt = fy_date_stop.year - fy_date_start.year + 1 for i in range(cnt): cy_days = calendar.isleap(year) and 366 or 365 if i == 0: # first year if fy_date_stop.year == year: duration = (fy_date_stop - fy_date_start).days + 1 else: duration = ( datetime(year, 12, 31) - fy_date_start).days + 1 factor = float(duration) / cy_days elif i == cnt - 1: # last year duration = ( fy_date_stop - datetime(year, 01, 01)).days + 1 factor += float(duration) / cy_days else: factor += 1.0 year += 1 return factor def _get_fy_duration_factor(self, entry, firstyear): """ localization: override this method to change the logic used to calculate the impact of extended/shortened fiscal years """ duration_factor = 1.0 fy_id = entry['fy_id'] if self.prorata: if firstyear: depreciation_date_start = datetime.strptime( self.date_start, '%Y-%m-%d') fy_date_stop = entry['date_stop'] first_fy_asset_days = \ (fy_date_stop - depreciation_date_start).days + 1 if fy_id: first_fy_duration = self._get_fy_duration( fy_id, option='days') first_fy_year_factor = self._get_fy_duration( fy_id, option='years') duration_factor = \ float(first_fy_asset_days) / first_fy_duration \ * first_fy_year_factor else: first_fy_duration = \ calendar.isleap(entry['date_start'].year) \ and 366 or 365 duration_factor = \ float(first_fy_asset_days) / first_fy_duration elif fy_id: duration_factor = self._get_fy_duration( fy_id, option='years') elif fy_id: fy_months = self._get_fy_duration( fy_id, option='months') duration_factor = float(fy_months) / 12 return duration_factor def _get_depreciation_start_date(self, fy, isTaxMode): """ In case of 'Linear': the first month is counted as a full month if the fiscal year starts in the middle of a month. """ if isTaxMode: date_start = datetime.strptime( self.date_start, '%Y-%m-%d') _,last_day = calendar.monthrange(date_start.year, date_start.month) depreciation_start_date = datetime( date_start.year, date_start.month, last_day) + \ relativedelta(months=1, days=-1) elif self.prorata: depreciation_start_date = datetime.strptime( self.date_start, '%Y-%m-%d') else: fy_date_start = datetime.strptime(fy.date_start, '%Y-%m-%d') depreciation_start_date = datetime( fy_date_start.year, fy_date_start.month, 1) return depreciation_start_date def _get_depreciation_stop_date(self, depreciation_start_date, isTaxMode): if isTaxMode: depreciation_stop_date = depreciation_start_date + \ relativedelta(months=int((100.0/self.taxadmin_method_percentage)*12), days=-1) elif self.method_time == 'year': depreciation_stop_date = depreciation_start_date + \ relativedelta(years=self.method_number, days=-1) elif self.method_time == 'number' or self.method_time == 'percentage': if self.method_period == 'month': depreciation_stop_date = depreciation_start_date + \ relativedelta(months=self.method_number, days=-1) elif self.method_period == 'quarter': m = [x for x in [3, 6, 9, 12] if x >= depreciation_start_date.month][0] first_line_date = depreciation_start_date \ + relativedelta(month=m, day=31) months = self.method_number * 3 depreciation_stop_date = first_line_date \ + relativedelta(months=months - 1, days=-1) elif self.method_period == 'year': depreciation_stop_date = depreciation_start_date + \ relativedelta(years=self.method_number, days=-1) elif self.method_time == 'end': depreciation_stop_date = datetime.strptime( self.method_end, '%Y-%m-%d') return depreciation_stop_date def _get_first_period_amount(self, table, entry, depreciation_start_date, line_dates): """ Return prorata amount for Time Method 'Year' in case of 'Prorata Temporis' """ amount = entry.get('period_amount') if self.prorata and self.method_time == 'year': dates = filter(lambda x: x <= entry['date_stop'], line_dates) full_periods = len(dates) - 1 amount = entry['fy_amount'] - amount * full_periods return amount def _compute_year_amount(self, residual_amount): """ Localization: override this method to change the degressive-linear calculation logic according to local legislation. """ if self.method_time != 'year': raise UserError( _("Programming Error"), _("The '_compute_year_amount' method is only intended for " "Time Method 'Number of Years.")) year_amount_linear = self.depreciation_base / self.method_number if self.method == 'linear': return year_amount_linear if self.method == 'linear-limit': if (residual_amount - year_amount_linear) < self.salvage_value: return residual_amount - self.salvage_value else: return year_amount_linear year_amount_degressive = residual_amount * \ self.method_progress_factor if self.method == 'degressive': return year_amount_degressive if self.method == 'degr-linear': if year_amount_linear > year_amount_degressive: return min(year_amount_linear, residual_amount) else: return min(year_amount_degressive, residual_amount) if self.method == 'degr-limit': if (residual_amount - year_amount_degressive) < self.salvage_value: return residual_amount - self.salvage_value else: return year_amount_degressive else: raise UserError( _("Illegal value %s in asset.method.") % self.method) def _compute_line_dates(self, table, start_date, stop_date, isTaxMode): """ The posting dates of the accounting entries depend on the chosen 'Period Length' as follows: - month: last day of the month - quarter: last of the quarter - year: last day of the fiscal year Override this method if another posting date logic is required. """ # isTaxMode = (self._context.get('mode') and self._context.get('mode') == 'taxadmin') line_dates = [] if self.method_period == 'month' or isTaxMode: line_date = start_date + relativedelta(day=31) if self.method_period == 'quarter': m = [x for x in [3, 6, 9, 12] if x >= start_date.month][0] line_date = start_date + relativedelta(month=m, day=31) elif self.method_period == 'year': line_date = table[0]['date_stop'] i = 1 while line_date < stop_date: line_dates.append(line_date) if self.method_period == 'month' or isTaxMode: line_date = line_date + relativedelta(months=1, day=31) elif self.method_period == 'quarter': line_date = line_date + relativedelta(months=3, day=31) elif self.method_period == 'year': line_date = table[i]['date_stop'] i += 1 # last entry if not ((self.method_time == 'number' or self.method_time == 'percentage' or isTaxMode) and len(line_dates) == (isTaxMode and int((100.0/self.taxadmin_method_percentage)*12) or self.method_number)): line_dates.append(line_date) return line_dates def _compute_depreciation_table_lines(self, table, depreciation_start_date, depreciation_stop_date, line_dates, isTaxMode): digits = self.env['decimal.precision'].precision_get('Account') asset_sign = self.depreciation_base >= 0 and 1 or -1 i_max = len(table) - 1 remaining_value = self.depreciation_base depreciated_value = 0.0 for i, entry in enumerate(table): lines = [] fy_amount_check = 0.0 fy_amount = entry['fy_amount'] li_max = len(line_dates) - 1 for li, line_date in enumerate(line_dates): if round(remaining_value, digits) == 0.0: break if (line_date > min(entry['date_stop'], depreciation_stop_date) and not (i == i_max and li == li_max)): break if self.method == 'degr-linear' \ and asset_sign * (fy_amount - fy_amount_check) < 0: break if i == 0 and li == 0: amount = self._get_first_period_amount( table, entry, depreciation_start_date, line_dates) amount = round(amount, digits) else: amount = entry.get('period_amount') # last year, last entry # Handle rounding deviations. if i == i_max and li == li_max: amount = remaining_value remaining_value = 0.0 else: remaining_value -= amount fy_amount_check += amount line = { 'date': line_date, 'amount': amount, 'depreciated_value': depreciated_value, 'remaining_value': remaining_value, } lines.append(line) depreciated_value += amount # Handle rounding and extended/shortened FY deviations. # # Remark: # In account_asset_management version < 8.0.2.8.0 # the FY deviation for the first FY # was compensated in the first FY depreciation line. # The code has now been simplified with compensation # always in last FT depreciation line. if self.method_time == 'year': if round(fy_amount_check - fy_amount, digits) != 0: diff = fy_amount_check - fy_amount amount = amount - diff remaining_value += diff lines[-1].update({ 'amount': amount, 'remaining_value': remaining_value, }) depreciated_value -= diff if not lines: table.pop(i) else: entry['lines'] = lines line_dates = line_dates[li:] for i, entry in enumerate(table): if not entry['fy_amount']: entry['fy_amount'] = sum( [l['amount'] for l in entry['lines']]) def _compute_depreciation_table(self, mode): ctx = self._context.copy() isTaxMode = (mode and mode == 'taxadmin') table = [] if (self.method_time in ['year', 'number', 'percentage'] or isTaxMode) and not self.method_number: return table ctx['company_id'] = self.company_id.id fy_obj = self.env['account.fiscalyear'].with_context(ctx) init_flag = False try: fy_id = fy_obj.find(self.date_start) fy = fy_obj.browse(fy_id) if fy.state == 'done': init_flag = True fy_date_start = datetime.strptime(fy.date_start, '%Y-%m-%d') fy_date_stop = datetime.strptime(fy.date_stop, '%Y-%m-%d') except: # The following logic is used when no fiscal year # is defined for the asset start date: # - We lookup the first fiscal year defined in the system # - The 'undefined' fiscal years are assumed to be years # with a duration equal to a calendar year first_fy = fy_obj.search( [('company_id', '=', self.company_id.id)], order='date_stop ASC', limit=1) first_fy_date_start = datetime.strptime( first_fy.date_start, '%Y-%m-%d') asset_date_start = datetime.strptime(self.date_start, '%Y-%m-%d') fy_date_start = first_fy_date_start if asset_date_start > fy_date_start: asset_ref = self.code and '%s (ref: %s)' \ % (self.name, self.code) or self.name raise UserError( _("You cannot compute a depreciation table for an asset " "starting in an undefined future fiscal year." "\nPlease correct the start date for asset '%s'.") % asset_ref) while asset_date_start < fy_date_start: fy_date_start = fy_date_start - relativedelta(years=1) fy_date_stop = fy_date_start + relativedelta(years=1, days=-1) fy_id = False fy = DummyFy( date_start=fy_date_start.strftime('%Y-%m-%d'), date_stop=fy_date_stop.strftime('%Y-%m-%d'), id=False, state='done', dummy=True) init_flag = True depreciation_start_date = self._get_depreciation_start_date(fy, isTaxMode) depreciation_stop_date = self._get_depreciation_stop_date( depreciation_start_date, isTaxMode) while fy_date_start <= depreciation_stop_date: table.append({ 'fy_id': fy_id, 'date_start': fy_date_start, 'date_stop': fy_date_stop, 'init': init_flag}) fy_date_start = fy_date_stop + relativedelta(days=1) try: fy_id = fy_obj.find(fy_date_start) init_flag = False except: fy_id = False if fy_id: fy = fy_obj.browse(fy_id) if fy.state == 'done': init_flag = True fy_date_stop = datetime.strptime(fy.date_stop, '%Y-%m-%d') else: fy_date_stop = fy_date_stop + relativedelta(years=1) # Step 1: # Calculate depreciation amount per fiscal year. # This is calculation is skipped for method_time != 'year'. digits = self.env['decimal.precision'].precision_get('Account') fy_residual_amount = self.depreciation_base i_max = len(table) - 1 asset_sign = self.depreciation_base >= 0 and 1 or -1 line_dates = self._compute_line_dates( table, depreciation_start_date, depreciation_stop_date, isTaxMode) for i, entry in enumerate(table): if self.method_time == 'year': year_amount = self._compute_year_amount(fy_residual_amount) if self.method_period == 'year': period_amount = year_amount elif self.method_period == 'quarter': period_amount = year_amount / 4 elif self.method_period == 'month': period_amount = year_amount / 12 if i == i_max: if self.method in ['linear-limit', 'degr-limit']: fy_amount = fy_residual_amount - self.salvage_value else: fy_amount = fy_residual_amount else: firstyear = i == 0 and True or False fy_factor = self._get_fy_duration_factor( entry, firstyear) fy_amount = year_amount * fy_factor if asset_sign * (fy_amount - fy_residual_amount) > 0: fy_amount = fy_residual_amount period_amount = round(period_amount, digits) fy_amount = round(fy_amount, digits) else: fy_amount = False if self.method_time == 'number' or self.method_time == 'percentage' or isTaxMode: number = isTaxMode and int((100.0/self.taxadmin_method_percentage)*12) or self.method_number elif self.method_time == 'end': number = len(line_dates) period_amount = round(self.depreciation_base / number, digits) entry.update({ 'period_amount': period_amount, 'fy_amount': fy_amount, }) if self.method_time == 'year': fy_residual_amount -= fy_amount if round(fy_residual_amount, digits) == 0: break i_max = i table = table[:i_max + 1] # Step 2: # Spread depreciation amount per fiscal year # over the depreciation periods. self._compute_depreciation_table_lines( table, depreciation_start_date, depreciation_stop_date, line_dates, isTaxMode) return table def _get_depreciation_entry_name(self, seq): """ use this method to customise the name of the accounting entry """ return (self.code or str(self.id)) + '/' + str(seq) @api.multi def _compute_entries(self, period, check_triggers=False): # To DO : add ir_cron job calling this method to # generate periodical accounting entries mode = self._context.get('mode', 'depreciate') if mode == 'depreciate': ctx = dict(self._context, mode='taxadmin') (result, error_log) = self.with_context(ctx)._compute_entries(period, check_triggers) else: result = [] error_log = '' asset_line_obj = self.env['account.asset.line'] if check_triggers: recompute_obj = self.env['account.asset.recompute.trigger'] recomputes = recompute_obj.sudo().search([('state', '=', 'open')]) if check_triggers and recomputes: trigger_companies = recomputes.mapped('company_id') for asset in self: if asset.company_id.id in trigger_companies.ids: asset.compute_depreciation_board() for asset in self: depreciations = asset_line_obj.search([ ('asset_id', '=', asset.id), ('type', '=', mode), ('init_entry', '=', False), ('line_date', '<', period.date_start), ('move_check', '=', False)]) if depreciations: asset_ref = asset.code and '%s (ref: %s)' \ % (asset.name, asset.code) or asset.name raise UserError( _("Asset '%s' contains unposted lines " "prior to the selected period." "\nPlease post these entries first !") % asset_ref) depreciations = asset_line_obj.search([ ('asset_id', 'in', self.ids), ('type', '=', mode), ('init_entry', '=', False), ('line_date', '<=', period.date_stop), ('line_date', '>=', period.date_start), ('move_check', '=', False)]) for depreciation in depreciations: try: with self._cr.savepoint(): result += depreciation.create_move() except: e = exc_info()[0] tb = ''.join(format_exception(*exc_info())) asset_ref = depreciation.asset_id.code and '%s (ref: %s)' \ % (asset.name, asset.code) or asset.name error_log += _( "\nError while processing asset '%s': %s" ) % (asset_ref, str(e)) error_msg = _( "Error while processing asset '%s': \n\n%s" ) % (asset_ref, tb) _logger.error("%s, %s", self._name, error_msg) if check_triggers and recomputes: companies = recomputes.mapped('company_id') triggers = recomputes.filtered( lambda r: r.company_id.id in companies.ids) if triggers: recompute_vals = { 'date_completed': fields.Datetime.now(), 'state': 'done', } triggers.sudo().write(recompute_vals) return (result, error_log) ```
[ { "content": "Reconstruct the code exactly:\n```python\n#\n# Project Kimchi\n#\n# Copyright IBM, Corp. 2013\n#\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Lesser General Public\n# License as published by the Free Software Foundation; either\n# version...
[ { "content": "Reconstruct the code exactly:\n<|memory_start|>```python\n#\n# Project Kimchi\n#\n# Copyright IBM, Corp. 2013\n#\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Lesser General Public\n# License as published by the Free Software Foundation; e...
```python # # Project Kimchi # # Copyright IBM, Corp. 2013 # # 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 Street, Fifth Floor, Boston, MA 02110-1301 USA from kimchi.exception import InvalidOperation, NotFoundError from kimchi.basemodel import BaseModel class CirclesModel(object): def __init__(self): self._circles = {} def create(self, params): name = params['name'] if name in self._circles: raise InvalidOperation("SPCIRCLE0001E", {'name': name}) self._circles[name] = Circle(params['radius']) return name def get_list(self): return sorted(self._circles) class CircleModel(object): def __init__(self, parent_model): # Circel and Circles models are friends, it's OK to share _circles. self._circles = parent_model._circles def lookup(self, name): try: circle = self._circles[name] except KeyError: raise NotFoundError("SPCIRC0002E", {'name': name}) return {'radius': circle.radius} def update(self, name, params): if name not in self._circles: raise NotFoundError("SPCIRC0002E", {'name': name}) self._circles[name].radius = params['radius'] return name def delete(self, name): try: del self._circles[name] except KeyError: pass class RectanglesModel(object): def __init__(self): self._rectangles = {} def create(self, params): name = params['name'] if name in self._rectangles: raise InvalidOperation("SPRET0001E", {'name': name}) self._rectangles[name] = Rectangle(params['length'], params['width']) return name def get_list(self): return sorted(self._rectangles) class RectangleModel(object): def __init__(self, parent_model): self._rectangles = parent_model._rectangles def lookup(self, name): try: rectangle = self._rectangles[name] except KeyError: raise NotFoundError("SPRET0002E", {'name': name}) return {'length': rectangle.length, 'width': rectangle.width} def update(self, name, params): if name not in self._rectangles: raise NotFoundError("SPRET0002E", {'name': name}) try: self._rectangles[name].length = params['length'] except KeyError: pass try: self._rectangles[name].width = params['width'] except KeyError: pass return name def delete(self, name): try: del self._rectangles[name] except KeyError: pass class Model(BaseModel): def __init__(self): circles = CirclesModel() circle = CircleModel(circles) rectangles = RectanglesModel() rectangle = RectangleModel(rectangles) return super(Model, self).__init__( [circle, circles, rectangle, rectangles]) class Rectangle(object): def __init__(self, length, width): self.length = length self.width = width class Circle(object): def __init__(self, radius): self.radius = radius ```
[ { "content": "Here is a code file:\n```python\n#!/usr/bin/python\n#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# Copyright (C) 2011 Yann GUIBET <yannguibet@gmail.com>\n# See LICENSE for details.\n\nfrom hashlib import sha512\nfrom .openssl import OpenSSL\nfrom .cipher import Cipher\nfrom .hash import hma...
[ { "content": "Here is a code file:\n<|memory_start|>```python\n#!/usr/bin/python\n#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# Copyright (C) 2011 Yann GUIBET <yannguibet@gmail.com>\n# See LICENSE for details.\n\nfrom hashlib import sha512\nfrom .openssl import OpenSSL\nfrom .cipher import Cipher\nfrom ...
```python #!/usr/bin/python #!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2011 Yann GUIBET <yannguibet@gmail.com> # See LICENSE for details. from hashlib import sha512 from .openssl import OpenSSL from .cipher import Cipher from .hash import hmac_sha256, equals from struct import pack, unpack class ECC: """ Asymmetric encryption with Elliptic Curve Cryptography (ECC) ECDH, ECDSA and ECIES import pyelliptic alice = pyelliptic.ECC() # default curve: sect283r1 bob = pyelliptic.ECC(curve='sect571r1') ciphertext = alice.encrypt("Hello Bob", bob.get_pubkey()) print bob.decrypt(ciphertext) signature = bob.sign("Hello Alice") # alice's job : print pyelliptic.ECC( pubkey=bob.get_pubkey()).verify(signature, "Hello Alice") # ERROR !!! try: key = alice.get_ecdh_key(bob.get_pubkey()) except: print("For ECDH key agreement,\ the keys must be defined on the same curve !") alice = pyelliptic.ECC(curve='sect571r1') print alice.get_ecdh_key(bob.get_pubkey()).encode('hex') print bob.get_ecdh_key(alice.get_pubkey()).encode('hex') """ def __init__(self, pubkey=None, privkey=None, pubkey_x=None, pubkey_y=None, raw_privkey=None, curve='sect283r1'): """ For a normal and High level use, specifie pubkey, privkey (if you need) and the curve """ if type(curve) == str: self.curve = OpenSSL.get_curve(curve) else: self.curve = curve if pubkey_x is not None and pubkey_y is not None: self._set_keys(pubkey_x, pubkey_y, raw_privkey) elif pubkey is not None: curve, pubkey_x, pubkey_y, i = ECC._decode_pubkey(pubkey) if privkey is not None: curve2, raw_privkey, i = ECC._decode_privkey(privkey) if curve != curve2: raise Exception("Bad ECC keys ...") self.curve = curve self._set_keys(pubkey_x, pubkey_y, raw_privkey) else: self.privkey, self.pubkey_x, self.pubkey_y = self._generate() def _set_keys(self, pubkey_x, pubkey_y, privkey): if self.raw_check_key(privkey, pubkey_x, pubkey_y) < 0: self.pubkey_x = None self.pubkey_y = None self.privkey = None raise Exception("Bad ECC keys ...") else: self.pubkey_x = pubkey_x self.pubkey_y = pubkey_y self.privkey = privkey @staticmethod def get_curves(): """ static method, returns the list of all the curves available """ return OpenSSL.curves.keys() def get_curve(self): return OpenSSL.get_curve_by_id(self.curve) def get_curve_id(self): return self.curve def get_pubkey(self): """ High level function which returns : curve(2) + len_of_pubkeyX(2) + pubkeyX + len_of_pubkeyY + pubkeyY """ return b''.join((pack('!H', self.curve), pack('!H', len(self.pubkey_x)), self.pubkey_x, pack('!H', len(self.pubkey_y)), self.pubkey_y )) def get_privkey(self): """ High level function which returns curve(2) + len_of_privkey(2) + privkey """ return b''.join((pack('!H', self.curve), pack('!H', len(self.privkey)), self.privkey )) @staticmethod def _decode_pubkey(pubkey): i = 0 curve = unpack('!H', pubkey[i:i + 2])[0] i += 2 tmplen = unpack('!H', pubkey[i:i + 2])[0] i += 2 pubkey_x = pubkey[i:i + tmplen] i += tmplen tmplen = unpack('!H', pubkey[i:i + 2])[0] i += 2 pubkey_y = pubkey[i:i + tmplen] i += tmplen return curve, pubkey_x, pubkey_y, i @staticmethod def _decode_privkey(privkey): i = 0 curve = unpack('!H', privkey[i:i + 2])[0] i += 2 tmplen = unpack('!H', privkey[i:i + 2])[0] i += 2 privkey = privkey[i:i + tmplen] i += tmplen return curve, privkey, i def _generate(self): try: pub_key_x = OpenSSL.BN_new() pub_key_y = OpenSSL.BN_new() key = OpenSSL.EC_KEY_new_by_curve_name(self.curve) if key == 0: raise Exception("[OpenSSL] EC_KEY_new_by_curve_name FAIL ...") if (OpenSSL.EC_KEY_generate_key(key)) == 0: raise Exception("[OpenSSL] EC_KEY_generate_key FAIL ...") if (OpenSSL.EC_KEY_check_key(key)) == 0: raise Exception("[OpenSSL] EC_KEY_check_key FAIL ...") priv_key = OpenSSL.EC_KEY_get0_private_key(key) group = OpenSSL.EC_KEY_get0_group(key) pub_key = OpenSSL.EC_KEY_get0_public_key(key) if (OpenSSL.EC_POINT_get_affine_coordinates_GFp(group, pub_key, pub_key_x, pub_key_y, 0 )) == 0: raise Exception( "[OpenSSL] EC_POINT_get_affine_coordinates_GFp FAIL ...") privkey = OpenSSL.malloc(0, OpenSSL.BN_num_bytes(priv_key)) pubkeyx = OpenSSL.malloc(0, OpenSSL.BN_num_bytes(pub_key_x)) pubkeyy = OpenSSL.malloc(0, OpenSSL.BN_num_bytes(pub_key_y)) OpenSSL.BN_bn2bin(priv_key, privkey) privkey = privkey.raw OpenSSL.BN_bn2bin(pub_key_x, pubkeyx) pubkeyx = pubkeyx.raw OpenSSL.BN_bn2bin(pub_key_y, pubkeyy) pubkeyy = pubkeyy.raw self.raw_check_key(privkey, pubkeyx, pubkeyy) return privkey, pubkeyx, pubkeyy finally: OpenSSL.EC_KEY_free(key) OpenSSL.BN_free(pub_key_x) OpenSSL.BN_free(pub_key_y) def get_ecdh_key(self, pubkey): """ High level function. Compute public key with the local private key and returns a 512bits shared key """ curve, pubkey_x, pubkey_y, i = ECC._decode_pubkey(pubkey) if curve != self.curve: raise Exception("ECC keys must be from the same curve !") return sha512(self.raw_get_ecdh_key(pubkey_x, pubkey_y)).digest() def raw_get_ecdh_key(self, pubkey_x, pubkey_y): try: ecdh_keybuffer = OpenSSL.malloc(0, 32) other_key = OpenSSL.EC_KEY_new_by_curve_name(self.curve) if other_key == 0: raise Exception("[OpenSSL] EC_KEY_new_by_curve_name FAIL ...") other_pub_key_x = OpenSSL.BN_bin2bn(pubkey_x, len(pubkey_x), 0) other_pub_key_y = OpenSSL.BN_bin2bn(pubkey_y, len(pubkey_y), 0) other_group = OpenSSL.EC_KEY_get0_group(other_key) other_pub_key = OpenSSL.EC_POINT_new(other_group) if (OpenSSL.EC_POINT_set_affine_coordinates_GFp(other_group, other_pub_key, other_pub_key_x, other_pub_key_y, 0)) == 0: raise Exception( "[OpenSSL] EC_POINT_set_affine_coordinates_GFp FAIL ...") if (OpenSSL.EC_KEY_set_public_key(other_key, other_pub_key)) == 0: raise Exception("[OpenSSL] EC_KEY_set_public_key FAIL ...") if (OpenSSL.EC_KEY_check_key(other_key)) == 0: raise Exception("[OpenSSL] EC_KEY_check_key FAIL ...") own_key = OpenSSL.EC_KEY_new_by_curve_name(self.curve) if own_key == 0: raise Exception("[OpenSSL] EC_KEY_new_by_curve_name FAIL ...") own_priv_key = OpenSSL.BN_bin2bn( self.privkey, len(self.privkey), 0) if (OpenSSL.EC_KEY_set_private_key(own_key, own_priv_key)) == 0: raise Exception("[OpenSSL] EC_KEY_set_private_key FAIL ...") OpenSSL.ECDH_set_method(own_key, OpenSSL.ECDH_OpenSSL()) ecdh_keylen = OpenSSL.ECDH_compute_key( ecdh_keybuffer, 32, other_pub_key, own_key, 0) if ecdh_keylen != 32: raise Exception("[OpenSSL] ECDH keylen FAIL ...") return ecdh_keybuffer.raw finally: OpenSSL.EC_KEY_free(other_key) OpenSSL.BN_free(other_pub_key_x) OpenSSL.BN_free(other_pub_key_y) OpenSSL.EC_POINT_free(other_pub_key) OpenSSL.EC_KEY_free(own_key) OpenSSL.BN_free(own_priv_key) def check_key(self, privkey, pubkey): """ Check the public key and the private key. The private key is optional (replace by None) """ curve, pubkey_x, pubkey_y, i = ECC._decode_pubkey(pubkey) if privkey is None: raw_privkey = None curve2 = curve else: curve2, raw_privkey, i = ECC._decode_privkey(privkey) if curve != curve2: raise Exception("Bad public and private key") return self.raw_check_key(raw_privkey, pubkey_x, pubkey_y, curve) def raw_check_key(self, privkey, pubkey_x, pubkey_y, curve=None): if curve is None: curve = self.curve elif type(curve) == str: curve = OpenSSL.get_curve(curve) else: curve = curve try: key = OpenSSL.EC_KEY_new_by_curve_name(curve) if key == 0: raise Exception("[OpenSSL] EC_KEY_new_by_curve_name FAIL ...") if privkey is not None: priv_key = OpenSSL.BN_bin2bn(privkey, len(privkey), 0) pub_key_x = OpenSSL.BN_bin2bn(pubkey_x, len(pubkey_x), 0) pub_key_y = OpenSSL.BN_bin2bn(pubkey_y, len(pubkey_y), 0) if privkey is not None: if (OpenSSL.EC_KEY_set_private_key(key, priv_key)) == 0: raise Exception( "[OpenSSL] EC_KEY_set_private_key FAIL ...") group = OpenSSL.EC_KEY_get0_group(key) pub_key = OpenSSL.EC_POINT_new(group) if (OpenSSL.EC_POINT_set_affine_coordinates_GFp(group, pub_key, pub_key_x, pub_key_y, 0)) == 0: raise Exception( "[OpenSSL] EC_POINT_set_affine_coordinates_GFp FAIL ...") if (OpenSSL.EC_KEY_set_public_key(key, pub_key)) == 0: raise Exception("[OpenSSL] EC_KEY_set_public_key FAIL ...") if (OpenSSL.EC_KEY_check_key(key)) == 0: raise Exception("[OpenSSL] EC_KEY_check_key FAIL ...") return 0 finally: OpenSSL.EC_KEY_free(key) OpenSSL.BN_free(pub_key_x) OpenSSL.BN_free(pub_key_y) OpenSSL.EC_POINT_free(pub_key) if privkey is not None: OpenSSL.BN_free(priv_key) def sign(self, inputb, digest_alg=OpenSSL.EVP_ecdsa): """ Sign the input with ECDSA method and returns the signature """ try: size = len(inputb) buff = OpenSSL.malloc(inputb, size) digest = OpenSSL.malloc(0, 64) md_ctx = OpenSSL.EVP_MD_CTX_create() dgst_len = OpenSSL.pointer(OpenSSL.c_int(0)) siglen = OpenSSL.pointer(OpenSSL.c_int(0)) sig = OpenSSL.malloc(0, 151) key = OpenSSL.EC_KEY_new_by_curve_name(self.curve) if key == 0: raise Exception("[OpenSSL] EC_KEY_new_by_curve_name FAIL ...") priv_key = OpenSSL.BN_bin2bn(self.privkey, len(self.privkey), 0) pub_key_x = OpenSSL.BN_bin2bn(self.pubkey_x, len(self.pubkey_x), 0) pub_key_y = OpenSSL.BN_bin2bn(self.pubkey_y, len(self.pubkey_y), 0) if (OpenSSL.EC_KEY_set_private_key(key, priv_key)) == 0: raise Exception("[OpenSSL] EC_KEY_set_private_key FAIL ...") group = OpenSSL.EC_KEY_get0_group(key) pub_key = OpenSSL.EC_POINT_new(group) if (OpenSSL.EC_POINT_set_affine_coordinates_GFp(group, pub_key, pub_key_x, pub_key_y, 0)) == 0: raise Exception( "[OpenSSL] EC_POINT_set_affine_coordinates_GFp FAIL ...") if (OpenSSL.EC_KEY_set_public_key(key, pub_key)) == 0: raise Exception("[OpenSSL] EC_KEY_set_public_key FAIL ...") if (OpenSSL.EC_KEY_check_key(key)) == 0: raise Exception("[OpenSSL] EC_KEY_check_key FAIL ...") OpenSSL.EVP_MD_CTX_init(md_ctx) OpenSSL.EVP_DigestInit_ex(md_ctx, digest_alg(), None) if (OpenSSL.EVP_DigestUpdate(md_ctx, buff, size)) == 0: raise Exception("[OpenSSL] EVP_DigestUpdate FAIL ...") OpenSSL.EVP_DigestFinal_ex(md_ctx, digest, dgst_len) OpenSSL.ECDSA_sign(0, digest, dgst_len.contents, sig, siglen, key) if (OpenSSL.ECDSA_verify(0, digest, dgst_len.contents, sig, siglen.contents, key)) != 1: raise Exception("[OpenSSL] ECDSA_verify FAIL ...") return sig.raw[:siglen.contents.value] finally: OpenSSL.EC_KEY_free(key) OpenSSL.BN_free(pub_key_x) OpenSSL.BN_free(pub_key_y) OpenSSL.BN_free(priv_key) OpenSSL.EC_POINT_free(pub_key) OpenSSL.EVP_MD_CTX_destroy(md_ctx) def verify(self, sig, inputb, digest_alg=OpenSSL.EVP_ecdsa): """ Verify the signature with the input and the local public key. Returns a boolean """ try: bsig = OpenSSL.malloc(sig, len(sig)) binputb = OpenSSL.malloc(inputb, len(inputb)) digest = OpenSSL.malloc(0, 64) dgst_len = OpenSSL.pointer(OpenSSL.c_int(0)) md_ctx = OpenSSL.EVP_MD_CTX_create() key = OpenSSL.EC_KEY_new_by_curve_name(self.curve) if key == 0: raise Exception("[OpenSSL] EC_KEY_new_by_curve_name FAIL ...") pub_key_x = OpenSSL.BN_bin2bn(self.pubkey_x, len(self.pubkey_x), 0) pub_key_y = OpenSSL.BN_bin2bn(self.pubkey_y, len(self.pubkey_y), 0) group = OpenSSL.EC_KEY_get0_group(key) pub_key = OpenSSL.EC_POINT_new(group) if (OpenSSL.EC_POINT_set_affine_coordinates_GFp(group, pub_key, pub_key_x, pub_key_y, 0)) == 0: raise Exception( "[OpenSSL] EC_POINT_set_affine_coordinates_GFp FAIL ...") if (OpenSSL.EC_KEY_set_public_key(key, pub_key)) == 0: raise Exception("[OpenSSL] EC_KEY_set_public_key FAIL ...") if (OpenSSL.EC_KEY_check_key(key)) == 0: raise Exception("[OpenSSL] EC_KEY_check_key FAIL ...") OpenSSL.EVP_MD_CTX_init(md_ctx) OpenSSL.EVP_DigestInit_ex(md_ctx, digest_alg(), None) if (OpenSSL.EVP_DigestUpdate(md_ctx, binputb, len(inputb))) == 0: raise Exception("[OpenSSL] EVP_DigestUpdate FAIL ...") OpenSSL.EVP_DigestFinal_ex(md_ctx, digest, dgst_len) ret = OpenSSL.ECDSA_verify( 0, digest, dgst_len.contents, bsig, len(sig), key) if ret == -1: return False # Fail to Check else: if ret == 0: return False # Bad signature ! else: return True # Good return False finally: OpenSSL.EC_KEY_free(key) OpenSSL.BN_free(pub_key_x) OpenSSL.BN_free(pub_key_y) OpenSSL.EC_POINT_free(pub_key) OpenSSL.EVP_MD_CTX_destroy(md_ctx) @staticmethod def encrypt(data, pubkey, ephemcurve=None, ciphername='aes-256-cbc'): """ Encrypt data with ECIES method using the public key of the recipient. """ curve, pubkey_x, pubkey_y, i = ECC._decode_pubkey(pubkey) return ECC.raw_encrypt(data, pubkey_x, pubkey_y, curve=curve, ephemcurve=ephemcurve, ciphername=ciphername) @staticmethod def raw_encrypt(data, pubkey_x, pubkey_y, curve='sect283r1', ephemcurve=None, ciphername='aes-256-cbc'): if ephemcurve is None: ephemcurve = curve ephem = ECC(curve=ephemcurve) key = sha512(ephem.raw_get_ecdh_key(pubkey_x, pubkey_y)).digest() key_e, key_m = key[:32], key[32:] pubkey = ephem.get_pubkey() iv = OpenSSL.rand(OpenSSL.get_cipher(ciphername).get_blocksize()) ctx = Cipher(key_e, iv, 1, ciphername) ciphertext = iv + pubkey + ctx.ciphering(data) mac = hmac_sha256(key_m, ciphertext) return ciphertext + mac def decrypt(self, data, ciphername='aes-256-cbc'): """ Decrypt data with ECIES method using the local private key """ blocksize = OpenSSL.get_cipher(ciphername).get_blocksize() iv = data[:blocksize] i = blocksize curve, pubkey_x, pubkey_y, i2 = ECC._decode_pubkey(data[i:]) i += i2 ciphertext = data[i:len(data)-32] i += len(ciphertext) mac = data[i:] key = sha512(self.raw_get_ecdh_key(pubkey_x, pubkey_y)).digest() key_e, key_m = key[:32], key[32:] if not equals(hmac_sha256(key_m, data[:len(data) - 32]), mac): raise RuntimeError("Fail to verify data") ctx = Cipher(key_e, iv, 0, ciphername) return ctx.ciphering(ciphertext) ```
[ { "content": "Here is the snippet:\n```python\nfrom django.core.urlresolvers import reverse\n\nfrom rest_framework import status\nfrom rest_framework.test import APITestCase\n\n\nclass ComponentAuthenticationTest(APITestCase):\n fixtures = ['users.json', 'component_data.json']\n\n def test_noauthed_reject...
[ { "content": "Here is the snippet:\n<|memory_start|>```python\nfrom django.core.urlresolvers import reverse\n\nfrom rest_framework import status\nfrom rest_framework.test import APITestCase\n\n\nclass ComponentAuthenticationTest(APITestCase):\n fixtures = ['users.json', 'component_data.json']\n\n def test...
```python from django.core.urlresolvers import reverse from rest_framework import status from rest_framework.test import APITestCase class ComponentAuthenticationTest(APITestCase): fixtures = ['users.json', 'component_data.json'] def test_noauthed_rejects(self): url = reverse('component-detail', kwargs={ 'slug': 'component-with-svg-data' }) res = self.client.get(url) self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED) def test_authed_as_user_accepts(self): url = reverse('component-detail', kwargs={ 'slug': 'component-with-svg-data' }) self.client.login(username='test_user', password='password1') res = self.client.get(url) self.assertEqual(res.status_code, status.HTTP_200_OK) def test_authed_as_staff_accepts(self): url = reverse('component-detail', kwargs={ 'slug': 'component-with-svg-data' }) self.client.login(username='test_staff', password='password1') res = self.client.get(url) self.assertEqual(res.status_code, status.HTTP_200_OK) def test_authed_as_admin_accepts(self): url = reverse('component-detail', kwargs={ 'slug': 'component-with-svg-data' }) self.client.login(username='test_admin', password='password1') res = self.client.get(url) self.assertEqual(res.status_code, status.HTTP_200_OK) ```
[ { "content": "Output the full code verbatim (no extra comments):\n```python\n# -*- coding: utf-8 -*-\n##############################################################################\n#\n# Copyright (C) 2016 Fernando Hidalgo (http://www.hidalgofernando.com.ar)\n# All Rights Reserved.\n#\n# This program...
[ { "content": "Output the full code verbatim (no extra comments):\n<|memory_start|>```python\n# -*- coding: utf-8 -*-\n##############################################################################\n#\n# Copyright (C) 2016 Fernando Hidalgo (http://www.hidalgofernando.com.ar)\n# All Rights Reserved.\n#\n#...
```python # -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2016 Fernando Hidalgo (http://www.hidalgofernando.com.ar) # 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/>. # ############################################################################## { 'name': 'ERSeP Regulations', 'version': '9.0.0.0.1', 'category': 'Tools', 'sequence': 1, 'summary': '', 'description': """ ERSeP Regulations ================= This module is a regionalization of Córdoba province for odoo-coop Based on the experience of the "Cooperativa Anisacate" cooperative. Uses the Argentine tax & legal regulations and particularly those of the province of "Córdoba" through the regulator ERSeP. """, 'author': 'Fernando Hidalgo', 'website': 'www.hidalgofernando.com.ar', 'license': 'AGPL-3', 'images': [ ], 'depends': [ 'electric_utility', 'base', 'l10n_ar_chart', ], 'external_dependencies': { # 'python': ['dbfread', 'hashlib'], }, 'data': [ 'data/account_chart.xml', 'data/account_tax.xml', 'data/service_category.xml', ], 'demo': [ ], 'test': [ ], } ```
[ { "content": "```python\n# encoding: utf-8\nimport datetime\nfrom south.db import db\nfrom south.v2 import SchemaMigration\nfrom django.db import models\n\nclass Migration(SchemaMigration):\n\n def forwards(self, orm):\n \n # Adding field 'Project.project_type'\n db.add_column('project_p...
[ { "content": "<|memory_start|>```python\n# encoding: utf-8\nimport datetime\nfrom south.db import db\nfrom south.v2 import SchemaMigration\nfrom django.db import models\n\nclass Migration(SchemaMigration):\n\n def forwards(self, orm):\n \n # Adding field 'Project.project_type'\n db.add_c...
```python # 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): # Adding field 'Project.project_type' db.add_column('project_project', 'project_type', self.gf('django.db.models.fields.CharField')(default='buildout', max_length=9), keep_default=False) # Changing field 'Project.description' db.alter_column('project_project', 'description', self.gf('django.db.models.fields.TextField')(blank=True)) def backwards(self, orm): # Deleting field 'Project.project_type' db.delete_column('project_project', 'project_type') # Changing field 'Project.description' db.alter_column('project_project', 'description', self.gf('django.db.models.fields.TextField')()) models = { 'project.project': { 'Meta': {'object_name': 'Project'}, 'base_directory': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '512'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'favourite': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'git_repo': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '512', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '32'}), 'project_type': ('django.db.models.fields.CharField', [], {'max_length': '9'}), 'test_status': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) } } complete_apps = ['project'] ```
[ { "content": "Write out the code verbatim, preserving indentation and whitespace:\n```python\n#!/usr/bin/env python2.7\n\"\"\"\\\nusage: pgctl-fuser [-d] file [file ...]\n\nShows the pids (of the current user) that have this file opened.\nThis is useful for finding which processes hold a file lock (flock).\nThi...
[ { "content": "Write out the code verbatim, preserving indentation and whitespace:\n<|memory_start|>```python\n#!/usr/bin/env python2.7\n\"\"\"\\\nusage: pgctl-fuser [-d] file [file ...]\n\nShows the pids (of the current user) that have this file opened.\nThis is useful for finding which processes hold a file lo...
```python #!/usr/bin/env python2.7 """\ usage: pgctl-fuser [-d] file [file ...] Shows the pids (of the current user) that have this file opened. This is useful for finding which processes hold a file lock (flock). This has the same behavior as `lsof -t file`, but is *much* faster. """ from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals from .debug import trace def stat(path): from os import stat try: return stat(path) except EnvironmentError as error: trace('fuser suppressed: %s', error) return None def listdir(path): from os import listdir try: return listdir(path) except EnvironmentError as error: trace('fuser suppressed: %s', error) return () def fuser(path, allow_deleted=False): """Return the list of pids that have 'path' open, for the current user""" search = stat(path) if search is None and not allow_deleted: return from glob import glob for fddir in glob('/proc/*/fd/'): try: pid = int(fddir.split('/', 3)[2]) except ValueError: continue fds = listdir(fddir) for fd in fds: from os.path import join fd = join(fddir, fd) found = stat(fd) if found is None: # fd disappeared since we listed continue if found == search: yield pid break if allow_deleted and found.st_nlink == 0: from os import readlink if readlink(fd) == path + ' (deleted)': yield pid break def main(args=None): from argparse import ArgumentParser from sys import argv args = args or argv parser = ArgumentParser(description=__doc__) parser.add_argument('-d', '--allow-deleted', action='store_true', help='allow deleted files') parser.add_argument('file', nargs='+') args = parser.parse_args(args[1:]) for f in args.file: for pid in fuser(f, allow_deleted=args.allow_deleted): print(pid) if __name__ == '__main__': exit(main()) ```
[ { "content": "```python\n#!/usr/bin/env python\n\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2 of the License, or\n# (at your option) any later version.\n#\n# This ...
[ { "content": "<|memory_start|>```python\n#!/usr/bin/env python\n\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2 of the License, or\n# (at your option) any later vers...
```python #!/usr/bin/env python # 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 LICENSE for more details. # # Copyright: 2017 IBM # Author: Pooja B Surya <pooja@linux.vnet.ibm.com> import os from avocado import Test from avocado import main from avocado.utils import build from avocado.utils import archive from avocado.utils.software_manager import SoftwareManager from avocado.utils import distro class Openblas(Test): """ OpenBLAS is an optimized BLAS library based on GotoBLAS2 1.13 BSD version. This test runs openblas tests """ def setUp(self): smm = SoftwareManager() detected_distro = distro.detect() packages = ['make', 'gcc'] if detected_distro.name == "Ubuntu": packages.append("gfortran") elif detected_distro.name == "SuSE": packages.append(["gcc-fortran", "libgfortran4"]) else: packages.append("gcc-gfortran") for package in packages: if not smm.check_installed(package) and not smm.install(package): self.cancel(' %s is needed for the test to be run' % package) url = "https://github.com/xianyi/OpenBLAS/archive/develop.zip" tarball = self.fetch_asset("OpenBLAS-develop.zip", locations=[url], expire='7d') archive.extract(tarball, self.srcdir) openblas_dir = os.path.join(self.srcdir, "OpenBLAS-develop") openblas_bin_dir = os.path.join(openblas_dir, 'bin') os.mkdir(openblas_bin_dir) build.make(openblas_dir, extra_args='FC=gfortran') build.make(openblas_dir, extra_args='PREFIX=%s install' % openblas_bin_dir) self.test_dir = os.path.join(openblas_dir, "test") def test(self): result = build. run_make(self.test_dir) for line in str(result).splitlines(): if '[FAIL]' in line: self.fail("test failed, Please check debug log for failed" "test cases") if __name__ == "__main__": main() ```
[ { "content": "Replicate the source code:\n```python\n# (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>\n#\n# This file is part of Ansible\n#\n# Ansible is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundat...
[ { "content": "Replicate the source code:\n<|memory_start|>```python\n# (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>\n#\n# This file is part of Ansible\n#\n# Ansible is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free ...
```python # (c) 2012, Michael DeHaan <michael.dehaan@gmail.com> # # 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/>. import os import sys import stat import time import shlex import errno import fnmatch import glob import platform import re import signal import socket import struct import datetime import getpass import pwd try: # python2 import ConfigParser as configparser except ImportError: # python3 import configparser from ansible.module_utils.basic import get_all_subclasses # py2 vs py3; replace with six via ziploader try: # python2 from StringIO import StringIO except ImportError: # python3 from io import StringIO try: # python2 from string import maketrans except ImportError: # python3 maketrans = str.maketrans # TODO: is this really identical? try: dict.iteritems except AttributeError: # Python 3 def iteritems(d): return d.items() else: # Python 2 def iteritems(d): return d.iteritems() try: # Python 2 long except NameError: # Python 3 long = int try: import selinux HAVE_SELINUX=True except ImportError: HAVE_SELINUX=False try: # Check if we have SSLContext support from ssl import create_default_context, SSLContext del create_default_context del SSLContext HAS_SSLCONTEXT = True except ImportError: HAS_SSLCONTEXT = False try: import json # Detect python-json which is incompatible and fallback to simplejson in # that case try: json.loads json.dumps except AttributeError: raise ImportError except ImportError: import simplejson as json # The distutils module is not shipped with SUNWPython on Solaris. # It's in the SUNWPython-devel package which also contains development files # that don't belong on production boxes. Since our Solaris code doesn't # depend on LooseVersion, do not import it on Solaris. if platform.system() != 'SunOS': from distutils.version import LooseVersion # -------------------------------------------------------------- # timeout function to make sure some fact gathering # steps do not exceed a time limit class TimeoutError(Exception): pass def timeout(seconds=10, error_message="Timer expired"): def decorator(func): def _handle_timeout(signum, frame): raise TimeoutError(error_message) def wrapper(*args, **kwargs): signal.signal(signal.SIGALRM, _handle_timeout) signal.alarm(seconds) try: result = func(*args, **kwargs) finally: signal.alarm(0) return result return wrapper return decorator # -------------------------------------------------------------- class Facts(object): """ This class should only attempt to populate those facts that are mostly generic to all systems. This includes platform facts, service facts (e.g. ssh keys or selinux), and distribution facts. Anything that requires extensive code or may have more than one possible implementation to establish facts for a given topic should subclass Facts. """ # i86pc is a Solaris and derivatives-ism _I386RE = re.compile(r'i([3456]86|86pc)') # For the most part, we assume that platform.dist() will tell the truth. # This is the fallback to handle unknowns or exceptions SELINUX_MODE_DICT = { 1: 'enforcing', 0: 'permissive', -1: 'disabled' } # A list of dicts. If there is a platform with more than one # package manager, put the preferred one last. If there is an # ansible module, use that as the value for the 'name' key. PKG_MGRS = [ { 'path' : '/usr/bin/yum', 'name' : 'yum' }, { 'path' : '/usr/bin/dnf', 'name' : 'dnf' }, { 'path' : '/usr/bin/apt-get', 'name' : 'apt' }, { 'path' : '/usr/bin/zypper', 'name' : 'zypper' }, { 'path' : '/usr/sbin/urpmi', 'name' : 'urpmi' }, { 'path' : '/usr/bin/pacman', 'name' : 'pacman' }, { 'path' : '/bin/opkg', 'name' : 'opkg' }, { 'path' : '/usr/pkg/bin/pkgin', 'name' : 'pkgin' }, { 'path' : '/opt/local/bin/pkgin', 'name' : 'pkgin' }, { 'path' : '/opt/local/bin/port', 'name' : 'macports' }, { 'path' : '/usr/local/bin/brew', 'name' : 'homebrew' }, { 'path' : '/sbin/apk', 'name' : 'apk' }, { 'path' : '/usr/sbin/pkg', 'name' : 'pkgng' }, { 'path' : '/usr/sbin/swlist', 'name' : 'SD-UX' }, { 'path' : '/usr/bin/emerge', 'name' : 'portage' }, { 'path' : '/usr/sbin/pkgadd', 'name' : 'svr4pkg' }, { 'path' : '/usr/bin/pkg', 'name' : 'pkg' }, { 'path' : '/usr/bin/xbps-install','name' : 'xbps' }, { 'path' : '/usr/local/sbin/pkg', 'name' : 'pkgng' }, ] def __init__(self, module, load_on_init=True, cached_facts=None): self.module = module if not cached_facts: self.facts = {} else: self.facts = cached_facts ### TODO: Eventually, these should all get moved to populate(). But # some of the values are currently being used by other subclasses (for # instance, os_family and distribution). Have to sort out what to do # about those first. if load_on_init: self.get_platform_facts() self.facts.update(Distribution(module).populate()) self.get_cmdline() self.get_public_ssh_host_keys() self.get_selinux_facts() self.get_caps_facts() self.get_fips_facts() self.get_pkg_mgr_facts() self.get_service_mgr_facts() self.get_lsb_facts() self.get_date_time_facts() self.get_user_facts() self.get_local_facts() self.get_env_facts() self.get_dns_facts() self.get_python_facts() def populate(self): return self.facts # Platform # platform.system() can be Linux, Darwin, Java, or Windows def get_platform_facts(self): self.facts['system'] = platform.system() self.facts['kernel'] = platform.release() self.facts['machine'] = platform.machine() self.facts['python_version'] = platform.python_version() self.facts['fqdn'] = socket.getfqdn() self.facts['hostname'] = platform.node().split('.')[0] self.facts['nodename'] = platform.node() self.facts['domain'] = '.'.join(self.facts['fqdn'].split('.')[1:]) arch_bits = platform.architecture()[0] self.facts['userspace_bits'] = arch_bits.replace('bit', '') if self.facts['machine'] == 'x86_64': self.facts['architecture'] = self.facts['machine'] if self.facts['userspace_bits'] == '64': self.facts['userspace_architecture'] = 'x86_64' elif self.facts['userspace_bits'] == '32': self.facts['userspace_architecture'] = 'i386' elif Facts._I386RE.search(self.facts['machine']): self.facts['architecture'] = 'i386' if self.facts['userspace_bits'] == '64': self.facts['userspace_architecture'] = 'x86_64' elif self.facts['userspace_bits'] == '32': self.facts['userspace_architecture'] = 'i386' else: self.facts['architecture'] = self.facts['machine'] if self.facts['system'] == 'AIX': # Attempt to use getconf to figure out architecture # fall back to bootinfo if needed getconf_bin = self.module.get_bin_path('getconf') if getconf_bin: rc, out, err = self.module.run_command([getconf_bin, 'MACHINE_ARCHITECTURE']) data = out.split('\n') self.facts['architecture'] = data[0] else: bootinfo_bin = self.module.get_bin_path('bootinfo') rc, out, err = self.module.run_command([bootinfo_bin, '-p']) data = out.split('\n') self.facts['architecture'] = data[0] elif self.facts['system'] == 'OpenBSD': self.facts['architecture'] = platform.uname()[5] machine_id = get_file_content("/var/lib/dbus/machine-id") or get_file_content("/etc/machine-id") if machine_id: machine_id = machine_id.split('\n')[0] self.facts["machine_id"] = machine_id def get_local_facts(self): fact_path = self.module.params.get('fact_path', None) if not fact_path or not os.path.exists(fact_path): return local = {} for fn in sorted(glob.glob(fact_path + '/*.fact')): # where it will sit under local facts fact_base = os.path.basename(fn).replace('.fact','') if stat.S_IXUSR & os.stat(fn)[stat.ST_MODE]: # run it # try to read it as json first # if that fails read it with ConfigParser # if that fails, skip it rc, out, err = self.module.run_command(fn) else: out = get_file_content(fn, default='') # load raw json fact = 'loading %s' % fact_base try: fact = json.loads(out) except ValueError: # load raw ini cp = configparser.ConfigParser() try: cp.readfp(StringIO(out)) except configparser.Error: fact = "error loading fact - please check content" else: fact = {} for sect in cp.sections(): if sect not in fact: fact[sect] = {} for opt in cp.options(sect): val = cp.get(sect, opt) fact[sect][opt]=val local[fact_base] = fact if not local: return self.facts['local'] = local def get_cmdline(self): data = get_file_content('/proc/cmdline') if data: self.facts['cmdline'] = {} try: for piece in shlex.split(data): item = piece.split('=', 1) if len(item) == 1: self.facts['cmdline'][item[0]] = True else: self.facts['cmdline'][item[0]] = item[1] except ValueError: pass def get_public_ssh_host_keys(self): keytypes = ('dsa', 'rsa', 'ecdsa', 'ed25519') # list of directories to check for ssh keys # used in the order listed here, the first one with keys is used keydirs = ['/etc/ssh', '/etc/openssh', '/etc'] for keydir in keydirs: for type_ in keytypes: factname = 'ssh_host_key_%s_public' % type_ if factname in self.facts: # a previous keydir was already successful, stop looking # for keys return key_filename = '%s/ssh_host_%s_key.pub' % (keydir, type_) keydata = get_file_content(key_filename) if keydata is not None: self.facts[factname] = keydata.split()[1] def get_pkg_mgr_facts(self): if self.facts['system'] == 'OpenBSD': self.facts['pkg_mgr'] = 'openbsd_pkg' else: self.facts['pkg_mgr'] = 'unknown' for pkg in Facts.PKG_MGRS: if os.path.exists(pkg['path']): self.facts['pkg_mgr'] = pkg['name'] def get_service_mgr_facts(self): #TODO: detect more custom init setups like bootscripts, dmd, s6, Epoch, runit, etc # also other OSs other than linux might need to check across several possible candidates # try various forms of querying pid 1 proc_1 = get_file_content('/proc/1/comm') if proc_1 is None: rc, proc_1, err = self.module.run_command("ps -p 1 -o comm|tail -n 1", use_unsafe_shell=True) else: proc_1 = os.path.basename(proc_1) if proc_1 is not None: proc_1 = proc_1.strip() if proc_1 == 'init' or proc_1.endswith('sh'): # many systems return init, so this cannot be trusted, if it ends in 'sh' it probalby is a shell in a container proc_1 = None # if not init/None it should be an identifiable or custom init, so we are done! if proc_1 is not None: self.facts['service_mgr'] = proc_1 # start with the easy ones elif self.facts['distribution'] == 'MacOSX': #FIXME: find way to query executable, version matching is not ideal if LooseVersion(platform.mac_ver()[0]) >= LooseVersion('10.4'): self.facts['service_mgr'] = 'launchd' else: self.facts['service_mgr'] = 'systemstarter' elif 'BSD' in self.facts['system'] or self.facts['system'] in ['Bitrig', 'DragonFly']: #FIXME: we might want to break out to individual BSDs self.facts['service_mgr'] = 'bsdinit' elif self.facts['system'] == 'AIX': self.facts['service_mgr'] = 'src' elif self.facts['system'] == 'SunOS': #FIXME: smf? self.facts['service_mgr'] = 'svcs' elif self.facts['system'] == 'Linux': if self.is_systemd_managed(): self.facts['service_mgr'] = 'systemd' elif self.module.get_bin_path('initctl') and os.path.exists("/etc/init/"): self.facts['service_mgr'] = 'upstart' elif os.path.realpath('/sbin/rc') == '/sbin/openrc': self.facts['service_mgr'] = 'openrc' elif os.path.exists('/etc/init.d/'): self.facts['service_mgr'] = 'sysvinit' if not self.facts.get('service_mgr', False): # if we cannot detect, fallback to generic 'service' self.facts['service_mgr'] = 'service' def get_lsb_facts(self): lsb_path = self.module.get_bin_path('lsb_release') if lsb_path: rc, out, err = self.module.run_command([lsb_path, "-a"]) if rc == 0: self.facts['lsb'] = {} for line in out.split('\n'): if len(line) < 1 or ':' not in line: continue value = line.split(':', 1)[1].strip() if 'LSB Version:' in line: self.facts['lsb']['release'] = value elif 'Distributor ID:' in line: self.facts['lsb']['id'] = value elif 'Description:' in line: self.facts['lsb']['description'] = value elif 'Release:' in line: self.facts['lsb']['release'] = value elif 'Codename:' in line: self.facts['lsb']['codename'] = value elif lsb_path is None and os.path.exists('/etc/lsb-release'): self.facts['lsb'] = {} for line in get_file_lines('/etc/lsb-release'): value = line.split('=',1)[1].strip() if 'DISTRIB_ID' in line: self.facts['lsb']['id'] = value elif 'DISTRIB_RELEASE' in line: self.facts['lsb']['release'] = value elif 'DISTRIB_DESCRIPTION' in line: self.facts['lsb']['description'] = value elif 'DISTRIB_CODENAME' in line: self.facts['lsb']['codename'] = value if 'lsb' in self.facts and 'release' in self.facts['lsb']: self.facts['lsb']['major_release'] = self.facts['lsb']['release'].split('.')[0] def get_selinux_facts(self): if not HAVE_SELINUX: self.facts['selinux'] = False return self.facts['selinux'] = {} if not selinux.is_selinux_enabled(): self.facts['selinux']['status'] = 'disabled' else: self.facts['selinux']['status'] = 'enabled' try: self.facts['selinux']['policyvers'] = selinux.security_policyvers() except OSError: self.facts['selinux']['policyvers'] = 'unknown' try: (rc, configmode) = selinux.selinux_getenforcemode() if rc == 0: self.facts['selinux']['config_mode'] = Facts.SELINUX_MODE_DICT.get(configmode, 'unknown') else: self.facts['selinux']['config_mode'] = 'unknown' except OSError: self.facts['selinux']['config_mode'] = 'unknown' try: mode = selinux.security_getenforce() self.facts['selinux']['mode'] = Facts.SELINUX_MODE_DICT.get(mode, 'unknown') except OSError: self.facts['selinux']['mode'] = 'unknown' try: (rc, policytype) = selinux.selinux_getpolicytype() if rc == 0: self.facts['selinux']['type'] = policytype else: self.facts['selinux']['type'] = 'unknown' except OSError: self.facts['selinux']['type'] = 'unknown' def get_caps_facts(self): capsh_path = self.module.get_bin_path('capsh') if capsh_path: rc, out, err = self.module.run_command([capsh_path, "--print"]) enforced_caps = [] enforced = 'NA' for line in out.split('\n'): if len(line) < 1: continue if line.startswith('Current:'): if line.split(':')[1].strip() == '=ep': enforced = 'False' else: enforced = 'True' enforced_caps = [i.strip() for i in line.split('=')[1].split(',')] self.facts['system_capabilities_enforced'] = enforced self.facts['system_capabilities'] = enforced_caps def get_fips_facts(self): self.facts['fips'] = False data = get_file_content('/proc/sys/crypto/fips_enabled') if data and data == '1': self.facts['fips'] = True def get_date_time_facts(self): self.facts['date_time'] = {} now = datetime.datetime.now() self.facts['date_time']['year'] = now.strftime('%Y') self.facts['date_time']['month'] = now.strftime('%m') self.facts['date_time']['weekday'] = now.strftime('%A') self.facts['date_time']['weekday_number'] = now.strftime('%w') self.facts['date_time']['weeknumber'] = now.strftime('%W') self.facts['date_time']['day'] = now.strftime('%d') self.facts['date_time']['hour'] = now.strftime('%H') self.facts['date_time']['minute'] = now.strftime('%M') self.facts['date_time']['second'] = now.strftime('%S') self.facts['date_time']['epoch'] = now.strftime('%s') if self.facts['date_time']['epoch'] == '' or self.facts['date_time']['epoch'][0] == '%': self.facts['date_time']['epoch'] = str(int(time.time())) self.facts['date_time']['date'] = now.strftime('%Y-%m-%d') self.facts['date_time']['time'] = now.strftime('%H:%M:%S') self.facts['date_time']['iso8601_micro'] = now.utcnow().strftime("%Y-%m-%dT%H:%M:%S.%fZ") self.facts['date_time']['iso8601'] = now.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ") self.facts['date_time']['iso8601_basic'] = now.strftime("%Y%m%dT%H%M%S%f") self.facts['date_time']['iso8601_basic_short'] = now.strftime("%Y%m%dT%H%M%S") self.facts['date_time']['tz'] = time.strftime("%Z") self.facts['date_time']['tz_offset'] = time.strftime("%z") def is_systemd_managed(self): # tools must be installed if self.module.get_bin_path('systemctl'): # this should show if systemd is the boot init system, if checking init faild to mark as systemd # these mirror systemd's own sd_boot test http://www.freedesktop.org/software/systemd/man/sd_booted.html for canary in ["/run/systemd/system/", "/dev/.run/systemd/", "/dev/.systemd/"]: if os.path.exists(canary): return True return False # User def get_user_facts(self): self.facts['user_id'] = getpass.getuser() pwent = pwd.getpwnam(getpass.getuser()) self.facts['user_uid'] = pwent.pw_uid self.facts['user_gid'] = pwent.pw_gid self.facts['user_gecos'] = pwent.pw_gecos self.facts['user_dir'] = pwent.pw_dir self.facts['user_shell'] = pwent.pw_shell def get_env_facts(self): self.facts['env'] = {} for k,v in iteritems(os.environ): self.facts['env'][k] = v def get_dns_facts(self): self.facts['dns'] = {} for line in get_file_content('/etc/resolv.conf', '').splitlines(): if line.startswith('#') or line.startswith(';') or line.strip() == '': continue tokens = line.split() if len(tokens) == 0: continue if tokens[0] == 'nameserver': if not 'nameservers' in self.facts['dns']: self.facts['dns']['nameservers'] = [] for nameserver in tokens[1:]: self.facts['dns']['nameservers'].append(nameserver) elif tokens[0] == 'domain': if len(tokens) > 1: self.facts['dns']['domain'] = tokens[1] elif tokens[0] == 'search': self.facts['dns']['search'] = [] for suffix in tokens[1:]: self.facts['dns']['search'].append(suffix) elif tokens[0] == 'sortlist': self.facts['dns']['sortlist'] = [] for address in tokens[1:]: self.facts['dns']['sortlist'].append(address) elif tokens[0] == 'options': self.facts['dns']['options'] = {} if len(tokens) > 1: for option in tokens[1:]: option_tokens = option.split(':', 1) if len(option_tokens) == 0: continue val = len(option_tokens) == 2 and option_tokens[1] or True self.facts['dns']['options'][option_tokens[0]] = val def _get_mount_size_facts(self, mountpoint): size_total = None size_available = None try: statvfs_result = os.statvfs(mountpoint) size_total = statvfs_result.f_bsize * statvfs_result.f_blocks size_available = statvfs_result.f_bsize * (statvfs_result.f_bavail) except OSError: pass return size_total, size_available def get_python_facts(self): self.facts['python'] = { 'version': { 'major': sys.version_info[0], 'minor': sys.version_info[1], 'micro': sys.version_info[2], 'releaselevel': sys.version_info[3], 'serial': sys.version_info[4] }, 'version_info': list(sys.version_info), 'executable': sys.executable, 'has_sslcontext': HAS_SSLCONTEXT } try: self.facts['python']['type'] = sys.subversion[0] except AttributeError: self.facts['python']['type'] = None class Distribution(object): """ This subclass of Facts fills the distribution, distribution_version and distribution_release variables To do so it checks the existance and content of typical files in /etc containing distribution information This is unit tested. Please extend the tests to cover all distributions if you have them available. """ # every distribution name mentioned here, must have one of # - allowempty == True # - be listed in SEARCH_STRING # - have a function get_distribution_DISTNAME implemented OSDIST_LIST = ( {'path': '/etc/oracle-release', 'name': 'OracleLinux'}, {'path': '/etc/slackware-version', 'name': 'Slackware'}, {'path': '/etc/redhat-release', 'name': 'RedHat'}, {'path': '/etc/vmware-release', 'name': 'VMwareESX', 'allowempty': True}, {'path': '/etc/openwrt_release', 'name': 'OpenWrt'}, {'path': '/etc/system-release', 'name': 'Amazon'}, {'path': '/etc/alpine-release', 'name': 'Alpine'}, {'path': '/etc/release', 'name': 'Solaris'}, {'path': '/etc/arch-release', 'name': 'Archlinux', 'allowempty': True}, {'path': '/etc/os-release', 'name': 'SuSE'}, {'path': '/etc/SuSE-release', 'name': 'SuSE'}, {'path': '/etc/gentoo-release', 'name': 'Gentoo'}, {'path': '/etc/os-release', 'name': 'Debian'}, {'path': '/etc/lsb-release', 'name': 'Mandriva'}, {'path': '/etc/altlinux-release', 'name': 'Altlinux'}, {'path': '/etc/os-release', 'name': 'NA'}, {'path': '/etc/coreos/update.conf', 'name': 'Coreos'}, ) SEARCH_STRING = { 'OracleLinux': 'Oracle Linux', 'RedHat': 'Red Hat', 'Altlinux': 'ALT Linux', } # A list with OS Family members OS_FAMILY = dict( RedHat = 'RedHat', Fedora = 'RedHat', CentOS = 'RedHat', Scientific = 'RedHat', SLC = 'RedHat', Ascendos = 'RedHat', CloudLinux = 'RedHat', PSBM = 'RedHat', OracleLinux = 'RedHat', OVS = 'RedHat', OEL = 'RedHat', Amazon = 'RedHat', XenServer = 'RedHat', Ubuntu = 'Debian', Debian = 'Debian', Raspbian = 'Debian', Slackware = 'Slackware', SLES = 'Suse', SLED = 'Suse', openSUSE = 'Suse', SuSE = 'Suse', SLES_SAP = 'Suse', Gentoo = 'Gentoo', Funtoo = 'Gentoo', Archlinux = 'Archlinux', Manjaro = 'Archlinux', Mandriva = 'Mandrake', Mandrake = 'Mandrake', Altlinux = 'Altlinux', Solaris = 'Solaris', Nexenta = 'Solaris', OmniOS = 'Solaris', OpenIndiana = 'Solaris', SmartOS = 'Solaris', AIX = 'AIX', Alpine = 'Alpine', MacOSX = 'Darwin', FreeBSD = 'FreeBSD', HPUX = 'HP-UX', openSUSE_Leap = 'Suse' ) def __init__(self, module): self.system = platform.system() self.facts = {} self.module = module def populate(self): self.get_distribution_facts() return self.facts def get_distribution_facts(self): # The platform module provides information about the running # system/distribution. Use this as a baseline and fix buggy systems # afterwards self.facts['distribution'] = self.system self.facts['distribution_release'] = platform.release() self.facts['distribution_version'] = platform.version() systems_implemented = ('AIX', 'HP-UX', 'Darwin', 'OpenBSD') self.facts['distribution'] = self.system if self.system in systems_implemented: cleanedname = self.system.replace('-','') distfunc = getattr(self, 'get_distribution_'+cleanedname) distfunc() elif self.system == 'Linux': # try to find out which linux distribution this is dist = platform.dist() self.facts['distribution'] = dist[0].capitalize() or 'NA' self.facts['distribution_version'] = dist[1] or 'NA' self.facts['distribution_major_version'] = dist[1].split('.')[0] or 'NA' self.facts['distribution_release'] = dist[2] or 'NA' # Try to handle the exceptions now ... # self.facts['distribution_debug'] = [] for ddict in self.OSDIST_LIST: name = ddict['name'] path = ddict['path'] if not os.path.exists(path): continue # if allowempty is set, we only check for file existance but not content if 'allowempty' in ddict and ddict['allowempty']: self.facts['distribution'] = name break if os.path.getsize(path) == 0: continue data = get_file_content(path) if name in self.SEARCH_STRING: # look for the distribution string in the data and replace according to RELEASE_NAME_MAP # only the distribution name is set, the version is assumed to be correct from platform.dist() if self.SEARCH_STRING[name] in data: # this sets distribution=RedHat if 'Red Hat' shows up in data self.facts['distribution'] = name else: # this sets distribution to what's in the data, e.g. CentOS, Scientific, ... self.facts['distribution'] = data.split()[0] break else: # call a dedicated function for parsing the file content try: distfunc = getattr(self, 'get_distribution_' + name) parsed = distfunc(name, data, path) if parsed is None or parsed: # distfunc return False if parsing failed # break only if parsing was succesful # otherwise continue with other distributions break except AttributeError: # this should never happen, but if it does fail quitely and not with a traceback pass # to debug multiple matching release files, one can use: # self.facts['distribution_debug'].append({path + ' ' + name: # (parsed, # self.facts['distribution'], # self.facts['distribution_version'], # self.facts['distribution_release'], # )}) self.facts['os_family'] = self.facts['distribution'] distro = self.facts['distribution'].replace(' ', '_') if distro in self.OS_FAMILY: self.facts['os_family'] = self.OS_FAMILY[distro] def get_distribution_AIX(self): rc, out, err = self.module.run_command("/usr/bin/oslevel") data = out.split('.') self.facts['distribution_version'] = data[0] self.facts['distribution_release'] = data[1] def get_distribution_HPUX(self): rc, out, err = self.module.run_command("/usr/sbin/swlist |egrep 'HPUX.*OE.*[AB].[0-9]+\.[0-9]+'", use_unsafe_shell=True) data = re.search('HPUX.*OE.*([AB].[0-9]+\.[0-9]+)\.([0-9]+).*', out) if data: self.facts['distribution_version'] = data.groups()[0] self.facts['distribution_release'] = data.groups()[1] def get_distribution_Darwin(self): self.facts['distribution'] = 'MacOSX' rc, out, err = self.module.run_command("/usr/bin/sw_vers -productVersion") data = out.split()[-1] self.facts['distribution_version'] = data def get_distribution_OpenBSD(self): rc, out, err = self.module.run_command("/sbin/sysctl -n kern.version") match = re.match('OpenBSD\s[0-9]+.[0-9]+-(\S+)\s.*', out) if match: self.facts['distribution_version'] = match.groups()[0] else: self.facts['distribution_version'] = 'release' def get_distribution_Slackware(self, name, data, path): if 'Slackware' not in data: return False # TODO: remove self.facts['distribution'] = name version = re.findall('\w+[.]\w+', data) if version: self.facts['distribution_version'] = version[0] def get_distribution_Amazon(self, name, data, path): if 'Amazon' not in data: return False # TODO: remove self.facts['distribution'] = 'Amazon' self.facts['distribution_version'] = data.split()[-1] def get_distribution_OpenWrt(self, name, data, path): if 'OpenWrt' not in data: return False # TODO: remove self.facts['distribution'] = name version = re.search('DISTRIB_RELEASE="(.*)"', data) if version: self.facts['distribution_version'] = version.groups()[0] release = re.search('DISTRIB_CODENAME="(.*)"', data) if release: self.facts['distribution_release'] = release.groups()[0] def get_distribution_Alpine(self, name, data, path): self.facts['distribution'] = 'Alpine' self.facts['distribution_version'] = data def get_distribution_Solaris(self, name, data, path): data = data.split('\n')[0] if 'Solaris' in data: ora_prefix = '' if 'Oracle Solaris' in data: data = data.replace('Oracle ','') ora_prefix = 'Oracle ' self.facts['distribution'] = data.split()[0] self.facts['distribution_version'] = data.split()[1] self.facts['distribution_release'] = ora_prefix + data return uname_rc, uname_out, uname_err = self.module.run_command(['uname', '-v']) distribution_version = None if 'SmartOS' in data: self.facts['distribution'] = 'SmartOS' if os.path.exists('/etc/product'): product_data = dict([l.split(': ', 1) for l in get_file_content('/etc/product').split('\n') if ': ' in l]) if 'Image' in product_data: distribution_version = product_data.get('Image').split()[-1] elif 'OpenIndiana' in data: self.facts['distribution'] = 'OpenIndiana' elif 'OmniOS' in data: self.facts['distribution'] = 'OmniOS' distribution_version = data.split()[-1] elif uname_rc == 0 and 'NexentaOS_' in uname_out: self.facts['distribution'] = 'Nexenta' distribution_version = data.split()[-1].lstrip('v') if self.facts['distribution'] in ('SmartOS', 'OpenIndiana', 'OmniOS', 'Nexenta'): self.facts['distribution_release'] = data.strip() if distribution_version is not None: self.facts['distribution_version'] = distribution_version elif uname_rc == 0: self.facts['distribution_version'] = uname_out.split('\n')[0].strip() return return False # TODO: remove if tested without this def get_distribution_SuSE(self, name, data, path): if 'suse' not in data.lower(): return False # TODO: remove if tested without this if path == '/etc/os-release': for line in data.splitlines(): distribution = re.search("^NAME=(.*)", line) if distribution: self.facts['distribution'] = distribution.group(1).strip('"') # example pattern are 13.04 13.0 13 distribution_version = re.search('^VERSION_ID="?([0-9]+\.?[0-9]*)"?', line) if distribution_version: self.facts['distribution_version'] = distribution_version.group(1) if 'open' in data.lower(): release = re.search("^PRETTY_NAME=[^(]+ \(?([^)]+?)\)", line) if release: self.facts['distribution_release'] = release.groups()[0] elif 'enterprise' in data.lower() and 'VERSION_ID' in line: # SLES doesn't got funny release names release = re.search('^VERSION_ID="?[0-9]+\.?([0-9]*)"?', line) if release.group(1): release = release.group(1) else: release = "0" # no minor number, so it is the first release self.facts['distribution_release'] = release elif path == '/etc/SuSE-release': if 'open' in data.lower(): data = data.splitlines() distdata = get_file_content(path).split('\n')[0] self.facts['distribution'] = distdata.split()[0] for line in data: release = re.search('CODENAME *= *([^\n]+)', line) if release: self.facts['distribution_release'] = release.groups()[0].strip() elif 'enterprise' in data.lower(): lines = data.splitlines() distribution = lines[0].split()[0] if "Server" in data: self.facts['distribution'] = "SLES" elif "Desktop" in data: self.facts['distribution'] = "SLED" for line in lines: release = re.search('PATCHLEVEL = ([0-9]+)', line) # SLES doesn't got funny release names if release: self.facts['distribution_release'] = release.group(1) self.facts['distribution_version'] = self.facts['distribution_version'] + '.' + release.group(1) def get_distribution_Debian(self, name, data, path): if 'Debian' in data or 'Raspbian' in data: self.facts['distribution'] = 'Debian' release = re.search("PRETTY_NAME=[^(]+ \(?([^)]+?)\)", data) if release: self.facts['distribution_release'] = release.groups()[0] elif 'Ubuntu' in data: self.facts['distribution'] = 'Ubuntu' pass # Ubuntu gets correct info from python functions else: return False # TODO: remove if tested without this def get_distribution_Mandriva(self, name, data, path): if 'Mandriva' in data: self.facts['distribution'] = 'Mandriva' version = re.search('DISTRIB_RELEASE="(.*)"', data) if version: self.facts['distribution_version'] = version.groups()[0] release = re.search('DISTRIB_CODENAME="(.*)"', data) if release: self.facts['distribution_release'] = release.groups()[0] self.facts['distribution'] = name else: return False def get_distribution_NA(self, name, data, path): for line in data.splitlines(): distribution = re.search("^NAME=(.*)", line) if distribution and self.facts['distribution'] == 'NA': self.facts['distribution'] = distribution.group(1).strip('"') version = re.search("^VERSION=(.*)", line) if version and self.facts['distribution_version'] == 'NA': self.facts['distribution_version'] = version.group(1).strip('"') def get_distribution_Coreos(self, name, data, path): if self.facts['distribution'].lower() == 'coreos': if not data: # include fix from #15230, #15228 return release = re.search("^GROUP=(.*)", data) if release: self.facts['distribution_release'] = release.group(1).strip('"') else: return False # TODO: remove if tested without this class Hardware(Facts): """ This is a generic Hardware subclass of Facts. This should be further subclassed to implement per platform. If you subclass this, it should define: - memfree_mb - memtotal_mb - swapfree_mb - swaptotal_mb - processor (a list) - processor_cores - processor_count All subclasses MUST define platform. """ platform = 'Generic' def __new__(cls, *arguments, **keyword): subclass = cls for sc in get_all_subclasses(Hardware): if sc.platform == platform.system(): subclass = sc return super(cls, subclass).__new__(subclass, *arguments, **keyword) def populate(self): return self.facts class LinuxHardware(Hardware): """ Linux-specific subclass of Hardware. Defines memory and CPU facts: - memfree_mb - memtotal_mb - swapfree_mb - swaptotal_mb - processor (a list) - processor_cores - processor_count In addition, it also defines number of DMI facts and device facts. """ platform = 'Linux' # Originally only had these four as toplevelfacts ORIGINAL_MEMORY_FACTS = frozenset(('MemTotal', 'SwapTotal', 'MemFree', 'SwapFree')) # Now we have all of these in a dict structure MEMORY_FACTS = ORIGINAL_MEMORY_FACTS.union(('Buffers', 'Cached', 'SwapCached')) def populate(self): self.get_cpu_facts() self.get_memory_facts() self.get_dmi_facts() self.get_device_facts() self.get_uptime_facts() self.get_lvm_facts() try: self.get_mount_facts() except TimeoutError: pass return self.facts def get_memory_facts(self): if not os.access("/proc/meminfo", os.R_OK): return memstats = {} for line in get_file_lines("/proc/meminfo"): data = line.split(":", 1) key = data[0] if key in self.ORIGINAL_MEMORY_FACTS: val = data[1].strip().split(' ')[0] self.facts["%s_mb" % key.lower()] = long(val) / 1024 if key in self.MEMORY_FACTS: val = data[1].strip().split(' ')[0] memstats[key.lower()] = long(val) / 1024 if None not in (memstats.get('memtotal'), memstats.get('memfree')): memstats['real:used'] = memstats['memtotal'] - memstats['memfree'] if None not in (memstats.get('cached'), memstats.get('memfree'), memstats.get('buffers')): memstats['nocache:free'] = memstats['cached'] + memstats['memfree'] + memstats['buffers'] if None not in (memstats.get('memtotal'), memstats.get('nocache:free')): memstats['nocache:used'] = memstats['memtotal'] - memstats['nocache:free'] if None not in (memstats.get('swaptotal'), memstats.get('swapfree')): memstats['swap:used'] = memstats['swaptotal'] - memstats['swapfree'] self.facts['memory_mb'] = { 'real' : { 'total': memstats.get('memtotal'), 'used': memstats.get('real:used'), 'free': memstats.get('memfree'), }, 'nocache' : { 'free': memstats.get('nocache:free'), 'used': memstats.get('nocache:used'), }, 'swap' : { 'total': memstats.get('swaptotal'), 'free': memstats.get('swapfree'), 'used': memstats.get('swap:used'), 'cached': memstats.get('swapcached'), }, } def get_cpu_facts(self): i = 0 vendor_id_occurrence = 0 model_name_occurrence = 0 physid = 0 coreid = 0 sockets = {} cores = {} xen = False xen_paravirt = False try: if os.path.exists('/proc/xen'): xen = True else: for line in get_file_lines('/sys/hypervisor/type'): if line.strip() == 'xen': xen = True # Only interested in the first line break except IOError: pass if not os.access("/proc/cpuinfo", os.R_OK): return self.facts['processor'] = [] for line in get_file_lines('/proc/cpuinfo'): data = line.split(":", 1) key = data[0].strip() if xen: if key == 'flags': # Check for vme cpu flag, Xen paravirt does not expose this. # Need to detect Xen paravirt because it exposes cpuinfo # differently than Xen HVM or KVM and causes reporting of # only a single cpu core. if 'vme' not in data: xen_paravirt = True # model name is for Intel arch, Processor (mind the uppercase P) # works for some ARM devices, like the Sheevaplug. if key in ['model name', 'Processor', 'vendor_id', 'cpu', 'Vendor']: if 'processor' not in self.facts: self.facts['processor'] = [] self.facts['processor'].append(data[1].strip()) if key == 'vendor_id': vendor_id_occurrence += 1 if key == 'model name': model_name_occurrence += 1 i += 1 elif key == 'physical id': physid = data[1].strip() if physid not in sockets: sockets[physid] = 1 elif key == 'core id': coreid = data[1].strip() if coreid not in sockets: cores[coreid] = 1 elif key == 'cpu cores': sockets[physid] = int(data[1].strip()) elif key == 'siblings': cores[coreid] = int(data[1].strip()) elif key == '# processors': self.facts['processor_cores'] = int(data[1].strip()) if vendor_id_occurrence == model_name_occurrence: i = vendor_id_occurrence if self.facts['architecture'] != 's390x': if xen_paravirt: self.facts['processor_count'] = i self.facts['processor_cores'] = i self.facts['processor_threads_per_core'] = 1 self.facts['processor_vcpus'] = i else: self.facts['processor_count'] = sockets and len(sockets) or i self.facts['processor_cores'] = sockets.values() and sockets.values()[0] or 1 self.facts['processor_threads_per_core'] = ((cores.values() and cores.values()[0] or 1) / self.facts['processor_cores']) self.facts['processor_vcpus'] = (self.facts['processor_threads_per_core'] * self.facts['processor_count'] * self.facts['processor_cores']) def get_dmi_facts(self): ''' learn dmi facts from system Try /sys first for dmi related facts. If that is not available, fall back to dmidecode executable ''' if os.path.exists('/sys/devices/virtual/dmi/id/product_name'): # Use kernel DMI info, if available # DMI SPEC -- http://www.dmtf.org/sites/default/files/standards/documents/DSP0134_2.7.0.pdf FORM_FACTOR = [ "Unknown", "Other", "Unknown", "Desktop", "Low Profile Desktop", "Pizza Box", "Mini Tower", "Tower", "Portable", "Laptop", "Notebook", "Hand Held", "Docking Station", "All In One", "Sub Notebook", "Space-saving", "Lunch Box", "Main Server Chassis", "Expansion Chassis", "Sub Chassis", "Bus Expansion Chassis", "Peripheral Chassis", "RAID Chassis", "Rack Mount Chassis", "Sealed-case PC", "Multi-system", "CompactPCI", "AdvancedTCA", "Blade" ] DMI_DICT = { 'bios_date': '/sys/devices/virtual/dmi/id/bios_date', 'bios_version': '/sys/devices/virtual/dmi/id/bios_version', 'form_factor': '/sys/devices/virtual/dmi/id/chassis_type', 'product_name': '/sys/devices/virtual/dmi/id/product_name', 'product_serial': '/sys/devices/virtual/dmi/id/product_serial', 'product_uuid': '/sys/devices/virtual/dmi/id/product_uuid', 'product_version': '/sys/devices/virtual/dmi/id/product_version', 'system_vendor': '/sys/devices/virtual/dmi/id/sys_vendor' } for (key,path) in DMI_DICT.items(): data = get_file_content(path) if data is not None: if key == 'form_factor': try: self.facts['form_factor'] = FORM_FACTOR[int(data)] except IndexError: self.facts['form_factor'] = 'unknown (%s)' % data else: self.facts[key] = data else: self.facts[key] = 'NA' else: # Fall back to using dmidecode, if available dmi_bin = self.module.get_bin_path('dmidecode') DMI_DICT = { 'bios_date': 'bios-release-date', 'bios_version': 'bios-version', 'form_factor': 'chassis-type', 'product_name': 'system-product-name', 'product_serial': 'system-serial-number', 'product_uuid': 'system-uuid', 'product_version': 'system-version', 'system_vendor': 'system-manufacturer' } for (k, v) in DMI_DICT.items(): if dmi_bin is not None: (rc, out, err) = self.module.run_command('%s -s %s' % (dmi_bin, v)) if rc == 0: # Strip out commented lines (specific dmidecode output) thisvalue = ''.join([ line for line in out.split('\n') if not line.startswith('#') ]) try: json.dumps(thisvalue) except UnicodeDecodeError: thisvalue = "NA" self.facts[k] = thisvalue else: self.facts[k] = 'NA' else: self.facts[k] = 'NA' @timeout(10) def get_mount_facts(self): uuids = dict() self.facts['mounts'] = [] bind_mounts = [] findmntPath = self.module.get_bin_path("findmnt") if findmntPath: rc, out, err = self.module.run_command("%s -lnur" % ( findmntPath ), use_unsafe_shell=True) if rc == 0: # find bind mounts, in case /etc/mtab is a symlink to /proc/mounts for line in out.split('\n'): fields = line.rstrip('\n').split() if(len(fields) < 2): continue if(re.match(".*\]",fields[1])): bind_mounts.append(fields[0]) mtab = get_file_content('/etc/mtab', '') for line in mtab.split('\n'): fields = line.rstrip('\n').split() if fields[0].startswith('/') or ':/' in fields[0]: if(fields[2] != 'none'): size_total, size_available = self._get_mount_size_facts(fields[1]) if fields[0] in uuids: uuid = uuids[fields[0]] else: uuid = 'NA' lsblkPath = self.module.get_bin_path("lsblk") if lsblkPath: rc, out, err = self.module.run_command("%s -ln --output UUID %s" % (lsblkPath, fields[0]), use_unsafe_shell=True) if rc == 0: uuid = out.strip() uuids[fields[0]] = uuid if fields[1] in bind_mounts: # only add if not already there, we might have a plain /etc/mtab if not re.match(".*bind.*", fields[3]): fields[3] += ",bind" self.facts['mounts'].append( {'mount': fields[1], 'device':fields[0], 'fstype': fields[2], 'options': fields[3], # statvfs data 'size_total': size_total, 'size_available': size_available, 'uuid': uuid, }) def get_device_facts(self): self.facts['devices'] = {} lspci = self.module.get_bin_path('lspci') if lspci: rc, pcidata, err = self.module.run_command([lspci, '-D']) else: pcidata = None try: block_devs = os.listdir("/sys/block") except OSError: return for block in block_devs: virtual = 1 sysfs_no_links = 0 try: path = os.readlink(os.path.join("/sys/block/", block)) except OSError: e = sys.exc_info()[1] if e.errno == errno.EINVAL: path = block sysfs_no_links = 1 else: continue if "virtual" in path: continue sysdir = os.path.join("/sys/block", path) if sysfs_no_links == 1: for folder in os.listdir(sysdir): if "device" in folder: virtual = 0 break if virtual: continue d = {} diskname = os.path.basename(sysdir) for key in ['vendor', 'model', 'sas_address', 'sas_device_handle']: d[key] = get_file_content(sysdir + "/device/" + key) for key,test in [ ('removable','/removable'), \ ('support_discard','/queue/discard_granularity'), ]: d[key] = get_file_content(sysdir + test) d['partitions'] = {} for folder in os.listdir(sysdir): m = re.search("(" + diskname + "\d+)", folder) if m: part = {} partname = m.group(1) part_sysdir = sysdir + "/" + partname part['start'] = get_file_content(part_sysdir + "/start",0) part['sectors'] = get_file_content(part_sysdir + "/size",0) part['sectorsize'] = get_file_content(part_sysdir + "/queue/logical_block_size") if not part['sectorsize']: part['sectorsize'] = get_file_content(part_sysdir + "/queue/hw_sector_size",512) part['size'] = self.module.pretty_bytes((float(part['sectors']) * float(part['sectorsize']))) d['partitions'][partname] = part d['rotational'] = get_file_content(sysdir + "/queue/rotational") d['scheduler_mode'] = "" scheduler = get_file_content(sysdir + "/queue/scheduler") if scheduler is not None: m = re.match(".*?(\[(.*)\])", scheduler) if m: d['scheduler_mode'] = m.group(2) d['sectors'] = get_file_content(sysdir + "/size") if not d['sectors']: d['sectors'] = 0 d['sectorsize'] = get_file_content(sysdir + "/queue/logical_block_size") if not d['sectorsize']: d['sectorsize'] = get_file_content(sysdir + "/queue/hw_sector_size",512) d['size'] = self.module.pretty_bytes(float(d['sectors']) * float(d['sectorsize'])) d['host'] = "" # domains are numbered (0 to ffff), bus (0 to ff), slot (0 to 1f), and function (0 to 7). m = re.match(".+/([a-f0-9]{4}:[a-f0-9]{2}:[0|1][a-f0-9]\.[0-7])/", sysdir) if m and pcidata: pciid = m.group(1) did = re.escape(pciid) m = re.search("^" + did + "\s(.*)$", pcidata, re.MULTILINE) if m: d['host'] = m.group(1) d['holders'] = [] if os.path.isdir(sysdir + "/holders"): for folder in os.listdir(sysdir + "/holders"): if not folder.startswith("dm-"): continue name = get_file_content(sysdir + "/holders/" + folder + "/dm/name") if name: d['holders'].append(name) else: d['holders'].append(folder) self.facts['devices'][diskname] = d def get_uptime_facts(self): uptime_file_content = get_file_content('/proc/uptime') if uptime_file_content: uptime_seconds_string = uptime_file_content.split(' ')[0] self.facts['uptime_seconds'] = int(float(uptime_seconds_string)) def get_lvm_facts(self): """ Get LVM Facts if running as root and lvm utils are available """ if os.getuid() == 0 and self.module.get_bin_path('vgs'): lvm_util_options = '--noheadings --nosuffix --units g' vgs_path = self.module.get_bin_path('vgs') #vgs fields: VG #PV #LV #SN Attr VSize VFree vgs={} if vgs_path: rc, vg_lines, err = self.module.run_command( '%s %s' % (vgs_path, lvm_util_options)) for vg_line in vg_lines.splitlines(): items = vg_line.split() vgs[items[0]] = {'size_g':items[-2], 'free_g':items[-1], 'num_lvs': items[2], 'num_pvs': items[1]} lvs_path = self.module.get_bin_path('lvs') #lvs fields: #LV VG Attr LSize Pool Origin Data% Move Log Copy% Convert lvs = {} if lvs_path: rc, lv_lines, err = self.module.run_command( '%s %s' % (lvs_path, lvm_util_options)) for lv_line in lv_lines.splitlines(): items = lv_line.split() lvs[items[0]] = {'size_g': items[3], 'vg': items[1]} self.facts['lvm'] = {'lvs': lvs, 'vgs': vgs} class SunOSHardware(Hardware): """ In addition to the generic memory and cpu facts, this also sets swap_reserved_mb and swap_allocated_mb that is available from *swap -s*. """ platform = 'SunOS' def populate(self): self.get_cpu_facts() self.get_memory_facts() try: self.get_mount_facts() except TimeoutError: pass return self.facts def get_cpu_facts(self): physid = 0 sockets = {} rc, out, err = self.module.run_command("/usr/bin/kstat cpu_info") self.facts['processor'] = [] for line in out.split('\n'): if len(line) < 1: continue data = line.split(None, 1) key = data[0].strip() # "brand" works on Solaris 10 & 11. "implementation" for Solaris 9. if key == 'module:': brand = '' elif key == 'brand': brand = data[1].strip() elif key == 'clock_MHz': clock_mhz = data[1].strip() elif key == 'implementation': processor = brand or data[1].strip() # Add clock speed to description for SPARC CPU if self.facts['machine'] != 'i86pc': processor += " @ " + clock_mhz + "MHz" if 'processor' not in self.facts: self.facts['processor'] = [] self.facts['processor'].append(processor) elif key == 'chip_id': physid = data[1].strip() if physid not in sockets: sockets[physid] = 1 else: sockets[physid] += 1 # Counting cores on Solaris can be complicated. # https://blogs.oracle.com/mandalika/entry/solaris_show_me_the_cpu # Treat 'processor_count' as physical sockets and 'processor_cores' as # virtual CPUs visisble to Solaris. Not a true count of cores for modern SPARC as # these processors have: sockets -> cores -> threads/virtual CPU. if len(sockets) > 0: self.facts['processor_count'] = len(sockets) self.facts['processor_cores'] = reduce(lambda x, y: x + y, sockets.values()) else: self.facts['processor_cores'] = 'NA' self.facts['processor_count'] = len(self.facts['processor']) def get_memory_facts(self): rc, out, err = self.module.run_command(["/usr/sbin/prtconf"]) for line in out.split('\n'): if 'Memory size' in line: self.facts['memtotal_mb'] = line.split()[2] rc, out, err = self.module.run_command("/usr/sbin/swap -s") allocated = long(out.split()[1][:-1]) reserved = long(out.split()[5][:-1]) used = long(out.split()[8][:-1]) free = long(out.split()[10][:-1]) self.facts['swapfree_mb'] = free / 1024 self.facts['swaptotal_mb'] = (free + used) / 1024 self.facts['swap_allocated_mb'] = allocated / 1024 self.facts['swap_reserved_mb'] = reserved / 1024 @timeout(10) def get_mount_facts(self): self.facts['mounts'] = [] # For a detailed format description see mnttab(4) # special mount_point fstype options time fstab = get_file_content('/etc/mnttab') if fstab: for line in fstab.split('\n'): fields = line.rstrip('\n').split('\t') size_total, size_available = self._get_mount_size_facts(fields[1]) self.facts['mounts'].append({'mount': fields[1], 'device': fields[0], 'fstype' : fields[2], 'options': fields[3], 'time': fields[4], 'size_total': size_total, 'size_available': size_available}) class OpenBSDHardware(Hardware): """ OpenBSD-specific subclass of Hardware. Defines memory, CPU and device facts: - memfree_mb - memtotal_mb - swapfree_mb - swaptotal_mb - processor (a list) - processor_cores - processor_count - processor_speed - devices """ platform = 'OpenBSD' DMESG_BOOT = '/var/run/dmesg.boot' def populate(self): self.sysctl = self.get_sysctl() self.get_memory_facts() self.get_processor_facts() self.get_device_facts() self.get_mount_facts() return self.facts def get_sysctl(self): rc, out, err = self.module.run_command(["/sbin/sysctl", "hw"]) if rc != 0: return dict() sysctl = dict() for line in out.splitlines(): (key, value) = line.split('=') sysctl[key] = value.strip() return sysctl @timeout(10) def get_mount_facts(self): self.facts['mounts'] = [] fstab = get_file_content('/etc/fstab') if fstab: for line in fstab.split('\n'): if line.startswith('#') or line.strip() == '': continue fields = re.sub(r'\s+',' ',line.rstrip('\n')).split() if fields[1] == 'none' or fields[3] == 'xx': continue size_total, size_available = self._get_mount_size_facts(fields[1]) self.facts['mounts'].append({'mount': fields[1], 'device': fields[0], 'fstype' : fields[2], 'options': fields[3], 'size_total': size_total, 'size_available': size_available}) def get_memory_facts(self): # Get free memory. vmstat output looks like: # procs memory page disks traps cpu # r b w avm fre flt re pi po fr sr wd0 fd0 int sys cs us sy id # 0 0 0 47512 28160 51 0 0 0 0 0 1 0 116 89 17 0 1 99 rc, out, err = self.module.run_command("/usr/bin/vmstat") if rc == 0: self.facts['memfree_mb'] = long(out.splitlines()[-1].split()[4]) / 1024 self.facts['memtotal_mb'] = long(self.sysctl['hw.usermem']) / 1024 / 1024 # Get swapctl info. swapctl output looks like: # total: 69268 1K-blocks allocated, 0 used, 69268 available # And for older OpenBSD: # total: 69268k bytes allocated = 0k used, 69268k available rc, out, err = self.module.run_command("/sbin/swapctl -sk") if rc == 0: swaptrans = maketrans(' ', ' ') data = out.split() self.facts['swapfree_mb'] = long(data[-2].translate(swaptrans, "kmg")) / 1024 self.facts['swaptotal_mb'] = long(data[1].translate(swaptrans, "kmg")) / 1024 def get_processor_facts(self): processor = [] dmesg_boot = get_file_content(OpenBSDHardware.DMESG_BOOT) if not dmesg_boot: rc, dmesg_boot, err = self.module.run_command("/sbin/dmesg") i = 0 for line in dmesg_boot.splitlines(): if line.split(' ', 1)[0] == 'cpu%i:' % i: processor.append(line.split(' ', 1)[1]) i = i + 1 processor_count = i self.facts['processor'] = processor self.facts['processor_count'] = processor_count # I found no way to figure out the number of Cores per CPU in OpenBSD self.facts['processor_cores'] = 'NA' def get_device_facts(self): devices = [] devices.extend(self.sysctl['hw.disknames'].split(',')) self.facts['devices'] = devices class FreeBSDHardware(Hardware): """ FreeBSD-specific subclass of Hardware. Defines memory and CPU facts: - memfree_mb - memtotal_mb - swapfree_mb - swaptotal_mb - processor (a list) - processor_cores - processor_count - devices """ platform = 'FreeBSD' DMESG_BOOT = '/var/run/dmesg.boot' def populate(self): self.get_cpu_facts() self.get_memory_facts() self.get_dmi_facts() self.get_device_facts() try: self.get_mount_facts() except TimeoutError: pass return self.facts def get_cpu_facts(self): self.facts['processor'] = [] rc, out, err = self.module.run_command("/sbin/sysctl -n hw.ncpu") self.facts['processor_count'] = out.strip() dmesg_boot = get_file_content(FreeBSDHardware.DMESG_BOOT) if not dmesg_boot: rc, dmesg_boot, err = self.module.run_command("/sbin/dmesg") for line in dmesg_boot.split('\n'): if 'CPU:' in line: cpu = re.sub(r'CPU:\s+', r"", line) self.facts['processor'].append(cpu.strip()) if 'Logical CPUs per core' in line: self.facts['processor_cores'] = line.split()[4] def get_memory_facts(self): rc, out, err = self.module.run_command("/sbin/sysctl vm.stats") for line in out.split('\n'): data = line.split() if 'vm.stats.vm.v_page_size' in line: pagesize = long(data[1]) if 'vm.stats.vm.v_page_count' in line: pagecount = long(data[1]) if 'vm.stats.vm.v_free_count' in line: freecount = long(data[1]) self.facts['memtotal_mb'] = pagesize * pagecount / 1024 / 1024 self.facts['memfree_mb'] = pagesize * freecount / 1024 / 1024 # Get swapinfo. swapinfo output looks like: # Device 1M-blocks Used Avail Capacity # /dev/ada0p3 314368 0 314368 0% # rc, out, err = self.module.run_command("/usr/sbin/swapinfo -k") lines = out.split('\n') if len(lines[-1]) == 0: lines.pop() data = lines[-1].split() if data[0] != 'Device': self.facts['swaptotal_mb'] = int(data[1]) / 1024 self.facts['swapfree_mb'] = int(data[3]) / 1024 @timeout(10) def get_mount_facts(self): self.facts['mounts'] = [] fstab = get_file_content('/etc/fstab') if fstab: for line in fstab.split('\n'): if line.startswith('#') or line.strip() == '': continue fields = re.sub(r'\s+',' ',line.rstrip('\n')).split() size_total, size_available = self._get_mount_size_facts(fields[1]) self.facts['mounts'].append({'mount': fields[1], 'device': fields[0], 'fstype' : fields[2], 'options': fields[3], 'size_total': size_total, 'size_available': size_available}) def get_device_facts(self): sysdir = '/dev' self.facts['devices'] = {} drives = re.compile('(ada?\d+|da\d+|a?cd\d+)') #TODO: rc, disks, err = self.module.run_command("/sbin/sysctl kern.disks") slices = re.compile('(ada?\d+s\d+\w*|da\d+s\d+\w*)') if os.path.isdir(sysdir): dirlist = sorted(os.listdir(sysdir)) for device in dirlist: d = drives.match(device) if d: self.facts['devices'][d.group(1)] = [] s = slices.match(device) if s: self.facts['devices'][d.group(1)].append(s.group(1)) def get_dmi_facts(self): ''' learn dmi facts from system Use dmidecode executable if available''' # Fall back to using dmidecode, if available dmi_bin = self.module.get_bin_path('dmidecode') DMI_DICT = dict( bios_date='bios-release-date', bios_version='bios-version', form_factor='chassis-type', product_name='system-product-name', product_serial='system-serial-number', product_uuid='system-uuid', product_version='system-version', system_vendor='system-manufacturer' ) for (k, v) in DMI_DICT.items(): if dmi_bin is not None: (rc, out, err) = self.module.run_command('%s -s %s' % (dmi_bin, v)) if rc == 0: # Strip out commented lines (specific dmidecode output) self.facts[k] = ''.join([ line for line in out.split('\n') if not line.startswith('#') ]) try: json.dumps(self.facts[k]) except UnicodeDecodeError: self.facts[k] = 'NA' else: self.facts[k] = 'NA' else: self.facts[k] = 'NA' class DragonFlyHardware(FreeBSDHardware): pass class NetBSDHardware(Hardware): """ NetBSD-specific subclass of Hardware. Defines memory and CPU facts: - memfree_mb - memtotal_mb - swapfree_mb - swaptotal_mb - processor (a list) - processor_cores - processor_count - devices """ platform = 'NetBSD' MEMORY_FACTS = ['MemTotal', 'SwapTotal', 'MemFree', 'SwapFree'] def populate(self): self.get_cpu_facts() self.get_memory_facts() try: self.get_mount_facts() except TimeoutError: pass return self.facts def get_cpu_facts(self): i = 0 physid = 0 sockets = {} if not os.access("/proc/cpuinfo", os.R_OK): return self.facts['processor'] = [] for line in get_file_lines("/proc/cpuinfo"): data = line.split(":", 1) key = data[0].strip() # model name is for Intel arch, Processor (mind the uppercase P) # works for some ARM devices, like the Sheevaplug. if key == 'model name' or key == 'Processor': if 'processor' not in self.facts: self.facts['processor'] = [] self.facts['processor'].append(data[1].strip()) i += 1 elif key == 'physical id': physid = data[1].strip() if physid not in sockets: sockets[physid] = 1 elif key == 'cpu cores': sockets[physid] = int(data[1].strip()) if len(sockets) > 0: self.facts['processor_count'] = len(sockets) self.facts['processor_cores'] = reduce(lambda x, y: x + y, sockets.values()) else: self.facts['processor_count'] = i self.facts['processor_cores'] = 'NA' def get_memory_facts(self): if not os.access("/proc/meminfo", os.R_OK): return for line in get_file_lines("/proc/meminfo"): data = line.split(":", 1) key = data[0] if key in NetBSDHardware.MEMORY_FACTS: val = data[1].strip().split(' ')[0] self.facts["%s_mb" % key.lower()] = long(val) / 1024 @timeout(10) def get_mount_facts(self): self.facts['mounts'] = [] fstab = get_file_content('/etc/fstab') if fstab: for line in fstab.split('\n'): if line.startswith('#') or line.strip() == '': continue fields = re.sub(r'\s+',' ',line.rstrip('\n')).split() size_total, size_available = self._get_mount_size_facts(fields[1]) self.facts['mounts'].append({'mount': fields[1], 'device': fields[0], 'fstype' : fields[2], 'options': fields[3], 'size_total': size_total, 'size_available': size_available}) class AIX(Hardware): """ AIX-specific subclass of Hardware. Defines memory and CPU facts: - memfree_mb - memtotal_mb - swapfree_mb - swaptotal_mb - processor (a list) - processor_cores - processor_count """ platform = 'AIX' def populate(self): self.get_cpu_facts() self.get_memory_facts() self.get_dmi_facts() return self.facts def get_cpu_facts(self): self.facts['processor'] = [] rc, out, err = self.module.run_command("/usr/sbin/lsdev -Cc processor") if out: i = 0 for line in out.split('\n'): if 'Available' in line: if i == 0: data = line.split(' ') cpudev = data[0] i += 1 self.facts['processor_count'] = int(i) rc, out, err = self.module.run_command("/usr/sbin/lsattr -El " + cpudev + " -a type") data = out.split(' ') self.facts['processor'] = data[1] rc, out, err = self.module.run_command("/usr/sbin/lsattr -El " + cpudev + " -a smt_threads") data = out.split(' ') self.facts['processor_cores'] = int(data[1]) def get_memory_facts(self): pagesize = 4096 rc, out, err = self.module.run_command("/usr/bin/vmstat -v") for line in out.split('\n'): data = line.split() if 'memory pages' in line: pagecount = long(data[0]) if 'free pages' in line: freecount = long(data[0]) self.facts['memtotal_mb'] = pagesize * pagecount / 1024 / 1024 self.facts['memfree_mb'] = pagesize * freecount / 1024 / 1024 # Get swapinfo. swapinfo output looks like: # Device 1M-blocks Used Avail Capacity # /dev/ada0p3 314368 0 314368 0% # rc, out, err = self.module.run_command("/usr/sbin/lsps -s") if out: lines = out.split('\n') data = lines[1].split() swaptotal_mb = long(data[0].rstrip('MB')) percused = int(data[1].rstrip('%')) self.facts['swaptotal_mb'] = swaptotal_mb self.facts['swapfree_mb'] = long(swaptotal_mb * ( 100 - percused ) / 100) def get_dmi_facts(self): rc, out, err = self.module.run_command("/usr/sbin/lsattr -El sys0 -a fwversion") data = out.split() self.facts['firmware_version'] = data[1].strip('IBM,') class HPUX(Hardware): """ HP-UX-specific subclass of Hardware. Defines memory and CPU facts: - memfree_mb - memtotal_mb - swapfree_mb - swaptotal_mb - processor - processor_cores - processor_count - model - firmware """ platform = 'HP-UX' def populate(self): self.get_cpu_facts() self.get_memory_facts() self.get_hw_facts() return self.facts def get_cpu_facts(self): if self.facts['architecture'] == '9000/800': rc, out, err = self.module.run_command("ioscan -FkCprocessor | wc -l", use_unsafe_shell=True) self.facts['processor_count'] = int(out.strip()) #Working with machinfo mess elif self.facts['architecture'] == 'ia64': if self.facts['distribution_version'] == "B.11.23": rc, out, err = self.module.run_command("/usr/contrib/bin/machinfo | grep 'Number of CPUs'", use_unsafe_shell=True) self.facts['processor_count'] = int(out.strip().split('=')[1]) rc, out, err = self.module.run_command("/usr/contrib/bin/machinfo | grep 'processor family'", use_unsafe_shell=True) self.facts['processor'] = re.search('.*(Intel.*)', out).groups()[0].strip() rc, out, err = self.module.run_command("ioscan -FkCprocessor | wc -l", use_unsafe_shell=True) self.facts['processor_cores'] = int(out.strip()) if self.facts['distribution_version'] == "B.11.31": #if machinfo return cores strings release B.11.31 > 1204 rc, out, err = self.module.run_command("/usr/contrib/bin/machinfo | grep core | wc -l", use_unsafe_shell=True) if out.strip()== '0': rc, out, err = self.module.run_command("/usr/contrib/bin/machinfo | grep Intel", use_unsafe_shell=True) self.facts['processor_count'] = int(out.strip().split(" ")[0]) #If hyperthreading is active divide cores by 2 rc, out, err = self.module.run_command("/usr/sbin/psrset | grep LCPU", use_unsafe_shell=True) data = re.sub(' +',' ',out).strip().split(' ') if len(data) == 1: hyperthreading = 'OFF' else: hyperthreading = data[1] rc, out, err = self.module.run_command("/usr/contrib/bin/machinfo | grep logical", use_unsafe_shell=True) data = out.strip().split(" ") if hyperthreading == 'ON': self.facts['processor_cores'] = int(data[0])/2 else: if len(data) == 1: self.facts['processor_cores'] = self.facts['processor_count'] else: self.facts['processor_cores'] = int(data[0]) rc, out, err = self.module.run_command("/usr/contrib/bin/machinfo | grep Intel |cut -d' ' -f4-", use_unsafe_shell=True) self.facts['processor'] = out.strip() else: rc, out, err = self.module.run_command("/usr/contrib/bin/machinfo | egrep 'socket[s]?$' | tail -1", use_unsafe_shell=True) self.facts['processor_count'] = int(out.strip().split(" ")[0]) rc, out, err = self.module.run_command("/usr/contrib/bin/machinfo | grep -e '[0-9] core' | tail -1", use_unsafe_shell=True) self.facts['processor_cores'] = int(out.strip().split(" ")[0]) rc, out, err = self.module.run_command("/usr/contrib/bin/machinfo | grep Intel", use_unsafe_shell=True) self.facts['processor'] = out.strip() def get_memory_facts(self): pagesize = 4096 rc, out, err = self.module.run_command("/usr/bin/vmstat | tail -1", use_unsafe_shell=True) data = int(re.sub(' +',' ',out).split(' ')[5].strip()) self.facts['memfree_mb'] = pagesize * data / 1024 / 1024 if self.facts['architecture'] == '9000/800': try: rc, out, err = self.module.run_command("grep Physical /var/adm/syslog/syslog.log") data = re.search('.*Physical: ([0-9]*) Kbytes.*',out).groups()[0].strip() self.facts['memtotal_mb'] = int(data) / 1024 except AttributeError: #For systems where memory details aren't sent to syslog or the log has rotated, use parsed #adb output. Unfortunately /dev/kmem doesn't have world-read, so this only works as root. if os.access("/dev/kmem", os.R_OK): rc, out, err = self.module.run_command("echo 'phys_mem_pages/D' | adb -k /stand/vmunix /dev/kmem | tail -1 | awk '{print $2}'", use_unsafe_shell=True) if not err: data = out self.facts['memtotal_mb'] = int(data) / 256 else: rc, out, err = self.module.run_command("/usr/contrib/bin/machinfo | grep Memory", use_unsafe_shell=True) data = re.search('Memory[\ :=]*([0-9]*).*MB.*',out).groups()[0].strip() self.facts['memtotal_mb'] = int(data) rc, out, err = self.module.run_command("/usr/sbin/swapinfo -m -d -f -q") self.facts['swaptotal_mb'] = int(out.strip()) rc, out, err = self.module.run_command("/usr/sbin/swapinfo -m -d -f | egrep '^dev|^fs'", use_unsafe_shell=True) swap = 0 for line in out.strip().split('\n'): swap += int(re.sub(' +',' ',line).split(' ')[3].strip()) self.facts['swapfree_mb'] = swap def get_hw_facts(self): rc, out, err = self.module.run_command("model") self.facts['model'] = out.strip() if self.facts['architecture'] == 'ia64': separator = ':' if self.facts['distribution_version'] == "B.11.23": separator = '=' rc, out, err = self.module.run_command("/usr/contrib/bin/machinfo |grep -i 'Firmware revision' | grep -v BMC", use_unsafe_shell=True) self.facts['firmware_version'] = out.split(separator)[1].strip() class Darwin(Hardware): """ Darwin-specific subclass of Hardware. Defines memory and CPU facts: - processor - processor_cores - memtotal_mb - memfree_mb - model - osversion - osrevision """ platform = 'Darwin' def populate(self): self.sysctl = self.get_sysctl() self.get_mac_facts() self.get_cpu_facts() self.get_memory_facts() return self.facts def get_sysctl(self): rc, out, err = self.module.run_command(["/usr/sbin/sysctl", "hw", "machdep", "kern"]) if rc != 0: return dict() sysctl = dict() for line in out.splitlines(): if line.rstrip("\n"): (key, value) = re.split(' = |: ', line, maxsplit=1) sysctl[key] = value.strip() return sysctl def get_system_profile(self): rc, out, err = self.module.run_command(["/usr/sbin/system_profiler", "SPHardwareDataType"]) if rc != 0: return dict() system_profile = dict() for line in out.splitlines(): if ': ' in line: (key, value) = line.split(': ', 1) system_profile[key.strip()] = ' '.join(value.strip().split()) return system_profile def get_mac_facts(self): rc, out, err = self.module.run_command("sysctl hw.model") if rc == 0: self.facts['model'] = out.splitlines()[-1].split()[1] self.facts['osversion'] = self.sysctl['kern.osversion'] self.facts['osrevision'] = self.sysctl['kern.osrevision'] def get_cpu_facts(self): if 'machdep.cpu.brand_string' in self.sysctl: # Intel self.facts['processor'] = self.sysctl['machdep.cpu.brand_string'] self.facts['processor_cores'] = self.sysctl['machdep.cpu.core_count'] else: # PowerPC system_profile = self.get_system_profile() self.facts['processor'] = '%s @ %s' % (system_profile['Processor Name'], system_profile['Processor Speed']) self.facts['processor_cores'] = self.sysctl['hw.physicalcpu'] def get_memory_facts(self): self.facts['memtotal_mb'] = long(self.sysctl['hw.memsize']) / 1024 / 1024 rc, out, err = self.module.run_command("sysctl hw.usermem") if rc == 0: self.facts['memfree_mb'] = long(out.splitlines()[-1].split()[1]) / 1024 / 1024 class Network(Facts): """ This is a generic Network subclass of Facts. This should be further subclassed to implement per platform. If you subclass this, you must define: - interfaces (a list of interface names) - interface_<name> dictionary of ipv4, ipv6, and mac address information. All subclasses MUST define platform. """ platform = 'Generic' IPV6_SCOPE = { '0' : 'global', '10' : 'host', '20' : 'link', '40' : 'admin', '50' : 'site', '80' : 'organization' } def __new__(cls, *arguments, **keyword): subclass = cls for sc in get_all_subclasses(Network): if sc.platform == platform.system(): subclass = sc return super(cls, subclass).__new__(subclass, *arguments, **keyword) def populate(self): return self.facts class LinuxNetwork(Network): """ This is a Linux-specific subclass of Network. It defines - interfaces (a list of interface names) - interface_<name> dictionary of ipv4, ipv6, and mac address information. - all_ipv4_addresses and all_ipv6_addresses: lists of all configured addresses. - ipv4_address and ipv6_address: the first non-local address for each family. """ platform = 'Linux' def populate(self): ip_path = self.module.get_bin_path('ip') if ip_path is None: return self.facts default_ipv4, default_ipv6 = self.get_default_interfaces(ip_path) interfaces, ips = self.get_interfaces_info(ip_path, default_ipv4, default_ipv6) self.facts['interfaces'] = interfaces.keys() for iface in interfaces: self.facts[iface] = interfaces[iface] self.facts['default_ipv4'] = default_ipv4 self.facts['default_ipv6'] = default_ipv6 self.facts['all_ipv4_addresses'] = ips['all_ipv4_addresses'] self.facts['all_ipv6_addresses'] = ips['all_ipv6_addresses'] return self.facts def get_default_interfaces(self, ip_path): # Use the commands: # ip -4 route get 8.8.8.8 -> Google public DNS # ip -6 route get 2404:6800:400a:800::1012 -> ipv6.google.com # to find out the default outgoing interface, address, and gateway command = dict( v4 = [ip_path, '-4', 'route', 'get', '8.8.8.8'], v6 = [ip_path, '-6', 'route', 'get', '2404:6800:400a:800::1012'] ) interface = dict(v4 = {}, v6 = {}) for v in 'v4', 'v6': if v == 'v6' and self.facts['os_family'] == 'RedHat' \ and self.facts['distribution_version'].startswith('4.'): continue if v == 'v6' and not socket.has_ipv6: continue rc, out, err = self.module.run_command(command[v]) if not out: # v6 routing may result in # RTNETLINK answers: Invalid argument continue words = out.split('\n')[0].split() # A valid output starts with the queried address on the first line if len(words) > 0 and words[0] == command[v][-1]: for i in range(len(words) - 1): if words[i] == 'dev': interface[v]['interface'] = words[i+1] elif words[i] == 'src': interface[v]['address'] = words[i+1] elif words[i] == 'via' and words[i+1] != command[v][-1]: interface[v]['gateway'] = words[i+1] return interface['v4'], interface['v6'] def get_interfaces_info(self, ip_path, default_ipv4, default_ipv6): interfaces = {} ips = dict( all_ipv4_addresses = [], all_ipv6_addresses = [], ) for path in glob.glob('/sys/class/net/*'): if not os.path.isdir(path): continue device = os.path.basename(path) interfaces[device] = { 'device': device } if os.path.exists(os.path.join(path, 'address')): macaddress = get_file_content(os.path.join(path, 'address'), default='') if macaddress and macaddress != '00:00:00:00:00:00': interfaces[device]['macaddress'] = macaddress if os.path.exists(os.path.join(path, 'mtu')): interfaces[device]['mtu'] = int(get_file_content(os.path.join(path, 'mtu'))) if os.path.exists(os.path.join(path, 'operstate')): interfaces[device]['active'] = get_file_content(os.path.join(path, 'operstate')) != 'down' if os.path.exists(os.path.join(path, 'device','driver', 'module')): interfaces[device]['module'] = os.path.basename(os.path.realpath(os.path.join(path, 'device', 'driver', 'module'))) if os.path.exists(os.path.join(path, 'type')): _type = get_file_content(os.path.join(path, 'type')) if _type == '1': interfaces[device]['type'] = 'ether' elif _type == '512': interfaces[device]['type'] = 'ppp' elif _type == '772': interfaces[device]['type'] = 'loopback' if os.path.exists(os.path.join(path, 'bridge')): interfaces[device]['type'] = 'bridge' interfaces[device]['interfaces'] = [ os.path.basename(b) for b in glob.glob(os.path.join(path, 'brif', '*')) ] if os.path.exists(os.path.join(path, 'bridge', 'bridge_id')): interfaces[device]['id'] = get_file_content(os.path.join(path, 'bridge', 'bridge_id'), default='') if os.path.exists(os.path.join(path, 'bridge', 'stp_state')): interfaces[device]['stp'] = get_file_content(os.path.join(path, 'bridge', 'stp_state')) == '1' if os.path.exists(os.path.join(path, 'bonding')): interfaces[device]['type'] = 'bonding' interfaces[device]['slaves'] = get_file_content(os.path.join(path, 'bonding', 'slaves'), default='').split() interfaces[device]['mode'] = get_file_content(os.path.join(path, 'bonding', 'mode'), default='').split()[0] interfaces[device]['miimon'] = get_file_content(os.path.join(path, 'bonding', 'miimon'), default='').split()[0] interfaces[device]['lacp_rate'] = get_file_content(os.path.join(path, 'bonding', 'lacp_rate'), default='').split()[0] primary = get_file_content(os.path.join(path, 'bonding', 'primary')) if primary: interfaces[device]['primary'] = primary path = os.path.join(path, 'bonding', 'all_slaves_active') if os.path.exists(path): interfaces[device]['all_slaves_active'] = get_file_content(path) == '1' if os.path.exists(os.path.join(path,'device')): interfaces[device]['pciid'] = os.path.basename(os.readlink(os.path.join(path,'device'))) # Check whether an interface is in promiscuous mode if os.path.exists(os.path.join(path,'flags')): promisc_mode = False # The second byte indicates whether the interface is in promiscuous mode. # 1 = promisc # 0 = no promisc data = int(get_file_content(os.path.join(path, 'flags')),16) promisc_mode = (data & 0x0100 > 0) interfaces[device]['promisc'] = promisc_mode def parse_ip_output(output, secondary=False): for line in output.split('\n'): if not line: continue words = line.split() broadcast = '' if words[0] == 'inet': if '/' in words[1]: address, netmask_length = words[1].split('/') if len(words) > 3: broadcast = words[3] else: # pointopoint interfaces do not have a prefix address = words[1] netmask_length = "32" address_bin = struct.unpack('!L', socket.inet_aton(address))[0] netmask_bin = (1<<32) - (1<<32>>int(netmask_length)) netmask = socket.inet_ntoa(struct.pack('!L', netmask_bin)) network = socket.inet_ntoa(struct.pack('!L', address_bin & netmask_bin)) iface = words[-1] if iface != device: interfaces[iface] = {} if not secondary and "ipv4" not in interfaces[iface]: interfaces[iface]['ipv4'] = {'address': address, 'broadcast': broadcast, 'netmask': netmask, 'network': network} else: if "ipv4_secondaries" not in interfaces[iface]: interfaces[iface]["ipv4_secondaries"] = [] interfaces[iface]["ipv4_secondaries"].append({ 'address': address, 'broadcast': broadcast, 'netmask': netmask, 'network': network, }) # add this secondary IP to the main device if secondary: if "ipv4_secondaries" not in interfaces[device]: interfaces[device]["ipv4_secondaries"] = [] interfaces[device]["ipv4_secondaries"].append({ 'address': address, 'broadcast': broadcast, 'netmask': netmask, 'network': network, }) # If this is the default address, update default_ipv4 if 'address' in default_ipv4 and default_ipv4['address'] == address: default_ipv4['broadcast'] = broadcast default_ipv4['netmask'] = netmask default_ipv4['network'] = network default_ipv4['macaddress'] = macaddress default_ipv4['mtu'] = interfaces[device]['mtu'] default_ipv4['type'] = interfaces[device].get("type", "unknown") default_ipv4['alias'] = words[-1] if not address.startswith('127.'): ips['all_ipv4_addresses'].append(address) elif words[0] == 'inet6': address, prefix = words[1].split('/') scope = words[3] if 'ipv6' not in interfaces[device]: interfaces[device]['ipv6'] = [] interfaces[device]['ipv6'].append({ 'address' : address, 'prefix' : prefix, 'scope' : scope }) # If this is the default address, update default_ipv6 if 'address' in default_ipv6 and default_ipv6['address'] == address: default_ipv6['prefix'] = prefix default_ipv6['scope'] = scope default_ipv6['macaddress'] = macaddress default_ipv6['mtu'] = interfaces[device]['mtu'] default_ipv6['type'] = interfaces[device].get("type", "unknown") if not address == '::1': ips['all_ipv6_addresses'].append(address) ip_path = self.module.get_bin_path("ip") args = [ip_path, 'addr', 'show', 'primary', device] rc, stdout, stderr = self.module.run_command(args) primary_data = stdout args = [ip_path, 'addr', 'show', 'secondary', device] rc, stdout, stderr = self.module.run_command(args) secondary_data = stdout parse_ip_output(primary_data) parse_ip_output(secondary_data, secondary=True) # replace : by _ in interface name since they are hard to use in template new_interfaces = {} for i in interfaces: if ':' in i: new_interfaces[i.replace(':','_')] = interfaces[i] else: new_interfaces[i] = interfaces[i] return new_interfaces, ips class GenericBsdIfconfigNetwork(Network): """ This is a generic BSD subclass of Network using the ifconfig command. It defines - interfaces (a list of interface names) - interface_<name> dictionary of ipv4, ipv6, and mac address information. - all_ipv4_addresses and all_ipv6_addresses: lists of all configured addresses. It currently does not define - default_ipv4 and default_ipv6 - type, mtu and network on interfaces """ platform = 'Generic_BSD_Ifconfig' def populate(self): ifconfig_path = self.module.get_bin_path('ifconfig') if ifconfig_path is None: return self.facts route_path = self.module.get_bin_path('route') if route_path is None: return self.facts default_ipv4, default_ipv6 = self.get_default_interfaces(route_path) interfaces, ips = self.get_interfaces_info(ifconfig_path) self.merge_default_interface(default_ipv4, interfaces, 'ipv4') self.merge_default_interface(default_ipv6, interfaces, 'ipv6') self.facts['interfaces'] = interfaces.keys() for iface in interfaces: self.facts[iface] = interfaces[iface] self.facts['default_ipv4'] = default_ipv4 self.facts['default_ipv6'] = default_ipv6 self.facts['all_ipv4_addresses'] = ips['all_ipv4_addresses'] self.facts['all_ipv6_addresses'] = ips['all_ipv6_addresses'] return self.facts def get_default_interfaces(self, route_path): # Use the commands: # route -n get 8.8.8.8 -> Google public DNS # route -n get -inet6 2404:6800:400a:800::1012 -> ipv6.google.com # to find out the default outgoing interface, address, and gateway command = dict( v4 = [route_path, '-n', 'get', '8.8.8.8'], v6 = [route_path, '-n', 'get', '-inet6', '2404:6800:400a:800::1012'] ) interface = dict(v4 = {}, v6 = {}) for v in 'v4', 'v6': if v == 'v6' and not socket.has_ipv6: continue rc, out, err = self.module.run_command(command[v]) if not out: # v6 routing may result in # RTNETLINK answers: Invalid argument continue lines = out.split('\n') for line in lines: words = line.split() # Collect output from route command if len(words) > 1: if words[0] == 'interface:': interface[v]['interface'] = words[1] if words[0] == 'gateway:': interface[v]['gateway'] = words[1] return interface['v4'], interface['v6'] def get_interfaces_info(self, ifconfig_path, ifconfig_options='-a'): interfaces = {} current_if = {} ips = dict( all_ipv4_addresses = [], all_ipv6_addresses = [], ) # FreeBSD, DragonflyBSD, NetBSD, OpenBSD and OS X all implicitly add '-a' # when running the command 'ifconfig'. # Solaris must explicitly run the command 'ifconfig -a'. rc, out, err = self.module.run_command([ifconfig_path, ifconfig_options]) for line in out.split('\n'): if line: words = line.split() if words[0] == 'pass': continue elif re.match('^\S', line) and len(words) > 3: current_if = self.parse_interface_line(words) interfaces[ current_if['device'] ] = current_if elif words[0].startswith('options='): self.parse_options_line(words, current_if, ips) elif words[0] == 'nd6': self.parse_nd6_line(words, current_if, ips) elif words[0] == 'ether': self.parse_ether_line(words, current_if, ips) elif words[0] == 'media:': self.parse_media_line(words, current_if, ips) elif words[0] == 'status:': self.parse_status_line(words, current_if, ips) elif words[0] == 'lladdr': self.parse_lladdr_line(words, current_if, ips) elif words[0] == 'inet': self.parse_inet_line(words, current_if, ips) elif words[0] == 'inet6': self.parse_inet6_line(words, current_if, ips) else: self.parse_unknown_line(words, current_if, ips) return interfaces, ips def parse_interface_line(self, words): device = words[0][0:-1] current_if = {'device': device, 'ipv4': [], 'ipv6': [], 'type': 'unknown'} current_if['flags'] = self.get_options(words[1]) current_if['macaddress'] = 'unknown' # will be overwritten later if len(words) >= 5 : # Newer FreeBSD versions current_if['metric'] = words[3] current_if['mtu'] = words[5] else: current_if['mtu'] = words[3] return current_if def parse_options_line(self, words, current_if, ips): # Mac has options like this... current_if['options'] = self.get_options(words[0]) def parse_nd6_line(self, words, current_if, ips): # FreeBSD has options like this... current_if['options'] = self.get_options(words[1]) def parse_ether_line(self, words, current_if, ips): current_if['macaddress'] = words[1] def parse_media_line(self, words, current_if, ips): # not sure if this is useful - we also drop information current_if['media'] = words[1] if len(words) > 2: current_if['media_select'] = words[2] if len(words) > 3: current_if['media_type'] = words[3][1:] if len(words) > 4: current_if['media_options'] = self.get_options(words[4]) def parse_status_line(self, words, current_if, ips): current_if['status'] = words[1] def parse_lladdr_line(self, words, current_if, ips): current_if['lladdr'] = words[1] def parse_inet_line(self, words, current_if, ips): address = {'address': words[1]} # deal with hex netmask if re.match('([0-9a-f]){8}', words[3]) and len(words[3]) == 8: words[3] = '0x' + words[3] if words[3].startswith('0x'): address['netmask'] = socket.inet_ntoa(struct.pack('!L', int(words[3], base=16))) else: # otherwise assume this is a dotted quad address['netmask'] = words[3] # calculate the network address_bin = struct.unpack('!L', socket.inet_aton(address['address']))[0] netmask_bin = struct.unpack('!L', socket.inet_aton(address['netmask']))[0] address['network'] = socket.inet_ntoa(struct.pack('!L', address_bin & netmask_bin)) # broadcast may be given or we need to calculate if len(words) > 5: address['broadcast'] = words[5] else: address['broadcast'] = socket.inet_ntoa(struct.pack('!L', address_bin | (~netmask_bin & 0xffffffff))) # add to our list of addresses if not words[1].startswith('127.'): ips['all_ipv4_addresses'].append(address['address']) current_if['ipv4'].append(address) def parse_inet6_line(self, words, current_if, ips): address = {'address': words[1]} if (len(words) >= 4) and (words[2] == 'prefixlen'): address['prefix'] = words[3] if (len(words) >= 6) and (words[4] == 'scopeid'): address['scope'] = words[5] localhost6 = ['::1', '::1/128', 'fe80::1%lo0'] if address['address'] not in localhost6: ips['all_ipv6_addresses'].append(address['address']) current_if['ipv6'].append(address) def parse_unknown_line(self, words, current_if, ips): # we are going to ignore unknown lines here - this may be # a bad idea - but you can override it in your subclass pass def get_options(self, option_string): start = option_string.find('<') + 1 end = option_string.rfind('>') if (start > 0) and (end > 0) and (end > start + 1): option_csv = option_string[start:end] return option_csv.split(',') else: return [] def merge_default_interface(self, defaults, interfaces, ip_type): if not 'interface' in defaults.keys(): return if not defaults['interface'] in interfaces: return ifinfo = interfaces[defaults['interface']] # copy all the interface values across except addresses for item in ifinfo.keys(): if item != 'ipv4' and item != 'ipv6': defaults[item] = ifinfo[item] if len(ifinfo[ip_type]) > 0: for item in ifinfo[ip_type][0].keys(): defaults[item] = ifinfo[ip_type][0][item] class HPUXNetwork(Network): """ HP-UX-specifig subclass of Network. Defines networking facts: - default_interface - interfaces (a list of interface names) - interface_<name> dictionary of ipv4 address information. """ platform = 'HP-UX' def populate(self): netstat_path = self.module.get_bin_path('netstat') if netstat_path is None: return self.facts self.get_default_interfaces() interfaces = self.get_interfaces_info() self.facts['interfaces'] = interfaces.keys() for iface in interfaces: self.facts[iface] = interfaces[iface] return self.facts def get_default_interfaces(self): rc, out, err = self.module.run_command("/usr/bin/netstat -nr") lines = out.split('\n') for line in lines: words = line.split() if len(words) > 1: if words[0] == 'default': self.facts['default_interface'] = words[4] self.facts['default_gateway'] = words[1] def get_interfaces_info(self): interfaces = {} rc, out, err = self.module.run_command("/usr/bin/netstat -ni") lines = out.split('\n') for line in lines: words = line.split() for i in range(len(words) - 1): if words[i][:3] == 'lan': device = words[i] interfaces[device] = { 'device': device } address = words[i+3] interfaces[device]['ipv4'] = { 'address': address } network = words[i+2] interfaces[device]['ipv4'] = { 'network': network, 'interface': device, 'address': address } return interfaces class DarwinNetwork(GenericBsdIfconfigNetwork): """ This is the Mac OS X/Darwin Network Class. It uses the GenericBsdIfconfigNetwork unchanged """ platform = 'Darwin' # media line is different to the default FreeBSD one def parse_media_line(self, words, current_if, ips): # not sure if this is useful - we also drop information current_if['media'] = 'Unknown' # Mac does not give us this current_if['media_select'] = words[1] if len(words) > 2: # MacOSX sets the media to '<unknown type>' for bridge interface # and parsing splits this into two words; this if/else helps if words[1] == '<unknown' and words[2] == 'type>': current_if['media_select'] = 'Unknown' current_if['media_type'] = 'unknown type' else: current_if['media_type'] = words[2][1:-1] if len(words) > 3: current_if['media_options'] = self.get_options(words[3]) class FreeBSDNetwork(GenericBsdIfconfigNetwork): """ This is the FreeBSD Network Class. It uses the GenericBsdIfconfigNetwork unchanged. """ platform = 'FreeBSD' class DragonFlyNetwork(GenericBsdIfconfigNetwork): """ This is the DragonFly Network Class. It uses the GenericBsdIfconfigNetwork unchanged. """ platform = 'DragonFly' class AIXNetwork(GenericBsdIfconfigNetwork): """ This is the AIX Network Class. It uses the GenericBsdIfconfigNetwork unchanged. """ platform = 'AIX' def get_default_interfaces(self, route_path): netstat_path = self.module.get_bin_path('netstat') rc, out, err = self.module.run_command([netstat_path, '-nr']) interface = dict(v4 = {}, v6 = {}) lines = out.split('\n') for line in lines: words = line.split() if len(words) > 1 and words[0] == 'default': if '.' in words[1]: interface['v4']['gateway'] = words[1] interface['v4']['interface'] = words[5] elif ':' in words[1]: interface['v6']['gateway'] = words[1] interface['v6']['interface'] = words[5] return interface['v4'], interface['v6'] # AIX 'ifconfig -a' does not have three words in the interface line def get_interfaces_info(self, ifconfig_path, ifconfig_options='-a'): interfaces = {} current_if = {} ips = dict( all_ipv4_addresses = [], all_ipv6_addresses = [], ) rc, out, err = self.module.run_command([ifconfig_path, ifconfig_options]) for line in out.split('\n'): if line: words = line.split() # only this condition differs from GenericBsdIfconfigNetwork if re.match('^\w*\d*:', line): current_if = self.parse_interface_line(words) interfaces[ current_if['device'] ] = current_if elif words[0].startswith('options='): self.parse_options_line(words, current_if, ips) elif words[0] == 'nd6': self.parse_nd6_line(words, current_if, ips) elif words[0] == 'ether': self.parse_ether_line(words, current_if, ips) elif words[0] == 'media:': self.parse_media_line(words, current_if, ips) elif words[0] == 'status:': self.parse_status_line(words, current_if, ips) elif words[0] == 'lladdr': self.parse_lladdr_line(words, current_if, ips) elif words[0] == 'inet': self.parse_inet_line(words, current_if, ips) elif words[0] == 'inet6': self.parse_inet6_line(words, current_if, ips) else: self.parse_unknown_line(words, current_if, ips) uname_path = self.module.get_bin_path('uname') if uname_path: rc, out, err = self.module.run_command([uname_path, '-W']) # don't bother with wpars it does not work # zero means not in wpar if not rc and out.split()[0] == '0': if current_if['macaddress'] == 'unknown' and re.match('^en', current_if['device']): entstat_path = self.module.get_bin_path('entstat') if entstat_path: rc, out, err = self.module.run_command([entstat_path, current_if['device'] ]) if rc != 0: break for line in out.split('\n'): if not line: pass buff = re.match('^Hardware Address: (.*)', line) if buff: current_if['macaddress'] = buff.group(1) buff = re.match('^Device Type:', line) if buff and re.match('.*Ethernet', line): current_if['type'] = 'ether' # device must have mtu attribute in ODM if 'mtu' not in current_if: lsattr_path = self.module.get_bin_path('lsattr') if lsattr_path: rc, out, err = self.module.run_command([lsattr_path,'-El', current_if['device'] ]) if rc != 0: break for line in out.split('\n'): if line: words = line.split() if words[0] == 'mtu': current_if['mtu'] = words[1] return interfaces, ips # AIX 'ifconfig -a' does not inform about MTU, so remove current_if['mtu'] here def parse_interface_line(self, words): device = words[0][0:-1] current_if = {'device': device, 'ipv4': [], 'ipv6': [], 'type': 'unknown'} current_if['flags'] = self.get_options(words[1]) current_if['macaddress'] = 'unknown' # will be overwritten later return current_if class OpenBSDNetwork(GenericBsdIfconfigNetwork): """ This is the OpenBSD Network Class. It uses the GenericBsdIfconfigNetwork. """ platform = 'OpenBSD' # OpenBSD 'ifconfig -a' does not have information about aliases def get_interfaces_info(self, ifconfig_path, ifconfig_options='-aA'): return super(OpenBSDNetwork, self).get_interfaces_info(ifconfig_path, ifconfig_options) # Return macaddress instead of lladdr def parse_lladdr_line(self, words, current_if, ips): current_if['macaddress'] = words[1] class SunOSNetwork(GenericBsdIfconfigNetwork): """ This is the SunOS Network Class. It uses the GenericBsdIfconfigNetwork. Solaris can have different FLAGS and MTU for IPv4 and IPv6 on the same interface so these facts have been moved inside the 'ipv4' and 'ipv6' lists. """ platform = 'SunOS' # Solaris 'ifconfig -a' will print interfaces twice, once for IPv4 and again for IPv6. # MTU and FLAGS also may differ between IPv4 and IPv6 on the same interface. # 'parse_interface_line()' checks for previously seen interfaces before defining # 'current_if' so that IPv6 facts don't clobber IPv4 facts (or vice versa). def get_interfaces_info(self, ifconfig_path): interfaces = {} current_if = {} ips = dict( all_ipv4_addresses = [], all_ipv6_addresses = [], ) rc, out, err = self.module.run_command([ifconfig_path, '-a']) for line in out.split('\n'): if line: words = line.split() if re.match('^\S', line) and len(words) > 3: current_if = self.parse_interface_line(words, current_if, interfaces) interfaces[ current_if['device'] ] = current_if elif words[0].startswith('options='): self.parse_options_line(words, current_if, ips) elif words[0] == 'nd6': self.parse_nd6_line(words, current_if, ips) elif words[0] == 'ether': self.parse_ether_line(words, current_if, ips) elif words[0] == 'media:': self.parse_media_line(words, current_if, ips) elif words[0] == 'status:': self.parse_status_line(words, current_if, ips) elif words[0] == 'lladdr': self.parse_lladdr_line(words, current_if, ips) elif words[0] == 'inet': self.parse_inet_line(words, current_if, ips) elif words[0] == 'inet6': self.parse_inet6_line(words, current_if, ips) else: self.parse_unknown_line(words, current_if, ips) # 'parse_interface_line' and 'parse_inet*_line' leave two dicts in the # ipv4/ipv6 lists which is ugly and hard to read. # This quick hack merges the dictionaries. Purely cosmetic. for iface in interfaces: for v in 'ipv4', 'ipv6': combined_facts = {} for facts in interfaces[iface][v]: combined_facts.update(facts) if len(combined_facts.keys()) > 0: interfaces[iface][v] = [combined_facts] return interfaces, ips def parse_interface_line(self, words, current_if, interfaces): device = words[0][0:-1] if device not in interfaces.keys(): current_if = {'device': device, 'ipv4': [], 'ipv6': [], 'type': 'unknown'} else: current_if = interfaces[device] flags = self.get_options(words[1]) v = 'ipv4' if 'IPv6' in flags: v = 'ipv6' current_if[v].append({'flags': flags, 'mtu': words[3]}) current_if['macaddress'] = 'unknown' # will be overwritten later return current_if # Solaris displays single digit octets in MAC addresses e.g. 0:1:2:d:e:f # Add leading zero to each octet where needed. def parse_ether_line(self, words, current_if, ips): macaddress = '' for octet in words[1].split(':'): octet = ('0' + octet)[-2:None] macaddress += (octet + ':') current_if['macaddress'] = macaddress[0:-1] class Virtual(Facts): """ This is a generic Virtual subclass of Facts. This should be further subclassed to implement per platform. If you subclass this, you should define: - virtualization_type - virtualization_role - container (e.g. solaris zones, freebsd jails, linux containers) All subclasses MUST define platform. """ def __new__(cls, *arguments, **keyword): subclass = cls for sc in get_all_subclasses(Virtual): if sc.platform == platform.system(): subclass = sc return super(cls, subclass).__new__(subclass, *arguments, **keyword) def populate(self): return self.facts class LinuxVirtual(Virtual): """ This is a Linux-specific subclass of Virtual. It defines - virtualization_type - virtualization_role """ platform = 'Linux' def populate(self): self.get_virtual_facts() return self.facts # For more information, check: http://people.redhat.com/~rjones/virt-what/ def get_virtual_facts(self): if os.path.exists('/proc/1/cgroup'): for line in get_file_lines('/proc/1/cgroup'): if re.search(r'/docker(/|-[0-9a-f]+\.scope)', line): self.facts['virtualization_type'] = 'docker' self.facts['virtualization_role'] = 'guest' return if re.search('/lxc/', line): self.facts['virtualization_type'] = 'lxc' self.facts['virtualization_role'] = 'guest' return if os.path.exists('/proc/vz'): self.facts['virtualization_type'] = 'openvz' if os.path.exists('/proc/bc'): self.facts['virtualization_role'] = 'host' else: self.facts['virtualization_role'] = 'guest' return systemd_container = get_file_content('/run/systemd/container') if systemd_container: self.facts['virtualization_type'] = systemd_container self.facts['virtualization_role'] = 'guest' return if os.path.exists("/proc/xen"): self.facts['virtualization_type'] = 'xen' self.facts['virtualization_role'] = 'guest' try: for line in get_file_lines('/proc/xen/capabilities'): if "control_d" in line: self.facts['virtualization_role'] = 'host' except IOError: pass return product_name = get_file_content('/sys/devices/virtual/dmi/id/product_name') if product_name in ['KVM', 'Bochs']: self.facts['virtualization_type'] = 'kvm' self.facts['virtualization_role'] = 'guest' return if product_name == 'RHEV Hypervisor': self.facts['virtualization_type'] = 'RHEV' self.facts['virtualization_role'] = 'guest' return if product_name == 'VMware Virtual Platform': self.facts['virtualization_type'] = 'VMware' self.facts['virtualization_role'] = 'guest' return bios_vendor = get_file_content('/sys/devices/virtual/dmi/id/bios_vendor') if bios_vendor == 'Xen': self.facts['virtualization_type'] = 'xen' self.facts['virtualization_role'] = 'guest' return if bios_vendor == 'innotek GmbH': self.facts['virtualization_type'] = 'virtualbox' self.facts['virtualization_role'] = 'guest' return sys_vendor = get_file_content('/sys/devices/virtual/dmi/id/sys_vendor') # FIXME: This does also match hyperv if sys_vendor == 'Microsoft Corporation': self.facts['virtualization_type'] = 'VirtualPC' self.facts['virtualization_role'] = 'guest' return if sys_vendor == 'Parallels Software International Inc.': self.facts['virtualization_type'] = 'parallels' self.facts['virtualization_role'] = 'guest' return if sys_vendor == 'QEMU': self.facts['virtualization_type'] = 'kvm' self.facts['virtualization_role'] = 'guest' return if sys_vendor == 'oVirt': self.facts['virtualization_type'] = 'kvm' self.facts['virtualization_role'] = 'guest' return if os.path.exists('/proc/self/status'): for line in get_file_lines('/proc/self/status'): if re.match('^VxID: \d+', line): self.facts['virtualization_type'] = 'linux_vserver' if re.match('^VxID: 0', line): self.facts['virtualization_role'] = 'host' else: self.facts['virtualization_role'] = 'guest' return if os.path.exists('/proc/cpuinfo'): for line in get_file_lines('/proc/cpuinfo'): if re.match('^model name.*QEMU Virtual CPU', line): self.facts['virtualization_type'] = 'kvm' elif re.match('^vendor_id.*User Mode Linux', line): self.facts['virtualization_type'] = 'uml' elif re.match('^model name.*UML', line): self.facts['virtualization_type'] = 'uml' elif re.match('^vendor_id.*PowerVM Lx86', line): self.facts['virtualization_type'] = 'powervm_lx86' elif re.match('^vendor_id.*IBM/S390', line): self.facts['virtualization_type'] = 'PR/SM' lscpu = self.module.get_bin_path('lscpu') if lscpu: rc, out, err = self.module.run_command(["lscpu"]) if rc == 0: for line in out.split("\n"): data = line.split(":", 1) key = data[0].strip() if key == 'Hypervisor': self.facts['virtualization_type'] = data[1].strip() else: self.facts['virtualization_type'] = 'ibm_systemz' else: continue if self.facts['virtualization_type'] == 'PR/SM': self.facts['virtualization_role'] = 'LPAR' else: self.facts['virtualization_role'] = 'guest' return # Beware that we can have both kvm and virtualbox running on a single system if os.path.exists("/proc/modules") and os.access('/proc/modules', os.R_OK): modules = [] for line in get_file_lines("/proc/modules"): data = line.split(" ", 1) modules.append(data[0]) if 'kvm' in modules: self.facts['virtualization_type'] = 'kvm' self.facts['virtualization_role'] = 'host' return if 'vboxdrv' in modules: self.facts['virtualization_type'] = 'virtualbox' self.facts['virtualization_role'] = 'host' return # If none of the above matches, return 'NA' for virtualization_type # and virtualization_role. This allows for proper grouping. self.facts['virtualization_type'] = 'NA' self.facts['virtualization_role'] = 'NA' return class FreeBSDVirtual(Virtual): """ This is a FreeBSD-specific subclass of Virtual. It defines - virtualization_type - virtualization_role """ platform = 'FreeBSD' def populate(self): self.get_virtual_facts() return self.facts def get_virtual_facts(self): self.facts['virtualization_type'] = '' self.facts['virtualization_role'] = '' class DragonFlyVirtual(FreeBSDVirtual): pass class OpenBSDVirtual(Virtual): """ This is a OpenBSD-specific subclass of Virtual. It defines - virtualization_type - virtualization_role """ platform = 'OpenBSD' def populate(self): self.get_virtual_facts() return self.facts def get_virtual_facts(self): self.facts['virtualization_type'] = '' self.facts['virtualization_role'] = '' class HPUXVirtual(Virtual): """ This is a HP-UX specific subclass of Virtual. It defines - virtualization_type - virtualization_role """ platform = 'HP-UX' def populate(self): self.get_virtual_facts() return self.facts def get_virtual_facts(self): if os.path.exists('/usr/sbin/vecheck'): rc, out, err = self.module.run_command("/usr/sbin/vecheck") if rc == 0: self.facts['virtualization_type'] = 'guest' self.facts['virtualization_role'] = 'HP vPar' if os.path.exists('/opt/hpvm/bin/hpvminfo'): rc, out, err = self.module.run_command("/opt/hpvm/bin/hpvminfo") if rc == 0 and re.match('.*Running.*HPVM vPar.*', out): self.facts['virtualization_type'] = 'guest' self.facts['virtualization_role'] = 'HPVM vPar' elif rc == 0 and re.match('.*Running.*HPVM guest.*', out): self.facts['virtualization_type'] = 'guest' self.facts['virtualization_role'] = 'HPVM IVM' elif rc == 0 and re.match('.*Running.*HPVM host.*', out): self.facts['virtualization_type'] = 'host' self.facts['virtualization_role'] = 'HPVM' if os.path.exists('/usr/sbin/parstatus'): rc, out, err = self.module.run_command("/usr/sbin/parstatus") if rc == 0: self.facts['virtualization_type'] = 'guest' self.facts['virtualization_role'] = 'HP nPar' class SunOSVirtual(Virtual): """ This is a SunOS-specific subclass of Virtual. It defines - virtualization_type - virtualization_role - container """ platform = 'SunOS' def populate(self): self.get_virtual_facts() return self.facts def get_virtual_facts(self): rc, out, err = self.module.run_command("/usr/sbin/prtdiag") for line in out.split('\n'): if 'VMware' in line: self.facts['virtualization_type'] = 'vmware' self.facts['virtualization_role'] = 'guest' if 'Parallels' in line: self.facts['virtualization_type'] = 'parallels' self.facts['virtualization_role'] = 'guest' if 'VirtualBox' in line: self.facts['virtualization_type'] = 'virtualbox' self.facts['virtualization_role'] = 'guest' if 'HVM domU' in line: self.facts['virtualization_type'] = 'xen' self.facts['virtualization_role'] = 'guest' # Check if it's a zone if os.path.exists("/usr/bin/zonename"): rc, out, err = self.module.run_command("/usr/bin/zonename") if out.rstrip() != "global": self.facts['container'] = 'zone' # Check if it's a branded zone (i.e. Solaris 8/9 zone) if os.path.isdir('/.SUNWnative'): self.facts['container'] = 'zone' # If it's a zone check if we can detect if our global zone is itself virtualized. # Relies on the "guest tools" (e.g. vmware tools) to be installed if 'container' in self.facts and self.facts['container'] == 'zone': rc, out, err = self.module.run_command("/usr/sbin/modinfo") for line in out.split('\n'): if 'VMware' in line: self.facts['virtualization_type'] = 'vmware' self.facts['virtualization_role'] = 'guest' if 'VirtualBox' in line: self.facts['virtualization_type'] = 'virtualbox' self.facts['virtualization_role'] = 'guest' # Detect domaining on Sparc hardware if os.path.exists("/usr/sbin/virtinfo"): # The output of virtinfo is different whether we are on a machine with logical # domains ('LDoms') on a T-series or domains ('Domains') on a M-series. Try LDoms first. rc, out, err = self.module.run_command("/usr/sbin/virtinfo -p") # The output contains multiple lines with different keys like this: # DOMAINROLE|impl=LDoms|control=false|io=false|service=false|root=false # The output may also be not formatted and the returncode is set to 0 regardless of the error condition: # virtinfo can only be run from the global zone try: for line in out.split('\n'): fields = line.split('|') if( fields[0] == 'DOMAINROLE' and fields[1] == 'impl=LDoms' ): self.facts['virtualization_type'] = 'ldom' self.facts['virtualization_role'] = 'guest' hostfeatures = [] for field in fields[2:]: arg = field.split('=') if( arg[1] == 'true' ): hostfeatures.append(arg[0]) if( len(hostfeatures) > 0 ): self.facts['virtualization_role'] = 'host (' + ','.join(hostfeatures) + ')' except ValueError: pass class Ohai(Facts): """ This is a subclass of Facts for including information gathered from Ohai. """ def populate(self): self.run_ohai() return self.facts def run_ohai(self): ohai_path = self.module.get_bin_path('ohai') if ohai_path is None: return rc, out, err = self.module.run_command(ohai_path) try: self.facts.update(json.loads(out)) except: pass class Facter(Facts): """ This is a subclass of Facts for including information gathered from Facter. """ def populate(self): self.run_facter() return self.facts def run_facter(self): facter_path = self.module.get_bin_path('facter', opt_dirs=['/opt/puppetlabs/bin']) cfacter_path = self.module.get_bin_path('cfacter', opt_dirs=['/opt/puppetlabs/bin']) # Prefer to use cfacter if available if cfacter_path is not None: facter_path = cfacter_path if facter_path is None: return # if facter is installed, and we can use --json because # ruby-json is ALSO installed, include facter data in the JSON rc, out, err = self.module.run_command(facter_path + " --puppet --json") try: self.facts = json.loads(out) except: pass def get_file_content(path, default=None, strip=True): data = default if os.path.exists(path) and os.access(path, os.R_OK): try: try: datafile = open(path) data = datafile.read() if strip: data = data.strip() if len(data) == 0: data = default finally: datafile.close() except: # ignore errors as some jails/containers might have readable permissions but not allow reads to proc # done in 2 blocks for 2.4 compat pass return data def get_file_lines(path): '''get list of lines from file''' data = get_file_content(path) if data: ret = data.splitlines() else: ret = [] return ret def ansible_facts(module, gather_subset): facts = {} facts['gather_subset'] = list(gather_subset) facts.update(Facts(module).populate()) for subset in gather_subset: facts.update(FACT_SUBSETS[subset](module, load_on_init=False, cached_facts=facts).populate()) return facts def get_all_facts(module): setup_options = dict(module_setup=True) # Retrieve module parameters gather_subset = module.params['gather_subset'] # Retrieve all facts elements additional_subsets = set() exclude_subsets = set() for subset in gather_subset: if subset == 'all': additional_subsets.update(VALID_SUBSETS) continue if subset.startswith('!'): subset = subset[1:] if subset == 'all': exclude_subsets.update(VALID_SUBSETS) continue exclude = True else: exclude = False if subset not in VALID_SUBSETS: raise TypeError("Bad subset '%s' given to Ansible. gather_subset options allowed: all, %s" % (subset, ", ".join(FACT_SUBSETS.keys()))) if exclude: exclude_subsets.add(subset) else: additional_subsets.add(subset) if not additional_subsets: additional_subsets.update(VALID_SUBSETS) additional_subsets.difference_update(exclude_subsets) # facter and ohai are given a different prefix than other subsets if 'facter' in additional_subsets: additional_subsets.difference_update(('facter',)) facter_ds = FACT_SUBSETS['facter'](module, load_on_init=False).populate() if facter_ds: for (k, v) in facter_ds.items(): setup_options['facter_%s' % k.replace('-', '_')] = v if 'ohai' in additional_subsets: additional_subsets.difference_update(('ohai',)) ohai_ds = FACT_SUBSETS['ohai'](module, load_on_init=False).populate() if ohai_ds: for (k, v) in ohai_ds.items(): setup_options['ohai_%s' % k.replace('-', '_')] = v facts = ansible_facts(module, additional_subsets) for (k, v) in facts.items(): setup_options["ansible_%s" % k.replace('-', '_')] = v setup_result = { 'ansible_facts': {} } for (k,v) in setup_options.items(): if module.params['filter'] == '*' or fnmatch.fnmatch(k, module.params['filter']): setup_result['ansible_facts'][k] = v # hack to keep --verbose from showing all the setup module results setup_result['_ansible_verbose_override'] = True return setup_result # Allowed fact subset for gather_subset options and what classes they use # Note: have to define this at the bottom as it references classes defined earlier in this file FACT_SUBSETS = dict( hardware=Hardware, network=Network, virtual=Virtual, ohai=Ohai, facter=Facter, ) VALID_SUBSETS = frozenset(FACT_SUBSETS.keys()) ```
[ { "content": "```python\n# -*- coding: utf-8 -*-\nimport heapq # used for the so colled \"open list\" that stores known nodes\nimport time # for time limitation\nfrom pathfinding.core.util import SQRT2\nfrom pathfinding.core.diagonal_movement import DiagonalMovement\n\n\n# max. amount of tries we iterate unti...
[ { "content": "<|memory_start|>```python\n# -*- coding: utf-8 -*-\nimport heapq # used for the so colled \"open list\" that stores known nodes\nimport time # for time limitation\nfrom pathfinding.core.util import SQRT2\nfrom pathfinding.core.diagonal_movement import DiagonalMovement\n\n\n# max. amount of tries...
```python # -*- coding: utf-8 -*- import heapq # used for the so colled "open list" that stores known nodes import time # for time limitation from pathfinding.core.util import SQRT2 from pathfinding.core.diagonal_movement import DiagonalMovement # max. amount of tries we iterate until we abort the search MAX_RUNS = float('inf') # max. time after we until we abort the search (in seconds) TIME_LIMIT = float('inf') # used for backtrace of bi-directional A* BY_START = 1 BY_END = 2 class ExecutionTimeException(Exception): def __init__(self, message): super(ExecutionTimeException, self).__init__(message) class ExecutionRunsException(Exception): def __init__(self, message): super(ExecutionRunsException, self).__init__(message) class Finder(object): def __init__(self, heuristic=None, weight=1, diagonal_movement=DiagonalMovement.never, weighted=True, time_limit=TIME_LIMIT, max_runs=MAX_RUNS): """ find shortest path :param heuristic: heuristic used to calculate distance of 2 points (defaults to manhattan) :param weight: weight for the edges :param diagonal_movement: if diagonal movement is allowed (see enum in diagonal_movement) :param weighted: the algorithm supports weighted nodes (should be True for A* and Dijkstra) :param time_limit: max. runtime in seconds :param max_runs: max. amount of tries until we abort the search (optional, only if we enter huge grids and have time constrains) <=0 means there are no constrains and the code might run on any large map. """ self.time_limit = time_limit self.max_runs = max_runs self.weighted = weighted self.diagonal_movement = diagonal_movement self.weight = weight self.heuristic = heuristic def calc_cost(self, node_a, node_b): """ get the distance between current node and the neighbor (cost) """ if node_b.x - node_a.x == 0 or node_b.y - node_a.y == 0: # direct neighbor - distance is 1 ng = 1 else: # not a direct neighbor - diagonal movement ng = SQRT2 # weight for weighted algorithms if self.weighted: ng *= node_b.weight return node_a.g + ng def apply_heuristic(self, node_a, node_b, heuristic=None): """ helper function to apply heuristic """ if not heuristic: heuristic = self.heuristic return heuristic( abs(node_a.x - node_b.x), abs(node_a.y - node_b.y)) def find_neighbors(self, grid, node, diagonal_movement=None): ''' find neighbor, same for Djikstra, A*, Bi-A*, IDA* ''' if not diagonal_movement: diagonal_movement = self.diagonal_movement return grid.neighbors(node, diagonal_movement=diagonal_movement) def keep_running(self): """ check, if we run into time or iteration constrains. :returns: True if we keep running and False if we run into a constraint """ if self.runs >= self.max_runs: raise ExecutionRunsException( '{} run into barrier of {} iterations without ' 'finding the destination'.format( self.__class__.__name__, self.max_runs)) if time.time() - self.start_time >= self.time_limit: raise ExecutionTimeException( '{} took longer than {} seconds, aborting!'.format( self.__class__.__name__, self.time_limit)) def process_node(self, node, parent, end, open_list, open_value=True): ''' we check if the given node is path of the path by calculating its cost and add or remove it from our path :param node: the node we like to test (the neighbor in A* or jump-node in JumpPointSearch) :param parent: the parent node (the current node we like to test) :param end: the end point to calculate the cost of the path :param open_list: the list that keeps track of our current path :param open_value: needed if we like to set the open list to something else than True (used for bi-directional algorithms) ''' # calculate cost from current node (parent) to the next node (neighbor) ng = self.calc_cost(parent, node) if not node.opened or ng < node.g: node.g = ng node.h = node.h or \ self.apply_heuristic(node, end) * self.weight # f is the estimated total cost from start to goal node.f = node.g + node.h node.parent = parent if not node.opened: heapq.heappush(open_list, node) node.opened = open_value else: # the node can be reached with smaller cost. # Since its f value has been updated, we have to # update its position in the open list open_list.remove(node) heapq.heappush(open_list, node) def check_neighbors(self, start, end, grid, open_list, open_value=True, backtrace_by=None): """ find next path segment based on given node (or return path if we found the end) :param start: start node :param end: end node :param grid: grid that stores all possible steps/tiles as 2D-list :param open_list: stores nodes that will be processed next """ raise NotImplementedError( 'Please implement check_neighbors in your finder') def find_path(self, start, end, grid): """ find a path from start to end node on grid by iterating over all neighbors of a node (see check_neighbors) :param start: start node :param end: end node :param grid: grid that stores all possible steps/tiles as 2D-list :return: """ self.start_time = time.time() # execution time limitation self.runs = 0 # count number of iterations start.opened = True open_list = [start] while len(open_list) > 0: self.runs += 1 self.keep_running() path = self.check_neighbors(start, end, grid, open_list) if path: return path, self.runs # failed to find path return [], self.runs ```
[ { "content": "```python\nimport cv2\r\nimport numpy as np\r\nimport time\r\nfrom matplotlib import pyplot as plt\r\n\r\nx = 0\r\ny = 0\r\n\r\n\r\ndef makematchpicture(Grayurl):\r\n img = cv2.imread(Grayurl, 0)\r\n img2 = img.copy()\r\n template = cv2.imread('test.png', 0)\r\n w, h = template.shape[:...
[ { "content": "<|memory_start|>```python\nimport cv2\r\nimport numpy as np\r\nimport time\r\nfrom matplotlib import pyplot as plt\r\n\r\nx = 0\r\ny = 0\r\n\r\n\r\ndef makematchpicture(Grayurl):\r\n img = cv2.imread(Grayurl, 0)\r\n img2 = img.copy()\r\n template = cv2.imread('test.png', 0)\r\n w, h = ...
```python import cv2 import numpy as np import time from matplotlib import pyplot as plt x = 0 y = 0 def makematchpicture(Grayurl): img = cv2.imread(Grayurl, 0) img2 = img.copy() template = cv2.imread('test.png', 0) w, h = template.shape[::-1] methods = ['cv2.TM_SQDIFF'] for meth in methods: img = img2.copy() method = eval(meth) # Apply template Matching res = cv2.matchTemplate(img, template, method) min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res) # If the method is TM_SQDIFF or TM_SQDIFF_NORMED, take minimum if method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]: top_left = min_loc else: top_left = max_loc bottom_right = (top_left[0] + w, top_left[1] + h) print("模板匹配:",int(top_left[0] + w / 2), int(top_left[1] + h / 2)) cv2.rectangle(img, top_left, bottom_right, 255, 2) plt.figure() plt.subplot(121), plt.imshow(res, cmap='gray') plt.title('Matching Result'), plt.xticks([]), plt.yticks([]) plt.subplot(122), plt.imshow(img, cmap='gray') plt.title('Detected Point'), plt.xticks([]), plt.yticks([]) plt.suptitle(meth) global x global y x = int(top_left[0] + w / 2) y = int(top_left[1] + h / 2) ```
[ { "content": "Here is the code block:\n```python\n# coding=utf-8\n#\n# Licensed to the Apache Software Foundation (ASF) under one or more\n# contributor license agreements. See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file ...
[ { "content": "Here is the code block:\n<|memory_start|>```python\n# coding=utf-8\n#\n# Licensed to the Apache Software Foundation (ASF) under one or more\n# contributor license agreements. See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF lic...
```python # coding=utf-8 # # 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 absolute_import from __future__ import print_function import unittest import mock from apache_beam.examples.snippets.util import assert_matches_stdout from apache_beam.testing.test_pipeline import TestPipeline from . import tostring def check_plants(actual): expected = '''[START plants] 🍓,Strawberry 🥕,Carrot 🍆,Eggplant 🍅,Tomato 🥔,Potato [END plants]'''.splitlines()[1:-1] assert_matches_stdout(actual, expected) def check_plant_lists(actual): expected = '''[START plant_lists] ['🍓', 'Strawberry', 'perennial'] ['🥕', 'Carrot', 'biennial'] ['🍆', 'Eggplant', 'perennial'] ['🍅', 'Tomato', 'annual'] ['🥔', 'Potato', 'perennial'] [END plant_lists]'''.splitlines()[1:-1] assert_matches_stdout(actual, expected) def check_plants_csv(actual): expected = '''[START plants_csv] 🍓,Strawberry,perennial 🥕,Carrot,biennial 🍆,Eggplant,perennial 🍅,Tomato,annual 🥔,Potato,perennial [END plants_csv]'''.splitlines()[1:-1] assert_matches_stdout(actual, expected) @mock.patch('apache_beam.Pipeline', TestPipeline) @mock.patch( 'apache_beam.examples.snippets.transforms.elementwise.tostring.print', str) class ToStringTest(unittest.TestCase): def test_tostring_kvs(self): tostring.tostring_kvs(check_plants) def test_tostring_element(self): tostring.tostring_element(check_plant_lists) def test_tostring_iterables(self): tostring.tostring_iterables(check_plants_csv) if __name__ == '__main__': unittest.main() ```
[ { "content": "Return the code exactly, with no changes:\n```python\n# This Source Code Form is subject to the terms of the Mozilla Public\n# License, v. 2.0. If a copy of the MPL was not distributed with this file,\n# You can obtain one at http://mozilla.org/MPL/2.0/.\n\n# This modules provides functionality fo...
[ { "content": "Return the code exactly, with no changes:\n<|memory_start|>```python\n# This Source Code Form is subject to the terms of the Mozilla Public\n# License, v. 2.0. If a copy of the MPL was not distributed with this file,\n# You can obtain one at http://mozilla.org/MPL/2.0/.\n\n# This modules provides ...
```python # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/. # This modules provides functionality for dealing with code completion. from __future__ import absolute_import, print_function import os import types from mozbuild.backend.common import CommonBackend from mozbuild.frontend.data import ( ComputedFlags, Sources, GeneratedSources, DirectoryTraversal, PerSourceFlag, VariablePassthru, ) from mozbuild.shellutil import ( quote as shell_quote, ) from mozbuild.util import expand_variables import mozpack.path as mozpath from collections import ( defaultdict, OrderedDict, ) class CompileDBBackend(CommonBackend): def _init(self): CommonBackend._init(self) # The database we're going to dump out to. self._db = OrderedDict() # The cache for per-directory flags self._flags = {} self._envs = {} self._local_flags = defaultdict(dict) self._per_source_flags = defaultdict(list) def consume_object(self, obj): # Those are difficult directories, that will be handled later. if obj.relsrcdir in ( 'build/unix/elfhack', 'build/unix/elfhack/inject', 'build/clang-plugin', 'build/clang-plugin/tests'): return True consumed = CommonBackend.consume_object(self, obj) if consumed: return True if isinstance(obj, DirectoryTraversal): self._envs[obj.objdir] = obj.config elif isinstance(obj, (Sources, GeneratedSources)): # For other sources, include each source file. for f in obj.files: self._build_db_line(obj.objdir, obj.relsrcdir, obj.config, f, obj.canonical_suffix) elif isinstance(obj, VariablePassthru): for var in ('MOZBUILD_CMFLAGS', 'MOZBUILD_CMMFLAGS'): if var in obj.variables: self._local_flags[obj.objdir][var] = obj.variables[var] elif isinstance(obj, PerSourceFlag): self._per_source_flags[obj.file_name].extend(obj.flags) elif isinstance(obj, ComputedFlags): for var, flags in obj.get_flags(): self._local_flags[obj.objdir]['COMPUTED_%s' % var] = flags return True def consume_finished(self): CommonBackend.consume_finished(self) db = [] for (directory, filename, unified), cmd in self._db.iteritems(): env = self._envs[directory] cmd = list(cmd) if unified is None: cmd.append(filename) else: cmd.append(unified) variables = { 'DIST': mozpath.join(env.topobjdir, 'dist'), 'DEPTH': env.topobjdir, 'MOZILLA_DIR': env.topsrcdir, 'topsrcdir': env.topsrcdir, 'topobjdir': env.topobjdir, } variables.update(self._local_flags[directory]) c = [] for a in cmd: a = expand_variables(a, variables).split() if not a: continue if isinstance(a, types.StringTypes): c.append(a) else: c.extend(a) per_source_flags = self._per_source_flags.get(filename) if per_source_flags is not None: c.extend(per_source_flags) db.append({ 'directory': directory, 'command': ' '.join(shell_quote(a) for a in c), 'file': mozpath.join(directory, filename), }) import json # Output the database (a JSON file) to objdir/compile_commands.json outputfile = os.path.join(self.environment.topobjdir, 'compile_commands.json') with self._write_file(outputfile) as jsonout: json.dump(db, jsonout, indent=0) def _process_unified_sources(self, obj): if not obj.have_unified_mapping: for f in list(sorted(obj.files)): self._build_db_line(obj.objdir, obj.relsrcdir, obj.config, f, obj.canonical_suffix) return # For unified sources, only include the unified source file. # Note that unified sources are never used for host sources. for f in obj.unified_source_mapping: self._build_db_line(obj.objdir, obj.relsrcdir, obj.config, f[0], obj.canonical_suffix) for entry in f[1]: self._build_db_line(obj.objdir, obj.relsrcdir, obj.config, entry, obj.canonical_suffix, unified=f[0]) def _handle_idl_manager(self, idl_manager): pass def _handle_ipdl_sources(self, ipdl_dir, sorted_ipdl_sources, sorted_nonstatic_ipdl_sources, sorted_static_ipdl_sources, unified_ipdl_cppsrcs_mapping): for f in unified_ipdl_cppsrcs_mapping: self._build_db_line(ipdl_dir, None, self.environment, f[0], '.cpp') def _handle_webidl_build(self, bindings_dir, unified_source_mapping, webidls, expected_build_output_files, global_define_files): for f in unified_source_mapping: self._build_db_line(bindings_dir, None, self.environment, f[0], '.cpp') COMPILERS = { '.c': 'CC', '.cpp': 'CXX', '.m': 'CC', '.mm': 'CXX', } CFLAGS = { '.c': 'CFLAGS', '.cpp': 'CXXFLAGS', '.m': 'CFLAGS', '.mm': 'CXXFLAGS', } def _build_db_line(self, objdir, reldir, cenv, filename, canonical_suffix, unified=None): if canonical_suffix not in self.COMPILERS: return db = self._db.setdefault((objdir, filename, unified), cenv.substs[self.COMPILERS[canonical_suffix]].split() + ['-o', '/dev/null', '-c']) reldir = reldir or mozpath.relpath(objdir, cenv.topobjdir) def append_var(name): value = cenv.substs.get(name) if not value: return if isinstance(value, types.StringTypes): value = value.split() db.extend(value) db.append('$(COMPUTED_%s)' % self.CFLAGS[canonical_suffix]) if canonical_suffix == '.m': append_var('OS_COMPILE_CMFLAGS') db.append('$(MOZBUILD_CMFLAGS)') elif canonical_suffix == '.mm': append_var('OS_COMPILE_CMMFLAGS') db.append('$(MOZBUILD_CMMFLAGS)') ```
[ { "content": "Output the full code verbatim (no extra comments):\n```python\n\"\"\"\nDjango-multilingual: a QuerySet subclass for models with translatable\nfields.\n\nThis file contains the implementation for QSRF Django.\n\"\"\"\n\nimport datetime\n\nfrom django.core.exceptions import FieldError\nfrom django.d...
[ { "content": "Output the full code verbatim (no extra comments):\n<|memory_start|>```python\n\"\"\"\nDjango-multilingual: a QuerySet subclass for models with translatable\nfields.\n\nThis file contains the implementation for QSRF Django.\n\"\"\"\n\nimport datetime\n\nfrom django.core.exceptions import FieldErro...
```python """ Django-multilingual: a QuerySet subclass for models with translatable fields. This file contains the implementation for QSRF Django. """ import datetime from django.core.exceptions import FieldError from django.db import connection from django.db.models.fields import FieldDoesNotExist from django.db.models.query import QuerySet, Q from django.db.models.sql.query import Query from django.db.models.sql.datastructures import ( EmptyResultSet, Empty, MultiJoin) from django.db.models.sql.constants import * from django.db.models.sql.where import WhereNode, EverythingNode, AND, OR try: # handle internal API changes in Django rev. 9700 from django.db.models.sql.where import Constraint def constraint_tuple(alias, col, field, lookup_type, value): return (Constraint(alias, col, field), lookup_type, value) except ImportError: # backwards compatibility, for Django versions 1.0 to rev. 9699 def constraint_tuple(alias, col, field, lookup_type, value): return (alias, col, field, lookup_type, value) from multilingual.languages import ( get_translation_table_alias, get_language_id_list, get_default_language, get_translated_field_alias, get_language_id_from_id_or_code) __ALL__ = ['MultilingualModelQuerySet'] class MultilingualQuery(Query): def __init__(self, model, connection, where=WhereNode): self.extra_join = {} self.include_translation_data = True extra_select = {} super(MultilingualQuery, self).__init__(model, connection, where=where) opts = self.model._meta qn = self.quote_name_unless_alias qn2 = self.connection.ops.quote_name master_table_name = opts.db_table translation_opts = opts.translation_model._meta trans_table_name = translation_opts.db_table if hasattr(opts, 'translation_model'): master_table_name = opts.db_table for language_id in get_language_id_list(): for fname in [f.attname for f in translation_opts.fields]: table_alias = get_translation_table_alias(trans_table_name, language_id) field_alias = get_translated_field_alias(fname, language_id) extra_select[field_alias] = qn2(table_alias) + '.' + qn2(fname) self.add_extra(extra_select, None, None, None, None, None) self._trans_extra_select_count = len(self.extra_select) def clone(self, klass=None, **kwargs): defaults = { 'extra_join': self.extra_join, 'include_translation_data': self.include_translation_data, } defaults.update(kwargs) return super(MultilingualQuery, self).clone(klass=klass, **defaults) def pre_sql_setup(self): """Adds the JOINS and SELECTS for fetching multilingual data. """ super(MultilingualQuery, self).pre_sql_setup() if not self.include_translation_data: return opts = self.model._meta qn = self.quote_name_unless_alias qn2 = self.connection.ops.quote_name if hasattr(opts, 'translation_model'): master_table_name = opts.db_table translation_opts = opts.translation_model._meta trans_table_name = translation_opts.db_table for language_id in get_language_id_list(): table_alias = get_translation_table_alias(trans_table_name, language_id) trans_join = ('LEFT JOIN %s AS %s ON ((%s.master_id = %s.%s) AND (%s.language_id = %s))' % (qn2(translation_opts.db_table), qn2(table_alias), qn2(table_alias), qn(master_table_name), qn2(self.model._meta.pk.column), qn2(table_alias), language_id)) self.extra_join[table_alias] = trans_join def get_from_clause(self): """Add the JOINS for related multilingual fields filtering. """ result = super(MultilingualQuery, self).get_from_clause() if not self.include_translation_data: return result from_ = result[0] for join in self.extra_join.values(): from_.append(join) return (from_, result[1]) def add_filter(self, filter_expr, connector=AND, negate=False, trim=False, can_reuse=None, process_extras=True): """Copied from add_filter to generate WHERES for translation fields. """ arg, value = filter_expr parts = arg.split(LOOKUP_SEP) if not parts: raise FieldError("Cannot parse keyword query %r" % arg) # Work out the lookup type and remove it from 'parts', if necessary. if len(parts) == 1 or parts[-1] not in self.query_terms: lookup_type = 'exact' else: lookup_type = parts.pop() # Interpret '__exact=None' as the sql 'is NULL'; otherwise, reject all # uses of None as a query value. if value is None: if lookup_type != 'exact': raise ValueError("Cannot use None as a query value") lookup_type = 'isnull' value = True elif (value == '' and lookup_type == 'exact' and connection.features.interprets_empty_strings_as_nulls): lookup_type = 'isnull' value = True elif callable(value): value = value() opts = self.get_meta() alias = self.get_initial_alias() allow_many = trim or not negate try: field, target, opts, join_list, last, extra_filters = self.setup_joins( parts, opts, alias, True, allow_many, can_reuse=can_reuse, negate=negate, process_extras=process_extras) except MultiJoin, e: self.split_exclude(filter_expr, LOOKUP_SEP.join(parts[:e.level]), can_reuse) return #NOTE: here comes Django Multilingual if hasattr(opts, 'translation_model'): field_name = parts[-1] if field_name == 'pk': field_name = opts.pk.name translation_opts = opts.translation_model._meta if field_name in translation_opts.translated_fields.keys(): field, model, direct, m2m = opts.get_field_by_name(field_name) if model == opts.translation_model: language_id = translation_opts.translated_fields[field_name][1] if language_id is None: language_id = get_default_language() master_table_name = opts.db_table trans_table_alias = get_translation_table_alias( model._meta.db_table, language_id) new_table = (master_table_name + "__" + trans_table_alias) self.where.add(constraint_tuple(new_table, field.column, field, lookup_type, value), connector) return final = len(join_list) penultimate = last.pop() if penultimate == final: penultimate = last.pop() if trim and len(join_list) > 1: extra = join_list[penultimate:] join_list = join_list[:penultimate] final = penultimate penultimate = last.pop() col = self.alias_map[extra[0]][LHS_JOIN_COL] for alias in extra: self.unref_alias(alias) else: col = target.column alias = join_list[-1] while final > 1: # An optimization: if the final join is against the same column as # we are comparing against, we can go back one step in the join # chain and compare against the lhs of the join instead (and then # repeat the optimization). The result, potentially, involves less # table joins. join = self.alias_map[alias] if col != join[RHS_JOIN_COL]: break self.unref_alias(alias) alias = join[LHS_ALIAS] col = join[LHS_JOIN_COL] join_list = join_list[:-1] final -= 1 if final == penultimate: penultimate = last.pop() if (lookup_type == 'isnull' and value is True and not negate and final > 1): # If the comparison is against NULL, we need to use a left outer # join when connecting to the previous model. We make that # adjustment here. We don't do this unless needed as it's less # efficient at the database level. self.promote_alias(join_list[penultimate]) if connector == OR: # Some joins may need to be promoted when adding a new filter to a # disjunction. We walk the list of new joins and where it diverges # from any previous joins (ref count is 1 in the table list), we # make the new additions (and any existing ones not used in the new # join list) an outer join. join_it = iter(join_list) table_it = iter(self.tables) join_it.next(), table_it.next() table_promote = False join_promote = False for join in join_it: table = table_it.next() if join == table and self.alias_refcount[join] > 1: continue join_promote = self.promote_alias(join) if table != join: table_promote = self.promote_alias(table) break self.promote_alias_chain(join_it, join_promote) self.promote_alias_chain(table_it, table_promote) self.where.add(constraint_tuple(alias, col, field, lookup_type, value), connector) if negate: self.promote_alias_chain(join_list) if lookup_type != 'isnull': if final > 1: for alias in join_list: if self.alias_map[alias][JOIN_TYPE] == self.LOUTER: j_col = self.alias_map[alias][RHS_JOIN_COL] entry = self.where_class() entry.add(constraint_tuple(alias, j_col, None, 'isnull', True), AND) entry.negate() self.where.add(entry, AND) break elif not (lookup_type == 'in' and not value) and field.null: # Leaky abstraction artifact: We have to specifically # exclude the "foo__in=[]" case from this handling, because # it's short-circuited in the Where class. entry = self.where_class() entry.add(constraint_tuple(alias, col, None, 'isnull', True), AND) entry.negate() self.where.add(entry, AND) if can_reuse is not None: can_reuse.update(join_list) if process_extras: for filter in extra_filters: self.add_filter(filter, negate=negate, can_reuse=can_reuse, process_extras=False) def _setup_joins_with_translation(self, names, opts, alias, dupe_multis, allow_many=True, allow_explicit_fk=False, can_reuse=None, negate=False, process_extras=True): """ This is based on a full copy of Query.setup_joins because currently I see no way to handle it differently. TO DO: there might actually be a way, by splitting a single multi-name setup_joins call into separate calls. Check it. -- marcin@elksoft.pl Compute the necessary table joins for the passage through the fields given in 'names'. 'opts' is the Options class for the current model (which gives the table we are joining to), 'alias' is the alias for the table we are joining to. If dupe_multis is True, any many-to-many or many-to-one joins will always create a new alias (necessary for disjunctive filters). Returns the final field involved in the join, the target database column (used for any 'where' constraint), the final 'opts' value and the list of tables joined. """ joins = [alias] last = [0] dupe_set = set() exclusions = set() extra_filters = [] for pos, name in enumerate(names): try: exclusions.add(int_alias) except NameError: pass exclusions.add(alias) last.append(len(joins)) if name == 'pk': name = opts.pk.name try: field, model, direct, m2m = opts.get_field_by_name(name) except FieldDoesNotExist: for f in opts.fields: if allow_explicit_fk and name == f.attname: # XXX: A hack to allow foo_id to work in values() for # backwards compatibility purposes. If we dropped that # feature, this could be removed. field, model, direct, m2m = opts.get_field_by_name(f.name) break else: names = opts.get_all_field_names() raise FieldError("Cannot resolve keyword %r into field. " "Choices are: %s" % (name, ", ".join(names))) if not allow_many and (m2m or not direct): for alias in joins: self.unref_alias(alias) raise MultiJoin(pos + 1) #NOTE: Start Django Multilingual specific code if hasattr(opts, 'translation_model'): translation_opts = opts.translation_model._meta if model == opts.translation_model: language_id = translation_opts.translated_fields[name][1] if language_id is None: language_id = get_default_language() #TODO: check alias master_table_name = opts.db_table trans_table_alias = get_translation_table_alias( model._meta.db_table, language_id) new_table = (master_table_name + "__" + trans_table_alias) qn = self.quote_name_unless_alias qn2 = self.connection.ops.quote_name trans_join = ('LEFT JOIN %s AS %s ON ((%s.master_id = %s.%s) AND (%s.language_id = %s))' % (qn2(model._meta.db_table), qn2(new_table), qn2(new_table), qn(master_table_name), qn2(model._meta.pk.column), qn2(new_table), language_id)) self.extra_join[new_table] = trans_join target = field continue #NOTE: End Django Multilingual specific code elif model: # The field lives on a base class of the current model. for int_model in opts.get_base_chain(model): lhs_col = opts.parents[int_model].column dedupe = lhs_col in opts.duplicate_targets if dedupe: exclusions.update(self.dupe_avoidance.get( (id(opts), lhs_col), ())) dupe_set.add((opts, lhs_col)) opts = int_model._meta alias = self.join((alias, opts.db_table, lhs_col, opts.pk.column), exclusions=exclusions) joins.append(alias) exclusions.add(alias) for (dupe_opts, dupe_col) in dupe_set: self.update_dupe_avoidance(dupe_opts, dupe_col, alias) cached_data = opts._join_cache.get(name) orig_opts = opts dupe_col = direct and field.column or field.field.column dedupe = dupe_col in opts.duplicate_targets if dupe_set or dedupe: if dedupe: dupe_set.add((opts, dupe_col)) exclusions.update(self.dupe_avoidance.get((id(opts), dupe_col), ())) if process_extras and hasattr(field, 'extra_filters'): extra_filters.extend(field.extra_filters(names, pos, negate)) if direct: if m2m: # Many-to-many field defined on the current model. if cached_data: (table1, from_col1, to_col1, table2, from_col2, to_col2, opts, target) = cached_data else: table1 = field.m2m_db_table() from_col1 = opts.pk.column to_col1 = field.m2m_column_name() opts = field.rel.to._meta table2 = opts.db_table from_col2 = field.m2m_reverse_name() to_col2 = opts.pk.column target = opts.pk orig_opts._join_cache[name] = (table1, from_col1, to_col1, table2, from_col2, to_col2, opts, target) int_alias = self.join((alias, table1, from_col1, to_col1), dupe_multis, exclusions, nullable=True, reuse=can_reuse) if int_alias == table2 and from_col2 == to_col2: joins.append(int_alias) alias = int_alias else: alias = self.join( (int_alias, table2, from_col2, to_col2), dupe_multis, exclusions, nullable=True, reuse=can_reuse) joins.extend([int_alias, alias]) elif field.rel: # One-to-one or many-to-one field if cached_data: (table, from_col, to_col, opts, target) = cached_data else: opts = field.rel.to._meta target = field.rel.get_related_field() table = opts.db_table from_col = field.column to_col = target.column orig_opts._join_cache[name] = (table, from_col, to_col, opts, target) alias = self.join((alias, table, from_col, to_col), exclusions=exclusions, nullable=field.null) joins.append(alias) else: # Non-relation fields. target = field break else: orig_field = field field = field.field if m2m: # Many-to-many field defined on the target model. if cached_data: (table1, from_col1, to_col1, table2, from_col2, to_col2, opts, target) = cached_data else: table1 = field.m2m_db_table() from_col1 = opts.pk.column to_col1 = field.m2m_reverse_name() opts = orig_field.opts table2 = opts.db_table from_col2 = field.m2m_column_name() to_col2 = opts.pk.column target = opts.pk orig_opts._join_cache[name] = (table1, from_col1, to_col1, table2, from_col2, to_col2, opts, target) int_alias = self.join((alias, table1, from_col1, to_col1), dupe_multis, exclusions, nullable=True, reuse=can_reuse) alias = self.join((int_alias, table2, from_col2, to_col2), dupe_multis, exclusions, nullable=True, reuse=can_reuse) joins.extend([int_alias, alias]) else: # One-to-many field (ForeignKey defined on the target model) if cached_data: (table, from_col, to_col, opts, target) = cached_data else: local_field = opts.get_field_by_name( field.rel.field_name)[0] opts = orig_field.opts table = opts.db_table from_col = local_field.column to_col = field.column target = opts.pk orig_opts._join_cache[name] = (table, from_col, to_col, opts, target) alias = self.join((alias, table, from_col, to_col), dupe_multis, exclusions, nullable=True, reuse=can_reuse) joins.append(alias) for (dupe_opts, dupe_col) in dupe_set: try: self.update_dupe_avoidance(dupe_opts, dupe_col, int_alias) except NameError: self.update_dupe_avoidance(dupe_opts, dupe_col, alias) if pos != len(names) - 1: raise FieldError("Join on field %r not permitted." % name) return field, target, opts, joins, last, extra_filters def setup_joins(self, names, opts, alias, dupe_multis, allow_many=True, allow_explicit_fk=False, can_reuse=None, negate=False, process_extras=True): if not self.include_translation_data: return super(MultilingualQuery, self).setup_joins(names, opts, alias, dupe_multis, allow_many, allow_explicit_fk, can_reuse, negate, process_extras) else: return self._setup_joins_with_translation(names, opts, alias, dupe_multis, allow_many, allow_explicit_fk, can_reuse, negate, process_extras) def get_count(self): # optimize for the common special case: count without any # filters if ((not (self.select or self.where or self.extra_where)) and self.include_translation_data): obj = self.clone(extra_select = {}, extra_join = {}, include_translation_data = False) return obj.get_count() else: return super(MultilingualQuery, self).get_count() class MultilingualModelQuerySet(QuerySet): """ A specialized QuerySet that knows how to handle translatable fields in ordering and filtering methods. """ def __init__(self, model=None, query=None): query = query or MultilingualQuery(model, connection) super(MultilingualModelQuerySet, self).__init__(model, query) def for_language(self, language_id_or_code): """ Set the default language for all objects returned with this query. """ clone = self._clone() clone._default_language = get_language_id_from_id_or_code(language_id_or_code) return clone def iterator(self): """ Add the default language information to all returned objects. """ default_language = getattr(self, '_default_language', None) for obj in super(MultilingualModelQuerySet, self).iterator(): obj._default_language = default_language yield obj def _clone(self, klass=None, **kwargs): """ Override _clone to preserve additional information needed by MultilingualModelQuerySet. """ clone = super(MultilingualModelQuerySet, self)._clone(klass, **kwargs) clone._default_language = getattr(self, '_default_language', None) return clone def order_by(self, *field_names): if hasattr(self.model._meta, 'translation_model'): trans_opts = self.model._meta.translation_model._meta new_field_names = [] for field_name in field_names: prefix = '' if field_name[0] == '-': prefix = '-' field_name = field_name[1:] field_and_lang = trans_opts.translated_fields.get(field_name) if field_and_lang: field, language_id = field_and_lang if language_id is None: language_id = getattr(self, '_default_language', None) real_name = get_translated_field_alias(field.attname, language_id) new_field_names.append(prefix + real_name) else: new_field_names.append(prefix + field_name) return super(MultilingualModelQuerySet, self).extra(order_by=new_field_names) else: return super(MultilingualModelQuerySet, self).order_by(*field_names) def values(self, *fields): return super(MultilingualModelQuerySet, self) def values_list(self, *fields, **kwargs): raise NotImplementedError ```
[ { "content": "Output the full code verbatim (no extra comments):\n```python\n# -*- coding: utf-8 -*-\n# pylint: disable-msg=W0612,E1101,W0141\nfrom warnings import catch_warnings, simplefilter\nimport datetime\nimport itertools\nimport pytest\nimport pytz\n\nfrom numpy.random import randn\nimport numpy as np\n\...
[ { "content": "Output the full code verbatim (no extra comments):\n<|memory_start|>```python\n# -*- coding: utf-8 -*-\n# pylint: disable-msg=W0612,E1101,W0141\nfrom warnings import catch_warnings, simplefilter\nimport datetime\nimport itertools\nimport pytest\nimport pytz\n\nfrom numpy.random import randn\nimpor...
```python # -*- coding: utf-8 -*- # pylint: disable-msg=W0612,E1101,W0141 from warnings import catch_warnings, simplefilter import datetime import itertools import pytest import pytz from numpy.random import randn import numpy as np from pandas.core.index import Index, MultiIndex from pandas import (Panel, DataFrame, Series, notna, isna, Timestamp, concat, read_csv) from pandas.core.dtypes.common import is_float_dtype, is_integer_dtype import pandas.core.common as com import pandas.util.testing as tm from pandas.compat import (range, lrange, StringIO, lzip, u, product as cart_product, zip) import pandas as pd import pandas._libs.index as _index AGG_FUNCTIONS = ['sum', 'prod', 'min', 'max', 'median', 'mean', 'skew', 'mad', 'std', 'var', 'sem'] class Base(object): def setup_method(self, method): index = MultiIndex(levels=[['foo', 'bar', 'baz', 'qux'], ['one', 'two', 'three']], labels=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3], [0, 1, 2, 0, 1, 1, 2, 0, 1, 2]], names=['first', 'second']) self.frame = DataFrame(np.random.randn(10, 3), index=index, columns=Index(['A', 'B', 'C'], name='exp')) self.single_level = MultiIndex(levels=[['foo', 'bar', 'baz', 'qux']], labels=[[0, 1, 2, 3]], names=['first']) # create test series object arrays = [['bar', 'bar', 'baz', 'baz', 'qux', 'qux', 'foo', 'foo'], ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']] tuples = lzip(*arrays) index = MultiIndex.from_tuples(tuples) s = Series(randn(8), index=index) s[3] = np.NaN self.series = s tm.N = 100 self.tdf = tm.makeTimeDataFrame() self.ymd = self.tdf.groupby([lambda x: x.year, lambda x: x.month, lambda x: x.day]).sum() # use Int64Index, to make sure things work self.ymd.index.set_levels([lev.astype('i8') for lev in self.ymd.index.levels], inplace=True) self.ymd.index.set_names(['year', 'month', 'day'], inplace=True) class TestMultiLevel(Base): def test_append(self): a, b = self.frame[:5], self.frame[5:] result = a.append(b) tm.assert_frame_equal(result, self.frame) result = a['A'].append(b['A']) tm.assert_series_equal(result, self.frame['A']) def test_append_index(self): idx1 = Index([1.1, 1.2, 1.3]) idx2 = pd.date_range('2011-01-01', freq='D', periods=3, tz='Asia/Tokyo') idx3 = Index(['A', 'B', 'C']) midx_lv2 = MultiIndex.from_arrays([idx1, idx2]) midx_lv3 = MultiIndex.from_arrays([idx1, idx2, idx3]) result = idx1.append(midx_lv2) # see gh-7112 tz = pytz.timezone('Asia/Tokyo') expected_tuples = [(1.1, tz.localize(datetime.datetime(2011, 1, 1))), (1.2, tz.localize(datetime.datetime(2011, 1, 2))), (1.3, tz.localize(datetime.datetime(2011, 1, 3)))] expected = Index([1.1, 1.2, 1.3] + expected_tuples) tm.assert_index_equal(result, expected) result = midx_lv2.append(idx1) expected = Index(expected_tuples + [1.1, 1.2, 1.3]) tm.assert_index_equal(result, expected) result = midx_lv2.append(midx_lv2) expected = MultiIndex.from_arrays([idx1.append(idx1), idx2.append(idx2)]) tm.assert_index_equal(result, expected) result = midx_lv2.append(midx_lv3) tm.assert_index_equal(result, expected) result = midx_lv3.append(midx_lv2) expected = Index._simple_new( np.array([(1.1, tz.localize(datetime.datetime(2011, 1, 1)), 'A'), (1.2, tz.localize(datetime.datetime(2011, 1, 2)), 'B'), (1.3, tz.localize(datetime.datetime(2011, 1, 3)), 'C')] + expected_tuples), None) tm.assert_index_equal(result, expected) def test_dataframe_constructor(self): multi = DataFrame(np.random.randn(4, 4), index=[np.array(['a', 'a', 'b', 'b']), np.array(['x', 'y', 'x', 'y'])]) assert isinstance(multi.index, MultiIndex) assert not isinstance(multi.columns, MultiIndex) multi = DataFrame(np.random.randn(4, 4), columns=[['a', 'a', 'b', 'b'], ['x', 'y', 'x', 'y']]) assert isinstance(multi.columns, MultiIndex) def test_series_constructor(self): multi = Series(1., index=[np.array(['a', 'a', 'b', 'b']), np.array( ['x', 'y', 'x', 'y'])]) assert isinstance(multi.index, MultiIndex) multi = Series(1., index=[['a', 'a', 'b', 'b'], ['x', 'y', 'x', 'y']]) assert isinstance(multi.index, MultiIndex) multi = Series(lrange(4), index=[['a', 'a', 'b', 'b'], ['x', 'y', 'x', 'y']]) assert isinstance(multi.index, MultiIndex) def test_reindex_level(self): # axis=0 month_sums = self.ymd.sum(level='month') result = month_sums.reindex(self.ymd.index, level=1) expected = self.ymd.groupby(level='month').transform(np.sum) tm.assert_frame_equal(result, expected) # Series result = month_sums['A'].reindex(self.ymd.index, level=1) expected = self.ymd['A'].groupby(level='month').transform(np.sum) tm.assert_series_equal(result, expected, check_names=False) # axis=1 month_sums = self.ymd.T.sum(axis=1, level='month') result = month_sums.reindex(columns=self.ymd.index, level=1) expected = self.ymd.groupby(level='month').transform(np.sum).T tm.assert_frame_equal(result, expected) def test_binops_level(self): def _check_op(opname): op = getattr(DataFrame, opname) month_sums = self.ymd.sum(level='month') result = op(self.ymd, month_sums, level='month') broadcasted = self.ymd.groupby(level='month').transform(np.sum) expected = op(self.ymd, broadcasted) tm.assert_frame_equal(result, expected) # Series op = getattr(Series, opname) result = op(self.ymd['A'], month_sums['A'], level='month') broadcasted = self.ymd['A'].groupby(level='month').transform( np.sum) expected = op(self.ymd['A'], broadcasted) expected.name = 'A' tm.assert_series_equal(result, expected) _check_op('sub') _check_op('add') _check_op('mul') _check_op('div') def test_pickle(self): def _test_roundtrip(frame): unpickled = tm.round_trip_pickle(frame) tm.assert_frame_equal(frame, unpickled) _test_roundtrip(self.frame) _test_roundtrip(self.frame.T) _test_roundtrip(self.ymd) _test_roundtrip(self.ymd.T) def test_reindex(self): expected = self.frame.iloc[[0, 3]] reindexed = self.frame.loc[[('foo', 'one'), ('bar', 'one')]] tm.assert_frame_equal(reindexed, expected) with catch_warnings(record=True): simplefilter("ignore", DeprecationWarning) reindexed = self.frame.ix[[('foo', 'one'), ('bar', 'one')]] tm.assert_frame_equal(reindexed, expected) def test_reindex_preserve_levels(self): new_index = self.ymd.index[::10] chunk = self.ymd.reindex(new_index) assert chunk.index is new_index chunk = self.ymd.loc[new_index] assert chunk.index is new_index with catch_warnings(record=True): simplefilter("ignore", DeprecationWarning) chunk = self.ymd.ix[new_index] assert chunk.index is new_index ymdT = self.ymd.T chunk = ymdT.reindex(columns=new_index) assert chunk.columns is new_index chunk = ymdT.loc[:, new_index] assert chunk.columns is new_index def test_repr_to_string(self): repr(self.frame) repr(self.ymd) repr(self.frame.T) repr(self.ymd.T) buf = StringIO() self.frame.to_string(buf=buf) self.ymd.to_string(buf=buf) self.frame.T.to_string(buf=buf) self.ymd.T.to_string(buf=buf) def test_repr_name_coincide(self): index = MultiIndex.from_tuples([('a', 0, 'foo'), ('b', 1, 'bar')], names=['a', 'b', 'c']) df = DataFrame({'value': [0, 1]}, index=index) lines = repr(df).split('\n') assert lines[2].startswith('a 0 foo') def test_getitem_simple(self): df = self.frame.T col = df['foo', 'one'] tm.assert_almost_equal(col.values, df.values[:, 0]) with pytest.raises(KeyError): df[('foo', 'four')] with pytest.raises(KeyError): df['foobar'] def test_series_getitem(self): s = self.ymd['A'] result = s[2000, 3] # TODO(wesm): unused? # result2 = s.loc[2000, 3] expected = s.reindex(s.index[42:65]) expected.index = expected.index.droplevel(0).droplevel(0) tm.assert_series_equal(result, expected) result = s[2000, 3, 10] expected = s[49] assert result == expected # fancy expected = s.reindex(s.index[49:51]) result = s.loc[[(2000, 3, 10), (2000, 3, 13)]] tm.assert_series_equal(result, expected) with catch_warnings(record=True): simplefilter("ignore", DeprecationWarning) result = s.ix[[(2000, 3, 10), (2000, 3, 13)]] tm.assert_series_equal(result, expected) # key error pytest.raises(KeyError, s.__getitem__, (2000, 3, 4)) def test_series_getitem_corner(self): s = self.ymd['A'] # don't segfault, GH #495 # out of bounds access pytest.raises(IndexError, s.__getitem__, len(self.ymd)) # generator result = s[(x > 0 for x in s)] expected = s[s > 0] tm.assert_series_equal(result, expected) def test_series_setitem(self): s = self.ymd['A'] s[2000, 3] = np.nan assert isna(s.values[42:65]).all() assert notna(s.values[:42]).all() assert notna(s.values[65:]).all() s[2000, 3, 10] = np.nan assert isna(s[49]) def test_series_slice_partial(self): pass def test_frame_getitem_setitem_boolean(self): df = self.frame.T.copy() values = df.values result = df[df > 0] expected = df.where(df > 0) tm.assert_frame_equal(result, expected) df[df > 0] = 5 values[values > 0] = 5 tm.assert_almost_equal(df.values, values) df[df == 5] = 0 values[values == 5] = 0 tm.assert_almost_equal(df.values, values) # a df that needs alignment first df[df[:-1] < 0] = 2 np.putmask(values[:-1], values[:-1] < 0, 2) tm.assert_almost_equal(df.values, values) with tm.assert_raises_regex(TypeError, 'boolean values only'): df[df * 0] = 2 def test_frame_getitem_setitem_slice(self): # getitem result = self.frame.iloc[:4] expected = self.frame[:4] tm.assert_frame_equal(result, expected) # setitem cp = self.frame.copy() cp.iloc[:4] = 0 assert (cp.values[:4] == 0).all() assert (cp.values[4:] != 0).all() def test_frame_getitem_setitem_multislice(self): levels = [['t1', 't2'], ['a', 'b', 'c']] labels = [[0, 0, 0, 1, 1], [0, 1, 2, 0, 1]] midx = MultiIndex(labels=labels, levels=levels, names=[None, 'id']) df = DataFrame({'value': [1, 2, 3, 7, 8]}, index=midx) result = df.loc[:, 'value'] tm.assert_series_equal(df['value'], result) with catch_warnings(record=True): simplefilter("ignore", DeprecationWarning) result = df.ix[:, 'value'] tm.assert_series_equal(df['value'], result) result = df.loc[df.index[1:3], 'value'] tm.assert_series_equal(df['value'][1:3], result) result = df.loc[:, :] tm.assert_frame_equal(df, result) result = df df.loc[:, 'value'] = 10 result['value'] = 10 tm.assert_frame_equal(df, result) df.loc[:, :] = 10 tm.assert_frame_equal(df, result) def test_frame_getitem_multicolumn_empty_level(self): f = DataFrame({'a': ['1', '2', '3'], 'b': ['2', '3', '4']}) f.columns = [['level1 item1', 'level1 item2'], ['', 'level2 item2'], ['level3 item1', 'level3 item2']] result = f['level1 item1'] expected = DataFrame([['1'], ['2'], ['3']], index=f.index, columns=['level3 item1']) tm.assert_frame_equal(result, expected) def test_frame_setitem_multi_column(self): df = DataFrame(randn(10, 4), columns=[['a', 'a', 'b', 'b'], [0, 1, 0, 1]]) cp = df.copy() cp['a'] = cp['b'] tm.assert_frame_equal(cp['a'], cp['b']) # set with ndarray cp = df.copy() cp['a'] = cp['b'].values tm.assert_frame_equal(cp['a'], cp['b']) # --------------------------------------- # #1803 columns = MultiIndex.from_tuples([('A', '1'), ('A', '2'), ('B', '1')]) df = DataFrame(index=[1, 3, 5], columns=columns) # Works, but adds a column instead of updating the two existing ones df['A'] = 0.0 # Doesn't work assert (df['A'].values == 0).all() # it broadcasts df['B', '1'] = [1, 2, 3] df['A'] = df['B', '1'] sliced_a1 = df['A', '1'] sliced_a2 = df['A', '2'] sliced_b1 = df['B', '1'] tm.assert_series_equal(sliced_a1, sliced_b1, check_names=False) tm.assert_series_equal(sliced_a2, sliced_b1, check_names=False) assert sliced_a1.name == ('A', '1') assert sliced_a2.name == ('A', '2') assert sliced_b1.name == ('B', '1') def test_getitem_tuple_plus_slice(self): # GH #671 df = DataFrame({'a': lrange(10), 'b': lrange(10), 'c': np.random.randn(10), 'd': np.random.randn(10)}) idf = df.set_index(['a', 'b']) result = idf.loc[(0, 0), :] expected = idf.loc[0, 0] expected2 = idf.xs((0, 0)) with catch_warnings(record=True): simplefilter("ignore", DeprecationWarning) expected3 = idf.ix[0, 0] tm.assert_series_equal(result, expected) tm.assert_series_equal(result, expected2) tm.assert_series_equal(result, expected3) def test_getitem_setitem_tuple_plus_columns(self): # GH #1013 df = self.ymd[:5] result = df.loc[(2000, 1, 6), ['A', 'B', 'C']] expected = df.loc[2000, 1, 6][['A', 'B', 'C']] tm.assert_series_equal(result, expected) def test_xs(self): xs = self.frame.xs(('bar', 'two')) xs2 = self.frame.loc[('bar', 'two')] tm.assert_series_equal(xs, xs2) tm.assert_almost_equal(xs.values, self.frame.values[4]) # GH 6574 # missing values in returned index should be preserrved acc = [ ('a', 'abcde', 1), ('b', 'bbcde', 2), ('y', 'yzcde', 25), ('z', 'xbcde', 24), ('z', None, 26), ('z', 'zbcde', 25), ('z', 'ybcde', 26), ] df = DataFrame(acc, columns=['a1', 'a2', 'cnt']).set_index(['a1', 'a2']) expected = DataFrame({'cnt': [24, 26, 25, 26]}, index=Index( ['xbcde', np.nan, 'zbcde', 'ybcde'], name='a2')) result = df.xs('z', level='a1') tm.assert_frame_equal(result, expected) def test_xs_partial(self): result = self.frame.xs('foo') result2 = self.frame.loc['foo'] expected = self.frame.T['foo'].T tm.assert_frame_equal(result, expected) tm.assert_frame_equal(result, result2) result = self.ymd.xs((2000, 4)) expected = self.ymd.loc[2000, 4] tm.assert_frame_equal(result, expected) # ex from #1796 index = MultiIndex(levels=[['foo', 'bar'], ['one', 'two'], [-1, 1]], labels=[[0, 0, 0, 0, 1, 1, 1, 1], [0, 0, 1, 1, 0, 0, 1, 1], [0, 1, 0, 1, 0, 1, 0, 1]]) df = DataFrame(np.random.randn(8, 4), index=index, columns=list('abcd')) result = df.xs(['foo', 'one']) expected = df.loc['foo', 'one'] tm.assert_frame_equal(result, expected) def test_xs_with_duplicates(self): # Issue #13719 df_dup = concat([self.frame] * 2) assert df_dup.index.is_unique is False expected = concat([self.frame.xs('one', level='second')] * 2) tm.assert_frame_equal(df_dup.xs('one', level='second'), expected) tm.assert_frame_equal(df_dup.xs(['one'], level=['second']), expected) def test_xs_level(self): result = self.frame.xs('two', level='second') expected = self.frame[self.frame.index.get_level_values(1) == 'two'] expected.index = expected.index.droplevel(1) tm.assert_frame_equal(result, expected) index = MultiIndex.from_tuples([('x', 'y', 'z'), ('a', 'b', 'c'), ( 'p', 'q', 'r')]) df = DataFrame(np.random.randn(3, 5), index=index) result = df.xs('c', level=2) expected = df[1:2] expected.index = expected.index.droplevel(2) tm.assert_frame_equal(result, expected) # this is a copy in 0.14 result = self.frame.xs('two', level='second') # setting this will give a SettingWithCopyError # as we are trying to write a view def f(x): x[:] = 10 pytest.raises(com.SettingWithCopyError, f, result) def test_xs_level_multiple(self): text = """ A B C D E one two three four a b 10.0032 5 -0.5109 -2.3358 -0.4645 0.05076 0.3640 a q 20 4 0.4473 1.4152 0.2834 1.00661 0.1744 x q 30 3 -0.6662 -0.5243 -0.3580 0.89145 2.5838""" df = read_csv(StringIO(text), sep=r'\s+', engine='python') result = df.xs(('a', 4), level=['one', 'four']) expected = df.xs('a').xs(4, level='four') tm.assert_frame_equal(result, expected) # this is a copy in 0.14 result = df.xs(('a', 4), level=['one', 'four']) # setting this will give a SettingWithCopyError # as we are trying to write a view def f(x): x[:] = 10 pytest.raises(com.SettingWithCopyError, f, result) # GH2107 dates = lrange(20111201, 20111205) ids = 'abcde' idx = MultiIndex.from_tuples([x for x in cart_product(dates, ids)]) idx.names = ['date', 'secid'] df = DataFrame(np.random.randn(len(idx), 3), idx, ['X', 'Y', 'Z']) rs = df.xs(20111201, level='date') xp = df.loc[20111201, :] tm.assert_frame_equal(rs, xp) def test_xs_level0(self): text = """ A B C D E one two three four a b 10.0032 5 -0.5109 -2.3358 -0.4645 0.05076 0.3640 a q 20 4 0.4473 1.4152 0.2834 1.00661 0.1744 x q 30 3 -0.6662 -0.5243 -0.3580 0.89145 2.5838""" df = read_csv(StringIO(text), sep=r'\s+', engine='python') result = df.xs('a', level=0) expected = df.xs('a') assert len(result) == 2 tm.assert_frame_equal(result, expected) def test_xs_level_series(self): s = self.frame['A'] result = s[:, 'two'] expected = self.frame.xs('two', level=1)['A'] tm.assert_series_equal(result, expected) s = self.ymd['A'] result = s[2000, 5] expected = self.ymd.loc[2000, 5]['A'] tm.assert_series_equal(result, expected) # not implementing this for now pytest.raises(TypeError, s.__getitem__, (2000, slice(3, 4))) # result = s[2000, 3:4] # lv =s.index.get_level_values(1) # expected = s[(lv == 3) | (lv == 4)] # expected.index = expected.index.droplevel(0) # tm.assert_series_equal(result, expected) # can do this though def test_get_loc_single_level(self): s = Series(np.random.randn(len(self.single_level)), index=self.single_level) for k in self.single_level.values: s[k] def test_getitem_toplevel(self): df = self.frame.T result = df['foo'] expected = df.reindex(columns=df.columns[:3]) expected.columns = expected.columns.droplevel(0) tm.assert_frame_equal(result, expected) result = df['bar'] result2 = df.loc[:, 'bar'] expected = df.reindex(columns=df.columns[3:5]) expected.columns = expected.columns.droplevel(0) tm.assert_frame_equal(result, expected) tm.assert_frame_equal(result, result2) def test_getitem_setitem_slice_integers(self): index = MultiIndex(levels=[[0, 1, 2], [0, 2]], labels=[[0, 0, 1, 1, 2, 2], [0, 1, 0, 1, 0, 1]]) frame = DataFrame(np.random.randn(len(index), 4), index=index, columns=['a', 'b', 'c', 'd']) res = frame.loc[1:2] exp = frame.reindex(frame.index[2:]) tm.assert_frame_equal(res, exp) frame.loc[1:2] = 7 assert (frame.loc[1:2] == 7).values.all() series = Series(np.random.randn(len(index)), index=index) res = series.loc[1:2] exp = series.reindex(series.index[2:]) tm.assert_series_equal(res, exp) series.loc[1:2] = 7 assert (series.loc[1:2] == 7).values.all() def test_getitem_int(self): levels = [[0, 1], [0, 1, 2]] labels = [[0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 1, 2]] index = MultiIndex(levels=levels, labels=labels) frame = DataFrame(np.random.randn(6, 2), index=index) result = frame.loc[1] expected = frame[-3:] expected.index = expected.index.droplevel(0) tm.assert_frame_equal(result, expected) # raises exception pytest.raises(KeyError, frame.loc.__getitem__, 3) # however this will work result = self.frame.iloc[2] expected = self.frame.xs(self.frame.index[2]) tm.assert_series_equal(result, expected) def test_getitem_partial(self): ymd = self.ymd.T result = ymd[2000, 2] expected = ymd.reindex(columns=ymd.columns[ymd.columns.labels[1] == 1]) expected.columns = expected.columns.droplevel(0).droplevel(0) tm.assert_frame_equal(result, expected) def test_setitem_change_dtype(self): dft = self.frame.T s = dft['foo', 'two'] dft['foo', 'two'] = s > s.median() tm.assert_series_equal(dft['foo', 'two'], s > s.median()) # assert isinstance(dft._data.blocks[1].items, MultiIndex) reindexed = dft.reindex(columns=[('foo', 'two')]) tm.assert_series_equal(reindexed['foo', 'two'], s > s.median()) def test_frame_setitem_ix(self): self.frame.loc[('bar', 'two'), 'B'] = 5 assert self.frame.loc[('bar', 'two'), 'B'] == 5 # with integer labels df = self.frame.copy() df.columns = lrange(3) df.loc[('bar', 'two'), 1] = 7 assert df.loc[('bar', 'two'), 1] == 7 with catch_warnings(record=True): simplefilter("ignore", DeprecationWarning) df = self.frame.copy() df.columns = lrange(3) df.ix[('bar', 'two'), 1] = 7 assert df.loc[('bar', 'two'), 1] == 7 def test_fancy_slice_partial(self): result = self.frame.loc['bar':'baz'] expected = self.frame[3:7] tm.assert_frame_equal(result, expected) result = self.ymd.loc[(2000, 2):(2000, 4)] lev = self.ymd.index.labels[1] expected = self.ymd[(lev >= 1) & (lev <= 3)] tm.assert_frame_equal(result, expected) def test_getitem_partial_column_select(self): idx = MultiIndex(labels=[[0, 0, 0], [0, 1, 1], [1, 0, 1]], levels=[['a', 'b'], ['x', 'y'], ['p', 'q']]) df = DataFrame(np.random.rand(3, 2), index=idx) result = df.loc[('a', 'y'), :] expected = df.loc[('a', 'y')] tm.assert_frame_equal(result, expected) result = df.loc[('a', 'y'), [1, 0]] expected = df.loc[('a', 'y')][[1, 0]] tm.assert_frame_equal(result, expected) with catch_warnings(record=True): simplefilter("ignore", DeprecationWarning) result = df.ix[('a', 'y'), [1, 0]] tm.assert_frame_equal(result, expected) pytest.raises(KeyError, df.loc.__getitem__, (('a', 'foo'), slice(None, None))) def test_delevel_infer_dtype(self): tuples = [tuple for tuple in cart_product( ['foo', 'bar'], [10, 20], [1.0, 1.1])] index = MultiIndex.from_tuples(tuples, names=['prm0', 'prm1', 'prm2']) df = DataFrame(np.random.randn(8, 3), columns=['A', 'B', 'C'], index=index) deleveled = df.reset_index() assert is_integer_dtype(deleveled['prm1']) assert is_float_dtype(deleveled['prm2']) def test_reset_index_with_drop(self): deleveled = self.ymd.reset_index(drop=True) assert len(deleveled.columns) == len(self.ymd.columns) assert deleveled.index.name == self.ymd.index.name deleveled = self.series.reset_index() assert isinstance(deleveled, DataFrame) assert len(deleveled.columns) == len(self.series.index.levels) + 1 assert deleveled.index.name == self.series.index.name deleveled = self.series.reset_index(drop=True) assert isinstance(deleveled, Series) assert deleveled.index.name == self.series.index.name def test_count_level(self): def _check_counts(frame, axis=0): index = frame._get_axis(axis) for i in range(index.nlevels): result = frame.count(axis=axis, level=i) expected = frame.groupby(axis=axis, level=i).count() expected = expected.reindex_like(result).astype('i8') tm.assert_frame_equal(result, expected) self.frame.iloc[1, [1, 2]] = np.nan self.frame.iloc[7, [0, 1]] = np.nan self.ymd.iloc[1, [1, 2]] = np.nan self.ymd.iloc[7, [0, 1]] = np.nan _check_counts(self.frame) _check_counts(self.ymd) _check_counts(self.frame.T, axis=1) _check_counts(self.ymd.T, axis=1) # can't call with level on regular DataFrame df = tm.makeTimeDataFrame() tm.assert_raises_regex( TypeError, 'hierarchical', df.count, level=0) self.frame['D'] = 'foo' result = self.frame.count(level=0, numeric_only=True) tm.assert_index_equal(result.columns, Index(list('ABC'), name='exp')) def test_count_level_series(self): index = MultiIndex(levels=[['foo', 'bar', 'baz'], ['one', 'two', 'three', 'four']], labels=[[0, 0, 0, 2, 2], [2, 0, 1, 1, 2]]) s = Series(np.random.randn(len(index)), index=index) result = s.count(level=0) expected = s.groupby(level=0).count() tm.assert_series_equal( result.astype('f8'), expected.reindex(result.index).fillna(0)) result = s.count(level=1) expected = s.groupby(level=1).count() tm.assert_series_equal( result.astype('f8'), expected.reindex(result.index).fillna(0)) def test_count_level_corner(self): s = self.frame['A'][:0] result = s.count(level=0) expected = Series(0, index=s.index.levels[0], name='A') tm.assert_series_equal(result, expected) df = self.frame[:0] result = df.count(level=0) expected = DataFrame({}, index=s.index.levels[0], columns=df.columns).fillna(0).astype(np.int64) tm.assert_frame_equal(result, expected) def test_get_level_number_out_of_bounds(self): with tm.assert_raises_regex(IndexError, "Too many levels"): self.frame.index._get_level_number(2) with tm.assert_raises_regex(IndexError, "not a valid level number"): self.frame.index._get_level_number(-3) def test_unstack(self): # just check that it works for now unstacked = self.ymd.unstack() unstacked.unstack() # test that ints work self.ymd.astype(int).unstack() # test that int32 work self.ymd.astype(np.int32).unstack() def test_unstack_multiple_no_empty_columns(self): index = MultiIndex.from_tuples([(0, 'foo', 0), (0, 'bar', 0), ( 1, 'baz', 1), (1, 'qux', 1)]) s = Series(np.random.randn(4), index=index) unstacked = s.unstack([1, 2]) expected = unstacked.dropna(axis=1, how='all') tm.assert_frame_equal(unstacked, expected) def test_stack(self): # regular roundtrip unstacked = self.ymd.unstack() restacked = unstacked.stack() tm.assert_frame_equal(restacked, self.ymd) unlexsorted = self.ymd.sort_index(level=2) unstacked = unlexsorted.unstack(2) restacked = unstacked.stack() tm.assert_frame_equal(restacked.sort_index(level=0), self.ymd) unlexsorted = unlexsorted[::-1] unstacked = unlexsorted.unstack(1) restacked = unstacked.stack().swaplevel(1, 2) tm.assert_frame_equal(restacked.sort_index(level=0), self.ymd) unlexsorted = unlexsorted.swaplevel(0, 1) unstacked = unlexsorted.unstack(0).swaplevel(0, 1, axis=1) restacked = unstacked.stack(0).swaplevel(1, 2) tm.assert_frame_equal(restacked.sort_index(level=0), self.ymd) # columns unsorted unstacked = self.ymd.unstack() unstacked = unstacked.sort_index(axis=1, ascending=False) restacked = unstacked.stack() tm.assert_frame_equal(restacked, self.ymd) # more than 2 levels in the columns unstacked = self.ymd.unstack(1).unstack(1) result = unstacked.stack(1) expected = self.ymd.unstack() tm.assert_frame_equal(result, expected) result = unstacked.stack(2) expected = self.ymd.unstack(1) tm.assert_frame_equal(result, expected) result = unstacked.stack(0) expected = self.ymd.stack().unstack(1).unstack(1) tm.assert_frame_equal(result, expected) # not all levels present in each echelon unstacked = self.ymd.unstack(2).loc[:, ::3] stacked = unstacked.stack().stack() ymd_stacked = self.ymd.stack() tm.assert_series_equal(stacked, ymd_stacked.reindex(stacked.index)) # stack with negative number result = self.ymd.unstack(0).stack(-2) expected = self.ymd.unstack(0).stack(0) # GH10417 def check(left, right): tm.assert_series_equal(left, right) assert left.index.is_unique is False li, ri = left.index, right.index tm.assert_index_equal(li, ri) df = DataFrame(np.arange(12).reshape(4, 3), index=list('abab'), columns=['1st', '2nd', '3rd']) mi = MultiIndex(levels=[['a', 'b'], ['1st', '2nd', '3rd']], labels=[np.tile( np.arange(2).repeat(3), 2), np.tile( np.arange(3), 4)]) left, right = df.stack(), Series(np.arange(12), index=mi) check(left, right) df.columns = ['1st', '2nd', '1st'] mi = MultiIndex(levels=[['a', 'b'], ['1st', '2nd']], labels=[np.tile( np.arange(2).repeat(3), 2), np.tile( [0, 1, 0], 4)]) left, right = df.stack(), Series(np.arange(12), index=mi) check(left, right) tpls = ('a', 2), ('b', 1), ('a', 1), ('b', 2) df.index = MultiIndex.from_tuples(tpls) mi = MultiIndex(levels=[['a', 'b'], [1, 2], ['1st', '2nd']], labels=[np.tile( np.arange(2).repeat(3), 2), np.repeat( [1, 0, 1], [3, 6, 3]), np.tile( [0, 1, 0], 4)]) left, right = df.stack(), Series(np.arange(12), index=mi) check(left, right) def test_unstack_odd_failure(self): data = """day,time,smoker,sum,len Fri,Dinner,No,8.25,3. Fri,Dinner,Yes,27.03,9 Fri,Lunch,No,3.0,1 Fri,Lunch,Yes,13.68,6 Sat,Dinner,No,139.63,45 Sat,Dinner,Yes,120.77,42 Sun,Dinner,No,180.57,57 Sun,Dinner,Yes,66.82,19 Thur,Dinner,No,3.0,1 Thur,Lunch,No,117.32,44 Thur,Lunch,Yes,51.51,17""" df = pd.read_csv(StringIO(data)).set_index(['day', 'time', 'smoker']) # it works, #2100 result = df.unstack(2) recons = result.stack() tm.assert_frame_equal(recons, df) def test_stack_mixed_dtype(self): df = self.frame.T df['foo', 'four'] = 'foo' df = df.sort_index(level=1, axis=1) stacked = df.stack() result = df['foo'].stack().sort_index() tm.assert_series_equal(stacked['foo'], result, check_names=False) assert result.name is None assert stacked['bar'].dtype == np.float_ def test_unstack_bug(self): df = DataFrame({'state': ['naive', 'naive', 'naive', 'activ', 'activ', 'activ'], 'exp': ['a', 'b', 'b', 'b', 'a', 'a'], 'barcode': [1, 2, 3, 4, 1, 3], 'v': ['hi', 'hi', 'bye', 'bye', 'bye', 'peace'], 'extra': np.arange(6.)}) result = df.groupby(['state', 'exp', 'barcode', 'v']).apply(len) unstacked = result.unstack() restacked = unstacked.stack() tm.assert_series_equal( restacked, result.reindex(restacked.index).astype(float)) def test_stack_unstack_preserve_names(self): unstacked = self.frame.unstack() assert unstacked.index.name == 'first' assert unstacked.columns.names == ['exp', 'second'] restacked = unstacked.stack() assert restacked.index.names == self.frame.index.names def test_unstack_level_name(self): result = self.frame.unstack('second') expected = self.frame.unstack(level=1) tm.assert_frame_equal(result, expected) def test_stack_level_name(self): unstacked = self.frame.unstack('second') result = unstacked.stack('exp') expected = self.frame.unstack().stack(0) tm.assert_frame_equal(result, expected) result = self.frame.stack('exp') expected = self.frame.stack() tm.assert_series_equal(result, expected) def test_stack_unstack_multiple(self): unstacked = self.ymd.unstack(['year', 'month']) expected = self.ymd.unstack('year').unstack('month') tm.assert_frame_equal(unstacked, expected) assert unstacked.columns.names == expected.columns.names # series s = self.ymd['A'] s_unstacked = s.unstack(['year', 'month']) tm.assert_frame_equal(s_unstacked, expected['A']) restacked = unstacked.stack(['year', 'month']) restacked = restacked.swaplevel(0, 1).swaplevel(1, 2) restacked = restacked.sort_index(level=0) tm.assert_frame_equal(restacked, self.ymd) assert restacked.index.names == self.ymd.index.names # GH #451 unstacked = self.ymd.unstack([1, 2]) expected = self.ymd.unstack(1).unstack(1).dropna(axis=1, how='all') tm.assert_frame_equal(unstacked, expected) unstacked = self.ymd.unstack([2, 1]) expected = self.ymd.unstack(2).unstack(1).dropna(axis=1, how='all') tm.assert_frame_equal(unstacked, expected.loc[:, unstacked.columns]) def test_stack_names_and_numbers(self): unstacked = self.ymd.unstack(['year', 'month']) # Can't use mixture of names and numbers to stack with tm.assert_raises_regex(ValueError, "level should contain"): unstacked.stack([0, 'month']) def test_stack_multiple_out_of_bounds(self): # nlevels == 3 unstacked = self.ymd.unstack(['year', 'month']) with tm.assert_raises_regex(IndexError, "Too many levels"): unstacked.stack([2, 3]) with tm.assert_raises_regex(IndexError, "not a valid level number"): unstacked.stack([-4, -3]) def test_unstack_period_series(self): # GH 4342 idx1 = pd.PeriodIndex(['2013-01', '2013-01', '2013-02', '2013-02', '2013-03', '2013-03'], freq='M', name='period') idx2 = Index(['A', 'B'] * 3, name='str') value = [1, 2, 3, 4, 5, 6] idx = MultiIndex.from_arrays([idx1, idx2]) s = Series(value, index=idx) result1 = s.unstack() result2 = s.unstack(level=1) result3 = s.unstack(level=0) e_idx = pd.PeriodIndex( ['2013-01', '2013-02', '2013-03'], freq='M', name='period') expected = DataFrame({'A': [1, 3, 5], 'B': [2, 4, 6]}, index=e_idx, columns=['A', 'B']) expected.columns.name = 'str' tm.assert_frame_equal(result1, expected) tm.assert_frame_equal(result2, expected) tm.assert_frame_equal(result3, expected.T) idx1 = pd.PeriodIndex(['2013-01', '2013-01', '2013-02', '2013-02', '2013-03', '2013-03'], freq='M', name='period1') idx2 = pd.PeriodIndex(['2013-12', '2013-11', '2013-10', '2013-09', '2013-08', '2013-07'], freq='M', name='period2') idx = MultiIndex.from_arrays([idx1, idx2]) s = Series(value, index=idx) result1 = s.unstack() result2 = s.unstack(level=1) result3 = s.unstack(level=0) e_idx = pd.PeriodIndex( ['2013-01', '2013-02', '2013-03'], freq='M', name='period1') e_cols = pd.PeriodIndex(['2013-07', '2013-08', '2013-09', '2013-10', '2013-11', '2013-12'], freq='M', name='period2') expected = DataFrame([[np.nan, np.nan, np.nan, np.nan, 2, 1], [np.nan, np.nan, 4, 3, np.nan, np.nan], [6, 5, np.nan, np.nan, np.nan, np.nan]], index=e_idx, columns=e_cols) tm.assert_frame_equal(result1, expected) tm.assert_frame_equal(result2, expected) tm.assert_frame_equal(result3, expected.T) def test_unstack_period_frame(self): # GH 4342 idx1 = pd.PeriodIndex(['2014-01', '2014-02', '2014-02', '2014-02', '2014-01', '2014-01'], freq='M', name='period1') idx2 = pd.PeriodIndex(['2013-12', '2013-12', '2014-02', '2013-10', '2013-10', '2014-02'], freq='M', name='period2') value = {'A': [1, 2, 3, 4, 5, 6], 'B': [6, 5, 4, 3, 2, 1]} idx = MultiIndex.from_arrays([idx1, idx2]) df = DataFrame(value, index=idx) result1 = df.unstack() result2 = df.unstack(level=1) result3 = df.unstack(level=0) e_1 = pd.PeriodIndex(['2014-01', '2014-02'], freq='M', name='period1') e_2 = pd.PeriodIndex(['2013-10', '2013-12', '2014-02', '2013-10', '2013-12', '2014-02'], freq='M', name='period2') e_cols = MultiIndex.from_arrays(['A A A B B B'.split(), e_2]) expected = DataFrame([[5, 1, 6, 2, 6, 1], [4, 2, 3, 3, 5, 4]], index=e_1, columns=e_cols) tm.assert_frame_equal(result1, expected) tm.assert_frame_equal(result2, expected) e_1 = pd.PeriodIndex(['2014-01', '2014-02', '2014-01', '2014-02'], freq='M', name='period1') e_2 = pd.PeriodIndex( ['2013-10', '2013-12', '2014-02'], freq='M', name='period2') e_cols = MultiIndex.from_arrays(['A A B B'.split(), e_1]) expected = DataFrame([[5, 4, 2, 3], [1, 2, 6, 5], [6, 3, 1, 4]], index=e_2, columns=e_cols) tm.assert_frame_equal(result3, expected) def test_stack_multiple_bug(self): """ bug when some uniques are not present in the data #3170""" id_col = ([1] * 3) + ([2] * 3) name = (['a'] * 3) + (['b'] * 3) date = pd.to_datetime(['2013-01-03', '2013-01-04', '2013-01-05'] * 2) var1 = np.random.randint(0, 100, 6) df = DataFrame(dict(ID=id_col, NAME=name, DATE=date, VAR1=var1)) multi = df.set_index(['DATE', 'ID']) multi.columns.name = 'Params' unst = multi.unstack('ID') down = unst.resample('W-THU').mean() rs = down.stack('ID') xp = unst.loc[:, ['VAR1']].resample('W-THU').mean().stack('ID') xp.columns.name = 'Params' tm.assert_frame_equal(rs, xp) def test_stack_dropna(self): # GH #3997 df = DataFrame({'A': ['a1', 'a2'], 'B': ['b1', 'b2'], 'C': [1, 1]}) df = df.set_index(['A', 'B']) stacked = df.unstack().stack(dropna=False) assert len(stacked) > len(stacked.dropna()) stacked = df.unstack().stack(dropna=True) tm.assert_frame_equal(stacked, stacked.dropna()) def test_unstack_multiple_hierarchical(self): df = DataFrame(index=[[0, 0, 0, 0, 1, 1, 1, 1], [0, 0, 1, 1, 0, 0, 1, 1], [0, 1, 0, 1, 0, 1, 0, 1 ]], columns=[[0, 0, 1, 1], [0, 1, 0, 1]]) df.index.names = ['a', 'b', 'c'] df.columns.names = ['d', 'e'] # it works! df.unstack(['b', 'c']) def test_groupby_transform(self): s = self.frame['A'] grouper = s.index.get_level_values(0) grouped = s.groupby(grouper) applied = grouped.apply(lambda x: x * 2) expected = grouped.transform(lambda x: x * 2) result = applied.reindex(expected.index) tm.assert_series_equal(result, expected, check_names=False) def test_unstack_sparse_keyspace(self): # memory problems with naive impl #2278 # Generate Long File & Test Pivot NUM_ROWS = 1000 df = DataFrame({'A': np.random.randint(100, size=NUM_ROWS), 'B': np.random.randint(300, size=NUM_ROWS), 'C': np.random.randint(-7, 7, size=NUM_ROWS), 'D': np.random.randint(-19, 19, size=NUM_ROWS), 'E': np.random.randint(3000, size=NUM_ROWS), 'F': np.random.randn(NUM_ROWS)}) idf = df.set_index(['A', 'B', 'C', 'D', 'E']) # it works! is sufficient idf.unstack('E') def test_unstack_unobserved_keys(self): # related to #2278 refactoring levels = [[0, 1], [0, 1, 2, 3]] labels = [[0, 0, 1, 1], [0, 2, 0, 2]] index = MultiIndex(levels, labels) df = DataFrame(np.random.randn(4, 2), index=index) result = df.unstack() assert len(result.columns) == 4 recons = result.stack() tm.assert_frame_equal(recons, df) def test_stack_order_with_unsorted_levels(self): # GH 16323 def manual_compare_stacked(df, df_stacked, lev0, lev1): assert all(df.loc[row, col] == df_stacked.loc[(row, col[lev0]), col[lev1]] for row in df.index for col in df.columns) # deep check for 1-row case for width in [2, 3]: levels_poss = itertools.product( itertools.permutations([0, 1, 2], width), repeat=2) for levels in levels_poss: columns = MultiIndex(levels=levels, labels=[[0, 0, 1, 1], [0, 1, 0, 1]]) df = DataFrame(columns=columns, data=[range(4)]) for stack_lev in range(2): df_stacked = df.stack(stack_lev) manual_compare_stacked(df, df_stacked, stack_lev, 1 - stack_lev) # check multi-row case mi = MultiIndex(levels=[["A", "C", "B"], ["B", "A", "C"]], labels=[np.repeat(range(3), 3), np.tile(range(3), 3)]) df = DataFrame(columns=mi, index=range(5), data=np.arange(5 * len(mi)).reshape(5, -1)) manual_compare_stacked(df, df.stack(0), 0, 1) def test_groupby_corner(self): midx = MultiIndex(levels=[['foo'], ['bar'], ['baz']], labels=[[0], [0], [0]], names=['one', 'two', 'three']) df = DataFrame([np.random.rand(4)], columns=['a', 'b', 'c', 'd'], index=midx) # should work df.groupby(level='three') def test_groupby_level_no_obs(self): # #1697 midx = MultiIndex.from_tuples([('f1', 's1'), ('f1', 's2'), ( 'f2', 's1'), ('f2', 's2'), ('f3', 's1'), ('f3', 's2')]) df = DataFrame( [[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12]], columns=midx) df1 = df.loc(axis=1)[df.columns.map( lambda u: u[0] in ['f2', 'f3'])] grouped = df1.groupby(axis=1, level=0) result = grouped.sum() assert (result.columns == ['f2', 'f3']).all() def test_join(self): a = self.frame.loc[self.frame.index[:5], ['A']] b = self.frame.loc[self.frame.index[2:], ['B', 'C']] joined = a.join(b, how='outer').reindex(self.frame.index) expected = self.frame.copy() expected.values[np.isnan(joined.values)] = np.nan assert not np.isnan(joined.values).all() # TODO what should join do with names ? tm.assert_frame_equal(joined, expected, check_names=False) def test_swaplevel(self): swapped = self.frame['A'].swaplevel() swapped2 = self.frame['A'].swaplevel(0) swapped3 = self.frame['A'].swaplevel(0, 1) swapped4 = self.frame['A'].swaplevel('first', 'second') assert not swapped.index.equals(self.frame.index) tm.assert_series_equal(swapped, swapped2) tm.assert_series_equal(swapped, swapped3) tm.assert_series_equal(swapped, swapped4) back = swapped.swaplevel() back2 = swapped.swaplevel(0) back3 = swapped.swaplevel(0, 1) back4 = swapped.swaplevel('second', 'first') assert back.index.equals(self.frame.index) tm.assert_series_equal(back, back2) tm.assert_series_equal(back, back3) tm.assert_series_equal(back, back4) ft = self.frame.T swapped = ft.swaplevel('first', 'second', axis=1) exp = self.frame.swaplevel('first', 'second').T tm.assert_frame_equal(swapped, exp) def test_swaplevel_panel(self): with catch_warnings(record=True): simplefilter("ignore", FutureWarning) panel = Panel({'ItemA': self.frame, 'ItemB': self.frame * 2}) expected = panel.copy() expected.major_axis = expected.major_axis.swaplevel(0, 1) for result in (panel.swaplevel(axis='major'), panel.swaplevel(0, axis='major'), panel.swaplevel(0, 1, axis='major')): tm.assert_panel_equal(result, expected) def test_reorder_levels(self): result = self.ymd.reorder_levels(['month', 'day', 'year']) expected = self.ymd.swaplevel(0, 1).swaplevel(1, 2) tm.assert_frame_equal(result, expected) result = self.ymd['A'].reorder_levels(['month', 'day', 'year']) expected = self.ymd['A'].swaplevel(0, 1).swaplevel(1, 2) tm.assert_series_equal(result, expected) result = self.ymd.T.reorder_levels(['month', 'day', 'year'], axis=1) expected = self.ymd.T.swaplevel(0, 1, axis=1).swaplevel(1, 2, axis=1) tm.assert_frame_equal(result, expected) with tm.assert_raises_regex(TypeError, 'hierarchical axis'): self.ymd.reorder_levels([1, 2], axis=1) with tm.assert_raises_regex(IndexError, 'Too many levels'): self.ymd.index.reorder_levels([1, 2, 3]) def test_insert_index(self): df = self.ymd[:5].T df[2000, 1, 10] = df[2000, 1, 7] assert isinstance(df.columns, MultiIndex) assert (df[2000, 1, 10] == df[2000, 1, 7]).all() def test_alignment(self): x = Series(data=[1, 2, 3], index=MultiIndex.from_tuples([("A", 1), ( "A", 2), ("B", 3)])) y = Series(data=[4, 5, 6], index=MultiIndex.from_tuples([("Z", 1), ( "Z", 2), ("B", 3)])) res = x - y exp_index = x.index.union(y.index) exp = x.reindex(exp_index) - y.reindex(exp_index) tm.assert_series_equal(res, exp) # hit non-monotonic code path res = x[::-1] - y[::-1] exp_index = x.index.union(y.index) exp = x.reindex(exp_index) - y.reindex(exp_index) tm.assert_series_equal(res, exp) def test_frame_getitem_view(self): df = self.frame.T.copy() # this works because we are modifying the underlying array # really a no-no df['foo'].values[:] = 0 assert (df['foo'].values == 0).all() # but not if it's mixed-type df['foo', 'four'] = 'foo' df = df.sort_index(level=0, axis=1) # this will work, but will raise/warn as its chained assignment def f(): df['foo']['one'] = 2 return df pytest.raises(com.SettingWithCopyError, f) try: df = f() except: pass assert (df['foo', 'one'] == 0).all() def test_count(self): frame = self.frame.copy() frame.index.names = ['a', 'b'] result = frame.count(level='b') expect = self.frame.count(level=1) tm.assert_frame_equal(result, expect, check_names=False) result = frame.count(level='a') expect = self.frame.count(level=0) tm.assert_frame_equal(result, expect, check_names=False) series = self.series.copy() series.index.names = ['a', 'b'] result = series.count(level='b') expect = self.series.count(level=1) tm.assert_series_equal(result, expect, check_names=False) assert result.index.name == 'b' result = series.count(level='a') expect = self.series.count(level=0) tm.assert_series_equal(result, expect, check_names=False) assert result.index.name == 'a' pytest.raises(KeyError, series.count, 'x') pytest.raises(KeyError, frame.count, level='x') @pytest.mark.parametrize('op', AGG_FUNCTIONS) @pytest.mark.parametrize('level', [0, 1]) @pytest.mark.parametrize('skipna', [True, False]) @pytest.mark.parametrize('sort', [True, False]) def test_series_group_min_max(self, op, level, skipna, sort): # GH 17537 grouped = self.series.groupby(level=level, sort=sort) # skipna=True leftside = grouped.agg(lambda x: getattr(x, op)(skipna=skipna)) rightside = getattr(self.series, op)(level=level, skipna=skipna) if sort: rightside = rightside.sort_index(level=level) tm.assert_series_equal(leftside, rightside) @pytest.mark.parametrize('op', AGG_FUNCTIONS) @pytest.mark.parametrize('level', [0, 1]) @pytest.mark.parametrize('axis', [0, 1]) @pytest.mark.parametrize('skipna', [True, False]) @pytest.mark.parametrize('sort', [True, False]) def test_frame_group_ops(self, op, level, axis, skipna, sort): # GH 17537 self.frame.iloc[1, [1, 2]] = np.nan self.frame.iloc[7, [0, 1]] = np.nan if axis == 0: frame = self.frame else: frame = self.frame.T grouped = frame.groupby(level=level, axis=axis, sort=sort) pieces = [] def aggf(x): pieces.append(x) return getattr(x, op)(skipna=skipna, axis=axis) leftside = grouped.agg(aggf) rightside = getattr(frame, op)(level=level, axis=axis, skipna=skipna) if sort: rightside = rightside.sort_index(level=level, axis=axis) frame = frame.sort_index(level=level, axis=axis) # for good measure, groupby detail level_index = frame._get_axis(axis).levels[level] tm.assert_index_equal(leftside._get_axis(axis), level_index) tm.assert_index_equal(rightside._get_axis(axis), level_index) tm.assert_frame_equal(leftside, rightside) def test_stat_op_corner(self): obj = Series([10.0], index=MultiIndex.from_tuples([(2, 3)])) result = obj.sum(level=0) expected = Series([10.0], index=[2]) tm.assert_series_equal(result, expected) def test_frame_any_all_group(self): df = DataFrame( {'data': [False, False, True, False, True, False, True]}, index=[ ['one', 'one', 'two', 'one', 'two', 'two', 'two'], [0, 1, 0, 2, 1, 2, 3]]) result = df.any(level=0) ex = DataFrame({'data': [False, True]}, index=['one', 'two']) tm.assert_frame_equal(result, ex) result = df.all(level=0) ex = DataFrame({'data': [False, False]}, index=['one', 'two']) tm.assert_frame_equal(result, ex) def test_std_var_pass_ddof(self): index = MultiIndex.from_arrays([np.arange(5).repeat(10), np.tile( np.arange(10), 5)]) df = DataFrame(np.random.randn(len(index), 5), index=index) for meth in ['var', 'std']: ddof = 4 alt = lambda x: getattr(x, meth)(ddof=ddof) result = getattr(df[0], meth)(level=0, ddof=ddof) expected = df[0].groupby(level=0).agg(alt) tm.assert_series_equal(result, expected) result = getattr(df, meth)(level=0, ddof=ddof) expected = df.groupby(level=0).agg(alt) tm.assert_frame_equal(result, expected) def test_frame_series_agg_multiple_levels(self): result = self.ymd.sum(level=['year', 'month']) expected = self.ymd.groupby(level=['year', 'month']).sum() tm.assert_frame_equal(result, expected) result = self.ymd['A'].sum(level=['year', 'month']) expected = self.ymd['A'].groupby(level=['year', 'month']).sum() tm.assert_series_equal(result, expected) def test_groupby_multilevel(self): result = self.ymd.groupby(level=[0, 1]).mean() k1 = self.ymd.index.get_level_values(0) k2 = self.ymd.index.get_level_values(1) expected = self.ymd.groupby([k1, k2]).mean() # TODO groupby with level_values drops names tm.assert_frame_equal(result, expected, check_names=False) assert result.index.names == self.ymd.index.names[:2] result2 = self.ymd.groupby(level=self.ymd.index.names[:2]).mean() tm.assert_frame_equal(result, result2) def test_groupby_multilevel_with_transform(self): pass def test_multilevel_consolidate(self): index = MultiIndex.from_tuples([('foo', 'one'), ('foo', 'two'), ( 'bar', 'one'), ('bar', 'two')]) df = DataFrame(np.random.randn(4, 4), index=index, columns=index) df['Totals', ''] = df.sum(1) df = df._consolidate() def test_ix_preserve_names(self): result = self.ymd.loc[2000] result2 = self.ymd['A'].loc[2000] assert result.index.names == self.ymd.index.names[1:] assert result2.index.names == self.ymd.index.names[1:] result = self.ymd.loc[2000, 2] result2 = self.ymd['A'].loc[2000, 2] assert result.index.name == self.ymd.index.names[2] assert result2.index.name == self.ymd.index.names[2] def test_partial_set(self): # GH #397 df = self.ymd.copy() exp = self.ymd.copy() df.loc[2000, 4] = 0 exp.loc[2000, 4].values[:] = 0 tm.assert_frame_equal(df, exp) df['A'].loc[2000, 4] = 1 exp['A'].loc[2000, 4].values[:] = 1 tm.assert_frame_equal(df, exp) df.loc[2000] = 5 exp.loc[2000].values[:] = 5 tm.assert_frame_equal(df, exp) # this works...for now df['A'].iloc[14] = 5 assert df['A'][14] == 5 def test_unstack_preserve_types(self): # GH #403 self.ymd['E'] = 'foo' self.ymd['F'] = 2 unstacked = self.ymd.unstack('month') assert unstacked['A', 1].dtype == np.float64 assert unstacked['E', 1].dtype == np.object_ assert unstacked['F', 1].dtype == np.float64 def test_unstack_group_index_overflow(self): labels = np.tile(np.arange(500), 2) level = np.arange(500) index = MultiIndex(levels=[level] * 8 + [[0, 1]], labels=[labels] * 8 + [np.arange(2).repeat(500)]) s = Series(np.arange(1000), index=index) result = s.unstack() assert result.shape == (500, 2) # test roundtrip stacked = result.stack() tm.assert_series_equal(s, stacked.reindex(s.index)) # put it at beginning index = MultiIndex(levels=[[0, 1]] + [level] * 8, labels=[np.arange(2).repeat(500)] + [labels] * 8) s = Series(np.arange(1000), index=index) result = s.unstack(0) assert result.shape == (500, 2) # put it in middle index = MultiIndex(levels=[level] * 4 + [[0, 1]] + [level] * 4, labels=([labels] * 4 + [np.arange(2).repeat(500)] + [labels] * 4)) s = Series(np.arange(1000), index=index) result = s.unstack(4) assert result.shape == (500, 2) def test_pyint_engine(self): # GH 18519 : when combinations of codes cannot be represented in 64 # bits, the index underlying the MultiIndex engine works with Python # integers, rather than uint64. N = 5 keys = [tuple(l) for l in [[0] * 10 * N, [1] * 10 * N, [2] * 10 * N, [np.nan] * N + [2] * 9 * N, [0] * N + [2] * 9 * N, [np.nan] * N + [2] * 8 * N + [0] * N]] # Each level contains 4 elements (including NaN), so it is represented # in 2 bits, for a total of 2*N*10 = 100 > 64 bits. If we were using a # 64 bit engine and truncating the first levels, the fourth and fifth # keys would collide; if truncating the last levels, the fifth and # sixth; if rotating bits rather than shifting, the third and fifth. for idx in range(len(keys)): index = MultiIndex.from_tuples(keys) assert index.get_loc(keys[idx]) == idx expected = np.arange(idx + 1, dtype=np.intp) result = index.get_indexer([keys[i] for i in expected]) tm.assert_numpy_array_equal(result, expected) # With missing key: idces = range(len(keys)) expected = np.array([-1] + list(idces), dtype=np.intp) missing = tuple([0, 1] * 5 * N) result = index.get_indexer([missing] + [keys[i] for i in idces]) tm.assert_numpy_array_equal(result, expected) def test_getitem_lowerdim_corner(self): pytest.raises(KeyError, self.frame.loc.__getitem__, (('bar', 'three'), 'B')) # in theory should be inserting in a sorted space???? self.frame.loc[('bar', 'three'), 'B'] = 0 assert self.frame.sort_index().loc[('bar', 'three'), 'B'] == 0 # --------------------------------------------------------------------- # AMBIGUOUS CASES! def test_partial_ix_missing(self): pytest.skip("skipping for now") result = self.ymd.loc[2000, 0] expected = self.ymd.loc[2000]['A'] tm.assert_series_equal(result, expected) # need to put in some work here # self.ymd.loc[2000, 0] = 0 # assert (self.ymd.loc[2000]['A'] == 0).all() # Pretty sure the second (and maybe even the first) is already wrong. pytest.raises(Exception, self.ymd.loc.__getitem__, (2000, 6)) pytest.raises(Exception, self.ymd.loc.__getitem__, (2000, 6), 0) # --------------------------------------------------------------------- def test_to_html(self): self.ymd.columns.name = 'foo' self.ymd.to_html() self.ymd.T.to_html() def test_level_with_tuples(self): index = MultiIndex(levels=[[('foo', 'bar', 0), ('foo', 'baz', 0), ( 'foo', 'qux', 0)], [0, 1]], labels=[[0, 0, 1, 1, 2, 2], [0, 1, 0, 1, 0, 1]]) series = Series(np.random.randn(6), index=index) frame = DataFrame(np.random.randn(6, 4), index=index) result = series[('foo', 'bar', 0)] result2 = series.loc[('foo', 'bar', 0)] expected = series[:2] expected.index = expected.index.droplevel(0) tm.assert_series_equal(result, expected) tm.assert_series_equal(result2, expected) pytest.raises(KeyError, series.__getitem__, (('foo', 'bar', 0), 2)) result = frame.loc[('foo', 'bar', 0)] result2 = frame.xs(('foo', 'bar', 0)) expected = frame[:2] expected.index = expected.index.droplevel(0) tm.assert_frame_equal(result, expected) tm.assert_frame_equal(result2, expected) index = MultiIndex(levels=[[('foo', 'bar'), ('foo', 'baz'), ( 'foo', 'qux')], [0, 1]], labels=[[0, 0, 1, 1, 2, 2], [0, 1, 0, 1, 0, 1]]) series = Series(np.random.randn(6), index=index) frame = DataFrame(np.random.randn(6, 4), index=index) result = series[('foo', 'bar')] result2 = series.loc[('foo', 'bar')] expected = series[:2] expected.index = expected.index.droplevel(0) tm.assert_series_equal(result, expected) tm.assert_series_equal(result2, expected) result = frame.loc[('foo', 'bar')] result2 = frame.xs(('foo', 'bar')) expected = frame[:2] expected.index = expected.index.droplevel(0) tm.assert_frame_equal(result, expected) tm.assert_frame_equal(result2, expected) def test_int_series_slicing(self): s = self.ymd['A'] result = s[5:] expected = s.reindex(s.index[5:]) tm.assert_series_equal(result, expected) exp = self.ymd['A'].copy() s[5:] = 0 exp.values[5:] = 0 tm.assert_numpy_array_equal(s.values, exp.values) result = self.ymd[5:] expected = self.ymd.reindex(s.index[5:]) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize('unicode_strings', [True, False]) def test_mixed_depth_get(self, unicode_strings): # If unicode_strings is True, the column labels in dataframe # construction will use unicode strings in Python 2 (pull request # #17099). arrays = [['a', 'top', 'top', 'routine1', 'routine1', 'routine2'], ['', 'OD', 'OD', 'result1', 'result2', 'result1'], ['', 'wx', 'wy', '', '', '']] if unicode_strings: arrays = [[u(s) for s in arr] for arr in arrays] tuples = sorted(zip(*arrays)) index = MultiIndex.from_tuples(tuples) df = DataFrame(np.random.randn(4, 6), columns=index) result = df['a'] expected = df['a', '', ''].rename('a') tm.assert_series_equal(result, expected) result = df['routine1', 'result1'] expected = df['routine1', 'result1', ''] expected = expected.rename(('routine1', 'result1')) tm.assert_series_equal(result, expected) def test_mixed_depth_insert(self): arrays = [['a', 'top', 'top', 'routine1', 'routine1', 'routine2'], ['', 'OD', 'OD', 'result1', 'result2', 'result1'], ['', 'wx', 'wy', '', '', '']] tuples = sorted(zip(*arrays)) index = MultiIndex.from_tuples(tuples) df = DataFrame(randn(4, 6), columns=index) result = df.copy() expected = df.copy() result['b'] = [1, 2, 3, 4] expected['b', '', ''] = [1, 2, 3, 4] tm.assert_frame_equal(result, expected) def test_mixed_depth_drop(self): arrays = [['a', 'top', 'top', 'routine1', 'routine1', 'routine2'], ['', 'OD', 'OD', 'result1', 'result2', 'result1'], ['', 'wx', 'wy', '', '', '']] tuples = sorted(zip(*arrays)) index = MultiIndex.from_tuples(tuples) df = DataFrame(randn(4, 6), columns=index) result = df.drop('a', axis=1) expected = df.drop([('a', '', '')], axis=1) tm.assert_frame_equal(expected, result) result = df.drop(['top'], axis=1) expected = df.drop([('top', 'OD', 'wx')], axis=1) expected = expected.drop([('top', 'OD', 'wy')], axis=1) tm.assert_frame_equal(expected, result) result = df.drop(('top', 'OD', 'wx'), axis=1) expected = df.drop([('top', 'OD', 'wx')], axis=1) tm.assert_frame_equal(expected, result) expected = df.drop([('top', 'OD', 'wy')], axis=1) expected = df.drop('top', axis=1) result = df.drop('result1', level=1, axis=1) expected = df.drop([('routine1', 'result1', ''), ('routine2', 'result1', '')], axis=1) tm.assert_frame_equal(expected, result) def test_drop_nonunique(self): df = DataFrame([["x-a", "x", "a", 1.5], ["x-a", "x", "a", 1.2], ["z-c", "z", "c", 3.1], ["x-a", "x", "a", 4.1], ["x-b", "x", "b", 5.1], ["x-b", "x", "b", 4.1], ["x-b", "x", "b", 2.2], ["y-a", "y", "a", 1.2], ["z-b", "z", "b", 2.1]], columns=["var1", "var2", "var3", "var4"]) grp_size = df.groupby("var1").size() drop_idx = grp_size.loc[grp_size == 1] idf = df.set_index(["var1", "var2", "var3"]) # it works! #2101 result = idf.drop(drop_idx.index, level=0).reset_index() expected = df[-df.var1.isin(drop_idx.index)] result.index = expected.index tm.assert_frame_equal(result, expected) def test_mixed_depth_pop(self): arrays = [['a', 'top', 'top', 'routine1', 'routine1', 'routine2'], ['', 'OD', 'OD', 'result1', 'result2', 'result1'], ['', 'wx', 'wy', '', '', '']] tuples = sorted(zip(*arrays)) index = MultiIndex.from_tuples(tuples) df = DataFrame(randn(4, 6), columns=index) df1 = df.copy() df2 = df.copy() result = df1.pop('a') expected = df2.pop(('a', '', '')) tm.assert_series_equal(expected, result, check_names=False) tm.assert_frame_equal(df1, df2) assert result.name == 'a' expected = df1['top'] df1 = df1.drop(['top'], axis=1) result = df2.pop('top') tm.assert_frame_equal(expected, result) tm.assert_frame_equal(df1, df2) def test_reindex_level_partial_selection(self): result = self.frame.reindex(['foo', 'qux'], level=0) expected = self.frame.iloc[[0, 1, 2, 7, 8, 9]] tm.assert_frame_equal(result, expected) result = self.frame.T.reindex(['foo', 'qux'], axis=1, level=0) tm.assert_frame_equal(result, expected.T) result = self.frame.loc[['foo', 'qux']] tm.assert_frame_equal(result, expected) result = self.frame['A'].loc[['foo', 'qux']] tm.assert_series_equal(result, expected['A']) result = self.frame.T.loc[:, ['foo', 'qux']] tm.assert_frame_equal(result, expected.T) def test_setitem_multiple_partial(self): expected = self.frame.copy() result = self.frame.copy() result.loc[['foo', 'bar']] = 0 expected.loc['foo'] = 0 expected.loc['bar'] = 0 tm.assert_frame_equal(result, expected) expected = self.frame.copy() result = self.frame.copy() result.loc['foo':'bar'] = 0 expected.loc['foo'] = 0 expected.loc['bar'] = 0 tm.assert_frame_equal(result, expected) expected = self.frame['A'].copy() result = self.frame['A'].copy() result.loc[['foo', 'bar']] = 0 expected.loc['foo'] = 0 expected.loc['bar'] = 0 tm.assert_series_equal(result, expected) expected = self.frame['A'].copy() result = self.frame['A'].copy() result.loc['foo':'bar'] = 0 expected.loc['foo'] = 0 expected.loc['bar'] = 0 tm.assert_series_equal(result, expected) def test_drop_level(self): result = self.frame.drop(['bar', 'qux'], level='first') expected = self.frame.iloc[[0, 1, 2, 5, 6]] tm.assert_frame_equal(result, expected) result = self.frame.drop(['two'], level='second') expected = self.frame.iloc[[0, 2, 3, 6, 7, 9]] tm.assert_frame_equal(result, expected) result = self.frame.T.drop(['bar', 'qux'], axis=1, level='first') expected = self.frame.iloc[[0, 1, 2, 5, 6]].T tm.assert_frame_equal(result, expected) result = self.frame.T.drop(['two'], axis=1, level='second') expected = self.frame.iloc[[0, 2, 3, 6, 7, 9]].T tm.assert_frame_equal(result, expected) def test_drop_level_nonunique_datetime(self): # GH 12701 idx = Index([2, 3, 4, 4, 5], name='id') idxdt = pd.to_datetime(['201603231400', '201603231500', '201603231600', '201603231600', '201603231700']) df = DataFrame(np.arange(10).reshape(5, 2), columns=list('ab'), index=idx) df['tstamp'] = idxdt df = df.set_index('tstamp', append=True) ts = Timestamp('201603231600') assert df.index.is_unique is False result = df.drop(ts, level='tstamp') expected = df.loc[idx != 4] tm.assert_frame_equal(result, expected) def test_drop_preserve_names(self): index = MultiIndex.from_arrays([[0, 0, 0, 1, 1, 1], [1, 2, 3, 1, 2, 3]], names=['one', 'two']) df = DataFrame(np.random.randn(6, 3), index=index) result = df.drop([(0, 2)]) assert result.index.names == ('one', 'two') def test_unicode_repr_issues(self): levels = [Index([u('a/\u03c3'), u('b/\u03c3'), u('c/\u03c3')]), Index([0, 1])] labels = [np.arange(3).repeat(2), np.tile(np.arange(2), 3)] index = MultiIndex(levels=levels, labels=labels) repr(index.levels) # NumPy bug # repr(index.get_level_values(1)) def test_unicode_repr_level_names(self): index = MultiIndex.from_tuples([(0, 0), (1, 1)], names=[u('\u0394'), 'i1']) s = Series(lrange(2), index=index) df = DataFrame(np.random.randn(2, 4), index=index) repr(s) repr(df) def test_dataframe_insert_column_all_na(self): # GH #1534 mix = MultiIndex.from_tuples([('1a', '2a'), ('1a', '2b'), ('1a', '2c') ]) df = DataFrame([[1, 2], [3, 4], [5, 6]], index=mix) s = Series({(1, 1): 1, (1, 2): 2}) df['new'] = s assert df['new'].isna().all() def test_join_segfault(self): # 1532 df1 = DataFrame({'a': [1, 1], 'b': [1, 2], 'x': [1, 2]}) df2 = DataFrame({'a': [2, 2], 'b': [1, 2], 'y': [1, 2]}) df1 = df1.set_index(['a', 'b']) df2 = df2.set_index(['a', 'b']) # it works! for how in ['left', 'right', 'outer']: df1.join(df2, how=how) def test_set_column_scalar_with_ix(self): subset = self.frame.index[[1, 4, 5]] self.frame.loc[subset] = 99 assert (self.frame.loc[subset].values == 99).all() col = self.frame['B'] col[subset] = 97 assert (self.frame.loc[subset, 'B'] == 97).all() def test_frame_dict_constructor_empty_series(self): s1 = Series([ 1, 2, 3, 4 ], index=MultiIndex.from_tuples([(1, 2), (1, 3), (2, 2), (2, 4)])) s2 = Series([ 1, 2, 3, 4 ], index=MultiIndex.from_tuples([(1, 2), (1, 3), (3, 2), (3, 4)])) s3 = Series() # it works! DataFrame({'foo': s1, 'bar': s2, 'baz': s3}) DataFrame.from_dict({'foo': s1, 'baz': s3, 'bar': s2}) def test_indexing_ambiguity_bug_1678(self): columns = MultiIndex.from_tuples([('Ohio', 'Green'), ('Ohio', 'Red'), ( 'Colorado', 'Green')]) index = MultiIndex.from_tuples([('a', 1), ('a', 2), ('b', 1), ('b', 2) ]) frame = DataFrame(np.arange(12).reshape((4, 3)), index=index, columns=columns) result = frame.iloc[:, 1] exp = frame.loc[:, ('Ohio', 'Red')] assert isinstance(result, Series) tm.assert_series_equal(result, exp) def test_nonunique_assignment_1750(self): df = DataFrame([[1, 1, "x", "X"], [1, 1, "y", "Y"], [1, 2, "z", "Z"]], columns=list("ABCD")) df = df.set_index(['A', 'B']) ix = MultiIndex.from_tuples([(1, 1)]) df.loc[ix, "C"] = '_' assert (df.xs((1, 1))['C'] == '_').all() def test_indexing_over_hashtable_size_cutoff(self): n = 10000 old_cutoff = _index._SIZE_CUTOFF _index._SIZE_CUTOFF = 20000 s = Series(np.arange(n), MultiIndex.from_arrays((["a"] * n, np.arange(n)))) # hai it works! assert s[("a", 5)] == 5 assert s[("a", 6)] == 6 assert s[("a", 7)] == 7 _index._SIZE_CUTOFF = old_cutoff def test_multiindex_na_repr(self): # only an issue with long columns from numpy import nan df3 = DataFrame({ 'A' * 30: {('A', 'A0006000', 'nuit'): 'A0006000'}, 'B' * 30: {('A', 'A0006000', 'nuit'): nan}, 'C' * 30: {('A', 'A0006000', 'nuit'): nan}, 'D' * 30: {('A', 'A0006000', 'nuit'): nan}, 'E' * 30: {('A', 'A0006000', 'nuit'): 'A'}, 'F' * 30: {('A', 'A0006000', 'nuit'): nan}, }) idf = df3.set_index(['A' * 30, 'C' * 30]) repr(idf) def test_assign_index_sequences(self): # #2200 df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [7, 8, 9]}).set_index(["a", "b"]) index = list(df.index) index[0] = ("faz", "boo") df.index = index repr(df) # this travels an improper code path index[0] = ["faz", "boo"] df.index = index repr(df) def test_tuples_have_na(self): index = MultiIndex(levels=[[1, 0], [0, 1, 2, 3]], labels=[[1, 1, 1, 1, -1, 0, 0, 0], [0, 1, 2, 3, 0, 1, 2, 3]]) assert isna(index[4][0]) assert isna(index.values[4][0]) def test_duplicate_groupby_issues(self): idx_tp = [('600809', '20061231'), ('600809', '20070331'), ('600809', '20070630'), ('600809', '20070331')] dt = ['demo', 'demo', 'demo', 'demo'] idx = MultiIndex.from_tuples(idx_tp, names=['STK_ID', 'RPT_Date']) s = Series(dt, index=idx) result = s.groupby(s.index).first() assert len(result) == 3 def test_duplicate_mi(self): # GH 4516 df = DataFrame([['foo', 'bar', 1.0, 1], ['foo', 'bar', 2.0, 2], ['bah', 'bam', 3.0, 3], ['bah', 'bam', 4.0, 4], ['foo', 'bar', 5.0, 5], ['bah', 'bam', 6.0, 6]], columns=list('ABCD')) df = df.set_index(['A', 'B']) df = df.sort_index(level=0) expected = DataFrame([['foo', 'bar', 1.0, 1], ['foo', 'bar', 2.0, 2], ['foo', 'bar', 5.0, 5]], columns=list('ABCD')).set_index(['A', 'B']) result = df.loc[('foo', 'bar')] tm.assert_frame_equal(result, expected) def test_duplicated_drop_duplicates(self): # GH 4060 idx = MultiIndex.from_arrays(([1, 2, 3, 1, 2, 3], [1, 1, 1, 1, 2, 2])) expected = np.array( [False, False, False, True, False, False], dtype=bool) duplicated = idx.duplicated() tm.assert_numpy_array_equal(duplicated, expected) assert duplicated.dtype == bool expected = MultiIndex.from_arrays(([1, 2, 3, 2, 3], [1, 1, 1, 2, 2])) tm.assert_index_equal(idx.drop_duplicates(), expected) expected = np.array([True, False, False, False, False, False]) duplicated = idx.duplicated(keep='last') tm.assert_numpy_array_equal(duplicated, expected) assert duplicated.dtype == bool expected = MultiIndex.from_arrays(([2, 3, 1, 2, 3], [1, 1, 1, 2, 2])) tm.assert_index_equal(idx.drop_duplicates(keep='last'), expected) expected = np.array([True, False, False, True, False, False]) duplicated = idx.duplicated(keep=False) tm.assert_numpy_array_equal(duplicated, expected) assert duplicated.dtype == bool expected = MultiIndex.from_arrays(([2, 3, 2, 3], [1, 1, 2, 2])) tm.assert_index_equal(idx.drop_duplicates(keep=False), expected) def test_multiindex_set_index(self): # segfault in #3308 d = {'t1': [2, 2.5, 3], 't2': [4, 5, 6]} df = DataFrame(d) tuples = [(0, 1), (0, 2), (1, 2)] df['tuples'] = tuples index = MultiIndex.from_tuples(df['tuples']) # it works! df.set_index(index) def test_datetimeindex(self): idx1 = pd.DatetimeIndex( ['2013-04-01 9:00', '2013-04-02 9:00', '2013-04-03 9:00' ] * 2, tz='Asia/Tokyo') idx2 = pd.date_range('2010/01/01', periods=6, freq='M', tz='US/Eastern') idx = MultiIndex.from_arrays([idx1, idx2]) expected1 = pd.DatetimeIndex(['2013-04-01 9:00', '2013-04-02 9:00', '2013-04-03 9:00'], tz='Asia/Tokyo') tm.assert_index_equal(idx.levels[0], expected1) tm.assert_index_equal(idx.levels[1], idx2) # from datetime combos # GH 7888 date1 = datetime.date.today() date2 = datetime.datetime.today() date3 = Timestamp.today() for d1, d2 in itertools.product( [date1, date2, date3], [date1, date2, date3]): index = MultiIndex.from_product([[d1], [d2]]) assert isinstance(index.levels[0], pd.DatetimeIndex) assert isinstance(index.levels[1], pd.DatetimeIndex) def test_constructor_with_tz(self): index = pd.DatetimeIndex(['2013/01/01 09:00', '2013/01/02 09:00'], name='dt1', tz='US/Pacific') columns = pd.DatetimeIndex(['2014/01/01 09:00', '2014/01/02 09:00'], name='dt2', tz='Asia/Tokyo') result = MultiIndex.from_arrays([index, columns]) tm.assert_index_equal(result.levels[0], index) tm.assert_index_equal(result.levels[1], columns) result = MultiIndex.from_arrays([Series(index), Series(columns)]) tm.assert_index_equal(result.levels[0], index) tm.assert_index_equal(result.levels[1], columns) def test_set_index_datetime(self): # GH 3950 df = DataFrame( {'label': ['a', 'a', 'a', 'b', 'b', 'b'], 'datetime': ['2011-07-19 07:00:00', '2011-07-19 08:00:00', '2011-07-19 09:00:00', '2011-07-19 07:00:00', '2011-07-19 08:00:00', '2011-07-19 09:00:00'], 'value': range(6)}) df.index = pd.to_datetime(df.pop('datetime'), utc=True) df.index = df.index.tz_convert('US/Pacific') expected = pd.DatetimeIndex(['2011-07-19 07:00:00', '2011-07-19 08:00:00', '2011-07-19 09:00:00'], name='datetime') expected = expected.tz_localize('UTC').tz_convert('US/Pacific') df = df.set_index('label', append=True) tm.assert_index_equal(df.index.levels[0], expected) tm.assert_index_equal(df.index.levels[1], Index(['a', 'b'], name='label')) df = df.swaplevel(0, 1) tm.assert_index_equal(df.index.levels[0], Index(['a', 'b'], name='label')) tm.assert_index_equal(df.index.levels[1], expected) df = DataFrame(np.random.random(6)) idx1 = pd.DatetimeIndex(['2011-07-19 07:00:00', '2011-07-19 08:00:00', '2011-07-19 09:00:00', '2011-07-19 07:00:00', '2011-07-19 08:00:00', '2011-07-19 09:00:00'], tz='US/Eastern') idx2 = pd.DatetimeIndex(['2012-04-01 09:00', '2012-04-01 09:00', '2012-04-01 09:00', '2012-04-02 09:00', '2012-04-02 09:00', '2012-04-02 09:00'], tz='US/Eastern') idx3 = pd.date_range('2011-01-01 09:00', periods=6, tz='Asia/Tokyo') df = df.set_index(idx1) df = df.set_index(idx2, append=True) df = df.set_index(idx3, append=True) expected1 = pd.DatetimeIndex(['2011-07-19 07:00:00', '2011-07-19 08:00:00', '2011-07-19 09:00:00'], tz='US/Eastern') expected2 = pd.DatetimeIndex(['2012-04-01 09:00', '2012-04-02 09:00'], tz='US/Eastern') tm.assert_index_equal(df.index.levels[0], expected1) tm.assert_index_equal(df.index.levels[1], expected2) tm.assert_index_equal(df.index.levels[2], idx3) # GH 7092 tm.assert_index_equal(df.index.get_level_values(0), idx1) tm.assert_index_equal(df.index.get_level_values(1), idx2) tm.assert_index_equal(df.index.get_level_values(2), idx3) def test_reset_index_datetime(self): # GH 3950 for tz in ['UTC', 'Asia/Tokyo', 'US/Eastern']: idx1 = pd.date_range('1/1/2011', periods=5, freq='D', tz=tz, name='idx1') idx2 = Index(range(5), name='idx2', dtype='int64') idx = MultiIndex.from_arrays([idx1, idx2]) df = DataFrame( {'a': np.arange(5, dtype='int64'), 'b': ['A', 'B', 'C', 'D', 'E']}, index=idx) expected = DataFrame({'idx1': [datetime.datetime(2011, 1, 1), datetime.datetime(2011, 1, 2), datetime.datetime(2011, 1, 3), datetime.datetime(2011, 1, 4), datetime.datetime(2011, 1, 5)], 'idx2': np.arange(5, dtype='int64'), 'a': np.arange(5, dtype='int64'), 'b': ['A', 'B', 'C', 'D', 'E']}, columns=['idx1', 'idx2', 'a', 'b']) expected['idx1'] = expected['idx1'].apply( lambda d: Timestamp(d, tz=tz)) tm.assert_frame_equal(df.reset_index(), expected) idx3 = pd.date_range('1/1/2012', periods=5, freq='MS', tz='Europe/Paris', name='idx3') idx = MultiIndex.from_arrays([idx1, idx2, idx3]) df = DataFrame( {'a': np.arange(5, dtype='int64'), 'b': ['A', 'B', 'C', 'D', 'E']}, index=idx) expected = DataFrame({'idx1': [datetime.datetime(2011, 1, 1), datetime.datetime(2011, 1, 2), datetime.datetime(2011, 1, 3), datetime.datetime(2011, 1, 4), datetime.datetime(2011, 1, 5)], 'idx2': np.arange(5, dtype='int64'), 'idx3': [datetime.datetime(2012, 1, 1), datetime.datetime(2012, 2, 1), datetime.datetime(2012, 3, 1), datetime.datetime(2012, 4, 1), datetime.datetime(2012, 5, 1)], 'a': np.arange(5, dtype='int64'), 'b': ['A', 'B', 'C', 'D', 'E']}, columns=['idx1', 'idx2', 'idx3', 'a', 'b']) expected['idx1'] = expected['idx1'].apply( lambda d: Timestamp(d, tz=tz)) expected['idx3'] = expected['idx3'].apply( lambda d: Timestamp(d, tz='Europe/Paris')) tm.assert_frame_equal(df.reset_index(), expected) # GH 7793 idx = MultiIndex.from_product([['a', 'b'], pd.date_range( '20130101', periods=3, tz=tz)]) df = DataFrame( np.arange(6, dtype='int64').reshape( 6, 1), columns=['a'], index=idx) expected = DataFrame({'level_0': 'a a a b b b'.split(), 'level_1': [ datetime.datetime(2013, 1, 1), datetime.datetime(2013, 1, 2), datetime.datetime(2013, 1, 3)] * 2, 'a': np.arange(6, dtype='int64')}, columns=['level_0', 'level_1', 'a']) expected['level_1'] = expected['level_1'].apply( lambda d: Timestamp(d, freq='D', tz=tz)) tm.assert_frame_equal(df.reset_index(), expected) def test_reset_index_period(self): # GH 7746 idx = MultiIndex.from_product( [pd.period_range('20130101', periods=3, freq='M'), list('abc')], names=['month', 'feature']) df = DataFrame(np.arange(9, dtype='int64').reshape(-1, 1), index=idx, columns=['a']) expected = DataFrame({ 'month': ([pd.Period('2013-01', freq='M')] * 3 + [pd.Period('2013-02', freq='M')] * 3 + [pd.Period('2013-03', freq='M')] * 3), 'feature': ['a', 'b', 'c'] * 3, 'a': np.arange(9, dtype='int64') }, columns=['month', 'feature', 'a']) tm.assert_frame_equal(df.reset_index(), expected) def test_reset_index_multiindex_columns(self): levels = [['A', ''], ['B', 'b']] df = DataFrame([[0, 2], [1, 3]], columns=MultiIndex.from_tuples(levels)) result = df[['B']].rename_axis('A').reset_index() tm.assert_frame_equal(result, df) # gh-16120: already existing column with tm.assert_raises_regex(ValueError, (r"cannot insert \('A', ''\), " "already exists")): df.rename_axis('A').reset_index() # gh-16164: multiindex (tuple) full key result = df.set_index([('A', '')]).reset_index() tm.assert_frame_equal(result, df) # with additional (unnamed) index level idx_col = DataFrame([[0], [1]], columns=MultiIndex.from_tuples([('level_0', '')])) expected = pd.concat([idx_col, df[[('B', 'b'), ('A', '')]]], axis=1) result = df.set_index([('B', 'b')], append=True).reset_index() tm.assert_frame_equal(result, expected) # with index name which is a too long tuple... with tm.assert_raises_regex(ValueError, ("Item must have length equal to number " "of levels.")): df.rename_axis([('C', 'c', 'i')]).reset_index() # or too short... levels = [['A', 'a', ''], ['B', 'b', 'i']] df2 = DataFrame([[0, 2], [1, 3]], columns=MultiIndex.from_tuples(levels)) idx_col = DataFrame([[0], [1]], columns=MultiIndex.from_tuples([('C', 'c', 'ii')])) expected = pd.concat([idx_col, df2], axis=1) result = df2.rename_axis([('C', 'c')]).reset_index(col_fill='ii') tm.assert_frame_equal(result, expected) # ... which is incompatible with col_fill=None with tm.assert_raises_regex(ValueError, ("col_fill=None is incompatible with " r"incomplete column name \('C', 'c'\)")): df2.rename_axis([('C', 'c')]).reset_index(col_fill=None) # with col_level != 0 result = df2.rename_axis([('c', 'ii')]).reset_index(col_level=1, col_fill='C') tm.assert_frame_equal(result, expected) def test_set_index_period(self): # GH 6631 df = DataFrame(np.random.random(6)) idx1 = pd.period_range('2011-01-01', periods=3, freq='M') idx1 = idx1.append(idx1) idx2 = pd.period_range('2013-01-01 09:00', periods=2, freq='H') idx2 = idx2.append(idx2).append(idx2) idx3 = pd.period_range('2005', periods=6, freq='A') df = df.set_index(idx1) df = df.set_index(idx2, append=True) df = df.set_index(idx3, append=True) expected1 = pd.period_range('2011-01-01', periods=3, freq='M') expected2 = pd.period_range('2013-01-01 09:00', periods=2, freq='H') tm.assert_index_equal(df.index.levels[0], expected1) tm.assert_index_equal(df.index.levels[1], expected2) tm.assert_index_equal(df.index.levels[2], idx3) tm.assert_index_equal(df.index.get_level_values(0), idx1) tm.assert_index_equal(df.index.get_level_values(1), idx2) tm.assert_index_equal(df.index.get_level_values(2), idx3) def test_repeat(self): # GH 9361 # fixed by # GH 7891 m_idx = MultiIndex.from_tuples([(1, 2), (3, 4), (5, 6), (7, 8)]) data = ['a', 'b', 'c', 'd'] m_df = Series(data, index=m_idx) assert m_df.repeat(3).shape == (3 * len(data), ) def test_iloc_mi(self): # GH 13797 # Test if iloc can handle integer locations in MultiIndexed DataFrame data = [['str00', 'str01'], ['str10', 'str11'], ['str20', 'srt21'], ['str30', 'str31'], ['str40', 'str41']] mi = MultiIndex.from_tuples( [('CC', 'A'), ('CC', 'B'), ('CC', 'B'), ('BB', 'a'), ('BB', 'b')]) expected = DataFrame(data) df_mi = DataFrame(data, index=mi) result = DataFrame([[df_mi.iloc[r, c] for c in range(2)] for r in range(5)]) tm.assert_frame_equal(result, expected) class TestSorted(Base): """ everything you wanted to test about sorting """ def test_sort_index_preserve_levels(self): result = self.frame.sort_index() assert result.index.names == self.frame.index.names def test_sorting_repr_8017(self): np.random.seed(0) data = np.random.randn(3, 4) for gen, extra in [([1., 3., 2., 5.], 4.), ([1, 3, 2, 5], 4), ([Timestamp('20130101'), Timestamp('20130103'), Timestamp('20130102'), Timestamp('20130105')], Timestamp('20130104')), (['1one', '3one', '2one', '5one'], '4one')]: columns = MultiIndex.from_tuples([('red', i) for i in gen]) df = DataFrame(data, index=list('def'), columns=columns) df2 = pd.concat([df, DataFrame('world', index=list('def'), columns=MultiIndex.from_tuples( [('red', extra)]))], axis=1) # check that the repr is good # make sure that we have a correct sparsified repr # e.g. only 1 header of read assert str(df2).splitlines()[0].split() == ['red'] # GH 8017 # sorting fails after columns added # construct single-dtype then sort result = df.copy().sort_index(axis=1) expected = df.iloc[:, [0, 2, 1, 3]] tm.assert_frame_equal(result, expected) result = df2.sort_index(axis=1) expected = df2.iloc[:, [0, 2, 1, 4, 3]] tm.assert_frame_equal(result, expected) # setitem then sort result = df.copy() result[('red', extra)] = 'world' result = result.sort_index(axis=1) tm.assert_frame_equal(result, expected) def test_sort_index_level(self): df = self.frame.copy() df.index = np.arange(len(df)) # axis=1 # series a_sorted = self.frame['A'].sort_index(level=0) # preserve names assert a_sorted.index.names == self.frame.index.names # inplace rs = self.frame.copy() rs.sort_index(level=0, inplace=True) tm.assert_frame_equal(rs, self.frame.sort_index(level=0)) def test_sort_index_level_large_cardinality(self): # #2684 (int64) index = MultiIndex.from_arrays([np.arange(4000)] * 3) df = DataFrame(np.random.randn(4000), index=index, dtype=np.int64) # it works! result = df.sort_index(level=0) assert result.index.lexsort_depth == 3 # #2684 (int32) index = MultiIndex.from_arrays([np.arange(4000)] * 3) df = DataFrame(np.random.randn(4000), index=index, dtype=np.int32) # it works! result = df.sort_index(level=0) assert (result.dtypes.values == df.dtypes.values).all() assert result.index.lexsort_depth == 3 def test_sort_index_level_by_name(self): self.frame.index.names = ['first', 'second'] result = self.frame.sort_index(level='second') expected = self.frame.sort_index(level=1) tm.assert_frame_equal(result, expected) def test_sort_index_level_mixed(self): sorted_before = self.frame.sort_index(level=1) df = self.frame.copy() df['foo'] = 'bar' sorted_after = df.sort_index(level=1) tm.assert_frame_equal(sorted_before, sorted_after.drop(['foo'], axis=1)) dft = self.frame.T sorted_before = dft.sort_index(level=1, axis=1) dft['foo', 'three'] = 'bar' sorted_after = dft.sort_index(level=1, axis=1) tm.assert_frame_equal(sorted_before.drop([('foo', 'three')], axis=1), sorted_after.drop([('foo', 'three')], axis=1)) def test_is_lexsorted(self): levels = [[0, 1], [0, 1, 2]] index = MultiIndex(levels=levels, labels=[[0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 1, 2]]) assert index.is_lexsorted() index = MultiIndex(levels=levels, labels=[[0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 2, 1]]) assert not index.is_lexsorted() index = MultiIndex(levels=levels, labels=[[0, 0, 1, 0, 1, 1], [0, 1, 0, 2, 2, 1]]) assert not index.is_lexsorted() assert index.lexsort_depth == 0 def test_getitem_multilevel_index_tuple_not_sorted(self): index_columns = list("abc") df = DataFrame([[0, 1, 0, "x"], [0, 0, 1, "y"]], columns=index_columns + ["data"]) df = df.set_index(index_columns) query_index = df.index[:1] rs = df.loc[query_index, "data"] xp_idx = MultiIndex.from_tuples([(0, 1, 0)], names=['a', 'b', 'c']) xp = Series(['x'], index=xp_idx, name='data') tm.assert_series_equal(rs, xp) def test_getitem_slice_not_sorted(self): df = self.frame.sort_index(level=1).T # buglet with int typechecking result = df.iloc[:, :np.int32(3)] expected = df.reindex(columns=df.columns[:3]) tm.assert_frame_equal(result, expected) def test_frame_getitem_not_sorted2(self): # 13431 df = DataFrame({'col1': ['b', 'd', 'b', 'a'], 'col2': [3, 1, 1, 2], 'data': ['one', 'two', 'three', 'four']}) df2 = df.set_index(['col1', 'col2']) df2_original = df2.copy() df2.index.set_levels(['b', 'd', 'a'], level='col1', inplace=True) df2.index.set_labels([0, 1, 0, 2], level='col1', inplace=True) assert not df2.index.is_lexsorted() assert not df2.index.is_monotonic assert df2_original.index.equals(df2.index) expected = df2.sort_index() assert expected.index.is_lexsorted() assert expected.index.is_monotonic result = df2.sort_index(level=0) assert result.index.is_lexsorted() assert result.index.is_monotonic tm.assert_frame_equal(result, expected) def test_frame_getitem_not_sorted(self): df = self.frame.T df['foo', 'four'] = 'foo' arrays = [np.array(x) for x in zip(*df.columns.values)] result = df['foo'] result2 = df.loc[:, 'foo'] expected = df.reindex(columns=df.columns[arrays[0] == 'foo']) expected.columns = expected.columns.droplevel(0) tm.assert_frame_equal(result, expected) tm.assert_frame_equal(result2, expected) df = df.T result = df.xs('foo') result2 = df.loc['foo'] expected = df.reindex(df.index[arrays[0] == 'foo']) expected.index = expected.index.droplevel(0) tm.assert_frame_equal(result, expected) tm.assert_frame_equal(result2, expected) def test_series_getitem_not_sorted(self): arrays = [['bar', 'bar', 'baz', 'baz', 'qux', 'qux', 'foo', 'foo'], ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']] tuples = lzip(*arrays) index = MultiIndex.from_tuples(tuples) s = Series(randn(8), index=index) arrays = [np.array(x) for x in zip(*index.values)] result = s['qux'] result2 = s.loc['qux'] expected = s[arrays[0] == 'qux'] expected.index = expected.index.droplevel(0) tm.assert_series_equal(result, expected) tm.assert_series_equal(result2, expected) def test_sort_index_and_reconstruction(self): # 15622 # lexsortedness should be identical # across MultiIndex consruction methods df = DataFrame([[1, 1], [2, 2]], index=list('ab')) expected = DataFrame([[1, 1], [2, 2], [1, 1], [2, 2]], index=MultiIndex.from_tuples([(0.5, 'a'), (0.5, 'b'), (0.8, 'a'), (0.8, 'b')])) assert expected.index.is_lexsorted() result = DataFrame( [[1, 1], [2, 2], [1, 1], [2, 2]], index=MultiIndex.from_product([[0.5, 0.8], list('ab')])) result = result.sort_index() assert result.index.is_lexsorted() assert result.index.is_monotonic tm.assert_frame_equal(result, expected) result = DataFrame( [[1, 1], [2, 2], [1, 1], [2, 2]], index=MultiIndex(levels=[[0.5, 0.8], ['a', 'b']], labels=[[0, 0, 1, 1], [0, 1, 0, 1]])) result = result.sort_index() assert result.index.is_lexsorted() tm.assert_frame_equal(result, expected) concatted = pd.concat([df, df], keys=[0.8, 0.5]) result = concatted.sort_index() assert result.index.is_lexsorted() assert result.index.is_monotonic tm.assert_frame_equal(result, expected) # 14015 df = DataFrame([[1, 2], [6, 7]], columns=MultiIndex.from_tuples( [(0, '20160811 12:00:00'), (0, '20160809 12:00:00')], names=['l1', 'Date'])) df.columns.set_levels(pd.to_datetime(df.columns.levels[1]), level=1, inplace=True) assert not df.columns.is_lexsorted() assert not df.columns.is_monotonic result = df.sort_index(axis=1) assert result.columns.is_lexsorted() assert result.columns.is_monotonic result = df.sort_index(axis=1, level=1) assert result.columns.is_lexsorted() assert result.columns.is_monotonic def test_sort_index_and_reconstruction_doc_example(self): # doc example df = DataFrame({'value': [1, 2, 3, 4]}, index=MultiIndex( levels=[['a', 'b'], ['bb', 'aa']], labels=[[0, 0, 1, 1], [0, 1, 0, 1]])) assert df.index.is_lexsorted() assert not df.index.is_monotonic # sort it expected = DataFrame({'value': [2, 1, 4, 3]}, index=MultiIndex( levels=[['a', 'b'], ['aa', 'bb']], labels=[[0, 0, 1, 1], [0, 1, 0, 1]])) result = df.sort_index() assert result.index.is_lexsorted() assert result.index.is_monotonic tm.assert_frame_equal(result, expected) # reconstruct result = df.sort_index().copy() result.index = result.index._sort_levels_monotonic() assert result.index.is_lexsorted() assert result.index.is_monotonic tm.assert_frame_equal(result, expected) def test_sort_index_reorder_on_ops(self): # 15687 df = DataFrame( np.random.randn(8, 2), index=MultiIndex.from_product( [['a', 'b'], ['big', 'small'], ['red', 'blu']], names=['letter', 'size', 'color']), columns=['near', 'far']) df = df.sort_index() def my_func(group): group.index = ['newz', 'newa'] return group result = df.groupby(level=['letter', 'size']).apply( my_func).sort_index() expected = MultiIndex.from_product( [['a', 'b'], ['big', 'small'], ['newa', 'newz']], names=['letter', 'size', None]) tm.assert_index_equal(result.index, expected) def test_sort_non_lexsorted(self): # degenerate case where we sort but don't # have a satisfying result :< # GH 15797 idx = MultiIndex([['A', 'B', 'C'], ['c', 'b', 'a']], [[0, 1, 2, 0, 1, 2], [0, 2, 1, 1, 0, 2]]) df = DataFrame({'col': range(len(idx))}, index=idx, dtype='int64') assert df.index.is_lexsorted() is False assert df.index.is_monotonic is False sorted = df.sort_index() assert sorted.index.is_lexsorted() is True assert sorted.index.is_monotonic is True expected = DataFrame( {'col': [1, 4, 5, 2]}, index=MultiIndex.from_tuples([('B', 'a'), ('B', 'c'), ('C', 'a'), ('C', 'b')]), dtype='int64') result = sorted.loc[pd.IndexSlice['B':'C', 'a':'c'], :] tm.assert_frame_equal(result, expected) def test_sort_index_nan(self): # GH 14784 # incorrect sorting w.r.t. nans tuples = [[12, 13], [np.nan, np.nan], [np.nan, 3], [1, 2]] mi = MultiIndex.from_tuples(tuples) df = DataFrame(np.arange(16).reshape(4, 4), index=mi, columns=list('ABCD')) s = Series(np.arange(4), index=mi) df2 = DataFrame({ 'date': pd.to_datetime([ '20121002', '20121007', '20130130', '20130202', '20130305', '20121002', '20121207', '20130130', '20130202', '20130305', '20130202', '20130305' ]), 'user_id': [1, 1, 1, 1, 1, 3, 3, 3, 5, 5, 5, 5], 'whole_cost': [1790, np.nan, 280, 259, np.nan, 623, 90, 312, np.nan, 301, 359, 801], 'cost': [12, 15, 10, 24, 39, 1, 0, np.nan, 45, 34, 1, 12] }).set_index(['date', 'user_id']) # sorting frame, default nan position is last result = df.sort_index() expected = df.iloc[[3, 0, 2, 1], :] tm.assert_frame_equal(result, expected) # sorting frame, nan position last result = df.sort_index(na_position='last') expected = df.iloc[[3, 0, 2, 1], :] tm.assert_frame_equal(result, expected) # sorting frame, nan position first result = df.sort_index(na_position='first') expected = df.iloc[[1, 2, 3, 0], :] tm.assert_frame_equal(result, expected) # sorting frame with removed rows result = df2.dropna().sort_index() expected = df2.sort_index().dropna() tm.assert_frame_equal(result, expected) # sorting series, default nan position is last result = s.sort_index() expected = s.iloc[[3, 0, 2, 1]] tm.assert_series_equal(result, expected) # sorting series, nan position last result = s.sort_index(na_position='last') expected = s.iloc[[3, 0, 2, 1]] tm.assert_series_equal(result, expected) # sorting series, nan position first result = s.sort_index(na_position='first') expected = s.iloc[[1, 2, 3, 0]] tm.assert_series_equal(result, expected) def test_sort_ascending_list(self): # GH: 16934 # Set up a Series with a three level MultiIndex arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'], ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two'], [4, 3, 2, 1, 4, 3, 2, 1]] tuples = lzip(*arrays) mi = MultiIndex.from_tuples(tuples, names=['first', 'second', 'third']) s = Series(range(8), index=mi) # Sort with boolean ascending result = s.sort_index(level=['third', 'first'], ascending=False) expected = s.iloc[[4, 0, 5, 1, 6, 2, 7, 3]] tm.assert_series_equal(result, expected) # Sort with list of boolean ascending result = s.sort_index(level=['third', 'first'], ascending=[False, True]) expected = s.iloc[[0, 4, 1, 5, 2, 6, 3, 7]] tm.assert_series_equal(result, expected) ```
[ { "content": "Reproduce the code exactly as provided (keep formatting):\n```python\nimport unittest\nimport javabridge\nfrom javabridge import JavaException, is_instance_of\nimport numpy as np\nfrom TASSELpy.TASSELbridge import TASSELbridge\ntry:\n try:\n javabridge.get_env()\n except AttributeErro...
[ { "content": "Reproduce the code exactly as provided (keep formatting):\n<|memory_start|>```python\nimport unittest\nimport javabridge\nfrom javabridge import JavaException, is_instance_of\nimport numpy as np\nfrom TASSELpy.TASSELbridge import TASSELbridge\ntry:\n try:\n javabridge.get_env()\n exce...
```python import unittest import javabridge from javabridge import JavaException, is_instance_of import numpy as np from TASSELpy.TASSELbridge import TASSELbridge try: try: javabridge.get_env() except AttributeError: print("AttributeError: start bridge") TASSELbridge.start() except AssertionError: print("AssertionError: start bridge") TASSELbridge.start() except: raise RuntimeError("Could not start JVM") from TASSELpy.net.maizegenetics.dna.WHICH_ALLELE import WHICH_ALLELE from TASSELpy.net.maizegenetics.dna.snp.GenotypeTable import GenotypeTable from TASSELpy.net.maizegenetics.dna.map.PositionList import PositionList from TASSELpy.net.maizegenetics.taxa.TaxaList import TaxaList from TASSELpy.net.maizegenetics.util.BitSet import BitSet from TASSELpy.net.maizegenetics.dna.snp.ImportUtils import ImportUtils from TASSELpy.utils.primativeArray import meta_byte_array, meta_long_array, meta_int_array, javaPrimativeArray from TASSELpy.javaObj import javaArray from TASSELpy.net.maizegenetics.dna.map.Chromosome import Chromosome from TASSELpy.java.lang.Integer import metaInteger from TASSELpy.java.lang.Long import metaLong from TASSELpy.java.lang.String import String,metaString from TASSELpy.java.lang.Byte import metaByte from TASSELpy.java.lang.Boolean import metaBoolean from TASSELpy.java.lang.Double import metaDouble from TASSELpy.net.maizegenetics.dna.snp.depth.AlleleDepth import AlleleDepth from TASSELpy.data import data_constants debug = False java_imports = {'IllegalStateException': 'java/lang/IllegalStateException', 'NullPointerException': 'java/lang/NullPointerException', 'UnsupportedOperationException': 'java/lang/UnsupportedOperationException'} class GenotypeTableTest(unittest.TestCase): """ Tests for GenotypeTable.py """ @classmethod def setUpClass(cls): # Load data try: cls.data = ImportUtils.readGuessFormat(data_constants.SHORT_HMP_FILE) except: raise ValueError("Could not load test data") def test_genotypeArray(self): if debug: print "Testing genotypeArray" arr = self.data.genotypeArray(0,0) self.assertIsInstance(arr,meta_byte_array) def test_genotype(self): if debug: print "Testing genotype" first_site_chrom = self.data.chromosome(0) first_site_pos = self.data.chromosomalPosition(0) geno1 = self.data.genotype(0,0) self.assertIsInstance(geno1, metaByte) self.assertEqual(geno1, self.data.genotype(0,first_site_chrom,first_site_pos)) def test_genotypeRange(self): if debug: print "Testing genotypeRange" arr = self.data.genotypeRange(0,0,1) self.assertIsInstance(arr,meta_byte_array) def test_genotypeAllSites(self): if debug: print "Testing genotypeAllSites" arr = self.data.genotypeAllSites(0) self.assertIsInstance(arr,meta_byte_array) def test_genotypeAllTaxa(self): if debug: print "Testing genotypeAllTaxa" arr = self.data.genotypeAllTaxa(0) self.assertIsInstance(arr,meta_byte_array) def test_allelePresenceForAllSites(self): if debug: print "Testing allelePresenceForAllSites" bitset_major = self.data.allelePresenceForAllSites(0,WHICH_ALLELE.Major) self.assertIsInstance(bitset_major,BitSet) def test_allelePresenceForSitesBlock(self): if debug: print "Testing allelePresenceForSitesBlock" arr = self.data.allelePresenceForSitesBlock(0,WHICH_ALLELE.Major,0,1) self.assertIsInstance(arr,meta_long_array) def test_haplotypeAllelePresenceForAllSites(self): if debug: print "Testing haplotypeAllelePresenceForAllSites" try: bitset_major = self.data.haplotypeAllelePresenceForAllSites(0,True,WHICH_ALLELE.Major) self.assertIsInstance(bitset_major,BitSet) except JavaException as e: self.assertTrue(is_instance_of(e.throwable, java_imports['UnsupportedOperationException'])) def test_haplotypeAllelePresenceForAllTaxa(self): if debug: print "Testing haplotypeAllelePresenceForAllTaxa" try: bitset_major = self.data.haplotypeAllelePresenceForAllTaxa(0,True,WHICH_ALLELE.Major) self.assertIsInstance(bitset_major,BitSet) except JavaException as e: self.assertTrue(is_instance_of(e.throwable, java_imports['UnsupportedOperationException'])) def test_haplotypeAllelePresenceForSitesBlock(self): if debug: print "Testing haplotypeAllelePresenceForSitesBlock" try: arr = self.data.haplotypeAllelePresenceForSitesBlock(0,True,WHICH_ALLELE.Major, 0,1) self.assertIsInstance(arr,meta_long_array) except JavaException as e: self.assertTrue(is_instance_of(e.throwable, java_imports['UnsupportedOperationException'])) def test_genotypeAsString(self): if debug: print "Testing genotypeAsString" geno1 = self.data.genotypeAsString(0,0) geno2 = self.data.genotypeAsString(0,np.int8(0)) self.assertIsInstance(geno1,metaString) self.assertIsInstance(geno2,metaString) def test_genotypeAsStringRange(self): if debug: print "Testing genotypeAsStringRange" genos = self.data.genotypeAsStringRange(0,0,1) self.assertIsInstance(genos,metaString) def test_genotypeAsStringRow(self): if debug: print "Testing genotypeAsStringRow" genos = self.data.genotypeAsStringRow(0) self.assertIsInstance(genos,metaString) def test_genotypeAsStringArray(self): if debug: print "Testing genotypeAsStringArray" arr = self.data.genotypeAsStringArray(0,0) self.assertIsInstance(arr[0],String) def test_referenceAllele(self): if debug: print "Testing referenceAllele" ref = self.data.referenceAllele(0) self.assertIsInstance(ref,metaByte) def test_referenceAlleles(self): if debug: print "Testing referenceAlleles" arr = self.data.referenceAlleles(0,1) self.assertIsInstance(arr,meta_byte_array) def test_referenceAlleleForAllSites(self): if debug: print "Testing referenceAlleleForAllSites" arr = self.data.referenceAlleleForAllSites() self.assertIsInstance(arr,meta_byte_array) def test_hasReference(self): if debug: print "Testing hasReference" self.assertFalse(self.data.hasReference()) def test_isHeterozygous(self): if debug: print "Testing isHeterozygous" self.assertIsInstance(self.data.isHeterozygous(0,0),metaBoolean) def test_heterozygousCount(self): if debug: print "Testing heterozygousCount" self.assertIsInstance(self.data.heterozygousCount(0),metaInteger) def test_siteName(self): if debug: print "Testing siteName" self.assertIsInstance(self.data.siteName(0),metaString) def test_chromosomeSiteCount(self): if debug: print "Testing chromosomeSitecount" first_site_chrom = self.data.chromosome(0) count = self.data.chromosomeSiteCount(first_site_chrom) self.assertIsInstance(count,metaInteger) def test_firstLastSiteOfChromosome(self): if debug: print "Testing firstLastSiteOfChromosome" first_site_chrom = self.data.chromosome(0) endpoints = self.data.firstLastSiteOfChromosome(first_site_chrom) self.assertIsInstance(endpoints, meta_int_array) def test_numberOfTaxa(self): if debug: print "Testing numberOfTaxa" self.assertIsInstance(self.data.numberOfTaxa(), metaInteger) def test_positions(self): if debug: print "Testing positions" poslist = self.data.positions() self.assertIsInstance(poslist, PositionList) def test_chromosomalPosition(self): if debug: print "Testing chromosomalPosition" self.assertIsInstance(self.data.chromosomalPosition(0),metaInteger) def test_siteOfPhysicalPosition(self): if debug: print "Testing siteOfPhysicalPosition" site1 = self.data.siteOfPhysicalPosition(data_constants.SHORT_HMP_FILE_FIRST_POS, Chromosome(data_constants.SHORT_HMP_FILE_FIRST_CHROM)) site2 = self.data.siteOfPhysicalPosition(data_constants.SHORT_HMP_FILE_FIRST_POS, Chromosome(data_constants.SHORT_HMP_FILE_FIRST_CHROM), data_constants.SHORT_HMP_FILE_FIRST_SITENAME) self.assertEquals(site1,0) self.assertEqual(site1,site2) def test_physicalPosition(self): if debug: print "Testing physicalPositions" positions = self.data.physicalPositions() self.assertIsInstance(positions, meta_int_array) def test_chromosomeName(self): if debug: print "Testing chromosomeName" self.assertEquals(self.data.chromosomeName(0), data_constants.SHORT_HMP_FILE_FIRST_CHROM) def test_chromosome(self): if debug: print "Testing chromosome" chrom1 = self.data.chromosome(0) chrom2 = self.data.chromosome(data_constants.SHORT_HMP_FILE_FIRST_CHROM) self.assertEquals(chrom1.getName(), data_constants.SHORT_HMP_FILE_FIRST_CHROM) self.assertEqual(chrom1,chrom2) def test_chromosomes(self): if debug: print "Testing chromosomes" chroms = self.data.chromosomes() self.assertIsInstance(chroms,javaArray) self.assertIsInstance(chroms[0], Chromosome) def test_numChromosomes(self): if debug: print "Testing numChromosomes" self.assertIsInstance(self.data.numChromosomes(),metaInteger) def test_chromosomesOffsets(self): if debug: print "Testing chromosomesOffsets" arr = self.data.chromosomesOffsets() self.assertIsInstance(arr,meta_int_array) def test_hasDepth(self): if debug: print "Testing hasDepth" self.assertIsInstance(self.data.hasDepth(),metaBoolean) def test_hasAlleleProbabilities(self): if debug: print("Testing hasAlleleProbabilities") self.assertFalse(self.data.hasAlleleProbabilities()) def test_indelSize(self): if debug: print "Testing indelSize" self.assertIsInstance(self.data.indelSize(0),metaInteger) def test_isIndel(self): if debug: print "Testing isIndel" self.assertIsInstance(self.data.isIndel(0),metaBoolean) def test_isAllPolymorphic(self): if debug: print "Testing isAllPolymorphic" self.assertIsInstance(self.data.isAllPolymorphic(),metaBoolean) def test_isPolymorphic(self): if debug: print "Testing isPolymorphic" self.assertIsInstance(self.data.isPolymorphic(0),metaBoolean) def test_majorAllele(self): if debug: print "Testing majorAllele" self.assertIsInstance(self.data.majorAllele(0),metaByte) def test_majorAlleleAsString(self): if debug: print "Testing majorAlleleAsString" self.assertIsInstance(self.data.majorAlleleAsString(0),metaString) def test_minorAllele(self): if debug: print "Testing minorAllele" self.assertIsInstance(self.data.minorAllele(0),metaByte) def test_minorAlleleAsString(self): if debug: print "Testing minorAlleleAsString" self.assertIsInstance(self.data.minorAlleleAsString(0),metaString) def test_minorAlleles(self): if debug: print "Testing minorAlleles" self.assertIsInstance(self.data.minorAlleles(0),meta_byte_array) def test_alleles(self): if debug: print "Testing alleles" self.assertIsInstance(self.data.alleles(0), meta_byte_array) def test_minorAlleleFrequency(self): if debug: print "Testing minorAlleleFrequency" self.assertIsInstance(self.data.minorAlleleFrequency(0),metaDouble) def test_majorAlleleFrequency(self): if debug: print "Testing majorAlleleFrequency" self.assertIsInstance(self.data.majorAlleleFrequency(0),metaDouble) def test_taxa(self): if debug: print "Testing taxa" taxa = self.data.taxa() self.assertIsInstance(taxa, TaxaList) def test_taxaName(self): if debug: print "Testing taxaName" self.assertIsInstance(self.data.taxaName(0), metaString) def test_genomeVersion(self): if debug: print "Testing genomeVersion" try: version = self.data.genomeVersion() if version is not None: self.assertIsInstance(version, metaString) except JavaException as e: self.assertTrue(is_instance_of(e.throwable, java_imports['UnsupportedOperationException'])) def test_isPositiveStrand(self): if debug: print "Testing isPositiveStrand" self.assertIsInstance(self.data.isPositiveStrand(0),metaBoolean) def test_compositeAlignments(self): if debug: print "Testing compositeAlignments" alns = self.data.compositeAlignments() exp_arr_type = javaArray.get_array_type(GenotypeTable) self.assertIsInstance(alns, exp_arr_type) def test_allelesSortedByFrequency(self): if debug: print "Testing allelesSortedByFrequency" arr = self.data.allelesSortedByFrequency(0) exp_arr_type = javaArray.get_array_type(javaPrimativeArray.get_array_type('int')) self.assertIsInstance(arr,exp_arr_type) def test_genosSortedByFrequency(self): if debug: print "Testing genosSortedByFrequency" arr = self.data.genosSortedByFrequency(0) self.assertIsInstance(arr[0][0],metaString) self.assertIsInstance(arr[1][0],metaInteger) def test_isPhased(self): if debug: print "Testing isPhased" self.assertIsInstance(self.data.isPhased(),metaBoolean) def test_retainsRareAlleles(self): if debug: print "Testing retainsRareAlleles" self.assertIsInstance(self.data.retainsRareAlleles(),metaBoolean) def test_alleleDefinitions(self): if debug: print "Testing alleleDefinitions" arr1 = self.data.alleleDefinitions() arr2 = self.data.alleleDefinitions(0) self.assertIsInstance(arr1[0][0], metaString) self.assertEqual(arr1[0][0], arr2[0]) def test_diploidAsString(self): if debug: print "Testing diploidAsString" val = self.data.diploidAsString(0,np.int8(0)) self.assertIsInstance(val,metaString) def test_maxNumAlleles(self): if debug: print "Testing maxNumAlleles" self.assertIsInstance(self.data.maxNumAlleles(), metaInteger) def test_totalGametesNonMissingForSites(self): if debug: print "Testing totalGametesNonMissingForSite" self.assertIsInstance(self.data.totalGametesNonMissingForSite(0), metaInteger) def test_totalNonMissingForSite(self): if debug: print "Testing totalNonMissingForSite" self.assertIsInstance(self.data.totalNonMissingForSite(0), metaInteger) def test_minorAlleleCount(self): if debug: print "Testing minorAlleleCount" self.assertIsInstance(self.data.minorAlleleCount(0), metaInteger) def test_majorAlleleCount(self): if debug: print "Testing majorAlleleCount" self.assertIsInstance(self.data.majorAlleleCount(0), metaInteger) def test_genoCount(self): if debug: print "Testing genoCount" arr = self.data.genoCounts() self.assertIsInstance(arr[0][0], metaString) self.assertIsInstance(arr[1][0], metaLong) def test_majorMinorCounts(self): if debug: print "Testing majorMinorCounts" arr = self.data.majorMinorCounts() self.assertIsInstance(arr[0][0], metaString) self.assertIsInstance(arr[1][0], metaLong) def test_totalGametesNonMissingForTaxon(self): if debug: print "Testing totalGametesNonMissingForTaxon" val = self.data.totalGametesNonMissingForTaxon(0) self.assertIsInstance(val, metaInteger) def test_heterozygousCountForTaxon(self): if debug: print "Testing heterozygousCountForTaxon" val = self.data.heterozygousCountForTaxon(0) self.assertIsInstance(val, metaInteger) def test_totalNonMissingForTaxon(self): if debug: print "Testing totalNonMissingForTaxon" val = self.data.totalNonMissingForTaxon(0) self.assertIsInstance(val, metaInteger) def test_depth(self): if debug: print "Testing depth" depth = self.data.depth() self.assertTrue(depth is None or isinstance(depth, AlleleDepth)) def test_depthForAlleles(self): if debug: print "Testing depthForAlleles" try: arr = self.data.depthForAlleles(0,0) self.assertIsInstance(arr[0],metaInteger) except JavaException as e: self.assertTrue(is_instance_of(e.throwable, java_imports['NullPointerException'])) def test_allelesBySortType(self): if debug: print "Testing allelesBySortType" arr = self.data.allelesBySortType(self.data.ALLELE_SORT_TYPE.Reference,0) self.assertTrue(arr is None or isinstance(arr, meta_byte_array)) def test_allelePresenceForAllTaxa(self): if debug: print "Testing allelePresenceForAllTaxa" bitset = self.data.allelePresenceForAllTaxa(0, WHICH_ALLELE.Major) self.assertIsInstance(bitset, BitSet) if __name__ == "__main__": debug = True unittest.main() TASSELbridge.stop() ```
[ { "content": "Provide a verbatim copy of the code:\n```python\n# -*- coding: utf-8 -*-\n##############################################################################\n#\n# Copyright (c) 2015 Andhitia Rama. All rights reserved.\n# @author Andhitia Rama\n#\n# This program is free software: you can redis...
[ { "content": "Provide a verbatim copy of the code:\n<|memory_start|>```python\n# -*- coding: utf-8 -*-\n##############################################################################\n#\n# Copyright (c) 2015 Andhitia Rama. All rights reserved.\n# @author Andhitia Rama\n#\n# This program is free softwar...
```python # -*- coding: utf-8 -*- ############################################################################## # # Copyright (c) 2015 Andhitia Rama. All rights reserved. # @author Andhitia Rama # # 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 models, fields class res_company(models.Model): """override company to add asset account""" _inherit = 'res.company' _name = 'res.company' asset_ids = fields.Many2many( string='Assets', comodel_name='account.account', relation='rel_company_2_asset_acc', column1='company_id', column2='account_id', ) ```
[ { "content": "```python\n#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n#\n# This file is part of solus-sc\n#\n# Copyright © 2013-2018 Ikey Doherty <ikey@solus-project.com>\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as...
[ { "content": "<|memory_start|>```python\n#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n#\n# This file is part of solus-sc\n#\n# Copyright © 2013-2018 Ikey Doherty <ikey@solus-project.com>\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General P...
```python #!/usr/bin/env python2 # -*- coding: utf-8 -*- # # This file is part of solus-sc # # Copyright © 2013-2018 Ikey Doherty <ikey@solus-project.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. # from .window import ScMainWindow from gi.repository import Gio, Gtk, Gdk, GLib, Notify from . import join_resource_path import random import time SC_APP_ID = "com.solus_project.SoftwareCentre" class ScApplication(Gtk.Application): app_window = None is_service_mode = False updates_view = False def activate_main_view(self): self.ensure_window() if self.updates_view: self.app_window.mode_open = "updates" else: self.app_window.mode_open = "home" self.app_window.present() def ensure_window(self): """ Ensure we have a window """ if self.app_window is None: self.app_window = ScMainWindow(self) def startup(self, app): """ Main entry """ self.init_css() def init_css(self): """ Set up the CSS before we throw any windows up """ try: f = Gio.File.new_for_path(join_resource_path("styling.css")) css = Gtk.CssProvider() css.load_from_file(f) screen = Gdk.Screen.get_default() prio = Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION Gtk.StyleContext.add_provider_for_screen(screen, css, prio) except Exception as e: print("Error loading CSS: {}".format(e)) def __init__(self): Gtk.Application.__init__( self, application_id=SC_APP_ID, flags=Gio.ApplicationFlags.HANDLES_COMMAND_LINE) self.connect("activate", self.on_activate) self.connect("startup", self.startup) self.connect("command-line", self.handle_command_line) self.connect("handle-local-options", self.handle_local_options) option = GLib.OptionEntry() option.long_name = "update-view" option.short_name = 0 option.flags = 0 option.arg = GLib.OptionArg.NONE option.arg_data = None description = _("Open up the updates view of the application") option.description = description self.add_main_option_entries([option]) # Need notifications Notify.init("Solus Software Centre") # Make sure random is moar betterer random.seed(time.time()) def on_activate(self, app): """ Activate the primary view """ self.activate_main_view() def handle_command_line(self, app, cmdline): self.activate() return 0 def handle_local_options(self, app, cmdline): if cmdline.contains("update-view"): self.updates_view = True return -1 ```
[ { "content": "Provide a verbatim copy of the code:\n```python\n# -*- coding: utf-8 -*-\nfrom operator import attrgetter\nfrom pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType\nfrom pyangbind.lib.yangtypes import RestrictedClassType\nfrom pyangbind.lib.yangtypes import TypedListType\nfrom pyangbind....
[ { "content": "Provide a verbatim copy of the code:\n<|memory_start|>```python\n# -*- coding: utf-8 -*-\nfrom operator import attrgetter\nfrom pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType\nfrom pyangbind.lib.yangtypes import RestrictedClassType\nfrom pyangbind.lib.yangtypes import TypedListType\...
```python # -*- coding: utf-8 -*- from operator import attrgetter from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType from pyangbind.lib.yangtypes import RestrictedClassType from pyangbind.lib.yangtypes import TypedListType from pyangbind.lib.yangtypes import YANGBool from pyangbind.lib.yangtypes import YANGListType from pyangbind.lib.yangtypes import YANGDynClass from pyangbind.lib.yangtypes import ReferenceType from pyangbind.lib.base import PybindBase from collections import OrderedDict from decimal import Decimal from bitarray import bitarray import six # PY3 support of some PY2 keywords (needs improved) if six.PY3: import builtins as __builtin__ long = int elif six.PY2: import __builtin__ from . import tlv class tlvs(PybindBase): """ This class was auto-generated by the PythonClass plugin for PYANG from YANG module openconfig-network-instance - based on the path /network-instances/network-instance/protocols/protocol/ospfv2/areas/area/lsdb/lsa-types/lsa-type/lsas/lsa/opaque-lsa/traffic-engineering/tlvs. Each member element of the container is represented as a class variable - with a specific YANG type. YANG Description: The TLVs contained in the TE Opaque LSA """ __slots__ = ("_path_helper", "_extmethods", "__tlv") _yang_name = "tlvs" _pybind_generated_by = "container" def __init__(self, *args, **kwargs): self._path_helper = False self._extmethods = False self.__tlv = YANGDynClass( base=YANGListType( False, tlv.tlv, yang_name="tlv", parent=self, is_container="list", user_ordered=False, path_helper=self._path_helper, yang_keys="False", extensions=None, ), is_container="list", yang_name="tlv", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace="http://openconfig.net/yang/network-instance", defining_module="openconfig-network-instance", yang_type="list", is_config=False, ) load = kwargs.pop("load", None) if args: if len(args) > 1: raise TypeError("cannot create a YANG container with >1 argument") all_attr = True for e in self._pyangbind_elements: if not hasattr(args[0], e): all_attr = False break if not all_attr: raise ValueError("Supplied object did not have the correct attributes") for e in self._pyangbind_elements: nobj = getattr(args[0], e) if nobj._changed() is False: continue setmethod = getattr(self, "_set_%s" % e) if load is None: setmethod(getattr(args[0], e)) else: setmethod(getattr(args[0], e), load=load) def _path(self): if hasattr(self, "_parent"): return self._parent._path() + [self._yang_name] else: return [ "network-instances", "network-instance", "protocols", "protocol", "ospfv2", "areas", "area", "lsdb", "lsa-types", "lsa-type", "lsas", "lsa", "opaque-lsa", "traffic-engineering", "tlvs", ] def _get_tlv(self): """ Getter method for tlv, mapped from YANG variable /network_instances/network_instance/protocols/protocol/ospfv2/areas/area/lsdb/lsa_types/lsa_type/lsas/lsa/opaque_lsa/traffic_engineering/tlvs/tlv (list) YANG Description: The Type-Length-Value tuples included in the TE LSA """ return self.__tlv def _set_tlv(self, v, load=False): """ Setter method for tlv, mapped from YANG variable /network_instances/network_instance/protocols/protocol/ospfv2/areas/area/lsdb/lsa_types/lsa_type/lsas/lsa/opaque_lsa/traffic_engineering/tlvs/tlv (list) If this variable is read-only (config: false) in the source YANG file, then _set_tlv is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_tlv() directly. YANG Description: The Type-Length-Value tuples included in the TE LSA """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass( v, base=YANGListType( False, tlv.tlv, yang_name="tlv", parent=self, is_container="list", user_ordered=False, path_helper=self._path_helper, yang_keys="False", extensions=None, ), is_container="list", yang_name="tlv", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace="http://openconfig.net/yang/network-instance", defining_module="openconfig-network-instance", yang_type="list", is_config=False, ) except (TypeError, ValueError): raise ValueError( { "error-string": """tlv must be of a type compatible with list""", "defined-type": "list", "generated-type": """YANGDynClass(base=YANGListType(False,tlv.tlv, yang_name="tlv", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='False', extensions=None), is_container='list', yang_name="tlv", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='list', is_config=False)""", } ) self.__tlv = t if hasattr(self, "_set"): self._set() def _unset_tlv(self): self.__tlv = YANGDynClass( base=YANGListType( False, tlv.tlv, yang_name="tlv", parent=self, is_container="list", user_ordered=False, path_helper=self._path_helper, yang_keys="False", extensions=None, ), is_container="list", yang_name="tlv", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace="http://openconfig.net/yang/network-instance", defining_module="openconfig-network-instance", yang_type="list", is_config=False, ) tlv = __builtin__.property(_get_tlv) _pyangbind_elements = OrderedDict([("tlv", tlv)]) from . import tlv class tlvs(PybindBase): """ This class was auto-generated by the PythonClass plugin for PYANG from YANG module openconfig-network-instance-l2 - based on the path /network-instances/network-instance/protocols/protocol/ospfv2/areas/area/lsdb/lsa-types/lsa-type/lsas/lsa/opaque-lsa/traffic-engineering/tlvs. Each member element of the container is represented as a class variable - with a specific YANG type. YANG Description: The TLVs contained in the TE Opaque LSA """ __slots__ = ("_path_helper", "_extmethods", "__tlv") _yang_name = "tlvs" _pybind_generated_by = "container" def __init__(self, *args, **kwargs): self._path_helper = False self._extmethods = False self.__tlv = YANGDynClass( base=YANGListType( False, tlv.tlv, yang_name="tlv", parent=self, is_container="list", user_ordered=False, path_helper=self._path_helper, yang_keys="False", extensions=None, ), is_container="list", yang_name="tlv", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace="http://openconfig.net/yang/network-instance", defining_module="openconfig-network-instance", yang_type="list", is_config=False, ) load = kwargs.pop("load", None) if args: if len(args) > 1: raise TypeError("cannot create a YANG container with >1 argument") all_attr = True for e in self._pyangbind_elements: if not hasattr(args[0], e): all_attr = False break if not all_attr: raise ValueError("Supplied object did not have the correct attributes") for e in self._pyangbind_elements: nobj = getattr(args[0], e) if nobj._changed() is False: continue setmethod = getattr(self, "_set_%s" % e) if load is None: setmethod(getattr(args[0], e)) else: setmethod(getattr(args[0], e), load=load) def _path(self): if hasattr(self, "_parent"): return self._parent._path() + [self._yang_name] else: return [ "network-instances", "network-instance", "protocols", "protocol", "ospfv2", "areas", "area", "lsdb", "lsa-types", "lsa-type", "lsas", "lsa", "opaque-lsa", "traffic-engineering", "tlvs", ] def _get_tlv(self): """ Getter method for tlv, mapped from YANG variable /network_instances/network_instance/protocols/protocol/ospfv2/areas/area/lsdb/lsa_types/lsa_type/lsas/lsa/opaque_lsa/traffic_engineering/tlvs/tlv (list) YANG Description: The Type-Length-Value tuples included in the TE LSA """ return self.__tlv def _set_tlv(self, v, load=False): """ Setter method for tlv, mapped from YANG variable /network_instances/network_instance/protocols/protocol/ospfv2/areas/area/lsdb/lsa_types/lsa_type/lsas/lsa/opaque_lsa/traffic_engineering/tlvs/tlv (list) If this variable is read-only (config: false) in the source YANG file, then _set_tlv is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_tlv() directly. YANG Description: The Type-Length-Value tuples included in the TE LSA """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass( v, base=YANGListType( False, tlv.tlv, yang_name="tlv", parent=self, is_container="list", user_ordered=False, path_helper=self._path_helper, yang_keys="False", extensions=None, ), is_container="list", yang_name="tlv", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace="http://openconfig.net/yang/network-instance", defining_module="openconfig-network-instance", yang_type="list", is_config=False, ) except (TypeError, ValueError): raise ValueError( { "error-string": """tlv must be of a type compatible with list""", "defined-type": "list", "generated-type": """YANGDynClass(base=YANGListType(False,tlv.tlv, yang_name="tlv", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='False', extensions=None), is_container='list', yang_name="tlv", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='list', is_config=False)""", } ) self.__tlv = t if hasattr(self, "_set"): self._set() def _unset_tlv(self): self.__tlv = YANGDynClass( base=YANGListType( False, tlv.tlv, yang_name="tlv", parent=self, is_container="list", user_ordered=False, path_helper=self._path_helper, yang_keys="False", extensions=None, ), is_container="list", yang_name="tlv", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace="http://openconfig.net/yang/network-instance", defining_module="openconfig-network-instance", yang_type="list", is_config=False, ) tlv = __builtin__.property(_get_tlv) _pyangbind_elements = OrderedDict([("tlv", tlv)]) ```
[ { "content": "Here is the snippet:\n```python\n#\n#\n# OpenERP, Open Source Management Solution\n# Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved\n#\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public L...
[ { "content": "Here is the snippet:\n<|memory_start|>```python\n#\n#\n# OpenERP, Open Source Management Solution\n# Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved\n#\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU ...
```python # # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved # # # 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/>. # # from openerp.osv import fields, osv from openerp.tools.translate import _ class project_task(osv.osv): _inherit = 'project.task' def _message_get_auto_subscribe_fields(self, cr, uid, updated_fields, auto_follow_fields=['user_id'], context=None): res = super(project_task, self)._message_get_auto_subscribe_fields(cr, uid, updated_fields, auto_follow_fields=auto_follow_fields, context=context) res.append('project_leader_id') return res def send_mail_task_new_test(self, cr, uid, ids, context=None): ''' Send mail automatically to change task to Backlog and to Testing Leader. ''' context = context or {} #Dont send context to dont get language of user in read method if ids.get('stage_id'): type = self.pool.get('project.task.type').read(cr, uid, ids['stage_id'][0], ['name']) if type.get('name', False) == 'Backlog': self.send_mail_task(cr,uid,ids,'template_send_email_task_new',context) elif type.get('name', False) == 'Testing Leader': self.send_mail_task(cr,uid,ids,'template_send_email_task_end',context) def send_mail_task(self,cr,uid,ids,template,context=None): imd_obj = self.pool.get('ir.model.data') template_ids = imd_obj.search( cr, uid, [('model', '=', 'email.template'), ('name', '=', template)]) if template_ids: res_id = imd_obj.read( cr, uid, template_ids, ['res_id'])[0]['res_id'] followers = self.read(cr, uid, ids.get('id'), [ 'message_follower_ids'])['message_follower_ids'] ids = [ids.get('id')] body_html = self.pool.get('email.template').read( cr, uid, res_id, ['body_html']).get('body_html') context.update({'default_template_id': res_id, 'default_body': body_html, 'default_use_template': True, 'default_composition_mode': 'comment', 'active_model': 'project.task', 'default_partner_ids': followers, 'mail_post_autofollow_partner_ids': followers, 'active_id': ids and type(ids) is list and ids[0] or ids, 'active_ids': ids and type(ids) is list and ids or [ids], }) mail_obj = self.pool.get('mail.compose.message') fields = mail_obj.fields_get(cr, uid) mail_ids = mail_obj.default_get( cr, uid, fields.keys(), context=context) mail_ids.update( {'model': 'project.task', 'body': body_html, 'composition_mode': 'mass_mail', 'partner_ids': [(6, 0, followers)]}) mail_ids = mail_obj.create(cr, uid, mail_ids, context=context) mail_obj.send_mail(cr, uid, [mail_ids], context=context) return False _track = {'stage_id': {'project.mt_task_stage': send_mail_task_new_test, }} _columns = { 'project_leader_id': fields.many2one('res.users','Project Leader',help="""Person responsible of task review, when is in Testing Leader state. The person should review: Work Summary, Branch and Make Functional Tests. When everything works this person should change task to done."""), } _defaults = { 'project_leader_id': lambda obj,cr,uid,context: uid, } ```
[ { "content": "Repeat the code exactly:\n```python\n#\n# Copyright 2009 Flavio Percoco Premoli\n#\n# This file is part of Ocvfw.\n#\n# Ocvfw is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License v2 as published\n# by the Free Software Foundation.\n#\n# Oc...
[ { "content": "Repeat the code exactly:\n<|memory_start|>```python\n#\n# Copyright 2009 Flavio Percoco Premoli\n#\n# This file is part of Ocvfw.\n#\n# Ocvfw is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License v2 as published\n# by the Free Software Foun...
```python # # Copyright 2009 Flavio Percoco Premoli # # This file is part of Ocvfw. # # Ocvfw is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License v2 as published # by the Free Software Foundation. # # Ocvfw 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 Ocvfw. If not, see <http://www.gnu.org/licenses/>>. """Little Framework for OpenCV Library.""" __id__ = "$Id$" __version__ = "$Revision$" __date__ = "$Date$" __copyright__ = "Copyright (c) 2008 Flavio Percoco Premoli" __license__ = "GPLv2" import time import debug import commons as co import cv2 #remove import cv2.cv as cv import numpy import array class OcvfwBase: def __init__( self ): """ Initialize the module and set its main variables. """ self.img = None self.mhi = None self.img_lkpoints = { "current" : [], "last" : [], "points" : [] } self.__lk_swap = False self.imageScale = 1.5 def set(self, key, value): """ """ if hasattr(self, "%s" % key): getattr(self, "%s" % key)(value) debug.debug("_ocv - set", "Changed %s value to %s" % (key, value)) return True debug.debug("_ocv - set", "%s not found" % (key)) return False def lk_swap(self, set=None): """ Enables/Disable the lk points swapping action. Arguments: - self: The main object pointer. - set: The new value. If None returns the current state. """ if set is None: return self.__lk_swap self.__lk_swap = set def new_image(self, size, num, ch): """ Creates a new image """ #if type(size) == "<type 'tuple'>": #size = co.cv.cvSize( size[0], size[1]) return co.cv.CreateImage( (size[0], size[1]), num, ch)# was size' def set_camera_idx(self, idx): """ Changes the camera device index. Arguments: - self: The main object pointer. - idx: The camera index. For Example: 0 for /dev/video0 """ self.idx = idx def wait_key(self, num): """ Simple call to the co.cv.WaitKey function, which has to be called periodically. Arguments: - self: The main object pointer. - num: An int value. """ return co.cv.WaitKey(num) def start_camera(self, params = None): """ Starts the camera capture Arguments: - params: A list with the capture properties. NOTE: Not implemented yet. """ self.capture = cv.CaptureFromCAM(self.idx ) debug.debug( "ocvfw", "start_camera: Camera Started" ) def query_image(self, bgr=False, flip=False): """ Queries the new frame. Arguments: - self: The main object pointer. - bgr: If True. The image will be converted from RGB to BGR. Returns The image even if it was stored in self.img """ frame = cv.QueryFrame( self.capture ) #Test to make sure camera starts properly #cv.ShowImage("webcam", frame) if not self.img: self.storage = co.cv.CreateMemStorage(0) self.imgSize = co.cv.GetSize (frame) self.img = co.cv.CreateImage ( self.imgSize, 8, 3 ) #self.img.origin = frame.origin self.grey = co.cv.CreateImage ( self.imgSize, 8, 1 ) self.yCrCb = co.cv.CreateImage ( self.imgSize, 8, 3 ) self.prevGrey = co.cv.CreateImage ( self.imgSize, 8, 1 ) self.pyramid = co.cv.CreateImage ( self.imgSize, 8, 1 ) self.prevPyramid = co.cv.CreateImage ( self.imgSize, 8, 1 ) #a = co.cv.Round(self.img.width/self.imageScale) #b = co.cv.Round(self.img.height/self.imageScale) #c = (a, b) self.small_img = co.cv.CreateImage( ( co.cv.Round(self.img.width/self.imageScale), co.cv.Round(self.img.height/self.imageScale) ), 8, 3 ) self.img = frame self.wait_key(10) return True def set_lkpoint(self, point): """ Set a point to follow it using the L. Kallman method. Arguments: - self: The main object pointer. - point: A co.cv.Point Point. """ #Point = co.cv.Point( point.x, point.y ) self.img_lkpoints["current"] = numpy.zeros((point.x, point.y), numpy.float32) self.img_lkpoints["current"] = cv.fromarray(self.img_lkpoints["current"]) self.grey = numpy.asarray(self.grey[:,:]) #new if numpy.all(self.img_lkpoints["current"]): #co.cv.FindCornerSubPix( cv2.cornerSubPix( # was cv.FindCornerSubPix self.grey, self.img_lkpoints["current"], (20, 20), (0,0), (cv.CV_TERMCRIT_ITER | cv.CV_TERMCRIT_EPS, 20, 0.03)) point.set_opencv( point ) self.img_lkpoints["points"].append(point) setattr(point.parent, point.label, point) if len(self.img_lkpoints["last"]) > 0: self.img_lkpoints["last"].append( self.img_lkpoints["current"][0] ) debug.debug( "ocvfw", "cmSetLKPoints: New LK Point Added" ) else: self.img_lkpoints["current"] = [] def clean_lkpoints(self): """ Cleans all the registered points. Arguments: - self: The main object pointer """ self.img_lkpoints = { "current" : [], "last" : [], "points" : [] } def show_lkpoints(self): """ Calculate the optical flow of the set points and draw them in the image. Arguments: - self: The main object pointer. """ self.prevGrey = numpy.asarray(self.prevGrey[:,:]) prevGrey = cv2.cvtColor(self.prevGrey, cv2.COLOR_BGR2GRAY) self.grey = numpy.asarray(self.grey[:,:]) grey = cv2.cvtColor(self.grey, cv2.COLOR_BGR2GRAY) # calculate the optical flow nextPts, status, err = cv2.calcOpticalFlowPyrLK ( prevGrey, #prevImg grey, #nextImg self.prevPyramid, #prevPts self.pyramid, #nextPts None, #status (20, 20), #winSize 2, #maxLevel (cv2.TERM_CRITERIA_MAX_ITER|cv2.TERM_CRITERIA_EPS, 20, 0.03), #criteria cv2.OPTFLOW_USE_INITIAL_FLOW #flags ) cv.ShowImage("test",self.grey) if isinstance(optical_flow[0], tuple): self.img_lkpoints["current"], status = optical_flow[0] else: self.img_lkpoints["current"], status = optical_flow # initializations counter = 0 new_points = [] for point in self.img_lkpoints["current"]: if not status[counter]: continue # this point is a correct point current = self.img_lkpoints["points"][counter] current.set_opencv(co.cv.Point(int(point.x), int(point.y))) new_points.append( point ) setattr(current.parent, current.label, current) # draw the current point current.parent.draw_point(point.x, point.y) # increment the counter counter += 1 #debug.debug( "ocvfw", "cmShowLKPoints: Showing %d LK Points" % counter ) # set back the self.imgPoints we keep self.img_lkpoints["current"] = new_points def swap_lkpoints(self): """ Swap the LK method variables so the new points will be the last points. This function has to be called after showing the new points. Arguments: - self: The main object pointer. """ # swapping self.prevGrey, self.grey = self.grey, self.prevGrey self.prevPyramid, self.pyramid = self.pyramid, self.prevPyramid self.img_lkpoints["last"], self.img_lkpoints["current"] = \ self.img_lkpoints["current"], self.img_lkpoints["last"] class OcvfwCtypes(OcvfwBase): """ This Class controlls the main camera functions. It works as a little framework for Opencv.cv. This Backend uses ctypes opencv python bindings. """ def __init__(self): """ Initialize the module and set its main variables. """ co.cv = __import__("pyopencv.cv", globals(), locals(), ['']) co.hg = __import__("pyopencv.cv", globals(), locals(), [''])#should be removed OcvfwBase.__init__(self) class OcvfwPython(OcvfwBase): """ This Class controlls the main camera functions. It works as a little framework for Openco.cv. This Backend uses normal opencv python bindings. """ co.cv = __import__("cv", globals(), locals(), ['']) co.hg = __import__("cv", globals(), locals(), ['']) #should be removed def __init__( self ): """ Initialize the module and set its main variables. """ OcvfwBase.__init__(self) def add_message(self, message, font=co.cv.CV_FONT_HERSHEY_COMPLEX, poss=None): """ Write a message into the image. Arguments: - self: The main object pointer. - message: A string with the message. - font: An OpenCV font to use. - poss: The position of the message in the image. NOTE: Not enabled yet. """ font = co.cv.InitFont ( font, 1, 1, 0.0, 1, co.cv.CV_AA) textSize, ymin = co.cv.GetTextSize (message, font) pt1 = (( self.img.width - textSize.width ) / 2 , 20 ) co.cv.PutText (self.img, message, pt1, font, co.cv.Scalar (255, 0, 0)) def get_haar_points(self, haarCascade, method=co.cv.CV_HAAR_DO_CANNY_PRUNING): """ Search for points matching the haarcascade selected. Arguments: - self: The main object pointer. - haarCascade: The selected cascade. - methode: The search method to use. DEFAULT: co.cv.CV_HAAR_DO_CANNY_PRUNING. Returns a list with the matches. """ cascade = co.cv.Load( haarCascade) #, self.imgSize ) if not cascade: debug.exception( "ocvfw", "The Haar Classifier Cascade load failed" ) co.cv.Resize( self.img, self.small_img, co.cv.CV_INTER_LINEAR ) #co.cv.ClearMemStorage( self.storage ) points = co.cv.HaarDetectObjects( self.small_img, cascade, self.storage, 1.2, 2, method, (20, 20) ) if points: matches = [ [ ( int(r[0][0]*self.imageScale), int(r[0][1]*self.imageScale)), \ ( int((r[0][0]+r[0][3])*self.imageScale), int((r[0][0]+r[0][2])*self.imageScale) )] \ for r in points] debug.debug( "ocvfw", "cmGetHaarPoints: detected some matches" ) return matches def get_haar_roi_points(self, haarCascade, rect, origSize=(0, 0), method=co.cv.CV_HAAR_DO_CANNY_PRUNING): """ Search for points matching the haarcascade selected. Arguments: - self: The main object pointer. - haarCascade: The selected cascade. - methode: The search method to use. DEFAULT: co.cv.CV_HAAR_DO_CANNY_PRUNING. Returns a list with the matches. """ cascade = co.cv.Load( haarCascade ) #, self.imgSize ) if not cascade: debug.exception( "ocvfw", "The Haar Classifier Cascade load failed" ) debug.debug( "ocvfw-get_haar_roi_points", self.img) #FIXME: Work around to fix when the rect is too big if (rect[0]+rect[2]) > self.img.width: rect = (rect[0], rect[1], self.img.width-rect[0],self.img.height-rect[1]) if (rect[1]+rect[3]) > self.img.height: rect = (rect[0], rect[1], self.img.width-rect[0],self.img.height-rect[1]) try: imageROI = co.cv.GetSubRect(self.img, rect) except cv2.error: print "****** imageROI error _ocv", self.img, rect if cascade: points = co.cv.HaarDetectObjects( imageROI, cascade, self.storage, 1.2, 2, method, (20,20) ) else: debug.exception( "ocvfw", "The Haar Classifier Cascade load Failed (ROI)" ) if points: matches = [ [ ( int(r[0][0]*origSize[0]), int(r[0][1]*origSize[1])), \ ( int((r[0][0]+r[0][3])+origSize[0]), int((r[0][1]+r[0][2])*origSize[1]) )] \ for r in points] #matches = [ [ ( int(r[0][0]), int(r[0][1])), \ # ( int((r[0][0]+r[0][3])), int((r[0][1]+r[0][2])) )] \ # for r in points] #FIXME: I don't think the matches are right return matches ########################################## # # # THIS IS NOT USED YET # # # ########################################## def get_motion_points(self, imgRoi=None): """ Calculate the motion points in the image. Arguments: - self: The main object pointer. - start: The start ROI point. - end: The end ROI point. - num: The nomber of points to return Returns A list with the points found. """ mv = [] n_ = 4 timestamp = time.clock()/1.0 if imgRoi: img = co.cv.GetSubRect( self.img, imgRoi ) imgSize = co.cv.cvSize( imgRoi.width, imgRoi.height ) self.imgRoi = img else: img = self.img imgSize = self.imgSize # Motion Related Variables if not self.mhi or self.mhi.width != imgSize.width or self.mhi.height != imgSize.height: self.buf = [ 0, 0, 0, 0 ] self.lastFm = 0 self.mhiD = 1 self.maxTD = 0.5 self.minTD = 0.05 self.mask = co.cv.CreateImage( imgSize, 8, 1 ) self.mhi = co.cv.CreateImage( imgSize, 32, 1 ) self.orient = co.cv.CreateImage( imgSize, 32, 1 ) self.segmask = co.cv.CreateImage( imgSize, 32, 1 ) co.cv.SetZero( self.mhi ) for i in range( n_ ): self.buf[i] = co.cv.CreateImage( imgSize, 8, 1 ) co.cv.cvZero( self.buf[i] ) idx1 = self.lastFm # convert frame to grayscale cv2.cvtColor( img, self.buf[self.lastFm], cv2.CV_BGR2GRAY ) # index of (self.lastFm - (n_-1))th frame idx2 = ( self.lastFm + 1 ) % n_ self.lastFm = idx2 silh = self.buf[idx2] # Get difference between frames co.cv.cvAbsDiff( self.buf[idx1], self.buf[idx2], silh ) # Threshold it co.cv.cvThreshold( silh, silh, 30, 1, co.cv.CV_THRESH_BINARY ) # Update MHI co.cv.cvUpdateMotionHistory( silh, self.mhi, timestamp, self.mhiD ) co.cv.cvCvtScale( self.mhi, self.mask, 255./self.mhiD, (self.mhiD - timestamp)*255./self.mhiD ) co.cv.cvCalcMotionGradient( self.mhi, self.mask, self.orient, self.maxTD, self.minTD, 3 ) co.cv.cvClearMemStorage( self.storage ) seq = co.cv.cvSegmentMotion( self.mhi, self.segmask, self.storage, timestamp, self.maxTD ) for i in range(0, seq.total): if i < 0: # case of the whole image continue else: # i-th motion component # Movement Rectangle mRect = seq[i].rect # reject very small components if( mRect.width + mRect.height < 30 ): continue center = co.cv.Point( (mRect.x + mRect.width/2), (mRect.y + mRect.height/2) ) silhRoi = co.cv.cvGetSubRect(silh, mRect) count = co.cv.cvNorm( silhRoi, None, co.cv.CV_L1, None ) # calculate number of points within silhouette ROI if( count < mRect.width * mRect.height * 0.05 ): continue mv.append(center) return mv ```
[ { "content": "Repeat the code exactly as the original, including blank lines:\n```python\n# -*- coding: utf-8 -*-\n#\n#\n# Author: Yannick Vaucher\n# Copyright 2014 Camptocamp SA\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero Genera...
[ { "content": "Repeat the code exactly as the original, including blank lines:\n<|memory_start|>```python\n# -*- coding: utf-8 -*-\n#\n#\n# Author: Yannick Vaucher\n# Copyright 2014 Camptocamp SA\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the G...
```python # -*- coding: utf-8 -*- # # # Author: Yannick Vaucher # Copyright 2014 Camptocamp SA # # 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/>. # # {"name": "Purchase Requisition Multicurrency", "version": "0.1", "author": "Camptocamp", "license": "AGPL-3", "category": "Purchase Management", "complexity": "normal", "images": [], "depends": ["purchase_requisition", ], "demo": [], "data": ["view/purchase_order.xml", "view/purchase_requisition.xml", ], "auto_install": False, "test": [], "installable": True, "certificate": "", } ```
[ { "content": "Return the code unaltered:\n```python\n#! /urs/bin/python\n# coding: utf8\nfrom __future__ import print_function\nimport pymongo\nfrom random import uniform\n\nTWEETS_LIMIT = 0\nTRACES_LIMIT = 0\n\nclass DBClient(object):\n '''Docstring for DBClient'''\n\n def __init__(self):\n super(...
[ { "content": "Return the code unaltered:\n<|memory_start|>```python\n#! /urs/bin/python\n# coding: utf8\nfrom __future__ import print_function\nimport pymongo\nfrom random import uniform\n\nTWEETS_LIMIT = 0\nTRACES_LIMIT = 0\n\nclass DBClient(object):\n '''Docstring for DBClient'''\n\n def __init__(self):...
```python #! /urs/bin/python # coding: utf8 from __future__ import print_function import pymongo from random import uniform TWEETS_LIMIT = 0 TRACES_LIMIT = 0 class DBClient(object): '''Docstring for DBClient''' def __init__(self): super(DBClient, self).__init__() self.mongo = pymongo.MongoClient() self.db = self.mongo.treets self.db.tweets.create_index('userName') self.db.users.create_index([('userName', 'text')]) self.db.tweets.create_index([('textMessage', 'text')]) self.db.tweets.ensure_index([('location', pymongo.GEOSPHERE)]) #self.users = self.tweets.distinct('userName')[:limit] def setup_db(self): self.create_locations() self.check_text_index() self.create_users_collection() self.remove_users_and_tweets(100) def remove_users_and_tweets(self, threshold_max, threshold_min=1): found = self.db.users.find( { '$where': 'this.tweetsIds.length >' + str(threshold_max) }) for u in found: self.db.tweets.remove({'_id': {'$in': u['tweetsIds']}}) self.db.users.remove( u ) def create_users_collection(self): self.db.users.remove() users = self.db.tweets.distinct('userName') users_coll = [] for u in users: user = {} user['userName'] = u user['tweetsIds'] = self.db.tweets.find({'userName': u}).distinct('_id') users_coll.append(user) self.db.users.insert(users_coll) def create_locations(self): print('creating locations for geo-indexing, this may take a while') for t in self.db.tweets.find(): coords = t['geo'] t['location'] = {'type': 'Point', 'coordinates': coords[::-1]} self.db.tweets.save(t) self.db.tweets.ensure_index([('location', pymongo.GEOSPHERE)]) def check_text_index(self): try: self.db.tweets.create_index([('textMessage', 'text')]) except: print('converting texts to unicode, this may take a while') for t in self.db.tweets.find(): t['textMessage'] = unicode(t['textMessage']) self.db.tweets.save(t) self.db.tweets.create_index([('textMessage', 'text')]) def get_tweets(self, limit=TWEETS_LIMIT): ''' Returns first <limit> tweets ''' return self.db.tweets.find().sort([('_id', -1)]).limit(limit) def get_random_tweets(self, limit=TWEETS_LIMIT): ''' returns <limit> random tweets ''' lenght = self.db.tweets.find().count() rand = int(uniform(0, 1)*lenght) return self.db.tweets.find().limit(limit).skip(rand) def get_tweets_near_point(self, coords, dist, limit=TWEETS_LIMIT): ''' returns <limit> tweets whithin <dist> meters from coords ''' return self.db.tweets.find({ 'location': { '$nearSphere': { '$geometry': { 'type': 'Point', 'coordinates': coords }, '$maxDistance': dist } } }).sort([('_id', -1)]) def get_tweets_near_point_and_text(self, coords, dist, text, limit=TWEETS_LIMIT): ''' returns <limit> tweets whithin <dist> meters from coords ''' return self.db.tweets.find( { "$and": [{"location":{'$geoWithin':{'$centerSphere': [coords,dist/6378.1]}}}, {'$text':{'$search': text}}] }).sort([('_id', -1)]) def get_tweets_for_text(self, text, limit=TWEETS_LIMIT): ''' search for tweets containing <text> and returns results ''' return self.db.tweets.find({'$text': {'$search': text}}).sort([('_id', -1)]).limit(limit) def get_tweets_for_user(self, user, limit=TWEETS_LIMIT): ''' returns tweets posted by user ''' return self.db.tweets.find({'_id': {'$in': user['tweetsIds']}}) #return self.db.tweets.find({'userName': user}).sort([('_id', -1)]).limit(limit) def get_tweets_for_user_str(self, username, limit=TWEETS_LIMIT): user = self.db.users.find_one({'$text': {'$search': username}}) if user: return [self.get_tweets_for_user(user, limit)] else: return [] def get_traces(self, limit=TRACES_LIMIT): ''' Returns first <limit> lists of tweets from the same users ''' users = self.db.users.find().limit(limit) return [self.get_tweets_for_user(user) for user in users] def get_traces_near_point(self, coords, dist, limit=TRACES_LIMIT): ''' TODO docstring ''' users = self.get_tweets_near_point(coords, dist).distinct('userName') users_objs = self.db.users.find({'userName': {'$in': users}}).limit(limit) return [self.get_tweets_for_user(user) for user in users_objs] def get_traces_near_point_and_text(self, coords, dist, text, limit=TRACES_LIMIT): ''' TODO docstring ''' users = self.get_tweets_near_point_and_text(coords, dist, text).distinct('userName') users_objs = self.db.users.find({'userName': {'$in': users}}).limit(limit) return [self.get_tweets_for_user(user) for user in users_objs] def get_traces_for_text(self, text, limit=TRACES_LIMIT): ''' TODO docstring ''' users = self.get_tweets_for_text(text, limit=limit).distinct('userName') users_objs = self.db.users.find({'userName': {'$in': users}}).limit(limit) return [self.get_tweets_for_user(user) for user in users_objs] def get_trace_for_user(self, username): ''' TODO docstring ''' return self.get_tweets_for_user_str(username) if __name__ == '__main__': client = DBClient() #client.create_users_collection() client.remove_users_and_tweets(100, 3) ```
[ { "content": "Repeat the code exactly as the original, including blank lines:\n```python\n\"\"\"\n gstation-edit MidiPort definition\n\"\"\"\n# this file is part of gstation-edit\n# Copyright (C) F LAIGNEL 2009-2017 <fengalin@free.fr>\n#\n# gstation-edit is free software: you can redistribute it and/or modify i...
[ { "content": "Repeat the code exactly as the original, including blank lines:\n<|memory_start|>```python\n\"\"\"\n gstation-edit MidiPort definition\n\"\"\"\n# this file is part of gstation-edit\n# Copyright (C) F LAIGNEL 2009-2017 <fengalin@free.fr>\n#\n# gstation-edit is free software: you can redistribute it...
```python """ gstation-edit MidiPort definition """ # this file is part of gstation-edit # Copyright (C) F LAIGNEL 2009-2017 <fengalin@free.fr> # # gstation-edit 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. # # gstation-edit 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/>. class MidiPort: def __init__(self, client, port, port_name): self.client = client self.port = port self.port_name = port_name def __str__(self): return '%s %d:%d'%(self.port_name, self.client, self.port) ```
[ { "content": "Provide a verbatim copy of the code:\n```python\nimport pytest\nimport doctest\nfrom insights.tests import context_wrap\nfrom insights.parsers import SkipException\nfrom insights.parsers import pmrep\nfrom insights.parsers.pmrep import PMREPMetrics\n\nPMREPMETRIC_DATA = \"\"\"\nTime,\"network.inte...
[ { "content": "Provide a verbatim copy of the code:\n<|memory_start|>```python\nimport pytest\nimport doctest\nfrom insights.tests import context_wrap\nfrom insights.parsers import SkipException\nfrom insights.parsers import pmrep\nfrom insights.parsers.pmrep import PMREPMetrics\n\nPMREPMETRIC_DATA = \"\"\"\nTim...
```python import pytest import doctest from insights.tests import context_wrap from insights.parsers import SkipException from insights.parsers import pmrep from insights.parsers.pmrep import PMREPMetrics PMREPMETRIC_DATA = """ Time,"network.interface.out.packets-lo","network.interface.out.packets-eth0","network.interface.collisions-lo","network.interface.collisions-eth0","swap.pagesout","mssql.memory_manager.stolen_server_memory","mssql.memory_manager.total_server_memory" 2021-04-26 05:42:24,,,,, 2021-04-26 05:42:25,1.000,2.000,3.000,4.000,5.000,349816,442000 """.strip() PMREPMETRIC_DATA_2 = """ Time,"network.interface.out.packets-lo","network.interface.collisions-lo","swap.pagesout" 2021-04-26 05:42:24,,, 2021-04-26 05:42:25,1.000,2.000,3.000 """.strip() PMREPMETRIC_WRONG_DATA = """ Time,"network.interface.out.packets-lo","network.interface.collisions-lo","swap.pagesout" """.strip() PMREPMETRIC_EMPTY_DATA = """ """.strip() def test_pmrep_info(): pmrep_table = PMREPMetrics(context_wrap(PMREPMETRIC_DATA)) pmrep_table = sorted(pmrep_table, key=lambda x: x['name']) assert pmrep_table[0] == {'name': 'Time', 'value': '2021-04-26 05:42:25'} assert pmrep_table[1] == {'name': 'mssql.memory_manager.stolen_server_memory', 'value': '349816'} assert pmrep_table[2] == {'name': 'mssql.memory_manager.total_server_memory', 'value': '442000'} assert pmrep_table[3] == {'name': 'network.interface.collisions-eth0', 'value': '4.000'} assert pmrep_table[4] == {'name': 'network.interface.collisions-lo', 'value': '3.000'} assert pmrep_table[5] == {'name': 'network.interface.out.packets-eth0', 'value': '2.000'} assert pmrep_table[6] == {'name': 'network.interface.out.packets-lo', 'value': '1.000'} assert pmrep_table[7] == {'name': 'swap.pagesout', 'value': '5.000'} pmrep_table = PMREPMetrics(context_wrap(PMREPMETRIC_DATA_2)) pmrep_table = sorted(pmrep_table, key=lambda x: x['name']) assert pmrep_table[0] == {'name': 'Time', 'value': '2021-04-26 05:42:25'} assert pmrep_table[1] == {'name': 'network.interface.collisions-lo', 'value': '2.000'} assert pmrep_table[2] == {'name': 'network.interface.out.packets-lo', 'value': '1.000'} assert pmrep_table[3] == {'name': 'swap.pagesout', 'value': '3.000'} pmrep_table = PMREPMetrics(context_wrap(PMREPMETRIC_DATA)) assert sorted(pmrep_table.search(name__endswith='lo'), key=lambda x: x['name']) == [{'name': 'network.interface.collisions-lo', 'value': '3.000'}, {'name': 'network.interface.out.packets-lo', 'value': '1.000'}] assert sorted(pmrep_table.search(name__endswith='swap.pagesout'), key=lambda x: x['name']) == [{'name': 'swap.pagesout', 'value': '5.000'}] def test_empty(): with pytest.raises(SkipException) as e: PMREPMetrics(context_wrap(PMREPMETRIC_EMPTY_DATA)) assert 'There is no data in the table' in str(e) def test_wrong_data(): with pytest.raises(SkipException) as e: PMREPMetrics(context_wrap(PMREPMETRIC_WRONG_DATA)) assert 'There is no data in the table' in str(e) def test_pmrep_doc_examples(): env = { 'pmrep_doc_obj': PMREPMetrics(context_wrap(PMREPMETRIC_DATA)), 'pmrep_doc_obj_search': PMREPMetrics(context_wrap(PMREPMETRIC_DATA)) } failed, total = doctest.testmod(pmrep, globs=env) assert failed == 0 ```
[ { "content": "```python\n\"\"\"\nContains classes controlling wizards for making new maps\n\"\"\"\n\nimport tkinter as tk\nimport mathsmap.colours as colours\n\nclass Wizard:\n \"\"\"\n A base class for all wizards in this project\n \"\"\"\n def clear(self):\n \"\"\"\n Remove all curre...
[ { "content": "<|memory_start|>```python\n\"\"\"\nContains classes controlling wizards for making new maps\n\"\"\"\n\nimport tkinter as tk\nimport mathsmap.colours as colours\n\nclass Wizard:\n \"\"\"\n A base class for all wizards in this project\n \"\"\"\n def clear(self):\n \"\"\"\n ...
```python """ Contains classes controlling wizards for making new maps """ import tkinter as tk import mathsmap.colours as colours class Wizard: """ A base class for all wizards in this project """ def clear(self): """ Remove all current widgets from top level of wizard """ for child in self.top.winfo_children(): child.destroy() class NewMap(Wizard): """ Class for any new map """ def __init__(self, controller): """ Set up NewMap wizard """ self.controller = controller self.top = tk.Toplevel() self.top.title("Make a new map") self.welcome_screen() def welcome_screen(self): """ Sets up first screen of wizard """ self.clear() self.scheme = colours.BLUESCHEME self.background = self.scheme.lighter self.top.configure(background=self.background) self.title = tk.Label(self.top, text="Let's make a new map!", font=(None, 20), background=self.background) self.title.grid(row=0, column=0, columnspan=2) self.text = tk.Label(self.top, text=("When do you need to make your mathsmap? " + "Is it right now, possibly in a rush before exams, " + "or over time, while you attend lectures and learn?"), wraplength=400, background=self.background ) self.text.grid(row=1, column=0, columnspan=2) buttons_needed = [("Right now!", 0), ("Over time!", 1)] for text, column in buttons_needed: button = tk.Button(self.top, text=text, width=15, height=3, background=self.scheme.darkest, activebackground=self.scheme.darker, foreground="white", font=(None, 15)) button.grid(row=2, column=column, pady=5) def clear(self): """ Remove all current widgets from top level """ for child in self.top.winfo_children(): child.destroy() class NewFutureMap(Wizard): """ Class for new maps to be added to slowly in the future """ pass class NewNowMap(Wizard): """ Class for new maps to be added to and completed right now """ pass ```
[ { "content": "```python\n# ##### BEGIN GPL LICENSE BLOCK #####\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; either version 2\n# of the License, or (at your option) any later...
[ { "content": "<|memory_start|>```python\n# ##### BEGIN GPL LICENSE BLOCK #####\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; either version 2\n# of the License, or (at your o...
```python # ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### import socket import bpy from bpy.props import IntProperty, FloatProperty, EnumProperty, StringProperty, BoolProperty from sverchok.node_tree import SverchCustomTreeNode, StringsSocket from sverchok.utils.profile import profile from sverchok.data_structure import updateNode class UdpClientNode(bpy.types.Node, SverchCustomTreeNode): bl_idname = 'UdpClientNode' bl_label = 'UDP Client' def send_msg(self, context): sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.setblocking(0) sock.sendto(bytes(self.send, 'UTF-8'), (self.ip, self.port)) def recv_msg(self): sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.setblocking(0) sock.settimeout(self.timeout) try: data, _ = sock.recvfrom(self.buffer_size) self.receive = data.decode('UTF-8') except socket.timeout: print('Timeout') send = StringProperty(name='send', description='Message to send', default='message', update=send_msg) receive = StringProperty(name='receive', description='Received message', default='', update=updateNode) ip = StringProperty(name='ip', description='IP address of server', default='127.0.0.1') port = IntProperty(name='port', description='Port number to send message', default=9250) buffer_size = IntProperty(name='buffer_size', description='Size of buffer', default=8192) timeout = FloatProperty(name='timeout', description='Timeout (sec)', default=0.5) active = BoolProperty(default=False, name='Active') def draw_buttons(self, context, layout): layout.prop(self, 'active', text='Active') layout.prop(self, 'ip', text='IP') layout.prop(self, 'port', text='Port') layout.prop(self, 'buffer_size', text='Buffer') layout.prop(self, 'timeout', text='Timeout') def sv_init(self, context): self.inputs.new('StringsSocket', 'send', 'send').prop_name = 'send' self.outputs.new('StringsSocket', 'receive', 'receive') @profile def process(self): if not self.active: return print(type(self.send),type(self.ip),type(self.port)) input_value = self.inputs[0].sv_get() if self.send != str(input_value): self.send = str(input_value) #self.send_msg(bpy.context) if self.outputs['receive'].is_linked: self.recv_msg() self.outputs['receive'].sv_set(self.receive) def register(): bpy.utils.register_class(UdpClientNode) def unregister(): bpy.utils.unregister_class(UdpClientNode) if __name__ == '__main__': register() ```
[ { "content": "Provide an exact copy of the source code:\n```python\n\"\"\"RachioObject module containing a helper class for all API calls.\"\"\"\nimport json\n\nfrom requests import Session\n\n_API_URL = \"https://api.rach.io/1/public\"\n\n\nclass RachioObject:\n \"\"\"The Rachio base object.\"\"\"\n\n de...
[ { "content": "Provide an exact copy of the source code:\n<|memory_start|>```python\n\"\"\"RachioObject module containing a helper class for all API calls.\"\"\"\nimport json\n\nfrom requests import Session\n\n_API_URL = \"https://api.rach.io/1/public\"\n\n\nclass RachioObject:\n \"\"\"The Rachio base object....
```python """RachioObject module containing a helper class for all API calls.""" import json from requests import Session _API_URL = "https://api.rach.io/1/public" class RachioObject: """The Rachio base object.""" def __init__(self, authtoken: str, http_session=None, timeout=25): """Rachioobject class initializer. :param authtoken: The API authentication token. :type authtoken: str :param http_session: The HTTP Session :type http_session: Session :param timeout: How long to wait for the server to send data before giving up, as a float, or a (connect timeout, read timeout) tuple. :type timeout: float :type timeout: tuple """ self.authtoken = authtoken self._headers = { "Content-Type": "application/json", "Authorization": f"Bearer {authtoken}", } self._http_session = http_session or Session() self.timeout = timeout def _request(self, path: str, method: str, body=None): """Make a request from the API. :return: The return value is a tuple of (response, content), the first being and instance of the httplib2.Response class, the second being a string that contains the response entity body (Python object if it contains JSON). :rtype: tuple """ if body is not None: body = json.dumps(body) url = f"{_API_URL}/{path}" response = self._http_session.request( method, url, headers=self._headers, data=body, timeout=self.timeout ) content_type = response.headers.get("content-type") headers = {k.lower(): v for k, v in response.headers.items()} headers["status"] = response.status_code if content_type and content_type.startswith("application/json"): return headers, response.json() return headers, response.text def get_request(self, path: str, body=None): """Make a GET request to the API. :return: The return value is a tuple of (response, content), the first being and instance of the httplib2.Response class, the second being a string that contains the response entity body (Python object if it contains JSON). :rtype: tuple """ return self._request(path, "GET", body) def put_request(self, path: str, body=None): """Make a PUT request to the API. :return: The return value is a tuple of (response, content), the first being and instance of the httplib2.Response class, the second being a string that contains the response entity body (Python object if it contains JSON). :rtype: tuple """ return self._request(path, "PUT", body) def post_request(self, path: str, body=None): """Make a POST request to the API. :return: The return value is a tuple of (response, content), the first being and instance of the httplib2.Response class, the second being a string that contains the response entity body (Python object if it contains JSON). :rtype: tuple """ return self._request(path, "POST", body) def delete_request(self, path: str, body=None): """Make a DELETE request to the API. :return: The return value is a tuple of (response, content), the first being and instance of the httplib2.Response class, the second being a string that contains the response entity body (Python object if it contains JSON). :rtype: tuple """ return self._request(path, "DELETE", body) ```
[ { "content": "```python\nimport argparse\nimport json\nimport logging\nimport time\nfrom collections import defaultdict\n\nfrom pynet import Node, NodeHooks, Encryptor, PeerDefinition\nfrom pynet.util import run_node\n\n\nSHUTDOWN = False\n\n\nclass KVPDB(object):\n \"\"\"A per-owner dictionary.\n\n Each owne...
[ { "content": "<|memory_start|>```python\nimport argparse\nimport json\nimport logging\nimport time\nfrom collections import defaultdict\n\nfrom pynet import Node, NodeHooks, Encryptor, PeerDefinition\nfrom pynet.util import run_node\n\n\nSHUTDOWN = False\n\n\nclass KVPDB(object):\n \"\"\"A per-owner dictionary...
```python import argparse import json import logging import time from collections import defaultdict from pynet import Node, NodeHooks, Encryptor, PeerDefinition from pynet.util import run_node SHUTDOWN = False class KVPDB(object): """A per-owner dictionary. Each owner has their own dictionary, this class exposes methods to get, set, query and delete keys on a per-owner basis. """ def __init__(self): self.db = defaultdict(dict) def get(self, owner, key): """Get a value for a specific owner.""" return self.db[owner].get(key, None) def set(self, owner, key, value): """Set a value for a specific owner.""" self.db[owner][key] = value def contains(self, owner, key): """Determine if a key exists for an owner.""" return key in self.db[owner] def delete(self, owner, key): """Remove a value for an owner.""" del self.db[owner][key] class MessageHandler(object): """A callable object for handling messages on a node.""" def __init__(self): self.db = KVPDB() def __call__(self, sender, body): parts = body.split(maxsplit=1) if len(parts) == 2: action, data = parts else: action, data = None, parts if action == b"get": log("get", data.decode()) if self.db.contains(sender, data): return (True, self.db.get(sender, data), None) else: return (False, "Key not found", None) elif action == b"set": key, value = data.split(maxsplit=1) log("set", key.decode()) self.db.set(sender, key, value) return (True, None, None) elif action == b"delete": log("delete", data.decode()) return (True, self.db.delete(sender, data), None) elif action == b"has": log("has?", data.decode()) return (True, "yes" if self.db.contains(sender, data) else "no", None) elif action == b"disconnect": del self.db[sender] self.node.remove_peer(sender) return (True, None, None) else: return (False, "Unknown command", None) class Hooks(NodeHooks): """Overrides the NodeHooks class to log messages and to allow ad-hoc peer registering.""" def handle_raw_message(self, data): handled, wait_for_response = super().handle_raw_message(data) if handled: log("Received message", data.decode()) return (handled, wait_for_response) def handle_unknown_peer(self, sender, body, signature): if body.startswith(b"register\n") and body.count(b"\n") >= 1: command, public_key = body.split(b"\n", maxsplit=1) if self.node.has_peer(sender): log("Peer already registered") self.node.write(b"Peer already registered", encrypt=False) else: log("Registered peer", sender) new_peer = PeerDefinition(sender, None, public_key) self.node.add_peer(new_peer) self.node.set_receiver(new_peer) self.node.write_success(b"registered") return (True, None) else: return super().handle_unknown_peer(sender, body, signature) def main(): args = parse_args() if args is not None: args.func(args) def parse_args(): argument_parser = argparse.ArgumentParser("A secured in-memory kvp server built on pynet") subparsers = argument_parser.add_subparsers() config_parser = subparsers.add_parser("config", description="Dump out a sample config") config_parser.set_defaults(func=dump_config) run_parser = subparsers.add_parser("run", description="Run the server") run_parser.add_argument("config_file") run_parser.set_defaults(func=run_server) args = argument_parser.parse_args() if hasattr(args, "func"): return args else: argument_parser.print_help() return None def dump_config(args): node = Node(None, "/tmp/pynet-kvp.sock") node.add_peer(PeerDefinition("first among peers", "127.0.0.1:1337", Encryptor.new_key().publickey())) print(json.dumps(node.get_config(), sort_keys=True, indent=2, separators=(", ", ": "))) def run_server(args): setup_logging(args) with open(args.config_file, "r") as rf: node = Node.from_config(MessageHandler(), json.load(rf), hooks=Hooks()) with run_node(node): log("Listening on {0}".format(node.address)) # NOTE: There is no functionality for flipping the SHUTDOWN switch, so at this point you'll # have to terminate the process manually. while not SHUTDOWN: time.sleep(1) def setup_logging(args): log_level = logging.INFO logger = logging.getLogger() logger.setLevel(log_level) handler = logging.StreamHandler() handler.setLevel(log_level) handler.setFormatter(logging.Formatter( "%(asctime)s\t%(levelname)s\t%(message)s", "%Y-%m-%dT%H:%M:%S%z")) logger.addHandler(handler) return (logger, handler) def log(*args): logging.info("\t".join(args)) if __name__ == "__main__": main() ```
[ { "content": "```python\nimport math\n\nclass ColorScience():\n\t\"\"\"Methodes relative at Color Science\"\"\"\n\t\n\t@staticmethod\n\tdef linearToSrgb(color):\n\t\tcolorOut = []\n\n\t\tfor i in range(3):\n\t\t\tif color[i] <= 0.0031308:\n\t\t\t\tcolorTmp = color[i] * 12.92\n\t\t\t\tcolorOut.append( round(colo...
[ { "content": "<|memory_start|>```python\nimport math\n\nclass ColorScience():\n\t\"\"\"Methodes relative at Color Science\"\"\"\n\t\n\t@staticmethod\n\tdef linearToSrgb(color):\n\t\tcolorOut = []\n\n\t\tfor i in range(3):\n\t\t\tif color[i] <= 0.0031308:\n\t\t\t\tcolorTmp = color[i] * 12.92\n\t\t\t\tcolorOut.ap...
```python import math class ColorScience(): """Methodes relative at Color Science""" @staticmethod def linearToSrgb(color): colorOut = [] for i in range(3): if color[i] <= 0.0031308: colorTmp = color[i] * 12.92 colorOut.append( round(colorTmp, 6) ) else: colorTmp = 1.055 * ( pow(color[i], 1 / 2.4) ) - 0.055 colorOut.append( round(colorTmp, 6) ) return colorOut @staticmethod def srgbToLinear(color): colorOut = [] for i in range(3): if color[i] <= 0.04045: colorTmp = color[i] / 12.92 colorOut.append( round(colorTmp, 6) ) else: colorTmp = pow( ( (color[i]+0.055) / 1.055 ), 2.4 ) colorOut.append( round(colorTmp, 6) ) return colorOut @staticmethod def floatToBits8(color): return [ int(i*255) for i in color ] @staticmethod def bits8ToFloat(color): return [ float(i/255) for i in color ] @staticmethod def applyLut(color, lut): return None @staticmethod def removeLut(color, lut): return None def rgbToHsv(self, color): # todo : fix forumla to don't have to make this ugly colorspace convertion # colorSrgb = self.linearToSrgb( color ) colorSrgb = color r = colorSrgb[0] g = colorSrgb[1] b = colorSrgb[2] mini = min( r, g, b ) maxi = max( r, g, b ) v = maxi delta = maxi - mini if maxi: s = delta / maxi else: s = 0 h = -1 return [ h, s, v ] if delta: if r == maxi: h = ( g - b ) / delta elif g == maxi: h = 2 + ( b - r ) / delta else: h = 4 + ( r - g ) / delta h *= 60.0 if h < 0 : h += 360 h /= 360.0 else: h = 0 return [ h, s, v ] def hsvToRgb(self, color): h = color[0] s = color[1] v = color[2] step = h / (1.0 / 6.0) pos = step - math.floor( step ) if math.floor(step) % 2 : m = ( 1.0 - pos ) * v else : m = pos * v maximum = 1.0 * v minimum = (1.0 - s) * v medium = m + ( (1.0 - s)*(v - m) ) switchValue = math.floor( step ) if switchValue == 0: r = maximum g = medium b = minimum if switchValue == 1: r = medium g = maximum b = minimum if switchValue == 2: r = minimum g = maximum b = medium if switchValue == 3: r = minimum g = medium b = maximum if switchValue == 4: r = medium g = minimum b = maximum if switchValue == 5 or switchValue == 6 or switchValue == -6 : r = maximum g = minimum b = medium rgb = [r, g, b] # todo : fix forumla to don't have to make this ugly colorspace convertion # rgb = self.srgbToLinear( rgb ) return rgb def hslToRgb(self, color): h = color[0] s = color[1] l = color[2] if s == 0: r = l g = l b = l else: def hueTorgb(p, q, t): if(t < 0.0) : t += 1.0 if(t > 1.0) : t -= 1.0 if(t < 1.0/6.0) : return p + (q - p) * 6.0 * t if(t < 1.0/2.0) : return q if(t < 2.0/3.0) : return p + (q - p) * (2.0/3.0 - t) * 6.0 return p if l < 0.5 : q = l * (1.0 + s) else : q = l + s - l * s p = 2.0 * l - q r = hue2rgb( p, q, h + 1.0/3.0 ) g = hue2rgb( p, q, h ) b = hue2rgb( p, q, h - 1.0/3.0 ) rgb = [r, g, b] # todo : fix forumla to don't have to make this ugly colorspace convertion rgb = self.srgbToLinear( rgb ) return rgb ```
[ { "content": "Return the code exactly, with no changes:\n```python\n# -*- coding: utf-8 -*-\n\nimport re\nimport urllib.parse\n\nfrom bs4 import BeautifulSoup\n\nfrom pyload.core.utils.misc import eval_js\n\nfrom ..anticaptchas.ReCaptcha import ReCaptcha\nfrom ..base.simple_downloader import SimpleDownloader\n\...
[ { "content": "Return the code exactly, with no changes:\n<|memory_start|>```python\n# -*- coding: utf-8 -*-\n\nimport re\nimport urllib.parse\n\nfrom bs4 import BeautifulSoup\n\nfrom pyload.core.utils.misc import eval_js\n\nfrom ..anticaptchas.ReCaptcha import ReCaptcha\nfrom ..base.simple_downloader import Sim...
```python # -*- coding: utf-8 -*- import re import urllib.parse from bs4 import BeautifulSoup from pyload.core.utils.misc import eval_js from ..anticaptchas.ReCaptcha import ReCaptcha from ..base.simple_downloader import SimpleDownloader class ZippyshareCom(SimpleDownloader): __name__ = "ZippyshareCom" __type__ = "downloader" __version__ = "0.98" __status__ = "testing" __pyload_version__ = "0.5" __pattern__ = r"https?://(?P<HOST>www\d{0,3}\.zippyshare\.com)/(?:[vd]/|view\.jsp.*key=)(?P<KEY>[\w^_]+)" __config__ = [ ("enabled", "bool", "Activated", True), ("use_premium", "bool", "Use premium account if available", True), ("fallback", "bool", "Fallback to free download if premium fails", True), ("chk_filesize", "bool", "Check file size", True), ("max_wait", "int", "Reconnect if waiting time is greater than minutes", 10), ] __description__ = """Zippyshare.com downloader plugin""" __license__ = "GPLv3" __authors__ = [ ("Walter Purcaro", "vuolter@gmail.com"), ("sebdelsol", "seb.morin@gmail.com"), ("GammaC0de", "nitzo2001[AT]yahoo[DOT]com"), ] COOKIES = [("zippyshare.com", "ziplocale", "en")] URL_REPLACEMENTS = [(__pattern__ + ".*", r"http://\g<HOST>/v/\g<KEY>/file.html")] NAME_PATTERN = r'(?:<title>Zippyshare.com - |"/)(?P<N>[^/]+)(?:</title>|";)' SIZE_PATTERN = r'>Size:.+?">(?P<S>[\d.,]+) (?P<U>[\w^_]+)' OFFLINE_PATTERN = r"does not exist (anymore )?on this server<" TEMP_OFFLINE_PATTERN = r"^unmatchable$" LINK_PATTERN = r"document.location = '(.+?)'" def setup(self): self.chunk_limit = -1 self.multi_dl = True self.resume_download = True def handle_free(self, pyfile): self.captcha = ReCaptcha(pyfile) captcha_key = self.captcha.detect_key() if captcha_key: try: self.link = re.search(self.LINK_PATTERN, self.data) self.captcha.challenge() except Exception as exc: self.error(exc) else: self.link = self.fixurl(self.get_link()) if ".com/pd/" in self.link: self.load(self.link) self.link = self.link.replace(".com/pd/", ".com/d/") if self.link and pyfile.name == "file.html": pyfile.name = urllib.parse.unquote(self.link.split("/")[-1]) def get_link(self): #: Get all the scripts inside the html body soup = BeautifulSoup(self.data) scripts = [ s.getText() for s in soup.body.findAll("script", type="text/javascript") if "('dlbutton').href =" in s.getText() ] #: Emulate a document in JS inits = [ """ var document = {} document.getElementById = function(x) { if (!this.hasOwnProperty(x)) { this[x] = {getAttribute : function(x) { return this[x] } } } return this[x] } """ ] #: inits is meant to be populated with the initialization of all the DOM elements found in the scripts eltRE = r'getElementById\([\'"](.+?)[\'"]\)(\.)?(getAttribute\([\'"])?(\w+)?([\'"]\))?' for m in re.findall(eltRE, " ".join(scripts)): JSid, JSattr = m[0], m[3] values = [ f for f in (elt.get(JSattr, None) for elt in soup.findAll(id=JSid)) if f ] if values: inits.append( 'document.getElementById("{}")["{}"] = "{}"'.format( JSid, JSattr, values[-1] ) ) #: Add try/catch in JS to handle deliberate errors scripts = ["\n".join(("try{", script, "} catch(err){}")) for script in scripts] #: Get the file's url by evaluating all the scripts scripts = inits + scripts + ["document.dlbutton.href"] return eval_js("\n".join(scripts)) ```
[ { "content": "Produce an exact reconstruction of the code:\n```python\n\"\"\"\n Plugin for UrlResolver\n Copyright (C) 2017 tknorris\n\n This program is free software: you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software ...
[ { "content": "Produce an exact reconstruction of the code:\n<|memory_start|>```python\n\"\"\"\n Plugin for UrlResolver\n Copyright (C) 2017 tknorris\n\n This program is free software: you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n th...
```python """ Plugin for UrlResolver Copyright (C) 2017 tknorris 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/>. """ import os from six.moves import reload_module import urlresolver.plugins.thevid_gmu from urlresolver import common from urlresolver.resolver import UrlResolver, ResolverError logger = common.log_utils.Logger.get_logger(__name__) logger.disable() VID_SOURCE = r'https://raw.githubusercontent.com/jsergio123/script.module.urlresolver/master/lib/urlresolver/plugins/thevid_gmu.py' VID_PATH = os.path.join(common.plugins_path, 'thevid_gmu.py') class TheVidResolver(UrlResolver): name = "TheVid" domains = ["thevid.net", "thevid.tv", "thevid.live"] pattern = r'(?://|\.)(thevid\.(?:net|tv|live))/(?:video|e|v)/([A-Za-z0-9]+)' def get_media_url(self, host, media_id): try: self._auto_update(VID_SOURCE, VID_PATH) reload_module(urlresolver.plugins.thevid_gmu) web_url = self.get_url(host, media_id) return urlresolver.plugins.thevid_gmu.get_media_url(web_url) except Exception as e: raise ResolverError('Exception during thevid.net resolve parse: %s' % e) def get_url(self, host, media_id): return self._default_get_url(host, media_id, template='http://{host}/e/{media_id}/') @classmethod def get_settings_xml(cls): xml = super(cls, cls).get_settings_xml() xml.append('<setting id="%s_auto_update" type="bool" label="Automatically update resolver" default="true"/>' % (cls.__name__)) xml.append('<setting id="%s_etag" type="text" default="" visible="false"/>' % (cls.__name__)) return xml ```
[ { "content": "Reconstruct the code exactly:\n```python\n\"\"\" The Chain of Responsibility Pattern\n\nNotes:\n\nThe Chain of Responsibility pattern allows the client programmer to dynamically\ncreate a recursive chain of objects - each of which tries to fulfill a\n'responsibility' (usually represented by a meth...
[ { "content": "Reconstruct the code exactly:\n<|memory_start|>```python\n\"\"\" The Chain of Responsibility Pattern\n\nNotes:\n\nThe Chain of Responsibility pattern allows the client programmer to dynamically\ncreate a recursive chain of objects - each of which tries to fulfill a\n'responsibility' (usually repre...
```python """ The Chain of Responsibility Pattern Notes: The Chain of Responsibility pattern allows the client programmer to dynamically create a recursive chain of objects - each of which tries to fulfill a 'responsibility' (usually represented by a method call). If an object in the chain is unable to fulfill it, the request propagates to the next level of the chain until it can be fulfilled. This chain is usually implemented as a linked list (but it can be implemented using other iterable structures). In the following example, we simulate a service that searches for a job candidate from several pools of candidates. The pools are categorized by geographical clusters (local/regional/global) and we assume that the user of this service wants to find the nearest candidate (in the smallest cluster) that meets all requirements. The chain of responsibility will thus be a linked list of the pools which the user will recursively check (smallest to largest) in order to find a good candidate. """ class AbstractPool: """The interface for the pool classes. All pools inherit from this.""" candidates = [] def __init__(self, successor_pool=None): """Note how each pool object can store a pointer to a successor_pool. If no such pointer is assigned, we assume that is the last pool in the chain. """ self._successor = successor_pool def get_match(self, params): """If a match is found in the pool of candidates, the candidate is returned, else the responsibility is propagated to the next pool in the chain. """ match = self._find(params) if match: return match elif self._successor: return self._successor.get_match(params) def _find(self, params): """Returns the first matching candidate in the pool if a match is found. The exact implementation of this method is irrelevant to the concept of the pattern. It may also be implemented differently for each pool. """ for candidate in self.__class__.candidates: if all(key in candidate.items() for key in params.items()): print("> Match found in {}:".format(self.__class__.__name__)) return candidate print("> No match found in {}.".format(self.__class__.__name__)) class LocalPool(AbstractPool): candidates = [ {"id": 12, "type": "developer", "level": "intermediate"}, {"id": 21, "type": "analyst", "level": "junior"} ] class RegionalPool(AbstractPool): candidates = [ {"id": 123, "type": "project_manager", "level": "intermediate"}, {"id": 321, "type": "designer", "level": "intermediate"} ] class GlobalPool(AbstractPool): candidates = [ # The following candidate is the only one that matches the needs. {"id": 1234, "type": "developer", "level": "senior"}, {"id": 4321, "type": "designer", "level": "senior"} ] if __name__ == "__main__": # Setting up recursive propagation in this order: local > regional > global. global_pool = GlobalPool() regional_pool = RegionalPool(global_pool) local_pool = LocalPool(regional_pool) print("Searching for a senior developer in the pools chain:") print(local_pool.get_match({"type": "developer", "level": "senior"})) ```
[ { "content": "```python\n#!/usr/bin/env python\n\n\"\"\" Assignment 1, Exercise 3, INF1340, Fall, 2015. Troubleshooting Car Issues.\n\nThis module contains one function diagnose_car(). It is an expert system to\ninteractive diagnose car issues.\n\n\"\"\"\n\n__author__ = 'Susan Sim'\n__email__ = \"ses@drsusansim...
[ { "content": "<|memory_start|>```python\n#!/usr/bin/env python\n\n\"\"\" Assignment 1, Exercise 3, INF1340, Fall, 2015. Troubleshooting Car Issues.\n\nThis module contains one function diagnose_car(). It is an expert system to\ninteractive diagnose car issues.\n\n\"\"\"\n\n__author__ = 'Susan Sim'\n__email__ = ...
```python #!/usr/bin/env python """ Assignment 1, Exercise 3, INF1340, Fall, 2015. Troubleshooting Car Issues. This module contains one function diagnose_car(). It is an expert system to interactive diagnose car issues. """ __author__ = 'Susan Sim' __email__ = "ses@drsusansim.org" __copyright__ = "2015 Susan Sim" __license__ = "MIT License" # ERROR_MESSAGE in case of improper user input ERROR_MESSAGE = 'I don\'t understand' # ========================================== Main Function ================================================= def diagnose_car(): """ Interactively queries the user with yes/no questions to identify a possible issue with a car. Test Cases Inputs:Y,N Expected: Replace cables and try again. Inputs:Y,Y Expected: Clean terminals and try starting again. Inputs:N,Y Expected:Replace the battery. Inputs:N,N,Y Expected:Check spark plug connections. Inputs:N,N,N,N Expected: Engine is not getting enough fuel. Clean fuel pump. Inputs:N,N,N,Y,Y Expected: Get it in for service. Inputs:N,N,N,Y,N Expected: Check to ensure the choke is opening and closing. """ check_silence() # diagnose_car() # ========================================== Helper Functions ================================================ # Each function represents a box on flowchart and supports re-usability # This function is the first box in the flow chart def check_silence(): silent = raw_input("Is the car silent when you turn the key?") if silent == "Y": check_battery() elif silent == "N": check_noise() else: print (ERROR_MESSAGE) check_silence() # This is the left side of the flowchart def check_battery(): corroded = raw_input("Are the battery terminals corroded?") if corroded == "Y": print ("Clean terminals and try starting again.") elif corroded == "N": print ("Replace cables and try again.") else: print (ERROR_MESSAGE) check_battery() # Everything below is the right side of the flow chart def check_noise(): click = raw_input("Does the car make a clicking noise?") if click == "Y": print ("Replace the battery.") elif click == "N": check_crank() else: print (ERROR_MESSAGE) check_noise() def check_crank(): crank = raw_input("Does the car crank up but fail to start?") if crank == "Y": print ("Check spark plug connections.") elif crank == "N": check_engine() else: print (ERROR_MESSAGE) check_crank() def check_engine(): engine = raw_input("Does engine start and then die?") if engine == "Y": check_fuel() elif engine == "N": print ("Engine is not getting enough fuel. Clean fuel pump.") else: print (ERROR_MESSAGE) check_engine() def check_fuel(): fuel = raw_input("Does your car have fuel injection?") if fuel == "N": print ("Check to ensure the choke is opening and closing.") elif fuel == "Y": print ("Get it in for service.") else: print (ERROR_MESSAGE) check_fuel() ```
[ { "content": "Repeat the full code snippet:\n```python\n#!/usr/bin/env python\n\nfrom setuptools import setup\n\nlong_desc = '''\n\nEncrypted JSON Transport Protocol\n---------------------------------\n\nEJTP is an overlay protocol that allows the pluggable use of underlying transports, such as UDP, TCP, HTTP, ...
[ { "content": "Repeat the full code snippet:\n<|memory_start|>```python\n#!/usr/bin/env python\n\nfrom setuptools import setup\n\nlong_desc = '''\n\nEncrypted JSON Transport Protocol\n---------------------------------\n\nEJTP is an overlay protocol that allows the pluggable use of underlying transports, such as ...
```python #!/usr/bin/env python from setuptools import setup long_desc = ''' Encrypted JSON Transport Protocol --------------------------------- EJTP is an overlay protocol that allows the pluggable use of underlying transports, such as UDP, TCP, HTTP, IRC, Email and carrier pigeon to provide a cryptographically secure network of unreliable message forwarding. You can think of it as a bit like a more general-purpose and security-minded successor to XMPP, using JSON rather than XML as its frame medium. On top of a simple frame format, EJTP boasts a consistent and simple format for describing encryption credentials, which is useful even without the rest of EJTP. The ejtp-crypto script makes it easy for other projects to take advantage of this pending a native port of ejtp.crypto to languages other than Python. The intention of EJTP is to make it trivial to establish secure and NAT-oblivious distributed services across a common network of message relays. Your system only has to worry about exchanging encryption credentials and establishing a connection with a relay host, helping to pave the way toward distributed apps that run entirely in HTML5 (pending a port of the project to JS). You can be serverless *and* smartphone-friendly. Optionally supports elliptic curve cryptography if the PyECC_ module is installed. For more technical and in-depth information, visit the `Github project <https://github.com/campadrenalin/EJTP-lib-python>`_. .. _PyECC: https://pypi.python.org/pypi/PyECC ''' setup( name = 'ejtp', version = '0.9.7p1', description = 'Encrypted JSON Transport Protocol library', long_description = long_desc, author = 'Philip Horger', author_email = 'philip.horger@gmail.com', url = 'https://github.com/campadrenalin/EJTP-lib-python/', package_data={ 'ejtp.tests' : ['examplecache.json', 'idents/*'] }, install_requires = [ 'pycrypto', 'persei', 'requests', 'streql', ], classifiers = [ 'Development Status :: 4 - Beta', 'License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)', 'Environment :: Console', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Operating System :: MacOS :: MacOS X', 'Operating System :: Microsoft :: Windows', 'Operating System :: POSIX', 'Intended Audience :: Developers', 'Topic :: Communications', 'Topic :: Internet', 'Topic :: Security :: Cryptography', ], scripts = [ 'scripts/ejtpd', 'scripts/ejtp-keygen', 'scripts/ejtp-console', 'scripts/ejtp-crypto', 'scripts/ejtp-identity', ], packages = [ 'ejtp', 'ejtp.applications', 'ejtp.applications.ejforward', 'ejtp.crypto', 'ejtp.frame', 'ejtp.identity', 'ejtp.jacks', 'ejtp.tests', 'ejtp.util', 'ejtp.vendor', ], ) ```
[ { "content": "Provide a verbatim copy of the code:\n```python\n#!/usr/bin/env python\n\"\"\"\nBased on test code moved here from bottom of tulip/jtlvint.py\n\nSCL; 31 Dec 2011.\n\"\"\"\n\nimport os\n\nfrom tulip.jtlvint import *\nfrom tulip.polytope import Region\nfrom tulip.prop2part import PropPreservingParti...
[ { "content": "Provide a verbatim copy of the code:\n<|memory_start|>```python\n#!/usr/bin/env python\n\"\"\"\nBased on test code moved here from bottom of tulip/jtlvint.py\n\nSCL; 31 Dec 2011.\n\"\"\"\n\nimport os\n\nfrom tulip.jtlvint import *\nfrom tulip.polytope import Region\nfrom tulip.prop2part import Pro...
```python #!/usr/bin/env python """ Based on test code moved here from bottom of tulip/jtlvint.py SCL; 31 Dec 2011. """ import os from tulip.jtlvint import * from tulip.polytope import Region from tulip.prop2part import PropPreservingPartition class jtlvint_test: def setUp(self): self.tmpdir = "tmpspec" testfile = os.path.join(self.tmpdir, "testjtlvint") self.smvfile = testfile + '.smv' self.spcfile = testfile + '.spc' self.autfile = testfile + '.aut' # env_vars = {'park' : 'boolean', 'cellID' : '{0,...,3,4,5}'} env_vars = {'park' : 'boolean', 'cellID' : [0,1,2,3,4,5]} sys_disc_vars = {'gear' : '{-1...1}'} cont_props = ['X0', 'X1', 'X2', 'X3', 'X4'] disc_dynamics = PropPreservingPartition() region0 = Region('p0', [1, 0, 0, 0, 0]) region1 = Region('p1', [0, 1, 0, 0, 0]) region2 = Region('p2', [1, 0, 1, 0, 0]) region3 = Region('p3', [0, 0, 0, 1, 0]) region4 = Region('p4', [0, 0, 0, 0, 1]) region5 = Region('p5', [1, 0, 0, 1, 1]) disc_dynamics.list_region = [region0, region1, region2, region3, region4, region5] disc_dynamics.num_regions = len(disc_dynamics.list_region) disc_dynamics.trans = [[1, 1, 0, 1, 0, 0], [1, 1, 1, 0, 1, 0], [0, 1, 1, 0, 0, 1], [1, 0, 0, 1, 1, 0], [0, 1, 0, 1, 1, 1], [0, 0, 1, 0, 1, 1]] disc_dynamics.list_prop_symbol = cont_props disc_dynamics.num_prop = len(disc_dynamics.list_prop_symbol) disc_props = {'Park' : 'park', 'X0d' : 'cellID=0', 'X1d' : 'cellID=1', 'X2d' : 'cellID=2', 'X3d' : 'cellID=3', 'X4d' : 'cellID=4', 'X5d' : 'gear = 1'} assumption = '[]<>(!park) & []<>(!X4d)' guarantee = '[]<>(X4d -> X4) & []<>X1 & [](Park -> X0)' spec = [assumption, guarantee] disc_dynamics=PropPreservingPartition() spec[1] = '[]<>(X0d -> X5d)' newvarname = generateJTLVInput(env_vars=env_vars, sys_disc_vars=sys_disc_vars, spec=spec, disc_props=disc_props, disc_dynamics=disc_dynamics, smv_file=self.smvfile, spc_file=self.spcfile, file_exist_option='r', verbose=2) def tearDown(self): os.remove(self.smvfile) os.remove(self.spcfile) os.remove(self.autfile) os.rmdir(self.tmpdir) def test_checkRealizability(self): assert checkRealizability(smv_file=self.smvfile, spc_file=self.spcfile, aut_file=self.autfile, heap_size='-Xmx128m', pick_sys_init=False, file_exist_option='r', verbose=3) def test_computeStrategy(self): assert computeStrategy(smv_file=self.smvfile, spc_file=self.spcfile, aut_file=self.autfile, heap_size='-Xmx128m', priority_kind='ZYX', init_option=1, file_exist_option='r', verbose=3) # assert computeStrategy(smv_file=self.smvfile, # spc_file=self.spcfile, # aut_file=self.autfile, # heap_size='-Xmx128m', # priority_kind='ZYX', # init_option=2, # file_exist_option='r', verbose=3) # assert not computeStrategy(smv_file=self.smvfile, # spc_file=self.spcfile, # aut_file=self.autfile, # heap_size='-Xmx128m', # priority_kind='ZYX', # init_option=0, # file_exist_option='r', verbose=3) # def test_synthesize(self): # assert synthesize(env_vars=env_vars, # sys_disc_vars=sys_disc_vars, # spec=spec, disc_props=disc_props, # disc_dynamics=disc_dynamics, # smv_file=self.smvfile, # spc_file=self.spcfile, # aut_file=self.autfile, # heap_size='-Xmx128m', priority_kind=3, # init_option=init_option, # file_exist_option='r', verbose=3) # def test_getCounterExamples(self): # counter_examples = getCounterExamples(aut_file=self.autfile, verbose=1) ```
[ { "content": "Replicate the code snippet exactly, without paraphrasing or reformatting:\n```python\n# -*- coding: utf-8 -*-\nimport collections\nfrom xml.sax.xmlreader import AttributesImpl\n\nfrom ecoxipy import _python2, _unicode\nfrom ecoxipy import _helpers\n\nfrom ._common import XMLNode, ContainerNode, _s...
[ { "content": "Replicate the code snippet exactly, without paraphrasing or reformatting:\n<|memory_start|>```python\n# -*- coding: utf-8 -*-\nimport collections\nfrom xml.sax.xmlreader import AttributesImpl\n\nfrom ecoxipy import _python2, _unicode\nfrom ecoxipy import _helpers\n\nfrom ._common import XMLNode, C...
```python # -*- coding: utf-8 -*- import collections from xml.sax.xmlreader import AttributesImpl from ecoxipy import _python2, _unicode from ecoxipy import _helpers from ._common import XMLNode, ContainerNode, _string_repr from ._content_nodes import Text from .indexing import (IndexDescriptor, ElementByUniqueAttributeValueIndexer, ElementsByNameIndexer, NamespaceIndexer) class DocumentType(object): '''\ Represents a document type declaration of a :class:`Document`. It should not be instantiated on itself. :param name: The document element name. :type name: Unicode string :param publicid: The document type public ID or :const:`None`. :type publicid: Unicode string :param systemid: The document type system ID or :const:`None`. :type systemid: Unicode string :param check_well_formedness: If :const:`True` the document element name will be checked to be a valid XML name. :type check_well_formedness: :func:`bool` ''' __slots__ = {'_name', '_publicid', '_systemid', '_check_well_formedness'} def __init__(self, name, publicid, systemid, check_well_formedness): if check_well_formedness: if name is not None: _helpers.enforce_valid_xml_name(name) if publicid is not None: _helpers.enforce_valid_doctype_publicid(publicid) if systemid is not None: _helpers.enforce_valid_doctype_systemid(systemid) self._name = name self._publicid = publicid self._systemid = systemid self._check_well_formedness = check_well_formedness @property def name(self): '''\ The document element name or :const:`None`. On setting if the value is :const:`None`, :attr:`publicid` and :attr:`systemid` are also set to :const:`None`. Otherwise the value is converted to an Unicode string; a :class:`ecoxipy.XMLWellFormednessException` is thrown if it is not a valid XML name and ``check_well_formedness`` is :const:`True`. ''' return self._name @name.setter def name(self, name): if name is None: self._publicid = None self._systemid = None else: name = _unicode(name) if self._check_well_formedness: _helpers.enforce_valid_xml_name(name) self._name = name @property def publicid(self): '''\ The document type public ID or :const:`None`. On setting if the value is not :const:`None` it is converted to a Unicode string; a :class:`ecoxipy.XMLWellFormednessException` is thrown if it is not a valid doctype public ID and ``check_well_formedness`` is :const:`True`. ''' return self._publicid @publicid.setter def publicid(self, publicid): if publicid is not None: publicid = _unicode(publicid) if self._check_well_formedness: _helpers.enforce_valid_doctype_publicid(publicid) self._publicid = publicid @property def systemid(self): '''\ The document type system ID or :const:`None`. On setting if the value is not :const:`None` it is converted to a Unicode string; a :class:`ecoxipy.XMLWellFormednessException` is thrown if it is not a valid doctype system ID and ``check_well_formedness`` is :const:`True`. ''' return self._systemid @systemid.setter def systemid(self, systemid): if systemid is not None: systemid = _unicode(systemid) if self._check_well_formedness: _helpers.enforce_valid_doctype_systemid(systemid) self._systemid = systemid def __repr__(self): return 'ecoxipy.pyxom.DocumentType({}, {}, {})'.format( _string_repr(self._name), _string_repr(self._publicid), _string_repr(self._systemid), ) def __eq__(self, other): return (isinstance(other, DocumentType) and self._name == other._name and self._publicid == other._publicid and self._systemid == other._systemid ) def __ne__(self, other): return (not(isinstance(other, DocumentType)) or self._name != other._name or self._publicid != other._publicid or self._systemid != other._systemid ) @staticmethod def _parse_values(name, publicid, systemid): if name is None: publicid = None systemid = None else: name = _unicode(name) if publicid is not None: publicid = _unicode(publicid) if systemid is not None: systemid = _unicode(systemid) return name, publicid, systemid @staticmethod def _create(name, publicid, systemid, check_well_formedness): name, publicid, systemid = DocumentType._parse_values( name, publicid, systemid) return DocumentType(name, publicid, systemid, check_well_formedness) class Document(ContainerNode): '''\ A :class:`ContainerNode` representing a XML document. :param doctype_name: The document type root element name or :const:`None` if the document should not have document type declaration. :type doctype_name: Unicode string :param doctype_publicid: The public ID of the document type declaration or :const:`None`. :type doctype_publicid: Unicode string :param doctype_systemid: The system ID of the document type declaration or :const:`None`. :type doctype_systemid: Unicode string :param children: The document root :class:`XMLNode` instances. :param encoding: The encoding of the document. If it is :const:`None` `UTF-8` is used. :type encoding: Unicode string :param omit_xml_declaration: If :const:`True` the XML declaration is omitted. :type omit_xml_declaration: :func:`bool` :param check_well_formedness: If :const:`True` the document element name will be checked to be a valid XML name. :type check_well_formedness: :func:`bool` :raises ecoxipy.XMLWellFormednessException: If ``check_well_formedness`` is :const:`True` and ``doctype_name`` is not a valid XML name, ``doctype_publicid`` is not a valid public ID or ``doctype_systemid`` is not a valid system ID. ''' __slots__ = {'_doctype', '_omit_xml_declaration', '_encoding'} def __init__(self, doctype_name, doctype_publicid, doctype_systemid, children, omit_xml_declaration, encoding, check_well_formedness=False): ContainerNode.__init__(self, children) self._doctype = DocumentType(doctype_name, doctype_publicid, doctype_systemid, check_well_formedness) self._omit_xml_declaration = omit_xml_declaration if encoding is None: encoding = u'UTF-8' self._encoding = encoding @staticmethod def create(*children, **kargs): '''\ Creates a document and converts parameters to appropriate types. :param children: The document root nodes. All items that are not :class:`XMLNode` instances create :class:`Text` nodes after they have been converted to Unicode strings. :param kargs: The same parameters as the constructor has (except ``children``) are recognized. The items ``doctype_name``, ``doctype_publicid``, ``doctype_systemid``, and ``encoding`` are converted to Unicode strings if they are not :const:`None`. ``omit_xml_declaration`` is converted to boolean. :returns: The created document. :rtype: :class:`Document` :raises ecoxipy.XMLWellFormednessException: If ``doctype_name`` is not a valid XML name, ``doctype_publicid`` is not a valid public ID or ``doctype_systemid`` is not a valid system ID. ''' doctype_name = kargs.get('doctype_name', None) doctype_publicid = kargs.get('doctype_publicid', None) doctype_systemid = kargs.get('doctype_systemid', None) doctype_name, doctype_publicid, doctype_systemid = DocumentType._parse_values( doctype_name, doctype_publicid, doctype_systemid) omit_xml_declaration = kargs.get('omit_xml_declaration', None) omit_xml_declaration = bool(omit_xml_declaration) encoding = kargs.get('encoding', None) if encoding is not None: encoding = _unicode(encoding) return Document(doctype_name, doctype_publicid, doctype_systemid, [ child if isinstance(child, XMLNode) else Text.create(child) for child in children ], omit_xml_declaration, encoding, True) @property def doctype(self): '''\ The :class:`DocumentType` instance of the document. On setting one of the following occurs: 1. If the value is :const:`None`, the document type's attributes are set to :const:`None`. 2. If the value is a byte or Unicode string, the document type document element name is set to this value (a byte string will be converted to Unicode). The document type public and system IDs will be set to :const:`None`. 3. If the value is a mapping, the items identified by the strings ``'name'``, ``'publicid'`` or ``'systemid'`` define the respective attributes of the document type, the others are assumed to be :const:`None`. 4. If the value is a sequence, the item at position zero defines the document type document element name, the item at position one defines the public ID and the item at position two defines the system ID. If the sequence is shorter than three, non-available items are assumed to be :const:`None`. The document type values are converted to appropriate values and their validity is checked if ``check_well_formedness`` is :const:`True`. Example: >>> doc = Document.create() >>> doc.doctype ecoxipy.pyxom.DocumentType(None, None, None) >>> doc.doctype = {'name': 'test', 'systemid': 'foo bar'} >>> doc.doctype ecoxipy.pyxom.DocumentType('test', None, 'foo bar') >>> doc.doctype = ('html', 'foo bar') >>> doc.doctype ecoxipy.pyxom.DocumentType('html', 'foo bar', None) >>> doc.doctype = 'foo' >>> doc.doctype ecoxipy.pyxom.DocumentType('foo', None, None) >>> doc.doctype = None >>> doc.doctype ecoxipy.pyxom.DocumentType(None, None, None) ''' return self._doctype @doctype.setter def doctype(self, value): if value is None: name = None publicid = None systemid = None else: if value.__class__ is bytes: value = _unicode(value) try: name = value.get('name', None) publicid = value.get('publicid', None) systemid = value.get('systemid', None) except AttributeError: if value.__class__ is _unicode: name = value publicid = None systemid = None else: if len(value) > 2: systemid = value[2] else: systemid = None if len(value) > 1: publicid = value[1] else: publicid = None if len(value) > 0: name = value[0] else: name = None name, publicid, systemid = DocumentType._parse_values( name, publicid, systemid) self._doctype.name = name self._doctype.publicid = publicid self._doctype.systemid = systemid @property def omit_xml_declaration(self): '''\ If :const:`True` the XML declaration is omitted. ''' return self._omit_xml_declaration @omit_xml_declaration.setter def omit_xml_declaration(self, value): self._omit_xml_declaration = bool(value) @property def encoding(self): '''\ The encoding of the document. On setting if the value is :const:`None` it is set to ``UTF-8``, otherwise it is converted to an Unicode string. ''' return self._encoding @encoding.setter def encoding(self, value): if value is None: value = u'UTF-8' else: value = _unicode(value) self._encoding = value def __bytes__(self): '''\ Creates a byte string containing the XML representation of the node with the encoding :meth:`encoding`. ''' return self.create_str(encoding=self._encoding) if _python2: __str__ = __bytes__ del __bytes__ def __hash__(self): return object.__hash__(self) @_helpers.inherit_docstring(ContainerNode) def create_sax_events(self, content_handler=None, out=None, out_encoding='UTF-8', indent_incr=None): return XMLNode.create_sax_events(self, content_handler, out, self._encoding, indent_incr) def _create_str(self, out): return out.document(self._doctype.name, self._doctype.publicid, self._doctype.systemid, self._children_strings(out), self._omit_xml_declaration, self._encoding) def _create_sax_events(self, content_handler, indent): content_handler.startDocument() try: notationDecl = content_handler.notationDecl except AttributeError: pass else: notationDecl(self._doctype.name, self._doctype.publicid, self._doctype.systemid) for child in self: child._create_sax_events(content_handler, indent) content_handler.endDocument() def __repr__(self): return 'ecoxipy.pyxom.Document[{}, {}, {}]'.format( repr(self._doctype), repr(self._omit_xml_declaration), _string_repr(self._encoding)) def __eq__(self, other): if not(isinstance(other, Document) and self._doctype == other._doctype and self._omit_xml_declaration == other._omit_xml_declaration and self._encoding == other._encoding and len(self) == len(other)): return False for i in range(len(self)): if self[i] != other[i]: return False return True def __ne__(self, other): if (not(isinstance(other, Document)) or self._doctype != other._doctype or self._omit_xml_declaration != other._omit_xml_declaration or self._encoding != other._encoding or len(self) != len(other)): return True for i in range(len(self)): if self[i] != other[i]: return True return False @_helpers.inherit_docstring(ContainerNode) def duplicate(self): return Document(self._doctype.name, self._doctype.publicid, self._doctype.systemid, [child.duplicate() for child in self], self._omit_xml_declaration, self._encoding) element_by_id = IndexDescriptor(ElementByUniqueAttributeValueIndexer()) '''\ A :class:`ecoxipy.pyxom.indexing.IndexDescriptor` instance using a :class:`ecoxipy.pyxom.indexing.ElementByUniqueAttributeValueIndexer` for indexing. Use it like a mapping to retrieve the element having an attribute ``id`` with the value being equal to the requested key, possibly throwing a :class:`KeyError` if such an element does not exist. **Important:** If the document's childs are relevantly modified (i.e. an ``id`` attribute was created, modified or deleted), :meth:`delete_indexes` should be called or this attribute should be deleted on the instance, which deletes the index. ''' elements_by_name = IndexDescriptor(ElementsByNameIndexer()) '''\ A :class:`ecoxipy.pyxom.indexing.IndexDescriptor` instance using a :class:`ecoxipy.pyxom.indexing.ElementsByNameIndexer` for indexing. Use it like a mapping to retrieve an iterator over elements having a name equal to the requested key, possibly throwing a :class:`KeyError` if such an element does not exist. **Important:** If the document's childs are relevantly modified (i.e. new elements were added or deleted, elements' names were modified), :meth:`delete_indexes` should be called or this attribute should be deleted on the instance, which deletes the index. ''' nodes_by_namespace = IndexDescriptor(NamespaceIndexer()) '''\ A :class:`ecoxipy.pyxom.indexing.IndexDescriptor` instance using a :class:`ecoxipy.pyxom.indexing.NamespaceIndexer` for indexing. **Important:** If the document's childs are relevantly modified (i.e. new elements/attributes were added or deleted, elements'/attributes' names were modified), :meth:`delete_indexes` should be called or this attribute should be deleted on the instance, which deletes the index. ''' def delete_indexes(self): '''\ A shortcut to delete the indexes of :attr:`element_by_id` and :attr:`elements_by_name`. ''' del self.element_by_id del self.elements_by_name del self.nodes_by_namespace del (IndexDescriptor, ElementByUniqueAttributeValueIndexer, ElementsByNameIndexer, NamespaceIndexer) ```
[ { "content": "Repeat the following code:\n```python\n#!/usr/bin/env python\n\nfrom cogflect.GeneratorBase import GeneratorBase\nfrom cogflect.common import generate_cppclass_common\nfrom cogflect.util import sanitizeTypename, indent\nimport cog\n\n_body = \"\"\"\n typedef %(name)s::type enum_type;\n\n // ...
[ { "content": "Repeat the following code:\n<|memory_start|>```python\n#!/usr/bin/env python\n\nfrom cogflect.GeneratorBase import GeneratorBase\nfrom cogflect.common import generate_cppclass_common\nfrom cogflect.util import sanitizeTypename, indent\nimport cog\n\n_body = \"\"\"\n typedef %(name)s::type enum_...
```python #!/usr/bin/env python from cogflect.GeneratorBase import GeneratorBase from cogflect.common import generate_cppclass_common from cogflect.util import sanitizeTypename, indent import cog _body = """ typedef %(name)s::type enum_type; // TODO: iterate public/protected/private independently? // TODO: iterate over members with a tag? <-- public/protected/private tags // TODO: tag to indicate reflection is available template<typename T> typename T::type& get_member(); template<typename T> typename T::type const& get_member() const; template<unsigned index> typename %(name)s::info_index<index>::type& get_indexed_member() { return get_member< info_index<index> >(); } template<unsigned index> typename %(name)s::info_index<index>::type const& get_indexed_member() const { return get_member< info_index<index> >(); } template<typename Processor> inline void get_runtime_member(Processor& p, type value) { cogflect::pass_member_action<Processor, data> tmp(p, *this); value.switcher(tmp); } template<typename Processor> inline void get_runtime_member(Processor const& p, type value) { cogflect::pass_member_action<const Processor, data> tmp(p, *this); value.switcher(tmp); } template<typename Processor> inline void get_runtime_member(Processor& p, type value) const { cogflect::pass_member_action<Processor, const data> tmp(p, *this); value.switcher(tmp); } template<typename Processor> inline void get_runtime_member(Processor const& p, type value) const { cogflect::pass_member_action<const Processor, const data> tmp(p, *this); value.switcher(tmp); } template<typename Processor> inline void get_runtime_indexed_member(Processor& p, unsigned index) { cogflect::pass_member_action<Processor, data> tmp(p, *this); type::index_switcher(index, tmp); } template<typename Processor> inline void get_runtime_indexed_member(Processor& p, unsigned index) const { cogflect::pass_member_action<Processor, const data> tmp(p, *this); type::index_switcher(index, tmp); } template<typename Processor> inline void get_runtime_indexed_member(Processor const& p, unsigned index) { cogflect::pass_member_action<const Processor, data> tmp(p, *this); type::index_switcher(index, tmp); } template<typename Processor> inline void get_runtime_indexed_member(Processor const& p, unsigned index) const { cogflect::pass_member_action<const Processor, const data> tmp(p, *this); type::index_switcher(index, tmp); } template<class VisitorT> inline void for_all_members(VisitorT& visitor) { %(forAllMembersBody)s } template<class VisitorT> inline void for_all_members(VisitorT& visitor) const { %(forAllMembersBody)s } template<class VisitorT> inline void for_all_members(VisitorT const& visitor) { %(forAllMembersBody)s } template<class VisitorT> inline void for_all_members(VisitorT const& visitor) const { %(forAllMembersBody)s } template<class TargetType> inline void shape_assign(TargetType const& other) { cogflect::shape_assign<data, TargetType> visitor; for_all_members(visitor); } """ class CppClass(GeneratorBase): def __init__(self, name, fields, config={}): GeneratorBase.__init__(self, name, fields, config) def __gen_for_all_members(self): calls = [] call_template = ("visitor.\n" " template process_member<%s_INFO>(%s_);") for f in self.fields: calls.append(indent(call_template % (f.name, f.name.lower()), 8)) return "\n".join(calls) def generate(self): generate_cppclass_common() cog.out("namespace %s {\n" "\n" % self.name) cog.out("class data\n" "{\n" "public:") cog.out(_body % { "name" : self.name, "forAllMembersBody" : self.__gen_for_all_members() }) cog.out("private:\n") for f in self.fields: if f.type: cog.out(" %s %s_;\n" % (sanitizeTypename(f.type), f.name.lower())) cog.out("}; // class data\n\n") for f in self.fields: if f.type: cog.out("template<>\n" "inline %(name)s_INFO::type& data::get_member<%(name)s_INFO>()\n" "{\n" " return %(lower_name)s_;\n" "}\n\n" % { "name" : f.name, "lower_name" : f.name.lower() }) for f in self.fields: if f.type: cog.out("template<>\n" "inline %(name)s_INFO::type const& data::get_member<%(name)s_INFO>() const\n" "{\n" " return %(lower_name)s_;\n" "}\n\n" % { "name" : f.name, "lower_name" : f.name.lower() }) cog.out("} // namespace %s\n" % self.name) ```
[ { "content": "```python\nimport json\n\nfrom flask import Flask\n\nfrom fittrackee.users.models import User\nfrom fittrackee.workouts.models import Sport, Workout\n\nfrom ..api_test_case import ApiTestCaseMixin\n\n\nclass TestGetStatsByTime(ApiTestCaseMixin):\n def test_it_gets_no_stats_when_user_has_no_work...
[ { "content": "<|memory_start|>```python\nimport json\n\nfrom flask import Flask\n\nfrom fittrackee.users.models import User\nfrom fittrackee.workouts.models import Sport, Workout\n\nfrom ..api_test_case import ApiTestCaseMixin\n\n\nclass TestGetStatsByTime(ApiTestCaseMixin):\n def test_it_gets_no_stats_when_...
```python import json from flask import Flask from fittrackee.users.models import User from fittrackee.workouts.models import Sport, Workout from ..api_test_case import ApiTestCaseMixin class TestGetStatsByTime(ApiTestCaseMixin): def test_it_gets_no_stats_when_user_has_no_workouts( self, app: Flask, user_1: User ) -> None: client, auth_token = self.get_test_client_and_auth_token(app) response = client.get( f'/api/stats/{user_1.username}/by_time', headers=dict(Authorization=f'Bearer {auth_token}'), ) data = json.loads(response.data.decode()) assert response.status_code == 200 assert 'success' in data['status'] assert data['data']['statistics'] == {} def test_it_returns_error_when_user_does_not_exists( self, app: Flask, user_1: User ) -> None: client, auth_token = self.get_test_client_and_auth_token(app) response = client.get( '/api/stats/1000/by_time', headers=dict(Authorization=f'Bearer {auth_token}'), ) data = json.loads(response.data.decode()) assert response.status_code == 404 assert 'not found' in data['status'] assert 'User does not exist.' in data['message'] def test_it_returns_error_if_date_format_is_invalid( self, app: Flask, user_1: User, sport_1_cycling: Sport, sport_2_running: Sport, seven_workouts_user_1: Workout, workout_running_user_1: Workout, ) -> None: client, auth_token = self.get_test_client_and_auth_token(app) response = client.get( ( f'/api/stats/{user_1.username}/by_time' f'?from="2018-04-01&to=2018-04-30' ), headers=dict(Authorization=f'Bearer {auth_token}'), ) data = json.loads(response.data.decode()) assert response.status_code == 500 assert 'error' in data['status'] assert ( 'Error. Please try again or contact the administrator.' in data['message'] ) def test_it_returns_error_if_period_is_invalid( self, app: Flask, user_1: User, sport_1_cycling: Sport, sport_2_running: Sport, seven_workouts_user_1: Workout, workout_running_user_1: Workout, ) -> None: client, auth_token = self.get_test_client_and_auth_token(app) response = client.get( f'/api/stats/{user_1.username}/by_time?from=2018-04-01&to=2018-04-30&time=day', # noqa headers=dict(Authorization=f'Bearer {auth_token}'), ) data = json.loads(response.data.decode()) assert response.status_code == 400 assert 'fail' in data['status'] assert 'Invalid time period.' in data['message'] def test_it_gets_stats_by_time_all_workouts( self, app: Flask, user_1: User, sport_1_cycling: Sport, sport_2_running: Sport, seven_workouts_user_1: Workout, workout_running_user_1: Workout, ) -> None: client, auth_token = self.get_test_client_and_auth_token(app) response = client.get( f'/api/stats/{user_1.username}/by_time', headers=dict(Authorization=f'Bearer {auth_token}'), ) data = json.loads(response.data.decode()) assert response.status_code == 200 assert 'success' in data['status'] assert data['data']['statistics'] == { '2017': { '1': { 'nb_workouts': 2, 'total_distance': 15.0, 'total_duration': 4480, } }, '2018': { '1': { 'nb_workouts': 5, 'total_distance': 39.0, 'total_duration': 11624, }, '2': { 'nb_workouts': 1, 'total_distance': 12.0, 'total_duration': 6000, }, }, } def test_it_gets_stats_for_april_2018( self, app: Flask, user_1: User, sport_1_cycling: Sport, sport_2_running: Sport, seven_workouts_user_1: Workout, workout_running_user_1: Workout, ) -> None: client, auth_token = self.get_test_client_and_auth_token(app) response = client.get( f'/api/stats/{user_1.username}/by_time?from=2018-04-01&to=2018-04-30', # noqa headers=dict(Authorization=f'Bearer {auth_token}'), ) data = json.loads(response.data.decode()) assert response.status_code == 200 assert 'success' in data['status'] assert data['data']['statistics'] == { '2018': { '1': { 'nb_workouts': 1, 'total_distance': 8.0, 'total_duration': 6000, }, '2': { 'nb_workouts': 1, 'total_distance': 12.0, 'total_duration': 6000, }, } } def test_it_gets_stats_for_april_2018_with_paris_timezone( self, app: Flask, user_1_paris: User, sport_1_cycling: Sport, sport_2_running: Sport, seven_workouts_user_1: Workout, workout_running_user_1: Workout, ) -> None: client, auth_token = self.get_test_client_and_auth_token(app) response = client.get( f'/api/stats/{user_1_paris.username}/by_time?' f'from=2018-04-01&to=2018-04-30', headers=dict(Authorization=f'Bearer {auth_token}'), ) data = json.loads(response.data.decode()) assert response.status_code == 200 assert 'success' in data['status'] assert data['data']['statistics'] == { '2018': { '1': { 'nb_workouts': 1, 'total_distance': 8.0, 'total_duration': 6000, }, '2': { 'nb_workouts': 1, 'total_distance': 12.0, 'total_duration': 6000, }, } } def test_it_gets_stats_by_year( self, app: Flask, user_1: User, sport_1_cycling: Sport, sport_2_running: Sport, seven_workouts_user_1: Workout, workout_running_user_1: Workout, ) -> None: client, auth_token = self.get_test_client_and_auth_token(app) response = client.get( f'/api/stats/{user_1.username}/by_time?time=year', headers=dict(Authorization=f'Bearer {auth_token}'), ) data = json.loads(response.data.decode()) assert response.status_code == 200 assert 'success' in data['status'] assert data['data']['statistics'] == { '2017': { '1': { 'nb_workouts': 2, 'total_distance': 15.0, 'total_duration': 4480, } }, '2018': { '1': { 'nb_workouts': 5, 'total_distance': 39.0, 'total_duration': 11624, }, '2': { 'nb_workouts': 1, 'total_distance': 12.0, 'total_duration': 6000, }, }, } def test_it_gets_stats_by_year_for_april_2018( self, app: Flask, user_1: User, sport_1_cycling: Sport, sport_2_running: Sport, seven_workouts_user_1: Workout, workout_running_user_1: Workout, ) -> None: client, auth_token = self.get_test_client_and_auth_token(app) response = client.get( f'/api/stats/{user_1.username}/by_time?from=2018-04-01&to=2018-04-30&time=year', # noqa headers=dict(Authorization=f'Bearer {auth_token}'), ) data = json.loads(response.data.decode()) assert response.status_code == 200 assert 'success' in data['status'] assert data['data']['statistics'] == { '2018': { '1': { 'nb_workouts': 1, 'total_distance': 8.0, 'total_duration': 6000, }, '2': { 'nb_workouts': 1, 'total_distance': 12.0, 'total_duration': 6000, }, } } def test_it_gets_stats_by_year_for_april_2018_with_paris_timezone( self, app: Flask, user_1_paris: User, sport_1_cycling: Sport, sport_2_running: Sport, seven_workouts_user_1: Workout, workout_running_user_1: Workout, ) -> None: client, auth_token = self.get_test_client_and_auth_token(app) response = client.get( f'/api/stats/{user_1_paris.username}/by_time?from=2018-04-01&to=2018-04-30&time=year', # noqa headers=dict(Authorization=f'Bearer {auth_token}'), ) data = json.loads(response.data.decode()) assert response.status_code == 200 assert 'success' in data['status'] assert data['data']['statistics'] == { '2018': { '1': { 'nb_workouts': 1, 'total_distance': 8.0, 'total_duration': 6000, }, '2': { 'nb_workouts': 1, 'total_distance': 12.0, 'total_duration': 6000, }, } } def test_it_gets_stats_by_month( self, app: Flask, user_1: User, sport_1_cycling: Sport, sport_2_running: Sport, seven_workouts_user_1: Workout, workout_running_user_1: Workout, ) -> None: client, auth_token = self.get_test_client_and_auth_token(app) response = client.get( f'/api/stats/{user_1.username}/by_time?time=month', headers=dict(Authorization=f'Bearer {auth_token}'), ) data = json.loads(response.data.decode()) assert response.status_code == 200 assert 'success' in data['status'] assert data['data']['statistics'] == { '2017-03': { '1': { 'nb_workouts': 1, 'total_distance': 5.0, 'total_duration': 1024, } }, '2017-06': { '1': { 'nb_workouts': 1, 'total_distance': 10.0, 'total_duration': 3456, } }, '2018-01': { '1': { 'nb_workouts': 1, 'total_distance': 10.0, 'total_duration': 1024, } }, '2018-02': { '1': { 'nb_workouts': 2, 'total_distance': 11.0, 'total_duration': 1600, } }, '2018-04': { '1': { 'nb_workouts': 1, 'total_distance': 8.0, 'total_duration': 6000, }, '2': { 'nb_workouts': 1, 'total_distance': 12.0, 'total_duration': 6000, }, }, '2018-05': { '1': { 'nb_workouts': 1, 'total_distance': 10.0, 'total_duration': 3000, } }, } def test_it_gets_stats_by_month_with_new_york_timezone( self, app: Flask, user_1_full: User, sport_1_cycling: Sport, sport_2_running: Sport, seven_workouts_user_1: Workout, workout_running_user_1: Workout, ) -> None: client, auth_token = self.get_test_client_and_auth_token(app) response = client.get( f'/api/stats/{user_1_full.username}/by_time?time=month', headers=dict(Authorization=f'Bearer {auth_token}'), ) data = json.loads(response.data.decode()) assert response.status_code == 200 assert 'success' in data['status'] assert data['data']['statistics'] == { '2017-03': { '1': { 'nb_workouts': 1, 'total_distance': 5.0, 'total_duration': 1024, } }, '2017-06': { '1': { 'nb_workouts': 1, 'total_distance': 10.0, 'total_duration': 3456, } }, '2018-01': { '1': { 'nb_workouts': 1, 'total_distance': 10.0, 'total_duration': 1024, } }, '2018-02': { '1': { 'nb_workouts': 2, 'total_distance': 11.0, 'total_duration': 1600, } }, '2018-04': { '1': { 'nb_workouts': 1, 'total_distance': 8.0, 'total_duration': 6000, }, '2': { 'nb_workouts': 1, 'total_distance': 12.0, 'total_duration': 6000, }, }, '2018-05': { '1': { 'nb_workouts': 1, 'total_distance': 10.0, 'total_duration': 3000, } }, } def test_it_gets_stats_by_month_for_april_2018( self, app: Flask, user_1: User, sport_1_cycling: Sport, sport_2_running: Sport, seven_workouts_user_1: Workout, workout_running_user_1: Workout, ) -> None: client, auth_token = self.get_test_client_and_auth_token(app) response = client.get( f'/api/stats/{user_1.username}/by_time?from=2018-04-01&to=2018-04-30&time=month', # noqa headers=dict(Authorization=f'Bearer {auth_token}'), ) data = json.loads(response.data.decode()) assert response.status_code == 200 assert 'success' in data['status'] assert data['data']['statistics'] == { '2018-04': { '1': { 'nb_workouts': 1, 'total_distance': 8.0, 'total_duration': 6000, }, '2': { 'nb_workouts': 1, 'total_distance': 12.0, 'total_duration': 6000, }, } } def test_it_gets_stats_by_week( self, app: Flask, user_1_full: User, sport_1_cycling: Sport, sport_2_running: Sport, seven_workouts_user_1: Workout, workout_running_user_1: Workout, ) -> None: client, auth_token = self.get_test_client_and_auth_token(app) response = client.get( f'/api/stats/{user_1_full.username}/by_time?time=week', headers=dict(Authorization=f'Bearer {auth_token}'), ) data = json.loads(response.data.decode()) assert response.status_code == 200 assert 'success' in data['status'] assert data['data']['statistics'] == { '2017-03-19': { '1': { 'nb_workouts': 1, 'total_distance': 5.0, 'total_duration': 1024, } }, '2017-05-28': { '1': { 'nb_workouts': 1, 'total_distance': 10.0, 'total_duration': 3456, } }, '2017-12-31': { '1': { 'nb_workouts': 1, 'total_distance': 10.0, 'total_duration': 1024, } }, '2018-02-18': { '1': { 'nb_workouts': 2, 'total_distance': 11.0, 'total_duration': 1600, } }, '2018-04-01': { '1': { 'nb_workouts': 1, 'total_distance': 8.0, 'total_duration': 6000, }, '2': { 'nb_workouts': 1, 'total_distance': 12.0, 'total_duration': 6000, }, }, '2018-05-06': { '1': { 'nb_workouts': 1, 'total_distance': 10.0, 'total_duration': 3000, } }, } def test_it_gets_stats_by_week_for_week_13( self, app: Flask, user_1: User, sport_1_cycling: Sport, sport_2_running: Sport, seven_workouts_user_1: Workout, workout_running_user_1: Workout, ) -> None: client, auth_token = self.get_test_client_and_auth_token(app) response = client.get( f'/api/stats/{user_1.username}/by_time?from=2018-04-01&to=2018-04-30&time=week', # noqa headers=dict(Authorization=f'Bearer {auth_token}'), ) data = json.loads(response.data.decode()) assert response.status_code == 200 assert 'success' in data['status'] assert data['data']['statistics'] == { '2018-04-01': { '1': { 'nb_workouts': 1, 'total_distance': 8.0, 'total_duration': 6000, }, '2': { 'nb_workouts': 1, 'total_distance': 12.0, 'total_duration': 6000, }, } } def test_if_get_stats_by_week_starting_with_monday( self, app: Flask, user_1: User, sport_1_cycling: Sport, sport_2_running: Sport, seven_workouts_user_1: Workout, workout_running_user_1: Workout, ) -> None: client, auth_token = self.get_test_client_and_auth_token(app) response = client.get( f'/api/stats/{user_1.username}/by_time?time=weekm', headers=dict(Authorization=f'Bearer {auth_token}'), ) data = json.loads(response.data.decode()) assert response.status_code == 200 assert 'success' in data['status'] assert data['data']['statistics'] == { '2017-03-20': { '1': { 'nb_workouts': 1, 'total_distance': 5.0, 'total_duration': 1024, } }, '2017-05-29': { '1': { 'nb_workouts': 1, 'total_distance': 10.0, 'total_duration': 3456, } }, '2018-01-01': { '1': { 'nb_workouts': 1, 'total_distance': 10.0, 'total_duration': 1024, } }, '2018-02-19': { '1': { 'nb_workouts': 2, 'total_distance': 11.0, 'total_duration': 1600, } }, '2018-03-26': { '1': { 'nb_workouts': 1, 'total_distance': 8.0, 'total_duration': 6000, }, '2': { 'nb_workouts': 1, 'total_distance': 12.0, 'total_duration': 6000, }, }, '2018-05-07': { '1': { 'nb_workouts': 1, 'total_distance': 10.0, 'total_duration': 3000, } }, } def test_it_gets_stats_by_week_starting_with_monday_for_week_13( self, app: Flask, user_1: User, sport_1_cycling: Sport, sport_2_running: Sport, seven_workouts_user_1: Workout, workout_running_user_1: Workout, ) -> None: client, auth_token = self.get_test_client_and_auth_token(app) response = client.get( f'/api/stats/{user_1.username}/by_time?from=2018-04-01&to=2018-04-30&time=weekm', # noqa headers=dict(Authorization=f'Bearer {auth_token}'), ) data = json.loads(response.data.decode()) assert response.status_code == 200 assert 'success' in data['status'] assert data['data']['statistics'] == { '2018-03-26': { '1': { 'nb_workouts': 1, 'total_distance': 8.0, 'total_duration': 6000, }, '2': { 'nb_workouts': 1, 'total_distance': 12.0, 'total_duration': 6000, }, } } class TestGetStatsBySport(ApiTestCaseMixin): def test_it_gets_stats_by_sport( self, app: Flask, user_1: User, sport_1_cycling: Sport, sport_2_running: Sport, seven_workouts_user_1: Workout, workout_running_user_1: Workout, ) -> None: client, auth_token = self.get_test_client_and_auth_token(app) response = client.get( f'/api/stats/{user_1.username}/by_sport', headers=dict(Authorization=f'Bearer {auth_token}'), ) data = json.loads(response.data.decode()) assert response.status_code == 200 assert 'success' in data['status'] assert data['data']['statistics'] == { '1': { 'nb_workouts': 7, 'total_distance': 54.0, 'total_duration': 16104, }, '2': { 'nb_workouts': 1, 'total_distance': 12.0, 'total_duration': 6000, }, } def test_it_get_stats_for_sport_1( self, app: Flask, user_1: User, sport_1_cycling: Sport, sport_2_running: Sport, seven_workouts_user_1: Workout, workout_running_user_1: Workout, ) -> None: client, auth_token = self.get_test_client_and_auth_token(app) response = client.get( f'/api/stats/{user_1.username}/by_sport?sport_id=1', headers=dict(Authorization=f'Bearer {auth_token}'), ) data = json.loads(response.data.decode()) assert response.status_code == 200 assert 'success' in data['status'] assert data['data']['statistics'] == { '1': { 'nb_workouts': 7, 'total_distance': 54.0, 'total_duration': 16104, } } def test_it_returns_errors_if_user_does_not_exist( self, app: Flask, user_1: User, sport_1_cycling: Sport, sport_2_running: Sport, seven_workouts_user_1: Workout, workout_running_user_1: Workout, ) -> None: client, auth_token = self.get_test_client_and_auth_token(app) response = client.get( '/api/stats/1000/by_sport?sport_id=1', headers=dict(Authorization=f'Bearer {auth_token}'), ) data = json.loads(response.data.decode()) assert response.status_code == 404 assert 'not found' in data['status'] assert 'User does not exist.' in data['message'] def test_it_returns_error_if_sport_does_not_exist( self, app: Flask, user_1: User, sport_1_cycling: Sport, sport_2_running: Sport, seven_workouts_user_1: Workout, workout_running_user_1: Workout, ) -> None: client, auth_token = self.get_test_client_and_auth_token(app) response = client.get( f'/api/stats/{user_1.username}/by_sport?sport_id=999', headers=dict(Authorization=f'Bearer {auth_token}'), ) data = json.loads(response.data.decode()) assert response.status_code == 404 assert 'not found' in data['status'] assert 'Sport does not exist.' in data['message'] def test_it_returns_error_if_sport_id_is_invalid( self, app: Flask, user_1: User, sport_1_cycling: Sport, sport_2_running: Sport, seven_workouts_user_1: Workout, workout_running_user_1: Workout, ) -> None: client, auth_token = self.get_test_client_and_auth_token(app) response = client.get( f'/api/stats/{user_1.username}/by_sport?sport_id="999', headers=dict(Authorization=f'Bearer {auth_token}'), ) data = json.loads(response.data.decode()) assert response.status_code == 500 assert 'error' in data['status'] assert ( 'Error. Please try again or contact the administrator.' in data['message'] ) class TestGetAllStats(ApiTestCaseMixin): def test_it_returns_all_stats_when_users_have_no_workouts( self, app: Flask, user_1_admin: User, user_2: User ) -> None: client, auth_token = self.get_test_client_and_auth_token( app, as_admin=True ) response = client.get( '/api/stats/all', headers=dict(Authorization=f'Bearer {auth_token}'), ) data = json.loads(response.data.decode()) assert response.status_code == 200 assert 'success' in data['status'] assert data['data']['workouts'] == 0 assert data['data']['sports'] == 0 assert data['data']['users'] == 2 assert 'uploads_dir_size' in data['data'] def test_it_gets_app_all_stats_with_workouts( self, app: Flask, user_1_admin: User, user_2: User, user_3: User, sport_1_cycling: Sport, sport_2_running: Sport, workout_cycling_user_1: Workout, workout_cycling_user_2: Workout, workout_running_user_1: Workout, ) -> None: client, auth_token = self.get_test_client_and_auth_token( app, as_admin=True ) response = client.get( '/api/stats/all', headers=dict(Authorization=f'Bearer {auth_token}'), ) data = json.loads(response.data.decode()) assert response.status_code == 200 assert 'success' in data['status'] assert data['data']['workouts'] == 3 assert data['data']['sports'] == 2 assert data['data']['users'] == 3 assert 'uploads_dir_size' in data['data'] def test_it_returns_error_if_user_has_no_admin_rights( self, app: Flask, user_1: User, user_2: User, user_3: User, sport_1_cycling: Sport, sport_2_running: Sport, workout_cycling_user_1: Workout, workout_cycling_user_2: Workout, workout_running_user_1: Workout, ) -> None: client, auth_token = self.get_test_client_and_auth_token(app) response = client.get( '/api/stats/all', headers=dict(Authorization=f'Bearer {auth_token}'), ) data = json.loads(response.data.decode()) assert response.status_code == 403 assert 'success' not in data['status'] assert 'error' in data['status'] assert 'You do not have permissions.' in data['message'] ```
[ { "content": "Repeat the following code:\n```python\nr\"\"\"\nTest ec.utils.\n\"\"\"\nimport unittest\n\nfrom ec.utils import get, static, custom, walk\n\nfrom support.helpers import RawInputHook as RIH, expect_exception\n\n# Tests\nclass TestUtils(unittest.TestCase):\n def setUp(self):\n pass\n\n def tear...
[ { "content": "Repeat the following code:\n<|memory_start|>```python\nr\"\"\"\nTest ec.utils.\n\"\"\"\nimport unittest\n\nfrom ec.utils import get, static, custom, walk\n\nfrom support.helpers import RawInputHook as RIH, expect_exception\n\n# Tests\nclass TestUtils(unittest.TestCase):\n def setUp(self):\n pa...
```python r""" Test ec.utils. """ import unittest from ec.utils import get, static, custom, walk from support.helpers import RawInputHook as RIH, expect_exception # Tests class TestUtils(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_get(self): Inputs = 'a', 1 RIH.values(*Inputs) # test the call assert(get('str') == Inputs[0]) assert(get('int', type=int) == Inputs[1]) def test_static(self): @static class cls: #pylint: disable=W0232 def method(val): return val assert(cls.method(1) == 1) def test_custom(self): _type = custom(lambda v: v%2 == 1, int, type_str='an odd number') assert(_type(1) == 1) assert(expect_exception(lambda: _type(2), ValueError)) assert(expect_exception(lambda: _type('a'), ValueError)) def test_walk(self): from targets import simple from ec import interface interface.setBase(simple) expected = set(['task1', 'group1', 'ex', 'hex']) got = set() for Member in walk(simple.__ec_member__): got.add(Member.Config['name']) assert(expected == got) if __name__ == '__main__': unittest.main() ```
[ { "content": "```python\nfrom helga.plugins import command\n\nfrom functions import bounty_lookup, crucible_lookup, daily_lookup\nfrom functions import heroic_lookup, nightfall_lookup, xur_lookup\nfrom scraper import VENDOR_NAMES\n\nguard_help = \"Returns a guardian's destinytracker.com page\"\n@command('guardi...
[ { "content": "<|memory_start|>```python\nfrom helga.plugins import command\n\nfrom functions import bounty_lookup, crucible_lookup, daily_lookup\nfrom functions import heroic_lookup, nightfall_lookup, xur_lookup\nfrom scraper import VENDOR_NAMES\n\nguard_help = \"Returns a guardian's destinytracker.com page\"\n...
```python from helga.plugins import command from functions import bounty_lookup, crucible_lookup, daily_lookup from functions import heroic_lookup, nightfall_lookup, xur_lookup from scraper import VENDOR_NAMES guard_help = "Returns a guardian's destinytracker.com page" @command('guardian', aliases=('g',), help=guard_help) def guardian(client, channel, nick, message, cmd, args): if len(args) != 2: return 'Command takes 2 arguments: !guardian system name' system, name = args[0], args[1] return gurdian_lookup(system, name) nf_help = 'Displays info on the current nightfall from destinytracker.com' @command('nightfall', aliases=('nf',), help=nf_help) def nightfall(client, channel, nick, message, cmd, args): return nightfall_lookup() hero_help = 'Displays info on the current heroic from destinytracker.com' @command('heroic', aliases=('hero',), help=hero_help) def heroic(client, channel, nick, message, cmd, args): return heroic_lookup() daily_help = 'Displays info on the current heroic daily from planetdestiny.com' @command('daily', aliases=(), help=daily_help) def daily(client, channel, nick, message, cmd, args): return daily_lookup() crucible_help = 'Displays info on the current daily crucible mode form planetdestiny.com' @command('crucible', aliases=(), help=crucible_help) def crucible(client, channel, nick, message, cmd, args): return crucible_lookup() @command('xur', aliases=(), help="Gives a URL for looking up Xur's inventory") def xur(client, channel, nick, message, cmd, args): return xur_lookup() valid_names = ', '.join(VENDOR_NAMES) bounty_help = "Looks up the bounties for a given vendor. Valid names are: %s" % valid_names @command('bounties', aliases=('b',), help=bounty_help) def bounties(client, channel, nick, message, cmd, args): vendor_name = args[0] if vendor_name.lower() not in VENDOR_NAMES: return "Invalid vendor. Valid names are: %s" % valid_names return bounty_lookup(vendor_name) ```
[ { "content": "Repeat the full code snippet:\n```python\n#!/usr/bin/python\n# -*- coding: utf-8 -*-\n# Block using iptables through Flask\n\nimport subprocess # Run iptables\nfrom IPy import IP # Valide IP\nimport re # Make sure to validate\nfrom flask import Flask # Run Flask\nfrom flask import request # For ur...
[ { "content": "Repeat the full code snippet:\n<|memory_start|>```python\n#!/usr/bin/python\n# -*- coding: utf-8 -*-\n# Block using iptables through Flask\n\nimport subprocess # Run iptables\nfrom IPy import IP # Valide IP\nimport re # Make sure to validate\nfrom flask import Flask # Run Flask\nfrom flask import ...
```python #!/usr/bin/python # -*- coding: utf-8 -*- # Block using iptables through Flask import subprocess # Run iptables from IPy import IP # Valide IP import re # Make sure to validate from flask import Flask # Run Flask from flask import request # For url arguments app = Flask(__name__) # wget "127.0.0.1:9000/block?ip=8.8.8.8" # wget -qO- "127.0.0.1:9000/block?ip=8.8.8.8&lock=xxxx" @app.route('/block',methods=["GET"]) def blocker_def(): block_ip = request.args.get('ip') # If used for localhost and not through proxy lock = request.args.get('lock') if lock == "xxxx": pass else: return "0" # If there is a-zA-Z chars, empty it, otherwise IP validate noalpha = re.search('[a-zA-Z]', block_ip) if noalpha == None: try: IP(block_ip) except: block_ip = "Invalid" print "Invalid input has been sent to us!!" if block_ip != "Invalid": if block_ip and len(block_ip) <= 15: block_ip = block_ip else: block_ip = "Invalid" print "Invalid input has been sent to us!!" else: block_ip = "Invalid" print "Invalid input has been sent to us!!" if block_ip != "Invalid": subprocess.call(['/sbin/iptables', '-I', 'INPUT', '-s', block_ip, '-j', 'DROP']) # Alternatively: iptables -I INPUT -s 8.8.8.8 -m time --utc --datestart 2017-08-23T00:00 --datestop 2099-08-25T00:00 -j DROP else: pass return "0" if __name__ == '__main__': app.run('127.0.0.1',9000) ```
[ { "content": "Repeat the full code snippet:\n```python\n#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2013 Tristan Fischer (sphere@dersphere.de)\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as pu...
[ { "content": "Repeat the full code snippet:\n<|memory_start|>```python\n#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2013 Tristan Fischer (sphere@dersphere.de)\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Publ...
```python #!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2013 Tristan Fischer (sphere@dersphere.de) # # 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/>. # from xbmcswift2 import Plugin, xbmc, xbmcgui from resources.lib.client import ( XBMCMailClient, InvalidCredentials, InvalidHost ) STRINGS = { 'email_mark_seen': 30000, 'email_mark_unseen': 30001, 'email_delete': 30002, 'delete': 30003, 'are_you_sure': 30004, 'select_provider': 30005, 'connection_error': 30006, 'wrong_credentials': 30007, 'want_set_now': 30008, 'wrong_host': 30009, 'page': 30010, 'refresh_inbox': 30011, } plugin = Plugin() @plugin.route('/') def show_mailboxes(): client = _login() if not client: return def _format_label(mailbox): label = mailbox['name'] if 'unseen' in mailbox and 'total' in mailbox: label = u'%s (%d/%d)' % ( label, int(mailbox['unseen']), int(mailbox['total']), ) return label items = [{ 'label': _format_label(mailbox), 'path': plugin.url_for( endpoint='show_mailbox', mailbox=mailbox['raw_name'], ) } for mailbox in client.get_mailboxes()] return plugin.finish(items) @plugin.route('/mailbox/<mailbox>/', options={'page': '1'}) @plugin.route('/mailbox/<mailbox>/<page>/', name='show_mailbox_page') def show_mailbox(mailbox, page): client = _login() if not client: return page = int(page) limit = 50 offset = (page - 1) * limit def context_menu(mailbox, email): items = [] if email['unseen']: items.append( (_('email_mark_seen'), _view(endpoint='email_mark_seen', mailbox=mailbox, email_id=email['id'])) ) else: items.append( (_('email_mark_unseen'), _view(endpoint='email_mark_unseen', mailbox=mailbox, email_id=email['id'])) ) items.append( (_('email_delete'), _view(endpoint='email_delete', mailbox=mailbox, email_id=email['id'])) ) items.append( (_('refresh_inbox'), _view(endpoint='refresh_inbox', mailbox=mailbox, email_id=email['id'])) ) return items def _format_label(email): label = '[B]%s[/B] - %s' % ( _format_from(email['from']), _format_subject(email['subject']), ) if email['unseen']: label = '[COLOR red]%s[/COLOR]' % label return label def _format_from(s): if ' <' in s: return s.split(' <')[0].strip('"') else: return s.split('@')[0] def _format_subject(s): return s.replace('\r\n', '') emails, has_next_page = client.get_emails(mailbox, limit, offset) has_prev_page = page > 1 items = [{ 'label': _format_label(email), 'replace_context_menu': True, 'info': {'count': i + 1}, 'context_menu': context_menu(mailbox, email), 'path': plugin.url_for( endpoint='email_show', mailbox=email['mailbox'], email_id=email['id'] ) } for i, email in enumerate(emails)] if has_next_page: items.append({ 'label': '>> %s %s >>' % (_('page'), (page + 1)), 'info': {'count': len(emails) + 2}, 'path': plugin.url_for( endpoint='show_mailbox_page', mailbox=mailbox, page=(page + 1), is_update='true', ) }) if has_prev_page: items.append({ 'label': '<< %s %s <<' % (_('page'), (page - 1)), 'info': {'count': 0}, 'path': plugin.url_for( endpoint='show_mailbox_page', mailbox=mailbox, page=(page - 1), is_update='true', ) }) finish_kwargs = { 'update_listing': 'is_update' in plugin.request.args, 'sort_methods': ('playlist_order', ) } return plugin.finish(items, **finish_kwargs) @plugin.route('/mailbox/<mailbox>/<email_id>/mark_seen') def email_mark_seen(mailbox, email_id): client = _login() if not client: return client.email_mark_seen(email_id, mailbox) _refresh_view() @plugin.route('/mailbox/<mailbox>/<email_id>/mark_unseen') def email_mark_unseen(mailbox, email_id): client = _login() if not client: return client.email_mark_unseen(email_id, mailbox) _refresh_view() @plugin.route('/mailbox/<mailbox>') def refresh_inbox(mailbox): return _refresh_view() @plugin.route('/mailbox/<mailbox>/<email_id>/delete') def email_delete(mailbox, email_id): client = _login() if not client: return confirmed = xbmcgui.Dialog().yesno( _('delete'), _('are_you_sure') ) if not confirmed: return client.email_delete(email_id, mailbox) _refresh_view() @plugin.route('/mailbox/<mailbox>/<email_id>/show') def email_show(mailbox, email_id): client = _login() if not client: return xbmc.executebuiltin('ActivateWindow(%d)' % 10147) window = xbmcgui.Window(10147) email = client.get_email(email_id, mailbox) header = '%s - %s' % (email['from'], email['subject']) text = '\r\n'.join(( '=====================================================', '[B]From:[/B] %s' % email['from'], '[B]To:[/B] %s' % email['to'], '[B]Date:[/B] %s' % email['date'], '[B]Subject:[/B] %s' % email['subject'], '=====================================================', email['body_text'], )) window.getControl(1).setLabel(header) window.getControl(5).setText(text) def ask_provider(): providers = [ {'name': 'Custom', 'imap_host': ''}, {'name': '1und1.de', 'imap_host': 'imap.1und1.de', 'use_ssl': 'true'}, {'name': 'Arcor.de', 'imap_host': 'imap.arcor.de', 'use_ssl': 'true'}, {'name': 'Freenet.de', 'imap_host': 'mx.freenet.de', 'use_ssl': 'false'}, {'name': 'Gmail.com', 'imap_host': 'imap.gmail.com', 'use_ssl': 'true'}, {'name': 'iCloud.com', 'imap_host': 'imap.mail.me.com', 'use_ssl': 'true'}, {'name': 'T-Online.de', 'imap_host': 'secureimap.t-online.de', 'use_ssl': 'true'}, {'name': 'Web.de', 'imap_host': 'imap.web.de', 'use_ssl': 'false'}, {'name': 'Yahoo.com', 'imap_host': 'imap.mail.yahoo.com', 'use_ssl': 'true'}, ] selected = xbmcgui.Dialog().select( _('select_provider'), [p['name'] for p in providers] ) if selected >= 0: return providers[selected] @plugin.route('/settings/set_provider') def set_default_list(): provider = ask_provider() if provider: plugin.set_setting('provider', provider['name']) for k, v in provider.iteritems(): if k == 'name': plugin.set_setting('provider', v) else: plugin.set_setting(k, v) else: plugin.set_setting('provider', 'Custom') def _run(*args, **kwargs): return 'XBMC.RunPlugin(%s)' % plugin.url_for(*args, **kwargs) def _view(*args, **kwargs): return 'XBMC.Container.Update(%s)' % plugin.url_for(*args, **kwargs) def _refresh_view(): xbmc.executebuiltin('Container.Refresh') def _login(): logged_in = False while not logged_in: try: client = XBMCMailClient( username=plugin.get_setting('username', unicode), password=plugin.get_setting('password', unicode), host=plugin.get_setting('imap_host', unicode), use_ssl=plugin.get_setting('use_ssl', bool), ) except InvalidCredentials: try_again = xbmcgui.Dialog().yesno( _('connection_error'), _('wrong_credentials'), _('want_set_now') ) if not try_again: return plugin.open_settings() except InvalidHost: try_again = xbmcgui.Dialog().yesno( _('connection_error'), _('wrong_host'), _('want_set_now') ) if not try_again: return plugin.open_settings() else: logged_in = True return client def _(string_id): if string_id in STRINGS: return plugin.get_string(STRINGS[string_id]) else: plugin.log.debug('String is missing: %s' % string_id) return string_id if __name__ == '__main__': plugin.run() ```
[ { "content": "Provide a verbatim copy of the code:\n```python\n# Задача 9. Вариант 22.\n# Создайте игру, в которой компьютер выбирает какое-либо слово, а игрок должен\n# его отгадать. Компьютер сообщает игроку, сколько букв в слове, и дает пять попыток\n# узнать, есть ли какая-либо буква в слове, причем програм...
[ { "content": "Provide a verbatim copy of the code:\n<|memory_start|>```python\n# Задача 9. Вариант 22.\n# Создайте игру, в которой компьютер выбирает какое-либо слово, а игрок должен\n# его отгадать. Компьютер сообщает игроку, сколько букв в слове, и дает пять попыток\n# узнать, есть ли какая-либо буква в слове...
```python # Задача 9. Вариант 22. # Создайте игру, в которой компьютер выбирает какое-либо слово, а игрок должен # его отгадать. Компьютер сообщает игроку, сколько букв в слове, и дает пять попыток # узнать, есть ли какая-либо буква в слове, причем программа может отвечать только # "Да" и "Нет". Вслед за тем игрок должен попробовать отгадать слово. # Щербаков Р.А. # 22.05.2016 import random words="Сессия","Питон","Автомат","РГСУ","Расписание" rand=random.randint(0,4) massiv=list(words[rand].lower()) print("Ты попал на поле чудес, только тут мы не говорим где находится буква которую \ угадаешь.\nТема: Учеба\nБукв: "+str(len(massiv))) popitka=5 inp="" text="Угадали" while popitka!=0: if input("У тебя "+str(popitka)+" попыток\nВведите букву: ") in massiv: print("Да") else: print("Нет") popitka-=1 while inp.lower()!=words[rand].lower(): inp=input("Введите слово: ") if(inp.lower()=="я слабак"): inp=words[rand] text="Слабак" elif(inp.lower()==words[rand].lower()): text="Угадали" else: print("Попытайтесь еще раз\nНаберите 'Я слабак' для выхода") input("\nВы "+text) ```
[ { "content": "Return the code exactly, with no changes:\n```python\n# the implementation here is a bit crappy.\nimport time\nfrom Directories import resolveFilename, SCOPE_CONFIG\nfrom boxbranding import getBoxType\n\nboxtype = getBoxType()\n\nPERCENTAGE_START = 50\nPERCENTAGE_END = 100\n\nprofile_start = time....
[ { "content": "Return the code exactly, with no changes:\n<|memory_start|>```python\n# the implementation here is a bit crappy.\nimport time\nfrom Directories import resolveFilename, SCOPE_CONFIG\nfrom boxbranding import getBoxType\n\nboxtype = getBoxType()\n\nPERCENTAGE_START = 50\nPERCENTAGE_END = 100\n\nprofi...
```python # the implementation here is a bit crappy. import time from Directories import resolveFilename, SCOPE_CONFIG from boxbranding import getBoxType boxtype = getBoxType() PERCENTAGE_START = 50 PERCENTAGE_END = 100 profile_start = time.time() profile_data = {} total_time = 1 profile_file = None try: f = open(resolveFilename(SCOPE_CONFIG, "profile"), "r") profile_old = f.readlines() f.close() t = None for line in profile_old: (t, id) = line[:-1].split('\t') t = float(t) total_time = t profile_data[id] = t except: print "no profile data available" try: profile_file = open(resolveFilename(SCOPE_CONFIG, "profile"), "w") except IOError: print "WARNING: couldn't open profile file!" def profile(id): now = time.time() - profile_start if profile_file: profile_file.write("%7.3f\t%s\n" % (now, id)) if id in profile_data: t = profile_data[id] if total_time: perc = t * (PERCENTAGE_END - PERCENTAGE_START) / total_time + PERCENTAGE_START else: perc = PERCENTAGE_START try: if boxtype == "odinm7" or boxtype == "odinm6" or boxtype == "xp1000s": f = open("/dev/dbox/oled0", "w") f.write("%d" % perc) elif boxtype == "gb800se" or boxtype == "gb800solo": f = open("/dev/dbox/oled0", "w") f.write("%d \n" % perc) elif boxtype == "gb800seplus": f = open("/dev/mcu", "w") f.write("%d \n" % perc) elif boxtype == "ebox5000": f = open("/proc/progress", "w") f.write("%d" % perc) else: f = open("/proc/progress", "w") f.write("%d \n" % perc) f.close() except IOError: pass def profile_final(): global profile_file if profile_file is not None: profile_file.close() profile_file = None ```
[ { "content": "Repeat the code precisely as written (spacing intact):\n```python\nimport os\nimport numpy\nimport scipy_data_fitting\n\nclass Fig4(scipy_data_fitting.Data):\n \"\"\"\n Use this to load the data from Figure 4 in PhysRevLett.105.167202.\n\n Should not be used directly, but only subclassed....
[ { "content": "Repeat the code precisely as written (spacing intact):\n<|memory_start|>```python\nimport os\nimport numpy\nimport scipy_data_fitting\n\nclass Fig4(scipy_data_fitting.Data):\n \"\"\"\n Use this to load the data from Figure 4 in PhysRevLett.105.167202.\n\n Should not be used directly, but ...
```python import os import numpy import scipy_data_fitting class Fig4(scipy_data_fitting.Data): """ Use this to load the data from Figure 4 in PhysRevLett.105.167202. Should not be used directly, but only subclassed. """ def __init__(self, subfig): super().__init__() self.subfig = subfig self.name = 'fig_4' + self.subfig self.genfromtxt_args['delimiter'] = "\t" self.genfromtxt_args['skip_header'] = 1 self.path = os.path.join('data', 'PhysRevLett.105.167202', 'figure_4' + subfig + '.tsv') if subfig == 'd': self.scale = (1, 'milli') class Fig4Parallel(Fig4): """ The parallel field data from Figure 4 in PhysRevLett.105.167202. """ def __init__(self, subfig): super().__init__(subfig) self.name = self.name + '_parallel' self.genfromtxt_args['usecols'] = (0, 1) if subfig == 'c': self.path = self.path.replace('.tsv', '.1.tsv') class Fig4Antiparallel(Fig4): """ The antiparallel field data from Figure 4 in PhysRevLett.105.167202. """ def __init__(self, subfig): super().__init__(subfig) self.name = self.name + '_antiparallel' if subfig == 'c': self.path = self.path.replace('.tsv', '.2.tsv') else: self.genfromtxt_args['usecols'] = (0, 2) class Fig4Difference(scipy_data_fitting.Data): """ The difference of the parallel and antiparallel field data from Figure 4 in PhysRevLett.105.167202. """ def __init__(self, subfig): super().__init__() self.subfig = subfig self.name = 'fig_4' + self.subfig + '_difference' parallel = Fig4Parallel(self.subfig) antiparallel = Fig4Antiparallel(self.subfig) self.array = numpy.array([ parallel.array[0], abs(parallel.array[1] - antiparallel.array[1]) ]) class Fig4Normalized(scipy_data_fitting.Data): """ The normalized field data from Figure 4 in PhysRevLett.105.167202. Should not be used directly, but only subclassed. """ def __init__(self, subfig, data_class): super().__init__() self.subfig = subfig self.name = 'fig_4' + self.subfig + '_normalized' self.unnormalized = data_class(self.subfig).array self.array = numpy.array([ self.unnormalized[0], self.unnormalized[1] / max(abs(self.unnormalized[1])) ]) class Fig4NormalizedParallel(Fig4Normalized): """ The normalized parallel field data from Figure 4 in PhysRevLett.105.167202. """ def __init__(self, subfig): super().__init__(subfig, Fig4Parallel) self.name = self.name + '_parallel' class Fig4NormalizedAntiparallel(Fig4Normalized): """ The normalized antiparallel field data from Figure 4 in PhysRevLett.105.167202. """ def __init__(self, subfig): super().__init__(subfig, Fig4Antiparallel) self.name = self.name + '_antiparallel' class Fig4NormalizedDifference(Fig4Normalized): """ The difference of the normalized parallel and antiparallel field data from Figure 4 in PhysRevLett.105.167202. """ def __init__(self, subfig): super().__init__(subfig, Fig4Difference) self.name = self.name + '_difference' ```
[ { "content": "Provide a verbatim copy of the code:\n```python\n#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport itertools\nimport os\nimport os.path\n\nimport sys\nimport argparse\nimport logging\n\n\ndef cartesian_product(dicts):\n return (dict(zip(dicts, x)) for x in itertools.product(*dicts.value...
[ { "content": "Provide a verbatim copy of the code:\n<|memory_start|>```python\n#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport itertools\nimport os\nimport os.path\n\nimport sys\nimport argparse\nimport logging\n\n\ndef cartesian_product(dicts):\n return (dict(zip(dicts, x)) for x in itertools.prod...
```python #!/usr/bin/env python3 # -*- coding: utf-8 -*- import itertools import os import os.path import sys import argparse import logging def cartesian_product(dicts): return (dict(zip(dicts, x)) for x in itertools.product(*dicts.values())) def summary(configuration): kvs = sorted([(k, v) for k, v in configuration.items()], key=lambda e: e[0]) return '_'.join([('%s=%s' % (k, v)) for (k, v) in kvs]) def to_cmd(c, _path=None): if _path is None: _path = '/home/pminervi/workspace/inferbeddings/' command = 'python3 {}/bin/kbp-cli.py' \ ' --train {}/data/guo-emnlp16/fb122/fb122_triples.train' \ ' --valid {}/data/guo-emnlp16/fb122/fb122_triples.valid' \ ' --test {}/data/guo-emnlp16/fb122/fb122_triples.test' \ ' --clauses {}/data/guo-emnlp16/fb122/clauses/fb122-clauses.pl' \ ' --nb-epochs {}' \ ' --lr 0.1' \ ' --nb-batches 10' \ ' --model {}' \ ' --similarity {}' \ ' --margin {}' \ ' --embedding-size {}' \ ' --loss {}' \ ' --adv-lr {} --adv-init-ground --adversary-epochs {}' \ ' --discriminator-epochs {} --adv-weight {} --adv-batch-size {} --adv-pooling {}' \ ''.format(_path, _path, _path, _path, _path, c['epochs'], c['model'], c['similarity'], c['margin'], c['embedding_size'], c['loss'], c['adv_lr'], c['adv_epochs'], c['disc_epochs'], c['adv_weight'], c['adv_batch_size'], c['adv_pooling']) return command def to_logfile(c, path): outfile = "%s/ucl_guo-fb122_adv_KALE_v1.%s.log" % (path, summary(c)) return outfile def main(argv): def formatter(prog): return argparse.HelpFormatter(prog, max_help_position=100, width=200) argparser = argparse.ArgumentParser('Generating experiments for the UCL cluster', formatter_class=formatter) argparser.add_argument('--debug', '-D', action='store_true', help='Debug flag') argparser.add_argument('--path', '-p', action='store', type=str, default=None, help='Path') args = argparser.parse_args(argv) hyperparameters_space_distmult_complex = dict( epochs=[100], model=['DistMult', 'ComplEx'], similarity=['dot'], margin=[1, 2, 5, 10], embedding_size=[100, 150, 200], # embedding_size=[20, 50, 100, 150, 200], loss=['hinge'], adv_lr=[.1], adv_epochs=[0, 10], disc_epochs=[10], adv_weight=[0, 1, 100], # adv_weight=[0, 1, 100, 10000, 1000000], adv_batch_size=[1, 10, 100], adv_pooling=['sum', 'mean', 'max'] # adv_pooling=['sum', 'mean', 'max', 'logsumexp'] ) configurations_distmult_complex = cartesian_product(hyperparameters_space_distmult_complex) path = '/home/pminervi/workspace/inferbeddings/logs/ucl_guo-fb122_adv_KALE_v1/' # Check that we are on the UCLCS cluster first if os.path.exists('/home/pminervi/'): # If the folder that will contain logs does not exist, create it if not os.path.exists(path): os.makedirs(path) configurations = list(configurations_distmult_complex) command_lines = set() for cfg in configurations: logfile = to_logfile(cfg, path) completed = False if os.path.isfile(logfile): with open(logfile, 'r', encoding='utf-8', errors='ignore') as f: content = f.read() completed = '### MICRO (test filtered)' in content if not completed: command_line = '{} >> {} 2>&1'.format(to_cmd(cfg, _path=args.path), logfile) command_lines |= {command_line} # Sort command lines and remove duplicates sorted_command_lines = sorted(command_lines) nb_jobs = len(sorted_command_lines) header = """#!/bin/bash #$ -cwd #$ -S /bin/bash #$ -o /dev/null #$ -e /dev/null #$ -t 1-{} #$ -l h_vmem=6G,tmem=6G #$ -l h_rt=4:00:00 """.format(nb_jobs) print(header) for job_id, command_line in enumerate(sorted_command_lines, 1): print('test $SGE_TASK_ID -eq {} && {}'.format(job_id, command_line)) if __name__ == '__main__': logging.basicConfig(level=logging.INFO) main(sys.argv[1:]) ```